CombinedText stringlengths 4 3.42M |
|---|
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE api_tests
#define BOOST_TEST_MAIN
#define BOOST_TEST_LOG_LEVEL all
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "../Source/UCI.hpp"
#include "../Source/Search.hpp"
#include "../Source/Board.hpp"
#include "../Source/Evaluation.hpp"
#include "../Source/MoveList.hpp"
using namespace std;
BOOST_AUTO_TEST_CASE(UCI_sentPosition)
{
cout << "Testing sentPosition function" << endl;
BOOST_CHECK(UCI::sentPosition("position startpos moves e3e2") == false);
BOOST_CHECK(UCI::sentPosition("position startpos moves e2e4") == true);
BOOST_CHECK(UCI::sentPosition("position startpos") == false);
BOOST_CHECK(UCI::sentPosition("position fen not a fen") == false);
}
BOOST_AUTO_TEST_CASE(evaluation_evaluateBoard)
{
cout << "Testing evaluateBoard function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //evaluation should be 0 for initial board
testBoard = Board("7k/8/8/8/8/8/8/7K w - - 0 1");
BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //no piece difference, symmetrical position
}
BOOST_AUTO_TEST_CASE(evaluation_CheckForDoublePawns)
{
Evaluation::initpopCountOfByte(); //initialising look-up table
cout << "Testing CheckForDoublePawns function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 0); //No double pawns for white
BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 0); //No double pawns for black
testBoard = Board("8/8/4kP2/8/5P2/PP1P2P1/PPP1P2P/3K4 w - - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 3); //3 sets of white double pawns
testBoard = Board("8/8/4kP2/8/5P2/PPPPP1PP/PPP1P2P/3K4 w - - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 6); //6 sets of white double pawns
testBoard = Board("4k3/pppppppp/pppppppp/2b2b2/P5P1/P1qK1PP1/P4PP1/6q1 w - - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 8); //8 sets of black double pawns
}
BOOST_AUTO_TEST_CASE(evaluation_rooksOnOpenFile)
{
cout << "Testing rooksOnOpenFile function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
int temp = Evaluation::CheckForDoublePawns(6, testBoard); //check for double pawns initialises array of open files
temp = Evaluation::CheckForDoublePawns(7, testBoard);
BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 0); //no rooks on open file for white
BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 0); //no rooks on open file for black
testBoard = Board("r2k1r2/pp2p1pp/8/5P2/7P/8/1P6/RRRKRRRR w - - 0 1");
temp = Evaluation::CheckForDoublePawns(6, testBoard);
temp = Evaluation::CheckForDoublePawns(7, testBoard);
BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 4); //4 rooks on open file for white
BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 1); //1 rook on open file for black
}
BOOST_AUTO_TEST_CASE(board_inCheck)
{
cout << "Testing inCheck function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check
BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check
testBoard = Board("4k3/8/4r3/8/8/8/8/4K3 w - - 0 1");
BOOST_CHECK(testBoard.inCheck(6) == true); //white is in check
BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check
testBoard = Board("k1r5/8/1N6/8/8/8/8/4K3 w - - 0 1");
BOOST_CHECK(testBoard.inCheck(7) == true); //black is in check
BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check
}
BOOST_AUTO_TEST_CASE(board_simpleMakeMove)
{
cout << "Testing simpleMakeMove function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
pair<int, int> startPosition = make_pair('e' - 'a', '2' - '1');
pair<int, int> endPosition = make_pair('e' - 'a', '4' - '1');
testBoard.simpleMakeMove(startPosition, endPosition, ' ');
BOOST_CHECK(testBoard.getPieceFromPos(4, 3) == 0); //pawn at e4
}
BOOST_AUTO_TEST_CASE(board_takePiece)
{
cout << "Testing takePiece function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
testBoard.takePiece(make_pair(0, 0));
BOOST_CHECK(testBoard.getPieceFromPos(0, 0) == -1); //piece has been removed
}
BOOST_AUTO_TEST_CASE(board_getPieceCode)
{
cout << "Testing getPieceCode function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(testBoard.getPieceCode('p') == 0); //pawn
BOOST_CHECK(testBoard.getPieceCode('P') == 0); //pawn
BOOST_CHECK(testBoard.getPieceCode('r') == 1); //rook
BOOST_CHECK(testBoard.getPieceCode('R') == 1); //rook
BOOST_CHECK(testBoard.getPieceCode('n') == 2); //knight
BOOST_CHECK(testBoard.getPieceCode('N') == 2); //knight
BOOST_CHECK(testBoard.getPieceCode('b') == 3); //bishop
BOOST_CHECK(testBoard.getPieceCode('B') == 3); //bishop
BOOST_CHECK(testBoard.getPieceCode('q') == 4); //queen
BOOST_CHECK(testBoard.getPieceCode('Q') == 4); //queen
BOOST_CHECK(testBoard.getPieceCode('k') == 5); //king
BOOST_CHECK(testBoard.getPieceCode('K') == 5); //king
}
int getColor(int x)
{
if (x == 1) {
return 6;
}
return 7;
}
int getLegalMoves(Board testBoard, int playerColor) {
MoveList possibleMoves = MoveList(testBoard, getColor(playerColor));
u64 castle = testBoard.getCastleOrEnpasent();
int legalMoves = 0;
while (true) {
pair<bool, mov> get = possibleMoves.getNextMove();
if (get.first) {
testBoard.makeMov(get.second);
if (testBoard.inCheck(getColor(playerColor)) == false) {
legalMoves++;
}
testBoard.unMakeMov(get.second, castle);
} else {
break;
}
}
return legalMoves;
}
BOOST_AUTO_TEST_CASE(MoveList_generateMoves)
{
cout << "Testing MoveList class" << endl;
Board testBoard = Board("k5R1/7R/8/8/8/8/8/K7 b - - 0 1");
BOOST_CHECK(getLegalMoves(testBoard, -1) == 0); //black is check mated
testBoard = Board("k7/8/8/8/8/8/8/K7 w - - 0 1");
BOOST_CHECK(getLegalMoves(testBoard, 1) == 3); //only piece is king in corner
testBoard = Board("k7/8/8/8/4K3/8/8/8 w - - 0 1");
BOOST_CHECK(getLegalMoves(testBoard, 1) == 8); //only piece is king in center
}
BOOST_AUTO_TEST_CASE(search_RootAlphaBeta)
{
cout << "Testing search" << endl;
Board testBoard = Board("k7/pppp4/8/8/8/8/8/K4R2 w - - 0 1");
Search searchClass;
BOOST_CHECK(searchClass.RootAlphaBeta(testBoard, 1, 4) == "f1f8"); //it should find the checkmate for white
}
Added Perft test for move generation
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE api_tests
#define BOOST_TEST_MAIN
#define BOOST_TEST_LOG_LEVEL all
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "../Source/UCI.hpp"
#include "../Source/Search.hpp"
#include "../Source/Board.hpp"
#include "../Source/Evaluation.hpp"
#include "../Source/MoveList.hpp"
using namespace std;
BOOST_AUTO_TEST_CASE(UCI_sentPosition)
{
cout << "Testing sentPosition function" << endl;
BOOST_CHECK(UCI::sentPosition("position startpos moves e3e2") == false);
BOOST_CHECK(UCI::sentPosition("position startpos moves e2e4") == true);
BOOST_CHECK(UCI::sentPosition("position startpos") == false);
BOOST_CHECK(UCI::sentPosition("position fen not a fen") == false);
}
BOOST_AUTO_TEST_CASE(evaluation_evaluateBoard)
{
cout << "Testing evaluateBoard function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //evaluation should be 0 for initial board
testBoard = Board("7k/8/8/8/8/8/8/7K w - - 0 1");
BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //no piece difference, symmetrical position
}
BOOST_AUTO_TEST_CASE(evaluation_CheckForDoublePawns)
{
Evaluation::initpopCountOfByte(); //initialising look-up table
cout << "Testing CheckForDoublePawns function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 0); //No double pawns for white
BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 0); //No double pawns for black
testBoard = Board("8/8/4kP2/8/5P2/PP1P2P1/PPP1P2P/3K4 w - - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 3); //3 sets of white double pawns
testBoard = Board("8/8/4kP2/8/5P2/PPPPP1PP/PPP1P2P/3K4 w - - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 6); //6 sets of white double pawns
testBoard = Board("4k3/pppppppp/pppppppp/2b2b2/P5P1/P1qK1PP1/P4PP1/6q1 w - - 0 1");
BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 8); //8 sets of black double pawns
}
BOOST_AUTO_TEST_CASE(evaluation_rooksOnOpenFile)
{
cout << "Testing rooksOnOpenFile function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
int temp = Evaluation::CheckForDoublePawns(6, testBoard); //check for double pawns initialises array of open files
temp = Evaluation::CheckForDoublePawns(7, testBoard);
BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 0); //no rooks on open file for white
BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 0); //no rooks on open file for black
testBoard = Board("r2k1r2/pp2p1pp/8/5P2/7P/8/1P6/RRRKRRRR w - - 0 1");
temp = Evaluation::CheckForDoublePawns(6, testBoard);
temp = Evaluation::CheckForDoublePawns(7, testBoard);
BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 4); //4 rooks on open file for white
BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 1); //1 rook on open file for black
}
BOOST_AUTO_TEST_CASE(board_inCheck)
{
cout << "Testing inCheck function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check
BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check
testBoard = Board("4k3/8/4r3/8/8/8/8/4K3 w - - 0 1");
BOOST_CHECK(testBoard.inCheck(6) == true); //white is in check
BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check
testBoard = Board("k1r5/8/1N6/8/8/8/8/4K3 w - - 0 1");
BOOST_CHECK(testBoard.inCheck(7) == true); //black is in check
BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check
}
BOOST_AUTO_TEST_CASE(board_simpleMakeMove)
{
cout << "Testing simpleMakeMove function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
pair<int, int> startPosition = make_pair('e' - 'a', '2' - '1');
pair<int, int> endPosition = make_pair('e' - 'a', '4' - '1');
testBoard.simpleMakeMove(startPosition, endPosition, ' ');
BOOST_CHECK(testBoard.getPieceFromPos(4, 3) == 0); //pawn at e4
}
BOOST_AUTO_TEST_CASE(board_takePiece)
{
cout << "Testing takePiece function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
testBoard.takePiece(make_pair(0, 0));
BOOST_CHECK(testBoard.getPieceFromPos(0, 0) == -1); //piece has been removed
}
BOOST_AUTO_TEST_CASE(board_getPieceCode)
{
cout << "Testing getPieceCode function" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
BOOST_CHECK(testBoard.getPieceCode('p') == 0); //pawn
BOOST_CHECK(testBoard.getPieceCode('P') == 0); //pawn
BOOST_CHECK(testBoard.getPieceCode('r') == 1); //rook
BOOST_CHECK(testBoard.getPieceCode('R') == 1); //rook
BOOST_CHECK(testBoard.getPieceCode('n') == 2); //knight
BOOST_CHECK(testBoard.getPieceCode('N') == 2); //knight
BOOST_CHECK(testBoard.getPieceCode('b') == 3); //bishop
BOOST_CHECK(testBoard.getPieceCode('B') == 3); //bishop
BOOST_CHECK(testBoard.getPieceCode('q') == 4); //queen
BOOST_CHECK(testBoard.getPieceCode('Q') == 4); //queen
BOOST_CHECK(testBoard.getPieceCode('k') == 5); //king
BOOST_CHECK(testBoard.getPieceCode('K') == 5); //king
}
int getColor(int x)
{
if (x == 1) {
return 6;
}
return 7;
}
int getLegalMoves(Board testBoard, int playerColor) {
MoveList possibleMoves = MoveList(testBoard, getColor(playerColor));
u64 castle = testBoard.getCastleOrEnpasent();
int legalMoves = 0;
while (true) {
pair<bool, mov> get = possibleMoves.getNextMove();
if (get.first) {
testBoard.makeMov(get.second);
if (testBoard.inCheck(getColor(playerColor)) == false) {
legalMoves++;
}
testBoard.unMakeMov(get.second, castle);
} else {
break;
}
}
return legalMoves;
}
BOOST_AUTO_TEST_CASE(MoveList_generateMoves)
{
cout << "Testing MoveList class" << endl;
Board testBoard = Board("k5R1/7R/8/8/8/8/8/K7 b - - 0 1");
BOOST_CHECK(getLegalMoves(testBoard, -1) == 0); //black is check mated
testBoard = Board("k7/8/8/8/8/8/8/K7 w - - 0 1");
BOOST_CHECK(getLegalMoves(testBoard, 1) == 3); //only piece is king in corner
testBoard = Board("k7/8/8/8/4K3/8/8/8 w - - 0 1");
BOOST_CHECK(getLegalMoves(testBoard, 1) == 8); //only piece is king in center
}
BOOST_AUTO_TEST_CASE(search_RootAlphaBeta)
{
cout << "Testing search" << endl;
Board testBoard = Board("k7/pppp4/8/8/8/8/8/K4R2 w - - 0 1");
BOOST_CHECK(Search::RootAlphaBeta(testBoard, 1, 4) == "f1f8"); //it should find the checkmate for white
}
//Perft is good for verifying the correctness of the move generation, generate all the leaf nodes at a given depth from a known position.
//This also shows how fast the move generation works in relation to other engines (slow, magic bitboards would speed up move generation)
u64 Perft(int depth, Board& gameBoard, int playerColor)
{
if (depth == 0) {
return 1;
}
u64 nodes = 0;
u64 castle = gameBoard.getCastleOrEnpasent();
MoveList possibleMoves(gameBoard, getColor(playerColor));
while (true) {
pair<bool, mov> get = possibleMoves.getNextMove();
if (get.first) {
gameBoard.makeMov(get.second);
if (gameBoard.inCheck(getColor(playerColor)) == false) {
nodes += Perft(depth - 1, gameBoard, playerColor*-1);
}
gameBoard.unMakeMov(get.second, castle);
} else {
break;
}
}
return nodes;
}
BOOST_AUTO_TEST_CASE(perft_Test)
{
cout << "Testing move generation (perft), this is slow" << endl;
Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); //initial position
BOOST_CHECK(Perft(4, testBoard, 1) == 197281); //Known value from the chess programming wiki http://chessprogramming.wikispaces.com/Perft+Results
testBoard = Board("r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -");
BOOST_CHECK(Perft(4, testBoard, 1) == 4085603);
testBoard = Board("8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -");
BOOST_CHECK(Perft(5, testBoard, 1) == 674624);
testBoard = Board("r2q1rk1/pP1p2pp/Q4n2/bbp1p3/Np6/1B3NBn/pPPP1PPP/R3K2R b KQ - 0 1");
BOOST_CHECK(Perft(4, testBoard, -1) == 422333);
testBoard = Board("rnbqkb1r/pp1p1ppp/2p5/4P3/2B5/8/PPP1NnPP/RNBQK2R w KQkq - 0 6");
BOOST_CHECK(Perft(3, testBoard, 1) == 53392);
testBoard = Board("r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10");
BOOST_CHECK(Perft(4, testBoard, 1) == 3894594);
}
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
*/
#include "osl/file.hxx"
#include "osl/detail/file.h"
#include "osl/diagnose.h"
#include "osl/thread.h"
#include <osl/signal.h>
#include "rtl/alloc.h"
#include <rtl/string.hxx>
#include "system.hxx"
#include "file_impl.hxx"
#include "file_error_transl.hxx"
#include "file_path_helper.hxx"
#include "file_url.hxx"
#include "uunxapi.hxx"
#include "readwrite_helper.hxx"
#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <algorithm>
#ifdef ANDROID
#include <osl/detail/android-bootstrap.h>
#endif
/************************************************************************
* TODO
*
* - Fix: check for corresponding struct sizes in exported functions
* - check size/use of oslDirectory
* - check size/use of oslDirectoryItem
***********************************************************************/
typedef struct
{
rtl_uString* ustrPath; /* holds native directory path */
DIR* pDirStruct;
#ifdef ANDROID
enum Kind
{
KIND_DIRENT = 1,
KIND_ASSETS = 2
};
int eKind;
lo_apk_dir* pApkDirStruct;
#endif
} oslDirectoryImpl;
DirectoryItem_Impl::DirectoryItem_Impl(
rtl_uString * ustrFilePath, unsigned char DType)
: m_RefCount (1),
m_ustrFilePath (ustrFilePath),
m_DType (DType)
{
if (m_ustrFilePath != 0)
rtl_uString_acquire(m_ustrFilePath);
}
DirectoryItem_Impl::~DirectoryItem_Impl()
{
if (m_ustrFilePath != 0)
rtl_uString_release(m_ustrFilePath);
}
void * DirectoryItem_Impl::operator new(size_t n)
{
return rtl_allocateMemory(n);
}
void DirectoryItem_Impl::operator delete(void * p)
{
rtl_freeMemory(p);
}
void DirectoryItem_Impl::acquire()
{
++m_RefCount;
}
void DirectoryItem_Impl::release()
{
if (0 == --m_RefCount)
delete this;
}
oslFileType DirectoryItem_Impl::getFileType() const
{
switch (m_DType)
{
#ifdef _DIRENT_HAVE_D_TYPE
case DT_LNK:
return osl_File_Type_Link;
case DT_DIR:
return osl_File_Type_Directory;
case DT_REG:
return osl_File_Type_Regular;
case DT_FIFO:
return osl_File_Type_Fifo;
case DT_SOCK:
return osl_File_Type_Socket;
case DT_CHR:
case DT_BLK:
return osl_File_Type_Special;
#endif /* _DIRENT_HAVE_D_TYPE */
default:
break;
}
return osl_File_Type_Unknown;
}
static oslFileError osl_psz_createDirectory(
char const * pszPath, sal_uInt32 flags);
static oslFileError osl_psz_removeDirectory(const sal_Char* pszPath);
oslFileError SAL_CALL osl_openDirectory(rtl_uString* ustrDirectoryURL, oslDirectory* pDirectory)
{
rtl_uString* ustrSystemPath = NULL;
oslFileError eRet;
char path[PATH_MAX];
if ((0 == ustrDirectoryURL) || (0 == ustrDirectoryURL->length) || (0 == pDirectory))
return osl_File_E_INVAL;
/* convert file URL to system path */
eRet = osl_getSystemPathFromFileURL_Ex(ustrDirectoryURL, &ustrSystemPath);
if( osl_File_E_None != eRet )
return eRet;
osl_systemPathRemoveSeparator(ustrSystemPath);
/* convert unicode path to text */
if ( UnicodeToText( path, PATH_MAX, ustrSystemPath->buffer, ustrSystemPath->length )
#ifdef MACOSX
&& macxp_resolveAlias( path, PATH_MAX ) == 0
#endif /* MACOSX */
)
{
#ifdef ANDROID
if( strncmp( path, "/assets/", sizeof( "/assets/" ) - 1) == 0 )
{
lo_apk_dir *pdir = lo_apk_opendir( path );
if( pdir )
{
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*) rtl_allocateMemory( sizeof(oslDirectoryImpl) );
if( pDirImpl )
{
pDirImpl->eKind = oslDirectoryImpl::KIND_ASSETS;
pDirImpl->pApkDirStruct = pdir;
pDirImpl->ustrPath = ustrSystemPath;
*pDirectory = (oslDirectory) pDirImpl;
return osl_File_E_None;
}
else
{
errno = ENOMEM;
lo_apk_closedir( pdir );
}
}
}
else
#endif
{
/* open directory */
DIR *pdir = opendir( path );
if( pdir )
{
/* create and initialize impl structure */
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*) rtl_allocateMemory( sizeof(oslDirectoryImpl) );
if( pDirImpl )
{
pDirImpl->pDirStruct = pdir;
pDirImpl->ustrPath = ustrSystemPath;
#ifdef ANDROID
pDirImpl->eKind = oslDirectoryImpl::KIND_DIRENT;
#endif
*pDirectory = (oslDirectory) pDirImpl;
return osl_File_E_None;
}
else
{
errno = ENOMEM;
closedir( pdir );
}
}
else
{
#ifdef DEBUG_OSL_FILE
perror ("osl_openDirectory"); fprintf (stderr, path);
#endif
}
}
}
rtl_uString_release( ustrSystemPath );
return oslTranslateFileError(OSL_FET_ERROR, errno);
}
oslFileError SAL_CALL osl_closeDirectory( oslDirectory Directory )
{
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*) Directory;
oslFileError err = osl_File_E_None;
OSL_ASSERT( Directory );
if( NULL == pDirImpl )
return osl_File_E_INVAL;
#ifdef ANDROID
if( pDirImpl->eKind == oslDirectoryImpl::KIND_ASSETS )
{
if (lo_apk_closedir( pDirImpl->pApkDirStruct ))
err = osl_File_E_IO;
}
else
#endif
{
if( closedir( pDirImpl->pDirStruct ) )
err = oslTranslateFileError(OSL_FET_ERROR, errno);
}
/* cleanup members */
rtl_uString_release( pDirImpl->ustrPath );
rtl_freeMemory( pDirImpl );
return err;
}
/**********************************************
* osl_readdir_impl_
*
* readdir wrapper, filters out "." and ".."
* on request
*********************************************/
static struct dirent* osl_readdir_impl_(DIR* pdir, bool bFilterLocalAndParentDir)
{
struct dirent* pdirent;
while ((pdirent = readdir(pdir)) != NULL)
{
if (bFilterLocalAndParentDir &&
((0 == strcmp(pdirent->d_name, ".")) || (0 == strcmp(pdirent->d_name, ".."))))
continue;
else
break;
}
return pdirent;
}
oslFileError SAL_CALL osl_getNextDirectoryItem(oslDirectory Directory, oslDirectoryItem* pItem, SAL_UNUSED_PARAMETER sal_uInt32 /*uHint*/)
{
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*)Directory;
rtl_uString* ustrFileName = NULL;
rtl_uString* ustrFilePath = NULL;
struct dirent* pEntry;
OSL_ASSERT(Directory);
OSL_ASSERT(pItem);
if ((NULL == Directory) || (NULL == pItem))
return osl_File_E_INVAL;
#ifdef ANDROID
if( pDirImpl->eKind == oslDirectoryImpl::KIND_ASSETS )
{
pEntry = lo_apk_readdir(pDirImpl->pApkDirStruct);
}
else
#endif
{
pEntry = osl_readdir_impl_(pDirImpl->pDirStruct, true);
}
if (NULL == pEntry)
return osl_File_E_NOENT;
#if defined(MACOSX)
// convert decomposed filename to precomposed unicode
char composed_name[BUFSIZ];
CFMutableStringRef strRef = CFStringCreateMutable (NULL, 0 );
CFStringAppendCString( strRef, pEntry->d_name, kCFStringEncodingUTF8 ); //UTF8 is default on Mac OSX
CFStringNormalize( strRef, kCFStringNormalizationFormC );
CFStringGetCString( strRef, composed_name, BUFSIZ, kCFStringEncodingUTF8 );
CFRelease( strRef );
rtl_string2UString( &ustrFileName, composed_name, strlen( composed_name),
osl_getThreadTextEncoding(), OSTRING_TO_OUSTRING_CVTFLAGS );
#else // not MACOSX
/* convert file name to unicode */
rtl_string2UString( &ustrFileName, pEntry->d_name, strlen( pEntry->d_name ),
osl_getThreadTextEncoding(), OSTRING_TO_OUSTRING_CVTFLAGS );
OSL_ASSERT(ustrFileName != 0);
#endif
osl_systemPathMakeAbsolutePath(pDirImpl->ustrPath, ustrFileName, &ustrFilePath);
rtl_uString_release( ustrFileName );
DirectoryItem_Impl * pImpl = static_cast< DirectoryItem_Impl* >(*pItem);
if (0 != pImpl)
{
pImpl->release(), pImpl = 0;
}
#ifdef _DIRENT_HAVE_D_TYPE
pImpl = new DirectoryItem_Impl(ustrFilePath, pEntry->d_type);
#else
pImpl = new DirectoryItem_Impl(ustrFilePath);
#endif /* _DIRENT_HAVE_D_TYPE */
*pItem = pImpl;
rtl_uString_release( ustrFilePath );
return osl_File_E_None;
}
oslFileError SAL_CALL osl_getDirectoryItem( rtl_uString* ustrFileURL, oslDirectoryItem* pItem )
{
rtl_uString* ustrSystemPath = NULL;
oslFileError osl_error = osl_File_E_INVAL;
OSL_ASSERT((0 != ustrFileURL) && (0 != pItem));
if ((0 == ustrFileURL) || (0 == ustrFileURL->length) || (0 == pItem))
return osl_File_E_INVAL;
osl_error = osl_getSystemPathFromFileURL_Ex(ustrFileURL, &ustrSystemPath);
if (osl_File_E_None != osl_error)
return osl_error;
osl_systemPathRemoveSeparator(ustrSystemPath);
if (-1 == access_u(ustrSystemPath, F_OK))
{
osl_error = oslTranslateFileError(OSL_FET_ERROR, errno);
}
else
{
*pItem = new DirectoryItem_Impl(ustrSystemPath);
}
rtl_uString_release(ustrSystemPath);
return osl_error;
}
oslFileError SAL_CALL osl_acquireDirectoryItem( oslDirectoryItem Item )
{
DirectoryItem_Impl * pImpl = static_cast< DirectoryItem_Impl* >(Item);
if (0 == pImpl)
return osl_File_E_INVAL;
pImpl->acquire();
return osl_File_E_None;
}
oslFileError SAL_CALL osl_releaseDirectoryItem( oslDirectoryItem Item )
{
DirectoryItem_Impl * pImpl = static_cast< DirectoryItem_Impl* >(Item);
if (0 == pImpl)
return osl_File_E_INVAL;
pImpl->release();
return osl_File_E_None;
}
oslFileError SAL_CALL osl_createDirectory( rtl_uString* ustrDirectoryURL )
{
return osl_createDirectoryWithFlags(
ustrDirectoryURL, osl_File_OpenFlag_Read | osl_File_OpenFlag_Write);
}
oslFileError osl_createDirectoryWithFlags(
rtl_uString * ustrDirectoryURL, sal_uInt32 flags)
{
char path[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrDirectoryURL );
/* convert directory url to system path */
eRet = FileURLToPath( path, PATH_MAX, ustrDirectoryURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( path, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_createDirectory( path, flags );
}
oslFileError SAL_CALL osl_removeDirectory( rtl_uString* ustrDirectoryURL )
{
char path[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrDirectoryURL );
/* convert directory url to system path */
eRet = FileURLToPath( path, PATH_MAX, ustrDirectoryURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( path, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_removeDirectory( path );
}
oslFileError osl_psz_createDirectory(char const * pszPath, sal_uInt32 flags)
{
int nRet=0;
int mode
= (((flags & osl_File_OpenFlag_Read) == 0
? 0
: ((flags & osl_File_OpenFlag_Private) == 0
? S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
: S_IRUSR | S_IXUSR))
| ((flags & osl_File_OpenFlag_Write) == 0
? 0
: ((flags & osl_File_OpenFlag_Private) == 0
? S_IWUSR | S_IWGRP | S_IWOTH
: S_IWUSR)));
nRet = mkdir(pszPath,mode);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static oslFileError osl_psz_removeDirectory( const sal_Char* pszPath )
{
int nRet=0;
nRet = rmdir(pszPath);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static int path_make_parent(sal_Unicode* path)
{
int i = rtl_ustr_lastIndexOfChar(path, '/');
if (i > 0)
{
*(path + i) = 0;
return i;
}
else
return 0;
}
static int create_dir_with_callback(
sal_Unicode* directory_path,
oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc,
void* pData)
{
int mode = S_IRWXU | S_IRWXG | S_IRWXO;
if (osl::mkdir(directory_path, mode) == 0)
{
if (aDirectoryCreationCallbackFunc)
{
rtl::OUString url;
osl::FileBase::getFileURLFromSystemPath(directory_path, url);
aDirectoryCreationCallbackFunc(pData, url.pData);
}
return 0;
}
return errno;
}
static oslFileError create_dir_recursively_(
sal_Unicode* dir_path,
oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc,
void* pData)
{
OSL_PRECOND((rtl_ustr_getLength(dir_path) > 0) && ((dir_path + (rtl_ustr_getLength(dir_path) - 1)) != (dir_path + rtl_ustr_lastIndexOfChar(dir_path, '/'))), \
"Path must not end with a slash");
int native_err = create_dir_with_callback(
dir_path, aDirectoryCreationCallbackFunc, pData);
if (native_err == 0)
return osl_File_E_None;
if (native_err != ENOENT)
return oslTranslateFileError(OSL_FET_ERROR, native_err);
// we step back until '/a_dir' at maximum because
// we should get an error unequal ENOENT when
// we try to create 'a_dir' at '/' and would so
// return before
int pos = path_make_parent(dir_path);
oslFileError osl_error = create_dir_recursively_(
dir_path, aDirectoryCreationCallbackFunc, pData);
if (osl_File_E_None != osl_error)
return osl_error;
dir_path[pos] = '/';
return create_dir_recursively_(dir_path, aDirectoryCreationCallbackFunc, pData);
}
oslFileError SAL_CALL osl_createDirectoryPath(
rtl_uString* aDirectoryUrl,
oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc,
void* pData)
{
if (aDirectoryUrl == NULL)
return osl_File_E_INVAL;
rtl::OUString sys_path;
oslFileError osl_error = osl_getSystemPathFromFileURL_Ex(aDirectoryUrl, &sys_path.pData);
if (osl_error != osl_File_E_None)
return osl_error;
osl::systemPathRemoveSeparator(sys_path);
// const_cast because sys_path is a local copy which we want to modify inplace instead of
// coyp it into another buffer on the heap again
return create_dir_recursively_(sys_path.pData->buffer, aDirectoryCreationCallbackFunc, pData);
}
static oslFileError osl_psz_removeFile(const sal_Char* pszPath);
static oslFileError osl_psz_copyFile(const sal_Char* pszPath, const sal_Char* pszDestPath, bool preserveMetadata);
static oslFileError osl_psz_moveFile(const sal_Char* pszPath, const sal_Char* pszDestPath);
static oslFileError oslDoCopy(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, mode_t nMode, size_t nSourceSize, int DestFileExists);
static void attemptChangeMetadata(const sal_Char* pszFileName, mode_t nMode, time_t nAcTime, time_t nModTime, uid_t nUID, gid_t nGID);
static int oslDoCopyLink(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName);
static int oslDoCopyFile(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, size_t nSourceSize, mode_t mode);
static oslFileError oslDoMoveFile(const sal_Char* pszPath, const sal_Char* pszDestPath);
oslFileError SAL_CALL osl_moveFile( rtl_uString* ustrFileURL, rtl_uString* ustrDestURL )
{
char srcPath[PATH_MAX];
char destPath[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrFileURL );
OSL_ASSERT( ustrDestURL );
/* convert source url to system path */
eRet = FileURLToPath( srcPath, PATH_MAX, ustrFileURL );
if( eRet != osl_File_E_None )
return eRet;
/* convert destination url to system path */
eRet = FileURLToPath( destPath, PATH_MAX, ustrDestURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( srcPath, PATH_MAX ) != 0 || macxp_resolveAlias( destPath, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return oslDoMoveFile( srcPath, destPath );
}
oslFileError SAL_CALL osl_copyFile( rtl_uString* ustrFileURL, rtl_uString* ustrDestURL )
{
char srcPath[PATH_MAX];
char destPath[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrFileURL );
OSL_ASSERT( ustrDestURL );
/* convert source url to system path */
eRet = FileURLToPath( srcPath, PATH_MAX, ustrFileURL );
if( eRet != osl_File_E_None )
return eRet;
/* convert destination url to system path */
eRet = FileURLToPath( destPath, PATH_MAX, ustrDestURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( srcPath, PATH_MAX ) != 0 || macxp_resolveAlias( destPath, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_copyFile( srcPath, destPath, false );
}
oslFileError SAL_CALL osl_removeFile( rtl_uString* ustrFileURL )
{
char path[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrFileURL );
/* convert file url to system path */
eRet = FileURLToPath( path, PATH_MAX, ustrFileURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( path, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_removeFile( path );
}
static oslFileError oslDoMoveFile( const sal_Char* pszPath, const sal_Char* pszDestPath)
{
oslFileError tErr = osl_psz_moveFile(pszPath,pszDestPath);
if ( tErr == osl_File_E_None )
{
return tErr;
}
if ( tErr != osl_File_E_XDEV )
{
return tErr;
}
tErr=osl_psz_copyFile(pszPath,pszDestPath, true);
if ( tErr != osl_File_E_None )
{
osl_psz_removeFile(pszDestPath);
return tErr;
}
tErr=osl_psz_removeFile(pszPath);
return tErr;
}
static oslFileError osl_psz_removeFile( const sal_Char* pszPath )
{
int nRet=0;
struct stat aStat;
nRet = lstat_c(pszPath,&aStat);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
if ( S_ISDIR(aStat.st_mode) )
{
return osl_File_E_ISDIR;
}
nRet = unlink(pszPath);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static oslFileError osl_psz_moveFile(const sal_Char* pszPath, const sal_Char* pszDestPath)
{
int nRet = 0;
nRet = rename(pszPath,pszDestPath);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static oslFileError osl_psz_copyFile( const sal_Char* pszPath, const sal_Char* pszDestPath, bool preserveMetadata )
{
time_t nAcTime=0;
time_t nModTime=0;
uid_t nUID=0;
gid_t nGID=0;
int nRet=0;
mode_t nMode=0;
struct stat aFileStat;
oslFileError tErr=osl_File_E_invalidError;
size_t nSourceSize=0;
int DestFileExists=1;
/* mfe: does the source file really exists? */
nRet = lstat_c(pszPath,&aFileStat);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
/* mfe: we do only copy files here! */
if ( S_ISDIR(aFileStat.st_mode) )
{
return osl_File_E_ISDIR;
}
nSourceSize=(size_t)aFileStat.st_size;
nMode=aFileStat.st_mode;
nAcTime=aFileStat.st_atime;
nModTime=aFileStat.st_mtime;
nUID=aFileStat.st_uid;
nGID=aFileStat.st_gid;
nRet = stat_c(pszDestPath,&aFileStat);
if ( nRet < 0 )
{
nRet=errno;
if ( nRet == ENOENT )
{
DestFileExists=0;
}
}
/* mfe: the destination file must not be a directory! */
if ( nRet == 0 && S_ISDIR(aFileStat.st_mode) )
{
return osl_File_E_ISDIR;
}
else
{
/* mfe: file does not exists or is no dir */
}
tErr = oslDoCopy(pszPath,pszDestPath,nMode,nSourceSize,DestFileExists);
if ( tErr != osl_File_E_None )
{
return tErr;
}
if (preserveMetadata)
{
attemptChangeMetadata(pszDestPath,nMode,nAcTime,nModTime,nUID,nGID);
}
return tErr;
}
static oslFileError oslDoCopy(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, mode_t nMode, size_t nSourceSize, int DestFileExists)
{
int nRet=0;
rtl::OString tmpDestFile;
if ( DestFileExists )
{
//TODO: better pick a temp file name instead of adding .osl-tmp:
tmpDestFile = rtl::OString(pszSourceFileName) + ".osl-tmp";
if (rename(pszDestFileName, tmpDestFile.getStr()) != 0)
{
if (errno == ENOENT)
{
DestFileExists = 0;
}
else
{
int e = errno;
SAL_INFO(
"sal.osl",
"rename(" << pszDestFileName << ", " << tmpDestFile
<< ") failed with errno " << e);
return osl_File_E_BUSY; // for want of a better error code
}
}
}
/* mfe: should be S_ISREG */
if ( !S_ISLNK(nMode) )
{
/* copy SourceFile to DestFile */
nRet = oslDoCopyFile(pszSourceFileName,pszDestFileName,nSourceSize, nMode);
}
/* mfe: OK redundant at the moment */
else if ( S_ISLNK(nMode) )
{
nRet = oslDoCopyLink(pszSourceFileName,pszDestFileName);
}
else
{
/* mfe: what to do here? */
nRet=ENOSYS;
}
if ( nRet > 0 && DestFileExists == 1 )
{
unlink(pszDestFileName);
if (rename(tmpDestFile.getStr(), pszDestFileName) != 0)
{
int e = errno;
SAL_WARN(
"sal.osl",
"rename(" << tmpDestFile << ", " << pszDestFileName
<< ") failed with errno " << e);
}
}
if ( nRet > 0 )
{
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
if ( DestFileExists == 1 )
{
unlink(tmpDestFile.getStr());
}
return osl_File_E_None;
}
void attemptChangeMetadata( const sal_Char* pszFileName, mode_t nMode, time_t nAcTime, time_t nModTime, uid_t nUID, gid_t nGID)
{
struct utimbuf aTimeBuffer;
if ( fchmodat(AT_FDCWD, pszFileName, nMode, AT_SYMLINK_NOFOLLOW) < 0 )
{
int e = errno;
SAL_INFO(
"sal.osl",
"fchmodat(" << pszFileName << ") failed with errno " << e);
}
// No way to change utime of a symlink itself:
if (!S_ISLNK(nMode))
{
aTimeBuffer.actime=nAcTime;
aTimeBuffer.modtime=nModTime;
if ( utime(pszFileName,&aTimeBuffer) < 0 )
{
int e = errno;
SAL_INFO(
"sal.osl",
"utime(" << pszFileName << ") failed with errno " << e);
}
}
if ( nUID != getuid() )
{
nUID=getuid();
}
if ( lchown(pszFileName,nUID,nGID) < 0 )
{
int e = errno;
SAL_INFO(
"sal.osl", "lchown(" << pszFileName << ") failed with errno " << e);
}
}
static int oslDoCopyLink(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName)
{
int nRet=0;
/* mfe: if dest file is symbolic link remove the link and place the file instead (hro says so) */
/* mfe: if source is a link copy the link and not the file it points to (hro says so) */
sal_Char pszLinkContent[PATH_MAX+1];
pszLinkContent[0] = '\0';
nRet = readlink(pszSourceFileName,pszLinkContent,PATH_MAX);
if ( nRet < 0 )
{
nRet=errno;
return nRet;
}
else
pszLinkContent[ nRet ] = 0;
nRet = symlink(pszLinkContent,pszDestFileName);
if ( nRet < 0 )
{
nRet=errno;
return nRet;
}
return 0;
}
static int oslDoCopyFile(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, size_t nSourceSize, mode_t mode)
{
oslFileHandle SourceFileFH=0;
int DestFileFD=0;
int nRet=0;
if (openFilePath(pszSourceFileName,
&SourceFileFH,
osl_File_OpenFlag_Read|osl_File_OpenFlag_NoLock|osl_File_OpenFlag_NoExcl, mode_t(-1)) != osl_File_E_None)
{
// Let's hope errno is still set relevantly after openFilePath...
nRet=errno;
return nRet;
}
DestFileFD=open(pszDestFileName, O_WRONLY | O_CREAT, mode);
if ( DestFileFD < 0 )
{
nRet=errno;
osl_closeFile(SourceFileFH);
return nRet;
}
size_t nRemains = nSourceSize;
if ( nRemains )
{
/* mmap has problems, try the direct streaming */
char pBuffer[0x7FFF];
do
{
size_t nToRead = std::min( sizeof(pBuffer), nRemains );
sal_uInt64 nRead;
bool succeeded;
if ( osl_readFile( SourceFileFH, pBuffer, nToRead, &nRead ) != osl_File_E_None || nRead > nToRead || nRead == 0 )
break;
succeeded = safeWrite( DestFileFD, pBuffer, nRead );
if ( !succeeded )
break;
// We know nRead <= nToRead, so it must fit in a size_t
nRemains -= (size_t) nRead;
}
while( nRemains );
}
if ( nRemains )
{
if ( errno )
nRet = errno;
else
nRet = ENOSPC;
}
osl_closeFile( SourceFileFH );
if ( close( DestFileFD ) == -1 && nRet == 0 )
nRet = errno;
return nRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
At least old Mac OS X does not know AT_FDCWD
...lets hope it is actually declared as a macro wherever it is known.
Change-Id: If541d02af3ac5d9ad4f0ac1cb4dd9f9f4550a78a
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
*/
#include "osl/file.hxx"
#include "osl/detail/file.h"
#include "osl/diagnose.h"
#include "osl/thread.h"
#include <osl/signal.h>
#include "rtl/alloc.h"
#include <rtl/string.hxx>
#include "system.hxx"
#include "file_impl.hxx"
#include "file_error_transl.hxx"
#include "file_path_helper.hxx"
#include "file_url.hxx"
#include "uunxapi.hxx"
#include "readwrite_helper.hxx"
#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <algorithm>
#ifdef ANDROID
#include <osl/detail/android-bootstrap.h>
#endif
/************************************************************************
* TODO
*
* - Fix: check for corresponding struct sizes in exported functions
* - check size/use of oslDirectory
* - check size/use of oslDirectoryItem
***********************************************************************/
typedef struct
{
rtl_uString* ustrPath; /* holds native directory path */
DIR* pDirStruct;
#ifdef ANDROID
enum Kind
{
KIND_DIRENT = 1,
KIND_ASSETS = 2
};
int eKind;
lo_apk_dir* pApkDirStruct;
#endif
} oslDirectoryImpl;
DirectoryItem_Impl::DirectoryItem_Impl(
rtl_uString * ustrFilePath, unsigned char DType)
: m_RefCount (1),
m_ustrFilePath (ustrFilePath),
m_DType (DType)
{
if (m_ustrFilePath != 0)
rtl_uString_acquire(m_ustrFilePath);
}
DirectoryItem_Impl::~DirectoryItem_Impl()
{
if (m_ustrFilePath != 0)
rtl_uString_release(m_ustrFilePath);
}
void * DirectoryItem_Impl::operator new(size_t n)
{
return rtl_allocateMemory(n);
}
void DirectoryItem_Impl::operator delete(void * p)
{
rtl_freeMemory(p);
}
void DirectoryItem_Impl::acquire()
{
++m_RefCount;
}
void DirectoryItem_Impl::release()
{
if (0 == --m_RefCount)
delete this;
}
oslFileType DirectoryItem_Impl::getFileType() const
{
switch (m_DType)
{
#ifdef _DIRENT_HAVE_D_TYPE
case DT_LNK:
return osl_File_Type_Link;
case DT_DIR:
return osl_File_Type_Directory;
case DT_REG:
return osl_File_Type_Regular;
case DT_FIFO:
return osl_File_Type_Fifo;
case DT_SOCK:
return osl_File_Type_Socket;
case DT_CHR:
case DT_BLK:
return osl_File_Type_Special;
#endif /* _DIRENT_HAVE_D_TYPE */
default:
break;
}
return osl_File_Type_Unknown;
}
static oslFileError osl_psz_createDirectory(
char const * pszPath, sal_uInt32 flags);
static oslFileError osl_psz_removeDirectory(const sal_Char* pszPath);
oslFileError SAL_CALL osl_openDirectory(rtl_uString* ustrDirectoryURL, oslDirectory* pDirectory)
{
rtl_uString* ustrSystemPath = NULL;
oslFileError eRet;
char path[PATH_MAX];
if ((0 == ustrDirectoryURL) || (0 == ustrDirectoryURL->length) || (0 == pDirectory))
return osl_File_E_INVAL;
/* convert file URL to system path */
eRet = osl_getSystemPathFromFileURL_Ex(ustrDirectoryURL, &ustrSystemPath);
if( osl_File_E_None != eRet )
return eRet;
osl_systemPathRemoveSeparator(ustrSystemPath);
/* convert unicode path to text */
if ( UnicodeToText( path, PATH_MAX, ustrSystemPath->buffer, ustrSystemPath->length )
#ifdef MACOSX
&& macxp_resolveAlias( path, PATH_MAX ) == 0
#endif /* MACOSX */
)
{
#ifdef ANDROID
if( strncmp( path, "/assets/", sizeof( "/assets/" ) - 1) == 0 )
{
lo_apk_dir *pdir = lo_apk_opendir( path );
if( pdir )
{
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*) rtl_allocateMemory( sizeof(oslDirectoryImpl) );
if( pDirImpl )
{
pDirImpl->eKind = oslDirectoryImpl::KIND_ASSETS;
pDirImpl->pApkDirStruct = pdir;
pDirImpl->ustrPath = ustrSystemPath;
*pDirectory = (oslDirectory) pDirImpl;
return osl_File_E_None;
}
else
{
errno = ENOMEM;
lo_apk_closedir( pdir );
}
}
}
else
#endif
{
/* open directory */
DIR *pdir = opendir( path );
if( pdir )
{
/* create and initialize impl structure */
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*) rtl_allocateMemory( sizeof(oslDirectoryImpl) );
if( pDirImpl )
{
pDirImpl->pDirStruct = pdir;
pDirImpl->ustrPath = ustrSystemPath;
#ifdef ANDROID
pDirImpl->eKind = oslDirectoryImpl::KIND_DIRENT;
#endif
*pDirectory = (oslDirectory) pDirImpl;
return osl_File_E_None;
}
else
{
errno = ENOMEM;
closedir( pdir );
}
}
else
{
#ifdef DEBUG_OSL_FILE
perror ("osl_openDirectory"); fprintf (stderr, path);
#endif
}
}
}
rtl_uString_release( ustrSystemPath );
return oslTranslateFileError(OSL_FET_ERROR, errno);
}
oslFileError SAL_CALL osl_closeDirectory( oslDirectory Directory )
{
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*) Directory;
oslFileError err = osl_File_E_None;
OSL_ASSERT( Directory );
if( NULL == pDirImpl )
return osl_File_E_INVAL;
#ifdef ANDROID
if( pDirImpl->eKind == oslDirectoryImpl::KIND_ASSETS )
{
if (lo_apk_closedir( pDirImpl->pApkDirStruct ))
err = osl_File_E_IO;
}
else
#endif
{
if( closedir( pDirImpl->pDirStruct ) )
err = oslTranslateFileError(OSL_FET_ERROR, errno);
}
/* cleanup members */
rtl_uString_release( pDirImpl->ustrPath );
rtl_freeMemory( pDirImpl );
return err;
}
/**********************************************
* osl_readdir_impl_
*
* readdir wrapper, filters out "." and ".."
* on request
*********************************************/
static struct dirent* osl_readdir_impl_(DIR* pdir, bool bFilterLocalAndParentDir)
{
struct dirent* pdirent;
while ((pdirent = readdir(pdir)) != NULL)
{
if (bFilterLocalAndParentDir &&
((0 == strcmp(pdirent->d_name, ".")) || (0 == strcmp(pdirent->d_name, ".."))))
continue;
else
break;
}
return pdirent;
}
oslFileError SAL_CALL osl_getNextDirectoryItem(oslDirectory Directory, oslDirectoryItem* pItem, SAL_UNUSED_PARAMETER sal_uInt32 /*uHint*/)
{
oslDirectoryImpl* pDirImpl = (oslDirectoryImpl*)Directory;
rtl_uString* ustrFileName = NULL;
rtl_uString* ustrFilePath = NULL;
struct dirent* pEntry;
OSL_ASSERT(Directory);
OSL_ASSERT(pItem);
if ((NULL == Directory) || (NULL == pItem))
return osl_File_E_INVAL;
#ifdef ANDROID
if( pDirImpl->eKind == oslDirectoryImpl::KIND_ASSETS )
{
pEntry = lo_apk_readdir(pDirImpl->pApkDirStruct);
}
else
#endif
{
pEntry = osl_readdir_impl_(pDirImpl->pDirStruct, true);
}
if (NULL == pEntry)
return osl_File_E_NOENT;
#if defined(MACOSX)
// convert decomposed filename to precomposed unicode
char composed_name[BUFSIZ];
CFMutableStringRef strRef = CFStringCreateMutable (NULL, 0 );
CFStringAppendCString( strRef, pEntry->d_name, kCFStringEncodingUTF8 ); //UTF8 is default on Mac OSX
CFStringNormalize( strRef, kCFStringNormalizationFormC );
CFStringGetCString( strRef, composed_name, BUFSIZ, kCFStringEncodingUTF8 );
CFRelease( strRef );
rtl_string2UString( &ustrFileName, composed_name, strlen( composed_name),
osl_getThreadTextEncoding(), OSTRING_TO_OUSTRING_CVTFLAGS );
#else // not MACOSX
/* convert file name to unicode */
rtl_string2UString( &ustrFileName, pEntry->d_name, strlen( pEntry->d_name ),
osl_getThreadTextEncoding(), OSTRING_TO_OUSTRING_CVTFLAGS );
OSL_ASSERT(ustrFileName != 0);
#endif
osl_systemPathMakeAbsolutePath(pDirImpl->ustrPath, ustrFileName, &ustrFilePath);
rtl_uString_release( ustrFileName );
DirectoryItem_Impl * pImpl = static_cast< DirectoryItem_Impl* >(*pItem);
if (0 != pImpl)
{
pImpl->release(), pImpl = 0;
}
#ifdef _DIRENT_HAVE_D_TYPE
pImpl = new DirectoryItem_Impl(ustrFilePath, pEntry->d_type);
#else
pImpl = new DirectoryItem_Impl(ustrFilePath);
#endif /* _DIRENT_HAVE_D_TYPE */
*pItem = pImpl;
rtl_uString_release( ustrFilePath );
return osl_File_E_None;
}
oslFileError SAL_CALL osl_getDirectoryItem( rtl_uString* ustrFileURL, oslDirectoryItem* pItem )
{
rtl_uString* ustrSystemPath = NULL;
oslFileError osl_error = osl_File_E_INVAL;
OSL_ASSERT((0 != ustrFileURL) && (0 != pItem));
if ((0 == ustrFileURL) || (0 == ustrFileURL->length) || (0 == pItem))
return osl_File_E_INVAL;
osl_error = osl_getSystemPathFromFileURL_Ex(ustrFileURL, &ustrSystemPath);
if (osl_File_E_None != osl_error)
return osl_error;
osl_systemPathRemoveSeparator(ustrSystemPath);
if (-1 == access_u(ustrSystemPath, F_OK))
{
osl_error = oslTranslateFileError(OSL_FET_ERROR, errno);
}
else
{
*pItem = new DirectoryItem_Impl(ustrSystemPath);
}
rtl_uString_release(ustrSystemPath);
return osl_error;
}
oslFileError SAL_CALL osl_acquireDirectoryItem( oslDirectoryItem Item )
{
DirectoryItem_Impl * pImpl = static_cast< DirectoryItem_Impl* >(Item);
if (0 == pImpl)
return osl_File_E_INVAL;
pImpl->acquire();
return osl_File_E_None;
}
oslFileError SAL_CALL osl_releaseDirectoryItem( oslDirectoryItem Item )
{
DirectoryItem_Impl * pImpl = static_cast< DirectoryItem_Impl* >(Item);
if (0 == pImpl)
return osl_File_E_INVAL;
pImpl->release();
return osl_File_E_None;
}
oslFileError SAL_CALL osl_createDirectory( rtl_uString* ustrDirectoryURL )
{
return osl_createDirectoryWithFlags(
ustrDirectoryURL, osl_File_OpenFlag_Read | osl_File_OpenFlag_Write);
}
oslFileError osl_createDirectoryWithFlags(
rtl_uString * ustrDirectoryURL, sal_uInt32 flags)
{
char path[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrDirectoryURL );
/* convert directory url to system path */
eRet = FileURLToPath( path, PATH_MAX, ustrDirectoryURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( path, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_createDirectory( path, flags );
}
oslFileError SAL_CALL osl_removeDirectory( rtl_uString* ustrDirectoryURL )
{
char path[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrDirectoryURL );
/* convert directory url to system path */
eRet = FileURLToPath( path, PATH_MAX, ustrDirectoryURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( path, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_removeDirectory( path );
}
oslFileError osl_psz_createDirectory(char const * pszPath, sal_uInt32 flags)
{
int nRet=0;
int mode
= (((flags & osl_File_OpenFlag_Read) == 0
? 0
: ((flags & osl_File_OpenFlag_Private) == 0
? S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
: S_IRUSR | S_IXUSR))
| ((flags & osl_File_OpenFlag_Write) == 0
? 0
: ((flags & osl_File_OpenFlag_Private) == 0
? S_IWUSR | S_IWGRP | S_IWOTH
: S_IWUSR)));
nRet = mkdir(pszPath,mode);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static oslFileError osl_psz_removeDirectory( const sal_Char* pszPath )
{
int nRet=0;
nRet = rmdir(pszPath);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static int path_make_parent(sal_Unicode* path)
{
int i = rtl_ustr_lastIndexOfChar(path, '/');
if (i > 0)
{
*(path + i) = 0;
return i;
}
else
return 0;
}
static int create_dir_with_callback(
sal_Unicode* directory_path,
oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc,
void* pData)
{
int mode = S_IRWXU | S_IRWXG | S_IRWXO;
if (osl::mkdir(directory_path, mode) == 0)
{
if (aDirectoryCreationCallbackFunc)
{
rtl::OUString url;
osl::FileBase::getFileURLFromSystemPath(directory_path, url);
aDirectoryCreationCallbackFunc(pData, url.pData);
}
return 0;
}
return errno;
}
static oslFileError create_dir_recursively_(
sal_Unicode* dir_path,
oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc,
void* pData)
{
OSL_PRECOND((rtl_ustr_getLength(dir_path) > 0) && ((dir_path + (rtl_ustr_getLength(dir_path) - 1)) != (dir_path + rtl_ustr_lastIndexOfChar(dir_path, '/'))), \
"Path must not end with a slash");
int native_err = create_dir_with_callback(
dir_path, aDirectoryCreationCallbackFunc, pData);
if (native_err == 0)
return osl_File_E_None;
if (native_err != ENOENT)
return oslTranslateFileError(OSL_FET_ERROR, native_err);
// we step back until '/a_dir' at maximum because
// we should get an error unequal ENOENT when
// we try to create 'a_dir' at '/' and would so
// return before
int pos = path_make_parent(dir_path);
oslFileError osl_error = create_dir_recursively_(
dir_path, aDirectoryCreationCallbackFunc, pData);
if (osl_File_E_None != osl_error)
return osl_error;
dir_path[pos] = '/';
return create_dir_recursively_(dir_path, aDirectoryCreationCallbackFunc, pData);
}
oslFileError SAL_CALL osl_createDirectoryPath(
rtl_uString* aDirectoryUrl,
oslDirectoryCreationCallbackFunc aDirectoryCreationCallbackFunc,
void* pData)
{
if (aDirectoryUrl == NULL)
return osl_File_E_INVAL;
rtl::OUString sys_path;
oslFileError osl_error = osl_getSystemPathFromFileURL_Ex(aDirectoryUrl, &sys_path.pData);
if (osl_error != osl_File_E_None)
return osl_error;
osl::systemPathRemoveSeparator(sys_path);
// const_cast because sys_path is a local copy which we want to modify inplace instead of
// coyp it into another buffer on the heap again
return create_dir_recursively_(sys_path.pData->buffer, aDirectoryCreationCallbackFunc, pData);
}
static oslFileError osl_psz_removeFile(const sal_Char* pszPath);
static oslFileError osl_psz_copyFile(const sal_Char* pszPath, const sal_Char* pszDestPath, bool preserveMetadata);
static oslFileError osl_psz_moveFile(const sal_Char* pszPath, const sal_Char* pszDestPath);
static oslFileError oslDoCopy(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, mode_t nMode, size_t nSourceSize, int DestFileExists);
static void attemptChangeMetadata(const sal_Char* pszFileName, mode_t nMode, time_t nAcTime, time_t nModTime, uid_t nUID, gid_t nGID);
static int oslDoCopyLink(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName);
static int oslDoCopyFile(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, size_t nSourceSize, mode_t mode);
static oslFileError oslDoMoveFile(const sal_Char* pszPath, const sal_Char* pszDestPath);
oslFileError SAL_CALL osl_moveFile( rtl_uString* ustrFileURL, rtl_uString* ustrDestURL )
{
char srcPath[PATH_MAX];
char destPath[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrFileURL );
OSL_ASSERT( ustrDestURL );
/* convert source url to system path */
eRet = FileURLToPath( srcPath, PATH_MAX, ustrFileURL );
if( eRet != osl_File_E_None )
return eRet;
/* convert destination url to system path */
eRet = FileURLToPath( destPath, PATH_MAX, ustrDestURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( srcPath, PATH_MAX ) != 0 || macxp_resolveAlias( destPath, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return oslDoMoveFile( srcPath, destPath );
}
oslFileError SAL_CALL osl_copyFile( rtl_uString* ustrFileURL, rtl_uString* ustrDestURL )
{
char srcPath[PATH_MAX];
char destPath[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrFileURL );
OSL_ASSERT( ustrDestURL );
/* convert source url to system path */
eRet = FileURLToPath( srcPath, PATH_MAX, ustrFileURL );
if( eRet != osl_File_E_None )
return eRet;
/* convert destination url to system path */
eRet = FileURLToPath( destPath, PATH_MAX, ustrDestURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( srcPath, PATH_MAX ) != 0 || macxp_resolveAlias( destPath, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_copyFile( srcPath, destPath, false );
}
oslFileError SAL_CALL osl_removeFile( rtl_uString* ustrFileURL )
{
char path[PATH_MAX];
oslFileError eRet;
OSL_ASSERT( ustrFileURL );
/* convert file url to system path */
eRet = FileURLToPath( path, PATH_MAX, ustrFileURL );
if( eRet != osl_File_E_None )
return eRet;
#ifdef MACOSX
if ( macxp_resolveAlias( path, PATH_MAX ) != 0 )
return oslTranslateFileError( OSL_FET_ERROR, errno );
#endif/* MACOSX */
return osl_psz_removeFile( path );
}
static oslFileError oslDoMoveFile( const sal_Char* pszPath, const sal_Char* pszDestPath)
{
oslFileError tErr = osl_psz_moveFile(pszPath,pszDestPath);
if ( tErr == osl_File_E_None )
{
return tErr;
}
if ( tErr != osl_File_E_XDEV )
{
return tErr;
}
tErr=osl_psz_copyFile(pszPath,pszDestPath, true);
if ( tErr != osl_File_E_None )
{
osl_psz_removeFile(pszDestPath);
return tErr;
}
tErr=osl_psz_removeFile(pszPath);
return tErr;
}
static oslFileError osl_psz_removeFile( const sal_Char* pszPath )
{
int nRet=0;
struct stat aStat;
nRet = lstat_c(pszPath,&aStat);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
if ( S_ISDIR(aStat.st_mode) )
{
return osl_File_E_ISDIR;
}
nRet = unlink(pszPath);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static oslFileError osl_psz_moveFile(const sal_Char* pszPath, const sal_Char* pszDestPath)
{
int nRet = 0;
nRet = rename(pszPath,pszDestPath);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
return osl_File_E_None;
}
static oslFileError osl_psz_copyFile( const sal_Char* pszPath, const sal_Char* pszDestPath, bool preserveMetadata )
{
time_t nAcTime=0;
time_t nModTime=0;
uid_t nUID=0;
gid_t nGID=0;
int nRet=0;
mode_t nMode=0;
struct stat aFileStat;
oslFileError tErr=osl_File_E_invalidError;
size_t nSourceSize=0;
int DestFileExists=1;
/* mfe: does the source file really exists? */
nRet = lstat_c(pszPath,&aFileStat);
if ( nRet < 0 )
{
nRet=errno;
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
/* mfe: we do only copy files here! */
if ( S_ISDIR(aFileStat.st_mode) )
{
return osl_File_E_ISDIR;
}
nSourceSize=(size_t)aFileStat.st_size;
nMode=aFileStat.st_mode;
nAcTime=aFileStat.st_atime;
nModTime=aFileStat.st_mtime;
nUID=aFileStat.st_uid;
nGID=aFileStat.st_gid;
nRet = stat_c(pszDestPath,&aFileStat);
if ( nRet < 0 )
{
nRet=errno;
if ( nRet == ENOENT )
{
DestFileExists=0;
}
}
/* mfe: the destination file must not be a directory! */
if ( nRet == 0 && S_ISDIR(aFileStat.st_mode) )
{
return osl_File_E_ISDIR;
}
else
{
/* mfe: file does not exists or is no dir */
}
tErr = oslDoCopy(pszPath,pszDestPath,nMode,nSourceSize,DestFileExists);
if ( tErr != osl_File_E_None )
{
return tErr;
}
if (preserveMetadata)
{
attemptChangeMetadata(pszDestPath,nMode,nAcTime,nModTime,nUID,nGID);
}
return tErr;
}
static oslFileError oslDoCopy(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, mode_t nMode, size_t nSourceSize, int DestFileExists)
{
int nRet=0;
rtl::OString tmpDestFile;
if ( DestFileExists )
{
//TODO: better pick a temp file name instead of adding .osl-tmp:
tmpDestFile = rtl::OString(pszSourceFileName) + ".osl-tmp";
if (rename(pszDestFileName, tmpDestFile.getStr()) != 0)
{
if (errno == ENOENT)
{
DestFileExists = 0;
}
else
{
int e = errno;
SAL_INFO(
"sal.osl",
"rename(" << pszDestFileName << ", " << tmpDestFile
<< ") failed with errno " << e);
return osl_File_E_BUSY; // for want of a better error code
}
}
}
/* mfe: should be S_ISREG */
if ( !S_ISLNK(nMode) )
{
/* copy SourceFile to DestFile */
nRet = oslDoCopyFile(pszSourceFileName,pszDestFileName,nSourceSize, nMode);
}
/* mfe: OK redundant at the moment */
else if ( S_ISLNK(nMode) )
{
nRet = oslDoCopyLink(pszSourceFileName,pszDestFileName);
}
else
{
/* mfe: what to do here? */
nRet=ENOSYS;
}
if ( nRet > 0 && DestFileExists == 1 )
{
unlink(pszDestFileName);
if (rename(tmpDestFile.getStr(), pszDestFileName) != 0)
{
int e = errno;
SAL_WARN(
"sal.osl",
"rename(" << tmpDestFile << ", " << pszDestFileName
<< ") failed with errno " << e);
}
}
if ( nRet > 0 )
{
return oslTranslateFileError(OSL_FET_ERROR, nRet);
}
if ( DestFileExists == 1 )
{
unlink(tmpDestFile.getStr());
}
return osl_File_E_None;
}
void attemptChangeMetadata( const sal_Char* pszFileName, mode_t nMode, time_t nAcTime, time_t nModTime, uid_t nUID, gid_t nGID)
{
struct utimbuf aTimeBuffer;
#if !defined AT_FDCWD
if (!S_ISLNK(nMode) && chmod(pszFileName, nMode) < 0)
#else
if ( fchmodat(AT_FDCWD, pszFileName, nMode, AT_SYMLINK_NOFOLLOW) < 0 )
#endif
{
int e = errno;
SAL_INFO(
"sal.osl", "chmod(" << pszFileName << ") failed with errno " << e);
}
// No way to change utime of a symlink itself:
if (!S_ISLNK(nMode))
{
aTimeBuffer.actime=nAcTime;
aTimeBuffer.modtime=nModTime;
if ( utime(pszFileName,&aTimeBuffer) < 0 )
{
int e = errno;
SAL_INFO(
"sal.osl",
"utime(" << pszFileName << ") failed with errno " << e);
}
}
if ( nUID != getuid() )
{
nUID=getuid();
}
if ( lchown(pszFileName,nUID,nGID) < 0 )
{
int e = errno;
SAL_INFO(
"sal.osl", "lchown(" << pszFileName << ") failed with errno " << e);
}
}
static int oslDoCopyLink(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName)
{
int nRet=0;
/* mfe: if dest file is symbolic link remove the link and place the file instead (hro says so) */
/* mfe: if source is a link copy the link and not the file it points to (hro says so) */
sal_Char pszLinkContent[PATH_MAX+1];
pszLinkContent[0] = '\0';
nRet = readlink(pszSourceFileName,pszLinkContent,PATH_MAX);
if ( nRet < 0 )
{
nRet=errno;
return nRet;
}
else
pszLinkContent[ nRet ] = 0;
nRet = symlink(pszLinkContent,pszDestFileName);
if ( nRet < 0 )
{
nRet=errno;
return nRet;
}
return 0;
}
static int oslDoCopyFile(const sal_Char* pszSourceFileName, const sal_Char* pszDestFileName, size_t nSourceSize, mode_t mode)
{
oslFileHandle SourceFileFH=0;
int DestFileFD=0;
int nRet=0;
if (openFilePath(pszSourceFileName,
&SourceFileFH,
osl_File_OpenFlag_Read|osl_File_OpenFlag_NoLock|osl_File_OpenFlag_NoExcl, mode_t(-1)) != osl_File_E_None)
{
// Let's hope errno is still set relevantly after openFilePath...
nRet=errno;
return nRet;
}
DestFileFD=open(pszDestFileName, O_WRONLY | O_CREAT, mode);
if ( DestFileFD < 0 )
{
nRet=errno;
osl_closeFile(SourceFileFH);
return nRet;
}
size_t nRemains = nSourceSize;
if ( nRemains )
{
/* mmap has problems, try the direct streaming */
char pBuffer[0x7FFF];
do
{
size_t nToRead = std::min( sizeof(pBuffer), nRemains );
sal_uInt64 nRead;
bool succeeded;
if ( osl_readFile( SourceFileFH, pBuffer, nToRead, &nRead ) != osl_File_E_None || nRead > nToRead || nRead == 0 )
break;
succeeded = safeWrite( DestFileFD, pBuffer, nRead );
if ( !succeeded )
break;
// We know nRead <= nToRead, so it must fit in a size_t
nRemains -= (size_t) nRead;
}
while( nRemains );
}
if ( nRemains )
{
if ( errno )
nRet = errno;
else
nRet = ENOSPC;
}
osl_closeFile( SourceFileFH );
if ( close( DestFileFD ) == -1 && nRet == 0 )
nRet = errno;
return nRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
#include "drawable.h"
#include <foundation/memory.h>
#include "idrawable_geometry.h"
#include <cmath>
namespace bowtie
{
////////////////////////////////
// Public interface.
Drawable::Drawable(Allocator& allocator, IDrawableGeometry& geometry) : _allocator(allocator), _geometry(geometry),
_pivot(0, 0), _position(0, 0), _render_state_changed(false), _rotation(0.7f)
{
}
Drawable::Drawable(const Drawable& other) : _allocator(other._allocator), _geometry(other._geometry.clone(_allocator)),
_pivot(0, 0), _position(other._position), _render_state_changed(false), _rotation(0.7f)
{
}
Drawable::~Drawable()
{
_allocator.destroy(&_geometry);
}
const Color& Drawable::color() const
{
return _geometry.color();
}
IDrawableGeometry& Drawable::geometry()
{
return _geometry;
}
const IDrawableGeometry& Drawable::geometry() const
{
return _geometry;
}
bool Drawable::geometry_changed() const
{
return _geometry.has_changed();
}
ResourceHandle Drawable::geometry_handle() const
{
return _geometry_handle;
}
Matrix4 Drawable::model_matrix() const
{
auto p = Matrix4();
p[3][0] = (float)_pivot.x;
p[3][1] = (float)_pivot.y;
auto p_inv = Matrix4();
p[3][0] = -(float)_pivot.x;
p[3][1] = -(float)_pivot.y;
auto r = Matrix4();
r[0][0] = cos(_rotation);
r[1][0] = -sin(_rotation);
r[0][1] = sin(_rotation);
r[1][1] = cos(_rotation);
auto t = Matrix4();
t[3][0] = _position.x;
t[3][1] = _position.y;
if (_pivot.x == 0 && _pivot.y == 0)
return r * t;
else
return p * r * p_inv * t;
}
const Vector2i& Drawable::pivot() const
{
return _pivot;
}
const Vector2& Drawable::position() const
{
return _position;
}
ResourceHandle Drawable::render_handle() const
{
return _render_handle;
}
void Drawable::reset_geometry_changed()
{
_geometry.reset_has_changed();
}
void Drawable::reset_state_changed()
{
_render_state_changed = false;
}
float Drawable::rotation() const
{
return _rotation;
}
void Drawable::set_color(const Color& color)
{
_geometry.set_color(color);
}
void Drawable::set_geometry_handle(ResourceHandle handle)
{
_geometry_handle = handle;
}
void Drawable::set_pivot(const Vector2i& pivot)
{
_pivot = pivot;
_render_state_changed = true;
}
void Drawable::set_position(const Vector2& position)
{
_position = position;
_render_state_changed = true;
}
void Drawable::set_render_handle(ResourceHandle handle)
{
assert(_render_handle.type == ResourceHandle::NotInitialized && "Trying to reset already initliaized drawable render handle.");
_render_handle = handle;
}
void Drawable::set_rotation(float rotation)
{
_rotation = rotation;
_render_state_changed = true;
}
void Drawable::set_shader(ResourceHandle shader)
{
_shader = shader;
_render_state_changed = true;
}
ResourceHandle Drawable::shader() const
{
return _shader;
}
bool Drawable::state_changed() const
{
return _render_state_changed;
}
}
Removed debug rotation.
#include "drawable.h"
#include <foundation/memory.h>
#include "idrawable_geometry.h"
#include <cmath>
namespace bowtie
{
////////////////////////////////
// Public interface.
Drawable::Drawable(Allocator& allocator, IDrawableGeometry& geometry) : _allocator(allocator), _geometry(geometry),
_pivot(0, 0), _position(0, 0), _render_state_changed(false), _rotation(0.0f)
{
}
Drawable::Drawable(const Drawable& other) : _allocator(other._allocator), _geometry(other._geometry.clone(_allocator)),
_pivot(0, 0), _position(other._position), _render_state_changed(false), _rotation(0.0f)
{
}
Drawable::~Drawable()
{
_allocator.destroy(&_geometry);
}
const Color& Drawable::color() const
{
return _geometry.color();
}
IDrawableGeometry& Drawable::geometry()
{
return _geometry;
}
const IDrawableGeometry& Drawable::geometry() const
{
return _geometry;
}
bool Drawable::geometry_changed() const
{
return _geometry.has_changed();
}
ResourceHandle Drawable::geometry_handle() const
{
return _geometry_handle;
}
Matrix4 Drawable::model_matrix() const
{
auto p = Matrix4();
p[3][0] = (float)_pivot.x;
p[3][1] = (float)_pivot.y;
auto p_inv = Matrix4();
p[3][0] = -(float)_pivot.x;
p[3][1] = -(float)_pivot.y;
auto r = Matrix4();
r[0][0] = cos(_rotation);
r[1][0] = -sin(_rotation);
r[0][1] = sin(_rotation);
r[1][1] = cos(_rotation);
auto t = Matrix4();
t[3][0] = _position.x;
t[3][1] = _position.y;
if (_pivot.x == 0 && _pivot.y == 0)
return r * t;
else
return p * r * p_inv * t;
}
const Vector2i& Drawable::pivot() const
{
return _pivot;
}
const Vector2& Drawable::position() const
{
return _position;
}
ResourceHandle Drawable::render_handle() const
{
return _render_handle;
}
void Drawable::reset_geometry_changed()
{
_geometry.reset_has_changed();
}
void Drawable::reset_state_changed()
{
_render_state_changed = false;
}
float Drawable::rotation() const
{
return _rotation;
}
void Drawable::set_color(const Color& color)
{
_geometry.set_color(color);
}
void Drawable::set_geometry_handle(ResourceHandle handle)
{
_geometry_handle = handle;
}
void Drawable::set_pivot(const Vector2i& pivot)
{
_pivot = pivot;
_render_state_changed = true;
}
void Drawable::set_position(const Vector2& position)
{
_position = position;
_render_state_changed = true;
}
void Drawable::set_render_handle(ResourceHandle handle)
{
assert(_render_handle.type == ResourceHandle::NotInitialized && "Trying to reset already initliaized drawable render handle.");
_render_handle = handle;
}
void Drawable::set_rotation(float rotation)
{
_rotation = rotation;
_render_state_changed = true;
}
void Drawable::set_shader(ResourceHandle shader)
{
_shader = shader;
_render_state_changed = true;
}
ResourceHandle Drawable::shader() const
{
return _shader;
}
bool Drawable::state_changed() const
{
return _render_state_changed;
}
}
|
/*************************************************************************
*
* $RCSfile: ChartOOoTContext.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:44:28 $
*
* 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 EXPRESSED 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 _XMLOFF_CHARTOOOTCONTEXT_HXX
#define _XMLOFF_CHARTOOOTCONTEXT_HXX
#ifndef _XMLOFF_TRANSFORMERCONTEXT_HXX
#include "TransformerContext.hxx"
#endif
class XMLChartOOoTransformerContext : public XMLTransformerContext
{
public:
TYPEINFO();
XMLChartOOoTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName );
virtual ~XMLChartOOoTransformerContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
};
#endif // _XMLOFF_CHARTOOOTCONTEXT_HXX
INTEGRATION: CWS ooo19126 (1.2.298); FILE MERGED
2005/09/05 14:40:17 rt 1.2.298.1: #i54170# Change license header: remove SISSL
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChartOOoTContext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:36:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#ifndef _XMLOFF_CHARTOOOTCONTEXT_HXX
#define _XMLOFF_CHARTOOOTCONTEXT_HXX
#ifndef _XMLOFF_TRANSFORMERCONTEXT_HXX
#include "TransformerContext.hxx"
#endif
class XMLChartOOoTransformerContext : public XMLTransformerContext
{
public:
TYPEINFO();
XMLChartOOoTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName );
virtual ~XMLChartOOoTransformerContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
};
#endif // _XMLOFF_CHARTOOOTCONTEXT_HXX
|
ISO C++11 does not allow conversion from string literal to 'char *'
Change-Id: I098d0b8b3428cbf57a69c331515093df36e0c172
|
// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_STORAGE_ARCHIVE_HPP
#define OUZEL_STORAGE_ARCHIVE_HPP
#include <cstdint>
#include <fstream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include "../utils/Utils.hpp"
namespace ouzel
{
namespace storage
{
class Archive final
{
public:
Archive() = default;
explicit Archive(const std::string& path):
file{path, std::ios::binary}
{
constexpr std::uint32_t CENTRAL_DIRECTORY = 0x02014B50;
constexpr std::uint32_t HEADER_SIGNATURE = 0x04034B50;
for (;;)
{
std::uint8_t signatureData[4];
file.read(reinterpret_cast<char*>(signatureData), sizeof(signatureData));
if (decodeLittleEndian<std::uint32_t>(signatureData) == CENTRAL_DIRECTORY)
break;
if (decodeLittleEndian<std::uint32_t>(signatureData) != HEADER_SIGNATURE)
throw std::runtime_error("Bad signature");
file.seekg(2, std::ios::cur); // skip version
file.seekg(2, std::ios::cur); // skip flags
std::uint8_t compressionData[2];
file.read(reinterpret_cast<char*>(&compressionData), sizeof(compressionData));
if (decodeLittleEndian<std::uint16_t>(compressionData) != 0x00)
throw std::runtime_error("Unsupported compression");
file.seekg(2, std::ios::cur); // skip modification time
file.seekg(2, std::ios::cur); // skip modification date
file.seekg(4, std::ios::cur); // skip CRC-32
std::uint8_t compressedSizeData[4];
file.read(reinterpret_cast<char*>(compressedSizeData), sizeof(compressedSizeData));
std::uint8_t uncompressedSizeData[4];
file.read(reinterpret_cast<char*>(uncompressedSizeData), sizeof(uncompressedSizeData));
const size_t uncompressedSize = decodeLittleEndian<std::uint32_t>(uncompressedSizeData);
std::uint8_t fileNameLengthData[2];
file.read(reinterpret_cast<char*>(fileNameLengthData), sizeof(fileNameLengthData));
const size_t fileNameLength = decodeLittleEndian<std::uint16_t>(fileNameLengthData);
std::uint8_t extraFieldLengthData[2];
file.read(reinterpret_cast<char*>(extraFieldLengthData), sizeof(extraFieldLengthData));
const size_t extraFieldLength = decodeLittleEndian<std::uint16_t>(extraFieldLengthData);
auto name = std::make_unique<char[]>(fileNameLength + 1);
file.read(name.get(), static_cast<std::streamsize>(fileNameLength));
name[fileNameLength] = '\0';
Entry& entry = entries[name.get()];
entry.size = uncompressedSize;
file.seekg(static_cast<std::streamoff>(extraFieldLength),
std::ios::cur); // skip extra field
entry.offset = file.tellg();
file.seekg(static_cast<std::streamoff>(uncompressedSize),
std::ios::cur); // skip uncompressed size
}
}
std::vector<std::uint8_t> readFile(const std::string& filename)
{
std::vector<std::uint8_t> data;
auto i = entries.find(filename);
if (i == entries.end())
throw std::runtime_error("File " + filename + " does not exist");
file.seekg(i->second.offset, std::ios::beg);
data.resize(i->second.size);
file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(i->second.size));
return data;
}
bool fileExists(const std::string& filename) const
{
return entries.find(filename) != entries.end();
}
private:
std::ifstream file;
struct Entry final
{
std::streamoff offset;
std::size_t size;
};
std::map<std::string, Entry> entries;
};
} // namespace storage
} // namespace ouzel
#endif // OUZEL_STORAGE_ARCHIVE_HPP
Initialize data with correct size instead of resizing it
// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_STORAGE_ARCHIVE_HPP
#define OUZEL_STORAGE_ARCHIVE_HPP
#include <cstdint>
#include <fstream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include "../utils/Utils.hpp"
namespace ouzel
{
namespace storage
{
class Archive final
{
public:
Archive() = default;
explicit Archive(const std::string& path):
file{path, std::ios::binary}
{
constexpr std::uint32_t CENTRAL_DIRECTORY = 0x02014B50;
constexpr std::uint32_t HEADER_SIGNATURE = 0x04034B50;
for (;;)
{
std::uint8_t signatureData[4];
file.read(reinterpret_cast<char*>(signatureData), sizeof(signatureData));
if (decodeLittleEndian<std::uint32_t>(signatureData) == CENTRAL_DIRECTORY)
break;
if (decodeLittleEndian<std::uint32_t>(signatureData) != HEADER_SIGNATURE)
throw std::runtime_error("Bad signature");
file.seekg(2, std::ios::cur); // skip version
file.seekg(2, std::ios::cur); // skip flags
std::uint8_t compressionData[2];
file.read(reinterpret_cast<char*>(&compressionData), sizeof(compressionData));
if (decodeLittleEndian<std::uint16_t>(compressionData) != 0x00)
throw std::runtime_error("Unsupported compression");
file.seekg(2, std::ios::cur); // skip modification time
file.seekg(2, std::ios::cur); // skip modification date
file.seekg(4, std::ios::cur); // skip CRC-32
std::uint8_t compressedSizeData[4];
file.read(reinterpret_cast<char*>(compressedSizeData), sizeof(compressedSizeData));
std::uint8_t uncompressedSizeData[4];
file.read(reinterpret_cast<char*>(uncompressedSizeData), sizeof(uncompressedSizeData));
const size_t uncompressedSize = decodeLittleEndian<std::uint32_t>(uncompressedSizeData);
std::uint8_t fileNameLengthData[2];
file.read(reinterpret_cast<char*>(fileNameLengthData), sizeof(fileNameLengthData));
const size_t fileNameLength = decodeLittleEndian<std::uint16_t>(fileNameLengthData);
std::uint8_t extraFieldLengthData[2];
file.read(reinterpret_cast<char*>(extraFieldLengthData), sizeof(extraFieldLengthData));
const size_t extraFieldLength = decodeLittleEndian<std::uint16_t>(extraFieldLengthData);
auto name = std::make_unique<char[]>(fileNameLength + 1);
file.read(name.get(), static_cast<std::streamsize>(fileNameLength));
name[fileNameLength] = '\0';
Entry& entry = entries[name.get()];
entry.size = uncompressedSize;
file.seekg(static_cast<std::streamoff>(extraFieldLength),
std::ios::cur); // skip extra field
entry.offset = file.tellg();
file.seekg(static_cast<std::streamoff>(uncompressedSize),
std::ios::cur); // skip uncompressed size
}
}
std::vector<std::uint8_t> readFile(const std::string& filename)
{
auto i = entries.find(filename);
if (i == entries.end())
throw std::runtime_error("File " + filename + " does not exist");
file.seekg(i->second.offset, std::ios::beg);
std::vector<std::uint8_t> data(i->second.size);
file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(i->second.size));
return data;
}
bool fileExists(const std::string& filename) const
{
return entries.find(filename) != entries.end();
}
private:
std::ifstream file;
struct Entry final
{
std::streamoff offset;
std::size_t size;
};
std::map<std::string, Entry> entries;
};
} // namespace storage
} // namespace ouzel
#endif // OUZEL_STORAGE_ARCHIVE_HPP
|
/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield
*
* This software is open source and may be redistributed and/or modified under
* the terms of the GNU General Public License (GPL) version 2.0.
* The full license is in LICENSE.txt file included with this distribution,.
*
* This software 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
* include LICENSE.txt for more details.
*/
#include <osg/Geometry>
#include <osg/Texture2D>
#include <osg/AutoTransform>
#include <osg/Notify>
#include <osg/io_utils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileNameUtils>
#include <osgUtil/Optimizer>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <OpenThreads/Thread>
#include <osgGA/GUIEventHandler>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/StateSetManipulator>
#include <osgPresentation/deprecated/SlideEventHandler>
#include <osgPresentation/Cursor>
#include "ReadShowFile.h"
#include "PointsEventHandler.h"
#include "Cluster.h"
#include "ExportHTML.h"
#include "SpellChecker.h"
#include <sstream>
#include <fstream>
#include <iostream>
#include <string.h>
#ifdef USE_SDL
#include "SDLIntegration.h"
#endif
#ifdef OSG_LIBRARY_STATIC
// include the plugins we need
USE_OSGPLUGIN(ive)
USE_OSGPLUGIN(osg)
USE_OSGPLUGIN(osg2)
USE_OSGPLUGIN(p3d)
USE_OSGPLUGIN(paths)
USE_OSGPLUGIN(rgb)
USE_OSGPLUGIN(OpenFlight)
USE_OSGPLUGIN(obj)
#ifdef USE_FREETYPE
USE_OSGPLUGIN(freetype)
#endif
#ifdef USE_PNG
USE_OSGPLUGIN(png)
#endif
#ifdef USE_JPEG
USE_OSGPLUGIN(jpeg)
#endif
#ifdef USE_FFMPEG
USE_OSGPLUGIN(ffmpeg)
#endif
#ifdef USE_POPPLER_CAIRO
USE_OSGPLUGIN(pdf)
#endif
#ifdef USE_CURL
USE_OSGPLUGIN(curl)
#endif
USE_DOTOSGWRAPPER_LIBRARY(osg)
USE_DOTOSGWRAPPER_LIBRARY(osgFX)
USE_DOTOSGWRAPPER_LIBRARY(osgParticle)
USE_DOTOSGWRAPPER_LIBRARY(osgShadow)
USE_DOTOSGWRAPPER_LIBRARY(osgSim)
USE_DOTOSGWRAPPER_LIBRARY(osgTerrain)
USE_DOTOSGWRAPPER_LIBRARY(osgText)
USE_DOTOSGWRAPPER_LIBRARY(osgViewer)
USE_DOTOSGWRAPPER_LIBRARY(osgVolume)
USE_DOTOSGWRAPPER_LIBRARY(osgWidget)
USE_SERIALIZER_WRAPPER_LIBRARY(osg)
USE_SERIALIZER_WRAPPER_LIBRARY(osgAnimation)
USE_SERIALIZER_WRAPPER_LIBRARY(osgFX)
USE_SERIALIZER_WRAPPER_LIBRARY(osgManipulator)
USE_SERIALIZER_WRAPPER_LIBRARY(osgParticle)
USE_SERIALIZER_WRAPPER_LIBRARY(osgShadow)
USE_SERIALIZER_WRAPPER_LIBRARY(osgSim)
USE_SERIALIZER_WRAPPER_LIBRARY(osgTerrain)
USE_SERIALIZER_WRAPPER_LIBRARY(osgText)
USE_SERIALIZER_WRAPPER_LIBRARY(osgVolume)
// include the platform specific GraphicsWindow implementation.
USE_GRAPHICSWINDOW()
#endif
static const char* s_version = "1.4 beta";
void setViewer(osgViewer::Viewer& viewer, float width, float height, float distance)
{
double vfov = osg::RadiansToDegrees(atan2(height/2.0f,distance)*2.0);
// double hfov = osg::RadiansToDegrees(atan2(width/2.0f,distance)*2.0);
viewer.getCamera()->setProjectionMatrixAsPerspective( vfov, width/height, 0.1, 1000.0);
OSG_INFO<<"setProjectionMatrixAsPerspective( "<<vfov<<", "<<width/height<<", "<<0.1<<", "<<1000.0<<");"<<std::endl;
}
class ForwardToDeviceEventHandler : public osgGA::GUIEventHandler {
public:
ForwardToDeviceEventHandler(osgGA::Device* device) : osgGA::GUIEventHandler(), _device(device) {}
virtual bool handle (const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osg::Object *, osg::NodeVisitor *)
{
OSG_INFO<<"ForwardToDeviceEventHandler::setEvent("<<ea.getKey()<<")"<<std::endl;
_device->sendEvent(ea);
return false;
}
private:
osg::ref_ptr<osgGA::Device> _device;
};
enum P3DApplicationType
{
VIEWER,
MASTER,
SLAVE
};
void processLoadedModel(osg::ref_ptr<osg::Node>& loadedModel, int optimizer_options, const std::string& cursorFileName)
{
if (!loadedModel) return;
#if !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)
// add back in enabling of the GL_ALPHA_TEST to get around the core OSG no longer setting it by default for opaque bins.
// the alpha test is required for the volume rendering alpha clipping to work.
loadedModel->getOrCreateStateSet()->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
#endif
// optimize the scene graph, remove rendundent nodes and state etc.
osgUtil::Optimizer optimizer;
optimizer.optimize(loadedModel.get(), optimizer_options);
if (!cursorFileName.empty())
{
osg::ref_ptr<osg::Group> group = new osg::Group;
group->addChild(loadedModel.get());
OSG_NOTICE<<"Creating Cursor"<<std::endl;
group->addChild(new osgPresentation::Cursor(cursorFileName, 20.0f));
loadedModel = group;
}
}
void addDeviceTo(osgViewer::Viewer& viewer, const std::string& device_name)
{
osg::ref_ptr<osgGA::Device> dev = osgDB::readFile<osgGA::Device>(device_name);
if (dev.valid())
{
OSG_INFO << "Adding Device : " << device_name << std::endl;
viewer.addDevice(dev.get());
if (dev->getCapabilities() & osgGA::Device::SEND_EVENTS)
viewer.getEventHandlers().push_front(new ForwardToDeviceEventHandler(dev.get()));
}
else
{
OSG_WARN << "could not open device: " << device_name << std::endl;
}
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the application for presenting 3D interactive slide shows.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-a","Turn auto stepping on by default");
arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time duration in seconds between layers/slides");
arguments.getApplicationUsage()->addCommandLineOption("-s <float> <float> <float>","width, height, distance and of the screen away from the viewer");
arguments.getApplicationUsage()->addCommandLineOption("--viewer","Start Present3D as the viewer version.");
arguments.getApplicationUsage()->addCommandLineOption("--authoring","Start Present3D as the authoring version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--master","Start Present3D as the master version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--slave","Start Present3D as the slave version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--publishing","Start Present3D as the publishing version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--timeDelayOnNewSlideWithMovies","Set the time delay on new slide with movies, done to allow movie threads to get in sync with rendering thread.");
arguments.getApplicationUsage()->addCommandLineOption("--targetFrameRate","Set the target frame rate, defaults to 80Hz.");
arguments.getApplicationUsage()->addCommandLineOption("--version","Report the Present3D version.");
arguments.getApplicationUsage()->addCommandLineOption("--print <filename>","Print out slides to a series of image files.");
arguments.getApplicationUsage()->addCommandLineOption("--html <filename>","Print out slides to a series of html & image files.");
arguments.getApplicationUsage()->addCommandLineOption("--loop","Switch on looping of presentation.");
arguments.getApplicationUsage()->addCommandLineOption("--devices","Print the Video input capability via QuickTime and exit.");
// add alias from xml to p3d to provide backwards compatibility for old p3d files.
osgDB::Registry::instance()->addFileExtensionAlias("xml","p3d");
// if user requests devices video capability.
if (arguments.read("-devices") || arguments.read("--devices"))
{
// Force load QuickTime plugin, probe video capability, exit
osgDB::readImageFile("devices.live");
return 1;
}
// read any env vars from presentations before we create viewer to make sure the viewer
// utilises these env vars
if (p3d::readEnvVars(arguments))
{
osg::DisplaySettings::instance()->readEnvironmentalVariables();
}
// set up any logins required for http access
std::string url, username, password;
while(arguments.read("--login",url, username, password))
{
if (!osgDB::Registry::instance()->getAuthenticationMap())
{
osgDB::Registry::instance()->setAuthenticationMap(new osgDB::AuthenticationMap);
osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails(
url,
new osgDB::AuthenticationDetails(username, password)
);
}
}
#ifdef USE_SDL
SDLIntegration sdlIntegration;
osg::notify(osg::INFO)<<"USE_SDL"<<std::endl;
#endif
bool doSetViewer = true;
std::string configurationFile;
// check env vars for configuration file
const char* str = getenv("PRESENT3D_CONFIG_FILE");
if (!str) str = getenv("OSG_CONFIG_FILE");
if (str) configurationFile = str;
// check command line parameters for configuration file.
while (arguments.read("-c",configurationFile)) {}
osg::Vec4 clearColor(0.0f,0.0f,0.0f,0.0f);
while (arguments.read("--clear-color",clearColor[0],clearColor[1],clearColor[2],clearColor[3])) {}
std::string filename;
if (arguments.read("--spell-check",filename))
{
p3d::SpellChecker spellChecker;
spellChecker.checkP3dXml(filename);
return 1;
}
if (arguments.read("--strip-text",filename))
{
p3d::XmlPatcher patcher;
// patcher.stripP3dXml(filename, osg::notify(osg::NOTICE));
osg::ref_ptr<osgDB::XmlNode> newNode = patcher.simplifyP3dXml(filename);
if (newNode.valid())
{
newNode->write(std::cout);
}
return 1;
}
std::string lhs_filename, rhs_filename;
if (arguments.read("--merge",lhs_filename, rhs_filename))
{
p3d::XmlPatcher patcher;
osg::ref_ptr<osgDB::XmlNode> newNode = patcher.mergeP3dXml(lhs_filename, rhs_filename);
if (newNode.valid())
{
newNode->write(std::cout);
}
return 1;
}
// construct the viewer.
osgViewer::Viewer viewer(arguments);
// set clear colour to black by default.
viewer.getCamera()->setClearColor(clearColor);
if (!configurationFile.empty())
{
viewer.readConfiguration(configurationFile);
doSetViewer = false;
}
const char* p3dDevice = getenv("P3D_DEVICE");
if (p3dDevice)
{
osgDB::StringList devices;
osgDB::split(p3dDevice, devices);
for(osgDB::StringList::iterator i = devices.begin(); i != devices.end(); ++i)
{
addDeviceTo(viewer, *i);
}
}
std::string device;
while (arguments.read("--device", device))
{
addDeviceTo(viewer, device);
}
if (arguments.read("--http-control"))
{
std::string server_address = "localhost";
std::string server_port = "8080";
std::string document_root = "htdocs";
while (arguments.read("--http-server-address", server_address)) {}
while (arguments.read("--http-server-port", server_port)) {}
while (arguments.read("--http-document-root", document_root)) {}
osg::ref_ptr<osgDB::Options> device_options = new osgDB::Options("documentRegisteredHandlers");
osg::ref_ptr<osgGA::Device> rest_http_device = osgDB::readFile<osgGA::Device>(server_address+":"+server_port+"/"+document_root+".resthttp", device_options.get());
if (rest_http_device.valid())
{
viewer.addDevice(rest_http_device.get());
}
}
// set up stereo masks
viewer.getCamera()->setCullMaskLeft(0x00000001);
viewer.getCamera()->setCullMaskRight(0x00000002);
bool assignLeftCullMaskForMono = true;
if (assignLeftCullMaskForMono)
{
viewer.getCamera()->setCullMask(viewer.getCamera()->getCullMaskLeft());
}
else
{
viewer.getCamera()->setCullMask(0xffffffff);
}
// set up the camera manipulators.
{
osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
std::string pathfile;
char keyForAnimationPath = '5';
while (arguments.read("-p",pathfile))
{
osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
if (apm || !apm->valid())
{
unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
keyswitchManipulator->selectMatrixManipulator(num);
++keyForAnimationPath;
}
}
viewer.setCameraManipulator( keyswitchManipulator.get() );
}
// add the state manipulator
osg::ref_ptr<osgGA::StateSetManipulator> ssManipulator = new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet());
ssManipulator->setKeyEventToggleTexturing('e');
viewer.addEventHandler( ssManipulator.get() );
// add the state manipulator
viewer.addEventHandler( new osgViewer::StatsHandler() );
viewer.addEventHandler( new osgViewer::WindowSizeHandler() );
// neeed to address.
// viewer.getScene()->getUpdateVisitor()->setTraversalMode(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN);
const char* p3dCursor = getenv("P3D_CURSOR");
std::string cursorFileName( p3dCursor ? p3dCursor : "");
while (arguments.read("--cursor",cursorFileName)) {}
const char* p3dShowCursor = getenv("P3D_SHOW_CURSOR");
std::string showCursor( p3dShowCursor ? p3dShowCursor : "YES");
while (arguments.read("--show-cursor")) { showCursor="YES"; }
while (arguments.read("--hide-cursor")) { showCursor="NO"; }
bool hideCursor = (showCursor=="No" || showCursor=="NO" || showCursor=="no");
while (arguments.read("--set-viewer")) { doSetViewer = true; }
while (arguments.read("--no-set-viewer")) { doSetViewer = false; }
// if we want to hide the cursor override the custom cursor.
if (hideCursor) cursorFileName.clear();
// cluster related entries.
int socketNumber=8100;
while (arguments.read("-n",socketNumber)) {}
float camera_fov=-1.0f;
while (arguments.read("-f",camera_fov)) {}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) {}
std::string exportName;
while (arguments.read("--print",exportName)) {}
while (arguments.read("--html",exportName)) {}
// read any time delay argument.
float timeDelayBetweenSlides = 1.0f;
while (arguments.read("-d",timeDelayBetweenSlides)) {}
bool autoSteppingActive = false;
while (arguments.read("-a")) autoSteppingActive = true;
bool loopPresentation = false;
while (arguments.read("--loop")) loopPresentation = true;
{
// set update hte default traversal mode settings for update visitor
// default to osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN.
osg::NodeVisitor::TraversalMode updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN; // viewer.getUpdateVisitor()->getTraversalMode();
const char* p3dUpdateStr = getenv("P3D_UPDATE");
if (p3dUpdateStr)
{
std::string updateStr(p3dUpdateStr);
if (updateStr=="active" || updateStr=="Active" || updateStr=="ACTIVE") updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN;
else if (updateStr=="all" || updateStr=="All" || updateStr=="ALL") updateTraversalMode = osg::NodeVisitor::TRAVERSE_ALL_CHILDREN;
}
while(arguments.read("--update-active")) updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN;
while(arguments.read("--update-all")) updateTraversalMode = osg::NodeVisitor::TRAVERSE_ALL_CHILDREN;
viewer.getUpdateVisitor()->setTraversalMode(updateTraversalMode);
}
// register the slide event handler - which moves the presentation from slide to slide, layer to layer.
osg::ref_ptr<osgPresentation::SlideEventHandler> seh = new osgPresentation::SlideEventHandler(&viewer);
viewer.addEventHandler(seh.get());
seh->setAutoSteppingActive(autoSteppingActive);
seh->setTimeDelayBetweenSlides(timeDelayBetweenSlides);
seh->setLoopPresentation(loopPresentation);
double targetFrameRate = 80.0;
while (arguments.read("--targetFrameRate",targetFrameRate)) {}
// set the time delay
float timeDelayOnNewSlideWithMovies = 0.4f;
while (arguments.read("--timeDelayOnNewSlideWithMovies",timeDelayOnNewSlideWithMovies)) {}
seh->setTimeDelayOnNewSlideWithMovies(timeDelayOnNewSlideWithMovies);
// set up optimizer options
unsigned int optimizer_options = osgUtil::Optimizer::DEFAULT_OPTIMIZATIONS;
bool relase_and_compile = false;
while (arguments.read("--release-and-compile"))
{
relase_and_compile = true;
}
seh->setReleaseAndCompileOnEachNewSlide(relase_and_compile);
if (relase_and_compile)
{
// make sure that imagery stays around after being applied to textures.
viewer.getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
}
//
// osgDB::Registry::instance()->getOrCreateDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
// optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
// osg::Texture::getTextureObjectManager()->setExpiryDelay(0.0f);
// osgDB::Registry::instance()->getOrCreateDatabasePager()->setExpiryDelay(1.0f);
// register the handler for modifying the point size
osg::ref_ptr<PointsEventHandler> peh = new PointsEventHandler;
viewer.addEventHandler(peh.get());
// add the screen capture handler
std::string screenCaptureFilename = "screen_shot.jpg";
while(arguments.read("--screenshot", screenCaptureFilename)) {}
osg::ref_ptr<osgViewer::ScreenCaptureHandler::WriteToFile> writeFile = new osgViewer::ScreenCaptureHandler::WriteToFile(
osgDB::getNameLessExtension(screenCaptureFilename),
osgDB::getFileExtension(screenCaptureFilename) );
osg::ref_ptr<osgViewer::ScreenCaptureHandler> screenCaptureHandler = new osgViewer::ScreenCaptureHandler(writeFile.get());
screenCaptureHandler->setKeyEventTakeScreenShot('m');//osgGA::GUIEventAdapter::KEY_Print);
screenCaptureHandler->setKeyEventToggleContinuousCapture('M');
viewer.addEventHandler(screenCaptureHandler.get());
// osg::DisplaySettings::instance()->setSplitStereoAutoAjustAspectRatio(false);
float width = osg::DisplaySettings::instance()->getScreenWidth();
float height = osg::DisplaySettings::instance()->getScreenHeight();
float distance = osg::DisplaySettings::instance()->getScreenDistance();
while (arguments.read("-s", width, height, distance))
{
osg::DisplaySettings::instance()->setScreenDistance(distance);
osg::DisplaySettings::instance()->setScreenHeight(height);
osg::DisplaySettings::instance()->setScreenWidth(width);
}
std::string outputFileName;
while(arguments.read("--output",outputFileName)) {}
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(osg::notify(osg::NOTICE));
return 1;
}
P3DApplicationType P3DApplicationType = VIEWER;
str = getenv("PRESENT3D_TYPE");
if (str)
{
if (strcmp(str,"viewer")==0) P3DApplicationType = VIEWER;
else if (strcmp(str,"master")==0) P3DApplicationType = MASTER;
else if (strcmp(str,"slave")==0) P3DApplicationType = SLAVE;
}
while (arguments.read("--viewer")) { P3DApplicationType = VIEWER; }
while (arguments.read("--master")) { P3DApplicationType = MASTER; }
while (arguments.read("--slave")) { P3DApplicationType = SLAVE; }
while (arguments.read("--version"))
{
std::string appTypeName = "invalid";
switch(P3DApplicationType)
{
case(VIEWER): appTypeName = "viewer"; break;
case(MASTER): appTypeName = "master"; break;
case(SLAVE): appTypeName = "slave"; break;
}
osg::notify(osg::NOTICE)<<std::endl;
osg::notify(osg::NOTICE)<<"Present3D "<<appTypeName<<" version : "<<s_version<<std::endl;
osg::notify(osg::NOTICE)<<std::endl;
return 0;
}
// any option left unread are converted into errors to write out later.
//arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have ocured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(osg::notify(osg::INFO));
return 1;
}
// read files name from arguments.
p3d::FileNameList xmlFiles, normalFiles;
if (!p3d::getFileNames(arguments, xmlFiles, normalFiles))
{
osg::notify(osg::NOTICE)<<std::endl;
osg::notify(osg::NOTICE)<<"No file specified, please specify and file to load."<<std::endl;
osg::notify(osg::NOTICE)<<std::endl;
return 1;
}
bool viewerInitialized = false;
if (!xmlFiles.empty())
{
osg::ref_ptr<osg::Node> holdingModel = p3d::readHoldingSlide(xmlFiles.front());
if (holdingModel.valid())
{
viewer.setSceneData(holdingModel.get());
seh->selectSlide(0);
if (!viewerInitialized)
{
// pass the global stateset to the point event handler so that it can
// alter the point size of all points in the scene.
peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());
// create the windows and run the threads.
viewer.realize();
if (doSetViewer) setViewer(viewer, width, height, distance);
viewerInitialized = true;
}
seh->home();
// render a frame
viewer.frame();
}
}
osg::Timer timer;
osg::Timer_t start_tick = timer.tick();
osg::ref_ptr<osgDB::ReaderWriter::Options> cacheAllOption = new osgDB::ReaderWriter::Options;
cacheAllOption->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL);
osgDB::Registry::instance()->setOptions(cacheAllOption.get());
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> loadedModel = p3d::readShowFiles(arguments,cacheAllOption.get()); // osgDB::readNodeFiles(arguments, cacheAllOption.get());
osgDB::Registry::instance()->setOptions( 0 );
// if no model has been successfully loaded report failure.
if (!loadedModel)
{
osg::notify(osg::INFO) << arguments.getApplicationName() <<": No data loaded" << std::endl;
return 1;
}
osg::Timer_t end_tick = timer.tick();
osg::notify(osg::INFO) << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
if (loadedModel->getNumDescriptions()>0)
{
for(unsigned int i=0; i<loadedModel->getNumDescriptions(); ++i)
{
const std::string& desc = loadedModel->getDescription(i);
if (desc=="loop")
{
osg::notify(osg::NOTICE)<<"Enabling looping"<<std::endl;
seh->setLoopPresentation(true);
}
else if (desc=="auto")
{
osg::notify(osg::NOTICE)<<"Enabling auto run"<<std::endl;
seh->setAutoSteppingActive(true);
}
}
}
processLoadedModel(loadedModel, optimizer_options, cursorFileName);
// set the scene to render
viewer.setSceneData(loadedModel.get());
if (!viewerInitialized)
{
// pass the global stateset to the point event handler so that it can
// alter the point size of all points in the scene.
peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());
// create the windows and run the threads.
viewer.realize();
if (doSetViewer) setViewer(viewer, width, height, distance);
viewerInitialized = true;
}
// pass the model to the slide event handler so it knows which to manipulate.
seh->set(loadedModel.get());
seh->selectSlide(0);
seh->home();
if (!outputFileName.empty())
{
osgDB::writeNodeFile(*loadedModel,outputFileName);
return 0;
}
if (!cursorFileName.empty() || hideCursor)
{
// have to add a frame in here to avoid problems with X11 threading issue on switching off the cursor
// not yet sure why it makes a difference, but it at least fixes the crash that would otherwise occur
// under X11.
viewer.frame();
// switch off the cursor
osgViewer::Viewer::Windows windows;
viewer.getWindows(windows);
for(osgViewer::Viewer::Windows::iterator itr = windows.begin();
itr != windows.end();
++itr)
{
(*itr)->useCursor(false);
}
}
osg::Timer_t startOfFrameTick = osg::Timer::instance()->tick();
double targetFrameTime = 1.0/targetFrameRate;
if (exportName.empty())
{
// objects for managing the broadcasting and recieving of camera packets.
CameraPacket cp;
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
DataConverter scratchPad(1024);
while( !viewer.done() && !masterKilled)
{
// wait for all cull and draw threads to complete.
viewer.advance();
osg::Timer_t currentTick = osg::Timer::instance()->tick();
double deltaTime = osg::Timer::instance()->delta_s(startOfFrameTick, currentTick);
if (deltaTime<targetFrameTime)
{
OpenThreads::Thread::microSleep(static_cast<unsigned int>((targetFrameTime-deltaTime)*1000000.0));
}
startOfFrameTick = osg::Timer::instance()->tick();
#if 0
if (kmcb)
{
double time = kmcb->getTime();
viewer.getFrameStamp()->setReferenceTime(time);
}
#endif
#ifdef USE_SDL
sdlIntegration.update(viewer);
#endif
if (P3DApplicationType==MASTER)
{
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCamera()->getViewMatrix());
cp.setPacket(modelview,viewer.getFrameStamp());
// cp.readEventQueue(viewer);
scratchPad.reset();
scratchPad.write(cp);
scratchPad.reset();
scratchPad.read(cp);
bc.setBuffer(scratchPad.startPtr(), scratchPad.numBytes());
std::cout << "bc.sync()"<<scratchPad.numBytes()<<std::endl;
bc.sync();
}
else if (P3DApplicationType==SLAVE)
{
rc.setBuffer(scratchPad.startPtr(), scratchPad.numBytes());
rc.sync();
scratchPad.reset();
scratchPad.read(cp);
// cp.writeEventQueue(viewer);
if (cp.getMasterKilled())
{
std::cout << "Received master killed."<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.eventTraversal();
if (seh->getRequestReload())
{
OSG_INFO<<"Reload requested"<<std::endl;
seh->setRequestReload(false);
int previous_ActiveSlide = seh->getActiveSlide();
int previous_ActiveLayer = seh->getActiveLayer();
// reset time so any event key generate
loadedModel = p3d::readShowFiles(arguments,cacheAllOption.get());
processLoadedModel(loadedModel, optimizer_options, cursorFileName);
if (!loadedModel)
{
return 0;
}
viewer.setSceneData(loadedModel.get());
seh->set(loadedModel.get());
seh->selectSlide(previous_ActiveSlide, previous_ActiveLayer);
continue;
}
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.updateTraversal();
if (P3DApplicationType==SLAVE)
{
osg::Matrix modelview;
cp.getModelView(modelview,camera_offset);
viewer.getCamera()->setViewMatrix(modelview);
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.renderingTraversals();
}
}
else
{
ExportHTML::write(seh.get(), viewer, exportName);
}
return 0;
}
From Stephan Huber, "attached you’ll find a small enhancement for present3d. Now you can get advanced help via —help-all etc (similar to osgviewer)"
/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield
*
* This software is open source and may be redistributed and/or modified under
* the terms of the GNU General Public License (GPL) version 2.0.
* The full license is in LICENSE.txt file included with this distribution,.
*
* This software 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
* include LICENSE.txt for more details.
*/
#include <osg/Geometry>
#include <osg/Texture2D>
#include <osg/AutoTransform>
#include <osg/Notify>
#include <osg/io_utils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileNameUtils>
#include <osgUtil/Optimizer>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <OpenThreads/Thread>
#include <osgGA/GUIEventHandler>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/StateSetManipulator>
#include <osgPresentation/deprecated/SlideEventHandler>
#include <osgPresentation/Cursor>
#include "ReadShowFile.h"
#include "PointsEventHandler.h"
#include "Cluster.h"
#include "ExportHTML.h"
#include "SpellChecker.h"
#include <sstream>
#include <fstream>
#include <iostream>
#include <string.h>
#ifdef USE_SDL
#include "SDLIntegration.h"
#endif
#ifdef OSG_LIBRARY_STATIC
// include the plugins we need
USE_OSGPLUGIN(ive)
USE_OSGPLUGIN(osg)
USE_OSGPLUGIN(osg2)
USE_OSGPLUGIN(p3d)
USE_OSGPLUGIN(paths)
USE_OSGPLUGIN(rgb)
USE_OSGPLUGIN(OpenFlight)
USE_OSGPLUGIN(obj)
#ifdef USE_FREETYPE
USE_OSGPLUGIN(freetype)
#endif
#ifdef USE_PNG
USE_OSGPLUGIN(png)
#endif
#ifdef USE_JPEG
USE_OSGPLUGIN(jpeg)
#endif
#ifdef USE_FFMPEG
USE_OSGPLUGIN(ffmpeg)
#endif
#ifdef USE_POPPLER_CAIRO
USE_OSGPLUGIN(pdf)
#endif
#ifdef USE_CURL
USE_OSGPLUGIN(curl)
#endif
USE_DOTOSGWRAPPER_LIBRARY(osg)
USE_DOTOSGWRAPPER_LIBRARY(osgFX)
USE_DOTOSGWRAPPER_LIBRARY(osgParticle)
USE_DOTOSGWRAPPER_LIBRARY(osgShadow)
USE_DOTOSGWRAPPER_LIBRARY(osgSim)
USE_DOTOSGWRAPPER_LIBRARY(osgTerrain)
USE_DOTOSGWRAPPER_LIBRARY(osgText)
USE_DOTOSGWRAPPER_LIBRARY(osgViewer)
USE_DOTOSGWRAPPER_LIBRARY(osgVolume)
USE_DOTOSGWRAPPER_LIBRARY(osgWidget)
USE_SERIALIZER_WRAPPER_LIBRARY(osg)
USE_SERIALIZER_WRAPPER_LIBRARY(osgAnimation)
USE_SERIALIZER_WRAPPER_LIBRARY(osgFX)
USE_SERIALIZER_WRAPPER_LIBRARY(osgManipulator)
USE_SERIALIZER_WRAPPER_LIBRARY(osgParticle)
USE_SERIALIZER_WRAPPER_LIBRARY(osgShadow)
USE_SERIALIZER_WRAPPER_LIBRARY(osgSim)
USE_SERIALIZER_WRAPPER_LIBRARY(osgTerrain)
USE_SERIALIZER_WRAPPER_LIBRARY(osgText)
USE_SERIALIZER_WRAPPER_LIBRARY(osgVolume)
// include the platform specific GraphicsWindow implementation.
USE_GRAPHICSWINDOW()
#endif
static const char* s_version = "1.4 beta";
void setViewer(osgViewer::Viewer& viewer, float width, float height, float distance)
{
double vfov = osg::RadiansToDegrees(atan2(height/2.0f,distance)*2.0);
// double hfov = osg::RadiansToDegrees(atan2(width/2.0f,distance)*2.0);
viewer.getCamera()->setProjectionMatrixAsPerspective( vfov, width/height, 0.1, 1000.0);
OSG_INFO<<"setProjectionMatrixAsPerspective( "<<vfov<<", "<<width/height<<", "<<0.1<<", "<<1000.0<<");"<<std::endl;
}
class ForwardToDeviceEventHandler : public osgGA::GUIEventHandler {
public:
ForwardToDeviceEventHandler(osgGA::Device* device) : osgGA::GUIEventHandler(), _device(device) {}
virtual bool handle (const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osg::Object *, osg::NodeVisitor *)
{
OSG_INFO<<"ForwardToDeviceEventHandler::setEvent("<<ea.getKey()<<")"<<std::endl;
_device->sendEvent(ea);
return false;
}
private:
osg::ref_ptr<osgGA::Device> _device;
};
enum P3DApplicationType
{
VIEWER,
MASTER,
SLAVE
};
void processLoadedModel(osg::ref_ptr<osg::Node>& loadedModel, int optimizer_options, const std::string& cursorFileName)
{
if (!loadedModel) return;
#if !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)
// add back in enabling of the GL_ALPHA_TEST to get around the core OSG no longer setting it by default for opaque bins.
// the alpha test is required for the volume rendering alpha clipping to work.
loadedModel->getOrCreateStateSet()->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
#endif
// optimize the scene graph, remove rendundent nodes and state etc.
osgUtil::Optimizer optimizer;
optimizer.optimize(loadedModel.get(), optimizer_options);
if (!cursorFileName.empty())
{
osg::ref_ptr<osg::Group> group = new osg::Group;
group->addChild(loadedModel.get());
OSG_NOTICE<<"Creating Cursor"<<std::endl;
group->addChild(new osgPresentation::Cursor(cursorFileName, 20.0f));
loadedModel = group;
}
}
void addDeviceTo(osgViewer::Viewer& viewer, const std::string& device_name)
{
osg::ref_ptr<osgGA::Device> dev = osgDB::readFile<osgGA::Device>(device_name);
if (dev.valid())
{
OSG_INFO << "Adding Device : " << device_name << std::endl;
viewer.addDevice(dev.get());
if (dev->getCapabilities() & osgGA::Device::SEND_EVENTS)
viewer.getEventHandlers().push_front(new ForwardToDeviceEventHandler(dev.get()));
}
else
{
OSG_WARN << "could not open device: " << device_name << std::endl;
}
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the application for presenting 3D interactive slide shows.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-a","Turn auto stepping on by default");
arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time duration in seconds between layers/slides");
arguments.getApplicationUsage()->addCommandLineOption("-s <float> <float> <float>","width, height, distance and of the screen away from the viewer");
arguments.getApplicationUsage()->addCommandLineOption("--viewer","Start Present3D as the viewer version.");
arguments.getApplicationUsage()->addCommandLineOption("--authoring","Start Present3D as the authoring version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--master","Start Present3D as the master version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--slave","Start Present3D as the slave version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--publishing","Start Present3D as the publishing version, license required.");
arguments.getApplicationUsage()->addCommandLineOption("--timeDelayOnNewSlideWithMovies","Set the time delay on new slide with movies, done to allow movie threads to get in sync with rendering thread.");
arguments.getApplicationUsage()->addCommandLineOption("--targetFrameRate","Set the target frame rate, defaults to 80Hz.");
arguments.getApplicationUsage()->addCommandLineOption("--version","Report the Present3D version.");
arguments.getApplicationUsage()->addCommandLineOption("--print <filename>","Print out slides to a series of image files.");
arguments.getApplicationUsage()->addCommandLineOption("--html <filename>","Print out slides to a series of html & image files.");
arguments.getApplicationUsage()->addCommandLineOption("--loop","Switch on looping of presentation.");
arguments.getApplicationUsage()->addCommandLineOption("--devices","Print the Video input capability via QuickTime and exit.");
// add alias from xml to p3d to provide backwards compatibility for old p3d files.
osgDB::Registry::instance()->addFileExtensionAlias("xml","p3d");
// if user requests devices video capability.
if (arguments.read("-devices") || arguments.read("--devices"))
{
// Force load QuickTime plugin, probe video capability, exit
osgDB::readImageFile("devices.live");
return 1;
}
// read any env vars from presentations before we create viewer to make sure the viewer
// utilises these env vars
if (p3d::readEnvVars(arguments))
{
osg::DisplaySettings::instance()->readEnvironmentalVariables();
}
// set up any logins required for http access
std::string url, username, password;
while(arguments.read("--login",url, username, password))
{
if (!osgDB::Registry::instance()->getAuthenticationMap())
{
osgDB::Registry::instance()->setAuthenticationMap(new osgDB::AuthenticationMap);
osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails(
url,
new osgDB::AuthenticationDetails(username, password)
);
}
}
#ifdef USE_SDL
SDLIntegration sdlIntegration;
osg::notify(osg::INFO)<<"USE_SDL"<<std::endl;
#endif
bool doSetViewer = true;
std::string configurationFile;
// check env vars for configuration file
const char* str = getenv("PRESENT3D_CONFIG_FILE");
if (!str) str = getenv("OSG_CONFIG_FILE");
if (str) configurationFile = str;
// check command line parameters for configuration file.
while (arguments.read("-c",configurationFile)) {}
osg::Vec4 clearColor(0.0f,0.0f,0.0f,0.0f);
while (arguments.read("--clear-color",clearColor[0],clearColor[1],clearColor[2],clearColor[3])) {}
std::string filename;
if (arguments.read("--spell-check",filename))
{
p3d::SpellChecker spellChecker;
spellChecker.checkP3dXml(filename);
return 1;
}
if (arguments.read("--strip-text",filename))
{
p3d::XmlPatcher patcher;
// patcher.stripP3dXml(filename, osg::notify(osg::NOTICE));
osg::ref_ptr<osgDB::XmlNode> newNode = patcher.simplifyP3dXml(filename);
if (newNode.valid())
{
newNode->write(std::cout);
}
return 1;
}
std::string lhs_filename, rhs_filename;
if (arguments.read("--merge",lhs_filename, rhs_filename))
{
p3d::XmlPatcher patcher;
osg::ref_ptr<osgDB::XmlNode> newNode = patcher.mergeP3dXml(lhs_filename, rhs_filename);
if (newNode.valid())
{
newNode->write(std::cout);
}
return 1;
}
// construct the viewer.
osgViewer::Viewer viewer(arguments);
// set clear colour to black by default.
viewer.getCamera()->setClearColor(clearColor);
if (!configurationFile.empty())
{
viewer.readConfiguration(configurationFile);
doSetViewer = false;
}
const char* p3dDevice = getenv("P3D_DEVICE");
if (p3dDevice)
{
osgDB::StringList devices;
osgDB::split(p3dDevice, devices);
for(osgDB::StringList::iterator i = devices.begin(); i != devices.end(); ++i)
{
addDeviceTo(viewer, *i);
}
}
std::string device;
while (arguments.read("--device", device))
{
addDeviceTo(viewer, device);
}
if (arguments.read("--http-control"))
{
std::string server_address = "localhost";
std::string server_port = "8080";
std::string document_root = "htdocs";
while (arguments.read("--http-server-address", server_address)) {}
while (arguments.read("--http-server-port", server_port)) {}
while (arguments.read("--http-document-root", document_root)) {}
osg::ref_ptr<osgDB::Options> device_options = new osgDB::Options("documentRegisteredHandlers");
osg::ref_ptr<osgGA::Device> rest_http_device = osgDB::readFile<osgGA::Device>(server_address+":"+server_port+"/"+document_root+".resthttp", device_options.get());
if (rest_http_device.valid())
{
viewer.addDevice(rest_http_device.get());
}
}
// set up stereo masks
viewer.getCamera()->setCullMaskLeft(0x00000001);
viewer.getCamera()->setCullMaskRight(0x00000002);
bool assignLeftCullMaskForMono = true;
if (assignLeftCullMaskForMono)
{
viewer.getCamera()->setCullMask(viewer.getCamera()->getCullMaskLeft());
}
else
{
viewer.getCamera()->setCullMask(0xffffffff);
}
// set up the camera manipulators.
{
osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
std::string pathfile;
char keyForAnimationPath = '5';
while (arguments.read("-p",pathfile))
{
osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
if (apm || !apm->valid())
{
unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
keyswitchManipulator->selectMatrixManipulator(num);
++keyForAnimationPath;
}
}
viewer.setCameraManipulator( keyswitchManipulator.get() );
}
// add the state manipulator
osg::ref_ptr<osgGA::StateSetManipulator> ssManipulator = new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet());
ssManipulator->setKeyEventToggleTexturing('e');
viewer.addEventHandler( ssManipulator.get() );
// add the state manipulator
viewer.addEventHandler( new osgViewer::StatsHandler() );
viewer.addEventHandler( new osgViewer::WindowSizeHandler() );
// neeed to address.
// viewer.getScene()->getUpdateVisitor()->setTraversalMode(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN);
const char* p3dCursor = getenv("P3D_CURSOR");
std::string cursorFileName( p3dCursor ? p3dCursor : "");
while (arguments.read("--cursor",cursorFileName)) {}
const char* p3dShowCursor = getenv("P3D_SHOW_CURSOR");
std::string showCursor( p3dShowCursor ? p3dShowCursor : "YES");
while (arguments.read("--show-cursor")) { showCursor="YES"; }
while (arguments.read("--hide-cursor")) { showCursor="NO"; }
bool hideCursor = (showCursor=="No" || showCursor=="NO" || showCursor=="no");
while (arguments.read("--set-viewer")) { doSetViewer = true; }
while (arguments.read("--no-set-viewer")) { doSetViewer = false; }
// if we want to hide the cursor override the custom cursor.
if (hideCursor) cursorFileName.clear();
// cluster related entries.
int socketNumber=8100;
while (arguments.read("-n",socketNumber)) {}
float camera_fov=-1.0f;
while (arguments.read("-f",camera_fov)) {}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) {}
std::string exportName;
while (arguments.read("--print",exportName)) {}
while (arguments.read("--html",exportName)) {}
// read any time delay argument.
float timeDelayBetweenSlides = 1.0f;
while (arguments.read("-d",timeDelayBetweenSlides)) {}
bool autoSteppingActive = false;
while (arguments.read("-a")) autoSteppingActive = true;
bool loopPresentation = false;
while (arguments.read("--loop")) loopPresentation = true;
{
// set update hte default traversal mode settings for update visitor
// default to osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN.
osg::NodeVisitor::TraversalMode updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN; // viewer.getUpdateVisitor()->getTraversalMode();
const char* p3dUpdateStr = getenv("P3D_UPDATE");
if (p3dUpdateStr)
{
std::string updateStr(p3dUpdateStr);
if (updateStr=="active" || updateStr=="Active" || updateStr=="ACTIVE") updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN;
else if (updateStr=="all" || updateStr=="All" || updateStr=="ALL") updateTraversalMode = osg::NodeVisitor::TRAVERSE_ALL_CHILDREN;
}
while(arguments.read("--update-active")) updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN;
while(arguments.read("--update-all")) updateTraversalMode = osg::NodeVisitor::TRAVERSE_ALL_CHILDREN;
viewer.getUpdateVisitor()->setTraversalMode(updateTraversalMode);
}
// register the slide event handler - which moves the presentation from slide to slide, layer to layer.
osg::ref_ptr<osgPresentation::SlideEventHandler> seh = new osgPresentation::SlideEventHandler(&viewer);
viewer.addEventHandler(seh.get());
seh->setAutoSteppingActive(autoSteppingActive);
seh->setTimeDelayBetweenSlides(timeDelayBetweenSlides);
seh->setLoopPresentation(loopPresentation);
double targetFrameRate = 80.0;
while (arguments.read("--targetFrameRate",targetFrameRate)) {}
// set the time delay
float timeDelayOnNewSlideWithMovies = 0.4f;
while (arguments.read("--timeDelayOnNewSlideWithMovies",timeDelayOnNewSlideWithMovies)) {}
seh->setTimeDelayOnNewSlideWithMovies(timeDelayOnNewSlideWithMovies);
// set up optimizer options
unsigned int optimizer_options = osgUtil::Optimizer::DEFAULT_OPTIMIZATIONS;
bool relase_and_compile = false;
while (arguments.read("--release-and-compile"))
{
relase_and_compile = true;
}
seh->setReleaseAndCompileOnEachNewSlide(relase_and_compile);
if (relase_and_compile)
{
// make sure that imagery stays around after being applied to textures.
viewer.getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
}
//
// osgDB::Registry::instance()->getOrCreateDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
// optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
// osg::Texture::getTextureObjectManager()->setExpiryDelay(0.0f);
// osgDB::Registry::instance()->getOrCreateDatabasePager()->setExpiryDelay(1.0f);
// register the handler for modifying the point size
osg::ref_ptr<PointsEventHandler> peh = new PointsEventHandler;
viewer.addEventHandler(peh.get());
// add the screen capture handler
std::string screenCaptureFilename = "screen_shot.jpg";
while(arguments.read("--screenshot", screenCaptureFilename)) {}
osg::ref_ptr<osgViewer::ScreenCaptureHandler::WriteToFile> writeFile = new osgViewer::ScreenCaptureHandler::WriteToFile(
osgDB::getNameLessExtension(screenCaptureFilename),
osgDB::getFileExtension(screenCaptureFilename) );
osg::ref_ptr<osgViewer::ScreenCaptureHandler> screenCaptureHandler = new osgViewer::ScreenCaptureHandler(writeFile.get());
screenCaptureHandler->setKeyEventTakeScreenShot('m');//osgGA::GUIEventAdapter::KEY_Print);
screenCaptureHandler->setKeyEventToggleContinuousCapture('M');
viewer.addEventHandler(screenCaptureHandler.get());
// osg::DisplaySettings::instance()->setSplitStereoAutoAjustAspectRatio(false);
float width = osg::DisplaySettings::instance()->getScreenWidth();
float height = osg::DisplaySettings::instance()->getScreenHeight();
float distance = osg::DisplaySettings::instance()->getScreenDistance();
while (arguments.read("-s", width, height, distance))
{
osg::DisplaySettings::instance()->setScreenDistance(distance);
osg::DisplaySettings::instance()->setScreenHeight(height);
osg::DisplaySettings::instance()->setScreenWidth(width);
}
std::string outputFileName;
while(arguments.read("--output",outputFileName)) {}
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
unsigned int helpType = 0;
if ((helpType = arguments.readHelpType()))
{
arguments.getApplicationUsage()->write(std::cout, helpType);
return 1;
}
P3DApplicationType P3DApplicationType = VIEWER;
str = getenv("PRESENT3D_TYPE");
if (str)
{
if (strcmp(str,"viewer")==0) P3DApplicationType = VIEWER;
else if (strcmp(str,"master")==0) P3DApplicationType = MASTER;
else if (strcmp(str,"slave")==0) P3DApplicationType = SLAVE;
}
while (arguments.read("--viewer")) { P3DApplicationType = VIEWER; }
while (arguments.read("--master")) { P3DApplicationType = MASTER; }
while (arguments.read("--slave")) { P3DApplicationType = SLAVE; }
while (arguments.read("--version"))
{
std::string appTypeName = "invalid";
switch(P3DApplicationType)
{
case(VIEWER): appTypeName = "viewer"; break;
case(MASTER): appTypeName = "master"; break;
case(SLAVE): appTypeName = "slave"; break;
}
osg::notify(osg::NOTICE)<<std::endl;
osg::notify(osg::NOTICE)<<"Present3D "<<appTypeName<<" version : "<<s_version<<std::endl;
osg::notify(osg::NOTICE)<<std::endl;
return 0;
}
// any option left unread are converted into errors to write out later.
//arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have ocured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(osg::notify(osg::INFO));
return 1;
}
// read files name from arguments.
p3d::FileNameList xmlFiles, normalFiles;
if (!p3d::getFileNames(arguments, xmlFiles, normalFiles))
{
osg::notify(osg::NOTICE)<<std::endl;
osg::notify(osg::NOTICE)<<"No file specified, please specify and file to load."<<std::endl;
osg::notify(osg::NOTICE)<<std::endl;
return 1;
}
bool viewerInitialized = false;
if (!xmlFiles.empty())
{
osg::ref_ptr<osg::Node> holdingModel = p3d::readHoldingSlide(xmlFiles.front());
if (holdingModel.valid())
{
viewer.setSceneData(holdingModel.get());
seh->selectSlide(0);
if (!viewerInitialized)
{
// pass the global stateset to the point event handler so that it can
// alter the point size of all points in the scene.
peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());
// create the windows and run the threads.
viewer.realize();
if (doSetViewer) setViewer(viewer, width, height, distance);
viewerInitialized = true;
}
seh->home();
// render a frame
viewer.frame();
}
}
osg::Timer timer;
osg::Timer_t start_tick = timer.tick();
osg::ref_ptr<osgDB::ReaderWriter::Options> cacheAllOption = new osgDB::ReaderWriter::Options;
cacheAllOption->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL);
osgDB::Registry::instance()->setOptions(cacheAllOption.get());
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> loadedModel = p3d::readShowFiles(arguments,cacheAllOption.get()); // osgDB::readNodeFiles(arguments, cacheAllOption.get());
osgDB::Registry::instance()->setOptions( 0 );
// if no model has been successfully loaded report failure.
if (!loadedModel)
{
osg::notify(osg::INFO) << arguments.getApplicationName() <<": No data loaded" << std::endl;
return 1;
}
osg::Timer_t end_tick = timer.tick();
osg::notify(osg::INFO) << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
if (loadedModel->getNumDescriptions()>0)
{
for(unsigned int i=0; i<loadedModel->getNumDescriptions(); ++i)
{
const std::string& desc = loadedModel->getDescription(i);
if (desc=="loop")
{
osg::notify(osg::NOTICE)<<"Enabling looping"<<std::endl;
seh->setLoopPresentation(true);
}
else if (desc=="auto")
{
osg::notify(osg::NOTICE)<<"Enabling auto run"<<std::endl;
seh->setAutoSteppingActive(true);
}
}
}
processLoadedModel(loadedModel, optimizer_options, cursorFileName);
// set the scene to render
viewer.setSceneData(loadedModel.get());
if (!viewerInitialized)
{
// pass the global stateset to the point event handler so that it can
// alter the point size of all points in the scene.
peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());
// create the windows and run the threads.
viewer.realize();
if (doSetViewer) setViewer(viewer, width, height, distance);
viewerInitialized = true;
}
// pass the model to the slide event handler so it knows which to manipulate.
seh->set(loadedModel.get());
seh->selectSlide(0);
seh->home();
if (!outputFileName.empty())
{
osgDB::writeNodeFile(*loadedModel,outputFileName);
return 0;
}
if (!cursorFileName.empty() || hideCursor)
{
// have to add a frame in here to avoid problems with X11 threading issue on switching off the cursor
// not yet sure why it makes a difference, but it at least fixes the crash that would otherwise occur
// under X11.
viewer.frame();
// switch off the cursor
osgViewer::Viewer::Windows windows;
viewer.getWindows(windows);
for(osgViewer::Viewer::Windows::iterator itr = windows.begin();
itr != windows.end();
++itr)
{
(*itr)->useCursor(false);
}
}
osg::Timer_t startOfFrameTick = osg::Timer::instance()->tick();
double targetFrameTime = 1.0/targetFrameRate;
if (exportName.empty())
{
// objects for managing the broadcasting and recieving of camera packets.
CameraPacket cp;
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
DataConverter scratchPad(1024);
while( !viewer.done() && !masterKilled)
{
// wait for all cull and draw threads to complete.
viewer.advance();
osg::Timer_t currentTick = osg::Timer::instance()->tick();
double deltaTime = osg::Timer::instance()->delta_s(startOfFrameTick, currentTick);
if (deltaTime<targetFrameTime)
{
OpenThreads::Thread::microSleep(static_cast<unsigned int>((targetFrameTime-deltaTime)*1000000.0));
}
startOfFrameTick = osg::Timer::instance()->tick();
#if 0
if (kmcb)
{
double time = kmcb->getTime();
viewer.getFrameStamp()->setReferenceTime(time);
}
#endif
#ifdef USE_SDL
sdlIntegration.update(viewer);
#endif
if (P3DApplicationType==MASTER)
{
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCamera()->getViewMatrix());
cp.setPacket(modelview,viewer.getFrameStamp());
// cp.readEventQueue(viewer);
scratchPad.reset();
scratchPad.write(cp);
scratchPad.reset();
scratchPad.read(cp);
bc.setBuffer(scratchPad.startPtr(), scratchPad.numBytes());
std::cout << "bc.sync()"<<scratchPad.numBytes()<<std::endl;
bc.sync();
}
else if (P3DApplicationType==SLAVE)
{
rc.setBuffer(scratchPad.startPtr(), scratchPad.numBytes());
rc.sync();
scratchPad.reset();
scratchPad.read(cp);
// cp.writeEventQueue(viewer);
if (cp.getMasterKilled())
{
std::cout << "Received master killed."<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.eventTraversal();
if (seh->getRequestReload())
{
OSG_INFO<<"Reload requested"<<std::endl;
seh->setRequestReload(false);
int previous_ActiveSlide = seh->getActiveSlide();
int previous_ActiveLayer = seh->getActiveLayer();
// reset time so any event key generate
loadedModel = p3d::readShowFiles(arguments,cacheAllOption.get());
processLoadedModel(loadedModel, optimizer_options, cursorFileName);
if (!loadedModel)
{
return 0;
}
viewer.setSceneData(loadedModel.get());
seh->set(loadedModel.get());
seh->selectSlide(previous_ActiveSlide, previous_ActiveLayer);
continue;
}
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.updateTraversal();
if (P3DApplicationType==SLAVE)
{
osg::Matrix modelview;
cp.getModelView(modelview,camera_offset);
viewer.getCamera()->setViewMatrix(modelview);
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.renderingTraversals();
}
}
else
{
ExportHTML::write(seh.get(), viewer, exportName);
}
return 0;
}
|
//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This tablegen backend emits code for use by the GlobalISel instruction
/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
///
/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
/// backend, filters out the ones that are unsupported, maps
/// SelectionDAG-specific constructs to their GlobalISel counterpart
/// (when applicable: MVT to LLT; SDNode to generic Instruction).
///
/// Not all patterns are supported: pass the tablegen invocation
/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
/// as well as why.
///
/// The generated file defines a single method:
/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
/// intended to be used in InstructionSelector::select as the first-step
/// selector for the patterns that don't require complex C++.
///
/// FIXME: We'll probably want to eventually define a base
/// "TargetGenInstructionSelector" class.
///
//===----------------------------------------------------------------------===//
#include "CodeGenDAGPatterns.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineValueType.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Error.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <string>
using namespace llvm;
#define DEBUG_TYPE "gisel-emitter"
STATISTIC(NumPatternTotal, "Total number of patterns");
STATISTIC(NumPatternSkipped, "Number of patterns skipped");
STATISTIC(NumPatternEmitted, "Number of patterns emitted");
static cl::opt<bool> WarnOnSkippedPatterns(
"warn-on-skipped-patterns",
cl::desc("Explain why a pattern was skipped for inclusion "
"in the GlobalISel selector"),
cl::init(false));
namespace {
class RuleMatcher;
//===- Helper functions ---------------------------------------------------===//
/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
static Optional<std::string> MVTToLLT(MVT::SimpleValueType SVT) {
std::string TyStr;
raw_string_ostream OS(TyStr);
MVT VT(SVT);
if (VT.isVector() && VT.getVectorNumElements() != 1) {
OS << "LLT::vector(" << VT.getVectorNumElements() << ", "
<< VT.getScalarSizeInBits() << ")";
} else if (VT.isInteger() || VT.isFloatingPoint()) {
OS << "LLT::scalar(" << VT.getSizeInBits() << ")";
} else {
return None;
}
OS.flush();
return TyStr;
}
static bool isTrivialOperatorNode(const TreePatternNode *N) {
return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
}
//===- Matchers -----------------------------------------------------------===//
template <class PredicateTy> class PredicateListMatcher {
private:
typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
PredicateVec Predicates;
public:
/// Construct a new operand predicate and add it to the matcher.
template <class Kind, class... Args>
Kind &addPredicate(Args&&... args) {
Predicates.emplace_back(
llvm::make_unique<Kind>(std::forward<Args>(args)...));
return *static_cast<Kind *>(Predicates.back().get());
}
typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
iterator_range<typename PredicateVec::const_iterator> predicates() const {
return make_range(predicates_begin(), predicates_end());
}
/// Emit a C++ expression that tests whether all the predicates are met.
template <class... Args>
void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
if (Predicates.empty()) {
OS << "true";
return;
}
StringRef Separator = "";
for (const auto &Predicate : predicates()) {
OS << Separator << "(";
Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
OS << ")";
Separator = " &&\n";
}
}
};
/// Generates code to check a predicate of an operand.
///
/// Typical predicates include:
/// * Operand is a particular register.
/// * Operand is assigned a particular register bank.
/// * Operand is an MBB.
class OperandPredicateMatcher {
public:
virtual ~OperandPredicateMatcher() {}
/// Emit a C++ expression that checks the predicate for the OpIdx operand of
/// the instruction given in InsnVarName.
virtual void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const = 0;
};
/// Generates code to check that an operand is a particular LLT.
class LLTOperandMatcher : public OperandPredicateMatcher {
protected:
std::string Ty;
public:
LLTOperandMatcher(std::string Ty) : Ty(Ty) {}
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const override {
OS << "MRI.getType(" << InsnVarName << ".getOperand(" << OpIdx
<< ").getReg()) == (" << Ty << ")";
}
};
/// Generates code to check that an operand is in a particular register bank.
class RegisterBankOperandMatcher : public OperandPredicateMatcher {
protected:
const CodeGenRegisterClass &RC;
public:
RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) : RC(RC) {}
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const override {
OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
<< "RegClass) == RBI.getRegBank(" << InsnVarName << ".getOperand("
<< OpIdx << ").getReg(), MRI, TRI))";
}
};
/// Generates code to check that an operand is a basic block.
class MBBOperandMatcher : public OperandPredicateMatcher {
public:
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const override {
OS << InsnVarName << ".getOperand(" << OpIdx << ").isMBB()";
}
};
/// Generates code to check that a set of predicates match for a particular
/// operand.
class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
protected:
unsigned OpIdx;
public:
OperandMatcher(unsigned OpIdx) : OpIdx(OpIdx) {}
/// Emit a C++ expression that tests whether the instruction named in
/// InsnVarName matches all the predicate and all the operands.
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
OS << "(";
emitCxxPredicateListExpr(OS, InsnVarName, OpIdx);
OS << ")";
}
};
/// Generates code to check a predicate on an instruction.
///
/// Typical predicates include:
/// * The opcode of the instruction is a particular value.
/// * The nsw/nuw flag is/isn't set.
class InstructionPredicateMatcher {
public:
virtual ~InstructionPredicateMatcher() {}
/// Emit a C++ expression that tests whether the instruction named in
/// InsnVarName matches the predicate.
virtual void emitCxxPredicateExpr(raw_ostream &OS,
StringRef InsnVarName) const = 0;
};
/// Generates code to check the opcode of an instruction.
class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
protected:
const CodeGenInstruction *I;
public:
InstructionOpcodeMatcher(const CodeGenInstruction *I) : I(I) {}
void emitCxxPredicateExpr(raw_ostream &OS,
StringRef InsnVarName) const override {
OS << InsnVarName << ".getOpcode() == " << I->Namespace
<< "::" << I->TheDef->getName();
}
};
/// Generates code to check that a set of predicates and operands match for a
/// particular instruction.
///
/// Typical predicates include:
/// * Has a specific opcode.
/// * Has an nsw/nuw flag or doesn't.
class InstructionMatcher
: public PredicateListMatcher<InstructionPredicateMatcher> {
protected:
std::vector<OperandMatcher> Operands;
public:
/// Add an operand to the matcher.
OperandMatcher &addOperand(unsigned OpIdx) {
Operands.emplace_back(OpIdx);
return Operands.back();
}
/// Emit a C++ expression that tests whether the instruction named in
/// InsnVarName matches all the predicates and all the operands.
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
emitCxxPredicateListExpr(OS, InsnVarName);
for (const auto &Operand : Operands) {
OS << " &&\n(";
Operand.emitCxxPredicateExpr(OS, InsnVarName);
OS << ")";
}
}
};
//===- Actions ------------------------------------------------------------===//
/// An action taken when all Matcher predicates succeeded for a parent rule.
///
/// Typical actions include:
/// * Changing the opcode of an instruction.
/// * Adding an operand to an instruction.
class MatchAction {
public:
virtual ~MatchAction() {}
virtual void emitCxxActionStmts(raw_ostream &OS) const = 0;
};
/// Generates a comment describing the matched rule being acted upon.
class DebugCommentAction : public MatchAction {
private:
const PatternToMatch &P;
public:
DebugCommentAction(const PatternToMatch &P) : P(P) {}
virtual void emitCxxActionStmts(raw_ostream &OS) const {
OS << "// " << *P.getSrcPattern() << " => " << *P.getDstPattern();
}
};
/// Generates code to set the opcode (really, the MCInstrDesc) of a matched
/// instruction to a given Instruction.
class MutateOpcodeAction : public MatchAction {
private:
const CodeGenInstruction *I;
public:
MutateOpcodeAction(const CodeGenInstruction *I) : I(I) {}
virtual void emitCxxActionStmts(raw_ostream &OS) const {
OS << "I.setDesc(TII.get(" << I->Namespace << "::" << I->TheDef->getName()
<< "));";
}
};
/// Generates code to check that a match rule matches.
class RuleMatcher {
/// A list of matchers that all need to succeed for the current rule to match.
/// FIXME: This currently supports a single match position but could be
/// extended to support multiple positions to support div/rem fusion or
/// load-multiple instructions.
std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
/// A list of actions that need to be taken when all predicates in this rule
/// have succeeded.
std::vector<std::unique_ptr<MatchAction>> Actions;
public:
RuleMatcher() {}
InstructionMatcher &addInstructionMatcher() {
Matchers.emplace_back(new InstructionMatcher());
return *Matchers.back();
}
template <class Kind, class... Args>
Kind &addAction(Args&&... args) {
Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
return *static_cast<Kind *>(Actions.back().get());
}
void emit(raw_ostream &OS) {
if (Matchers.empty())
llvm_unreachable("Unexpected empty matcher!");
// The representation supports rules that require multiple roots such as:
// %ptr(p0) = ...
// %elt0(s32) = G_LOAD %ptr
// %1(p0) = G_ADD %ptr, 4
// %elt1(s32) = G_LOAD p0 %1
// which could be usefully folded into:
// %ptr(p0) = ...
// %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
// on some targets but we don't need to make use of that yet.
assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
OS << " if (";
Matchers.front()->emitCxxPredicateExpr(OS, "I");
OS << ") {\n";
for (const auto &MA : Actions) {
OS << " ";
MA->emitCxxActionStmts(OS);
OS << "\n";
}
OS << " constrainSelectedInstRegOperands(I, TII, TRI, RBI);\n";
OS << " return true;\n";
OS << " }\n\n";
}
};
//===- GlobalISelEmitter class --------------------------------------------===//
class GlobalISelEmitter {
public:
explicit GlobalISelEmitter(RecordKeeper &RK);
void run(raw_ostream &OS);
private:
const RecordKeeper &RK;
const CodeGenDAGPatterns CGP;
const CodeGenTarget &Target;
/// Keep track of the equivalence between SDNodes and Instruction.
/// This is defined using 'GINodeEquiv' in the target description.
DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
void gatherNodeEquivs();
const CodeGenInstruction *findNodeEquiv(Record *N);
/// Analyze pattern \p P, returning a matcher for it if possible.
/// Otherwise, return an Error explaining why we don't support it.
Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
};
void GlobalISelEmitter::gatherNodeEquivs() {
assert(NodeEquivs.empty());
for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
NodeEquivs[Equiv->getValueAsDef("Node")] =
&Target.getInstruction(Equiv->getValueAsDef("I"));
}
const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) {
return NodeEquivs.lookup(N);
}
GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
: RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
//===- Emitter ------------------------------------------------------------===//
/// Helper function to let the emitter report skip reason error messages.
static Error failedImport(const Twine &Reason) {
return make_error<StringError>(Reason, inconvertibleErrorCode());
}
Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
// Keep track of the matchers and actions to emit.
RuleMatcher M;
M.addAction<DebugCommentAction>(P);
// First, analyze the whole pattern.
// If the entire pattern has a predicate (e.g., target features), ignore it.
if (!P.getPredicates()->getValues().empty())
return failedImport("Pattern has a predicate");
// Physreg imp-defs require additional logic. Ignore the pattern.
if (!P.getDstRegs().empty())
return failedImport("Pattern defines a physical register");
// Next, analyze the pattern operators.
TreePatternNode *Src = P.getSrcPattern();
TreePatternNode *Dst = P.getDstPattern();
// If the root of either pattern isn't a simple operator, ignore it.
if (!isTrivialOperatorNode(Dst))
return failedImport("Dst pattern root isn't a trivial operator");
if (!isTrivialOperatorNode(Src))
return failedImport("Src pattern root isn't a trivial operator");
Record *DstOp = Dst->getOperator();
if (!DstOp->isSubClassOf("Instruction"))
return failedImport("Pattern operator isn't an instruction");
auto &DstI = Target.getInstruction(DstOp);
auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
if (!SrcGIOrNull)
return failedImport("Pattern operator lacks an equivalent Instruction");
auto &SrcGI = *SrcGIOrNull;
// The operators look good: match the opcode and mutate it to the new one.
InstructionMatcher &InsnMatcher = M.addInstructionMatcher();
InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
M.addAction<MutateOpcodeAction>(&DstI);
// Next, analyze the children, only accepting patterns that don't require
// any change to operands.
if (Src->getNumChildren() != Dst->getNumChildren())
return failedImport("Src/dst patterns have a different # of children");
unsigned OpIdx = 0;
// Start with the defined operands (i.e., the results of the root operator).
if (DstI.Operands.NumDefs != Src->getExtTypes().size())
return failedImport("Src pattern results and dst MI defs are different");
for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Record *DstIOpRec = DstI.Operands[OpIdx].Rec;
if (!DstIOpRec->isSubClassOf("RegisterClass"))
return failedImport("Dst MI def isn't a register class");
auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
if (!OpTyOrNone)
return failedImport("Dst operand has an unsupported type");
OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
OM.addPredicate<RegisterBankOperandMatcher>(
Target.getRegisterClass(DstIOpRec));
++OpIdx;
}
// Finally match the used operands (i.e., the children of the root operator).
for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
auto *SrcChild = Src->getChild(i);
auto *DstChild = Dst->getChild(i);
// Patterns can reorder operands. Ignore those for now.
if (SrcChild->getName() != DstChild->getName())
return failedImport("Src/dst pattern children not in same order");
// The only non-leaf child we accept is 'bb': it's an operator because
// BasicBlockSDNode isn't inline, but in MI it's just another operand.
if (!SrcChild->isLeaf()) {
if (DstChild->isLeaf() ||
SrcChild->getOperator() != DstChild->getOperator())
return failedImport("Src/dst pattern child operator mismatch");
if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
InsnMatcher.addOperand(OpIdx++).addPredicate<MBBOperandMatcher>();
continue;
}
}
return failedImport("Src pattern child isn't a leaf node");
}
if (SrcChild->getLeafValue() != DstChild->getLeafValue())
return failedImport("Src/dst pattern child leaf mismatch");
// Otherwise, we're looking for a bog-standard RegisterClass operand.
if (SrcChild->hasAnyPredicate())
return failedImport("Src pattern child has predicate");
auto *ChildRec = cast<DefInit>(SrcChild->getLeafValue())->getDef();
if (!ChildRec->isSubClassOf("RegisterClass"))
return failedImport("Src pattern child isn't a RegisterClass");
ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
if (ChildTypes.size() != 1)
return failedImport("Src pattern child has multiple results");
auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
if (!OpTyOrNone)
return failedImport("Src operand has an unsupported type");
OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
OM.addPredicate<RegisterBankOperandMatcher>(
Target.getRegisterClass(ChildRec));
++OpIdx;
}
// We're done with this pattern! It's eligible for GISel emission; return it.
return std::move(M);
}
void GlobalISelEmitter::run(raw_ostream &OS) {
// Track the GINodeEquiv definitions.
gatherNodeEquivs();
emitSourceFileHeader(("Global Instruction Selector for the " +
Target.getName() + " target").str(), OS);
OS << "bool " << Target.getName()
<< "InstructionSelector::selectImpl"
"(MachineInstr &I) const {\n const MachineRegisterInfo &MRI = "
"I.getParent()->getParent()->getRegInfo();\n\n";
// Look through the SelectionDAG patterns we found, possibly emitting some.
for (const PatternToMatch &Pat : CGP.ptms()) {
++NumPatternTotal;
auto MatcherOrErr = runOnPattern(Pat);
// The pattern analysis can fail, indicating an unsupported pattern.
// Report that if we've been asked to do so.
if (auto Err = MatcherOrErr.takeError()) {
if (WarnOnSkippedPatterns) {
PrintWarning(Pat.getSrcRecord()->getLoc(),
"Skipped pattern: " + toString(std::move(Err)));
} else {
consumeError(std::move(Err));
}
++NumPatternSkipped;
continue;
}
MatcherOrErr->emit(OS);
++NumPatternEmitted;
}
OS << " return false;\n}\n";
}
} // end anonymous namespace
//===----------------------------------------------------------------------===//
namespace llvm {
void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
GlobalISelEmitter(RK).run(OS);
}
} // End llvm namespace
[globalisel] Separate the SelectionDAG importer from the emitter. NFC
Summary:
In the near future the rules will be sorted between these two steps to
ensure that more important rules are not prevented by less important ones.
Reviewers: t.p.northover, ab, rovka, qcolombet, aditya_nandakumar
Reviewed By: ab
Subscribers: dberris, kristof.beyls, llvm-commits
Differential Revision: https://reviews.llvm.org/D29709
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@295661 91177308-0d34-0410-b5e6-96231b3b80d8
//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This tablegen backend emits code for use by the GlobalISel instruction
/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
///
/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
/// backend, filters out the ones that are unsupported, maps
/// SelectionDAG-specific constructs to their GlobalISel counterpart
/// (when applicable: MVT to LLT; SDNode to generic Instruction).
///
/// Not all patterns are supported: pass the tablegen invocation
/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
/// as well as why.
///
/// The generated file defines a single method:
/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
/// intended to be used in InstructionSelector::select as the first-step
/// selector for the patterns that don't require complex C++.
///
/// FIXME: We'll probably want to eventually define a base
/// "TargetGenInstructionSelector" class.
///
//===----------------------------------------------------------------------===//
#include "CodeGenDAGPatterns.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineValueType.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Error.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <string>
using namespace llvm;
#define DEBUG_TYPE "gisel-emitter"
STATISTIC(NumPatternTotal, "Total number of patterns");
STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
STATISTIC(NumPatternEmitted, "Number of patterns emitted");
static cl::opt<bool> WarnOnSkippedPatterns(
"warn-on-skipped-patterns",
cl::desc("Explain why a pattern was skipped for inclusion "
"in the GlobalISel selector"),
cl::init(false));
namespace {
//===- Helper functions ---------------------------------------------------===//
/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
static Optional<std::string> MVTToLLT(MVT::SimpleValueType SVT) {
std::string TyStr;
raw_string_ostream OS(TyStr);
MVT VT(SVT);
if (VT.isVector() && VT.getVectorNumElements() != 1) {
OS << "LLT::vector(" << VT.getVectorNumElements() << ", "
<< VT.getScalarSizeInBits() << ")";
} else if (VT.isInteger() || VT.isFloatingPoint()) {
OS << "LLT::scalar(" << VT.getSizeInBits() << ")";
} else {
return None;
}
OS.flush();
return TyStr;
}
static bool isTrivialOperatorNode(const TreePatternNode *N) {
return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
}
//===- Matchers -----------------------------------------------------------===//
template <class PredicateTy> class PredicateListMatcher {
private:
typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
PredicateVec Predicates;
public:
/// Construct a new operand predicate and add it to the matcher.
template <class Kind, class... Args>
Kind &addPredicate(Args&&... args) {
Predicates.emplace_back(
llvm::make_unique<Kind>(std::forward<Args>(args)...));
return *static_cast<Kind *>(Predicates.back().get());
}
typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
iterator_range<typename PredicateVec::const_iterator> predicates() const {
return make_range(predicates_begin(), predicates_end());
}
/// Emit a C++ expression that tests whether all the predicates are met.
template <class... Args>
void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
if (Predicates.empty()) {
OS << "true";
return;
}
StringRef Separator = "";
for (const auto &Predicate : predicates()) {
OS << Separator << "(";
Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
OS << ")";
Separator = " &&\n";
}
}
};
/// Generates code to check a predicate of an operand.
///
/// Typical predicates include:
/// * Operand is a particular register.
/// * Operand is assigned a particular register bank.
/// * Operand is an MBB.
class OperandPredicateMatcher {
public:
virtual ~OperandPredicateMatcher() {}
/// Emit a C++ expression that checks the predicate for the OpIdx operand of
/// the instruction given in InsnVarName.
virtual void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const = 0;
};
/// Generates code to check that an operand is a particular LLT.
class LLTOperandMatcher : public OperandPredicateMatcher {
protected:
std::string Ty;
public:
LLTOperandMatcher(std::string Ty) : Ty(Ty) {}
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const override {
OS << "MRI.getType(" << InsnVarName << ".getOperand(" << OpIdx
<< ").getReg()) == (" << Ty << ")";
}
};
/// Generates code to check that an operand is in a particular register bank.
class RegisterBankOperandMatcher : public OperandPredicateMatcher {
protected:
const CodeGenRegisterClass &RC;
public:
RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) : RC(RC) {}
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const override {
OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
<< "RegClass) == RBI.getRegBank(" << InsnVarName << ".getOperand("
<< OpIdx << ").getReg(), MRI, TRI))";
}
};
/// Generates code to check that an operand is a basic block.
class MBBOperandMatcher : public OperandPredicateMatcher {
public:
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
unsigned OpIdx) const override {
OS << InsnVarName << ".getOperand(" << OpIdx << ").isMBB()";
}
};
/// Generates code to check that a set of predicates match for a particular
/// operand.
class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
protected:
unsigned OpIdx;
public:
OperandMatcher(unsigned OpIdx) : OpIdx(OpIdx) {}
/// Emit a C++ expression that tests whether the instruction named in
/// InsnVarName matches all the predicate and all the operands.
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
OS << "(";
emitCxxPredicateListExpr(OS, InsnVarName, OpIdx);
OS << ")";
}
};
/// Generates code to check a predicate on an instruction.
///
/// Typical predicates include:
/// * The opcode of the instruction is a particular value.
/// * The nsw/nuw flag is/isn't set.
class InstructionPredicateMatcher {
public:
virtual ~InstructionPredicateMatcher() {}
/// Emit a C++ expression that tests whether the instruction named in
/// InsnVarName matches the predicate.
virtual void emitCxxPredicateExpr(raw_ostream &OS,
StringRef InsnVarName) const = 0;
};
/// Generates code to check the opcode of an instruction.
class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
protected:
const CodeGenInstruction *I;
public:
InstructionOpcodeMatcher(const CodeGenInstruction *I) : I(I) {}
void emitCxxPredicateExpr(raw_ostream &OS,
StringRef InsnVarName) const override {
OS << InsnVarName << ".getOpcode() == " << I->Namespace
<< "::" << I->TheDef->getName();
}
};
/// Generates code to check that a set of predicates and operands match for a
/// particular instruction.
///
/// Typical predicates include:
/// * Has a specific opcode.
/// * Has an nsw/nuw flag or doesn't.
class InstructionMatcher
: public PredicateListMatcher<InstructionPredicateMatcher> {
protected:
std::vector<OperandMatcher> Operands;
public:
/// Add an operand to the matcher.
OperandMatcher &addOperand(unsigned OpIdx) {
Operands.emplace_back(OpIdx);
return Operands.back();
}
/// Emit a C++ expression that tests whether the instruction named in
/// InsnVarName matches all the predicates and all the operands.
void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
emitCxxPredicateListExpr(OS, InsnVarName);
for (const auto &Operand : Operands) {
OS << " &&\n(";
Operand.emitCxxPredicateExpr(OS, InsnVarName);
OS << ")";
}
}
};
//===- Actions ------------------------------------------------------------===//
/// An action taken when all Matcher predicates succeeded for a parent rule.
///
/// Typical actions include:
/// * Changing the opcode of an instruction.
/// * Adding an operand to an instruction.
class MatchAction {
public:
virtual ~MatchAction() {}
virtual void emitCxxActionStmts(raw_ostream &OS) const = 0;
};
/// Generates a comment describing the matched rule being acted upon.
class DebugCommentAction : public MatchAction {
private:
const PatternToMatch &P;
public:
DebugCommentAction(const PatternToMatch &P) : P(P) {}
virtual void emitCxxActionStmts(raw_ostream &OS) const {
OS << "// " << *P.getSrcPattern() << " => " << *P.getDstPattern();
}
};
/// Generates code to set the opcode (really, the MCInstrDesc) of a matched
/// instruction to a given Instruction.
class MutateOpcodeAction : public MatchAction {
private:
const CodeGenInstruction *I;
public:
MutateOpcodeAction(const CodeGenInstruction *I) : I(I) {}
virtual void emitCxxActionStmts(raw_ostream &OS) const {
OS << "I.setDesc(TII.get(" << I->Namespace << "::" << I->TheDef->getName()
<< "));";
}
};
/// Generates code to check that a match rule matches.
class RuleMatcher {
/// A list of matchers that all need to succeed for the current rule to match.
/// FIXME: This currently supports a single match position but could be
/// extended to support multiple positions to support div/rem fusion or
/// load-multiple instructions.
std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
/// A list of actions that need to be taken when all predicates in this rule
/// have succeeded.
std::vector<std::unique_ptr<MatchAction>> Actions;
public:
RuleMatcher() {}
InstructionMatcher &addInstructionMatcher() {
Matchers.emplace_back(new InstructionMatcher());
return *Matchers.back();
}
template <class Kind, class... Args>
Kind &addAction(Args&&... args) {
Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
return *static_cast<Kind *>(Actions.back().get());
}
void emit(raw_ostream &OS) const {
if (Matchers.empty())
llvm_unreachable("Unexpected empty matcher!");
// The representation supports rules that require multiple roots such as:
// %ptr(p0) = ...
// %elt0(s32) = G_LOAD %ptr
// %1(p0) = G_ADD %ptr, 4
// %elt1(s32) = G_LOAD p0 %1
// which could be usefully folded into:
// %ptr(p0) = ...
// %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
// on some targets but we don't need to make use of that yet.
assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
OS << " if (";
Matchers.front()->emitCxxPredicateExpr(OS, "I");
OS << ") {\n";
for (const auto &MA : Actions) {
OS << " ";
MA->emitCxxActionStmts(OS);
OS << "\n";
}
OS << " constrainSelectedInstRegOperands(I, TII, TRI, RBI);\n";
OS << " return true;\n";
OS << " }\n\n";
}
};
//===- GlobalISelEmitter class --------------------------------------------===//
class GlobalISelEmitter {
public:
explicit GlobalISelEmitter(RecordKeeper &RK);
void run(raw_ostream &OS);
private:
const RecordKeeper &RK;
const CodeGenDAGPatterns CGP;
const CodeGenTarget &Target;
/// Keep track of the equivalence between SDNodes and Instruction.
/// This is defined using 'GINodeEquiv' in the target description.
DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
void gatherNodeEquivs();
const CodeGenInstruction *findNodeEquiv(Record *N);
/// Analyze pattern \p P, returning a matcher for it if possible.
/// Otherwise, return an Error explaining why we don't support it.
Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
};
void GlobalISelEmitter::gatherNodeEquivs() {
assert(NodeEquivs.empty());
for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
NodeEquivs[Equiv->getValueAsDef("Node")] =
&Target.getInstruction(Equiv->getValueAsDef("I"));
}
const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) {
return NodeEquivs.lookup(N);
}
GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
: RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
//===- Emitter ------------------------------------------------------------===//
/// Helper function to let the emitter report skip reason error messages.
static Error failedImport(const Twine &Reason) {
return make_error<StringError>(Reason, inconvertibleErrorCode());
}
Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
// Keep track of the matchers and actions to emit.
RuleMatcher M;
M.addAction<DebugCommentAction>(P);
// First, analyze the whole pattern.
// If the entire pattern has a predicate (e.g., target features), ignore it.
if (!P.getPredicates()->getValues().empty())
return failedImport("Pattern has a predicate");
// Physreg imp-defs require additional logic. Ignore the pattern.
if (!P.getDstRegs().empty())
return failedImport("Pattern defines a physical register");
// Next, analyze the pattern operators.
TreePatternNode *Src = P.getSrcPattern();
TreePatternNode *Dst = P.getDstPattern();
// If the root of either pattern isn't a simple operator, ignore it.
if (!isTrivialOperatorNode(Dst))
return failedImport("Dst pattern root isn't a trivial operator");
if (!isTrivialOperatorNode(Src))
return failedImport("Src pattern root isn't a trivial operator");
Record *DstOp = Dst->getOperator();
if (!DstOp->isSubClassOf("Instruction"))
return failedImport("Pattern operator isn't an instruction");
auto &DstI = Target.getInstruction(DstOp);
auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
if (!SrcGIOrNull)
return failedImport("Pattern operator lacks an equivalent Instruction");
auto &SrcGI = *SrcGIOrNull;
// The operators look good: match the opcode and mutate it to the new one.
InstructionMatcher &InsnMatcher = M.addInstructionMatcher();
InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
M.addAction<MutateOpcodeAction>(&DstI);
// Next, analyze the children, only accepting patterns that don't require
// any change to operands.
if (Src->getNumChildren() != Dst->getNumChildren())
return failedImport("Src/dst patterns have a different # of children");
unsigned OpIdx = 0;
// Start with the defined operands (i.e., the results of the root operator).
if (DstI.Operands.NumDefs != Src->getExtTypes().size())
return failedImport("Src pattern results and dst MI defs are different");
for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Record *DstIOpRec = DstI.Operands[OpIdx].Rec;
if (!DstIOpRec->isSubClassOf("RegisterClass"))
return failedImport("Dst MI def isn't a register class");
auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
if (!OpTyOrNone)
return failedImport("Dst operand has an unsupported type");
OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
OM.addPredicate<RegisterBankOperandMatcher>(
Target.getRegisterClass(DstIOpRec));
++OpIdx;
}
// Finally match the used operands (i.e., the children of the root operator).
for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
auto *SrcChild = Src->getChild(i);
auto *DstChild = Dst->getChild(i);
// Patterns can reorder operands. Ignore those for now.
if (SrcChild->getName() != DstChild->getName())
return failedImport("Src/dst pattern children not in same order");
// The only non-leaf child we accept is 'bb': it's an operator because
// BasicBlockSDNode isn't inline, but in MI it's just another operand.
if (!SrcChild->isLeaf()) {
if (DstChild->isLeaf() ||
SrcChild->getOperator() != DstChild->getOperator())
return failedImport("Src/dst pattern child operator mismatch");
if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
InsnMatcher.addOperand(OpIdx++).addPredicate<MBBOperandMatcher>();
continue;
}
}
return failedImport("Src pattern child isn't a leaf node");
}
if (SrcChild->getLeafValue() != DstChild->getLeafValue())
return failedImport("Src/dst pattern child leaf mismatch");
// Otherwise, we're looking for a bog-standard RegisterClass operand.
if (SrcChild->hasAnyPredicate())
return failedImport("Src pattern child has predicate");
auto *ChildRec = cast<DefInit>(SrcChild->getLeafValue())->getDef();
if (!ChildRec->isSubClassOf("RegisterClass"))
return failedImport("Src pattern child isn't a RegisterClass");
ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
if (ChildTypes.size() != 1)
return failedImport("Src pattern child has multiple results");
auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
if (!OpTyOrNone)
return failedImport("Src operand has an unsupported type");
OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
OM.addPredicate<RegisterBankOperandMatcher>(
Target.getRegisterClass(ChildRec));
++OpIdx;
}
// We're done with this pattern! It's eligible for GISel emission; return it.
++NumPatternImported;
return std::move(M);
}
void GlobalISelEmitter::run(raw_ostream &OS) {
// Track the GINodeEquiv definitions.
gatherNodeEquivs();
emitSourceFileHeader(("Global Instruction Selector for the " +
Target.getName() + " target").str(), OS);
OS << "bool " << Target.getName()
<< "InstructionSelector::selectImpl"
"(MachineInstr &I) const {\n const MachineRegisterInfo &MRI = "
"I.getParent()->getParent()->getRegInfo();\n\n";
std::vector<RuleMatcher> Rules;
// Look through the SelectionDAG patterns we found, possibly emitting some.
for (const PatternToMatch &Pat : CGP.ptms()) {
++NumPatternTotal;
auto MatcherOrErr = runOnPattern(Pat);
// The pattern analysis can fail, indicating an unsupported pattern.
// Report that if we've been asked to do so.
if (auto Err = MatcherOrErr.takeError()) {
if (WarnOnSkippedPatterns) {
PrintWarning(Pat.getSrcRecord()->getLoc(),
"Skipped pattern: " + toString(std::move(Err)));
} else {
consumeError(std::move(Err));
}
++NumPatternImportsSkipped;
continue;
}
Rules.push_back(std::move(MatcherOrErr.get()));
}
for (const auto &Rule : Rules) {
Rule.emit(OS);
++NumPatternEmitted;
}
OS << " return false;\n}\n";
}
} // end anonymous namespace
//===----------------------------------------------------------------------===//
namespace llvm {
void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
GlobalISelEmitter(RK).run(OS);
}
} // End llvm namespace
|
// This file is part of the hdf5_handler implementing for the CF-compliant
// Copyright (c) 2011-2013 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
/////////////////////////////////////////////////////////////////////////////
/// \file HDF5GMCF.cc
/// \brief Implementation of the mapping of NASA generic HDF5 products to DAP by following CF
///
/// It includes functions to
/// 1) retrieve HDF5 metadata info.
/// 2) translate HDF5 objects into DAP DDS and DAS by following CF conventions.
///
///
/// \author Muqun Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2013 The HDF Group
///
/// All rights reserved.
#include "HDF5CF.h"
#include <BESDebug.h>
#include <algorithm>
//#include <sstream>
using namespace HDF5CF;
GMCVar::GMCVar(Var*var) {
newname = var->newname;
name = var->name;
fullpath = var->fullpath;
rank = var->rank;
dtype = var->dtype;
unsupported_attr_dtype = var->unsupported_attr_dtype;
unsupported_dspace = var->unsupported_dspace;
for (vector<Attribute*>::iterator ira = var->attrs.begin();
ira!=var->attrs.end(); ++ira) {
Attribute* attr= new Attribute();
attr->name = (*ira)->name;
attr->newname = (*ira)->newname;
attr->dtype =(*ira)->dtype;
attr->count =(*ira)->count;
attr->strsize = (*ira)->strsize;
attr->fstrsize = (*ira)->fstrsize;
attr->value =(*ira)->value;
attrs.push_back(attr);
}
for (vector<Dimension*>::iterator ird = var->dims.begin();
ird!=var->dims.end(); ++ird) {
Dimension *dim = new Dimension((*ird)->size);
//"h5","dim->name "<< (*ird)->name <<endl;
//"h5","dim->newname "<< (*ird)->newname <<endl;
dim->name = (*ird)->name;
dim->newname = (*ird)->newname;
dims.push_back(dim);
}
product_type = General_Product;
}
#if 0
GMCVar::GMCVar(GMCVar*cvar) {
newname = cvar->newname;
name = cvar->name;
fullpath = cvar->fullpath;
rank = cvar->rank;
dtype = cvar->dtype;
unsupported_attr_dtype = cvar->unsupported_attr_dtype;
unsupported_dspace = cvar->unsupported_dspace;
for (vector<Attribute*>::iterator ira = cvar->attrs.begin();
ira!=cvar->attrs.end(); ++ira) {
Attribute* attr= new Attribute();
attr->name = (*ira)->name;
attr->newname = (*ira)->newname;
attr->dtype =(*ira)->dtype;
attr->count =(*ira)->count;
attr->strsize = (*ira)->strsize;
attr->fstrsize = (*ira)->fstrsize;
attr->value =(*ira)->value;
attrs.push_back(attr);
}
for (vector<Dimension*>::iterator ird = cvar->dims.begin();
ird!=cvar->dims.end(); ++ird) {
Dimension *dim = new Dimension((*ird)->size);
//"h5","dim->name "<< (*ird)->name <<endl;
//"h5","dim->newname "<< (*ird)->newname <<endl;
dim->name = (*ird)->name;
dim->newname = (*ird)->newname;
dims.push_back(dim);
}
GMcvar->cfdimname = latdim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
}
#endif
GMSPVar::GMSPVar(Var*var) {
fullpath = var->fullpath;
rank = var->rank;
unsupported_attr_dtype = var->unsupported_attr_dtype;
unsupported_dspace = var->unsupported_dspace;
for (vector<Attribute*>::iterator ira = var->attrs.begin();
ira!=var->attrs.end(); ++ira) {
Attribute* attr= new Attribute();
attr->name = (*ira)->name;
attr->newname = (*ira)->newname;
attr->dtype =(*ira)->dtype;
attr->count =(*ira)->count;
attr->strsize = (*ira)->strsize;
attr->fstrsize = (*ira)->fstrsize;
attr->value =(*ira)->value;
attrs.push_back(attr);
} // for (vector<Attribute*>::iterator ira = var->attrs.begin();
for (vector<Dimension*>::iterator ird = var->dims.begin();
ird!=var->dims.end(); ++ird) {
Dimension *dim = new Dimension((*ird)->size);
dim->name = (*ird)->name;
dim->newname = (*ird)->newname;
dims.push_back(dim);
}
}
GMFile::GMFile(const char*path, hid_t file_id, H5GCFProduct product_type, GMPattern gproduct_pattern):
File(path,file_id), product_type(product_type),gproduct_pattern(gproduct_pattern),iscoard(false),ll2d_no_cv(false)
{
}
GMFile::~GMFile()
{
if (!this->cvars.empty()){
for (vector<GMCVar *>:: const_iterator i= this->cvars.begin(); i!=this->cvars.end(); ++i) {
delete *i;
}
}
if (!this->spvars.empty()){
for (vector<GMSPVar *>:: const_iterator i= this->spvars.begin(); i!=this->spvars.end(); ++i) {
delete *i;
}
}
}
string GMFile::get_CF_string(string s) {
// HDF5 group or variable path always starts with '/'. When CF naming rule is applied,
// the first '/' is always changes to "_", this is not necessary. However,
// to keep the backward compatiablity, I use a BES key for people to go back with the original name.
if(s[0] !='/')
return File::get_CF_string(s);
else if (General_Product == product_type && OTHERGMS == gproduct_pattern) {
string check_keepleading_underscore_key = "H5.KeepVarLeadingUnderscore";
if(true == HDF5CFDAPUtil::check_beskeys(check_keepleading_underscore_key))
return File::get_CF_string(s);
else {
s.erase(0,1);
return File::get_CF_string(s);
}
}
else {
s.erase(0,1);
return File::get_CF_string(s);
}
}
void GMFile::Retrieve_H5_Info(const char *path,
hid_t file_id, bool include_attr) throw (Exception) {
// MeaSure SeaWiFS and Ozone need the attribute info. to build the dimension name list.
// GPM needs the attribute info. to obtain the lat/lon.
// So set the include_attr to be true for these products.
if (product_type == Mea_SeaWiFS_L2 || product_type == Mea_SeaWiFS_L3
|| GPMS_L3 == product_type || GPMM_L3 == product_type || GPM_L1 == product_type || OBPG_L3 == product_type
|| Mea_Ozone == product_type || General_Product == product_type)
File::Retrieve_H5_Info(path,file_id,true);
else
File::Retrieve_H5_Info(path,file_id,include_attr);
}
void GMFile::Update_Product_Type() throw(Exception) {
if(GPMS_L3 == this->product_type || GPMM_L3 == this->product_type) {
// Check Dimscale attributes
Check_General_Product_Pattern();
if(GENERAL_DIMSCALE == this->gproduct_pattern){
if(GPMS_L3 == this->product_type) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv)
(*irv)->newname = (*irv)->name;
}
this->product_type = General_Product;
}
}
}
void GMFile::Retrieve_H5_Supported_Attr_Values() throw (Exception) {
File::Retrieve_H5_Supported_Attr_Values();
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
//if ((CV_EXIST == (*ircv)->cvartype ) || (CV_MODIFY == (*ircv)->cvartype)
// || (CV_FILLINDEX == (*ircv)->cvartype)){
if ((*ircv)->cvartype != CV_NONLATLON_MISS){
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ++ira) {
Retrieve_H5_Attr_Value(*ira,(*ircv)->fullpath);
}
}
}
for (vector<GMSPVar *>::iterator irspv = this->spvars.begin();
irspv != this->spvars.end(); ++irspv) {
for (vector<Attribute *>::iterator ira = (*irspv)->attrs.begin();
ira != (*irspv)->attrs.end(); ++ira) {
Retrieve_H5_Attr_Value(*ira,(*irspv)->fullpath);
Adjust_H5_Attr_Value(*ira);
}
}
}
void GMFile::Adjust_H5_Attr_Value(Attribute *attr) throw (Exception) {
if (product_type == ACOS_L2S_OR_OCO2_L1B) {
if (("Type" == attr->name) && (H5VSTRING == attr->dtype)) {
string orig_attrvalues(attr->value.begin(),attr->value.end());
if (orig_attrvalues != "Signed64") return;
string new_attrvalues = "Signed32";
// Since the new_attrvalues size is the same as the orig_attrvalues size
// No need to adjust the strsize and fstrsize. KY 2011-2-1
attr->value.clear();
attr->value.resize(new_attrvalues.size());
copy(new_attrvalues.begin(),new_attrvalues.end(),attr->value.begin());
}
} // if (product_type == ACOS_L2S_OR_OCO2_L1B)
}
void GMFile:: Handle_Unsupported_Dtype(bool include_attr) throw(Exception) {
if(true == check_ignored) {
Gen_Unsupported_Dtype_Info(include_attr);
}
File::Handle_Unsupported_Dtype(include_attr);
Handle_GM_Unsupported_Dtype(include_attr);
}
void GMFile:: Handle_GM_Unsupported_Dtype(bool include_attr) throw(Exception) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ) {
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
delete (*ira);
ira = (*ircv)->attrs.erase(ira);
}
else {
++ira;
}
}
}
H5DataType temp_dtype = (*ircv)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
// This may need to be checked carefully in the future,
// My current understanding is that the coordinate variable can
// be ignored if the corresponding variable is ignored.
// Currently we don't find any NASA files in this category.
// KY 2012-5-21
delete (*ircv);
ircv = this->cvars.erase(ircv);
}
else {
++ircv;
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
ircv != this->spvars.end(); ) {
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
delete (*ira);
ira = (*ircv)->attrs.erase(ira);
}
else {
++ira;
}
}
}
H5DataType temp_dtype = (*ircv)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
delete (*ircv);
ircv = this->spvars.erase(ircv);
}
else {
++ircv;
}
}// for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
}
void GMFile:: Gen_Unsupported_Dtype_Info(bool include_attr) {
if(true == include_attr) {
File::Gen_Group_Unsupported_Dtype_Info();
File::Gen_Var_Unsupported_Dtype_Info();
Gen_VarAttr_Unsupported_Dtype_Info();
}
}
void GMFile:: Gen_VarAttr_Unsupported_Dtype_Info() throw(Exception){
// First general variables(non-CV and non-special variable)
if((General_Product == this->product_type && GENERAL_DIMSCALE== this->gproduct_pattern)
|| (Mea_Ozone == this->product_type) || (Mea_SeaWiFS_L2 == this->product_type) || (Mea_SeaWiFS_L3 == this->product_type)
|| (OBPG_L3 == this->product_type)) {
Gen_DimScale_VarAttr_Unsupported_Dtype_Info();
}
else
File::Gen_VarAttr_Unsupported_Dtype_Info();
// CV and special variables
Gen_GM_VarAttr_Unsupported_Dtype_Info();
}
void GMFile:: Gen_GM_VarAttr_Unsupported_Dtype_Info(){
if((General_Product == this->product_type && GENERAL_DIMSCALE== this->gproduct_pattern)
|| (Mea_Ozone == this->product_type) || (Mea_SeaWiFS_L2 == this->product_type) || (Mea_SeaWiFS_L3 == this->product_type)
|| (OBPG_L3 == this->product_type)) {
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
// If the attribute REFERENCE_LIST comes with the attribut CLASS, the
// attribute REFERENCE_LIST is okay to ignore. No need to report.
bool is_ignored = ignored_dimscale_ref_list((*irv));
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
// "DIMENSION_LIST" is okay to ignore and "REFERENCE_LIST"
// is okay to ignore if the variable has another attribute
// CLASS="DIMENSION_SCALE"
if (("DIMENSION_LIST" !=(*ira)->name) &&
(("REFERENCE_LIST" != (*ira)->name || true == is_ignored)))
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
// If the attribute REFERENCE_LIST comes with the attribut CLASS, the
// attribute REFERENCE_LIST is okay to ignore. No need to report.
bool is_ignored = ignored_dimscale_ref_list((*irv));
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
// "DIMENSION_LIST" is okay to ignore and "REFERENCE_LIST"
// is okay to ignore if the variable has another attribute
// CLASS="DIMENSION_SCALE"
if (("DIMENSION_LIST" !=(*ira)->name) &&
(("REFERENCE_LIST" != (*ira)->name || true == is_ignored)))
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
}
else {
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
}
}
void GMFile:: Handle_Unsupported_Dspace() throw(Exception) {
if(true == check_ignored)
Gen_Unsupported_Dspace_Info();
File::Handle_Unsupported_Dspace();
Handle_GM_Unsupported_Dspace();
}
void GMFile:: Handle_GM_Unsupported_Dspace() throw(Exception) {
if(true == this->unsupported_var_dspace) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ) {
if (true == (*ircv)->unsupported_dspace ) {
// This may need to be checked carefully in the future,
// My current understanding is that the coordinate variable can
// be ignored if the corresponding variable is ignored.
// Currently we don't find any NASA files in this category.
// KY 2012-5-21
delete (*ircv);
ircv = this->cvars.erase(ircv);
//ircv--;
}
else {
++ircv;
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
ircv != this->spvars.end(); ) {
if (true == (*ircv)->unsupported_dspace) {
delete (*ircv);
ircv = this->spvars.erase(ircv);
}
else {
++ircv;
}
}// for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
}// if(true == this->unsupported_dspace)
}
void GMFile:: Gen_Unsupported_Dspace_Info() throw(Exception){
File::Gen_Unsupported_Dspace_Info();
}
void GMFile:: Handle_Unsupported_Others(bool include_attr) throw(Exception) {
File::Handle_Unsupported_Others(include_attr);
if(true == this->check_ignored && true == include_attr) {
// Check the drop long string feature.
string check_droplongstr_key ="H5.EnableDropLongString";
bool is_droplongstr = false;
is_droplongstr = HDF5CFDAPUtil::check_beskeys(check_droplongstr_key);
if(true == is_droplongstr){
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();++ira) {
if(true == Check_DropLongStr((*irv),(*ira))) {
this->add_ignored_droplongstr_hdr();
this->add_ignored_var_longstr_info((*irv),(*ira));
}
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();++ira) {
if(true == Check_DropLongStr((*irv),(*ira))) {
this->add_ignored_droplongstr_hdr();
this->add_ignored_var_longstr_info((*irv),(*ira));
}
}
}
}
}
if(false == this->have_ignored)
this->add_no_ignored_info();
}
void GMFile::Add_Dim_Name() throw(Exception){
switch(product_type) {
case Mea_SeaWiFS_L2:
case Mea_SeaWiFS_L3:
Add_Dim_Name_Mea_SeaWiFS();
break;
case Aqu_L3:
Add_Dim_Name_Aqu_L3();
break;
case SMAP:
Add_Dim_Name_SMAP();
break;
case ACOS_L2S_OR_OCO2_L1B:
Add_Dim_Name_ACOS_L2S_OCO2_L1B();
break;
case Mea_Ozone:
Add_Dim_Name_Mea_Ozonel3z();
break;
case GPMS_L3:
case GPMM_L3:
case GPM_L1:
Add_Dim_Name_GPM();
break;
case OBPG_L3:
Add_Dim_Name_OBPG_L3();
break;
case General_Product:
Add_Dim_Name_General_Product();
break;
default:
throw1("Cannot generate dim. names for unsupported datatype");
} // switch(product_type)
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Add_Dim_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
//Add Dim. Names for OBPG level 3 product
void GMFile::Add_Dim_Name_OBPG_L3() throw(Exception) {
// netCDF-4 like structure
Add_Dim_Name_General_Product();
}
//Add Dim. Names for MeaSures SeaWiFS. Future: May combine with the handling of netCDF-4 products
void GMFile::Add_Dim_Name_Mea_SeaWiFS() throw(Exception){
//cerr<<"coming to Add_Dim_Name_Mea_SeaWiFS"<<endl;
pair<set<string>::iterator,bool> setret;
if (Mea_SeaWiFS_L3 == product_type)
iscoard = true;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
Handle_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone((*irv));
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
if (true == dimnamelist.empty())
throw1("This product should have the dimension names, but no dimension names are found");
}
void GMFile::Handle_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone(Var* var)
throw(Exception){
Attribute* dimlistattr = NULL;
bool has_dimlist = false;
bool has_class = false;
bool has_reflist = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name) {
dimlistattr = *ira;
has_dimlist = true;
}
if ("CLASS" == (*ira)->name)
has_class = true;
if ("REFERENCE_LIST" == (*ira)->name)
has_reflist = true;
if (true == has_dimlist)
break;
if (true == has_class && true == has_reflist)
break;
} // for(vector<Attribute *>::iterator ira = var->attrs.begin(); ...
if (true == has_dimlist)
Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone(var,dimlistattr);
// Dim name is the same as the variable name for dimscale variable
else if(true == has_class && true == has_reflist) {
if (var->dims.size() !=1)
throw2("dimension scale dataset must be 1 dimension, this is not true for variable ",
var->name);
// The var name is the object name, however, we would like the dimension name to be full path.
// so that the dim name can be served as the key for future handling.
(var->dims)[0]->name = var->fullpath;
(var->dims)[0]->newname = var->fullpath;
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((var->dims)[0]->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((var->dims)[0]->name,(var->dims)[0]->size);
}
// No dimension, add fake dim names, this may never happen for MeaSure
// but just for coherence and completeness.
// For Fake dimesnion
else {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= var->dims.begin();
ird != var->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
// Just for debugging
#if 0
for (int i = 0; i < var->dims.size(); ++i) {
Add_One_FakeDim_Name((var->dims)[i]);
bool gotoMainLoop = false;
for (int j =i-1; j>=0 && !gotoMainLoop; --j) {
if (((var->dims)[i])->size == ((var->dims)[j])->size){
Adjust_Duplicate_FakeDim_Name((var->dims)[i]);
gotoMainLoop = true;
}
}
}
#endif
}
}
// Helper function to support dimensions of MeaSUrES SeaWiFS and OZone products
void GMFile::Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone(Var *var,Attribute*dimlistattr)
throw (Exception){
ssize_t objnamelen = -1;
hobj_ref_t rbuf;
//hvl_t *vlbuf = NULL;
vector<hvl_t> vlbuf;
hid_t dset_id = -1;
hid_t attr_id = -1;
hid_t atype_id = -1;
hid_t amemtype_id = -1;
hid_t aspace_id = -1;
hid_t ref_dset = -1;
if(NULL == dimlistattr)
throw2("Cannot obtain the dimension list attribute for variable ",var->name);
if (0==var->rank)
throw2("The number of dimension should NOT be 0 for the variable ",var->name);
try {
vlbuf.resize(var->rank);
dset_id = H5Dopen(this->fileid,(var->fullpath).c_str(),H5P_DEFAULT);
if (dset_id < 0)
throw2("Cannot open the dataset ",var->fullpath);
attr_id = H5Aopen(dset_id,(dimlistattr->name).c_str(),H5P_DEFAULT);
if (attr_id <0 )
throw4("Cannot open the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
atype_id = H5Aget_type(attr_id);
if (atype_id <0)
throw4("Cannot obtain the datatype of the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
amemtype_id = H5Tget_native_type(atype_id, H5T_DIR_ASCEND);
if (amemtype_id < 0)
throw2("Cannot obtain the memory datatype for the attribute ",dimlistattr->name);
if (H5Aread(attr_id,amemtype_id,&vlbuf[0]) <0)
throw2("Cannot obtain the referenced object for the variable ",var->name);
vector<char> objname;
int vlbuf_index = 0;
// The dimension names of variables will be the HDF5 dataset names dereferenced from the DIMENSION_LIST attribute.
for (vector<Dimension *>::iterator ird = var->dims.begin();
ird != var->dims.end(); ++ird) {
rbuf =((hobj_ref_t*)vlbuf[vlbuf_index].p)[0];
if ((ref_dset = H5Rdereference(attr_id, H5R_OBJECT, &rbuf)) < 0)
throw2("Cannot dereference from the DIMENSION_LIST attribute for the variable ",var->name);
if ((objnamelen= H5Iget_name(ref_dset,NULL,0))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
objname.resize(objnamelen+1);
if ((objnamelen= H5Iget_name(ref_dset,&objname[0],objnamelen+1))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
string objname_str = string(objname.begin(),objname.end());
string trim_objname = objname_str.substr(0,objnamelen);
(*ird)->name = string(trim_objname.begin(),trim_objname.end());
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
(*ird)->newname = (*ird)->name;
H5Dclose(ref_dset);
ref_dset = -1;
objname.clear();
vlbuf_index++;
}// for (vector<Dimension *>::iterator ird = var->dims.begin()
if(vlbuf.size()!= 0) {
if ((aspace_id = H5Aget_space(attr_id)) < 0)
throw2("Cannot get hdf5 dataspace id for the attribute ",dimlistattr->name);
if (H5Dvlen_reclaim(amemtype_id,aspace_id,H5P_DEFAULT,(void*)&vlbuf[0])<0)
throw2("Cannot successfully clean up the variable length memory for the variable ",var->name);
H5Sclose(aspace_id);
}
H5Tclose(atype_id);
H5Tclose(amemtype_id);
H5Aclose(attr_id);
H5Dclose(dset_id);
}
catch(...) {
if(atype_id != -1)
H5Tclose(atype_id);
if(amemtype_id != -1)
H5Tclose(amemtype_id);
if(aspace_id != -1)
H5Sclose(aspace_id);
if(attr_id != -1)
H5Aclose(attr_id);
if(dset_id != -1)
H5Dclose(dset_id);
//throw1("Error in method GMFile::Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone");
throw;
}
}
// Add MeaSURES OZone level 3Z dimension names
void GMFile::Add_Dim_Name_Mea_Ozonel3z() throw(Exception){
iscoard = true;
bool use_dimscale = false;
for (vector<Group *>::iterator irg = this->groups.begin();
irg != this->groups.end(); ++ irg) {
if ("/Dimensions" == (*irg)->path) {
use_dimscale = true;
break;
}
}
if (false == use_dimscale) {
bool has_dimlist = false;
bool has_class = false;
bool has_reflist = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name)
has_dimlist = true;
}
if (true == has_dimlist)
break;
}
if (true == has_dimlist) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("CLASS" == (*ira)->name)
has_class = true;
if ("REFERENCE_LIST" == (*ira)->name)
has_reflist = true;
if (true == has_class && true == has_reflist)
break;
}
if (true == has_class &&
true == has_reflist)
break;
}
if (true == has_class && true == has_reflist)
use_dimscale = true;
} // if (true == has_dimlist)
} // if (false == use_dimscale)
if (true == use_dimscale) {
pair<set<string>::iterator,bool> setret;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
Handle_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone((*irv));
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
setret = dimnamelist.insert((*ird)->name);
if(true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
}
if (true == dimnamelist.empty())
throw1("This product should have the dimension names, but no dimension names are found");
} // if (true == use_dimscale)
else {
// Since the dim. size of each dimension of 2D lat/lon may be the same, so use multimap.
multimap<hsize_t,string> ozonedimsize_to_dimname;
pair<multimap<hsize_t,string>::iterator,multimap<hsize_t,string>::iterator> mm_er_ret;
multimap<hsize_t,string>::iterator irmm;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool is_cv = check_cv((*irv)->name);
if (true == is_cv) {
if ((*irv)->dims.size() != 1)
throw3("The coordinate variable", (*irv)->name," must be one dimension for the zonal average product");
ozonedimsize_to_dimname.insert(pair<hsize_t,string>(((*irv)->dims)[0]->size,(*irv)->fullpath));
#if 0
((*irv)->dims[0])->name = (*irv)->name;
((*irv)->dims[0])->newname = (*irv)->name;
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert(((*irv)->dims[0])->name);
if (setret.second)
Insert_One_NameSizeMap_Element(((*irv)->dims[0])->name,((*irv)->dims[0])->size);
#endif
}
}// for (vector<Var *>::iterator irv = this->vars.begin(); ...
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
pair<set<string>::iterator,bool> setret;
pair<set<string>::iterator,bool> tempsetret;
set<string> tempdimnamelist;
bool fakedimflag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
fakedimflag = true;
mm_er_ret = ozonedimsize_to_dimname.equal_range((*ird)->size);
for (irmm = mm_er_ret.first; irmm!=mm_er_ret.second;irmm++) {
setret = tempdimnamelist.insert(irmm->second);
if (true == setret.second) {
(*ird)->name = irmm->second;
(*ird)->newname = (*ird)->name;
setret = dimnamelist.insert((*ird)->name);
if(setret.second) Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
fakedimflag = false;
break;
}
}
if (true == fakedimflag) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
} // for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
tempdimnamelist.clear();
fakedimsize.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin();
} // else
}
// This is a special helper function for MeaSURES ozone products
bool GMFile::check_cv(string & varname) throw(Exception) {
const string lat_name ="Latitude";
const string time_name ="Time";
const string ratio_pressure_name ="MixingRatioPressureLevels";
const string profile_pressure_name ="ProfilePressureLevels";
const string wave_length_name ="Wavelength";
if (lat_name == varname)
return true;
else if (time_name == varname)
return true;
else if (ratio_pressure_name == varname)
return true;
else if (profile_pressure_name == varname)
return true;
else if (wave_length_name == varname)
return true;
else
return false;
}
// Add Dimension names for GPM products
void GMFile::Add_Dim_Name_GPM()throw(Exception)
{
// This is used to create a dimension name set.
pair<set<string>::iterator,bool> setret;
// The commented code is for an old version of GPM products. May remove them later. KY 2015-06-16
// One GPM variable (sunVectorInBodyFrame) misses an element for DimensionNames attributes.
// We need to create a fakedim name to fill in. To make the dimension name unique, we use a counter.
// int dim_count = 0;
// map<string,string> varname_to_fakedim;
// map<int,string> gpm_dimsize_to_fakedimname;
// We find that GPM has an attribute DimensionNames(nlon,nlat) in this case.
// We will use this attribute to specify the dimension names.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
bool has_dim_name_attr = false;
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
if("DimensionNames" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,(*irv)->fullpath);
string dimname_value((*ira)->value.begin(),(*ira)->value.end());
vector<string> ind_elems;
char sep=',';
HDF5CFUtil::Split(&dimname_value[0],sep,ind_elems);
if(ind_elems.size() != (size_t)((*irv)->getRank())) {
throw2("The number of dims obtained from the <DimensionNames> attribute is not equal to the rank ",
(*irv)->name);
}
for(unsigned int i = 0; i<ind_elems.size(); ++i) {
((*irv)->dims)[i]->name = ind_elems[i];
// Generate a dimension name is the dimension name is missing.
// The routine will ensure that the fakeDim name is unique.
if(((*irv)->dims)[i]->name==""){
Add_One_FakeDim_Name(((*irv)->dims)[i]);
// For debugging
#if 0
string fakedim = "FakeDim";
stringstream sdim_count;
sdim_count << dim_count;
fakedim = fakedim + sdim_count.str();
dim_count++;
((*irv)->dims)[i]->name = fakedim;
((*irv)->dims)[i]->newname = fakedim;
ind_elems[i] = fakedim;
#endif
}
else {
((*irv)->dims)[i]->newname = ind_elems[i];
setret = dimnamelist.insert(((*irv)->dims)[i]->name);
if (true == setret.second) {
Insert_One_NameSizeMap_Element(((*irv)->dims)[i]->name,
((*irv)->dims)[i]->size);
}
else {
if(dimname_to_dimsize[((*irv)->dims)[i]->name] !=((*irv)->dims)[i]->size)
throw5("Dimension ",((*irv)->dims)[i]->name, "has two sizes",
((*irv)->dims)[i]->size,dimname_to_dimsize[((*irv)->dims)[i]->name]);
}
}
}// for(unsigned int i = 0; i<ind_elems.size(); ++i)
has_dim_name_attr = true;
break;
} //if("DimensionNames" == (*ira)->name)
} //for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin()
#if 0
if(false == has_dim_name_attr) {
throw4( "The variable ", (*irv)->name, " doesn't have the DimensionNames attribute.",
"We currently don't support this case. Please report to the NASA data center.");
}
#endif
} //for (vector<Var *>::iterator irv = this->vars.begin();
}
// Add Dimension names for Aquarius level 3 products
void GMFile::Add_Dim_Name_Aqu_L3()throw(Exception)
{
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
if ("l3m_data" == (*irv)->name) {
((*irv)->dims)[0]->name = "lat";
((*irv)->dims)[0]->newname = "lat";
((*irv)->dims)[1]->name = "lon";
((*irv)->dims)[1]->newname = "lon";
break;
}
// For the time being, don't assign dimension names to palette,
// we will see if tools can pick up l3m and then make decisions.
#if 0
if ("palette" == (*irv)->name) {
//"h5","coming to palette" <<endl;
((*irv)->dims)[0]->name = "paldim0";
((*irv)->dims)[0]->newname = "paldim0";
((*irv)->dims)[1]->name = "paldim1";
((*irv)->dims)[1]->newname = "paldim1";
}
#endif
}// for (vector<Var *>::iterator irv = this->vars.begin()
}
// Add dimension names for SMAP(note: the SMAP may change their structures. The code may not apply to them.)
void GMFile::Add_Dim_Name_SMAP()throw(Exception){
string tempvarname ="";
string key = "_lat";
string smapdim0 ="YDim";
string smapdim1 ="XDim";
// Since the dim. size of each dimension of 2D lat/lon may be the same, so use multimap.
multimap<hsize_t,string> smapdimsize_to_dimname;
pair<multimap<hsize_t,string>::iterator,multimap<hsize_t,string>::iterator> mm_er_ret;
multimap<hsize_t,string>::iterator irmm;
// Generate dimension names based on the size of "???_lat"(one coordinate variable)
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
tempvarname = (*irv)->name;
if ((tempvarname.size() > key.size())&&
(key == tempvarname.substr(tempvarname.size()-key.size(),key.size()))){
//cerr<<"tempvarname " <<tempvarname <<endl;
if ((*irv)->dims.size() !=2)
throw1("Currently only 2D lat/lon is supported for SMAP");
smapdimsize_to_dimname.insert(pair<hsize_t,string>(((*irv)->dims)[0]->size,smapdim0));
smapdimsize_to_dimname.insert(pair<hsize_t,string>(((*irv)->dims)[1]->size,smapdim1));
break;
}
}
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
pair<set<string>::iterator,bool> setret;
pair<set<string>::iterator,bool> tempsetret;
set<string> tempdimnamelist;
bool fakedimflag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
fakedimflag = true;
mm_er_ret = smapdimsize_to_dimname.equal_range((*ird)->size);
for (irmm = mm_er_ret.first; irmm!=mm_er_ret.second;irmm++) {
setret = tempdimnamelist.insert(irmm->second);
if (setret.second) {
(*ird)->name = irmm->second;
(*ird)->newname = (*ird)->name;
setret = dimnamelist.insert((*ird)->name);
if(setret.second) Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
fakedimflag = false;
break;
}
}
if (true == fakedimflag) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (!setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
} // for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
tempdimnamelist.clear();
fakedimsize.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin();
}
//Add dimension names for ACOS level2S or OCO2 level1B products
void GMFile::Add_Dim_Name_ACOS_L2S_OCO2_L1B()throw(Exception){
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
}
// Add dimension names for general products.
void GMFile::Add_Dim_Name_General_Product()throw(Exception){
// Check attributes
Check_General_Product_Pattern();
// This general product should follow the HDF5 dimension scale model.
if (GENERAL_DIMSCALE == this->gproduct_pattern)
Add_Dim_Name_Dimscale_General_Product();
// This general product has 2-D latitude,longitude
else if (GENERAL_LATLON2D == this->gproduct_pattern)
Add_Dim_Name_LatLon2D_General_Product();
// This general product has 1-D latitude,longitude
else if (GENERAL_LATLON1D == this->gproduct_pattern)
Add_Dim_Name_LatLon1D_General_Product();
}
void GMFile::Check_General_Product_Pattern() throw(Exception) {
if(false == Check_Dimscale_General_Product_Pattern()) {
if(false == Check_LatLon2D_General_Product_Pattern())
if(false == Check_LatLon1D_General_Product_Pattern())
Check_LatLon_With_Coordinate_Attr_General_Product_Pattern();
}
}
// If having 2-D latitude/longitude,set the general product pattern.
// In this version, we only check if we have "latitude,longitude","Latitude,Longitude","lat,lon" and "cell_lat,cell_lon"names.
// The "cell_lat" and "cell_lon" come from SMAP. KY 2015-12-2
bool GMFile::Check_LatLon2D_General_Product_Pattern() throw(Exception) {
// bool ret_value = Check_LatLonName_General_Product(2);
bool ret_value = false;
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("latitude","longitude");
if(false == ret_value) {
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("Latitude","Longitude");
if(false == ret_value) {
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("lat","lon");
if(false == ret_value)
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("cell_lat","cell_lon");
}
}
if(true == ret_value)
this->gproduct_pattern = GENERAL_LATLON2D;
return ret_value;
}
bool GMFile::Check_LatLon2D_General_Product_Pattern_Name_Size(const string & latname,const string & lonname) throw(Exception) {
bool ret_value = false;
short ll_flag = 0;
vector<size_t>lat_size(2.0);
vector<size_t>lon_size(2,0);
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
if((*irv)->name == latname) {
string lat_path =HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
// Tackle only the root group or the name of the group as "/Geolocation"
if("/" == lat_path || "/Geolocation/" == lat_path) {
ll_flag++;
lat_size[0] = (*irv)->getDimensions()[0]->size;
lat_size[1] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == lonname) {
string lon_path = HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
if("/" == lon_path || "/Geolocation/" == lon_path) {
ll_flag++;
lon_size[0] = (*irv)->getDimensions()[0]->size;
lon_size[1] = (*irv)->getDimensions()[1]->size;
}
}
if(2 == ll_flag)
break;
}
}
if(2 == ll_flag) {
bool latlon_size_match = true;
for (int size_index = 0; size_index <lat_size.size();size_index++) {
if(lat_size[size_index] != lon_size[size_index]){
latlon_size_match = false;
break;
}
}
if (true == latlon_size_match) {
gp_latname = latname;
gp_lonname = lonname;
ret_value = true;
}
}
return ret_value;
}
#if 0
// If having 1-D latitude/longitude,set the general product pattern.
bool GMFile::Check_LatLon1D_General_Product_Pattern() throw(Exception) {
bool ret_value = Check_LatLonName_General_Product(1);
if(true == ret_value)
this->gproduct_pattern = GENERAL_LATLON1D;
return ret_value;
}
#endif
// If having 2-D latitude/longitude,set the general product pattern.
// In this version, we only check if we have "latitude,longitude","Latitude,Longitude","lat,lon" and "cell_lat,cell_lon"names.
// The "cell_lat" and "cell_lon" come from SMAP. KY 2015-12-2
bool GMFile::Check_LatLon1D_General_Product_Pattern() throw(Exception) {
// bool ret_value = Check_LatLonName_General_Product(2);
bool ret_value = false;
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("latitude","longitude");
if(false == ret_value) {
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("Latitude","Longitude");
if(false == ret_value) {
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("lat","lon");
if(false == ret_value)
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("cell_lat","cell_lon");
}
}
if(true == ret_value)
this->gproduct_pattern = GENERAL_LATLON1D;
return ret_value;
}
bool GMFile::Check_LatLon1D_General_Product_Pattern_Name_Size(const string & latname,const string & lonname) throw(Exception) {
bool ret_value = false;
short ll_flag = 0;
size_t lat_size = 0;
size_t lon_size = 0;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 1) {
if((*irv)->name == latname) {
string lat_path =HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
// Tackle only the root group or the name of the group as "/Geolocation"
if("/" == lat_path || "/Geolocation/" == lat_path) {
ll_flag++;
lat_size = (*irv)->getDimensions()[0]->size;
}
}
else if((*irv)->name == lonname) {
string lon_path = HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
if("/" == lon_path || "/Geolocation/" == lon_path) {
ll_flag++;
lon_size = (*irv)->getDimensions()[0]->size;
}
}
if(2 == ll_flag)
break;
}
}
if(2 == ll_flag) {
bool latlon_size_match_grid = true;
// When the size of latitude is equal to the size of longitude for a 1-D lat/lon, it is very possible
// that this is not a regular grid but rather a profile with the lat,lon to be recorded as the function of time.
// Adding the coordinate/dimension as the normal grid is wrong, so check out this case.
// KY 2015-12-2
if(lat_size == lon_size) {
// It is very unusual that lat_size = lon_size for a grid.
latlon_size_match_grid = false;
// For a normal grid, a >2D variable should exist to have both lat and lon size, if such a variable that has the same size exists, we
// will treat it as a normal grid.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank >=2) {
short ll_size_flag = 0;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
if(lat_size == (*ird)->size) {
ll_size_flag++;
if(2 == ll_size_flag){
break;
}
}
}
if(2 == ll_size_flag) {
latlon_size_match_grid = true;
break;
}
}
}
}
if (true == latlon_size_match_grid) {
gp_latname = latname;
gp_lonname = lonname;
ret_value = true;
}
}
return ret_value;
}
bool GMFile::Check_LatLon_With_Coordinate_Attr_General_Product_Pattern() throw(Exception) {
bool ret_value = false;
string co_attrname = "coordinates";
string co_attrvalue="";
string unit_attrname = "units";
string lat_unit_attrvalue ="degrees_north";
string lon_unit_attrvalue ="degrees_east";
bool coor_has_lat_flag = false;
bool coor_has_lon_flag = false;
vector<Var*> tempvar_lat;
vector<Var*> tempvar_lon;
// Check if having both lat, lon coordinate values.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank >=2) {
for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin();
ira !=(*irv)->attrs.end();++ira) {
if((*ira)->name == co_attrname) {
Retrieve_H5_Attr_Value((*ira),(*irv)->fullpath);
string orig_attr_value((*ira)->value.begin(),(*ira)->value.end());
vector<string> coord_values;
char sep=' ';
HDF5CFUtil::Split_helper(coord_values,orig_attr_value,sep);
for(vector<string>::iterator irs=coord_values.begin();irs!=coord_values.end();++irs)
cerr<<"coord value is "<<(*irs) <<endl;
for(vector<string>::iterator irs=coord_values.begin();irs!=coord_values.end();++irs) {
string coord_value_suffix1;
string coord_value_suffix2;
if((*irs).size() >=3) {
coord_value_suffix1 = (*irs).substr((*irs).size()-3,3);
if((*irs).size() >=6)
coord_value_suffix2 = (*irs).substr((*irs).size()-6,6);
}
if(coord_value_suffix1=="lat" || coord_value_suffix2 =="latitude" || coord_value_suffix2 == "Latitude")
coor_has_lat_flag = true;
else if(coord_value_suffix1=="lon" || coord_value_suffix2 =="longitude" || coord_value_suffix2 == "Longitude")
coor_has_lon_flag = true;
}
if(true == coor_has_lat_flag && true == coor_has_lon_flag)
break;
}
}
if(true == coor_has_lat_flag && true == coor_has_lon_flag)
break;
else {
coor_has_lat_flag = false;
coor_has_lon_flag = false;
}
}
}
// Check the variable names that include latitude and longitude suffixes such as lat,latitude and Latitude.
if(true == coor_has_lat_flag && true == coor_has_lon_flag) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool var_is_lat = false;
bool var_is_lon = false;
string varname = (*irv)->name;
string ll_ssuffix;
string ll_lsuffix;
if(varname.size() >=3) {
ll_ssuffix = varname.substr(varname.size()-3,3);
if(varname.size() >=6)
ll_lsuffix = varname.substr(varname.size()-6,6);
}
if(ll_ssuffix=="lat" || ll_lsuffix =="latitude" || ll_lsuffix == "Latitude")
var_is_lat = true;
else if(ll_ssuffix=="lon" || ll_lsuffix =="longitude" || ll_lsuffix == "Longitude")
var_is_lon = true;
if(true == var_is_lat) {
if((*irv)->rank > 0) {
Var * lat = new Var(*irv);
tempvar_lat.push_back(lat);
}
}
else if(true == var_is_lon) {
if((*irv)->rank >0) {
Var * lon = new Var(*irv);
tempvar_lon.push_back(lon);
}
}
}
// Build up lat/lon name-size struct,
// 1) Compare the rank, sizes and the orders of tempvar_lon against tempvar_lat
// rank >=2 the sizes,orders, should be consistent
// rank =1, no check issue.
// 2) If the condition is fulfilled, save them to the vector struct, also mark if more than lon is found,
// only pick up the correct one. If no correct one, remove this lat/lon.
for(vector<Var*>:: iterator irlat = tempvar_lat.begin(); irlat!=tempvar_lat.end();++irlat) {
cerr<<"lat variable name is "<<(*irlat)->fullpath <<endl;
set<string> lon_candidate_path;
for(vector<Var*>:: iterator irlon = tempvar_lon.begin(); irlon!=tempvar_lon.end();++irlon) {
cerr<<"lon variable name is "<<(*irlon)->fullpath <<endl;
if ((*irlat)->rank == (*irlon)->rank) {
if((*irlat)->rank == 1)
lon_candidate_path.insert((*irlon)->fullpath);
else { // Check the dim order and size.
bool same_dim = true;
for(int dim_index = 0; dim_index <(*irlat)->rank; dim_index++) {
if((*irlat)->getDimensions()[dim_index]->size !=
(*irlon)->getDimensions()[dim_index]->size){
same_dim = false;
break;
}
}
if(true == same_dim)
lon_candidate_path.insert((*irlon)->fullpath);
}
}
}
// Check the size of the lon., if the size is not 1, see if having the same path one.
if(lon_candidate_path.size() != 1) {
string lat_path = HDF5CFUtil::obtain_string_before_lastslash((*irlat)->fullpath);
string lon_final_candidate_path;
short num_lon_path = 0;
for(set<string>::iterator islon_path =lon_candidate_path.begin();islon_path!=lon_candidate_path.end();++islon_path) {
// Search the path.
if(HDF5CFUtil::obtain_string_before_lastslash((*islon_path))==lat_path) {
num_lon_path++;
if(1 == num_lon_path)
lon_final_candidate_path = *islon_path;
else if(num_lon_path > 1)
break;
}
}
if(num_lon_path ==1) {// insert this lat/lon pair to the struct
Name_Size_2Pairs latlon_pair;
latlon_pair.name1 = (*irlat)->fullpath;
latlon_pair.name2 = lon_final_candidate_path;
latlon_pair.size1 = (*irlat)->getDimensions()[0]->size;
latlon_pair.size2 = (*irlat)->getDimensions()[1]->size;
latlon_pair.rank = (*irlat)->rank;
latloncv_candidate_pairs.push_back(latlon_pair);
}
}
else {//insert this lat/lon pair to the struct
Name_Size_2Pairs latlon_pair;
latlon_pair.name1 = (*irlat)->fullpath;
// Find how to get the first element of the size TOOODOOO,comment out the following line
//latlon_pair.name2 = lon_candidate_path[0];
latlon_pair.size1 = (*irlat)->getDimensions()[0]->size;
latlon_pair.size2 = (*irlat)->getDimensions()[1]->size;
latlon_pair.rank = (*irlat)->rank;
latloncv_candidate_pairs.push_back(latlon_pair);
}
}
if(latloncv_candidate_pairs.size() >0) {
int num_1d_rank = 0;
int num_2d_rank = 0;
int num_g2d_rank = 0;
for(vector<struct Name_Size_2Pairs>::iterator ivs=latloncv_candidate_pairs.begin(); ivs!=latloncv_candidate_pairs.end();++ivs) {
if(1 == (*ivs).rank)
num_1d_rank++;
else if(2 == (*ivs).rank)
num_2d_rank++;
else if((*ivs).rank >2)
num_g2d_rank++;
else
;// throw an error
}
if (num_2d_rank !=0)
ret_value = true;
else if(num_1d_rank!=0) {
// Check if lat and lon shares the same size and the dimension of a variable that holds the coordinates only holds one size.
}
}
release_standalone_var_vector(tempvar_lat);
release_standalone_var_vector(tempvar_lon);
}
return false;
}
#if 0
// In this version, we only check if we have "latitude,longitude","Latitude,Longitude","lat,lon" names.
// This routine will check this case.
bool GMFile::Check_LatLonName_General_Product(int ll_rank) throw(Exception) {
if(ll_rank <1 || ll_rank >2)
throw2("Only support rank = 1 or 2 lat/lon case for the general product. The current rank is ",ll_rank);
bool ret_value = false;
size_t lat2D_dimsize0 = 0;
size_t lat2D_dimsize1 = 0;
size_t lon2D_dimsize0 = 0;
size_t lon2D_dimsize1 = 0;
// The element order is latlon_flag,latilong_flag and LatLon_flag.
vector<short>ll_flag(3,0);
vector<size_t>lat_size;
vector<size_t>lon_size;
// We only need to check 2-D latlon
if(2 == ll_rank) {
//lat/lon is 2-D array, so the size is doubled.
lat_size.assign(6,0);
lon_size.assign(6,0);
}
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == ll_rank) {
if((*irv)->name == "lat") {
ll_flag[0]++;
if(ll_rank == 2) {
lat_size[0] = (*irv)->getDimensions()[0]->size;
lat_size[1] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "lon") {
ll_flag[0]++;
if(ll_rank == 2) {
lon_size[0] = (*irv)->getDimensions()[0]->size;
lon_size[1] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "latitude"){
ll_flag[1]++;
if(ll_rank == 2) {
lat_size[2] = (*irv)->getDimensions()[0]->size;
lat_size[3] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "longitude"){
ll_flag[1]++;
if(ll_rank == 2) {
lon_size[2] = (*irv)->getDimensions()[0]->size;
lon_size[3] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "Latitude"){
ll_flag[2]++;
if(ll_rank == 2) {
lat_size[4] = (*irv)->getDimensions()[0]->size;
lat_size[5] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "Longitude"){
ll_flag[2]++;
if(ll_rank == 2) {
lon_size[4] = (*irv)->getDimensions()[0]->size;
lon_size[5] = (*irv)->getDimensions()[1]->size;
}
}
}
}
int total_llflag = 0;
for (int i = 0; i < ll_flag.size();i++)
if(2 == ll_flag[i])
total_llflag ++;
// We only support 1 (L)lat(i)/(L)lon(g) pair.
if(1 == total_llflag) {
bool latlon_size_match = true;
if(2 == ll_rank) {
for (int size_index = 0; size_index <lat_size.size();size_index++) {
if(lat_size[size_index] != lon_size[size_index]){
latlon_size_match = false;
break;
}
}
}
if(true == latlon_size_match) {
ret_value = true;
if(2 == ll_flag[0]) {
gp_latname = "lat";
gp_lonname = "lon";
}
else if ( 2 == ll_flag[1]) {
gp_latname = "latitude";
gp_lonname = "longitude";
}
else if (2 == ll_flag[2]){
gp_latname = "Latitude";
gp_lonname = "Longitude";
}
}
}
return ret_value;
}
#endif
// Add dimension names for the case that has 2-D lat/lon.
void GMFile::Add_Dim_Name_LatLon2D_General_Product() throw(Exception) {
//cerr<<"coming to Add_Dim_Name_LatLon2D_General_Product "<<endl;
// cerr<<"gp_latname is "<<gp_latname <<endl;
// cerr<<"gp_lonname is "<<gp_lonname <<endl;
string latdimname0,latdimname1;
size_t latdimsize0 = 0;
size_t latdimsize1 = 0;
// Need to generate fake dimensions.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
// Avoid the same size dimension sharing the same dimension name.
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
// Find variable name that is latitude or lat or Latitude
// Note that we don't need to check longitude since longitude dim. sizes should be the same as the latitude for this case.
if((*irv)->name == gp_latname) {
if((*irv)->rank != 2) {
throw4("coordinate variables ",gp_latname,
" must have rank 2 for the 2-D latlon case , the current rank is ",
(*irv)->rank);
}
latdimname0 = (*irv)->getDimensions()[0]->name;
latdimsize0 = (*irv)->getDimensions()[0]->size;
latdimname1 = (*irv)->getDimensions()[1]->name;
latdimsize1 = (*irv)->getDimensions()[1]->size;
}
}
//cerr<<"latdimname0 is "<<latdimname0 <<endl;
//cerr<<"latdimname1 is "<<latdimname1 <<endl;
//cerr<<"latdimsize0 is "<<latdimsize0 <<endl;
//cerr<<"latdimsize1 is "<<latdimsize1 <<endl;
//int lat_dim0_index = 0;
//int lat_dim1_index = 0;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
int lat_dim0_index = 0;
int lat_dim1_index = 0;
bool has_lat_dims_size = false;
for (int dim_index = 0; dim_index <(*irv)->dims.size(); dim_index++) {
// Find if having the first dimension size of lat
if(((*irv)->dims[dim_index])->size == latdimsize0) {
// Find if having the second dimension size of lat
lat_dim0_index = dim_index;
for(int dim_index2 = dim_index+1;dim_index2 < (*irv)->dims.size();dim_index2++) {
if(((*irv)->dims[dim_index2])->size == latdimsize1) {
lat_dim1_index = dim_index2;
has_lat_dims_size = true;
break;
}
}
}
if(true == has_lat_dims_size)
break;
}
// Find the lat's dimension sizes, change the (fake) dimension names.
if(true == has_lat_dims_size) {
((*irv)->dims[lat_dim0_index])->name = latdimname0;
//((*irv)->dims[lat_dim0_index])->newname = latdimname0;
((*irv)->dims[lat_dim1_index])->name = latdimname1;
//((*irv)->dims[lat_dim1_index])->newname = latdimname1;
}
}
//When we generate Fake dimensions, we may encounter discontiguous Fake dimension names such
// as FakeDim0, FakeDim9 etc. We would like to make Fake dimension names in contiguous order
// FakeDim0,FakeDim1,etc.
// Obtain the tempdimnamelist set.
set<string>tempdimnamelist;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird)
tempdimnamelist.insert((*ird)->name);
}
// Generate the final dimnamelist,it is a contiguous order: FakeDim0,FakeDim1 etc.
set<string>finaldimnamelist;
string finaldimname_base = "FakeDim";
for(int i = 0; i<tempdimnamelist.size();i++) {
stringstream sfakedimindex;
sfakedimindex << i;
string finaldimname = finaldimname_base + sfakedimindex.str();
finaldimnamelist.insert(finaldimname);
//cerr<<"finaldimname is "<<finaldimname <<endl;
}
// If the original tempdimnamelist is not the same as the finaldimnamelist,
// we need to generate a map from original name to the final name.
if(finaldimnamelist != tempdimnamelist) {
map<string,string> tempdimname_to_finaldimname;
set<string>:: iterator tempit = tempdimnamelist.begin();
set<string>:: iterator finalit = finaldimnamelist.begin();
while(tempit != tempdimnamelist.end()) {
tempdimname_to_finaldimname[*tempit] = *finalit;
//cerr<<"tempdimname again "<<*tempit <<endl;
//cerr<<"finalname again "<<*finalit <<endl;
tempit++;
finalit++;
}
//cerr<<"dim name map size is "<<tempdimname_to_finaldimname.size() <<endl;
// Change the dimension names of every variable to the final dimension name list.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
if(tempdimname_to_finaldimname.find((*ird)->name) !=tempdimname_to_finaldimname.end()){
(*ird)->name = tempdimname_to_finaldimname[(*ird)->name];
}
else
throw3("The dimension names ",(*ird)->name, "cannot be found in the dim. name list.");
}
}
}
dimnamelist.clear();
dimnamelist = finaldimnamelist;
// We need to update dimname_to_dimsize map. This may be used in the future.
dimname_to_dimsize.clear();
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
if(finaldimnamelist.find((*ird)->name)!=finaldimnamelist.end()) {
dimname_to_dimsize[(*ird)->name] = (*ird)->size;
finaldimnamelist.erase((*ird)->name);
}
}
if(true == finaldimnamelist.empty())
break;
}
// Finally set dimension newname
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
(*ird)->newname = (*ird)->name;
}
}
}
// Add dimension names for the case that has 1-D lat/lon.
void GMFile::Add_Dim_Name_LatLon1D_General_Product() throw(Exception) {
// Only need to add the fake dimension names
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
// Avoid the same size dimension sharing the same dimension name.
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
}
}
// Check if this general product is netCDF4-like HDF5 file.
// We only need to check "DIMENSION_LIST","CLASS" and CLASS values.
bool GMFile::Check_Dimscale_General_Product_Pattern() throw(Exception) {
bool ret_value = false;
bool has_dimlist = false;
bool has_dimscalelist = false;
// Check if containing the "DIMENSION_LIST" attribute;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name) {
has_dimlist = true;
break;
}
}
if (true == has_dimlist)
break;
}
// Check if containing both the attribute "CLASS" and the attribute "REFERENCE_LIST" for the same variable.
// This is the dimension scale.
// Actually "REFERENCE_LIST" is not necessary for a dimension scale dataset. If a dimension scale doesn't
// have a "REFERENCE_LIST", it is still valid. But no other variables use this dimension scale. We found
// such a case in a matched_airs_aqua product. KY 2012-12-03
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("CLASS" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,(*irv)->fullpath);
string class_value;
class_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),class_value.begin());
// Compare the attribute "CLASS" value with "DIMENSION_SCALE". We only compare the string with the size of
// "DIMENSION_SCALE", which is 15.
if (0 == class_value.compare(0,15,"DIMENSION_SCALE")) {
has_dimscalelist = true;
break;
}
}
}
if (true == has_dimscalelist)
break;
}
if (true == has_dimlist && true == has_dimscalelist) {
this->gproduct_pattern = GENERAL_DIMSCALE;
ret_value = true;
}
return ret_value;
}
void GMFile::Add_Dim_Name_Dimscale_General_Product() throw(Exception) {
//cerr<<"coming to Add_Dim_Name_Dimscale_General_Product"<<endl;
pair<set<string>::iterator,bool> setret;
this->iscoard = true;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
Handle_UseDimscale_Var_Dim_Names_General_Product((*irv));
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
if (true == dimnamelist.empty())
throw1("This product should have the dimension names, but no dimension names are found");
}
void GMFile::Handle_UseDimscale_Var_Dim_Names_General_Product(Var *var) throw(Exception) {
Attribute* dimlistattr = NULL;
bool has_dimlist = false;
bool has_dimclass = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name) {
dimlistattr = *ira;
has_dimlist = true;
}
if ("CLASS" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,var->fullpath);
string class_value;
class_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),class_value.begin());
// Compare the attribute "CLASS" value with "DIMENSION_SCALE". We only compare the string with the size of
// "DIMENSION_SCALE", which is 15.
if (0 == class_value.compare(0,15,"DIMENSION_SCALE")) {
has_dimclass = true;
break;
}
}
} // for(vector<Attribute *>::iterator ira = var->attrs.begin(); ...
// This is a general variable, we need to find the corresponding coordinate variables.
if (true == has_dimlist)
Add_UseDimscale_Var_Dim_Names_General_Product(var,dimlistattr);
// Dim name is the same as the variable name for dimscale variable
else if(true == has_dimclass) {
if (var->dims.size() !=1)
throw2("Currently dimension scale dataset must be 1 dimension, this is not true for the dataset ",
var->name);
// The var name is the object name, however, we would like the dimension name to be the full path.
// so that the dim name can be served as the key for future handling.
(var->dims)[0]->name = var->fullpath;
(var->dims)[0]->newname = var->fullpath;
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((var->dims)[0]->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((var->dims)[0]->name,(var->dims)[0]->size);
}
// No dimension, add fake dim names, this will rarely happen.
else {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= var->dims.begin();
ird != var->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
// Avoid the same size dimension sharing the same dimension name.
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
}
}
// Add dimension names for the case when HDF5 dimension scale is followed(netCDF4-like)
void GMFile::Add_UseDimscale_Var_Dim_Names_General_Product(Var *var,Attribute*dimlistattr)
throw (Exception){
ssize_t objnamelen = -1;
hobj_ref_t rbuf;
//hvl_t *vlbuf = NULL;
vector<hvl_t> vlbuf;
hid_t dset_id = -1;
hid_t attr_id = -1;
hid_t atype_id = -1;
hid_t amemtype_id = -1;
hid_t aspace_id = -1;
hid_t ref_dset = -1;
if(NULL == dimlistattr)
throw2("Cannot obtain the dimension list attribute for variable ",var->name);
if (0==var->rank)
throw2("The number of dimension should NOT be 0 for the variable ",var->name);
try {
//vlbuf = new hvl_t[var->rank];
vlbuf.resize(var->rank);
dset_id = H5Dopen(this->fileid,(var->fullpath).c_str(),H5P_DEFAULT);
if (dset_id < 0)
throw2("Cannot open the dataset ",var->fullpath);
attr_id = H5Aopen(dset_id,(dimlistattr->name).c_str(),H5P_DEFAULT);
if (attr_id <0 )
throw4("Cannot open the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
atype_id = H5Aget_type(attr_id);
if (atype_id <0)
throw4("Cannot obtain the datatype of the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
amemtype_id = H5Tget_native_type(atype_id, H5T_DIR_ASCEND);
if (amemtype_id < 0)
throw2("Cannot obtain the memory datatype for the attribute ",dimlistattr->name);
if (H5Aread(attr_id,amemtype_id,&vlbuf[0]) <0)
throw2("Cannot obtain the referenced object for the variable ",var->name);
vector<char> objname;
int vlbuf_index = 0;
// The dimension names of variables will be the HDF5 dataset names dereferenced from the DIMENSION_LIST attribute.
for (vector<Dimension *>::iterator ird = var->dims.begin();
ird != var->dims.end(); ++ird) {
rbuf =((hobj_ref_t*)vlbuf[vlbuf_index].p)[0];
if ((ref_dset = H5Rdereference(attr_id, H5R_OBJECT, &rbuf)) < 0)
throw2("Cannot dereference from the DIMENSION_LIST attribute for the variable ",var->name);
if ((objnamelen= H5Iget_name(ref_dset,NULL,0))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
objname.resize(objnamelen+1);
if ((objnamelen= H5Iget_name(ref_dset,&objname[0],objnamelen+1))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
string objname_str = string(objname.begin(),objname.end());
// We need to remove the first character of the object name since the first character
// of the object full path is always "/" and this will be changed to "_".
// The convention of handling the dimension-scale general product is to remove the first "_".
// Check the get_CF_string function of HDF5GMCF.cc.
string trim_objname = objname_str.substr(0,objnamelen);
(*ird)->name = string(trim_objname.begin(),trim_objname.end());
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
(*ird)->newname = (*ird)->name;
H5Dclose(ref_dset);
ref_dset = -1;
objname.clear();
vlbuf_index++;
}// for (vector<Dimension *>::iterator ird = var->dims.begin()
if(vlbuf.size()!= 0) {
if ((aspace_id = H5Aget_space(attr_id)) < 0)
throw2("Cannot get hdf5 dataspace id for the attribute ",dimlistattr->name);
if (H5Dvlen_reclaim(amemtype_id,aspace_id,H5P_DEFAULT,(void*)&vlbuf[0])<0)
throw2("Cannot successfully clean up the variable length memory for the variable ",var->name);
H5Sclose(aspace_id);
}
H5Tclose(atype_id);
H5Tclose(amemtype_id);
H5Aclose(attr_id);
H5Dclose(dset_id);
// if(vlbuf != NULL)
// delete[] vlbuf;
}
catch(...) {
if(atype_id != -1)
H5Tclose(atype_id);
if(amemtype_id != -1)
H5Tclose(amemtype_id);
if(aspace_id != -1)
H5Sclose(aspace_id);
if(attr_id != -1)
H5Aclose(attr_id);
if(dset_id != -1)
H5Dclose(dset_id);
//if(vlbuf != NULL)
// delete[] vlbuf;
//throw1("Error in method GMFile::Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone");
throw;
}
}
// Handle coordinate variables
void GMFile::Handle_CVar() throw(Exception){
// No coordinate variables are generated for ACOS_L2S or OCO2_L1B
// Currently we support the three patterns for the general products:
// 1) Dimensions follow HDF5 dimension scale specification
// 2) Dimensions don't follow HDF5 dimension scale specification but have 1D lat/lon
// 3) Dimensions don't follow HDF5 dimension scale specification bu have 2D lat/lon
if (General_Product == this->product_type ||
ACOS_L2S_OR_OCO2_L1B == this->product_type) {
if (GENERAL_DIMSCALE == this->gproduct_pattern)
Handle_CVar_Dimscale_General_Product();
else if (GENERAL_LATLON1D == this->gproduct_pattern)
Handle_CVar_LatLon1D_General_Product();
else if (GENERAL_LATLON2D == this->gproduct_pattern)
Handle_CVar_LatLon2D_General_Product();
return;
}
else if (Mea_SeaWiFS_L2 == this->product_type ||
Mea_SeaWiFS_L3 == this->product_type)
Handle_CVar_Mea_SeaWiFS();
else if (Aqu_L3 == this->product_type)
Handle_CVar_Aqu_L3();
else if (OBPG_L3 == this->product_type)
Handle_CVar_OBPG_L3();
else if (SMAP == this->product_type)
Handle_CVar_SMAP();
else if (Mea_Ozone == this->product_type)
Handle_CVar_Mea_Ozone();
else if (GPMS_L3 == this->product_type || GPMM_L3 == this->product_type)
Handle_CVar_GPM_L3();
else if (GPM_L1 == this->product_type)
Handle_CVar_GPM_L1();
}
// Handle GPM level 1 coordinate variables
void GMFile::Handle_CVar_GPM_L1() throw(Exception) {
#if 0
// Loop through the variable list to build the coordinates.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->name=="AlgorithmRuntimeInfo") {
delete(*irv);
this->vars.erase(irv);
break;
}
}
#endif
// Loop through all variables to check 2-D "Latitude" and "Longitude".
// Create coordinate variables based on 2-D "Latitude" and "Longitude".
// Latitude[Xdim][YDim] Longitude[Xdim][YDim], Latitude <->Xdim, Longitude <->YDim.
// Make sure to build cf dimension names cfdimname = latpath+ the lat dimension name.
// We want to save dimension names of Latitude and Longitude since
// the Fake coordinate variables of these two dimensions should not be generated.
// So we need to remember these dimension names.
//string ll_dim0,ll_dim1;
set<string> ll_dim_set;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if((*irv)->rank == 2 && (*irv)->name == "Latitude") {
GMCVar* GMcvar = new GMCVar(*irv);
size_t lat_pos = (*irv)->fullpath.rfind("Latitude");
string lat_path = (*irv)->fullpath.substr(0,lat_pos);
GMcvar->cfdimname = lat_path + ((*irv)->dims)[0]->name;
//ll_dim0 = ((*irv)->dims)[0]->name;
ll_dim_set.insert(((*irv)->dims)[0]->name);
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
}
if((*irv)->rank == 2 && (*irv)->name == "Longitude") {
GMCVar* GMcvar = new GMCVar(*irv);
size_t lon_pos = (*irv)->fullpath.rfind("Longitude");
string lon_path = (*irv)->fullpath.substr(0,lon_pos);
GMcvar->cfdimname = lon_path + ((*irv)->dims)[1]->name;
ll_dim_set.insert(((*irv)->dims)[1]->name);
//ll_dim1 = ((*irv)->dims)[1]->name;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
}
else {
++irv;
}
}// for (vector<Var *>::iterator irv = this->vars.begin();...
#if 0
// Loop through all variables and create a dim set.
set<string> cvdimset;
pair<set<string>::iterator,bool> setret;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for(vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
setret = cvdimset.insert((*ird)->name);
cerr<<"var name is "<<(*irv)->fullpath <<endl;
if (true == setret.second) {
cerr<<"dim name is "<<(*ird)->name <<endl;
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
}
}// for (vector<Var *>::iterator irv = this->vars.begin();...
#endif
// For each dimension, create a coordinate variable.
// Here we just need to loop through the map dimname_to_dimsize,
// use the name and the size to create coordinate variables.
for (map<string,hsize_t>::const_iterator itd = dimname_to_dimsize.begin();
itd!=dimname_to_dimsize.end();++itd) {
// We will not create fake coordinate variables for the
// dimensions of latitude and longitude.
if((ll_dim_set.find(itd->first)) == ll_dim_set.end()) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,itd->first);
this->cvars.push_back(GMcvar);
}
}//for (map<string,hsize_t>::iterator itd = dimname_to_dimsize.begin(); ...
}
// Handle coordinate variables for GPM level 3
void GMFile::Handle_CVar_GPM_L3() throw(Exception){
iscoard = true;
//map<string,hsize_t>::iterator itd;
// Here we just need to loop through the map dimname_to_dimsize,
// use the name and the size to create coordinate variables.
for (map<string,hsize_t>::const_iterator itd = dimname_to_dimsize.begin();
itd!=dimname_to_dimsize.end();++itd) {
GMCVar*GMcvar = new GMCVar();
if("nlon" == itd->first || "nlat" == itd->first
|| "lnH" == itd->first || "ltH" == itd->first
|| "lnL" == itd->first || "ltL" == itd->first) {
GMcvar->name = itd->first;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5FLOAT32;
Dimension* gmcvar_dim = new Dimension(itd->second);
gmcvar_dim->name = GMcvar->name;
gmcvar_dim->newname = gmcvar_dim->name;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = gmcvar_dim->name;
if ("nlat" ==GMcvar->name || "ltH" == GMcvar->name
|| "ltL" == GMcvar->name)
GMcvar->cvartype = CV_LAT_MISS;
else if ("nlon" == GMcvar->name || "lnH" == GMcvar->name
|| "lnL" == GMcvar->name)
GMcvar->cvartype = CV_LON_MISS;
GMcvar->product_type = product_type;
}
else if (("nlayer" == itd->first && 28 == itd->second) ||
("hgt" == itd->first && 5 == itd->second) ||
("nalt" == itd->first && 5 == itd->second)){
GMcvar->name = itd->first;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5FLOAT32;
Dimension* gmcvar_dim = new Dimension(itd->second);
gmcvar_dim->name = GMcvar->name;
gmcvar_dim->newname = gmcvar_dim->name;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = gmcvar_dim->name;
GMcvar->cvartype = CV_SPECIAL;
GMcvar->product_type = product_type;
}
else
Create_Missing_CV(GMcvar,itd->first);
this->cvars.push_back(GMcvar);
}//for (map<string,hsize_t>::iterator itd = dimname_to_dimsize.begin(); ...
}
// Handle Coordinate variables for MeaSuRES SeaWiFS
void GMFile::Handle_CVar_Mea_SeaWiFS() throw(Exception){
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();++irs) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if ((*irs)== (*irv)->fullpath) {
if (!iscoard && (("/natrack" == (*irs))
|| "/nxtrack" == (*irs))) {
++irv;
continue;
}
if((*irv)->dims.size()!=1)
throw3("Coard coordinate variable ",(*irv)->name, "is not 1D");
// Create Coordinate variables.
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
} // if ((*irs)== (*irv)->fullpath)
else if(false == iscoard) {
// 2-D lat/lon, natrack maps to lat, nxtrack maps to lon.
if ((((*irs) =="/natrack") && ((*irv)->fullpath == "/latitude"))
||(((*irs) =="/nxtrack") && ((*irv)->fullpath == "/longitude"))) {
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
}
else {
++irv;
}
}// else if(false == iscoard)
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin() ...
} // for (set<string>::iterator irs = dimnamelist.begin() ...
// Creating the missing "third-dimension" according to the dimension names.
// This may never happen for the current MeaSure SeaWiFS, but put it here for code coherence and completeness.
// KY 12-30-2011
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();++irs) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle Coordinate varibles for SMAP(Note: this may be subject to change since SMAP products may have new structures)
void GMFile::Handle_CVar_SMAP() throw(Exception) {
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
string tempvarname;
string key0 = "_lat";
string key1 = "_lon";
string smapdim0 ="YDim";
string smapdim1 ="XDim";
bool foundkey0 = false;
bool foundkey1 = false;
set<string> itset;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
tempvarname = (*irv)->name;
if ((tempvarname.size() > key0.size())&&
(key0 == tempvarname.substr(tempvarname.size()-key0.size(),key0.size()))){
foundkey0 = true;
if (dimnamelist.find(smapdim0)== dimnamelist.end())
throw5("variable ",tempvarname," must have dimension ",smapdim0," , but not found ");
tempdimnamelist.erase(smapdim0);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->newname = GMcvar->name; // Remove the path, just use the variable name
GMcvar->cfdimname = smapdim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
// irv--;
}// if ((tempvarname.size() > key0.size())&& ...
else if ((tempvarname.size() > key1.size())&&
(key1 == tempvarname.substr(tempvarname.size()-key1.size(),key1.size()))){
foundkey1 = true;
if (dimnamelist.find(smapdim1)== dimnamelist.end())
throw5("variable ",tempvarname," must have dimension ",smapdim1," , but not found ");
tempdimnamelist.erase(smapdim1);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->newname = GMcvar->name;
GMcvar->cfdimname = smapdim1;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
// irv--;
}// else if ((tempvarname.size() > key1.size())&& ...
else {
++irv;
}
if (true == foundkey0 && true == foundkey1)
break;
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();++irs) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle coordinate variables for Aquarius level 3 products
void GMFile::Handle_CVar_Aqu_L3() throw(Exception) {
iscoard = true;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if ( "l3m_data" == (*irv)->name) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
GMCVar*GMcvar = new GMCVar();
GMcvar->name = (*ird)->name;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5FLOAT32;
Dimension* gmcvar_dim = new Dimension((*ird)->size);
gmcvar_dim->name = GMcvar->name;
gmcvar_dim->newname = gmcvar_dim->name;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = gmcvar_dim->name;
if ("lat" ==GMcvar->name ) GMcvar->cvartype = CV_LAT_MISS;
if ("lon" == GMcvar->name ) GMcvar->cvartype = CV_LON_MISS;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
} // for (vector<Dimension *>::iterator ird = (*irv)->dims.begin(); ...
} // if ( "l3m_data" == (*irv)->name)
}//for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
//Handle coordinate variables for MeaSuRES Ozone products
void GMFile::Handle_CVar_Mea_Ozone() throw(Exception){
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
if(false == iscoard)
throw1("Measure Ozone level 3 zonal average product must follow COARDS conventions");
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();++irs) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if ((*irs)== (*irv)->fullpath) {
if((*irv)->dims.size()!=1)
throw3("Coard coordinate variable",(*irv)->name, "is not 1D");
// Create Coordinate variables.
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
} // if ((*irs)== (*irv)->fullpath)
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
} // for (set<string>::iterator irs = dimnamelist.begin();
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();irs++) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle coordinate variables for general products that use HDF5 dimension scales.
void GMFile::Handle_CVar_Dimscale_General_Product() throw(Exception) {
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();++irs) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
// This is the dimension scale dataset; it should be changed to a coordinate variable.
if ((*irs)== (*irv)->fullpath) {
if((*irv)->dims.size()!=1)
throw3("COARDS coordinate variable",(*irv)->name, "is not 1D");
// Create Coordinate variables.
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
// Check if this is just a netCDF-4 dimension.
bool is_netcdf_dimension = Is_netCDF_Dimension(*irv);
// If this is just the netcdf dimension, we
// will fill in the index numbers.
if (true == is_netcdf_dimension)
GMcvar->cvartype = CV_FILLINDEX;
else
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
} // if ((*irs)== (*irv)->fullpath)
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
} // for (set<string>::iterator irs = dimnamelist.begin();
/// Comment out the following code because we are using a more general approach
#if 0
// Will check if this file has 2-D lat/lon.If yes, update the CV.
string latname,lonname;
bool latlon_2d_cv = Check_2DLatLon_Dimscale(latname, lonname);
if( true == latlon_2d_cv) {
Update_2DLatLon_Dimscale_CV(latname,lonname);
}
#endif
// Check if we have 2-D lat/lon CVs, and if yes, add those to the CV list.
Update_M2DLatLon_Dimscale_CVs();
// Add other missing coordinate variables.
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();irs++) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
//Debugging
#if 0
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();irs++) {
cerr<<"dimension name is "<<(*irs)<<endl;
}
#endif
}
// Check if we have 2-D lat/lon CVs, and if yes, add those to the CV list.
void GMFile::Update_M2DLatLon_Dimscale_CVs() throw(Exception) {
// If this is not a file that only includes 1-D lat/lon CVs
if(false == Check_1DGeolocation_Dimscale()) {
//if(iscoard == true)
//cerr<<"COARD is true at the beginning of Update"<<endl;
//cerr<<"File path is "<<this->path <<endl;
// Define temporary vectors to store 1-D lat/lon CVs
vector<GMCVar*> tempcvar_1dlat;
vector<GMCVar*> tempcvar_1dlon;
// 1. Obtain 1-D lat/lon CVs(only search the CF units and the reserved lat/lon names)
Obtain_1DLatLon_CVs(tempcvar_1dlat,tempcvar_1dlon);
// Define temporary vectors to store 2-D lat/lon Vars
vector<Var*> tempcvar_2dlat;
vector<Var*> tempcvar_2dlon;
// TODO: Add descriptions
// This map remembers the positions of the latlon vars in the vector var.
// Remembering the positions avoids the searching of these lat and lon again when
// deleting them for the var vector and adding them(only the CVs) to the CV vector.
// KY 2015-12-23
map<string,int> latlon2d_path_to_index;
// 2. Obtain 2-D lat/lon variables(only search the CF units and the reserved names)
Obtain_2DLatLon_Vars(tempcvar_2dlat,tempcvar_2dlon,latlon2d_path_to_index);
#if 0
for(vector<GMCVar *>::iterator irv = tempcvar_1dlat.begin();irv != tempcvar_1dlat.end();++irv)
cerr<<"1-D lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<GMCVar *>::iterator irv = tempcvar_1dlon.begin();irv != tempcvar_1dlon.end();++irv)
cerr<<"1-D lon variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv)
cerr<<"2-D lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv)
cerr<<"2-D lon variable full path is "<<(*irv)->fullpath <<endl;
#endif
// 3. Sequeeze the 2-D lat/lon vectors by removing the ones that share the same dims with 1-D lat/lon CVs.
Obtain_2DLLVars_With_Dims_not_1DLLCVars(tempcvar_2dlat,tempcvar_2dlon,tempcvar_1dlat,tempcvar_1dlon,latlon2d_path_to_index);
#if 0
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv)
cerr<<"2-D Left lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv)
cerr<<"2-D Left lon variable full path is "<<(*irv)->fullpath <<endl;
#endif
// 4. Assemble the final 2-D lat/lon CV candidate vectors by checking if the corresponding 2-D lon of a 2-D lat shares
// the same dimension and under the same group and if there is another pair of 2-D lat/lon under the same group.
Obtain_2DLLCVar_Candidate(tempcvar_2dlat,tempcvar_2dlon,latlon2d_path_to_index);
#if 0
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv)
cerr<<"Final candidate 2-D Left lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv)
cerr<<"Final candidate 2-D Left lon variable full path is "<<(*irv)->fullpath <<endl;
#endif
// 5. Remove the 2-D lat/lon variables that are to be used as CVs from the vector that stores general variables
// var2d_index remembers the index of the 2-D lat/lon CVs in the original vector of vars.
vector<int> var2d_index;
for (map<string,int>::const_iterator it= latlon2d_path_to_index.begin();it!=latlon2d_path_to_index.end();++it)
var2d_index.push_back(it->second);
Remove_2DLLCVar_Final_Candidate_from_Vars(var2d_index);
// 6. If we have 2-D CVs, COARDS should be turned off.
if(tempcvar_2dlat.size()>0)
iscoard = false;
// 7. Add the CVs based on the final 2-D lat/lon CV candidates.
// We need to remember the dim names that the 2-D lat/lon CVs are associated with.
set<string>dim_names_2d_cvs;
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv){
//cerr<<"3 2-D Left lat variable full path is "<<(*irv)->fullpath <<endl;
GMCVar *lat = new GMCVar((*irv));
// Latitude is always corresponding to the first dimension.
lat->cfdimname = (*irv)->getDimensions()[0]->name;
dim_names_2d_cvs.insert(lat->cfdimname);
lat->cvartype = CV_EXIST;
lat->product_type = product_type;
this->cvars.push_back(lat);
}
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv){
//cerr<<"3 2-D Left lon variable full path is "<<(*irv)->fullpath <<endl;
GMCVar *lon = new GMCVar((*irv));
// Longitude is always corresponding to the second dimension.
lon->cfdimname = (*irv)->getDimensions()[1]->name;
dim_names_2d_cvs.insert(lon->cfdimname);
lon->cvartype = CV_EXIST;
lon->product_type = product_type;
this->cvars.push_back(lon);
}
// 8. Move the originally assigned 1-D CVs that are replaced by 2-D CVs back to the general variable list.
// Also remove the CV created by the pure dimensions.
// Dimension names are used to identify those 1-D CVs.
for(vector<GMCVar*>::iterator ircv= this->cvars.begin();ircv !=this->cvars.end();) {
if(1 == (*ircv)->rank) {
if(dim_names_2d_cvs.find((*ircv)->cfdimname)!=dim_names_2d_cvs.end()) {
if(CV_FILLINDEX == (*ircv)->cvartype) {// This is pure dimension
delete(*ircv);
ircv = this->cvars.erase(ircv);
}
else if(CV_EXIST == (*ircv)->cvartype) {// This var exists already
// Add this var. to the var list.
Var *var = new Var((*ircv));
this->vars.push_back(var);
// Remove this var. from the GMCVar list.
delete(*ircv);
ircv = this->cvars.erase(ircv);
}
else {// the removed 1-D coordinate variable should be either the CV_FILLINDEX or CV_EXIST.
if(CV_LAT_MISS == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_LAT_MISS");
else if(CV_LON_MISS == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_LON_MISS");
else if(CV_NONLATLON_MISS == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_NONLATLON_MISS");
else if(CV_MODIFY == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_MODIFY");
else if(CV_SPECIAL == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_SPECIAL");
else
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_UNSUPPORTED");
}
}
else
++ircv;
}
else
++ircv;
}
#if 0
//if(iscoard == true)
//cerr<<"COARD is true"<<endl;
for(set<string>::iterator irs = grp_cv_paths.begin();irs != grp_cv_paths.end();++irs) {
cerr<<"group path is "<< (*irs)<<endl;
}
#endif
#if 0
//Print CVs
cerr<<"File name is "<< this->path <<endl;
cerr<<"CV names are the following "<<endl;
for (vector<GMCVar *>:: iterator i= this->cvars.begin(); i!=this->cvars.end(); ++i)
cerr<<(*i)->fullpath <<endl;
#endif
// 6. release the resources allocated by the temporary vectors.
release_standalone_GMCVar_vector(tempcvar_1dlat);
release_standalone_GMCVar_vector(tempcvar_1dlon);
release_standalone_var_vector(tempcvar_2dlat);
release_standalone_var_vector(tempcvar_2dlon);
}
}
// If Check_1DGeolocation_Dimscale() is true, no need to build 2-D lat/lon coordinate variables.
// This function is introduced to avoid the performance penalty caused by handling the general 2-D lat/lon case.
bool GMFile::Check_1DGeolocation_Dimscale() throw(Exception) {
bool has_only_1d_geolocation_cv = false;
bool has_1d_lat_cv_flag = false;
bool has_1d_lon_cv_flag = false;
string lat_dimname;
hsize_t lat_size = 0;
string lon_dimname;
hsize_t lon_size = 0;
// We need to consider both 1-D lat/lon and the 1-D zonal average case(1-D lat only).
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
string attr_name ="units";
string lat_unit_value = "degrees_north";
string lon_unit_value = "degrees_east";
for(vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end();ira++) {
if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lat_unit_value)) {
lat_size = (*ircv)->getDimensions()[0]->size;
lat_dimname = (*ircv)->getDimensions()[0]->name;
has_1d_lat_cv_flag = true;
break;
}
else if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lon_unit_value)){
lon_size = (*ircv)->getDimensions()[0]->size;
lon_dimname = (*ircv)->getDimensions()[0]->name;
has_1d_lon_cv_flag = true;
break;
}
}
}
}
// If having 1-D lat/lon CVs, this is a good sign for only 1-D lat/lon CVs ,
// just need to have a couple of checks.
if(true == has_1d_lat_cv_flag ) {
if(true == has_1d_lon_cv_flag) {
//cerr<<"BOTH 1-D lat/lon CVs are true "<<endl;
// Come to the possible classic netCDF-4 case,
if(0 == this->groups.size()) {
// Rarely happens when lat_size is the same as the lon_size.
// However, still want to make sure there is a 2-D variable that uses both lat and lon dims.
if(lat_size == lon_size) {
bool var_has_latdim = false;
bool var_has_londim = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank >= 2) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
if((*ird)->name == lat_dimname)
var_has_latdim = true;
else if((*ird)->name == lon_dimname)
var_has_londim = true;
}
if(true == var_has_latdim && true == var_has_londim) {
has_only_1d_geolocation_cv = true;
break;
}
else {
var_has_latdim = false;
var_has_londim = false;
}
}
}
}
else
has_only_1d_geolocation_cv = true;
}
else {
// Multiple groups, need to check if having 2-D lat/lon pairs
bool has_2d_latname_flag = false;
bool has_2d_lonname_flag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
//Note: When the 2nd parameter is true in the function Is_geolatlon, it checks the lat/latitude/Latitude
if(true == Is_geolatlon((*irv)->name,true))
has_2d_latname_flag = true;
//Note: When the 2nd parameter is false in the function Is_geolatlon, it checks the lon/longitude/Longitude
else if(true == Is_geolatlon((*irv)->name,false))
has_2d_lonname_flag = true;
if((true == has_2d_latname_flag) && (true == has_2d_lonname_flag))
break;
}
}
if(has_2d_latname_flag != true || has_2d_lonname_flag != true) {
//Check if having the 2-D lat/lon by checking if having lat/lon CF units(lon's units: degrees_east lat's units: degrees_north)
has_2d_latname_flag = false;
has_2d_lonname_flag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
if (false == has_2d_latname_flag) {
// When the third parameter of the function has_latlon_cf_units is set to true, it checks latitude
has_2d_latname_flag = has_latlon_cf_units((*ira),(*irv)->fullpath,true);
if(true == has_2d_latname_flag)
break;
else if(false == has_2d_lonname_flag) {
// When the third parameter of the function has_latlon_cf_units is set to false, it checks longitude
has_2d_lonname_flag = has_latlon_cf_units((*ira),(*irv)->fullpath,false);
if(true == has_2d_lonname_flag)
break;
}
}
else if(false == has_2d_lonname_flag) {
// Now has_2d_latname_flag is true, just need to check the has_2d_lonname_flag
// When the third parameter of has_latlon_cf_units is set to false, it checks longitude
has_2d_lonname_flag = has_latlon_cf_units((*ira),(*irv)->fullpath,false);
if(true == has_2d_lonname_flag)
break;
}
}
if(true == has_2d_latname_flag && true == has_2d_lonname_flag)
break;
}
}
}
// If we cannot find either of 2-D any lat/lon variables, this file is treated as having only 1-D lat/lon.
if(has_2d_latname_flag != true || has_2d_lonname_flag != true)
has_only_1d_geolocation_cv = true;
}
}//
else {//Zonal average case, we do not need to find 2-D lat/lon CVs.
has_only_1d_geolocation_cv = true;
}
}
#if 0
if(has_only_1d_geolocation_cv == true)
cerr <<"has only 1D lat/lon CVs. "<<endl;
else
cerr<<"Possibly has 2D lat/lon CVs. "<<endl;
#endif
return has_only_1d_geolocation_cv;
}
// Obtain the originally assigned 1-D lat/lon coordinate variables.
// This function should be used before generating any 2-D lat/lon CVs.
void GMFile::Obtain_1DLatLon_CVs(vector<GMCVar*> &cvar_1dlat,vector<GMCVar*> &cvar_1dlon) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
string attr_name ="units";
string lat_unit_value = "degrees_north";
string lon_unit_value = "degrees_east";
for(vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end();ira++) {
// 1-D latitude
if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lat_unit_value)) {
GMCVar *lat = new GMCVar((*ircv));
lat->cfdimname = (*ircv)->getDimensions()[0]->name;
lat->cvartype = (*ircv)->cvartype;
lat->product_type = (*ircv)->product_type;
cvar_1dlat.push_back(lat);
}
// 1-D longitude
else if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lon_unit_value)){
GMCVar *lon = new GMCVar((*ircv));
lon->cfdimname = (*ircv)->getDimensions()[0]->name;
lon->cvartype = (*ircv)->cvartype;
lon->product_type = (*ircv)->product_type;
cvar_1dlon.push_back(lon);
}
}
}
}
}
// Obtain all 2-D lat/lon variables.
// Latitude variables are saved in the vector var_2dlat. Longitude variables are saved in the vector var_2dlon.
// We also remember the index of these lat/lon in the original var vector.
void GMFile::Obtain_2DLatLon_Vars(vector<Var*> &var_2dlat,vector<Var*> &var_2dlon,map<string,int> & latlon2d_path_to_index) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
//Note: When the 2nd parameter is true in the function Is_geolatlon, it checks the lat/latitude/Latitude
if(true == Is_geolatlon((*irv)->name,true)) {
Var *lat = new Var((*irv));
var_2dlat.push_back(lat);
latlon2d_path_to_index[(*irv)->fullpath]= distance(this->vars.begin(),irv);
continue;
}
else {
bool has_2dlat = false;
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
// When the third parameter of has_latlon_cf_units is set to true, it checks latitude
if(true == has_latlon_cf_units((*ira),(*irv)->fullpath,true)) {
Var *lat = new Var((*irv));
var_2dlat.push_back(lat);
latlon2d_path_to_index[(*irv)->fullpath] = distance(this->vars.begin(),irv);
has_2dlat = true;
break;
}
}
if(true == has_2dlat)
continue;
}
//Note: When the 2nd parameter is false in the function Is_geolatlon, it checks the lon/longitude/Longitude
if(true == Is_geolatlon((*irv)->name,false)) {
Var *lon = new Var((*irv));
latlon2d_path_to_index[(*irv)->fullpath] = distance(this->vars.begin(),irv);
var_2dlon.push_back(lon);
}
else {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
// When the third parameter of has_latlon_cf_units is set to false, it checks longitude
if(true == has_latlon_cf_units((*ira),(*irv)->fullpath,false)) {
Var *lon = new Var((*irv));
latlon2d_path_to_index[(*irv)->fullpath] = distance(this->vars.begin(),irv);
var_2dlon.push_back(lon);
break;
}
}
}
}
}
}
// Sequeeze the 2-D lat/lon vectors by removing the ones that share the same dims with 1-D lat/lon CVs.
// The latlon2d_path_to_index map also needs to be updated.
void GMFile::Obtain_2DLLVars_With_Dims_not_1DLLCVars(vector<Var*> &var_2dlat,
vector<Var*> &var_2dlon,
vector<GMCVar*> &cvar_1dlat,
vector<GMCVar*> &cvar_1dlon,
map<string,int> &latlon2d_path_to_index) {
for(vector<Var *>::iterator irv = var_2dlat.begin();irv != var_2dlat.end();) {
bool remove_2dlat = false;
for(vector<GMCVar *>::iterator ircv = cvar_1dlat.begin();ircv != cvar_1dlat.end();++ircv) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end(); ++ird) {
if((*ird)->name == (*ircv)->getDimensions()[0]->name &&
(*ird)->size == (*ircv)->getDimensions()[0]->size) {
latlon2d_path_to_index.erase((*irv)->fullpath);
delete(*irv);
irv = var_2dlat.erase(irv);
remove_2dlat = true;
break;
}
}
if(true == remove_2dlat)
break;
}
if(false == remove_2dlat)
++irv;
}
for(vector<Var *>::iterator irv = var_2dlon.begin();irv != var_2dlon.end();) {
bool remove_2dlon = false;
for(vector<GMCVar *>::iterator ircv = cvar_1dlon.begin();ircv != cvar_1dlon.end();++ircv) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end(); ++ird) {
if((*ird)->name == (*ircv)->getDimensions()[0]->name &&
(*ird)->size == (*ircv)->getDimensions()[0]->size) {
latlon2d_path_to_index.erase((*irv)->fullpath);
delete(*irv);
irv = var_2dlon.erase(irv);
remove_2dlon = true;
break;
}
}
if(true == remove_2dlon)
break;
}
if(false == remove_2dlon)
++irv;
}
}
//Out of the collected 2-D lat/lon variables, we will select the final qualified 2-D lat/lon as CVs.
void GMFile::Obtain_2DLLCVar_Candidate(vector<Var*> &var_2dlat,
vector<Var*> &var_2dlon,
map<string,int>& latlon2d_path_to_index) throw(Exception){
// First check 2-D lat, see if we have the corresponding 2-D lon(same dims, under the same group).
// If no, remove that lat from the vector.
vector<string> lon2d_group_paths;
for(vector<Var *>::iterator irv_2dlat = var_2dlat.begin();irv_2dlat !=var_2dlat.end();) {
for(vector<Var *>::iterator irv_2dlon = var_2dlon.begin();irv_2dlon != var_2dlon.end();++irv_2dlon) {
if(((*irv_2dlat)->getDimensions()[0]->name == (*irv_2dlon)->getDimensions()[0]->name) &&
((*irv_2dlat)->getDimensions()[0]->size == (*irv_2dlon)->getDimensions()[0]->size) &&
((*irv_2dlat)->getDimensions()[1]->name == (*irv_2dlon)->getDimensions()[1]->name) &&
((*irv_2dlat)->getDimensions()[1]->size == (*irv_2dlon)->getDimensions()[1]->size))
lon2d_group_paths.push_back(HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlon)->fullpath));
//lon2d_group_paths.push_back((*irv_2dlon)->fullpath.substr(0,(*irv_2dlon)->fullpath.find_last_of("/")));
}
// Doesn't find any lons that shares the same dims,remove this lat from the 2dlat vector,
// also update the latlon2d_path_to_index map
if(0 == lon2d_group_paths.size()) {
latlon2d_path_to_index.erase((*irv_2dlat)->fullpath);
delete(*irv_2dlat);
irv_2dlat = var_2dlat.erase(irv_2dlat);
}
else {// Find lons,check if they are under the same group
//string lat2d_group_path = (*irv_2dlat)->fullpath.substr(0,(*irv_2dlat)->fullpath.find_last_of("/"));
string lat2d_group_path = HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlat)->fullpath);
// Check how many lon2d shares the same group with the lat2d
short lon2d_has_lat2d_group_path_flag = 0;
for(vector<string>::iterator ivs = lon2d_group_paths.begin();ivs!=lon2d_group_paths.end();++ivs) {
if((*ivs)==lat2d_group_path)
lon2d_has_lat2d_group_path_flag++;
}
// No lon2d shares the same group with the lat2d, remove this lat2d
if(0 == lon2d_has_lat2d_group_path_flag) {
latlon2d_path_to_index.erase((*irv_2dlat)->fullpath);
delete(*irv_2dlat);
irv_2dlat = var_2dlat.erase(irv_2dlat);
}
// Only one lon2d, yes, keep it.
else if (1== lon2d_has_lat2d_group_path_flag) {
++irv_2dlat;
}
// More than 1 lon2d, we will remove the lat2d, but save the group path so that we may
// flatten the variable path stored in the coordinates attribute under this group.
else {
// Save the group path for the future use.
grp_cv_paths.insert(lat2d_group_path);
latlon2d_path_to_index.erase((*irv_2dlat)->fullpath);
delete(*irv_2dlat);
irv_2dlat = var_2dlat.erase(irv_2dlat);
}
}
//Clear the vector that stores the same dim. since it is only applied to this lat,
lon2d_group_paths.clear();
}
#if 0
for(vector<Var *>::iterator irv_2dlat = var_2dlat.begin();irv_2dlat !=var_2dlat.end();++irv_2dlat)
cerr<<"2 left 2-D lat variable full path is: "<<(*irv_2dlat)->fullpath <<endl;
#endif
// Second check 2-D lon, see if we have the corresponding 2-D lat(same dims, under the same group).
// If no, remove that lon from the vector.
vector<string> lat2d_group_paths;
// Check the longitude
for(vector<Var *>::iterator irv_2dlon = var_2dlon.begin();irv_2dlon !=var_2dlon.end();) {
for(vector<Var *>::iterator irv_2dlat = var_2dlat.begin();irv_2dlat != var_2dlat.end();++irv_2dlat) {
if(((*irv_2dlat)->getDimensions()[0]->name == (*irv_2dlon)->getDimensions()[0]->name) &&
((*irv_2dlat)->getDimensions()[0]->size == (*irv_2dlon)->getDimensions()[0]->size) &&
((*irv_2dlat)->getDimensions()[1]->name == (*irv_2dlon)->getDimensions()[1]->name) &&
((*irv_2dlat)->getDimensions()[1]->size == (*irv_2dlon)->getDimensions()[1]->size))
lat2d_group_paths.push_back(HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlat)->fullpath));
//lat2d_group_paths.push_back((*irv_2dlat)->fullpath.substr(0,(*irv_2dlat)->fullpath.find_last_of("/")));
}
// Doesn't find any lats that shares the same dims,remove this lon from this vector
if(0 == lat2d_group_paths.size()) {
latlon2d_path_to_index.erase((*irv_2dlon)->fullpath);
delete(*irv_2dlon);
irv_2dlon = var_2dlon.erase(irv_2dlon);
}
else {
//string lon2d_group_path = (*irv_2dlon)->fullpath.substr(0,(*irv_2dlon)->fullpath.find_last_of("/"));
string lon2d_group_path = HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlon)->fullpath);
// Check how many lat2d shares the same group with the lon2d
short lat2d_has_lon2d_group_path_flag = 0;
for(vector<string>::iterator ivs = lat2d_group_paths.begin();ivs!=lat2d_group_paths.end();++ivs) {
if((*ivs)==lon2d_group_path)
lat2d_has_lon2d_group_path_flag++;
}
// No lat2d shares the same group with the lon2d, remove this lon2d
if(0 == lat2d_has_lon2d_group_path_flag) {
latlon2d_path_to_index.erase((*irv_2dlon)->fullpath);
delete(*irv_2dlon);
irv_2dlon = var_2dlon.erase(irv_2dlon);
}
// Only one lat2d shares the same group with the lon2d, yes, keep it.
else if (1== lat2d_has_lon2d_group_path_flag) {
++irv_2dlon;
}
// more than 1 lat2d, we will remove the lon2d, but save the group path so that we can
// change the coordinates attribute for variables under this group later.
else {
// Save the group path for future "coordinates" modification.
grp_cv_paths.insert(lon2d_group_path);
latlon2d_path_to_index.erase((*irv_2dlon)->fullpath);
delete(*irv_2dlon);
irv_2dlon = var_2dlon.erase(irv_2dlon);
}
}
//Clear the vector that stores the same dim. since it is only applied to this lon,
lat2d_group_paths.clear();
}
#if 0
for(vector<Var*>::iterator itv = var_2dlat.begin(); itv!= var_2dlat.end();++itv) {
cerr<<"Before unique, 2-D CV latitude name is "<<(*itv)->fullpath <<endl;
}
for(vector<Var*>::iterator itv = var_2dlon.begin(); itv!= var_2dlon.end();++itv) {
cerr<<"Before unique, 2-D CV longitude name is "<<(*itv)->fullpath <<endl;
}
#endif
// Final check var_2dlat and var_2dlon to remove non-qualified CVs.
Obtain_unique_2dCV(var_2dlat,latlon2d_path_to_index);
Obtain_unique_2dCV(var_2dlon,latlon2d_path_to_index);
#if 0
for(vector<Var*>::iterator itv = var_2dlat.begin(); itv!= var_2dlat.end();++itv) {
cerr<<"2-D CV latitude name is "<<(*itv)->fullpath <<endl;
}
for(vector<Var*>::iterator itv = var_2dlon.begin(); itv!= var_2dlon.end();++itv) {
cerr<<"2-D CV longitude name is "<<(*itv)->fullpath <<endl;
}
#endif
// This is to serve as a sanity check. This can help us find bugs in the first place.
if(var_2dlat.size() != var_2dlon.size()) {
throw1("Error in generating 2-D lat/lon CVs.");
}
}
// If two vars in the 2-D lat or 2-D lon CV candidate vector share the same dim. , these two vars cannot be CVs.
// The group they belong to is the group candidate that the coordinates attribute of the variable under that group may be modified..
void GMFile::Obtain_unique_2dCV(vector<Var*> &var_ll,map<string,int>&latlon2d_path_to_index){
vector<bool> var_share_dims(var_ll.size(),false);
for( int i = 0; i <var_ll.size();i++) {
string var_ll_i_path = HDF5CFUtil::obtain_string_before_lastslash(var_ll[i]->fullpath);
for(int j = i+1; j<var_ll.size();j++) {
if((var_ll[i]->getDimensions()[0]->name == var_ll[j]->getDimensions()[0]->name)
||(var_ll[i]->getDimensions()[0]->name == var_ll[j]->getDimensions()[1]->name)
||(var_ll[i]->getDimensions()[1]->name == var_ll[j]->getDimensions()[0]->name)
||(var_ll[i]->getDimensions()[1]->name == var_ll[j]->getDimensions()[1]->name)){
string var_ll_j_path = HDF5CFUtil::obtain_string_before_lastslash(var_ll[j]->fullpath);
// Compare var_ll_i_path and var_ll_j_path,only set the child group path be true and remember the path.
// Obtain the string size,
// compare the string size, long.compare(0,shortlength,short)==0,
// yes, save the long path(child group path), set the long path one true. Else save two paths, set both true
if(var_ll_i_path.size() > var_ll_j_path.size()) {
// If var_ll_j_path is the parent group of var_ll_i_path,
// set the shared dim. be true for the child group only,remember the path.
if(var_ll_i_path.compare(0,var_ll_j_path.size(),var_ll_j_path)==0) {
var_share_dims[i] = true;
grp_cv_paths.insert(var_ll_i_path);
}
else {// Save both as shared, they cannot be CVs.
var_share_dims[i] = true;
var_share_dims[j] = true;
grp_cv_paths.insert(var_ll_i_path);
grp_cv_paths.insert(var_ll_j_path);
}
}
else if (var_ll_i_path.size() == var_ll_j_path.size()) {// Share the same group, remember both group paths.
var_share_dims[i] = true;
var_share_dims[j] = true;
if(var_ll_i_path == var_ll_j_path)
grp_cv_paths.insert(var_ll_i_path);
else {
grp_cv_paths.insert(var_ll_i_path);
grp_cv_paths.insert(var_ll_j_path);
}
}
else {
// var_ll_i_path is the parent group of var_ll_j_path,
// set the shared dim. be true for the child group,remember the path.
if(var_ll_j_path.compare(0,var_ll_i_path.size(),var_ll_i_path)==0) {
var_share_dims[j] = true;
grp_cv_paths.insert(var_ll_j_path);
}
else {// Save both as shared, they cannot be CVs.
var_share_dims[i] = true;
var_share_dims[j] = true;
grp_cv_paths.insert(var_ll_i_path);
grp_cv_paths.insert(var_ll_j_path);
}
}
}
}
}
// Remove the shared 2-D lat/lon CVs from the 2-D lat/lon CV candidates.
int var_index = 0;
for(vector<Var*>::iterator itv = var_ll.begin(); itv!= var_ll.end();) {
if(true == var_share_dims[var_index]) {
latlon2d_path_to_index.erase((*itv)->fullpath);
delete(*itv);
itv = var_ll.erase(itv);
}
else {
++itv;
}
++var_index;
}
}
// When promoting a 2-D lat or lon to a coordinate variable, we need to remove them from the general variable vector.
void GMFile::Remove_2DLLCVar_Final_Candidate_from_Vars(vector<int> &var2d_index) throw(Exception) {
//Sort the 2-D lat/lon var index according to the ascending order before removing the 2-D lat/lon vars
sort(var2d_index.begin(),var2d_index.end());
vector<Var *>::iterator it = this->vars.begin();
// This is a performance optimiziation operation.
// We find it is typical for swath files that have many many general variables but only have very few lat/lon CVs.
// To reduce the looping through all variables and comparing the fullpath(string), we use index and remember
// the position of 2-D CVs in the iterator. In this way, only a few operations are needed.
for (int i = 0; i <var2d_index.size();i++) {
if ( i == 0)
advance(it,var2d_index[i]);
else
advance(it,var2d_index[i]-var2d_index[i-1]-1);
if(it == this->vars.end())
throw1("Out of range to obtain 2D lat/lon variables");
else {
//cerr<<"removed latitude/longitude names are "<<(*it)->fullpath <<endl;
delete(*it);
it = this->vars.erase(it);
}
}
}
//This function is for generating the coordinates attribute for the 2-D lat/lon.
//It will check if this var can have the "coordinates" attribute that includes the 2-D lat/lon.
bool GMFile::Check_Var_2D_CVars(Var *var) throw(Exception) {
bool ret_value = true;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank==2) {
short first_dim_index = 0;
short first_dim_times = 0;
short second_dim_index = 0;
short second_dim_times = 0;
for (vector<Dimension *>::iterator ird = var->dims.begin();
ird != var->dims.end(); ++ird) {
if((*ird)->name == ((*ircv)->getDimensions()[0])->name) {
first_dim_index = distance(var->dims.begin(),ird);
first_dim_times++;
}
else if((*ird)->name == ((*ircv)->getDimensions()[1])->name) {
second_dim_index = distance(var->dims.begin(),ird);
second_dim_times++;
}
}
// The 2-D CV dimensions must only appear once as the dimension of the variable
// It also must follow the dimension order of the 2-D lat/lon dimensions.
if(first_dim_times == 1 && second_dim_times == 1) {
if(first_dim_index < second_dim_index) {
ret_value = false;
break;
}
}
}
}
return ret_value;
}
// This function flattens the variable path in the "coordinates" attribute.
bool GMFile::Flatten_VarPath_In_Coordinates_Attr(Var *var) throw(Exception) {
string co_attrname = "coordinates";
bool has_coor_attr = false;
string orig_coor_value;
string flatten_coor_value;
char sc = ' ';
for (vector<Attribute *>:: iterator ira =var->attrs.begin(); ira !=var->attrs.end();) {
// We only check the original attribute name
// Remove the original "coordinates" attribute.
if((*ira)->name == co_attrname) {
Retrieve_H5_Attr_Value((*ira),var->fullpath);
string orig_attr_value((*ira)->value.begin(),(*ira)->value.end());
orig_coor_value = orig_attr_value;
has_coor_attr = true;
delete(*ira);
ira = var->attrs.erase(ira);
break;
}
else
++ira;
}
if(true == has_coor_attr) {
// We need to loop through each element in the "coordinates".
size_t ele_start_pos = 0;
size_t cur_pos = orig_coor_value.find_first_of(sc);
while(cur_pos !=string::npos) {
string tempstr = orig_coor_value.substr(ele_start_pos,cur_pos-ele_start_pos);
tempstr = get_CF_string(tempstr);
flatten_coor_value += tempstr + sc;
ele_start_pos = cur_pos+1;
cur_pos = orig_coor_value.find_first_of(sc,cur_pos+1);
}
// Flatten each element
if(ele_start_pos == 0)
flatten_coor_value = get_CF_string(orig_coor_value);
else
flatten_coor_value += get_CF_string(orig_coor_value.substr(ele_start_pos));
// Generate the new "coordinates" attribute.
Attribute *attr = new Attribute();
Add_Str_Attr(attr,co_attrname,flatten_coor_value);
var->attrs.push_back(attr);
}
return true;
}
// The following two routines only handle one 2-D lat/lon CVs. It is replaced by the more general
// multi 2-D lat/lon CV routines. Leave it here just for references.
#if 0
bool GMFile::Check_2DLatLon_Dimscale(string & latname, string &lonname) throw(Exception) {
// New code to support 2-D lat/lon, still in development.
// Need to handle 2-D latitude and longitude cases.
// 1. Searching only the coordinate variables and if getting either of the following, keep the current way,
// (A) GMcvar no CV_FILLINDEX:(The 2-D latlon case should have fake CVs)
// (B) CV_EXIST: Attributes contain units and units value is degrees_east or degrees_north(have lat/lon)
// (B) CV_EXIST: variables have name pair{lat/latitude/Latitude,lon/longitude/Longitude}(have lat/lon)
//
// 2. if not 1), searching all the variables and see if finding variables {lat/latitude/Latitude,lon/longitude/Longitude};
// If finding {lat/lon},{latitude,longitude},{latitude,Longitude} pair,
// if the number of dimension of either variable is not 2, keep the current way.
// else check if the dimension name of latitude and longitude are the same, not, keep the current way
// check the units of this CV pair, if units of the latitude is not degrees_north,
// change it to degrees_north.
// if units of the longitude is not degrees_east, change it to degrees_east.
// make iscoard false.
bool latlon_2d_cv_check1 = false;
// Some products(TOM MEaSURE) provide the true dimension scales for 2-D lat,lon. So relax this check.
latlon_2d_cv_check1 = true;
#if 0
// If having 2-D lat/lon, the corresponding dimension must be pure and the CV type must be FILLINDEX.
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_FILLINDEX){
latlon_2d_cv_check1 = true;
break;
}
}
#endif
bool latlon_2d_cv_check2 = true;
// There may still not be 2-D lat/lon. Check the units attributes and lat/lon pairs.
if(true == latlon_2d_cv_check1) {
BESDEBUG("h5","Coming to check if having 2d latlon coordinates for a netCDF-4 like product. "<<endl);
// check if units attribute values have CF lat/lon units "degrees_north" or "degrees_east".
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
for(vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end();ira++) {
string attr_name ="units";
string lat_unit_value = "degrees_north";
string lon_unit_value = "degrees_east";
// Considering the cross-section case, either is fine.
if((true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lat_unit_value)) ||
(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lon_unit_value))) {
latlon_2d_cv_check2= false;
break;
}
}
}
if(false == latlon_2d_cv_check2)
break;
}
}
bool latlon_2d_cv_check3 = true;
// Even we cannot find the CF lat/lon attributes, we may still find lat/lon etc pairs.
if(true == latlon_2d_cv_check1 && true == latlon_2d_cv_check2) {
short latlon_flag = 0;
short LatLon_flag = 0;
short latilong_flag = 0;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
if((*ircv)->name == "lat")
latlon_flag++;
else if((*ircv)->name == "lon")
latlon_flag++;
else if((*ircv)->name == "latitude")
latilong_flag++;
else if((*ircv)->name == "longitude")
latilong_flag++;
else if((*ircv)->name == "Latitude")
LatLon_flag++;
else if((*ircv)->name == "Longitude")
LatLon_flag++;
}
}
if((2== latlon_flag) || (2 == latilong_flag) || (2 == LatLon_flag ))
latlon_2d_cv_check3 = false;
}
bool latlon_2d = false;
short latlon_flag = 0;
string latdim1,latdim2,londim1,londim2;
short LatLon_flag = 0;
string Latdim1,Latdim2,Londim1,Londim2;
short latilong_flag = 0;
string latidim1,latidim2,longdim1,longdim2;
// Final check, we need to check if we have 2-D {lat/latitude/Latitude, lon/longitude/Longitude}
// in the general variable list.
// Here, depending on the future support, lat/lon pairs with other names(cell_lat,cell_lon etc) may be supported.
// KY 2015-12-03
if(true == latlon_2d_cv_check1 && true == latlon_2d_cv_check2 && true == latlon_2d_cv_check3) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
//
if((*irv)->rank == 2) {
if((*irv)->name == "lat") {
latlon_flag++;
latdim1 = (*irv)->getDimensions()[0]->name;
latdim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "lon") {
latlon_flag++;
londim1 = (*irv)->getDimensions()[0]->name;
londim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "latitude"){
latilong_flag++;
latidim1 = (*irv)->getDimensions()[0]->name;
latidim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "longitude"){
latilong_flag++;
longdim1 = (*irv)->getDimensions()[0]->name;
longdim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "Latitude"){
LatLon_flag++;
Latdim1 = (*irv)->getDimensions()[0]->name;
Latdim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "Longitude"){
LatLon_flag++;
Londim1 = (*irv)->getDimensions()[0]->name;
Londim2 = (*irv)->getDimensions()[1]->name;
}
}
}
// Here we ensure that only one lat/lon(lati/long,Lati/Long) is in the file.
// If we find >=2 pairs lat/lon and latitude/longitude, or Latitude/Longitude,
// we will not treat this as a 2-D latlon Dimscale case. The data producer
// should correct their mistakes.
if(2 == latlon_flag) {
if((2 == latilong_flag) || ( 2 == LatLon_flag))
latlon_2d = false;
else if((latdim1 == londim1) && (latdim2 == londim2)) {
latname = "lat";
lonname = "lon";
latlon_2d = true;
}
}
else if ( 2 == latilong_flag) {
if( 2 == LatLon_flag)
latlon_2d = false;
else if ((latidim1 == longdim1) ||(latidim2 == longdim2)) {
latname = "latitude";
lonname = "longitude";
latlon_2d = true;
}
}
else if (2 == LatLon_flag){
if ((Latdim1 == Londim1) ||(Latdim2 == Londim2)) {
latname = "Latitude";
lonname = "Longitude";
latlon_2d = true;
}
}
}
return latlon_2d;
}
// Update the coordinate variables for files that use HDF5 dimension scales and have 2-D lat/lon.
void GMFile::Update_2DLatLon_Dimscale_CV(const string &latname,const string &lonname) throw(Exception) {
iscoard = false;
// Update latitude.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
// Find 2-D latitude
if((*irv)->name == latname) {
// Obtain the first dimension of this variable
string latdim0 = (*irv)->getDimensions()[0]->name;
//cerr<<"latdim0 is "<<latdim0 <<endl;
// Remove the CV corresponding to latdim0
for (vector<GMCVar *>:: iterator i= this->cvars.begin(); i!=this->cvars.end(); ) {
if((*i)->cfdimname == latdim0) {
if(CV_FILLINDEX == (*i)->cvartype) {
delete(*i);
i = this->cvars.erase(i);
}
else if(CV_EXIST == (*i)->cvartype) {
// Add this var. to the var list.
Var *var = new Var((*i));
this->vars.push_back(var);
// Remove this var. from the GMCVar list.
delete(*i);
i = this->cvars.erase(i);
}
else {// the latdimname should be either the CV_FILLINDEX or CV_EXIST.
if(CV_LAT_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_LAT_MISS");
else if(CV_LON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_LON_MISS");
else if(CV_NONLATLON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_NONLATLON_MISS");
else if(CV_MODIFY == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_MODIFY");
else if(CV_SPECIAL == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_SPECIAL");
else
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_UNSUPPORTED");
}
}
else
++i;
}
// Add the 2-D latitude(latname) to the CV list.
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = latdim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
}
}
}
// Update longitude.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
// Find 2-D longitude
if((*irv)->name == lonname) {
// Obtain the second dimension of this variable
string londim0 = (*irv)->getDimensions()[1]->name;
// Remove the CV corresponding to londim0
for (vector<GMCVar *>:: iterator i= this->cvars.begin(); i!=this->cvars.end(); ) {
// NEED more work!!! should also remove ntime from the GMCVar list but add it to the cvar list.Same for Lon.
if((*i)->cfdimname == londim0) {
if(CV_FILLINDEX == (*i)->cvartype) {
delete(*i);
i= this->cvars.erase(i);
}
else if(CV_EXIST == (*i)->cvartype) {
// Add this var. to the var list.
Var *var = new Var((*i));
this->vars.push_back(var);
// Remove this var. from the GMCVar list.
delete(*i);
i = this->cvars.erase(i);
}
else {// the latdimname should be either the CV_FILLINDEX or CV_EXIST.
if(CV_LAT_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_LAT_MISS");
else if(CV_LON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_LON_MISS");
else if(CV_NONLATLON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_NONLATLON_MISS");
else if(CV_MODIFY == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_MODIFY");
else if(CV_SPECIAL == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_SPECIAL");
else
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_UNSUPPORTED");
}
}
else
++i;
}
// Add the 2-D longitude(lonname) to the CV list.
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = londim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
}
}
}
}
#endif
// Handle coordinate variables for general HDF5 products that have 1-D lat/lon
void GMFile::Handle_CVar_LatLon1D_General_Product() throw(Exception) {
this->iscoard = true;
Handle_CVar_LatLon_General_Product();
}
// Handle coordinate variables for general HDF5 products that have 2-D lat/lon
void GMFile::Handle_CVar_LatLon2D_General_Product() throw(Exception) {
Handle_CVar_LatLon_General_Product();
}
// Routine used by other routines to handle coordinate variables for general HDF5 product
// that have either 1-D or 2-D lat/lon
void GMFile::Handle_CVar_LatLon_General_Product() throw(Exception) {
if((GENERAL_LATLON2D != this->gproduct_pattern)
&& GENERAL_LATLON1D != this->gproduct_pattern)
throw1("This function only supports latlon 1D or latlon 2D general products");
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// This is the dimension scale dataset; it should be changed to a coordinate variable.
if (gp_latname== (*irv)->name) {
// For latitude, regardless 1D or 2D, the first dimension needs to be updated.
// Create Coordinate variables.
tempdimnamelist.erase(((*irv)->dims[0])->name);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = ((*irv)->dims[0])->name;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
} // if ((*irs)== (*irv)->fullpath)
} // for (vector<Var *>::iterator irv = this->vars.begin();
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// This is the dimension scale dataset; it should be changed to a coordinate variable.
if (gp_lonname== (*irv)->name) {
// For 2-D lat/lon, the londimname should be the second dimension of the longitude
// For 1-D lat/lon, the londimname should be the first dimension of the longitude
// Create Coordinate variables.
string londimname;
if(GENERAL_LATLON2D == this->gproduct_pattern)
londimname = ((*irv)->dims[1])->name;
else
londimname = ((*irv)->dims[0])->name;
tempdimnamelist.erase(londimname);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = londimname;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
} // if ((*irs)== (*irv)->fullpath)
} // for (vector<Var *>::iterator irv = this->vars.begin();
//
// Add other missing coordinate variables.
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();irs++) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle coordinate variables for OBPG level 3
void GMFile::Handle_CVar_OBPG_L3() throw(Exception) {
if (GENERAL_DIMSCALE == this->gproduct_pattern)
Handle_CVar_Dimscale_General_Product();
// Change the CV Type of the corresponding CVs of lat and lon from CV_FILLINDEX to CV_LATMISS or CV_LONMISS
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// Here I try to avoid using the dimension name row and column to find the lat/lon dimension size.
// So I am looking for a 2-D floating-point array or a 2-D array under the group geophsical_data.
// This may be subject to change if OBPG level 3 change its arrangement of variables.
// KY 2014-09-29
if((*irv)->rank == 2) {
if(((*irv)->fullpath.find("/geophsical_data") == 0) || ((*irv)->dtype == H5FLOAT32)) {
size_t lat_size = (*irv)->getDimensions()[0]->size;
string lat_name = (*irv)->getDimensions()[0]->name;
size_t lon_size = (*irv)->getDimensions()[1]->size;
string lon_name = (*irv)->getDimensions()[1]->name;
size_t temp_size = 0;
string temp_name;
H5DataType ll_dtype = (*irv)->dtype;
//cerr<<"lat_name is "<<lat_name <<endl;
//cerr<<"lon_name is "<<lon_name <<endl;
// We always assume that longitude size is greater than latitude size.
if(lat_size >lon_size) {
temp_size = lon_size;
temp_name = lon_name;
lon_size = lat_size;
lon_name = lat_name;
lat_size = temp_size;
lat_name = temp_name;
}
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_FILLINDEX) {
if((*ircv)->getDimensions()[0]->size == lat_size &&
(*ircv)->getDimensions()[0]->name == lat_name) {
(*ircv)->cvartype = CV_LAT_MISS;
(*ircv)->dtype = ll_dtype;
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ++ira) {
if ((*ira)->name == "NAME") {
delete (*ira);
(*ircv)->attrs.erase(ira);
break;
}
}
}
else if((*ircv)->getDimensions()[0]->size == lon_size &&
(*ircv)->getDimensions()[0]->name == lon_name) {
(*ircv)->cvartype = CV_LON_MISS;
(*ircv)->dtype = ll_dtype;
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ++ira) {
if ((*ira)->name == "NAME") {
delete (*ira);
(*ircv)->attrs.erase(ira);
break;
}
}
}
}
}
break;
} // if(((*irv)->fullpath.find("/geophsical_data") == 0) || ((*irv)->dtype == H5FLOAT32))
} // if((*irv)->rank == 2)
} // for (vector<Var *>::iterator irv = this->vars.begin();
}
// Handle some special variables. Currently only GPM and ACOS have these variables.
void GMFile::Handle_SpVar() throw(Exception){
if (ACOS_L2S_OR_OCO2_L1B == product_type)
Handle_SpVar_ACOS_OCO2();
else if(GPM_L1 == product_type) {
// Loop through the variable list to build the coordinates.
// These variables need to be removed.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->name=="AlgorithmRuntimeInfo") {
delete(*irv);
this->vars.erase(irv);
break;
}
}
}
// GPM level-3 These variables need to be removed.
else if(GPMM_L3 == product_type || GPMS_L3 == product_type) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if((*irv)->name=="InputFileNames") {
delete(*irv);
irv = this->vars.erase(irv);
}
else if((*irv)->name=="InputAlgorithmVersions") {
delete(*irv);
irv = this->vars.erase(irv);
}
else if((*irv)->name=="InputGenerationDateTimes") {
delete(*irv);
irv = this->vars.erase(irv);
}
else {
++irv;
}
}
}
}
// Handle special variables for ACOS.
void GMFile::Handle_SpVar_ACOS_OCO2() throw(Exception) {
//The ACOS or OCO2 have 64-bit variables. DAP2 doesn't support 64-bit variables.
// So we will not handle attributes yet.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if (H5INT64 == (*irv)->getType()) {
// First: Time Part of soundingid
GMSPVar * spvar = new GMSPVar(*irv);
spvar->name = (*irv)->name +"_Time";
spvar->newname = (*irv)->newname+"_Time";
spvar->dtype = H5INT32;
spvar->otype = (*irv)->getType();
spvar->sdbit = 1;
// 2 digit hour, 2 digit min, 2 digit seconds
spvar->numofdbits = 6;
this->spvars.push_back(spvar);
// Second: Date Part of soundingid
GMSPVar * spvar2 = new GMSPVar(*irv);
spvar2->name = (*irv)->name +"_Date";
spvar2->newname = (*irv)->newname+"_Date";
spvar2->dtype = H5INT32;
spvar2->otype = (*irv)->getType();
spvar2->sdbit = 7;
// 4 digit year, 2 digit month, 2 digit day
spvar2->numofdbits = 8;
this->spvars.push_back(spvar2);
delete(*irv);
irv = this->vars.erase(irv);
} // if (H5INT64 == (*irv)->getType())
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
// Adjust Object names, For some products, NASA data centers don't need
// the fullpath of objects.
void GMFile::Adjust_Obj_Name() throw(Exception) {
if(Mea_Ozone == product_type)
Adjust_Mea_Ozone_Obj_Name();
if(GPMS_L3 == product_type || GPMM_L3 == product_type)
Adjust_GPM_L3_Obj_Name();
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Adjust_Obj_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
// Adjust object names for GPM level 3 products
void GMFile:: Adjust_GPM_L3_Obj_Name() throw(Exception) {
//cerr<<"number of group is "<<this->groups.size() <<endl;
string objnewname;
// In this definition, root group is not considered as a group.
if(this->groups.size() <= 1) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
objnewname = HDF5CFUtil::obtain_string_after_lastslash((*irv)->newname);
if (objnewname !="")
(*irv)->newname = objnewname;
}
}
else {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
//cerr<<"(*irv)->newname is "<<(*irv)->newname <<endl;
size_t grid_group_path_pos = ((*irv)->newname.substr(1)).find_first_of("/");
objnewname = ((*irv)->newname).substr(grid_group_path_pos+2);
(*irv)->newname = objnewname;
}
}
}
// Adjust object names for MeaSUREs OZone
void GMFile:: Adjust_Mea_Ozone_Obj_Name() throw(Exception) {
string objnewname;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
objnewname = HDF5CFUtil::obtain_string_after_lastslash((*irv)->newname);
if (objnewname !="")
(*irv)->newname = objnewname;
#if 0
//Just for debugging
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
cerr<<"Ozone dim. name "<<(*ird)->name <<endl;
cerr<<"Ozone dim. new name "<<(*ird)->newname <<endl;
}
#endif
}
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
objnewname = HDF5CFUtil::obtain_string_after_lastslash((*irv)->newname);
if (objnewname !="")
(*irv)->newname = objnewname;
#if 0
//Just for debugging
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
cerr<<"Ozone CV dim. name "<<(*ird)->name <<endl;
cerr<<"Ozone CV dim. new name "<<(*ird)->newname <<endl;
}
#endif
}
}
// Flatten object names.
void GMFile::Flatten_Obj_Name(bool include_attr) throw(Exception){
File::Flatten_Obj_Name(include_attr);
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
(*irv)->newname = get_CF_string((*irv)->newname);
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
(*ird)->newname = get_CF_string((*ird)->newname);
}
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira)
(*ira)->newname = File::get_CF_string((*ira)->newname);
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
(*irv)->newname = get_CF_string((*irv)->newname);
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird)
(*ird)->newname = get_CF_string((*ird)->newname);
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira)
(*ira)->newname = File::get_CF_string((*ira)->newname);
}
}
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Flatten_Obj_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
// Rarely object name clashings may occur. This routine makes sure
// all object names are unique.
void GMFile::Handle_Obj_NameClashing(bool include_attr) throw(Exception) {
// objnameset will be filled with all object names that we are going to check the name clashing.
// For example, we want to see if there are any name clashings for all variable names in this file.
// objnameset will include all variable names. If a name clashing occurs, we can figure out from the set operation immediately.
set<string>objnameset;
Handle_GMCVar_NameClashing(objnameset);
Handle_GMSPVar_NameClashing(objnameset);
File::Handle_GeneralObj_NameClashing(include_attr,objnameset);
if (true == include_attr) {
Handle_GMCVar_AttrNameClashing();
Handle_GMSPVar_AttrNameClashing();
}
// Moving to h5gmcfdap.cc, right after Adjust_Dim_Name
//Handle_DimNameClashing();
}
void GMFile::Handle_GMCVar_NameClashing(set<string> &objnameset ) throw(Exception) {
GMHandle_General_NameClashing(objnameset,this->cvars);
}
void GMFile::Handle_GMSPVar_NameClashing(set<string> &objnameset ) throw(Exception) {
GMHandle_General_NameClashing(objnameset,this->spvars);
}
// This routine handles attribute name clashings.
void GMFile::Handle_GMCVar_AttrNameClashing() throw(Exception) {
set<string> objnameset;
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
Handle_General_NameClashing(objnameset,(*irv)->attrs);
objnameset.clear();
}
}
void GMFile::Handle_GMSPVar_AttrNameClashing() throw(Exception) {
set<string> objnameset;
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
Handle_General_NameClashing(objnameset,(*irv)->attrs);
objnameset.clear();
}
}
//class T must have member string newname
// The subroutine to handle name clashings,
// it builds up a map from original object names to clashing-free object names.
template<class T> void
GMFile::GMHandle_General_NameClashing(set <string>&objnameset, vector<T*>& objvec) throw(Exception){
pair<set<string>::iterator,bool> setret;
set<string>::iterator iss;
vector<string> clashnamelist;
vector<string>::iterator ivs;
map<int,int> cl_to_ol;
int ol_index = 0;
int cl_index = 0;
typename vector<T*>::iterator irv;
//for (vector<T*>::iterator irv = objvec.begin();
for (irv = objvec.begin();
irv != objvec.end(); ++irv) {
setret = objnameset.insert((*irv)->newname);
if (false == setret.second ) {
clashnamelist.insert(clashnamelist.end(),(*irv)->newname);
cl_to_ol[cl_index] = ol_index;
cl_index++;
}
ol_index++;
}
// Now change the clashed elements to unique elements;
// Generate the set which has the same size as the original vector.
for (ivs=clashnamelist.begin(); ivs!=clashnamelist.end(); ++ivs) {
int clash_index = 1;
string temp_clashname = *ivs +'_';
HDF5CFUtil::gen_unique_name(temp_clashname,objnameset,clash_index);
*ivs = temp_clashname;
}
// Now go back to the original vector, make it unique.
for (unsigned int i =0; i <clashnamelist.size(); i++)
objvec[cl_to_ol[i]]->newname = clashnamelist[i];
}
// Handle dimension name clashings
void GMFile::Handle_DimNameClashing() throw(Exception){
//cerr<<"coming to DimNameClashing "<<endl;
// ACOS L2S or OCO2 L1B products doesn't need the dimension name clashing check based on our current understanding. KY 2012-5-16
if (ACOS_L2S_OR_OCO2_L1B == product_type)
return;
map<string,string>dimname_to_dimnewname;
pair<map<string,string>::iterator,bool>mapret;
set<string> dimnameset;
vector<Dimension*>vdims;
set<string> dimnewnameset;
pair<set<string>::iterator,bool> setret;
// First: Generate the dimset/dimvar based on coordinate variables.
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv !=this->cvars.end(); ++irv) {
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
//setret = dimnameset.insert((*ird)->newname);
setret = dimnameset.insert((*ird)->name);
if (true == setret.second)
vdims.push_back(*ird);
}
}
// For some cases, dimension names are provided but there are no corresponding coordinate
// variables. For now, we will assume no such cases.
// Actually, we find such a case in our fake testsuite. So we need to fix it.
for(vector<Var *>::iterator irv= this->vars.begin();
irv != this->vars.end();++irv) {
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
//setret = dimnameset.insert((*ird)->newname);
setret = dimnameset.insert((*ird)->name);
if (setret.second) vdims.push_back(*ird);
}
}
GMHandle_General_NameClashing(dimnewnameset,vdims);
// Third: Make dimname_to_dimnewname map
for (vector<Dimension*>::iterator ird = vdims.begin();ird!=vdims.end();++ird) {
mapret = dimname_to_dimnewname.insert(pair<string,string>((*ird)->name,(*ird)->newname));
if (false == mapret.second)
throw4("The dimension name ",(*ird)->name," should map to ",
(*ird)->newname);
}
// Fourth: Change the original dimension new names to the unique dimension new names
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv !=this->cvars.end(); ++irv)
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end();++ird)
(*ird)->newname = dimname_to_dimnewname[(*ird)->name];
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv)
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird)
(*ird)->newname = dimname_to_dimnewname[(*ird)->name];
}
// For COARDS, dim. names need to be the same as obj. names.
void GMFile::Adjust_Dim_Name() throw(Exception){
#if 0
// Just for debugging
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension new name "<<(*ird)->newname <<endl;
}
}
#endif
// Only need for COARD conventions.
if( true == iscoard) {
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv !=this->cvars.end(); ++irv) {
#if 0
cerr<<"1D Cvariable name is "<<(*irv)->name <<endl;
cerr<<"1D Cvariable new name is "<<(*irv)->newname <<endl;
cerr<<"1D Cvariable dim name is "<<((*irv)->dims)[0]->name <<endl;
cerr<<"1D Cvariable dim new name is "<<((*irv)->dims)[0]->newname <<endl;
#endif
if ((*irv)->dims.size()!=1)
throw3("Coard coordinate variable ",(*irv)->name, "is not 1D");
if ((*irv)->newname != (((*irv)->dims)[0]->newname)) {
((*irv)->dims)[0]->newname = (*irv)->newname;
// For all variables that have this dimension,the dimension newname should also change.
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); ++irv2) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ++ird) {
// This is the key, the dimension name of this dimension
// should be equal to the dimension name of the coordinate variable.
// Then the dimension name matches and the dimension name should be changed to
// the new dimension name.
if ((*ird)->name == ((*irv)->dims)[0]->name)
(*ird)->newname = ((*irv)->dims)[0]->newname;
}
}
} // if ((*irv)->newname != (((*irv)->dims)[0]->newname))
}// for (vector<GMCVar *>::iterator irv = this->cvars.begin(); ...
} // if( true == iscoard)
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Adjust_Dim_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
// Add supplemental CF attributes for some products.
void
GMFile:: Add_Supplement_Attrs(bool add_path) throw(Exception) {
if (General_Product == product_type || true == add_path) {
File::Add_Supplement_Attrs(add_path);
// Adding variable original name(origname) and full path(fullpath)
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
if (((*irv)->cvartype == CV_EXIST) || ((*irv)->cvartype == CV_MODIFY)) {
Attribute * attr = new Attribute();
const string varname = (*irv)->name;
const string attrname = "origname";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
}
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
if (((*irv)->cvartype == CV_EXIST) || ((*irv)->cvartype == CV_MODIFY)) {
Attribute * attr = new Attribute();
const string varname = (*irv)->fullpath;
const string attrname = "fullnamepath";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
Attribute * attr = new Attribute();
const string varname = (*irv)->name;
const string attrname = "origname";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
Attribute * attr = new Attribute();
const string varname = (*irv)->fullpath;
const string attrname = "fullnamepath";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
} // if (General_Product == product_type || true == add_path)
if(GPM_L1 == product_type || GPMS_L3 == product_type || GPMM_L3 == product_type)
Add_GPM_Attrs();
else if (Aqu_L3 == product_type)
Add_Aqu_Attrs();
else if (Mea_SeaWiFS_L2 == product_type || Mea_SeaWiFS_L3 == product_type)
Add_SeaWiFS_Attrs();
}
// Add CF attributes for GPM products
void
GMFile:: Add_GPM_Attrs() throw(Exception) {
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
const string attr_name_be_replaced = "CodeMissingValue";
const string attr_new_name = "_FillValue";
const string attr_cor_fill_value = "-9999.9";
const string attr2_name_be_replaced = "Units";
const string attr2_new_name ="units";
// Need to convert String type CodeMissingValue to the corresponding _FilLValue
// Create a function at HDF5CF.cc. use strtod,strtof,strtol etc. function to convert
// string to the corresponding type.
for (it_v = vars.begin(); it_v != vars.end(); ++it_v) {
for(ira = (*it_v)->attrs.begin(); ira!= (*it_v)->attrs.end();ira++) {
if((attr_name_be_replaced == (*ira)->name)) {
if((*ira)->dtype == H5FSTRING)
Change_Attr_One_Str_to_Others((*ira),(*it_v));
(*ira)->name = attr_new_name;
(*ira)->newname = attr_new_name;
}
}
}
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
for(ira = (*irv)->attrs.begin(); ira!= (*irv)->attrs.end();ira++) {
if(attr_name_be_replaced == (*ira)->name) {
if((*ira)->dtype == H5FSTRING)
Change_Attr_One_Str_to_Others((*ira),(*irv));
(*ira)->name = attr_new_name;
(*ira)->newname = attr_new_name;
break;
}
}
if(product_type == GPM_L1) {
if ((*irv)->cvartype == CV_EXIST) {
for(ira = (*irv)->attrs.begin(); ira!= (*irv)->attrs.end();ira++) {
if(attr2_name_be_replaced == (*ira)->name) {
if((*irv)->name.find("Latitude") !=string::npos) {
string unit_value = "degrees_north";
(*ira)->value.clear();
Add_Str_Attr(*ira,attr2_new_name,unit_value);
//(*ira)->value.resize(unit_value.size());
//copy(unit_value.begin(),unit_value.end(),(*ira)->value.begin());
}
else if((*irv)->name.find("Longitude") !=string::npos) {
string unit_value = "degrees_east";
(*ira)->value.clear();
Add_Str_Attr(*ira,attr2_new_name,unit_value);
//(*ira)->value.resize(unit_value.size());
//copy(unit_value.begin(),unit_value.end(),(*ira)->value.begin());
}
}
}
}
else if ((*irv)->cvartype == CV_NONLATLON_MISS) {
string comment;
const string attrname = "comment";
Attribute*attr = new Attribute();
{
if((*irv)->name == "nchannel1")
comment = "Number of Swath S1 channels (10V 10H 19V 19H 23V 37V 37H 89V 89H).";
else if((*irv)->name == "nchannel2")
comment = "Number of Swath S2 channels (166V 166H 183+/-3V 183+/-8V).";
else if((*irv)->name == "nchan1")
comment = "Number of channels in Swath 1.";
else if((*irv)->name == "nchan2")
comment = "Number of channels in Swath 2.";
else if((*irv)->name == "VH")
comment = "Number of polarizations.";
else if((*irv)->name == "GMIxyz")
comment = "x, y, z components in GMI instrument coordinate system.";
else if((*irv)->name == "LNL")
comment = "Linear and non-linear.";
else if((*irv)->name == "nscan")
comment = "Number of scans in the granule.";
else if((*irv)->name == "nscan1")
comment = "Typical number of Swath S1 scans in the granule.";
else if((*irv)->name == "nscan2")
comment = "Typical number of Swath S2 scans in the granule.";
else if((*irv)->name == "npixelev")
comment = "Number of earth view pixels in one scan.";
else if((*irv)->name == "npixelht")
comment = "Number of hot load pixels in one scan.";
else if((*irv)->name == "npixelcs")
comment = "Number of cold sky pixels in one scan.";
else if((*irv)->name == "npixelfr")
comment = "Number of full rotation earth view pixels in one scan.";
else if((*irv)->name == "nfreq1")
comment = "Number of frequencies in Swath 1.";
else if((*irv)->name == "nfreq2")
comment = "Number of frequencies in Swath 2.";
else if((*irv)->name == "npix1")
comment = "Number of pixels in Swath 1.";
else if((*irv)->name == "npix2")
comment = "Number of pixels in Swath 2.";
else if((*irv)->name == "npix3")
comment = "Number of pixels in Swath 3.";
else if((*irv)->name == "npix4")
comment = "Number of pixels in Swath 4.";
else if((*irv)->name == "ncolds1")
comment = "Maximum number of cold samples in Swath 1.";
else if((*irv)->name == "ncolds2")
comment = "Maximum number of cold samples in Swath 2.";
else if((*irv)->name == "nhots1")
comment = "Maximum number of hot samples in Swath 1.";
else if((*irv)->name == "nhots2")
comment = "Maximum number of hot samples in Swath 2.";
else if((*irv)->name == "ntherm")
comment = "Number of hot load thermisters.";
else if((*irv)->name == "ntach")
comment = "Number of tachometer readings.";
else if((*irv)->name == "nsamt"){
comment = "Number of sample types. ";
comment = +"The types are: total science GSDR, earthview,hot load, cold sky.";
}
else if((*irv)->name == "nndiode")
comment = "Number of noise diodes.";
else if((*irv)->name == "n7")
comment = "Number seven.";
else if((*irv)->name == "nray")
comment = "Number of angle bins in each NS scan.";
else if((*irv)->name == "nrayMS")
comment = "Number of angle bins in each MS scan.";
else if((*irv)->name == "nrayHS")
comment = "Number of angle bins in each HS scan.";
else if((*irv)->name == "nbin")
comment = "Number of range bins in each NS and MS ray. Bin interval is 125m.";
else if((*irv)->name == "nbinHS")
comment = "Number of range bins in each HS ray. Bin interval is 250m.";
else if((*irv)->name == "nbinSZP")
comment = "Number of range bins for sigmaZeroProfile.";
else if((*irv)->name == "nbinSZPHS")
comment = "Number of range bins for sigmaZeroProfile in each HS scan.";
else if((*irv)->name == "nNP")
comment = "Number of NP kinds.";
else if((*irv)->name == "nearFar")
comment = "Near reference, Far reference.";
else if((*irv)->name == "foreBack")
comment = "Forward, Backward.";
else if((*irv)->name == "method")
comment = "Number of SRT methods.";
else if((*irv)->name == "nNode")
comment = "Number of binNode.";
else if((*irv)->name == "nDSD")
comment = "Number of DSD parameters. Parameters are N0 and D0";
else if((*irv)->name == "LS")
comment = "Liquid, solid.";
}
if(""==comment)
delete attr;
else {
Add_Str_Attr(attr,attrname,comment);
(*irv)->attrs.push_back(attr);
}
}
}
if(product_type == GPMS_L3 || product_type == GPMM_L3) {
if ((*irv)->cvartype == CV_NONLATLON_MISS) {
string comment;
const string attrname = "comment";
Attribute*attr = new Attribute();
{
if((*irv)->name == "chn")
comment = "Number of channels:Ku,Ka,KaHS,DPR.";
else if((*irv)->name == "inst")
comment = "Number of instruments:Ku,Ka,KaHS.";
else if((*irv)->name == "tim")
comment = "Number of hours(local time).";
else if((*irv)->name == "ang"){
comment = "Number of angles.The meaning of ang is different for each channel.";
comment +=
"For Ku channel all indices are used with the meaning 0,1,2,..6 =angle bins 24,";
comment +=
"(20,28),(16,32),(12,36),(8,40),(3,44),and (0,48).";
comment +=
"For Ka channel 4 indices are used with the meaning 0,1,2,3 = angle bins 12,(8,16),";
comment +=
"(4,20),and (0,24). For KaHS channel 4 indices are used with the meaning 0,1,2,3 =";
comment += "angle bins(11,2),(7,16),(3,20),and (0.23).";
}
else if((*irv)->name == "rt")
comment = "Number of rain types: stratiform, convective,all.";
else if((*irv)->name == "st")
comment = "Number of surface types:ocean,land,all.";
else if((*irv)->name == "bin"){
comment = "Number of bins in histogram. The thresholds are different for different";
comment +=" variables. see the file specification for this algorithm.";
}
else if((*irv)->name == "nvar") {
comment = "Number of phase bins. Bins are counts of phase less than 100, ";
comment +="counts of phase greater than or equal to 100 and less than 200, ";
comment +="counts of phase greater than or equal to 200.";
}
else if((*irv)->name == "AD")
comment = "Ascending or descending half of the orbit.";
}
if(""==comment)
delete attr;
else {
Add_Str_Attr(attr,attrname,comment);
(*irv)->attrs.push_back(attr);
}
}
}
if ((*irv)->cvartype == CV_SPECIAL) {
if((*irv)->name == "nlayer" || (*irv)->name == "hgt"
|| (*irv)->name == "nalt") {
Attribute*attr = new Attribute();
string unit_value = "km";
Add_Str_Attr(attr,attr2_new_name,unit_value);
(*irv)->attrs.push_back(attr);
Attribute*attr1 = new Attribute();
string attr1_axis="axis";
string attr1_value = "Z";
Add_Str_Attr(attr1,attr1_axis,attr1_value);
(*irv)->attrs.push_back(attr1);
Attribute*attr2 = new Attribute();
string attr2_positive="positive";
string attr2_value = "up";
Add_Str_Attr(attr2,attr2_positive,attr2_value);
(*irv)->attrs.push_back(attr2);
}
if((*irv)->name == "hgt" || (*irv)->name == "nalt"){
Attribute*attr1 = new Attribute();
string comment ="Number of heights above the earth ellipsoid";
Add_Str_Attr(attr1,"comment",comment);
(*irv)->attrs.push_back(attr1);
}
}
}
// Old code, leave it for the time being
#if 0
const string fill_value_attr_name = "_FillValue";
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
bool has_fillvalue = false;
for(ira = (*it_v)->attrs.begin(); ira!= (*it_v)->attrs.end();ira++) {
if (fill_value_attr_name == (*ira)->name){
has_fillvalue = true;
break;
}
}
// Add the fill value
if (has_fillvalue != true ) {
if(H5FLOAT32 == (*it_v)->dtype) {
Attribute* attr = new Attribute();
float _FillValue = -9999.9;
Add_One_Float_Attr(attr,fill_value_attr_name,_FillValue);
(*it_v)->attrs.push_back(attr);
}
}
}// for (it_v = vars.begin(); ...
#endif
}
// Add attributes for Aquarius products
void
GMFile:: Add_Aqu_Attrs() throw(Exception) {
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
const string orig_longname_attr_name = "Parameter";
const string longname_attr_name ="long_name";
string longname_value;
const string orig_units_attr_name = "Units";
const string units_attr_name = "units";
string units_value;
// const string orig_valid_min_attr_name = "Data Minimum";
const string orig_valid_min_attr_name = "Data Minimum";
const string valid_min_attr_name = "valid_min";
float valid_min_value;
const string orig_valid_max_attr_name = "Data Maximum";
const string valid_max_attr_name = "valid_max";
float valid_max_value;
// The fill value is -32767.0. However, No _FillValue attribute is added.
// So add it here. KY 2012-2-16
const string fill_value_attr_name = "_FillValue";
float _FillValue = -32767.0;
for (ira = this->root_attrs.begin(); ira != this->root_attrs.end(); ++ira) {
if (orig_longname_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
longname_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),longname_value.begin());
}
else if (orig_units_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
units_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),units_value.begin());
}
else if (orig_valid_min_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
memcpy(&valid_min_value,(void*)(&((*ira)->value[0])),(*ira)->value.size());
}
else if (orig_valid_max_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
memcpy(&valid_max_value,(void*)(&((*ira)->value[0])),(*ira)->value.size());
}
}// for (ira = this->root_attrs.begin(); ira != this->root_attrs.end(); ++ira)
// New version Aqu(Q20112132011243.L3m_MO_SCI_V3.0_SSS_1deg.bz2) files seem to have CF attributes added.
// In this case, we should not add extra CF attributes, or duplicate values may appear. KY 2015-06-20
bool has_long_name = false;
bool has_units = false;
bool has_valid_min = false;
bool has_valid_max = false;
bool has_fillvalue = false;
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
if ("l3m_data" == (*it_v)->name) {
for (ira = (*it_v)->attrs.begin(); ira != (*it_v)->attrs.end(); ++ira) {
if (longname_attr_name == (*ira)->name)
has_long_name = true;
else if(units_attr_name == (*ira)->name)
has_units = true;
else if(valid_min_attr_name == (*ira)->name)
has_valid_min = true;
else if(valid_max_attr_name == (*ira)->name)
has_valid_max = true;
else if(fill_value_attr_name == (*ira)->name)
has_fillvalue = true;
}
break;
}
} // for (it_v = vars.begin(); ...
// Level 3 variable name is l3m_data
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
if ("l3m_data" == (*it_v)->name) {
Attribute *attr = NULL;
// 1. Add the long_name attribute if no
if(false == has_long_name) {
attr = new Attribute();
Add_Str_Attr(attr,longname_attr_name,longname_value);
(*it_v)->attrs.push_back(attr);
}
// 2. Add the units attribute
if(false == has_units) {
attr = new Attribute();
Add_Str_Attr(attr,units_attr_name,units_value);
(*it_v)->attrs.push_back(attr);
}
// 3. Add the valid_min attribute
if(false == has_valid_min) {
attr = new Attribute();
Add_One_Float_Attr(attr,valid_min_attr_name,valid_min_value);
(*it_v)->attrs.push_back(attr);
}
// 4. Add the valid_max attribute
if(false == has_valid_max) {
attr = new Attribute();
Add_One_Float_Attr(attr,valid_max_attr_name,valid_max_value);
(*it_v)->attrs.push_back(attr);
}
// 5. Add the _FillValue attribute
if(false == has_fillvalue) {
attr = new Attribute();
Add_One_Float_Attr(attr,fill_value_attr_name,_FillValue);
(*it_v)->attrs.push_back(attr);
}
break;
}
} // for (it_v = vars.begin(); ...
}
// Add SeaWiFS attributes
void
GMFile:: Add_SeaWiFS_Attrs() throw(Exception) {
// The fill value is -999.0. However, No _FillValue attribute is added.
// So add it here. KY 2012-2-16
const string fill_value_attr_name = "_FillValue";
float _FillValue = -999.0;
const string valid_range_attr_name = "valid_range";
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
if (H5FLOAT32 == (*it_v)->dtype) {
bool has_fillvalue = false;
bool has_validrange = false;
for(ira = (*it_v)->attrs.begin(); ira!= (*it_v)->attrs.end();ira++) {
if (fill_value_attr_name == (*ira)->name){
has_fillvalue = true;
break;
}
else if(valid_range_attr_name == (*ira)->name) {
has_validrange = true;
break;
}
}
// Add the fill value
if (has_fillvalue != true && has_validrange != true ) {
Attribute* attr = new Attribute();
Add_One_Float_Attr(attr,fill_value_attr_name,_FillValue);
(*it_v)->attrs.push_back(attr);
}
}// if (H5FLOAT32 == (*it_v)->dtype)
}// for (it_v = vars.begin(); ...
}
#if 0
// Handle the "coordinates" and "units" attributes of coordinate variables.
void GMFile:: Handle_Coor_Attr() {
string co_attrname = "coordinates";
string co_attrvalue="";
string unit_attrname = "units";
string nonll_unit_attrvalue ="level";
string lat_unit_attrvalue ="degrees_north";
string lon_unit_attrvalue ="degrees_east";
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
//cerr<<"CV name is "<<(*ircv)->name << " cv type is "<<(*ircv)->cvartype <<endl;
if ((*ircv)->cvartype == CV_NONLATLON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,nonll_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
else if ((*ircv)->cvartype == CV_LAT_MISS) {
//cerr<<"Should add new attribute "<<endl;
Attribute * attr = new Attribute();
// float temp = -999.9;
// Add_One_Float_Attr(attr,unit_attrname,temp);
Add_Str_Attr(attr,unit_attrname,lat_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
//cerr<<"After adding new attribute "<<endl;
}
else if ((*ircv)->cvartype == CV_LON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,lon_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin(); ...
// No need to handle MeaSUREs SeaWiFS level 2 products
if(product_type == Mea_SeaWiFS_L2)
return;
// GPM level 1 needs to be handled separately
else if(product_type == GPM_L1) {
Handle_GPM_l1_Coor_Attr();
return;
}
// No need to handle products that follow COARDS.
else if (true == iscoard) {
// May need to check coordinates for 2-D lat/lon but cannot treat those lat/lon as CV case. KY 2015-12-10-TEMPPP
return;
}
// Now handle the 2-D lat/lon case(note: this only applies to the one that dim. scale doesn't apply)
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2) {
// The following code makes sure that the replacement only happens with the general 2-D lat/lon case.
if(gp_latname == (*ircv)->name)
Replace_Var_Str_Attr((*ircv),unit_attrname,lat_unit_attrvalue);
else if(gp_lonname ==(*ircv)->name)
Replace_Var_Str_Attr((*ircv),unit_attrname,lon_unit_attrvalue);
}
}
// Check the dimension names of 2-D lat/lon CVs
string ll2d_dimname0,ll2d_dimname1;
bool has_ll2d_coords = false;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2) {
// Note: we should still use the original dim. name to match the general variables.
ll2d_dimname0 = (*ircv)->getDimensions()[0]->name;
ll2d_dimname1 = (*ircv)->getDimensions()[1]->name;
if(ll2d_dimname0 !="" && ll2d_dimname1 !="")
has_ll2d_coords = true;
break;
}
}
if(true == has_ll2d_coords) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool coor_attr_keep_exist = false;
// May need to delete only the "coordinates" with both 2-D lat/lon dim. KY 2015-12-07
if(((*irv)->rank >=2)) {
short ll2dim_flag = 0;
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ ird) {
if((*ird)->name == ll2d_dimname0)
ll2dim_flag++;
else if((*ird)->name == ll2d_dimname1)
ll2dim_flag++;
}
if(ll2dim_flag != 2)
coor_attr_keep_exist = true;
// Remove the following code later since the released SMAP products are different. KY 2015-12-08
if(product_type == SMAP)
coor_attr_keep_exist = true;
if (false == coor_attr_keep_exist) {
for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin();
ira !=(*irv)->attrs.end();) {
if ((*ira)->newname == co_attrname) {
delete (*ira);
ira = (*irv)->attrs.erase(ira);
}
else {
++ira;
}
}// for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin(); ...
// Generate the "coordinates" attribute only for variables that have both 2-D lat/lon dim. names.
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ ird) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if ((*ird)->name == (*ircv)->cfdimname)
co_attrvalue = (co_attrvalue.empty())
?(*ircv)->newname:co_attrvalue + " "+(*ircv)->newname;
}
}
if (false == co_attrvalue.empty()) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,co_attrname,co_attrvalue);
(*irv)->attrs.push_back(attr);
}
co_attrvalue.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
}
}
}
#endif
// Handle the "coordinates" and "units" attributes of coordinate variables.
void GMFile:: Handle_Coor_Attr() {
string co_attrname = "coordinates";
string co_attrvalue="";
string unit_attrname = "units";
string nonll_unit_attrvalue ="level";
string lat_unit_attrvalue ="degrees_north";
string lon_unit_attrvalue ="degrees_east";
//cerr<<"coming to handle 2-D lat/lon CVs first ."<<endl;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
//cerr<<"CV name is "<<(*ircv)->name << " cv type is "<<(*ircv)->cvartype <<endl;
if ((*ircv)->cvartype == CV_NONLATLON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,nonll_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
else if ((*ircv)->cvartype == CV_LAT_MISS) {
//cerr<<"Should add new attribute "<<endl;
Attribute * attr = new Attribute();
// float temp = -999.9;
// Add_One_Float_Attr(attr,unit_attrname,temp);
Add_Str_Attr(attr,unit_attrname,lat_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
//cerr<<"After adding new attribute "<<endl;
}
else if ((*ircv)->cvartype == CV_LON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,lon_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin(); ...
// No need to handle MeaSUREs SeaWiFS level 2 products
if(product_type == Mea_SeaWiFS_L2)
return;
// GPM level 1 needs to be handled separately
else if(product_type == GPM_L1) {
Handle_GPM_l1_Coor_Attr();
return;
}
// Handle Lat/Lon with "coordinates" attribute.
else if(product_type == General_Product && gproduct_pattern == GENERAL_LATLON_COOR_ATTR){
Handle_LatLon_With_CoordinateAttr_Coor_Attr();
return;
}
// No need to handle products that follow COARDS.
else if (true == iscoard) {
// If we find that there are groups that should check the coordinates attribute of the variable.
// We should flatten the path inside the coordinates..
if(grp_cv_paths.size() >0) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if(grp_cv_paths.find(HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath)) != grp_cv_paths.end()){
// Check the "coordinates" attribute and flatten the values.
Flatten_VarPath_In_Coordinates_Attr(*irv);
}
}
}
return;
}
// Now handle the 2-D lat/lon case
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2 && (*ircv)->cvartype == CV_EXIST) {
//Note: When the 2nd parameter is true in the function Is_geolatlon, it checks the lat/latitude/Latitude
// When the 2nd parameter is false in the function Is_geolatlon, it checks the lon/longitude/Longitude
// The following code makes sure that the replacement only happens with the general 2-D lat/lon case.
if(gp_latname == (*ircv)->name) {
// Only if gp_latname is not lat/latitude/Latitude, change the units
if(false == Is_geolatlon(gp_latname,true))
Replace_Var_Str_Attr((*ircv),unit_attrname,lat_unit_attrvalue);
}
else if(gp_lonname ==(*ircv)->name) {
// Only if gp_lonname is not lon/longitude/Longitude, change the units
if(false == Is_geolatlon(gp_lonname,false))
Replace_Var_Str_Attr((*ircv),unit_attrname,lon_unit_attrvalue);
}
// We meet several products that miss the 2-D latitude and longitude CF units although they
// have the CV names like latitude/longitude, we should double check this case,
// add add the correct CF units if possible. We will watch if this is the right way.
else if(true == Is_geolatlon((*ircv)->name,true))
Replace_Var_Str_Attr((*ircv),unit_attrname,lat_unit_attrvalue);
else if(true == Is_geolatlon((*ircv)->name,false))
Replace_Var_Str_Attr((*ircv),unit_attrname,lon_unit_attrvalue);
}
}
// If we find that there are groups that should check the coordinates attribute of the variable.
// We should flatten the path inside the coordinates. Note this is for 2D-latlon CV case.
if(grp_cv_paths.size() >0) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
//cerr<<"the group of this variable is "<< HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
if(grp_cv_paths.find(HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath)) != grp_cv_paths.end()){
// Check the "coordinates" attribute and flatten the values.
Flatten_VarPath_In_Coordinates_Attr(*irv);
}
}
}
// Check if having 2-D lat/lon CVs
bool has_ll2d_coords = false;
// Since iscoard is false up to this point, So the netCDF-4 like 2-D lat/lon case must fulfill if the program comes here.
if(General_Product == this->product_type && GENERAL_DIMSCALE == this->gproduct_pattern)
has_ll2d_coords = true;
else {// For other cases.
string ll2d_dimname0,ll2d_dimname1;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2) {
// Note: we should still use the original dim. name to match the general variables.
ll2d_dimname0 = (*ircv)->getDimensions()[0]->name;
ll2d_dimname1 = (*ircv)->getDimensions()[1]->name;
if(ll2d_dimname0 !="" && ll2d_dimname1 !="")
has_ll2d_coords = true;
break;
}
}
}
if(true == has_ll2d_coords) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool coor_attr_keep_exist = false;
if(((*irv)->rank >=2)) {
// Check if this var is under group_cv_paths, no, then check if this var's dims are the same as the dims of 2-D CVars
if(grp_cv_paths.find(HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath)) == grp_cv_paths.end())
// If finding this var is associated with 2-D lat/lon CVs, not keep the original "coordinates" attribute.
coor_attr_keep_exist = Check_Var_2D_CVars(*irv);
else {
coor_attr_keep_exist = true;
}
// Remove the following code later since the released SMAP products are different. KY 2015-12-08
if(product_type == SMAP)
coor_attr_keep_exist = true;
// Need to delete the original "coordinates" and rebuild the "coordinates" if this var is associated with the 2-D lat/lon CVs.
if (false == coor_attr_keep_exist) {
for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin();
ira !=(*irv)->attrs.end();) {
if ((*ira)->newname == co_attrname) {
delete (*ira);
ira = (*irv)->attrs.erase(ira);
}
else {
++ira;
}
}// for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin(); ...
// Generate the new "coordinates" attribute.
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ ird) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if ((*ird)->name == (*ircv)->cfdimname)
co_attrvalue = (co_attrvalue.empty())
?(*ircv)->newname:co_attrvalue + " "+(*ircv)->newname;
}
}
if (false == co_attrvalue.empty()) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,co_attrname,co_attrvalue);
(*irv)->attrs.push_back(attr);
}
co_attrvalue.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
}
}
}
// Handle GPM level 1 coordiantes attributes.
void GMFile:: Handle_GPM_l1_Coor_Attr() throw(Exception){
// Build a map from CFdimname to 2-D lat/lon variable name, should be something like: aa_list[cfdimname]=s1_latitude .
// Loop all variables
// Inner loop: for all dims of a var
// if(dimname matches the dim(not cfdim) name of one of 2-D lat/lon,
// check if the variable's full path contains the path of one of 2-D lat/lon,
// yes, build its cfdimname = path+ dimname, check this cfdimname with the cfdimname of the corresponding 2-D lat/lon
// If matched, save this latitude variable name as one of the coordinate variable.
// else this is a 3rd-dimension cv, just use the dimension name(or the corresponding cv name maybe through a map).
// Prepare 1) 2-D CVar(lat,lon) corresponding dimension name set.
// 2) cfdim name to cvar name map(don't need to use a map, just a holder. It should be fine.
// "coordinates" attribute name and value. We only need to provide this atttribute for variables that have 2-D lat/lon
string co_attrname = "coordinates";
string co_attrvalue="";
// 2-D cv dimname set.
set<string> cvar_2d_dimset;
pair<map<string,string>::iterator,bool>mapret;
// Hold the mapping from cfdimname to 2-D cvar name. Something like nscan->lat, npixel->lon
map<string,string>cfdimname_to_cvar2dname;
// Loop through cv variables to build 2-D cv dimname set and the mapping from cfdimname to 2-D cvar name.
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
//This CVar must be 2-D array.
if((*irv)->rank == 2) {
//cerr<<"2-D cv name is "<<(*irv)->name <<endl;
//cerr<<"2-D cv new name is "<<(*irv)->newname <<endl;
//cerr<<"(*irv)->cfdimname is "<<(*irv)->cfdimname <<endl;
for(vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
cvar_2d_dimset.insert((*ird)->name);
}
// Generate cfdimname to cvar2d map
mapret = cfdimname_to_cvar2dname.insert(pair<string,string>((*irv)->cfdimname,(*irv)->newname));
if (false == mapret.second)
throw4("The cf dimension name ",(*irv)->cfdimname," should map to 2-D coordinate variable",
(*irv)->newname);
}
}
// Loop through the variable list to build the coordinates.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// Only apply to >2D variables.
if((*irv)->rank >=2) {
// The variable dimension names must be found in the 2D cvar dim. nameset.
// The flag must be at least 2.
short have_2d_dimnames_flag = 0;
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
if (cvar_2d_dimset.find((*ird)->name)!=cvar_2d_dimset.end())
have_2d_dimnames_flag++;
}
// Final candidates to have 2-D CVar coordinates.
if(have_2d_dimnames_flag >=2) {
//cerr<<"var name "<<(*irv)->name <<" has 2-D CVar coordinates "<<endl;
// Obtain the variable path
string var_path;
if((*irv)->fullpath.size() > (*irv)->name.size())
var_path=(*irv)->fullpath.substr(0,(*irv)->fullpath.size()-(*irv)->name.size());
else
throw4("The variable full path ",(*irv)->fullpath," doesn't contain the variable name ",
(*irv)->name);
// A flag to identify if this variable really needs the 2-D coordinate variables.
short cv_2d_flag = 0;
// 2-D coordinate variable names for the potential variable candidate
vector<string> cv_2d_names;
// Dimension names of the 2-D coordinate variables.
set<string> cv_2d_dimnames;
// Loop through the map from dim. name to coordinate name.
for(map<string,string>::const_iterator itm = cfdimname_to_cvar2dname.begin();
itm != cfdimname_to_cvar2dname.end();++itm) {
// Obtain the dimension name from the cfdimname.
string reduced_dimname = HDF5CFUtil::obtain_string_after_lastslash(itm->first);
//cerr<<"reduced_dimname is "<<reduced_dimname <<endl;
string cfdim_path;
if(itm->first.size() <= reduced_dimname.size())
throw2("The cf dim. name of this dimension is not right.",itm->first);
else
cfdim_path= itm->first.substr(0,itm->first.size() - reduced_dimname.size());
// cfdim_path will not be NULL only when the cfdim name is for the 2-D cv var.
//cerr<<"var_path is "<<var_path <<endl;
//cerr<<"cfdim_path is "<<cfdim_path <<endl;
// Find the correct path,
// Note:
// var_path doesn't have to be the same as cfdim_path
// consider the variable /a1/a2/foo and the latitude /a1/latitude(cfdimpath is /a1)
// If there is no /a1/a2/latitude, the /a1/latitude can be used as the coordinate of /a1/a2/foo.
// But we want to check if var_path is the same as cfdim_path first. So we check cfdimname_to_cvarname again.
if(var_path == cfdim_path) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end();++ird) {
if(reduced_dimname == (*ird)->name) {
cv_2d_flag++;
cv_2d_names.push_back(itm->second);
cv_2d_dimnames.insert((*ird)->name);
}
}
}
}
// Note:
// var_path doesn't have to be the same as cfdim_path
// consider the variable /a1/a2/foo and the latitude /a1/latitude(cfdimpath is /a1)
// If there is no /a1/a2/latitude, the /a1/latitude can be used as the coordinate of /a1/a2/foo.
// The variable has 2 coordinates(dimensions) if the flag is 2
// If the flag is not 2, we will see if the above case stands.
if(cv_2d_flag != 2) {
cv_2d_flag = 0;
// Loop through the map from dim. name to coordinate name.
for(map<string,string>::const_iterator itm = cfdimname_to_cvar2dname.begin();
itm != cfdimname_to_cvar2dname.end();++itm) {
// Obtain the dimension name from the cfdimname.
string reduced_dimname = HDF5CFUtil::obtain_string_after_lastslash(itm->first);
string cfdim_path;
if(itm->first.size() <= reduced_dimname.size())
throw2("The cf dim. name of this dimension is not right.",itm->first);
else
cfdim_path= itm->first.substr(0,itm->first.size() - reduced_dimname.size());
// cfdim_path will not be NULL only when the cfdim name is for the 2-D cv var.
// Find the correct path,
// Note:
// var_path doesn't have to be the same as cfdim_path
// consider the variable /a1/a2/foo and the latitude /a1/latitude(cfdimpath is /a1)
// If there is no /a1/a2/latitude, the /a1/latitude can be used as the coordinate of /a1/a2/foo.
//
if(var_path.find(cfdim_path)!=string::npos) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end();++ird) {
if(reduced_dimname == (*ird)->name) {
cv_2d_flag++;
cv_2d_names.push_back(itm->second);
cv_2d_dimnames.insert((*ird)->name);
}
}
}
}
}
// Now we got all cases.
if(2 == cv_2d_flag) {
// Add latitude and longitude to the 'coordinates' attribute.
co_attrvalue = cv_2d_names[0] + " " + cv_2d_names[1];
if((*irv)->rank >2) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
// Add 3rd-dimension to the 'coordinates' attribute.
if(cv_2d_dimnames.find((*ird)->name) == cv_2d_dimnames.end())
co_attrvalue = co_attrvalue + " " +(*ird)->newname;
}
}
Attribute * attr = new Attribute();
Add_Str_Attr(attr,co_attrname,co_attrvalue);
(*irv)->attrs.push_back(attr);
}
}
}
}
}
void GMFile::Handle_LatLon_With_CoordinateAttr_Coor_Attr() throw(Exception) {
}
// Create Missing coordinate variables. Index numbers are used for these variables.
void GMFile:: Create_Missing_CV(GMCVar *GMcvar, const string& dimname) throw(Exception) {
GMcvar->name = dimname;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5INT32;
hsize_t gmcvar_dimsize = dimname_to_dimsize[dimname];
Dimension* gmcvar_dim = new Dimension(gmcvar_dimsize);
gmcvar_dim->name = dimname;
gmcvar_dim->newname = dimname;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = dimname;
GMcvar->cvartype = CV_NONLATLON_MISS;
GMcvar->product_type = product_type;
}
// Check if this is just a netCDF-4 dimension. We need to check the dimension scale dataset attribute "NAME",
// the value should start with "This is a netCDF dimension but not a netCDF variable".
bool GMFile::Is_netCDF_Dimension(Var *var) throw(Exception) {
string netcdf_dim_mark = "This is a netCDF dimension but not a netCDF variable";
bool is_only_dimension = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if ("NAME" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,var->fullpath);
string name_value;
name_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),name_value.begin());
// Compare the attribute "NAME" value with the string netcdf_dim_mark. We only compare the string with the size of netcdf_dim_mark
if (0 == name_value.compare(0,netcdf_dim_mark.size(),netcdf_dim_mark))
is_only_dimension = true;
break;
}
} // for(vector<Attribute *>::iterator ira = var->attrs.begin(); ...
return is_only_dimension;
}
// Handle attributes for special variables.
void
GMFile::Handle_SpVar_Attr() throw(Exception) {
}
void
GMFile::release_standalone_GMCVar_vector(vector<GMCVar*>&tempgc_vars){
for (vector<GMCVar *>::iterator i = tempgc_vars.begin();
i != tempgc_vars.end(); ) {
delete(*i);
i = tempgc_vars.erase(i);
}
}
#if 0
void
GMFile::add_ignored_info_attrs(bool is_grp,bool is_first){
}
void
GMFile::add_ignored_info_objs(bool is_dim_related, bool is_first) {
}
#endif
#if 0
bool
GMFile::ignored_dimscale_ref_list(Var *var) {
bool ignored_dimscale = true;
if(General_Product == this->product_type && GENERAL_DIMSCALE== this->gproduct_pattern) {
bool has_dimscale = false;
bool has_reference_list = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if((*ira)->name == "REFERENCE_LIST" &&
false == HDF5CFUtil::cf_strict_support_type((*ira)->getType()))
has_reference_list = true;
if((*ira)->name == "CLASS") {
Retrieve_H5_Attr_Value(*ira,var->fullpath);
string class_value;
class_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),class_value.begin());
// Compare the attribute "CLASS" value with "DIMENSION_SCALE". We only compare the string with the size of
// "DIMENSION_SCALE", which is 15.
if (0 == class_value.compare(0,15,"DIMENSION_SCALE")) {
has_dimscale = true;
}
}
if(true == has_dimscale && true == has_reference_list) {
ignored_dimscale= false;
break;
}
}
}
return ignored_dimscale;
}
#endif
2D latlon check
// This file is part of the hdf5_handler implementing for the CF-compliant
// Copyright (c) 2011-2013 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
/////////////////////////////////////////////////////////////////////////////
/// \file HDF5GMCF.cc
/// \brief Implementation of the mapping of NASA generic HDF5 products to DAP by following CF
///
/// It includes functions to
/// 1) retrieve HDF5 metadata info.
/// 2) translate HDF5 objects into DAP DDS and DAS by following CF conventions.
///
///
/// \author Muqun Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2013 The HDF Group
///
/// All rights reserved.
#include "HDF5CF.h"
#include <BESDebug.h>
#include <algorithm>
//#include <sstream>
using namespace HDF5CF;
GMCVar::GMCVar(Var*var) {
newname = var->newname;
name = var->name;
fullpath = var->fullpath;
rank = var->rank;
dtype = var->dtype;
unsupported_attr_dtype = var->unsupported_attr_dtype;
unsupported_dspace = var->unsupported_dspace;
for (vector<Attribute*>::iterator ira = var->attrs.begin();
ira!=var->attrs.end(); ++ira) {
Attribute* attr= new Attribute();
attr->name = (*ira)->name;
attr->newname = (*ira)->newname;
attr->dtype =(*ira)->dtype;
attr->count =(*ira)->count;
attr->strsize = (*ira)->strsize;
attr->fstrsize = (*ira)->fstrsize;
attr->value =(*ira)->value;
attrs.push_back(attr);
}
for (vector<Dimension*>::iterator ird = var->dims.begin();
ird!=var->dims.end(); ++ird) {
Dimension *dim = new Dimension((*ird)->size);
//"h5","dim->name "<< (*ird)->name <<endl;
//"h5","dim->newname "<< (*ird)->newname <<endl;
dim->name = (*ird)->name;
dim->newname = (*ird)->newname;
dims.push_back(dim);
}
product_type = General_Product;
}
#if 0
GMCVar::GMCVar(GMCVar*cvar) {
newname = cvar->newname;
name = cvar->name;
fullpath = cvar->fullpath;
rank = cvar->rank;
dtype = cvar->dtype;
unsupported_attr_dtype = cvar->unsupported_attr_dtype;
unsupported_dspace = cvar->unsupported_dspace;
for (vector<Attribute*>::iterator ira = cvar->attrs.begin();
ira!=cvar->attrs.end(); ++ira) {
Attribute* attr= new Attribute();
attr->name = (*ira)->name;
attr->newname = (*ira)->newname;
attr->dtype =(*ira)->dtype;
attr->count =(*ira)->count;
attr->strsize = (*ira)->strsize;
attr->fstrsize = (*ira)->fstrsize;
attr->value =(*ira)->value;
attrs.push_back(attr);
}
for (vector<Dimension*>::iterator ird = cvar->dims.begin();
ird!=cvar->dims.end(); ++ird) {
Dimension *dim = new Dimension((*ird)->size);
//"h5","dim->name "<< (*ird)->name <<endl;
//"h5","dim->newname "<< (*ird)->newname <<endl;
dim->name = (*ird)->name;
dim->newname = (*ird)->newname;
dims.push_back(dim);
}
GMcvar->cfdimname = latdim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
}
#endif
GMSPVar::GMSPVar(Var*var) {
fullpath = var->fullpath;
rank = var->rank;
unsupported_attr_dtype = var->unsupported_attr_dtype;
unsupported_dspace = var->unsupported_dspace;
for (vector<Attribute*>::iterator ira = var->attrs.begin();
ira!=var->attrs.end(); ++ira) {
Attribute* attr= new Attribute();
attr->name = (*ira)->name;
attr->newname = (*ira)->newname;
attr->dtype =(*ira)->dtype;
attr->count =(*ira)->count;
attr->strsize = (*ira)->strsize;
attr->fstrsize = (*ira)->fstrsize;
attr->value =(*ira)->value;
attrs.push_back(attr);
} // for (vector<Attribute*>::iterator ira = var->attrs.begin();
for (vector<Dimension*>::iterator ird = var->dims.begin();
ird!=var->dims.end(); ++ird) {
Dimension *dim = new Dimension((*ird)->size);
dim->name = (*ird)->name;
dim->newname = (*ird)->newname;
dims.push_back(dim);
}
}
GMFile::GMFile(const char*path, hid_t file_id, H5GCFProduct product_type, GMPattern gproduct_pattern):
File(path,file_id), product_type(product_type),gproduct_pattern(gproduct_pattern),iscoard(false),ll2d_no_cv(false)
{
}
GMFile::~GMFile()
{
if (!this->cvars.empty()){
for (vector<GMCVar *>:: const_iterator i= this->cvars.begin(); i!=this->cvars.end(); ++i) {
delete *i;
}
}
if (!this->spvars.empty()){
for (vector<GMSPVar *>:: const_iterator i= this->spvars.begin(); i!=this->spvars.end(); ++i) {
delete *i;
}
}
}
string GMFile::get_CF_string(string s) {
// HDF5 group or variable path always starts with '/'. When CF naming rule is applied,
// the first '/' is always changes to "_", this is not necessary. However,
// to keep the backward compatiablity, I use a BES key for people to go back with the original name.
if(s[0] !='/')
return File::get_CF_string(s);
else if (General_Product == product_type && OTHERGMS == gproduct_pattern) {
string check_keepleading_underscore_key = "H5.KeepVarLeadingUnderscore";
if(true == HDF5CFDAPUtil::check_beskeys(check_keepleading_underscore_key))
return File::get_CF_string(s);
else {
s.erase(0,1);
return File::get_CF_string(s);
}
}
else {
s.erase(0,1);
return File::get_CF_string(s);
}
}
void GMFile::Retrieve_H5_Info(const char *path,
hid_t file_id, bool include_attr) throw (Exception) {
// MeaSure SeaWiFS and Ozone need the attribute info. to build the dimension name list.
// GPM needs the attribute info. to obtain the lat/lon.
// So set the include_attr to be true for these products.
if (product_type == Mea_SeaWiFS_L2 || product_type == Mea_SeaWiFS_L3
|| GPMS_L3 == product_type || GPMM_L3 == product_type || GPM_L1 == product_type || OBPG_L3 == product_type
|| Mea_Ozone == product_type || General_Product == product_type)
File::Retrieve_H5_Info(path,file_id,true);
else
File::Retrieve_H5_Info(path,file_id,include_attr);
}
void GMFile::Update_Product_Type() throw(Exception) {
if(GPMS_L3 == this->product_type || GPMM_L3 == this->product_type) {
// Check Dimscale attributes
Check_General_Product_Pattern();
if(GENERAL_DIMSCALE == this->gproduct_pattern){
if(GPMS_L3 == this->product_type) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv)
(*irv)->newname = (*irv)->name;
}
this->product_type = General_Product;
}
}
}
void GMFile::Retrieve_H5_Supported_Attr_Values() throw (Exception) {
File::Retrieve_H5_Supported_Attr_Values();
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
//if ((CV_EXIST == (*ircv)->cvartype ) || (CV_MODIFY == (*ircv)->cvartype)
// || (CV_FILLINDEX == (*ircv)->cvartype)){
if ((*ircv)->cvartype != CV_NONLATLON_MISS){
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ++ira) {
Retrieve_H5_Attr_Value(*ira,(*ircv)->fullpath);
}
}
}
for (vector<GMSPVar *>::iterator irspv = this->spvars.begin();
irspv != this->spvars.end(); ++irspv) {
for (vector<Attribute *>::iterator ira = (*irspv)->attrs.begin();
ira != (*irspv)->attrs.end(); ++ira) {
Retrieve_H5_Attr_Value(*ira,(*irspv)->fullpath);
Adjust_H5_Attr_Value(*ira);
}
}
}
void GMFile::Adjust_H5_Attr_Value(Attribute *attr) throw (Exception) {
if (product_type == ACOS_L2S_OR_OCO2_L1B) {
if (("Type" == attr->name) && (H5VSTRING == attr->dtype)) {
string orig_attrvalues(attr->value.begin(),attr->value.end());
if (orig_attrvalues != "Signed64") return;
string new_attrvalues = "Signed32";
// Since the new_attrvalues size is the same as the orig_attrvalues size
// No need to adjust the strsize and fstrsize. KY 2011-2-1
attr->value.clear();
attr->value.resize(new_attrvalues.size());
copy(new_attrvalues.begin(),new_attrvalues.end(),attr->value.begin());
}
} // if (product_type == ACOS_L2S_OR_OCO2_L1B)
}
void GMFile:: Handle_Unsupported_Dtype(bool include_attr) throw(Exception) {
if(true == check_ignored) {
Gen_Unsupported_Dtype_Info(include_attr);
}
File::Handle_Unsupported_Dtype(include_attr);
Handle_GM_Unsupported_Dtype(include_attr);
}
void GMFile:: Handle_GM_Unsupported_Dtype(bool include_attr) throw(Exception) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ) {
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
delete (*ira);
ira = (*ircv)->attrs.erase(ira);
}
else {
++ira;
}
}
}
H5DataType temp_dtype = (*ircv)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
// This may need to be checked carefully in the future,
// My current understanding is that the coordinate variable can
// be ignored if the corresponding variable is ignored.
// Currently we don't find any NASA files in this category.
// KY 2012-5-21
delete (*ircv);
ircv = this->cvars.erase(ircv);
}
else {
++ircv;
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
ircv != this->spvars.end(); ) {
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
delete (*ira);
ira = (*ircv)->attrs.erase(ira);
}
else {
++ira;
}
}
}
H5DataType temp_dtype = (*ircv)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
delete (*ircv);
ircv = this->spvars.erase(ircv);
}
else {
++ircv;
}
}// for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
}
void GMFile:: Gen_Unsupported_Dtype_Info(bool include_attr) {
if(true == include_attr) {
File::Gen_Group_Unsupported_Dtype_Info();
File::Gen_Var_Unsupported_Dtype_Info();
Gen_VarAttr_Unsupported_Dtype_Info();
}
}
void GMFile:: Gen_VarAttr_Unsupported_Dtype_Info() throw(Exception){
// First general variables(non-CV and non-special variable)
if((General_Product == this->product_type && GENERAL_DIMSCALE== this->gproduct_pattern)
|| (Mea_Ozone == this->product_type) || (Mea_SeaWiFS_L2 == this->product_type) || (Mea_SeaWiFS_L3 == this->product_type)
|| (OBPG_L3 == this->product_type)) {
Gen_DimScale_VarAttr_Unsupported_Dtype_Info();
}
else
File::Gen_VarAttr_Unsupported_Dtype_Info();
// CV and special variables
Gen_GM_VarAttr_Unsupported_Dtype_Info();
}
void GMFile:: Gen_GM_VarAttr_Unsupported_Dtype_Info(){
if((General_Product == this->product_type && GENERAL_DIMSCALE== this->gproduct_pattern)
|| (Mea_Ozone == this->product_type) || (Mea_SeaWiFS_L2 == this->product_type) || (Mea_SeaWiFS_L3 == this->product_type)
|| (OBPG_L3 == this->product_type)) {
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
// If the attribute REFERENCE_LIST comes with the attribut CLASS, the
// attribute REFERENCE_LIST is okay to ignore. No need to report.
bool is_ignored = ignored_dimscale_ref_list((*irv));
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
// "DIMENSION_LIST" is okay to ignore and "REFERENCE_LIST"
// is okay to ignore if the variable has another attribute
// CLASS="DIMENSION_SCALE"
if (("DIMENSION_LIST" !=(*ira)->name) &&
(("REFERENCE_LIST" != (*ira)->name || true == is_ignored)))
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
// If the attribute REFERENCE_LIST comes with the attribut CLASS, the
// attribute REFERENCE_LIST is okay to ignore. No need to report.
bool is_ignored = ignored_dimscale_ref_list((*irv));
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
// "DIMENSION_LIST" is okay to ignore and "REFERENCE_LIST"
// is okay to ignore if the variable has another attribute
// CLASS="DIMENSION_SCALE"
if (("DIMENSION_LIST" !=(*ira)->name) &&
(("REFERENCE_LIST" != (*ira)->name || true == is_ignored)))
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
}
else {
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
if (false == (*irv)->attrs.empty()) {
if (true == (*irv)->unsupported_attr_dtype) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
H5DataType temp_dtype = (*ira)->getType();
if (false == HDF5CFUtil::cf_strict_support_type(temp_dtype)) {
this->add_ignored_info_attrs(false,(*irv)->fullpath,(*ira)->name);
}
}
}
}
}
}
}
void GMFile:: Handle_Unsupported_Dspace() throw(Exception) {
if(true == check_ignored)
Gen_Unsupported_Dspace_Info();
File::Handle_Unsupported_Dspace();
Handle_GM_Unsupported_Dspace();
}
void GMFile:: Handle_GM_Unsupported_Dspace() throw(Exception) {
if(true == this->unsupported_var_dspace) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ) {
if (true == (*ircv)->unsupported_dspace ) {
// This may need to be checked carefully in the future,
// My current understanding is that the coordinate variable can
// be ignored if the corresponding variable is ignored.
// Currently we don't find any NASA files in this category.
// KY 2012-5-21
delete (*ircv);
ircv = this->cvars.erase(ircv);
//ircv--;
}
else {
++ircv;
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
ircv != this->spvars.end(); ) {
if (true == (*ircv)->unsupported_dspace) {
delete (*ircv);
ircv = this->spvars.erase(ircv);
}
else {
++ircv;
}
}// for (vector<GMSPVar *>::iterator ircv = this->spvars.begin();
}// if(true == this->unsupported_dspace)
}
void GMFile:: Gen_Unsupported_Dspace_Info() throw(Exception){
File::Gen_Unsupported_Dspace_Info();
}
void GMFile:: Handle_Unsupported_Others(bool include_attr) throw(Exception) {
File::Handle_Unsupported_Others(include_attr);
if(true == this->check_ignored && true == include_attr) {
// Check the drop long string feature.
string check_droplongstr_key ="H5.EnableDropLongString";
bool is_droplongstr = false;
is_droplongstr = HDF5CFDAPUtil::check_beskeys(check_droplongstr_key);
if(true == is_droplongstr){
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();++ira) {
if(true == Check_DropLongStr((*irv),(*ira))) {
this->add_ignored_droplongstr_hdr();
this->add_ignored_var_longstr_info((*irv),(*ira));
}
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();++ira) {
if(true == Check_DropLongStr((*irv),(*ira))) {
this->add_ignored_droplongstr_hdr();
this->add_ignored_var_longstr_info((*irv),(*ira));
}
}
}
}
}
if(false == this->have_ignored)
this->add_no_ignored_info();
}
void GMFile::Add_Dim_Name() throw(Exception){
switch(product_type) {
case Mea_SeaWiFS_L2:
case Mea_SeaWiFS_L3:
Add_Dim_Name_Mea_SeaWiFS();
break;
case Aqu_L3:
Add_Dim_Name_Aqu_L3();
break;
case SMAP:
Add_Dim_Name_SMAP();
break;
case ACOS_L2S_OR_OCO2_L1B:
Add_Dim_Name_ACOS_L2S_OCO2_L1B();
break;
case Mea_Ozone:
Add_Dim_Name_Mea_Ozonel3z();
break;
case GPMS_L3:
case GPMM_L3:
case GPM_L1:
Add_Dim_Name_GPM();
break;
case OBPG_L3:
Add_Dim_Name_OBPG_L3();
break;
case General_Product:
Add_Dim_Name_General_Product();
break;
default:
throw1("Cannot generate dim. names for unsupported datatype");
} // switch(product_type)
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Add_Dim_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
//Add Dim. Names for OBPG level 3 product
void GMFile::Add_Dim_Name_OBPG_L3() throw(Exception) {
// netCDF-4 like structure
Add_Dim_Name_General_Product();
}
//Add Dim. Names for MeaSures SeaWiFS. Future: May combine with the handling of netCDF-4 products
void GMFile::Add_Dim_Name_Mea_SeaWiFS() throw(Exception){
//cerr<<"coming to Add_Dim_Name_Mea_SeaWiFS"<<endl;
pair<set<string>::iterator,bool> setret;
if (Mea_SeaWiFS_L3 == product_type)
iscoard = true;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
Handle_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone((*irv));
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
if (true == dimnamelist.empty())
throw1("This product should have the dimension names, but no dimension names are found");
}
void GMFile::Handle_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone(Var* var)
throw(Exception){
Attribute* dimlistattr = NULL;
bool has_dimlist = false;
bool has_class = false;
bool has_reflist = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name) {
dimlistattr = *ira;
has_dimlist = true;
}
if ("CLASS" == (*ira)->name)
has_class = true;
if ("REFERENCE_LIST" == (*ira)->name)
has_reflist = true;
if (true == has_dimlist)
break;
if (true == has_class && true == has_reflist)
break;
} // for(vector<Attribute *>::iterator ira = var->attrs.begin(); ...
if (true == has_dimlist)
Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone(var,dimlistattr);
// Dim name is the same as the variable name for dimscale variable
else if(true == has_class && true == has_reflist) {
if (var->dims.size() !=1)
throw2("dimension scale dataset must be 1 dimension, this is not true for variable ",
var->name);
// The var name is the object name, however, we would like the dimension name to be full path.
// so that the dim name can be served as the key for future handling.
(var->dims)[0]->name = var->fullpath;
(var->dims)[0]->newname = var->fullpath;
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((var->dims)[0]->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((var->dims)[0]->name,(var->dims)[0]->size);
}
// No dimension, add fake dim names, this may never happen for MeaSure
// but just for coherence and completeness.
// For Fake dimesnion
else {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= var->dims.begin();
ird != var->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
// Just for debugging
#if 0
for (int i = 0; i < var->dims.size(); ++i) {
Add_One_FakeDim_Name((var->dims)[i]);
bool gotoMainLoop = false;
for (int j =i-1; j>=0 && !gotoMainLoop; --j) {
if (((var->dims)[i])->size == ((var->dims)[j])->size){
Adjust_Duplicate_FakeDim_Name((var->dims)[i]);
gotoMainLoop = true;
}
}
}
#endif
}
}
// Helper function to support dimensions of MeaSUrES SeaWiFS and OZone products
void GMFile::Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone(Var *var,Attribute*dimlistattr)
throw (Exception){
ssize_t objnamelen = -1;
hobj_ref_t rbuf;
//hvl_t *vlbuf = NULL;
vector<hvl_t> vlbuf;
hid_t dset_id = -1;
hid_t attr_id = -1;
hid_t atype_id = -1;
hid_t amemtype_id = -1;
hid_t aspace_id = -1;
hid_t ref_dset = -1;
if(NULL == dimlistattr)
throw2("Cannot obtain the dimension list attribute for variable ",var->name);
if (0==var->rank)
throw2("The number of dimension should NOT be 0 for the variable ",var->name);
try {
vlbuf.resize(var->rank);
dset_id = H5Dopen(this->fileid,(var->fullpath).c_str(),H5P_DEFAULT);
if (dset_id < 0)
throw2("Cannot open the dataset ",var->fullpath);
attr_id = H5Aopen(dset_id,(dimlistattr->name).c_str(),H5P_DEFAULT);
if (attr_id <0 )
throw4("Cannot open the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
atype_id = H5Aget_type(attr_id);
if (atype_id <0)
throw4("Cannot obtain the datatype of the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
amemtype_id = H5Tget_native_type(atype_id, H5T_DIR_ASCEND);
if (amemtype_id < 0)
throw2("Cannot obtain the memory datatype for the attribute ",dimlistattr->name);
if (H5Aread(attr_id,amemtype_id,&vlbuf[0]) <0)
throw2("Cannot obtain the referenced object for the variable ",var->name);
vector<char> objname;
int vlbuf_index = 0;
// The dimension names of variables will be the HDF5 dataset names dereferenced from the DIMENSION_LIST attribute.
for (vector<Dimension *>::iterator ird = var->dims.begin();
ird != var->dims.end(); ++ird) {
rbuf =((hobj_ref_t*)vlbuf[vlbuf_index].p)[0];
if ((ref_dset = H5Rdereference(attr_id, H5R_OBJECT, &rbuf)) < 0)
throw2("Cannot dereference from the DIMENSION_LIST attribute for the variable ",var->name);
if ((objnamelen= H5Iget_name(ref_dset,NULL,0))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
objname.resize(objnamelen+1);
if ((objnamelen= H5Iget_name(ref_dset,&objname[0],objnamelen+1))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
string objname_str = string(objname.begin(),objname.end());
string trim_objname = objname_str.substr(0,objnamelen);
(*ird)->name = string(trim_objname.begin(),trim_objname.end());
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
(*ird)->newname = (*ird)->name;
H5Dclose(ref_dset);
ref_dset = -1;
objname.clear();
vlbuf_index++;
}// for (vector<Dimension *>::iterator ird = var->dims.begin()
if(vlbuf.size()!= 0) {
if ((aspace_id = H5Aget_space(attr_id)) < 0)
throw2("Cannot get hdf5 dataspace id for the attribute ",dimlistattr->name);
if (H5Dvlen_reclaim(amemtype_id,aspace_id,H5P_DEFAULT,(void*)&vlbuf[0])<0)
throw2("Cannot successfully clean up the variable length memory for the variable ",var->name);
H5Sclose(aspace_id);
}
H5Tclose(atype_id);
H5Tclose(amemtype_id);
H5Aclose(attr_id);
H5Dclose(dset_id);
}
catch(...) {
if(atype_id != -1)
H5Tclose(atype_id);
if(amemtype_id != -1)
H5Tclose(amemtype_id);
if(aspace_id != -1)
H5Sclose(aspace_id);
if(attr_id != -1)
H5Aclose(attr_id);
if(dset_id != -1)
H5Dclose(dset_id);
//throw1("Error in method GMFile::Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone");
throw;
}
}
// Add MeaSURES OZone level 3Z dimension names
void GMFile::Add_Dim_Name_Mea_Ozonel3z() throw(Exception){
iscoard = true;
bool use_dimscale = false;
for (vector<Group *>::iterator irg = this->groups.begin();
irg != this->groups.end(); ++ irg) {
if ("/Dimensions" == (*irg)->path) {
use_dimscale = true;
break;
}
}
if (false == use_dimscale) {
bool has_dimlist = false;
bool has_class = false;
bool has_reflist = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name)
has_dimlist = true;
}
if (true == has_dimlist)
break;
}
if (true == has_dimlist) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("CLASS" == (*ira)->name)
has_class = true;
if ("REFERENCE_LIST" == (*ira)->name)
has_reflist = true;
if (true == has_class && true == has_reflist)
break;
}
if (true == has_class &&
true == has_reflist)
break;
}
if (true == has_class && true == has_reflist)
use_dimscale = true;
} // if (true == has_dimlist)
} // if (false == use_dimscale)
if (true == use_dimscale) {
pair<set<string>::iterator,bool> setret;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
Handle_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone((*irv));
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
setret = dimnamelist.insert((*ird)->name);
if(true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
}
if (true == dimnamelist.empty())
throw1("This product should have the dimension names, but no dimension names are found");
} // if (true == use_dimscale)
else {
// Since the dim. size of each dimension of 2D lat/lon may be the same, so use multimap.
multimap<hsize_t,string> ozonedimsize_to_dimname;
pair<multimap<hsize_t,string>::iterator,multimap<hsize_t,string>::iterator> mm_er_ret;
multimap<hsize_t,string>::iterator irmm;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool is_cv = check_cv((*irv)->name);
if (true == is_cv) {
if ((*irv)->dims.size() != 1)
throw3("The coordinate variable", (*irv)->name," must be one dimension for the zonal average product");
ozonedimsize_to_dimname.insert(pair<hsize_t,string>(((*irv)->dims)[0]->size,(*irv)->fullpath));
#if 0
((*irv)->dims[0])->name = (*irv)->name;
((*irv)->dims[0])->newname = (*irv)->name;
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert(((*irv)->dims[0])->name);
if (setret.second)
Insert_One_NameSizeMap_Element(((*irv)->dims[0])->name,((*irv)->dims[0])->size);
#endif
}
}// for (vector<Var *>::iterator irv = this->vars.begin(); ...
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
pair<set<string>::iterator,bool> setret;
pair<set<string>::iterator,bool> tempsetret;
set<string> tempdimnamelist;
bool fakedimflag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
fakedimflag = true;
mm_er_ret = ozonedimsize_to_dimname.equal_range((*ird)->size);
for (irmm = mm_er_ret.first; irmm!=mm_er_ret.second;irmm++) {
setret = tempdimnamelist.insert(irmm->second);
if (true == setret.second) {
(*ird)->name = irmm->second;
(*ird)->newname = (*ird)->name;
setret = dimnamelist.insert((*ird)->name);
if(setret.second) Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
fakedimflag = false;
break;
}
}
if (true == fakedimflag) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
} // for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
tempdimnamelist.clear();
fakedimsize.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin();
} // else
}
// This is a special helper function for MeaSURES ozone products
bool GMFile::check_cv(string & varname) throw(Exception) {
const string lat_name ="Latitude";
const string time_name ="Time";
const string ratio_pressure_name ="MixingRatioPressureLevels";
const string profile_pressure_name ="ProfilePressureLevels";
const string wave_length_name ="Wavelength";
if (lat_name == varname)
return true;
else if (time_name == varname)
return true;
else if (ratio_pressure_name == varname)
return true;
else if (profile_pressure_name == varname)
return true;
else if (wave_length_name == varname)
return true;
else
return false;
}
// Add Dimension names for GPM products
void GMFile::Add_Dim_Name_GPM()throw(Exception)
{
// This is used to create a dimension name set.
pair<set<string>::iterator,bool> setret;
// The commented code is for an old version of GPM products. May remove them later. KY 2015-06-16
// One GPM variable (sunVectorInBodyFrame) misses an element for DimensionNames attributes.
// We need to create a fakedim name to fill in. To make the dimension name unique, we use a counter.
// int dim_count = 0;
// map<string,string> varname_to_fakedim;
// map<int,string> gpm_dimsize_to_fakedimname;
// We find that GPM has an attribute DimensionNames(nlon,nlat) in this case.
// We will use this attribute to specify the dimension names.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
bool has_dim_name_attr = false;
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
if("DimensionNames" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,(*irv)->fullpath);
string dimname_value((*ira)->value.begin(),(*ira)->value.end());
vector<string> ind_elems;
char sep=',';
HDF5CFUtil::Split(&dimname_value[0],sep,ind_elems);
if(ind_elems.size() != (size_t)((*irv)->getRank())) {
throw2("The number of dims obtained from the <DimensionNames> attribute is not equal to the rank ",
(*irv)->name);
}
for(unsigned int i = 0; i<ind_elems.size(); ++i) {
((*irv)->dims)[i]->name = ind_elems[i];
// Generate a dimension name is the dimension name is missing.
// The routine will ensure that the fakeDim name is unique.
if(((*irv)->dims)[i]->name==""){
Add_One_FakeDim_Name(((*irv)->dims)[i]);
// For debugging
#if 0
string fakedim = "FakeDim";
stringstream sdim_count;
sdim_count << dim_count;
fakedim = fakedim + sdim_count.str();
dim_count++;
((*irv)->dims)[i]->name = fakedim;
((*irv)->dims)[i]->newname = fakedim;
ind_elems[i] = fakedim;
#endif
}
else {
((*irv)->dims)[i]->newname = ind_elems[i];
setret = dimnamelist.insert(((*irv)->dims)[i]->name);
if (true == setret.second) {
Insert_One_NameSizeMap_Element(((*irv)->dims)[i]->name,
((*irv)->dims)[i]->size);
}
else {
if(dimname_to_dimsize[((*irv)->dims)[i]->name] !=((*irv)->dims)[i]->size)
throw5("Dimension ",((*irv)->dims)[i]->name, "has two sizes",
((*irv)->dims)[i]->size,dimname_to_dimsize[((*irv)->dims)[i]->name]);
}
}
}// for(unsigned int i = 0; i<ind_elems.size(); ++i)
has_dim_name_attr = true;
break;
} //if("DimensionNames" == (*ira)->name)
} //for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin()
#if 0
if(false == has_dim_name_attr) {
throw4( "The variable ", (*irv)->name, " doesn't have the DimensionNames attribute.",
"We currently don't support this case. Please report to the NASA data center.");
}
#endif
} //for (vector<Var *>::iterator irv = this->vars.begin();
}
// Add Dimension names for Aquarius level 3 products
void GMFile::Add_Dim_Name_Aqu_L3()throw(Exception)
{
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); irv++) {
if ("l3m_data" == (*irv)->name) {
((*irv)->dims)[0]->name = "lat";
((*irv)->dims)[0]->newname = "lat";
((*irv)->dims)[1]->name = "lon";
((*irv)->dims)[1]->newname = "lon";
break;
}
// For the time being, don't assign dimension names to palette,
// we will see if tools can pick up l3m and then make decisions.
#if 0
if ("palette" == (*irv)->name) {
//"h5","coming to palette" <<endl;
((*irv)->dims)[0]->name = "paldim0";
((*irv)->dims)[0]->newname = "paldim0";
((*irv)->dims)[1]->name = "paldim1";
((*irv)->dims)[1]->newname = "paldim1";
}
#endif
}// for (vector<Var *>::iterator irv = this->vars.begin()
}
// Add dimension names for SMAP(note: the SMAP may change their structures. The code may not apply to them.)
void GMFile::Add_Dim_Name_SMAP()throw(Exception){
string tempvarname ="";
string key = "_lat";
string smapdim0 ="YDim";
string smapdim1 ="XDim";
// Since the dim. size of each dimension of 2D lat/lon may be the same, so use multimap.
multimap<hsize_t,string> smapdimsize_to_dimname;
pair<multimap<hsize_t,string>::iterator,multimap<hsize_t,string>::iterator> mm_er_ret;
multimap<hsize_t,string>::iterator irmm;
// Generate dimension names based on the size of "???_lat"(one coordinate variable)
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
tempvarname = (*irv)->name;
if ((tempvarname.size() > key.size())&&
(key == tempvarname.substr(tempvarname.size()-key.size(),key.size()))){
//cerr<<"tempvarname " <<tempvarname <<endl;
if ((*irv)->dims.size() !=2)
throw1("Currently only 2D lat/lon is supported for SMAP");
smapdimsize_to_dimname.insert(pair<hsize_t,string>(((*irv)->dims)[0]->size,smapdim0));
smapdimsize_to_dimname.insert(pair<hsize_t,string>(((*irv)->dims)[1]->size,smapdim1));
break;
}
}
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
pair<set<string>::iterator,bool> setret;
pair<set<string>::iterator,bool> tempsetret;
set<string> tempdimnamelist;
bool fakedimflag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
fakedimflag = true;
mm_er_ret = smapdimsize_to_dimname.equal_range((*ird)->size);
for (irmm = mm_er_ret.first; irmm!=mm_er_ret.second;irmm++) {
setret = tempdimnamelist.insert(irmm->second);
if (setret.second) {
(*ird)->name = irmm->second;
(*ird)->newname = (*ird)->name;
setret = dimnamelist.insert((*ird)->name);
if(setret.second) Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
fakedimflag = false;
break;
}
}
if (true == fakedimflag) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (!setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
} // for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
tempdimnamelist.clear();
fakedimsize.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin();
}
//Add dimension names for ACOS level2S or OCO2 level1B products
void GMFile::Add_Dim_Name_ACOS_L2S_OCO2_L1B()throw(Exception){
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
}
// Add dimension names for general products.
void GMFile::Add_Dim_Name_General_Product()throw(Exception){
// Check attributes
Check_General_Product_Pattern();
// This general product should follow the HDF5 dimension scale model.
if (GENERAL_DIMSCALE == this->gproduct_pattern)
Add_Dim_Name_Dimscale_General_Product();
// This general product has 2-D latitude,longitude
else if (GENERAL_LATLON2D == this->gproduct_pattern)
Add_Dim_Name_LatLon2D_General_Product();
// This general product has 1-D latitude,longitude
else if (GENERAL_LATLON1D == this->gproduct_pattern)
Add_Dim_Name_LatLon1D_General_Product();
}
void GMFile::Check_General_Product_Pattern() throw(Exception) {
if(false == Check_Dimscale_General_Product_Pattern()) {
if(false == Check_LatLon2D_General_Product_Pattern())
if(false == Check_LatLon1D_General_Product_Pattern())
Check_LatLon_With_Coordinate_Attr_General_Product_Pattern();
}
}
// If having 2-D latitude/longitude,set the general product pattern.
// In this version, we only check if we have "latitude,longitude","Latitude,Longitude","lat,lon" and "cell_lat,cell_lon"names.
// The "cell_lat" and "cell_lon" come from SMAP. KY 2015-12-2
bool GMFile::Check_LatLon2D_General_Product_Pattern() throw(Exception) {
// bool ret_value = Check_LatLonName_General_Product(2);
bool ret_value = false;
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("latitude","longitude");
if(false == ret_value) {
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("Latitude","Longitude");
if(false == ret_value) {
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("lat","lon");
if(false == ret_value)
ret_value = Check_LatLon2D_General_Product_Pattern_Name_Size("cell_lat","cell_lon");
}
}
if(true == ret_value)
this->gproduct_pattern = GENERAL_LATLON2D;
return ret_value;
}
bool GMFile::Check_LatLon2D_General_Product_Pattern_Name_Size(const string & latname,const string & lonname) throw(Exception) {
bool ret_value = false;
short ll_flag = 0;
vector<size_t>lat_size(2.0);
vector<size_t>lon_size(2,0);
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
if((*irv)->name == latname) {
string lat_path =HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
// Tackle only the root group or the name of the group as "/Geolocation"
if("/" == lat_path || "/Geolocation/" == lat_path) {
ll_flag++;
lat_size[0] = (*irv)->getDimensions()[0]->size;
lat_size[1] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == lonname) {
string lon_path = HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
if("/" == lon_path || "/Geolocation/" == lon_path) {
ll_flag++;
lon_size[0] = (*irv)->getDimensions()[0]->size;
lon_size[1] = (*irv)->getDimensions()[1]->size;
}
}
if(2 == ll_flag)
break;
}
}
if(2 == ll_flag) {
bool latlon_size_match = true;
for (int size_index = 0; size_index <lat_size.size();size_index++) {
if(lat_size[size_index] != lon_size[size_index]){
latlon_size_match = false;
break;
}
}
if (true == latlon_size_match) {
gp_latname = latname;
gp_lonname = lonname;
ret_value = true;
}
}
return ret_value;
}
#if 0
// If having 1-D latitude/longitude,set the general product pattern.
bool GMFile::Check_LatLon1D_General_Product_Pattern() throw(Exception) {
bool ret_value = Check_LatLonName_General_Product(1);
if(true == ret_value)
this->gproduct_pattern = GENERAL_LATLON1D;
return ret_value;
}
#endif
// If having 2-D latitude/longitude,set the general product pattern.
// In this version, we only check if we have "latitude,longitude","Latitude,Longitude","lat,lon" and "cell_lat,cell_lon"names.
// The "cell_lat" and "cell_lon" come from SMAP. KY 2015-12-2
bool GMFile::Check_LatLon1D_General_Product_Pattern() throw(Exception) {
// bool ret_value = Check_LatLonName_General_Product(2);
bool ret_value = false;
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("latitude","longitude");
if(false == ret_value) {
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("Latitude","Longitude");
if(false == ret_value) {
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("lat","lon");
if(false == ret_value)
ret_value = Check_LatLon1D_General_Product_Pattern_Name_Size("cell_lat","cell_lon");
}
}
if(true == ret_value)
this->gproduct_pattern = GENERAL_LATLON1D;
return ret_value;
}
bool GMFile::Check_LatLon1D_General_Product_Pattern_Name_Size(const string & latname,const string & lonname) throw(Exception) {
bool ret_value = false;
short ll_flag = 0;
size_t lat_size = 0;
size_t lon_size = 0;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 1) {
if((*irv)->name == latname) {
string lat_path =HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
// Tackle only the root group or the name of the group as "/Geolocation"
if("/" == lat_path || "/Geolocation/" == lat_path) {
ll_flag++;
lat_size = (*irv)->getDimensions()[0]->size;
}
}
else if((*irv)->name == lonname) {
string lon_path = HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
if("/" == lon_path || "/Geolocation/" == lon_path) {
ll_flag++;
lon_size = (*irv)->getDimensions()[0]->size;
}
}
if(2 == ll_flag)
break;
}
}
if(2 == ll_flag) {
bool latlon_size_match_grid = true;
// When the size of latitude is equal to the size of longitude for a 1-D lat/lon, it is very possible
// that this is not a regular grid but rather a profile with the lat,lon to be recorded as the function of time.
// Adding the coordinate/dimension as the normal grid is wrong, so check out this case.
// KY 2015-12-2
if(lat_size == lon_size) {
// It is very unusual that lat_size = lon_size for a grid.
latlon_size_match_grid = false;
// For a normal grid, a >2D variable should exist to have both lat and lon size, if such a variable that has the same size exists, we
// will treat it as a normal grid.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank >=2) {
short ll_size_flag = 0;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
if(lat_size == (*ird)->size) {
ll_size_flag++;
if(2 == ll_size_flag){
break;
}
}
}
if(2 == ll_size_flag) {
latlon_size_match_grid = true;
break;
}
}
}
}
if (true == latlon_size_match_grid) {
gp_latname = latname;
gp_lonname = lonname;
ret_value = true;
}
}
return ret_value;
}
bool GMFile::Check_LatLon_With_Coordinate_Attr_General_Product_Pattern() throw(Exception) {
bool ret_value = false;
string co_attrname = "coordinates";
string co_attrvalue="";
string unit_attrname = "units";
string lat_unit_attrvalue ="degrees_north";
string lon_unit_attrvalue ="degrees_east";
bool coor_has_lat_flag = false;
bool coor_has_lon_flag = false;
vector<Var*> tempvar_lat;
vector<Var*> tempvar_lon;
// Check if having both lat, lon coordinate values.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank >=2) {
for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin();
ira !=(*irv)->attrs.end();++ira) {
if((*ira)->name == co_attrname) {
Retrieve_H5_Attr_Value((*ira),(*irv)->fullpath);
string orig_attr_value((*ira)->value.begin(),(*ira)->value.end());
vector<string> coord_values;
char sep=' ';
HDF5CFUtil::Split_helper(coord_values,orig_attr_value,sep);
for(vector<string>::iterator irs=coord_values.begin();irs!=coord_values.end();++irs)
cerr<<"coord value is "<<(*irs) <<endl;
for(vector<string>::iterator irs=coord_values.begin();irs!=coord_values.end();++irs) {
string coord_value_suffix1;
string coord_value_suffix2;
if((*irs).size() >=3) {
coord_value_suffix1 = (*irs).substr((*irs).size()-3,3);
if((*irs).size() >=6)
coord_value_suffix2 = (*irs).substr((*irs).size()-6,6);
}
if(coord_value_suffix1=="lat" || coord_value_suffix2 =="latitude" || coord_value_suffix2 == "Latitude")
coor_has_lat_flag = true;
else if(coord_value_suffix1=="lon" || coord_value_suffix2 =="longitude" || coord_value_suffix2 == "Longitude")
coor_has_lon_flag = true;
}
if(true == coor_has_lat_flag && true == coor_has_lon_flag)
break;
}
}
if(true == coor_has_lat_flag && true == coor_has_lon_flag)
break;
else {
coor_has_lat_flag = false;
coor_has_lon_flag = false;
}
}
}
// Check the variable names that include latitude and longitude suffixes such as lat,latitude and Latitude.
if(true == coor_has_lat_flag && true == coor_has_lon_flag) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool var_is_lat = false;
bool var_is_lon = false;
string varname = (*irv)->name;
string ll_ssuffix;
string ll_lsuffix;
if(varname.size() >=3) {
ll_ssuffix = varname.substr(varname.size()-3,3);
if(varname.size() >=6)
ll_lsuffix = varname.substr(varname.size()-6,6);
}
if(ll_ssuffix=="lat" || ll_lsuffix =="latitude" || ll_lsuffix == "Latitude")
var_is_lat = true;
else if(ll_ssuffix=="lon" || ll_lsuffix =="longitude" || ll_lsuffix == "Longitude")
var_is_lon = true;
if(true == var_is_lat) {
if((*irv)->rank > 0) {
Var * lat = new Var(*irv);
tempvar_lat.push_back(lat);
}
}
else if(true == var_is_lon) {
if((*irv)->rank >0) {
Var * lon = new Var(*irv);
tempvar_lon.push_back(lon);
}
}
}
// Build up lat/lon name-size struct,
// 1) Compare the rank, sizes and the orders of tempvar_lon against tempvar_lat
// rank >=2 the sizes,orders, should be consistent
// rank =1, no check issue.
// 2) If the condition is fulfilled, save them to the vector struct, also mark if more than lon is found,
// only pick up the correct one. If no correct one, remove this lat/lon.
for(vector<Var*>:: iterator irlat = tempvar_lat.begin(); irlat!=tempvar_lat.end();++irlat) {
cerr<<"lat variable name is "<<(*irlat)->fullpath <<endl;
set<string> lon_candidate_path;
for(vector<Var*>:: iterator irlon = tempvar_lon.begin(); irlon!=tempvar_lon.end();++irlon) {
cerr<<"lon variable name is "<<(*irlon)->fullpath <<endl;
if ((*irlat)->rank == (*irlon)->rank) {
if((*irlat)->rank == 1)
lon_candidate_path.insert((*irlon)->fullpath);
else { // Check the dim order and size.
bool same_dim = true;
for(int dim_index = 0; dim_index <(*irlat)->rank; dim_index++) {
if((*irlat)->getDimensions()[dim_index]->size !=
(*irlon)->getDimensions()[dim_index]->size){
same_dim = false;
break;
}
}
if(true == same_dim)
lon_candidate_path.insert((*irlon)->fullpath);
}
}
}
// Check the size of the lon., if the size is not 1, see if having the same path one.
if(lon_candidate_path.size() != 1) {
string lat_path = HDF5CFUtil::obtain_string_before_lastslash((*irlat)->fullpath);
string lon_final_candidate_path;
short num_lon_path = 0;
for(set<string>::iterator islon_path =lon_candidate_path.begin();islon_path!=lon_candidate_path.end();++islon_path) {
// Search the path.
if(HDF5CFUtil::obtain_string_before_lastslash((*islon_path))==lat_path) {
num_lon_path++;
if(1 == num_lon_path)
lon_final_candidate_path = *islon_path;
else if(num_lon_path > 1)
break;
}
}
if(num_lon_path ==1) {// insert this lat/lon pair to the struct
Name_Size_2Pairs latlon_pair;
latlon_pair.name1 = (*irlat)->fullpath;
latlon_pair.name2 = lon_final_candidate_path;
latlon_pair.size1 = (*irlat)->getDimensions()[0]->size;
latlon_pair.size2 = (*irlat)->getDimensions()[1]->size;
latlon_pair.rank = (*irlat)->rank;
latloncv_candidate_pairs.push_back(latlon_pair);
}
}
else {//insert this lat/lon pair to the struct
Name_Size_2Pairs latlon_pair;
latlon_pair.name1 = (*irlat)->fullpath;
// Find how to get the first element of the size TOOODOOO,comment out the following line
//latlon_pair.name2 = lon_candidate_path[0];
latlon_pair.size1 = (*irlat)->getDimensions()[0]->size;
latlon_pair.size2 = (*irlat)->getDimensions()[1]->size;
latlon_pair.rank = (*irlat)->rank;
latloncv_candidate_pairs.push_back(latlon_pair);
}
}
if(latloncv_candidate_pairs.size() >0) {
int num_1d_rank = 0;
int num_2d_rank = 0;
int num_g2d_rank = 0;
vector<struct Name_Size_2Pairs> temp_1d_latlon_pairs;
for(vector<struct Name_Size_2Pairs>::iterator ivs=latloncv_candidate_pairs.begin(); ivs!=latloncv_candidate_pairs.end();++ivs) {
if(1 == (*ivs).rank) {
num_1d_rank++;
}
else if(2 == (*ivs).rank)
num_2d_rank++;
else if((*ivs).rank >2)
num_g2d_rank++;
else
;// throw an error
}
if (num_2d_rank !=0)
ret_value = true;
else if(num_1d_rank!=0) {
// Check if lat and lon shares the same size and the dimension of a variable that holds the coordinates only holds one size.
}
}
release_standalone_var_vector(tempvar_lat);
release_standalone_var_vector(tempvar_lon);
}
return false;
}
#if 0
// In this version, we only check if we have "latitude,longitude","Latitude,Longitude","lat,lon" names.
// This routine will check this case.
bool GMFile::Check_LatLonName_General_Product(int ll_rank) throw(Exception) {
if(ll_rank <1 || ll_rank >2)
throw2("Only support rank = 1 or 2 lat/lon case for the general product. The current rank is ",ll_rank);
bool ret_value = false;
size_t lat2D_dimsize0 = 0;
size_t lat2D_dimsize1 = 0;
size_t lon2D_dimsize0 = 0;
size_t lon2D_dimsize1 = 0;
// The element order is latlon_flag,latilong_flag and LatLon_flag.
vector<short>ll_flag(3,0);
vector<size_t>lat_size;
vector<size_t>lon_size;
// We only need to check 2-D latlon
if(2 == ll_rank) {
//lat/lon is 2-D array, so the size is doubled.
lat_size.assign(6,0);
lon_size.assign(6,0);
}
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == ll_rank) {
if((*irv)->name == "lat") {
ll_flag[0]++;
if(ll_rank == 2) {
lat_size[0] = (*irv)->getDimensions()[0]->size;
lat_size[1] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "lon") {
ll_flag[0]++;
if(ll_rank == 2) {
lon_size[0] = (*irv)->getDimensions()[0]->size;
lon_size[1] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "latitude"){
ll_flag[1]++;
if(ll_rank == 2) {
lat_size[2] = (*irv)->getDimensions()[0]->size;
lat_size[3] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "longitude"){
ll_flag[1]++;
if(ll_rank == 2) {
lon_size[2] = (*irv)->getDimensions()[0]->size;
lon_size[3] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "Latitude"){
ll_flag[2]++;
if(ll_rank == 2) {
lat_size[4] = (*irv)->getDimensions()[0]->size;
lat_size[5] = (*irv)->getDimensions()[1]->size;
}
}
else if((*irv)->name == "Longitude"){
ll_flag[2]++;
if(ll_rank == 2) {
lon_size[4] = (*irv)->getDimensions()[0]->size;
lon_size[5] = (*irv)->getDimensions()[1]->size;
}
}
}
}
int total_llflag = 0;
for (int i = 0; i < ll_flag.size();i++)
if(2 == ll_flag[i])
total_llflag ++;
// We only support 1 (L)lat(i)/(L)lon(g) pair.
if(1 == total_llflag) {
bool latlon_size_match = true;
if(2 == ll_rank) {
for (int size_index = 0; size_index <lat_size.size();size_index++) {
if(lat_size[size_index] != lon_size[size_index]){
latlon_size_match = false;
break;
}
}
}
if(true == latlon_size_match) {
ret_value = true;
if(2 == ll_flag[0]) {
gp_latname = "lat";
gp_lonname = "lon";
}
else if ( 2 == ll_flag[1]) {
gp_latname = "latitude";
gp_lonname = "longitude";
}
else if (2 == ll_flag[2]){
gp_latname = "Latitude";
gp_lonname = "Longitude";
}
}
}
return ret_value;
}
#endif
// Add dimension names for the case that has 2-D lat/lon.
void GMFile::Add_Dim_Name_LatLon2D_General_Product() throw(Exception) {
//cerr<<"coming to Add_Dim_Name_LatLon2D_General_Product "<<endl;
// cerr<<"gp_latname is "<<gp_latname <<endl;
// cerr<<"gp_lonname is "<<gp_lonname <<endl;
string latdimname0,latdimname1;
size_t latdimsize0 = 0;
size_t latdimsize1 = 0;
// Need to generate fake dimensions.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
// Avoid the same size dimension sharing the same dimension name.
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
// Find variable name that is latitude or lat or Latitude
// Note that we don't need to check longitude since longitude dim. sizes should be the same as the latitude for this case.
if((*irv)->name == gp_latname) {
if((*irv)->rank != 2) {
throw4("coordinate variables ",gp_latname,
" must have rank 2 for the 2-D latlon case , the current rank is ",
(*irv)->rank);
}
latdimname0 = (*irv)->getDimensions()[0]->name;
latdimsize0 = (*irv)->getDimensions()[0]->size;
latdimname1 = (*irv)->getDimensions()[1]->name;
latdimsize1 = (*irv)->getDimensions()[1]->size;
}
}
//cerr<<"latdimname0 is "<<latdimname0 <<endl;
//cerr<<"latdimname1 is "<<latdimname1 <<endl;
//cerr<<"latdimsize0 is "<<latdimsize0 <<endl;
//cerr<<"latdimsize1 is "<<latdimsize1 <<endl;
//int lat_dim0_index = 0;
//int lat_dim1_index = 0;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
int lat_dim0_index = 0;
int lat_dim1_index = 0;
bool has_lat_dims_size = false;
for (int dim_index = 0; dim_index <(*irv)->dims.size(); dim_index++) {
// Find if having the first dimension size of lat
if(((*irv)->dims[dim_index])->size == latdimsize0) {
// Find if having the second dimension size of lat
lat_dim0_index = dim_index;
for(int dim_index2 = dim_index+1;dim_index2 < (*irv)->dims.size();dim_index2++) {
if(((*irv)->dims[dim_index2])->size == latdimsize1) {
lat_dim1_index = dim_index2;
has_lat_dims_size = true;
break;
}
}
}
if(true == has_lat_dims_size)
break;
}
// Find the lat's dimension sizes, change the (fake) dimension names.
if(true == has_lat_dims_size) {
((*irv)->dims[lat_dim0_index])->name = latdimname0;
//((*irv)->dims[lat_dim0_index])->newname = latdimname0;
((*irv)->dims[lat_dim1_index])->name = latdimname1;
//((*irv)->dims[lat_dim1_index])->newname = latdimname1;
}
}
//When we generate Fake dimensions, we may encounter discontiguous Fake dimension names such
// as FakeDim0, FakeDim9 etc. We would like to make Fake dimension names in contiguous order
// FakeDim0,FakeDim1,etc.
// Obtain the tempdimnamelist set.
set<string>tempdimnamelist;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird)
tempdimnamelist.insert((*ird)->name);
}
// Generate the final dimnamelist,it is a contiguous order: FakeDim0,FakeDim1 etc.
set<string>finaldimnamelist;
string finaldimname_base = "FakeDim";
for(int i = 0; i<tempdimnamelist.size();i++) {
stringstream sfakedimindex;
sfakedimindex << i;
string finaldimname = finaldimname_base + sfakedimindex.str();
finaldimnamelist.insert(finaldimname);
//cerr<<"finaldimname is "<<finaldimname <<endl;
}
// If the original tempdimnamelist is not the same as the finaldimnamelist,
// we need to generate a map from original name to the final name.
if(finaldimnamelist != tempdimnamelist) {
map<string,string> tempdimname_to_finaldimname;
set<string>:: iterator tempit = tempdimnamelist.begin();
set<string>:: iterator finalit = finaldimnamelist.begin();
while(tempit != tempdimnamelist.end()) {
tempdimname_to_finaldimname[*tempit] = *finalit;
//cerr<<"tempdimname again "<<*tempit <<endl;
//cerr<<"finalname again "<<*finalit <<endl;
tempit++;
finalit++;
}
//cerr<<"dim name map size is "<<tempdimname_to_finaldimname.size() <<endl;
// Change the dimension names of every variable to the final dimension name list.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
if(tempdimname_to_finaldimname.find((*ird)->name) !=tempdimname_to_finaldimname.end()){
(*ird)->name = tempdimname_to_finaldimname[(*ird)->name];
}
else
throw3("The dimension names ",(*ird)->name, "cannot be found in the dim. name list.");
}
}
}
dimnamelist.clear();
dimnamelist = finaldimnamelist;
// We need to update dimname_to_dimsize map. This may be used in the future.
dimname_to_dimsize.clear();
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
if(finaldimnamelist.find((*ird)->name)!=finaldimnamelist.end()) {
dimname_to_dimsize[(*ird)->name] = (*ird)->size;
finaldimnamelist.erase((*ird)->name);
}
}
if(true == finaldimnamelist.empty())
break;
}
// Finally set dimension newname
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
(*ird)->newname = (*ird)->name;
}
}
}
// Add dimension names for the case that has 1-D lat/lon.
void GMFile::Add_Dim_Name_LatLon1D_General_Product() throw(Exception) {
// Only need to add the fake dimension names
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
// Avoid the same size dimension sharing the same dimension name.
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
}
}
// Check if this general product is netCDF4-like HDF5 file.
// We only need to check "DIMENSION_LIST","CLASS" and CLASS values.
bool GMFile::Check_Dimscale_General_Product_Pattern() throw(Exception) {
bool ret_value = false;
bool has_dimlist = false;
bool has_dimscalelist = false;
// Check if containing the "DIMENSION_LIST" attribute;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name) {
has_dimlist = true;
break;
}
}
if (true == has_dimlist)
break;
}
// Check if containing both the attribute "CLASS" and the attribute "REFERENCE_LIST" for the same variable.
// This is the dimension scale.
// Actually "REFERENCE_LIST" is not necessary for a dimension scale dataset. If a dimension scale doesn't
// have a "REFERENCE_LIST", it is still valid. But no other variables use this dimension scale. We found
// such a case in a matched_airs_aqua product. KY 2012-12-03
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for(vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end();ira++) {
if ("CLASS" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,(*irv)->fullpath);
string class_value;
class_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),class_value.begin());
// Compare the attribute "CLASS" value with "DIMENSION_SCALE". We only compare the string with the size of
// "DIMENSION_SCALE", which is 15.
if (0 == class_value.compare(0,15,"DIMENSION_SCALE")) {
has_dimscalelist = true;
break;
}
}
}
if (true == has_dimscalelist)
break;
}
if (true == has_dimlist && true == has_dimscalelist) {
this->gproduct_pattern = GENERAL_DIMSCALE;
ret_value = true;
}
return ret_value;
}
void GMFile::Add_Dim_Name_Dimscale_General_Product() throw(Exception) {
//cerr<<"coming to Add_Dim_Name_Dimscale_General_Product"<<endl;
pair<set<string>::iterator,bool> setret;
this->iscoard = true;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
Handle_UseDimscale_Var_Dim_Names_General_Product((*irv));
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
if (true == dimnamelist.empty())
throw1("This product should have the dimension names, but no dimension names are found");
}
void GMFile::Handle_UseDimscale_Var_Dim_Names_General_Product(Var *var) throw(Exception) {
Attribute* dimlistattr = NULL;
bool has_dimlist = false;
bool has_dimclass = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if ("DIMENSION_LIST" == (*ira)->name) {
dimlistattr = *ira;
has_dimlist = true;
}
if ("CLASS" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,var->fullpath);
string class_value;
class_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),class_value.begin());
// Compare the attribute "CLASS" value with "DIMENSION_SCALE". We only compare the string with the size of
// "DIMENSION_SCALE", which is 15.
if (0 == class_value.compare(0,15,"DIMENSION_SCALE")) {
has_dimclass = true;
break;
}
}
} // for(vector<Attribute *>::iterator ira = var->attrs.begin(); ...
// This is a general variable, we need to find the corresponding coordinate variables.
if (true == has_dimlist)
Add_UseDimscale_Var_Dim_Names_General_Product(var,dimlistattr);
// Dim name is the same as the variable name for dimscale variable
else if(true == has_dimclass) {
if (var->dims.size() !=1)
throw2("Currently dimension scale dataset must be 1 dimension, this is not true for the dataset ",
var->name);
// The var name is the object name, however, we would like the dimension name to be the full path.
// so that the dim name can be served as the key for future handling.
(var->dims)[0]->name = var->fullpath;
(var->dims)[0]->newname = var->fullpath;
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((var->dims)[0]->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((var->dims)[0]->name,(var->dims)[0]->size);
}
// No dimension, add fake dim names, this will rarely happen.
else {
set<hsize_t> fakedimsize;
pair<set<hsize_t>::iterator,bool> setsizeret;
for (vector<Dimension *>::iterator ird= var->dims.begin();
ird != var->dims.end(); ++ird) {
Add_One_FakeDim_Name(*ird);
setsizeret = fakedimsize.insert((*ird)->size);
// Avoid the same size dimension sharing the same dimension name.
if (false == setsizeret.second)
Adjust_Duplicate_FakeDim_Name(*ird);
}
}
}
// Add dimension names for the case when HDF5 dimension scale is followed(netCDF4-like)
void GMFile::Add_UseDimscale_Var_Dim_Names_General_Product(Var *var,Attribute*dimlistattr)
throw (Exception){
ssize_t objnamelen = -1;
hobj_ref_t rbuf;
//hvl_t *vlbuf = NULL;
vector<hvl_t> vlbuf;
hid_t dset_id = -1;
hid_t attr_id = -1;
hid_t atype_id = -1;
hid_t amemtype_id = -1;
hid_t aspace_id = -1;
hid_t ref_dset = -1;
if(NULL == dimlistattr)
throw2("Cannot obtain the dimension list attribute for variable ",var->name);
if (0==var->rank)
throw2("The number of dimension should NOT be 0 for the variable ",var->name);
try {
//vlbuf = new hvl_t[var->rank];
vlbuf.resize(var->rank);
dset_id = H5Dopen(this->fileid,(var->fullpath).c_str(),H5P_DEFAULT);
if (dset_id < 0)
throw2("Cannot open the dataset ",var->fullpath);
attr_id = H5Aopen(dset_id,(dimlistattr->name).c_str(),H5P_DEFAULT);
if (attr_id <0 )
throw4("Cannot open the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
atype_id = H5Aget_type(attr_id);
if (atype_id <0)
throw4("Cannot obtain the datatype of the attribute ",dimlistattr->name," of HDF5 dataset ",var->fullpath);
amemtype_id = H5Tget_native_type(atype_id, H5T_DIR_ASCEND);
if (amemtype_id < 0)
throw2("Cannot obtain the memory datatype for the attribute ",dimlistattr->name);
if (H5Aread(attr_id,amemtype_id,&vlbuf[0]) <0)
throw2("Cannot obtain the referenced object for the variable ",var->name);
vector<char> objname;
int vlbuf_index = 0;
// The dimension names of variables will be the HDF5 dataset names dereferenced from the DIMENSION_LIST attribute.
for (vector<Dimension *>::iterator ird = var->dims.begin();
ird != var->dims.end(); ++ird) {
rbuf =((hobj_ref_t*)vlbuf[vlbuf_index].p)[0];
if ((ref_dset = H5Rdereference(attr_id, H5R_OBJECT, &rbuf)) < 0)
throw2("Cannot dereference from the DIMENSION_LIST attribute for the variable ",var->name);
if ((objnamelen= H5Iget_name(ref_dset,NULL,0))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
objname.resize(objnamelen+1);
if ((objnamelen= H5Iget_name(ref_dset,&objname[0],objnamelen+1))<=0)
throw2("Cannot obtain the dataset name dereferenced from the DIMENSION_LIST attribute for the variable ",var->name);
string objname_str = string(objname.begin(),objname.end());
// We need to remove the first character of the object name since the first character
// of the object full path is always "/" and this will be changed to "_".
// The convention of handling the dimension-scale general product is to remove the first "_".
// Check the get_CF_string function of HDF5GMCF.cc.
string trim_objname = objname_str.substr(0,objnamelen);
(*ird)->name = string(trim_objname.begin(),trim_objname.end());
pair<set<string>::iterator,bool> setret;
setret = dimnamelist.insert((*ird)->name);
if (true == setret.second)
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
(*ird)->newname = (*ird)->name;
H5Dclose(ref_dset);
ref_dset = -1;
objname.clear();
vlbuf_index++;
}// for (vector<Dimension *>::iterator ird = var->dims.begin()
if(vlbuf.size()!= 0) {
if ((aspace_id = H5Aget_space(attr_id)) < 0)
throw2("Cannot get hdf5 dataspace id for the attribute ",dimlistattr->name);
if (H5Dvlen_reclaim(amemtype_id,aspace_id,H5P_DEFAULT,(void*)&vlbuf[0])<0)
throw2("Cannot successfully clean up the variable length memory for the variable ",var->name);
H5Sclose(aspace_id);
}
H5Tclose(atype_id);
H5Tclose(amemtype_id);
H5Aclose(attr_id);
H5Dclose(dset_id);
// if(vlbuf != NULL)
// delete[] vlbuf;
}
catch(...) {
if(atype_id != -1)
H5Tclose(atype_id);
if(amemtype_id != -1)
H5Tclose(amemtype_id);
if(aspace_id != -1)
H5Sclose(aspace_id);
if(attr_id != -1)
H5Aclose(attr_id);
if(dset_id != -1)
H5Dclose(dset_id);
//if(vlbuf != NULL)
// delete[] vlbuf;
//throw1("Error in method GMFile::Add_UseDimscale_Var_Dim_Names_Mea_SeaWiFS_Ozone");
throw;
}
}
// Handle coordinate variables
void GMFile::Handle_CVar() throw(Exception){
// No coordinate variables are generated for ACOS_L2S or OCO2_L1B
// Currently we support the three patterns for the general products:
// 1) Dimensions follow HDF5 dimension scale specification
// 2) Dimensions don't follow HDF5 dimension scale specification but have 1D lat/lon
// 3) Dimensions don't follow HDF5 dimension scale specification bu have 2D lat/lon
if (General_Product == this->product_type ||
ACOS_L2S_OR_OCO2_L1B == this->product_type) {
if (GENERAL_DIMSCALE == this->gproduct_pattern)
Handle_CVar_Dimscale_General_Product();
else if (GENERAL_LATLON1D == this->gproduct_pattern)
Handle_CVar_LatLon1D_General_Product();
else if (GENERAL_LATLON2D == this->gproduct_pattern)
Handle_CVar_LatLon2D_General_Product();
return;
}
else if (Mea_SeaWiFS_L2 == this->product_type ||
Mea_SeaWiFS_L3 == this->product_type)
Handle_CVar_Mea_SeaWiFS();
else if (Aqu_L3 == this->product_type)
Handle_CVar_Aqu_L3();
else if (OBPG_L3 == this->product_type)
Handle_CVar_OBPG_L3();
else if (SMAP == this->product_type)
Handle_CVar_SMAP();
else if (Mea_Ozone == this->product_type)
Handle_CVar_Mea_Ozone();
else if (GPMS_L3 == this->product_type || GPMM_L3 == this->product_type)
Handle_CVar_GPM_L3();
else if (GPM_L1 == this->product_type)
Handle_CVar_GPM_L1();
}
// Handle GPM level 1 coordinate variables
void GMFile::Handle_CVar_GPM_L1() throw(Exception) {
#if 0
// Loop through the variable list to build the coordinates.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->name=="AlgorithmRuntimeInfo") {
delete(*irv);
this->vars.erase(irv);
break;
}
}
#endif
// Loop through all variables to check 2-D "Latitude" and "Longitude".
// Create coordinate variables based on 2-D "Latitude" and "Longitude".
// Latitude[Xdim][YDim] Longitude[Xdim][YDim], Latitude <->Xdim, Longitude <->YDim.
// Make sure to build cf dimension names cfdimname = latpath+ the lat dimension name.
// We want to save dimension names of Latitude and Longitude since
// the Fake coordinate variables of these two dimensions should not be generated.
// So we need to remember these dimension names.
//string ll_dim0,ll_dim1;
set<string> ll_dim_set;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if((*irv)->rank == 2 && (*irv)->name == "Latitude") {
GMCVar* GMcvar = new GMCVar(*irv);
size_t lat_pos = (*irv)->fullpath.rfind("Latitude");
string lat_path = (*irv)->fullpath.substr(0,lat_pos);
GMcvar->cfdimname = lat_path + ((*irv)->dims)[0]->name;
//ll_dim0 = ((*irv)->dims)[0]->name;
ll_dim_set.insert(((*irv)->dims)[0]->name);
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
}
if((*irv)->rank == 2 && (*irv)->name == "Longitude") {
GMCVar* GMcvar = new GMCVar(*irv);
size_t lon_pos = (*irv)->fullpath.rfind("Longitude");
string lon_path = (*irv)->fullpath.substr(0,lon_pos);
GMcvar->cfdimname = lon_path + ((*irv)->dims)[1]->name;
ll_dim_set.insert(((*irv)->dims)[1]->name);
//ll_dim1 = ((*irv)->dims)[1]->name;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
}
else {
++irv;
}
}// for (vector<Var *>::iterator irv = this->vars.begin();...
#if 0
// Loop through all variables and create a dim set.
set<string> cvdimset;
pair<set<string>::iterator,bool> setret;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
for(vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
setret = cvdimset.insert((*ird)->name);
cerr<<"var name is "<<(*irv)->fullpath <<endl;
if (true == setret.second) {
cerr<<"dim name is "<<(*ird)->name <<endl;
Insert_One_NameSizeMap_Element((*ird)->name,(*ird)->size);
}
}
}// for (vector<Var *>::iterator irv = this->vars.begin();...
#endif
// For each dimension, create a coordinate variable.
// Here we just need to loop through the map dimname_to_dimsize,
// use the name and the size to create coordinate variables.
for (map<string,hsize_t>::const_iterator itd = dimname_to_dimsize.begin();
itd!=dimname_to_dimsize.end();++itd) {
// We will not create fake coordinate variables for the
// dimensions of latitude and longitude.
if((ll_dim_set.find(itd->first)) == ll_dim_set.end()) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,itd->first);
this->cvars.push_back(GMcvar);
}
}//for (map<string,hsize_t>::iterator itd = dimname_to_dimsize.begin(); ...
}
// Handle coordinate variables for GPM level 3
void GMFile::Handle_CVar_GPM_L3() throw(Exception){
iscoard = true;
//map<string,hsize_t>::iterator itd;
// Here we just need to loop through the map dimname_to_dimsize,
// use the name and the size to create coordinate variables.
for (map<string,hsize_t>::const_iterator itd = dimname_to_dimsize.begin();
itd!=dimname_to_dimsize.end();++itd) {
GMCVar*GMcvar = new GMCVar();
if("nlon" == itd->first || "nlat" == itd->first
|| "lnH" == itd->first || "ltH" == itd->first
|| "lnL" == itd->first || "ltL" == itd->first) {
GMcvar->name = itd->first;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5FLOAT32;
Dimension* gmcvar_dim = new Dimension(itd->second);
gmcvar_dim->name = GMcvar->name;
gmcvar_dim->newname = gmcvar_dim->name;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = gmcvar_dim->name;
if ("nlat" ==GMcvar->name || "ltH" == GMcvar->name
|| "ltL" == GMcvar->name)
GMcvar->cvartype = CV_LAT_MISS;
else if ("nlon" == GMcvar->name || "lnH" == GMcvar->name
|| "lnL" == GMcvar->name)
GMcvar->cvartype = CV_LON_MISS;
GMcvar->product_type = product_type;
}
else if (("nlayer" == itd->first && 28 == itd->second) ||
("hgt" == itd->first && 5 == itd->second) ||
("nalt" == itd->first && 5 == itd->second)){
GMcvar->name = itd->first;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5FLOAT32;
Dimension* gmcvar_dim = new Dimension(itd->second);
gmcvar_dim->name = GMcvar->name;
gmcvar_dim->newname = gmcvar_dim->name;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = gmcvar_dim->name;
GMcvar->cvartype = CV_SPECIAL;
GMcvar->product_type = product_type;
}
else
Create_Missing_CV(GMcvar,itd->first);
this->cvars.push_back(GMcvar);
}//for (map<string,hsize_t>::iterator itd = dimname_to_dimsize.begin(); ...
}
// Handle Coordinate variables for MeaSuRES SeaWiFS
void GMFile::Handle_CVar_Mea_SeaWiFS() throw(Exception){
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();++irs) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if ((*irs)== (*irv)->fullpath) {
if (!iscoard && (("/natrack" == (*irs))
|| "/nxtrack" == (*irs))) {
++irv;
continue;
}
if((*irv)->dims.size()!=1)
throw3("Coard coordinate variable ",(*irv)->name, "is not 1D");
// Create Coordinate variables.
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
} // if ((*irs)== (*irv)->fullpath)
else if(false == iscoard) {
// 2-D lat/lon, natrack maps to lat, nxtrack maps to lon.
if ((((*irs) =="/natrack") && ((*irv)->fullpath == "/latitude"))
||(((*irs) =="/nxtrack") && ((*irv)->fullpath == "/longitude"))) {
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
}
else {
++irv;
}
}// else if(false == iscoard)
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin() ...
} // for (set<string>::iterator irs = dimnamelist.begin() ...
// Creating the missing "third-dimension" according to the dimension names.
// This may never happen for the current MeaSure SeaWiFS, but put it here for code coherence and completeness.
// KY 12-30-2011
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();++irs) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle Coordinate varibles for SMAP(Note: this may be subject to change since SMAP products may have new structures)
void GMFile::Handle_CVar_SMAP() throw(Exception) {
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
string tempvarname;
string key0 = "_lat";
string key1 = "_lon";
string smapdim0 ="YDim";
string smapdim1 ="XDim";
bool foundkey0 = false;
bool foundkey1 = false;
set<string> itset;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
tempvarname = (*irv)->name;
if ((tempvarname.size() > key0.size())&&
(key0 == tempvarname.substr(tempvarname.size()-key0.size(),key0.size()))){
foundkey0 = true;
if (dimnamelist.find(smapdim0)== dimnamelist.end())
throw5("variable ",tempvarname," must have dimension ",smapdim0," , but not found ");
tempdimnamelist.erase(smapdim0);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->newname = GMcvar->name; // Remove the path, just use the variable name
GMcvar->cfdimname = smapdim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
// irv--;
}// if ((tempvarname.size() > key0.size())&& ...
else if ((tempvarname.size() > key1.size())&&
(key1 == tempvarname.substr(tempvarname.size()-key1.size(),key1.size()))){
foundkey1 = true;
if (dimnamelist.find(smapdim1)== dimnamelist.end())
throw5("variable ",tempvarname," must have dimension ",smapdim1," , but not found ");
tempdimnamelist.erase(smapdim1);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->newname = GMcvar->name;
GMcvar->cfdimname = smapdim1;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
// irv--;
}// else if ((tempvarname.size() > key1.size())&& ...
else {
++irv;
}
if (true == foundkey0 && true == foundkey1)
break;
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();++irs) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle coordinate variables for Aquarius level 3 products
void GMFile::Handle_CVar_Aqu_L3() throw(Exception) {
iscoard = true;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if ( "l3m_data" == (*irv)->name) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
GMCVar*GMcvar = new GMCVar();
GMcvar->name = (*ird)->name;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5FLOAT32;
Dimension* gmcvar_dim = new Dimension((*ird)->size);
gmcvar_dim->name = GMcvar->name;
gmcvar_dim->newname = gmcvar_dim->name;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = gmcvar_dim->name;
if ("lat" ==GMcvar->name ) GMcvar->cvartype = CV_LAT_MISS;
if ("lon" == GMcvar->name ) GMcvar->cvartype = CV_LON_MISS;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
} // for (vector<Dimension *>::iterator ird = (*irv)->dims.begin(); ...
} // if ( "l3m_data" == (*irv)->name)
}//for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
//Handle coordinate variables for MeaSuRES Ozone products
void GMFile::Handle_CVar_Mea_Ozone() throw(Exception){
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
if(false == iscoard)
throw1("Measure Ozone level 3 zonal average product must follow COARDS conventions");
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();++irs) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if ((*irs)== (*irv)->fullpath) {
if((*irv)->dims.size()!=1)
throw3("Coard coordinate variable",(*irv)->name, "is not 1D");
// Create Coordinate variables.
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
} // if ((*irs)== (*irv)->fullpath)
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
} // for (set<string>::iterator irs = dimnamelist.begin();
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();irs++) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle coordinate variables for general products that use HDF5 dimension scales.
void GMFile::Handle_CVar_Dimscale_General_Product() throw(Exception) {
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();++irs) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
// This is the dimension scale dataset; it should be changed to a coordinate variable.
if ((*irs)== (*irv)->fullpath) {
if((*irv)->dims.size()!=1)
throw3("COARDS coordinate variable",(*irv)->name, "is not 1D");
// Create Coordinate variables.
tempdimnamelist.erase(*irs);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = *irs;
// Check if this is just a netCDF-4 dimension.
bool is_netcdf_dimension = Is_netCDF_Dimension(*irv);
// If this is just the netcdf dimension, we
// will fill in the index numbers.
if (true == is_netcdf_dimension)
GMcvar->cvartype = CV_FILLINDEX;
else
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
irv = this->vars.erase(irv);
//irv--;
} // if ((*irs)== (*irv)->fullpath)
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin();
} // for (set<string>::iterator irs = dimnamelist.begin();
/// Comment out the following code because we are using a more general approach
#if 0
// Will check if this file has 2-D lat/lon.If yes, update the CV.
string latname,lonname;
bool latlon_2d_cv = Check_2DLatLon_Dimscale(latname, lonname);
if( true == latlon_2d_cv) {
Update_2DLatLon_Dimscale_CV(latname,lonname);
}
#endif
// Check if we have 2-D lat/lon CVs, and if yes, add those to the CV list.
Update_M2DLatLon_Dimscale_CVs();
// Add other missing coordinate variables.
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();irs++) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
//Debugging
#if 0
for (set<string>::iterator irs = dimnamelist.begin();
irs != dimnamelist.end();irs++) {
cerr<<"dimension name is "<<(*irs)<<endl;
}
#endif
}
// Check if we have 2-D lat/lon CVs, and if yes, add those to the CV list.
void GMFile::Update_M2DLatLon_Dimscale_CVs() throw(Exception) {
// If this is not a file that only includes 1-D lat/lon CVs
if(false == Check_1DGeolocation_Dimscale()) {
//if(iscoard == true)
//cerr<<"COARD is true at the beginning of Update"<<endl;
//cerr<<"File path is "<<this->path <<endl;
// Define temporary vectors to store 1-D lat/lon CVs
vector<GMCVar*> tempcvar_1dlat;
vector<GMCVar*> tempcvar_1dlon;
// 1. Obtain 1-D lat/lon CVs(only search the CF units and the reserved lat/lon names)
Obtain_1DLatLon_CVs(tempcvar_1dlat,tempcvar_1dlon);
// Define temporary vectors to store 2-D lat/lon Vars
vector<Var*> tempcvar_2dlat;
vector<Var*> tempcvar_2dlon;
// TODO: Add descriptions
// This map remembers the positions of the latlon vars in the vector var.
// Remembering the positions avoids the searching of these lat and lon again when
// deleting them for the var vector and adding them(only the CVs) to the CV vector.
// KY 2015-12-23
map<string,int> latlon2d_path_to_index;
// 2. Obtain 2-D lat/lon variables(only search the CF units and the reserved names)
Obtain_2DLatLon_Vars(tempcvar_2dlat,tempcvar_2dlon,latlon2d_path_to_index);
#if 0
for(vector<GMCVar *>::iterator irv = tempcvar_1dlat.begin();irv != tempcvar_1dlat.end();++irv)
cerr<<"1-D lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<GMCVar *>::iterator irv = tempcvar_1dlon.begin();irv != tempcvar_1dlon.end();++irv)
cerr<<"1-D lon variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv)
cerr<<"2-D lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv)
cerr<<"2-D lon variable full path is "<<(*irv)->fullpath <<endl;
#endif
// 3. Sequeeze the 2-D lat/lon vectors by removing the ones that share the same dims with 1-D lat/lon CVs.
Obtain_2DLLVars_With_Dims_not_1DLLCVars(tempcvar_2dlat,tempcvar_2dlon,tempcvar_1dlat,tempcvar_1dlon,latlon2d_path_to_index);
#if 0
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv)
cerr<<"2-D Left lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv)
cerr<<"2-D Left lon variable full path is "<<(*irv)->fullpath <<endl;
#endif
// 4. Assemble the final 2-D lat/lon CV candidate vectors by checking if the corresponding 2-D lon of a 2-D lat shares
// the same dimension and under the same group and if there is another pair of 2-D lat/lon under the same group.
Obtain_2DLLCVar_Candidate(tempcvar_2dlat,tempcvar_2dlon,latlon2d_path_to_index);
#if 0
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv)
cerr<<"Final candidate 2-D Left lat variable full path is "<<(*irv)->fullpath <<endl;
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv)
cerr<<"Final candidate 2-D Left lon variable full path is "<<(*irv)->fullpath <<endl;
#endif
// 5. Remove the 2-D lat/lon variables that are to be used as CVs from the vector that stores general variables
// var2d_index remembers the index of the 2-D lat/lon CVs in the original vector of vars.
vector<int> var2d_index;
for (map<string,int>::const_iterator it= latlon2d_path_to_index.begin();it!=latlon2d_path_to_index.end();++it)
var2d_index.push_back(it->second);
Remove_2DLLCVar_Final_Candidate_from_Vars(var2d_index);
// 6. If we have 2-D CVs, COARDS should be turned off.
if(tempcvar_2dlat.size()>0)
iscoard = false;
// 7. Add the CVs based on the final 2-D lat/lon CV candidates.
// We need to remember the dim names that the 2-D lat/lon CVs are associated with.
set<string>dim_names_2d_cvs;
for(vector<Var *>::iterator irv = tempcvar_2dlat.begin();irv != tempcvar_2dlat.end();++irv){
//cerr<<"3 2-D Left lat variable full path is "<<(*irv)->fullpath <<endl;
GMCVar *lat = new GMCVar((*irv));
// Latitude is always corresponding to the first dimension.
lat->cfdimname = (*irv)->getDimensions()[0]->name;
dim_names_2d_cvs.insert(lat->cfdimname);
lat->cvartype = CV_EXIST;
lat->product_type = product_type;
this->cvars.push_back(lat);
}
for(vector<Var *>::iterator irv = tempcvar_2dlon.begin();irv != tempcvar_2dlon.end();++irv){
//cerr<<"3 2-D Left lon variable full path is "<<(*irv)->fullpath <<endl;
GMCVar *lon = new GMCVar((*irv));
// Longitude is always corresponding to the second dimension.
lon->cfdimname = (*irv)->getDimensions()[1]->name;
dim_names_2d_cvs.insert(lon->cfdimname);
lon->cvartype = CV_EXIST;
lon->product_type = product_type;
this->cvars.push_back(lon);
}
// 8. Move the originally assigned 1-D CVs that are replaced by 2-D CVs back to the general variable list.
// Also remove the CV created by the pure dimensions.
// Dimension names are used to identify those 1-D CVs.
for(vector<GMCVar*>::iterator ircv= this->cvars.begin();ircv !=this->cvars.end();) {
if(1 == (*ircv)->rank) {
if(dim_names_2d_cvs.find((*ircv)->cfdimname)!=dim_names_2d_cvs.end()) {
if(CV_FILLINDEX == (*ircv)->cvartype) {// This is pure dimension
delete(*ircv);
ircv = this->cvars.erase(ircv);
}
else if(CV_EXIST == (*ircv)->cvartype) {// This var exists already
// Add this var. to the var list.
Var *var = new Var((*ircv));
this->vars.push_back(var);
// Remove this var. from the GMCVar list.
delete(*ircv);
ircv = this->cvars.erase(ircv);
}
else {// the removed 1-D coordinate variable should be either the CV_FILLINDEX or CV_EXIST.
if(CV_LAT_MISS == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_LAT_MISS");
else if(CV_LON_MISS == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_LON_MISS");
else if(CV_NONLATLON_MISS == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_NONLATLON_MISS");
else if(CV_MODIFY == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_MODIFY");
else if(CV_SPECIAL == (*ircv)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_SPECIAL");
else
throw3("For the 2-D lat/lon case, the latitude dimension name ",(*ircv)->cfdimname, "is a coordinate variable of type CV_UNSUPPORTED");
}
}
else
++ircv;
}
else
++ircv;
}
#if 0
//if(iscoard == true)
//cerr<<"COARD is true"<<endl;
for(set<string>::iterator irs = grp_cv_paths.begin();irs != grp_cv_paths.end();++irs) {
cerr<<"group path is "<< (*irs)<<endl;
}
#endif
#if 0
//Print CVs
cerr<<"File name is "<< this->path <<endl;
cerr<<"CV names are the following "<<endl;
for (vector<GMCVar *>:: iterator i= this->cvars.begin(); i!=this->cvars.end(); ++i)
cerr<<(*i)->fullpath <<endl;
#endif
// 6. release the resources allocated by the temporary vectors.
release_standalone_GMCVar_vector(tempcvar_1dlat);
release_standalone_GMCVar_vector(tempcvar_1dlon);
release_standalone_var_vector(tempcvar_2dlat);
release_standalone_var_vector(tempcvar_2dlon);
}
}
// If Check_1DGeolocation_Dimscale() is true, no need to build 2-D lat/lon coordinate variables.
// This function is introduced to avoid the performance penalty caused by handling the general 2-D lat/lon case.
bool GMFile::Check_1DGeolocation_Dimscale() throw(Exception) {
bool has_only_1d_geolocation_cv = false;
bool has_1d_lat_cv_flag = false;
bool has_1d_lon_cv_flag = false;
string lat_dimname;
hsize_t lat_size = 0;
string lon_dimname;
hsize_t lon_size = 0;
// We need to consider both 1-D lat/lon and the 1-D zonal average case(1-D lat only).
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
string attr_name ="units";
string lat_unit_value = "degrees_north";
string lon_unit_value = "degrees_east";
for(vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end();ira++) {
if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lat_unit_value)) {
lat_size = (*ircv)->getDimensions()[0]->size;
lat_dimname = (*ircv)->getDimensions()[0]->name;
has_1d_lat_cv_flag = true;
break;
}
else if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lon_unit_value)){
lon_size = (*ircv)->getDimensions()[0]->size;
lon_dimname = (*ircv)->getDimensions()[0]->name;
has_1d_lon_cv_flag = true;
break;
}
}
}
}
// If having 1-D lat/lon CVs, this is a good sign for only 1-D lat/lon CVs ,
// just need to have a couple of checks.
if(true == has_1d_lat_cv_flag ) {
if(true == has_1d_lon_cv_flag) {
//cerr<<"BOTH 1-D lat/lon CVs are true "<<endl;
// Come to the possible classic netCDF-4 case,
if(0 == this->groups.size()) {
// Rarely happens when lat_size is the same as the lon_size.
// However, still want to make sure there is a 2-D variable that uses both lat and lon dims.
if(lat_size == lon_size) {
bool var_has_latdim = false;
bool var_has_londim = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank >= 2) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
if((*ird)->name == lat_dimname)
var_has_latdim = true;
else if((*ird)->name == lon_dimname)
var_has_londim = true;
}
if(true == var_has_latdim && true == var_has_londim) {
has_only_1d_geolocation_cv = true;
break;
}
else {
var_has_latdim = false;
var_has_londim = false;
}
}
}
}
else
has_only_1d_geolocation_cv = true;
}
else {
// Multiple groups, need to check if having 2-D lat/lon pairs
bool has_2d_latname_flag = false;
bool has_2d_lonname_flag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
//Note: When the 2nd parameter is true in the function Is_geolatlon, it checks the lat/latitude/Latitude
if(true == Is_geolatlon((*irv)->name,true))
has_2d_latname_flag = true;
//Note: When the 2nd parameter is false in the function Is_geolatlon, it checks the lon/longitude/Longitude
else if(true == Is_geolatlon((*irv)->name,false))
has_2d_lonname_flag = true;
if((true == has_2d_latname_flag) && (true == has_2d_lonname_flag))
break;
}
}
if(has_2d_latname_flag != true || has_2d_lonname_flag != true) {
//Check if having the 2-D lat/lon by checking if having lat/lon CF units(lon's units: degrees_east lat's units: degrees_north)
has_2d_latname_flag = false;
has_2d_lonname_flag = false;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
if (false == has_2d_latname_flag) {
// When the third parameter of the function has_latlon_cf_units is set to true, it checks latitude
has_2d_latname_flag = has_latlon_cf_units((*ira),(*irv)->fullpath,true);
if(true == has_2d_latname_flag)
break;
else if(false == has_2d_lonname_flag) {
// When the third parameter of the function has_latlon_cf_units is set to false, it checks longitude
has_2d_lonname_flag = has_latlon_cf_units((*ira),(*irv)->fullpath,false);
if(true == has_2d_lonname_flag)
break;
}
}
else if(false == has_2d_lonname_flag) {
// Now has_2d_latname_flag is true, just need to check the has_2d_lonname_flag
// When the third parameter of has_latlon_cf_units is set to false, it checks longitude
has_2d_lonname_flag = has_latlon_cf_units((*ira),(*irv)->fullpath,false);
if(true == has_2d_lonname_flag)
break;
}
}
if(true == has_2d_latname_flag && true == has_2d_lonname_flag)
break;
}
}
}
// If we cannot find either of 2-D any lat/lon variables, this file is treated as having only 1-D lat/lon.
if(has_2d_latname_flag != true || has_2d_lonname_flag != true)
has_only_1d_geolocation_cv = true;
}
}//
else {//Zonal average case, we do not need to find 2-D lat/lon CVs.
has_only_1d_geolocation_cv = true;
}
}
#if 0
if(has_only_1d_geolocation_cv == true)
cerr <<"has only 1D lat/lon CVs. "<<endl;
else
cerr<<"Possibly has 2D lat/lon CVs. "<<endl;
#endif
return has_only_1d_geolocation_cv;
}
// Obtain the originally assigned 1-D lat/lon coordinate variables.
// This function should be used before generating any 2-D lat/lon CVs.
void GMFile::Obtain_1DLatLon_CVs(vector<GMCVar*> &cvar_1dlat,vector<GMCVar*> &cvar_1dlon) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
string attr_name ="units";
string lat_unit_value = "degrees_north";
string lon_unit_value = "degrees_east";
for(vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end();ira++) {
// 1-D latitude
if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lat_unit_value)) {
GMCVar *lat = new GMCVar((*ircv));
lat->cfdimname = (*ircv)->getDimensions()[0]->name;
lat->cvartype = (*ircv)->cvartype;
lat->product_type = (*ircv)->product_type;
cvar_1dlat.push_back(lat);
}
// 1-D longitude
else if(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lon_unit_value)){
GMCVar *lon = new GMCVar((*ircv));
lon->cfdimname = (*ircv)->getDimensions()[0]->name;
lon->cvartype = (*ircv)->cvartype;
lon->product_type = (*ircv)->product_type;
cvar_1dlon.push_back(lon);
}
}
}
}
}
// Obtain all 2-D lat/lon variables.
// Latitude variables are saved in the vector var_2dlat. Longitude variables are saved in the vector var_2dlon.
// We also remember the index of these lat/lon in the original var vector.
void GMFile::Obtain_2DLatLon_Vars(vector<Var*> &var_2dlat,vector<Var*> &var_2dlon,map<string,int> & latlon2d_path_to_index) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
//Note: When the 2nd parameter is true in the function Is_geolatlon, it checks the lat/latitude/Latitude
if(true == Is_geolatlon((*irv)->name,true)) {
Var *lat = new Var((*irv));
var_2dlat.push_back(lat);
latlon2d_path_to_index[(*irv)->fullpath]= distance(this->vars.begin(),irv);
continue;
}
else {
bool has_2dlat = false;
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
// When the third parameter of has_latlon_cf_units is set to true, it checks latitude
if(true == has_latlon_cf_units((*ira),(*irv)->fullpath,true)) {
Var *lat = new Var((*irv));
var_2dlat.push_back(lat);
latlon2d_path_to_index[(*irv)->fullpath] = distance(this->vars.begin(),irv);
has_2dlat = true;
break;
}
}
if(true == has_2dlat)
continue;
}
//Note: When the 2nd parameter is false in the function Is_geolatlon, it checks the lon/longitude/Longitude
if(true == Is_geolatlon((*irv)->name,false)) {
Var *lon = new Var((*irv));
latlon2d_path_to_index[(*irv)->fullpath] = distance(this->vars.begin(),irv);
var_2dlon.push_back(lon);
}
else {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira) {
// When the third parameter of has_latlon_cf_units is set to false, it checks longitude
if(true == has_latlon_cf_units((*ira),(*irv)->fullpath,false)) {
Var *lon = new Var((*irv));
latlon2d_path_to_index[(*irv)->fullpath] = distance(this->vars.begin(),irv);
var_2dlon.push_back(lon);
break;
}
}
}
}
}
}
// Sequeeze the 2-D lat/lon vectors by removing the ones that share the same dims with 1-D lat/lon CVs.
// The latlon2d_path_to_index map also needs to be updated.
void GMFile::Obtain_2DLLVars_With_Dims_not_1DLLCVars(vector<Var*> &var_2dlat,
vector<Var*> &var_2dlon,
vector<GMCVar*> &cvar_1dlat,
vector<GMCVar*> &cvar_1dlon,
map<string,int> &latlon2d_path_to_index) {
for(vector<Var *>::iterator irv = var_2dlat.begin();irv != var_2dlat.end();) {
bool remove_2dlat = false;
for(vector<GMCVar *>::iterator ircv = cvar_1dlat.begin();ircv != cvar_1dlat.end();++ircv) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end(); ++ird) {
if((*ird)->name == (*ircv)->getDimensions()[0]->name &&
(*ird)->size == (*ircv)->getDimensions()[0]->size) {
latlon2d_path_to_index.erase((*irv)->fullpath);
delete(*irv);
irv = var_2dlat.erase(irv);
remove_2dlat = true;
break;
}
}
if(true == remove_2dlat)
break;
}
if(false == remove_2dlat)
++irv;
}
for(vector<Var *>::iterator irv = var_2dlon.begin();irv != var_2dlon.end();) {
bool remove_2dlon = false;
for(vector<GMCVar *>::iterator ircv = cvar_1dlon.begin();ircv != cvar_1dlon.end();++ircv) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end(); ++ird) {
if((*ird)->name == (*ircv)->getDimensions()[0]->name &&
(*ird)->size == (*ircv)->getDimensions()[0]->size) {
latlon2d_path_to_index.erase((*irv)->fullpath);
delete(*irv);
irv = var_2dlon.erase(irv);
remove_2dlon = true;
break;
}
}
if(true == remove_2dlon)
break;
}
if(false == remove_2dlon)
++irv;
}
}
//Out of the collected 2-D lat/lon variables, we will select the final qualified 2-D lat/lon as CVs.
void GMFile::Obtain_2DLLCVar_Candidate(vector<Var*> &var_2dlat,
vector<Var*> &var_2dlon,
map<string,int>& latlon2d_path_to_index) throw(Exception){
// First check 2-D lat, see if we have the corresponding 2-D lon(same dims, under the same group).
// If no, remove that lat from the vector.
vector<string> lon2d_group_paths;
for(vector<Var *>::iterator irv_2dlat = var_2dlat.begin();irv_2dlat !=var_2dlat.end();) {
for(vector<Var *>::iterator irv_2dlon = var_2dlon.begin();irv_2dlon != var_2dlon.end();++irv_2dlon) {
if(((*irv_2dlat)->getDimensions()[0]->name == (*irv_2dlon)->getDimensions()[0]->name) &&
((*irv_2dlat)->getDimensions()[0]->size == (*irv_2dlon)->getDimensions()[0]->size) &&
((*irv_2dlat)->getDimensions()[1]->name == (*irv_2dlon)->getDimensions()[1]->name) &&
((*irv_2dlat)->getDimensions()[1]->size == (*irv_2dlon)->getDimensions()[1]->size))
lon2d_group_paths.push_back(HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlon)->fullpath));
//lon2d_group_paths.push_back((*irv_2dlon)->fullpath.substr(0,(*irv_2dlon)->fullpath.find_last_of("/")));
}
// Doesn't find any lons that shares the same dims,remove this lat from the 2dlat vector,
// also update the latlon2d_path_to_index map
if(0 == lon2d_group_paths.size()) {
latlon2d_path_to_index.erase((*irv_2dlat)->fullpath);
delete(*irv_2dlat);
irv_2dlat = var_2dlat.erase(irv_2dlat);
}
else {// Find lons,check if they are under the same group
//string lat2d_group_path = (*irv_2dlat)->fullpath.substr(0,(*irv_2dlat)->fullpath.find_last_of("/"));
string lat2d_group_path = HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlat)->fullpath);
// Check how many lon2d shares the same group with the lat2d
short lon2d_has_lat2d_group_path_flag = 0;
for(vector<string>::iterator ivs = lon2d_group_paths.begin();ivs!=lon2d_group_paths.end();++ivs) {
if((*ivs)==lat2d_group_path)
lon2d_has_lat2d_group_path_flag++;
}
// No lon2d shares the same group with the lat2d, remove this lat2d
if(0 == lon2d_has_lat2d_group_path_flag) {
latlon2d_path_to_index.erase((*irv_2dlat)->fullpath);
delete(*irv_2dlat);
irv_2dlat = var_2dlat.erase(irv_2dlat);
}
// Only one lon2d, yes, keep it.
else if (1== lon2d_has_lat2d_group_path_flag) {
++irv_2dlat;
}
// More than 1 lon2d, we will remove the lat2d, but save the group path so that we may
// flatten the variable path stored in the coordinates attribute under this group.
else {
// Save the group path for the future use.
grp_cv_paths.insert(lat2d_group_path);
latlon2d_path_to_index.erase((*irv_2dlat)->fullpath);
delete(*irv_2dlat);
irv_2dlat = var_2dlat.erase(irv_2dlat);
}
}
//Clear the vector that stores the same dim. since it is only applied to this lat,
lon2d_group_paths.clear();
}
#if 0
for(vector<Var *>::iterator irv_2dlat = var_2dlat.begin();irv_2dlat !=var_2dlat.end();++irv_2dlat)
cerr<<"2 left 2-D lat variable full path is: "<<(*irv_2dlat)->fullpath <<endl;
#endif
// Second check 2-D lon, see if we have the corresponding 2-D lat(same dims, under the same group).
// If no, remove that lon from the vector.
vector<string> lat2d_group_paths;
// Check the longitude
for(vector<Var *>::iterator irv_2dlon = var_2dlon.begin();irv_2dlon !=var_2dlon.end();) {
for(vector<Var *>::iterator irv_2dlat = var_2dlat.begin();irv_2dlat != var_2dlat.end();++irv_2dlat) {
if(((*irv_2dlat)->getDimensions()[0]->name == (*irv_2dlon)->getDimensions()[0]->name) &&
((*irv_2dlat)->getDimensions()[0]->size == (*irv_2dlon)->getDimensions()[0]->size) &&
((*irv_2dlat)->getDimensions()[1]->name == (*irv_2dlon)->getDimensions()[1]->name) &&
((*irv_2dlat)->getDimensions()[1]->size == (*irv_2dlon)->getDimensions()[1]->size))
lat2d_group_paths.push_back(HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlat)->fullpath));
//lat2d_group_paths.push_back((*irv_2dlat)->fullpath.substr(0,(*irv_2dlat)->fullpath.find_last_of("/")));
}
// Doesn't find any lats that shares the same dims,remove this lon from this vector
if(0 == lat2d_group_paths.size()) {
latlon2d_path_to_index.erase((*irv_2dlon)->fullpath);
delete(*irv_2dlon);
irv_2dlon = var_2dlon.erase(irv_2dlon);
}
else {
//string lon2d_group_path = (*irv_2dlon)->fullpath.substr(0,(*irv_2dlon)->fullpath.find_last_of("/"));
string lon2d_group_path = HDF5CFUtil::obtain_string_before_lastslash((*irv_2dlon)->fullpath);
// Check how many lat2d shares the same group with the lon2d
short lat2d_has_lon2d_group_path_flag = 0;
for(vector<string>::iterator ivs = lat2d_group_paths.begin();ivs!=lat2d_group_paths.end();++ivs) {
if((*ivs)==lon2d_group_path)
lat2d_has_lon2d_group_path_flag++;
}
// No lat2d shares the same group with the lon2d, remove this lon2d
if(0 == lat2d_has_lon2d_group_path_flag) {
latlon2d_path_to_index.erase((*irv_2dlon)->fullpath);
delete(*irv_2dlon);
irv_2dlon = var_2dlon.erase(irv_2dlon);
}
// Only one lat2d shares the same group with the lon2d, yes, keep it.
else if (1== lat2d_has_lon2d_group_path_flag) {
++irv_2dlon;
}
// more than 1 lat2d, we will remove the lon2d, but save the group path so that we can
// change the coordinates attribute for variables under this group later.
else {
// Save the group path for future "coordinates" modification.
grp_cv_paths.insert(lon2d_group_path);
latlon2d_path_to_index.erase((*irv_2dlon)->fullpath);
delete(*irv_2dlon);
irv_2dlon = var_2dlon.erase(irv_2dlon);
}
}
//Clear the vector that stores the same dim. since it is only applied to this lon,
lat2d_group_paths.clear();
}
#if 0
for(vector<Var*>::iterator itv = var_2dlat.begin(); itv!= var_2dlat.end();++itv) {
cerr<<"Before unique, 2-D CV latitude name is "<<(*itv)->fullpath <<endl;
}
for(vector<Var*>::iterator itv = var_2dlon.begin(); itv!= var_2dlon.end();++itv) {
cerr<<"Before unique, 2-D CV longitude name is "<<(*itv)->fullpath <<endl;
}
#endif
// Final check var_2dlat and var_2dlon to remove non-qualified CVs.
Obtain_unique_2dCV(var_2dlat,latlon2d_path_to_index);
Obtain_unique_2dCV(var_2dlon,latlon2d_path_to_index);
#if 0
for(vector<Var*>::iterator itv = var_2dlat.begin(); itv!= var_2dlat.end();++itv) {
cerr<<"2-D CV latitude name is "<<(*itv)->fullpath <<endl;
}
for(vector<Var*>::iterator itv = var_2dlon.begin(); itv!= var_2dlon.end();++itv) {
cerr<<"2-D CV longitude name is "<<(*itv)->fullpath <<endl;
}
#endif
// This is to serve as a sanity check. This can help us find bugs in the first place.
if(var_2dlat.size() != var_2dlon.size()) {
throw1("Error in generating 2-D lat/lon CVs.");
}
}
// If two vars in the 2-D lat or 2-D lon CV candidate vector share the same dim. , these two vars cannot be CVs.
// The group they belong to is the group candidate that the coordinates attribute of the variable under that group may be modified..
void GMFile::Obtain_unique_2dCV(vector<Var*> &var_ll,map<string,int>&latlon2d_path_to_index){
vector<bool> var_share_dims(var_ll.size(),false);
for( int i = 0; i <var_ll.size();i++) {
string var_ll_i_path = HDF5CFUtil::obtain_string_before_lastslash(var_ll[i]->fullpath);
for(int j = i+1; j<var_ll.size();j++) {
if((var_ll[i]->getDimensions()[0]->name == var_ll[j]->getDimensions()[0]->name)
||(var_ll[i]->getDimensions()[0]->name == var_ll[j]->getDimensions()[1]->name)
||(var_ll[i]->getDimensions()[1]->name == var_ll[j]->getDimensions()[0]->name)
||(var_ll[i]->getDimensions()[1]->name == var_ll[j]->getDimensions()[1]->name)){
string var_ll_j_path = HDF5CFUtil::obtain_string_before_lastslash(var_ll[j]->fullpath);
// Compare var_ll_i_path and var_ll_j_path,only set the child group path be true and remember the path.
// Obtain the string size,
// compare the string size, long.compare(0,shortlength,short)==0,
// yes, save the long path(child group path), set the long path one true. Else save two paths, set both true
if(var_ll_i_path.size() > var_ll_j_path.size()) {
// If var_ll_j_path is the parent group of var_ll_i_path,
// set the shared dim. be true for the child group only,remember the path.
if(var_ll_i_path.compare(0,var_ll_j_path.size(),var_ll_j_path)==0) {
var_share_dims[i] = true;
grp_cv_paths.insert(var_ll_i_path);
}
else {// Save both as shared, they cannot be CVs.
var_share_dims[i] = true;
var_share_dims[j] = true;
grp_cv_paths.insert(var_ll_i_path);
grp_cv_paths.insert(var_ll_j_path);
}
}
else if (var_ll_i_path.size() == var_ll_j_path.size()) {// Share the same group, remember both group paths.
var_share_dims[i] = true;
var_share_dims[j] = true;
if(var_ll_i_path == var_ll_j_path)
grp_cv_paths.insert(var_ll_i_path);
else {
grp_cv_paths.insert(var_ll_i_path);
grp_cv_paths.insert(var_ll_j_path);
}
}
else {
// var_ll_i_path is the parent group of var_ll_j_path,
// set the shared dim. be true for the child group,remember the path.
if(var_ll_j_path.compare(0,var_ll_i_path.size(),var_ll_i_path)==0) {
var_share_dims[j] = true;
grp_cv_paths.insert(var_ll_j_path);
}
else {// Save both as shared, they cannot be CVs.
var_share_dims[i] = true;
var_share_dims[j] = true;
grp_cv_paths.insert(var_ll_i_path);
grp_cv_paths.insert(var_ll_j_path);
}
}
}
}
}
// Remove the shared 2-D lat/lon CVs from the 2-D lat/lon CV candidates.
int var_index = 0;
for(vector<Var*>::iterator itv = var_ll.begin(); itv!= var_ll.end();) {
if(true == var_share_dims[var_index]) {
latlon2d_path_to_index.erase((*itv)->fullpath);
delete(*itv);
itv = var_ll.erase(itv);
}
else {
++itv;
}
++var_index;
}
}
// When promoting a 2-D lat or lon to a coordinate variable, we need to remove them from the general variable vector.
void GMFile::Remove_2DLLCVar_Final_Candidate_from_Vars(vector<int> &var2d_index) throw(Exception) {
//Sort the 2-D lat/lon var index according to the ascending order before removing the 2-D lat/lon vars
sort(var2d_index.begin(),var2d_index.end());
vector<Var *>::iterator it = this->vars.begin();
// This is a performance optimiziation operation.
// We find it is typical for swath files that have many many general variables but only have very few lat/lon CVs.
// To reduce the looping through all variables and comparing the fullpath(string), we use index and remember
// the position of 2-D CVs in the iterator. In this way, only a few operations are needed.
for (int i = 0; i <var2d_index.size();i++) {
if ( i == 0)
advance(it,var2d_index[i]);
else
advance(it,var2d_index[i]-var2d_index[i-1]-1);
if(it == this->vars.end())
throw1("Out of range to obtain 2D lat/lon variables");
else {
//cerr<<"removed latitude/longitude names are "<<(*it)->fullpath <<endl;
delete(*it);
it = this->vars.erase(it);
}
}
}
//This function is for generating the coordinates attribute for the 2-D lat/lon.
//It will check if this var can have the "coordinates" attribute that includes the 2-D lat/lon.
bool GMFile::Check_Var_2D_CVars(Var *var) throw(Exception) {
bool ret_value = true;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank==2) {
short first_dim_index = 0;
short first_dim_times = 0;
short second_dim_index = 0;
short second_dim_times = 0;
for (vector<Dimension *>::iterator ird = var->dims.begin();
ird != var->dims.end(); ++ird) {
if((*ird)->name == ((*ircv)->getDimensions()[0])->name) {
first_dim_index = distance(var->dims.begin(),ird);
first_dim_times++;
}
else if((*ird)->name == ((*ircv)->getDimensions()[1])->name) {
second_dim_index = distance(var->dims.begin(),ird);
second_dim_times++;
}
}
// The 2-D CV dimensions must only appear once as the dimension of the variable
// It also must follow the dimension order of the 2-D lat/lon dimensions.
if(first_dim_times == 1 && second_dim_times == 1) {
if(first_dim_index < second_dim_index) {
ret_value = false;
break;
}
}
}
}
return ret_value;
}
// This function flattens the variable path in the "coordinates" attribute.
bool GMFile::Flatten_VarPath_In_Coordinates_Attr(Var *var) throw(Exception) {
string co_attrname = "coordinates";
bool has_coor_attr = false;
string orig_coor_value;
string flatten_coor_value;
char sc = ' ';
for (vector<Attribute *>:: iterator ira =var->attrs.begin(); ira !=var->attrs.end();) {
// We only check the original attribute name
// Remove the original "coordinates" attribute.
if((*ira)->name == co_attrname) {
Retrieve_H5_Attr_Value((*ira),var->fullpath);
string orig_attr_value((*ira)->value.begin(),(*ira)->value.end());
orig_coor_value = orig_attr_value;
has_coor_attr = true;
delete(*ira);
ira = var->attrs.erase(ira);
break;
}
else
++ira;
}
if(true == has_coor_attr) {
// We need to loop through each element in the "coordinates".
size_t ele_start_pos = 0;
size_t cur_pos = orig_coor_value.find_first_of(sc);
while(cur_pos !=string::npos) {
string tempstr = orig_coor_value.substr(ele_start_pos,cur_pos-ele_start_pos);
tempstr = get_CF_string(tempstr);
flatten_coor_value += tempstr + sc;
ele_start_pos = cur_pos+1;
cur_pos = orig_coor_value.find_first_of(sc,cur_pos+1);
}
// Flatten each element
if(ele_start_pos == 0)
flatten_coor_value = get_CF_string(orig_coor_value);
else
flatten_coor_value += get_CF_string(orig_coor_value.substr(ele_start_pos));
// Generate the new "coordinates" attribute.
Attribute *attr = new Attribute();
Add_Str_Attr(attr,co_attrname,flatten_coor_value);
var->attrs.push_back(attr);
}
return true;
}
// The following two routines only handle one 2-D lat/lon CVs. It is replaced by the more general
// multi 2-D lat/lon CV routines. Leave it here just for references.
#if 0
bool GMFile::Check_2DLatLon_Dimscale(string & latname, string &lonname) throw(Exception) {
// New code to support 2-D lat/lon, still in development.
// Need to handle 2-D latitude and longitude cases.
// 1. Searching only the coordinate variables and if getting either of the following, keep the current way,
// (A) GMcvar no CV_FILLINDEX:(The 2-D latlon case should have fake CVs)
// (B) CV_EXIST: Attributes contain units and units value is degrees_east or degrees_north(have lat/lon)
// (B) CV_EXIST: variables have name pair{lat/latitude/Latitude,lon/longitude/Longitude}(have lat/lon)
//
// 2. if not 1), searching all the variables and see if finding variables {lat/latitude/Latitude,lon/longitude/Longitude};
// If finding {lat/lon},{latitude,longitude},{latitude,Longitude} pair,
// if the number of dimension of either variable is not 2, keep the current way.
// else check if the dimension name of latitude and longitude are the same, not, keep the current way
// check the units of this CV pair, if units of the latitude is not degrees_north,
// change it to degrees_north.
// if units of the longitude is not degrees_east, change it to degrees_east.
// make iscoard false.
bool latlon_2d_cv_check1 = false;
// Some products(TOM MEaSURE) provide the true dimension scales for 2-D lat,lon. So relax this check.
latlon_2d_cv_check1 = true;
#if 0
// If having 2-D lat/lon, the corresponding dimension must be pure and the CV type must be FILLINDEX.
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_FILLINDEX){
latlon_2d_cv_check1 = true;
break;
}
}
#endif
bool latlon_2d_cv_check2 = true;
// There may still not be 2-D lat/lon. Check the units attributes and lat/lon pairs.
if(true == latlon_2d_cv_check1) {
BESDEBUG("h5","Coming to check if having 2d latlon coordinates for a netCDF-4 like product. "<<endl);
// check if units attribute values have CF lat/lon units "degrees_north" or "degrees_east".
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
for(vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end();ira++) {
string attr_name ="units";
string lat_unit_value = "degrees_north";
string lon_unit_value = "degrees_east";
// Considering the cross-section case, either is fine.
if((true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lat_unit_value)) ||
(true == Is_Str_Attr(*ira,(*ircv)->fullpath,attr_name,lon_unit_value))) {
latlon_2d_cv_check2= false;
break;
}
}
}
if(false == latlon_2d_cv_check2)
break;
}
}
bool latlon_2d_cv_check3 = true;
// Even we cannot find the CF lat/lon attributes, we may still find lat/lon etc pairs.
if(true == latlon_2d_cv_check1 && true == latlon_2d_cv_check2) {
short latlon_flag = 0;
short LatLon_flag = 0;
short latilong_flag = 0;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_EXIST) {
if((*ircv)->name == "lat")
latlon_flag++;
else if((*ircv)->name == "lon")
latlon_flag++;
else if((*ircv)->name == "latitude")
latilong_flag++;
else if((*ircv)->name == "longitude")
latilong_flag++;
else if((*ircv)->name == "Latitude")
LatLon_flag++;
else if((*ircv)->name == "Longitude")
LatLon_flag++;
}
}
if((2== latlon_flag) || (2 == latilong_flag) || (2 == LatLon_flag ))
latlon_2d_cv_check3 = false;
}
bool latlon_2d = false;
short latlon_flag = 0;
string latdim1,latdim2,londim1,londim2;
short LatLon_flag = 0;
string Latdim1,Latdim2,Londim1,Londim2;
short latilong_flag = 0;
string latidim1,latidim2,longdim1,longdim2;
// Final check, we need to check if we have 2-D {lat/latitude/Latitude, lon/longitude/Longitude}
// in the general variable list.
// Here, depending on the future support, lat/lon pairs with other names(cell_lat,cell_lon etc) may be supported.
// KY 2015-12-03
if(true == latlon_2d_cv_check1 && true == latlon_2d_cv_check2 && true == latlon_2d_cv_check3) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
//
if((*irv)->rank == 2) {
if((*irv)->name == "lat") {
latlon_flag++;
latdim1 = (*irv)->getDimensions()[0]->name;
latdim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "lon") {
latlon_flag++;
londim1 = (*irv)->getDimensions()[0]->name;
londim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "latitude"){
latilong_flag++;
latidim1 = (*irv)->getDimensions()[0]->name;
latidim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "longitude"){
latilong_flag++;
longdim1 = (*irv)->getDimensions()[0]->name;
longdim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "Latitude"){
LatLon_flag++;
Latdim1 = (*irv)->getDimensions()[0]->name;
Latdim2 = (*irv)->getDimensions()[1]->name;
}
else if((*irv)->name == "Longitude"){
LatLon_flag++;
Londim1 = (*irv)->getDimensions()[0]->name;
Londim2 = (*irv)->getDimensions()[1]->name;
}
}
}
// Here we ensure that only one lat/lon(lati/long,Lati/Long) is in the file.
// If we find >=2 pairs lat/lon and latitude/longitude, or Latitude/Longitude,
// we will not treat this as a 2-D latlon Dimscale case. The data producer
// should correct their mistakes.
if(2 == latlon_flag) {
if((2 == latilong_flag) || ( 2 == LatLon_flag))
latlon_2d = false;
else if((latdim1 == londim1) && (latdim2 == londim2)) {
latname = "lat";
lonname = "lon";
latlon_2d = true;
}
}
else if ( 2 == latilong_flag) {
if( 2 == LatLon_flag)
latlon_2d = false;
else if ((latidim1 == longdim1) ||(latidim2 == longdim2)) {
latname = "latitude";
lonname = "longitude";
latlon_2d = true;
}
}
else if (2 == LatLon_flag){
if ((Latdim1 == Londim1) ||(Latdim2 == Londim2)) {
latname = "Latitude";
lonname = "Longitude";
latlon_2d = true;
}
}
}
return latlon_2d;
}
// Update the coordinate variables for files that use HDF5 dimension scales and have 2-D lat/lon.
void GMFile::Update_2DLatLon_Dimscale_CV(const string &latname,const string &lonname) throw(Exception) {
iscoard = false;
// Update latitude.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
// Find 2-D latitude
if((*irv)->name == latname) {
// Obtain the first dimension of this variable
string latdim0 = (*irv)->getDimensions()[0]->name;
//cerr<<"latdim0 is "<<latdim0 <<endl;
// Remove the CV corresponding to latdim0
for (vector<GMCVar *>:: iterator i= this->cvars.begin(); i!=this->cvars.end(); ) {
if((*i)->cfdimname == latdim0) {
if(CV_FILLINDEX == (*i)->cvartype) {
delete(*i);
i = this->cvars.erase(i);
}
else if(CV_EXIST == (*i)->cvartype) {
// Add this var. to the var list.
Var *var = new Var((*i));
this->vars.push_back(var);
// Remove this var. from the GMCVar list.
delete(*i);
i = this->cvars.erase(i);
}
else {// the latdimname should be either the CV_FILLINDEX or CV_EXIST.
if(CV_LAT_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_LAT_MISS");
else if(CV_LON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_LON_MISS");
else if(CV_NONLATLON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_NONLATLON_MISS");
else if(CV_MODIFY == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_MODIFY");
else if(CV_SPECIAL == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_SPECIAL");
else
throw3("For the 2-D lat/lon case, the latitude dimension name ",latdim0, "is a coordinate variable of type CV_UNSUPPORTED");
}
}
else
++i;
}
// Add the 2-D latitude(latname) to the CV list.
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = latdim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
}
}
}
// Update longitude.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->rank == 2) {
// Find 2-D longitude
if((*irv)->name == lonname) {
// Obtain the second dimension of this variable
string londim0 = (*irv)->getDimensions()[1]->name;
// Remove the CV corresponding to londim0
for (vector<GMCVar *>:: iterator i= this->cvars.begin(); i!=this->cvars.end(); ) {
// NEED more work!!! should also remove ntime from the GMCVar list but add it to the cvar list.Same for Lon.
if((*i)->cfdimname == londim0) {
if(CV_FILLINDEX == (*i)->cvartype) {
delete(*i);
i= this->cvars.erase(i);
}
else if(CV_EXIST == (*i)->cvartype) {
// Add this var. to the var list.
Var *var = new Var((*i));
this->vars.push_back(var);
// Remove this var. from the GMCVar list.
delete(*i);
i = this->cvars.erase(i);
}
else {// the latdimname should be either the CV_FILLINDEX or CV_EXIST.
if(CV_LAT_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_LAT_MISS");
else if(CV_LON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_LON_MISS");
else if(CV_NONLATLON_MISS == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_NONLATLON_MISS");
else if(CV_MODIFY == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_MODIFY");
else if(CV_SPECIAL == (*i)->cvartype)
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_SPECIAL");
else
throw3("For the 2-D lat/lon case, the longitude dimension name ",londim0, "is a coordinate variable of type CV_UNSUPPORTED");
}
}
else
++i;
}
// Add the 2-D longitude(lonname) to the CV list.
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = londim0;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
}
}
}
}
#endif
// Handle coordinate variables for general HDF5 products that have 1-D lat/lon
void GMFile::Handle_CVar_LatLon1D_General_Product() throw(Exception) {
this->iscoard = true;
Handle_CVar_LatLon_General_Product();
}
// Handle coordinate variables for general HDF5 products that have 2-D lat/lon
void GMFile::Handle_CVar_LatLon2D_General_Product() throw(Exception) {
Handle_CVar_LatLon_General_Product();
}
// Routine used by other routines to handle coordinate variables for general HDF5 product
// that have either 1-D or 2-D lat/lon
void GMFile::Handle_CVar_LatLon_General_Product() throw(Exception) {
if((GENERAL_LATLON2D != this->gproduct_pattern)
&& GENERAL_LATLON1D != this->gproduct_pattern)
throw1("This function only supports latlon 1D or latlon 2D general products");
pair<set<string>::iterator,bool> setret;
set<string>tempdimnamelist = dimnamelist;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// This is the dimension scale dataset; it should be changed to a coordinate variable.
if (gp_latname== (*irv)->name) {
// For latitude, regardless 1D or 2D, the first dimension needs to be updated.
// Create Coordinate variables.
tempdimnamelist.erase(((*irv)->dims[0])->name);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = ((*irv)->dims[0])->name;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
} // if ((*irs)== (*irv)->fullpath)
} // for (vector<Var *>::iterator irv = this->vars.begin();
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// This is the dimension scale dataset; it should be changed to a coordinate variable.
if (gp_lonname== (*irv)->name) {
// For 2-D lat/lon, the londimname should be the second dimension of the longitude
// For 1-D lat/lon, the londimname should be the first dimension of the longitude
// Create Coordinate variables.
string londimname;
if(GENERAL_LATLON2D == this->gproduct_pattern)
londimname = ((*irv)->dims[1])->name;
else
londimname = ((*irv)->dims[0])->name;
tempdimnamelist.erase(londimname);
GMCVar* GMcvar = new GMCVar(*irv);
GMcvar->cfdimname = londimname;
GMcvar->cvartype = CV_EXIST;
GMcvar->product_type = product_type;
this->cvars.push_back(GMcvar);
delete(*irv);
this->vars.erase(irv);
break;
} // if ((*irs)== (*irv)->fullpath)
} // for (vector<Var *>::iterator irv = this->vars.begin();
//
// Add other missing coordinate variables.
for (set<string>::iterator irs = tempdimnamelist.begin();
irs != tempdimnamelist.end();irs++) {
GMCVar*GMcvar = new GMCVar();
Create_Missing_CV(GMcvar,*irs);
this->cvars.push_back(GMcvar);
}
}
// Handle coordinate variables for OBPG level 3
void GMFile::Handle_CVar_OBPG_L3() throw(Exception) {
if (GENERAL_DIMSCALE == this->gproduct_pattern)
Handle_CVar_Dimscale_General_Product();
// Change the CV Type of the corresponding CVs of lat and lon from CV_FILLINDEX to CV_LATMISS or CV_LONMISS
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// Here I try to avoid using the dimension name row and column to find the lat/lon dimension size.
// So I am looking for a 2-D floating-point array or a 2-D array under the group geophsical_data.
// This may be subject to change if OBPG level 3 change its arrangement of variables.
// KY 2014-09-29
if((*irv)->rank == 2) {
if(((*irv)->fullpath.find("/geophsical_data") == 0) || ((*irv)->dtype == H5FLOAT32)) {
size_t lat_size = (*irv)->getDimensions()[0]->size;
string lat_name = (*irv)->getDimensions()[0]->name;
size_t lon_size = (*irv)->getDimensions()[1]->size;
string lon_name = (*irv)->getDimensions()[1]->name;
size_t temp_size = 0;
string temp_name;
H5DataType ll_dtype = (*irv)->dtype;
//cerr<<"lat_name is "<<lat_name <<endl;
//cerr<<"lon_name is "<<lon_name <<endl;
// We always assume that longitude size is greater than latitude size.
if(lat_size >lon_size) {
temp_size = lon_size;
temp_name = lon_name;
lon_size = lat_size;
lon_name = lat_name;
lat_size = temp_size;
lat_name = temp_name;
}
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->cvartype == CV_FILLINDEX) {
if((*ircv)->getDimensions()[0]->size == lat_size &&
(*ircv)->getDimensions()[0]->name == lat_name) {
(*ircv)->cvartype = CV_LAT_MISS;
(*ircv)->dtype = ll_dtype;
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ++ira) {
if ((*ira)->name == "NAME") {
delete (*ira);
(*ircv)->attrs.erase(ira);
break;
}
}
}
else if((*ircv)->getDimensions()[0]->size == lon_size &&
(*ircv)->getDimensions()[0]->name == lon_name) {
(*ircv)->cvartype = CV_LON_MISS;
(*ircv)->dtype = ll_dtype;
for (vector<Attribute *>::iterator ira = (*ircv)->attrs.begin();
ira != (*ircv)->attrs.end(); ++ira) {
if ((*ira)->name == "NAME") {
delete (*ira);
(*ircv)->attrs.erase(ira);
break;
}
}
}
}
}
break;
} // if(((*irv)->fullpath.find("/geophsical_data") == 0) || ((*irv)->dtype == H5FLOAT32))
} // if((*irv)->rank == 2)
} // for (vector<Var *>::iterator irv = this->vars.begin();
}
// Handle some special variables. Currently only GPM and ACOS have these variables.
void GMFile::Handle_SpVar() throw(Exception){
if (ACOS_L2S_OR_OCO2_L1B == product_type)
Handle_SpVar_ACOS_OCO2();
else if(GPM_L1 == product_type) {
// Loop through the variable list to build the coordinates.
// These variables need to be removed.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if((*irv)->name=="AlgorithmRuntimeInfo") {
delete(*irv);
this->vars.erase(irv);
break;
}
}
}
// GPM level-3 These variables need to be removed.
else if(GPMM_L3 == product_type || GPMS_L3 == product_type) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if((*irv)->name=="InputFileNames") {
delete(*irv);
irv = this->vars.erase(irv);
}
else if((*irv)->name=="InputAlgorithmVersions") {
delete(*irv);
irv = this->vars.erase(irv);
}
else if((*irv)->name=="InputGenerationDateTimes") {
delete(*irv);
irv = this->vars.erase(irv);
}
else {
++irv;
}
}
}
}
// Handle special variables for ACOS.
void GMFile::Handle_SpVar_ACOS_OCO2() throw(Exception) {
//The ACOS or OCO2 have 64-bit variables. DAP2 doesn't support 64-bit variables.
// So we will not handle attributes yet.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ) {
if (H5INT64 == (*irv)->getType()) {
// First: Time Part of soundingid
GMSPVar * spvar = new GMSPVar(*irv);
spvar->name = (*irv)->name +"_Time";
spvar->newname = (*irv)->newname+"_Time";
spvar->dtype = H5INT32;
spvar->otype = (*irv)->getType();
spvar->sdbit = 1;
// 2 digit hour, 2 digit min, 2 digit seconds
spvar->numofdbits = 6;
this->spvars.push_back(spvar);
// Second: Date Part of soundingid
GMSPVar * spvar2 = new GMSPVar(*irv);
spvar2->name = (*irv)->name +"_Date";
spvar2->newname = (*irv)->newname+"_Date";
spvar2->dtype = H5INT32;
spvar2->otype = (*irv)->getType();
spvar2->sdbit = 7;
// 4 digit year, 2 digit month, 2 digit day
spvar2->numofdbits = 8;
this->spvars.push_back(spvar2);
delete(*irv);
irv = this->vars.erase(irv);
} // if (H5INT64 == (*irv)->getType())
else {
++irv;
}
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
// Adjust Object names, For some products, NASA data centers don't need
// the fullpath of objects.
void GMFile::Adjust_Obj_Name() throw(Exception) {
if(Mea_Ozone == product_type)
Adjust_Mea_Ozone_Obj_Name();
if(GPMS_L3 == product_type || GPMM_L3 == product_type)
Adjust_GPM_L3_Obj_Name();
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Adjust_Obj_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
// Adjust object names for GPM level 3 products
void GMFile:: Adjust_GPM_L3_Obj_Name() throw(Exception) {
//cerr<<"number of group is "<<this->groups.size() <<endl;
string objnewname;
// In this definition, root group is not considered as a group.
if(this->groups.size() <= 1) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
objnewname = HDF5CFUtil::obtain_string_after_lastslash((*irv)->newname);
if (objnewname !="")
(*irv)->newname = objnewname;
}
}
else {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
//cerr<<"(*irv)->newname is "<<(*irv)->newname <<endl;
size_t grid_group_path_pos = ((*irv)->newname.substr(1)).find_first_of("/");
objnewname = ((*irv)->newname).substr(grid_group_path_pos+2);
(*irv)->newname = objnewname;
}
}
}
// Adjust object names for MeaSUREs OZone
void GMFile:: Adjust_Mea_Ozone_Obj_Name() throw(Exception) {
string objnewname;
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
objnewname = HDF5CFUtil::obtain_string_after_lastslash((*irv)->newname);
if (objnewname !="")
(*irv)->newname = objnewname;
#if 0
//Just for debugging
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
cerr<<"Ozone dim. name "<<(*ird)->name <<endl;
cerr<<"Ozone dim. new name "<<(*ird)->newname <<endl;
}
#endif
}
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
objnewname = HDF5CFUtil::obtain_string_after_lastslash((*irv)->newname);
if (objnewname !="")
(*irv)->newname = objnewname;
#if 0
//Just for debugging
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
cerr<<"Ozone CV dim. name "<<(*ird)->name <<endl;
cerr<<"Ozone CV dim. new name "<<(*ird)->newname <<endl;
}
#endif
}
}
// Flatten object names.
void GMFile::Flatten_Obj_Name(bool include_attr) throw(Exception){
File::Flatten_Obj_Name(include_attr);
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
(*irv)->newname = get_CF_string((*irv)->newname);
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
(*ird)->newname = get_CF_string((*ird)->newname);
}
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira)
(*ira)->newname = File::get_CF_string((*ira)->newname);
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
(*irv)->newname = get_CF_string((*irv)->newname);
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird)
(*ird)->newname = get_CF_string((*ird)->newname);
if (true == include_attr) {
for (vector<Attribute *>::iterator ira = (*irv)->attrs.begin();
ira != (*irv)->attrs.end(); ++ira)
(*ira)->newname = File::get_CF_string((*ira)->newname);
}
}
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Flatten_Obj_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
// Rarely object name clashings may occur. This routine makes sure
// all object names are unique.
void GMFile::Handle_Obj_NameClashing(bool include_attr) throw(Exception) {
// objnameset will be filled with all object names that we are going to check the name clashing.
// For example, we want to see if there are any name clashings for all variable names in this file.
// objnameset will include all variable names. If a name clashing occurs, we can figure out from the set operation immediately.
set<string>objnameset;
Handle_GMCVar_NameClashing(objnameset);
Handle_GMSPVar_NameClashing(objnameset);
File::Handle_GeneralObj_NameClashing(include_attr,objnameset);
if (true == include_attr) {
Handle_GMCVar_AttrNameClashing();
Handle_GMSPVar_AttrNameClashing();
}
// Moving to h5gmcfdap.cc, right after Adjust_Dim_Name
//Handle_DimNameClashing();
}
void GMFile::Handle_GMCVar_NameClashing(set<string> &objnameset ) throw(Exception) {
GMHandle_General_NameClashing(objnameset,this->cvars);
}
void GMFile::Handle_GMSPVar_NameClashing(set<string> &objnameset ) throw(Exception) {
GMHandle_General_NameClashing(objnameset,this->spvars);
}
// This routine handles attribute name clashings.
void GMFile::Handle_GMCVar_AttrNameClashing() throw(Exception) {
set<string> objnameset;
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
Handle_General_NameClashing(objnameset,(*irv)->attrs);
objnameset.clear();
}
}
void GMFile::Handle_GMSPVar_AttrNameClashing() throw(Exception) {
set<string> objnameset;
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
Handle_General_NameClashing(objnameset,(*irv)->attrs);
objnameset.clear();
}
}
//class T must have member string newname
// The subroutine to handle name clashings,
// it builds up a map from original object names to clashing-free object names.
template<class T> void
GMFile::GMHandle_General_NameClashing(set <string>&objnameset, vector<T*>& objvec) throw(Exception){
pair<set<string>::iterator,bool> setret;
set<string>::iterator iss;
vector<string> clashnamelist;
vector<string>::iterator ivs;
map<int,int> cl_to_ol;
int ol_index = 0;
int cl_index = 0;
typename vector<T*>::iterator irv;
//for (vector<T*>::iterator irv = objvec.begin();
for (irv = objvec.begin();
irv != objvec.end(); ++irv) {
setret = objnameset.insert((*irv)->newname);
if (false == setret.second ) {
clashnamelist.insert(clashnamelist.end(),(*irv)->newname);
cl_to_ol[cl_index] = ol_index;
cl_index++;
}
ol_index++;
}
// Now change the clashed elements to unique elements;
// Generate the set which has the same size as the original vector.
for (ivs=clashnamelist.begin(); ivs!=clashnamelist.end(); ++ivs) {
int clash_index = 1;
string temp_clashname = *ivs +'_';
HDF5CFUtil::gen_unique_name(temp_clashname,objnameset,clash_index);
*ivs = temp_clashname;
}
// Now go back to the original vector, make it unique.
for (unsigned int i =0; i <clashnamelist.size(); i++)
objvec[cl_to_ol[i]]->newname = clashnamelist[i];
}
// Handle dimension name clashings
void GMFile::Handle_DimNameClashing() throw(Exception){
//cerr<<"coming to DimNameClashing "<<endl;
// ACOS L2S or OCO2 L1B products doesn't need the dimension name clashing check based on our current understanding. KY 2012-5-16
if (ACOS_L2S_OR_OCO2_L1B == product_type)
return;
map<string,string>dimname_to_dimnewname;
pair<map<string,string>::iterator,bool>mapret;
set<string> dimnameset;
vector<Dimension*>vdims;
set<string> dimnewnameset;
pair<set<string>::iterator,bool> setret;
// First: Generate the dimset/dimvar based on coordinate variables.
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv !=this->cvars.end(); ++irv) {
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
//setret = dimnameset.insert((*ird)->newname);
setret = dimnameset.insert((*ird)->name);
if (true == setret.second)
vdims.push_back(*ird);
}
}
// For some cases, dimension names are provided but there are no corresponding coordinate
// variables. For now, we will assume no such cases.
// Actually, we find such a case in our fake testsuite. So we need to fix it.
for(vector<Var *>::iterator irv= this->vars.begin();
irv != this->vars.end();++irv) {
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
//setret = dimnameset.insert((*ird)->newname);
setret = dimnameset.insert((*ird)->name);
if (setret.second) vdims.push_back(*ird);
}
}
GMHandle_General_NameClashing(dimnewnameset,vdims);
// Third: Make dimname_to_dimnewname map
for (vector<Dimension*>::iterator ird = vdims.begin();ird!=vdims.end();++ird) {
mapret = dimname_to_dimnewname.insert(pair<string,string>((*ird)->name,(*ird)->newname));
if (false == mapret.second)
throw4("The dimension name ",(*ird)->name," should map to ",
(*ird)->newname);
}
// Fourth: Change the original dimension new names to the unique dimension new names
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv !=this->cvars.end(); ++irv)
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end();++ird)
(*ird)->newname = dimname_to_dimnewname[(*ird)->name];
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv)
for (vector <Dimension *>:: iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird)
(*ird)->newname = dimname_to_dimnewname[(*ird)->name];
}
// For COARDS, dim. names need to be the same as obj. names.
void GMFile::Adjust_Dim_Name() throw(Exception){
#if 0
// Just for debugging
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension new name "<<(*ird)->newname <<endl;
}
}
#endif
// Only need for COARD conventions.
if( true == iscoard) {
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv !=this->cvars.end(); ++irv) {
#if 0
cerr<<"1D Cvariable name is "<<(*irv)->name <<endl;
cerr<<"1D Cvariable new name is "<<(*irv)->newname <<endl;
cerr<<"1D Cvariable dim name is "<<((*irv)->dims)[0]->name <<endl;
cerr<<"1D Cvariable dim new name is "<<((*irv)->dims)[0]->newname <<endl;
#endif
if ((*irv)->dims.size()!=1)
throw3("Coard coordinate variable ",(*irv)->name, "is not 1D");
if ((*irv)->newname != (((*irv)->dims)[0]->newname)) {
((*irv)->dims)[0]->newname = (*irv)->newname;
// For all variables that have this dimension,the dimension newname should also change.
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); ++irv2) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ++ird) {
// This is the key, the dimension name of this dimension
// should be equal to the dimension name of the coordinate variable.
// Then the dimension name matches and the dimension name should be changed to
// the new dimension name.
if ((*ird)->name == ((*irv)->dims)[0]->name)
(*ird)->newname = ((*irv)->dims)[0]->newname;
}
}
} // if ((*irv)->newname != (((*irv)->dims)[0]->newname))
}// for (vector<GMCVar *>::iterator irv = this->cvars.begin(); ...
} // if( true == iscoard)
// Just for debugging
#if 0
for (vector<Var*>::iterator irv2 = this->vars.begin();
irv2 != this->vars.end(); irv2++) {
for (vector<Dimension *>::iterator ird = (*irv2)->dims.begin();
ird !=(*irv2)->dims.end(); ird++) {
cerr<<"Dimension name afet Adjust_Dim_Name "<<(*ird)->newname <<endl;
}
}
#endif
}
// Add supplemental CF attributes for some products.
void
GMFile:: Add_Supplement_Attrs(bool add_path) throw(Exception) {
if (General_Product == product_type || true == add_path) {
File::Add_Supplement_Attrs(add_path);
// Adding variable original name(origname) and full path(fullpath)
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
if (((*irv)->cvartype == CV_EXIST) || ((*irv)->cvartype == CV_MODIFY)) {
Attribute * attr = new Attribute();
const string varname = (*irv)->name;
const string attrname = "origname";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
}
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
if (((*irv)->cvartype == CV_EXIST) || ((*irv)->cvartype == CV_MODIFY)) {
Attribute * attr = new Attribute();
const string varname = (*irv)->fullpath;
const string attrname = "fullnamepath";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
Attribute * attr = new Attribute();
const string varname = (*irv)->name;
const string attrname = "origname";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
for (vector<GMSPVar *>::iterator irv = this->spvars.begin();
irv != this->spvars.end(); ++irv) {
Attribute * attr = new Attribute();
const string varname = (*irv)->fullpath;
const string attrname = "fullnamepath";
Add_Str_Attr(attr,attrname,varname);
(*irv)->attrs.push_back(attr);
}
} // if (General_Product == product_type || true == add_path)
if(GPM_L1 == product_type || GPMS_L3 == product_type || GPMM_L3 == product_type)
Add_GPM_Attrs();
else if (Aqu_L3 == product_type)
Add_Aqu_Attrs();
else if (Mea_SeaWiFS_L2 == product_type || Mea_SeaWiFS_L3 == product_type)
Add_SeaWiFS_Attrs();
}
// Add CF attributes for GPM products
void
GMFile:: Add_GPM_Attrs() throw(Exception) {
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
const string attr_name_be_replaced = "CodeMissingValue";
const string attr_new_name = "_FillValue";
const string attr_cor_fill_value = "-9999.9";
const string attr2_name_be_replaced = "Units";
const string attr2_new_name ="units";
// Need to convert String type CodeMissingValue to the corresponding _FilLValue
// Create a function at HDF5CF.cc. use strtod,strtof,strtol etc. function to convert
// string to the corresponding type.
for (it_v = vars.begin(); it_v != vars.end(); ++it_v) {
for(ira = (*it_v)->attrs.begin(); ira!= (*it_v)->attrs.end();ira++) {
if((attr_name_be_replaced == (*ira)->name)) {
if((*ira)->dtype == H5FSTRING)
Change_Attr_One_Str_to_Others((*ira),(*it_v));
(*ira)->name = attr_new_name;
(*ira)->newname = attr_new_name;
}
}
}
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
for(ira = (*irv)->attrs.begin(); ira!= (*irv)->attrs.end();ira++) {
if(attr_name_be_replaced == (*ira)->name) {
if((*ira)->dtype == H5FSTRING)
Change_Attr_One_Str_to_Others((*ira),(*irv));
(*ira)->name = attr_new_name;
(*ira)->newname = attr_new_name;
break;
}
}
if(product_type == GPM_L1) {
if ((*irv)->cvartype == CV_EXIST) {
for(ira = (*irv)->attrs.begin(); ira!= (*irv)->attrs.end();ira++) {
if(attr2_name_be_replaced == (*ira)->name) {
if((*irv)->name.find("Latitude") !=string::npos) {
string unit_value = "degrees_north";
(*ira)->value.clear();
Add_Str_Attr(*ira,attr2_new_name,unit_value);
//(*ira)->value.resize(unit_value.size());
//copy(unit_value.begin(),unit_value.end(),(*ira)->value.begin());
}
else if((*irv)->name.find("Longitude") !=string::npos) {
string unit_value = "degrees_east";
(*ira)->value.clear();
Add_Str_Attr(*ira,attr2_new_name,unit_value);
//(*ira)->value.resize(unit_value.size());
//copy(unit_value.begin(),unit_value.end(),(*ira)->value.begin());
}
}
}
}
else if ((*irv)->cvartype == CV_NONLATLON_MISS) {
string comment;
const string attrname = "comment";
Attribute*attr = new Attribute();
{
if((*irv)->name == "nchannel1")
comment = "Number of Swath S1 channels (10V 10H 19V 19H 23V 37V 37H 89V 89H).";
else if((*irv)->name == "nchannel2")
comment = "Number of Swath S2 channels (166V 166H 183+/-3V 183+/-8V).";
else if((*irv)->name == "nchan1")
comment = "Number of channels in Swath 1.";
else if((*irv)->name == "nchan2")
comment = "Number of channels in Swath 2.";
else if((*irv)->name == "VH")
comment = "Number of polarizations.";
else if((*irv)->name == "GMIxyz")
comment = "x, y, z components in GMI instrument coordinate system.";
else if((*irv)->name == "LNL")
comment = "Linear and non-linear.";
else if((*irv)->name == "nscan")
comment = "Number of scans in the granule.";
else if((*irv)->name == "nscan1")
comment = "Typical number of Swath S1 scans in the granule.";
else if((*irv)->name == "nscan2")
comment = "Typical number of Swath S2 scans in the granule.";
else if((*irv)->name == "npixelev")
comment = "Number of earth view pixels in one scan.";
else if((*irv)->name == "npixelht")
comment = "Number of hot load pixels in one scan.";
else if((*irv)->name == "npixelcs")
comment = "Number of cold sky pixels in one scan.";
else if((*irv)->name == "npixelfr")
comment = "Number of full rotation earth view pixels in one scan.";
else if((*irv)->name == "nfreq1")
comment = "Number of frequencies in Swath 1.";
else if((*irv)->name == "nfreq2")
comment = "Number of frequencies in Swath 2.";
else if((*irv)->name == "npix1")
comment = "Number of pixels in Swath 1.";
else if((*irv)->name == "npix2")
comment = "Number of pixels in Swath 2.";
else if((*irv)->name == "npix3")
comment = "Number of pixels in Swath 3.";
else if((*irv)->name == "npix4")
comment = "Number of pixels in Swath 4.";
else if((*irv)->name == "ncolds1")
comment = "Maximum number of cold samples in Swath 1.";
else if((*irv)->name == "ncolds2")
comment = "Maximum number of cold samples in Swath 2.";
else if((*irv)->name == "nhots1")
comment = "Maximum number of hot samples in Swath 1.";
else if((*irv)->name == "nhots2")
comment = "Maximum number of hot samples in Swath 2.";
else if((*irv)->name == "ntherm")
comment = "Number of hot load thermisters.";
else if((*irv)->name == "ntach")
comment = "Number of tachometer readings.";
else if((*irv)->name == "nsamt"){
comment = "Number of sample types. ";
comment = +"The types are: total science GSDR, earthview,hot load, cold sky.";
}
else if((*irv)->name == "nndiode")
comment = "Number of noise diodes.";
else if((*irv)->name == "n7")
comment = "Number seven.";
else if((*irv)->name == "nray")
comment = "Number of angle bins in each NS scan.";
else if((*irv)->name == "nrayMS")
comment = "Number of angle bins in each MS scan.";
else if((*irv)->name == "nrayHS")
comment = "Number of angle bins in each HS scan.";
else if((*irv)->name == "nbin")
comment = "Number of range bins in each NS and MS ray. Bin interval is 125m.";
else if((*irv)->name == "nbinHS")
comment = "Number of range bins in each HS ray. Bin interval is 250m.";
else if((*irv)->name == "nbinSZP")
comment = "Number of range bins for sigmaZeroProfile.";
else if((*irv)->name == "nbinSZPHS")
comment = "Number of range bins for sigmaZeroProfile in each HS scan.";
else if((*irv)->name == "nNP")
comment = "Number of NP kinds.";
else if((*irv)->name == "nearFar")
comment = "Near reference, Far reference.";
else if((*irv)->name == "foreBack")
comment = "Forward, Backward.";
else if((*irv)->name == "method")
comment = "Number of SRT methods.";
else if((*irv)->name == "nNode")
comment = "Number of binNode.";
else if((*irv)->name == "nDSD")
comment = "Number of DSD parameters. Parameters are N0 and D0";
else if((*irv)->name == "LS")
comment = "Liquid, solid.";
}
if(""==comment)
delete attr;
else {
Add_Str_Attr(attr,attrname,comment);
(*irv)->attrs.push_back(attr);
}
}
}
if(product_type == GPMS_L3 || product_type == GPMM_L3) {
if ((*irv)->cvartype == CV_NONLATLON_MISS) {
string comment;
const string attrname = "comment";
Attribute*attr = new Attribute();
{
if((*irv)->name == "chn")
comment = "Number of channels:Ku,Ka,KaHS,DPR.";
else if((*irv)->name == "inst")
comment = "Number of instruments:Ku,Ka,KaHS.";
else if((*irv)->name == "tim")
comment = "Number of hours(local time).";
else if((*irv)->name == "ang"){
comment = "Number of angles.The meaning of ang is different for each channel.";
comment +=
"For Ku channel all indices are used with the meaning 0,1,2,..6 =angle bins 24,";
comment +=
"(20,28),(16,32),(12,36),(8,40),(3,44),and (0,48).";
comment +=
"For Ka channel 4 indices are used with the meaning 0,1,2,3 = angle bins 12,(8,16),";
comment +=
"(4,20),and (0,24). For KaHS channel 4 indices are used with the meaning 0,1,2,3 =";
comment += "angle bins(11,2),(7,16),(3,20),and (0.23).";
}
else if((*irv)->name == "rt")
comment = "Number of rain types: stratiform, convective,all.";
else if((*irv)->name == "st")
comment = "Number of surface types:ocean,land,all.";
else if((*irv)->name == "bin"){
comment = "Number of bins in histogram. The thresholds are different for different";
comment +=" variables. see the file specification for this algorithm.";
}
else if((*irv)->name == "nvar") {
comment = "Number of phase bins. Bins are counts of phase less than 100, ";
comment +="counts of phase greater than or equal to 100 and less than 200, ";
comment +="counts of phase greater than or equal to 200.";
}
else if((*irv)->name == "AD")
comment = "Ascending or descending half of the orbit.";
}
if(""==comment)
delete attr;
else {
Add_Str_Attr(attr,attrname,comment);
(*irv)->attrs.push_back(attr);
}
}
}
if ((*irv)->cvartype == CV_SPECIAL) {
if((*irv)->name == "nlayer" || (*irv)->name == "hgt"
|| (*irv)->name == "nalt") {
Attribute*attr = new Attribute();
string unit_value = "km";
Add_Str_Attr(attr,attr2_new_name,unit_value);
(*irv)->attrs.push_back(attr);
Attribute*attr1 = new Attribute();
string attr1_axis="axis";
string attr1_value = "Z";
Add_Str_Attr(attr1,attr1_axis,attr1_value);
(*irv)->attrs.push_back(attr1);
Attribute*attr2 = new Attribute();
string attr2_positive="positive";
string attr2_value = "up";
Add_Str_Attr(attr2,attr2_positive,attr2_value);
(*irv)->attrs.push_back(attr2);
}
if((*irv)->name == "hgt" || (*irv)->name == "nalt"){
Attribute*attr1 = new Attribute();
string comment ="Number of heights above the earth ellipsoid";
Add_Str_Attr(attr1,"comment",comment);
(*irv)->attrs.push_back(attr1);
}
}
}
// Old code, leave it for the time being
#if 0
const string fill_value_attr_name = "_FillValue";
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
bool has_fillvalue = false;
for(ira = (*it_v)->attrs.begin(); ira!= (*it_v)->attrs.end();ira++) {
if (fill_value_attr_name == (*ira)->name){
has_fillvalue = true;
break;
}
}
// Add the fill value
if (has_fillvalue != true ) {
if(H5FLOAT32 == (*it_v)->dtype) {
Attribute* attr = new Attribute();
float _FillValue = -9999.9;
Add_One_Float_Attr(attr,fill_value_attr_name,_FillValue);
(*it_v)->attrs.push_back(attr);
}
}
}// for (it_v = vars.begin(); ...
#endif
}
// Add attributes for Aquarius products
void
GMFile:: Add_Aqu_Attrs() throw(Exception) {
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
const string orig_longname_attr_name = "Parameter";
const string longname_attr_name ="long_name";
string longname_value;
const string orig_units_attr_name = "Units";
const string units_attr_name = "units";
string units_value;
// const string orig_valid_min_attr_name = "Data Minimum";
const string orig_valid_min_attr_name = "Data Minimum";
const string valid_min_attr_name = "valid_min";
float valid_min_value;
const string orig_valid_max_attr_name = "Data Maximum";
const string valid_max_attr_name = "valid_max";
float valid_max_value;
// The fill value is -32767.0. However, No _FillValue attribute is added.
// So add it here. KY 2012-2-16
const string fill_value_attr_name = "_FillValue";
float _FillValue = -32767.0;
for (ira = this->root_attrs.begin(); ira != this->root_attrs.end(); ++ira) {
if (orig_longname_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
longname_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),longname_value.begin());
}
else if (orig_units_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
units_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),units_value.begin());
}
else if (orig_valid_min_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
memcpy(&valid_min_value,(void*)(&((*ira)->value[0])),(*ira)->value.size());
}
else if (orig_valid_max_attr_name == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,"/");
memcpy(&valid_max_value,(void*)(&((*ira)->value[0])),(*ira)->value.size());
}
}// for (ira = this->root_attrs.begin(); ira != this->root_attrs.end(); ++ira)
// New version Aqu(Q20112132011243.L3m_MO_SCI_V3.0_SSS_1deg.bz2) files seem to have CF attributes added.
// In this case, we should not add extra CF attributes, or duplicate values may appear. KY 2015-06-20
bool has_long_name = false;
bool has_units = false;
bool has_valid_min = false;
bool has_valid_max = false;
bool has_fillvalue = false;
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
if ("l3m_data" == (*it_v)->name) {
for (ira = (*it_v)->attrs.begin(); ira != (*it_v)->attrs.end(); ++ira) {
if (longname_attr_name == (*ira)->name)
has_long_name = true;
else if(units_attr_name == (*ira)->name)
has_units = true;
else if(valid_min_attr_name == (*ira)->name)
has_valid_min = true;
else if(valid_max_attr_name == (*ira)->name)
has_valid_max = true;
else if(fill_value_attr_name == (*ira)->name)
has_fillvalue = true;
}
break;
}
} // for (it_v = vars.begin(); ...
// Level 3 variable name is l3m_data
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
if ("l3m_data" == (*it_v)->name) {
Attribute *attr = NULL;
// 1. Add the long_name attribute if no
if(false == has_long_name) {
attr = new Attribute();
Add_Str_Attr(attr,longname_attr_name,longname_value);
(*it_v)->attrs.push_back(attr);
}
// 2. Add the units attribute
if(false == has_units) {
attr = new Attribute();
Add_Str_Attr(attr,units_attr_name,units_value);
(*it_v)->attrs.push_back(attr);
}
// 3. Add the valid_min attribute
if(false == has_valid_min) {
attr = new Attribute();
Add_One_Float_Attr(attr,valid_min_attr_name,valid_min_value);
(*it_v)->attrs.push_back(attr);
}
// 4. Add the valid_max attribute
if(false == has_valid_max) {
attr = new Attribute();
Add_One_Float_Attr(attr,valid_max_attr_name,valid_max_value);
(*it_v)->attrs.push_back(attr);
}
// 5. Add the _FillValue attribute
if(false == has_fillvalue) {
attr = new Attribute();
Add_One_Float_Attr(attr,fill_value_attr_name,_FillValue);
(*it_v)->attrs.push_back(attr);
}
break;
}
} // for (it_v = vars.begin(); ...
}
// Add SeaWiFS attributes
void
GMFile:: Add_SeaWiFS_Attrs() throw(Exception) {
// The fill value is -999.0. However, No _FillValue attribute is added.
// So add it here. KY 2012-2-16
const string fill_value_attr_name = "_FillValue";
float _FillValue = -999.0;
const string valid_range_attr_name = "valid_range";
vector<HDF5CF::Var *>::const_iterator it_v;
vector<HDF5CF::Attribute *>::const_iterator ira;
for (it_v = vars.begin();
it_v != vars.end(); ++it_v) {
if (H5FLOAT32 == (*it_v)->dtype) {
bool has_fillvalue = false;
bool has_validrange = false;
for(ira = (*it_v)->attrs.begin(); ira!= (*it_v)->attrs.end();ira++) {
if (fill_value_attr_name == (*ira)->name){
has_fillvalue = true;
break;
}
else if(valid_range_attr_name == (*ira)->name) {
has_validrange = true;
break;
}
}
// Add the fill value
if (has_fillvalue != true && has_validrange != true ) {
Attribute* attr = new Attribute();
Add_One_Float_Attr(attr,fill_value_attr_name,_FillValue);
(*it_v)->attrs.push_back(attr);
}
}// if (H5FLOAT32 == (*it_v)->dtype)
}// for (it_v = vars.begin(); ...
}
#if 0
// Handle the "coordinates" and "units" attributes of coordinate variables.
void GMFile:: Handle_Coor_Attr() {
string co_attrname = "coordinates";
string co_attrvalue="";
string unit_attrname = "units";
string nonll_unit_attrvalue ="level";
string lat_unit_attrvalue ="degrees_north";
string lon_unit_attrvalue ="degrees_east";
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
//cerr<<"CV name is "<<(*ircv)->name << " cv type is "<<(*ircv)->cvartype <<endl;
if ((*ircv)->cvartype == CV_NONLATLON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,nonll_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
else if ((*ircv)->cvartype == CV_LAT_MISS) {
//cerr<<"Should add new attribute "<<endl;
Attribute * attr = new Attribute();
// float temp = -999.9;
// Add_One_Float_Attr(attr,unit_attrname,temp);
Add_Str_Attr(attr,unit_attrname,lat_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
//cerr<<"After adding new attribute "<<endl;
}
else if ((*ircv)->cvartype == CV_LON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,lon_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin(); ...
// No need to handle MeaSUREs SeaWiFS level 2 products
if(product_type == Mea_SeaWiFS_L2)
return;
// GPM level 1 needs to be handled separately
else if(product_type == GPM_L1) {
Handle_GPM_l1_Coor_Attr();
return;
}
// No need to handle products that follow COARDS.
else if (true == iscoard) {
// May need to check coordinates for 2-D lat/lon but cannot treat those lat/lon as CV case. KY 2015-12-10-TEMPPP
return;
}
// Now handle the 2-D lat/lon case(note: this only applies to the one that dim. scale doesn't apply)
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2) {
// The following code makes sure that the replacement only happens with the general 2-D lat/lon case.
if(gp_latname == (*ircv)->name)
Replace_Var_Str_Attr((*ircv),unit_attrname,lat_unit_attrvalue);
else if(gp_lonname ==(*ircv)->name)
Replace_Var_Str_Attr((*ircv),unit_attrname,lon_unit_attrvalue);
}
}
// Check the dimension names of 2-D lat/lon CVs
string ll2d_dimname0,ll2d_dimname1;
bool has_ll2d_coords = false;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2) {
// Note: we should still use the original dim. name to match the general variables.
ll2d_dimname0 = (*ircv)->getDimensions()[0]->name;
ll2d_dimname1 = (*ircv)->getDimensions()[1]->name;
if(ll2d_dimname0 !="" && ll2d_dimname1 !="")
has_ll2d_coords = true;
break;
}
}
if(true == has_ll2d_coords) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool coor_attr_keep_exist = false;
// May need to delete only the "coordinates" with both 2-D lat/lon dim. KY 2015-12-07
if(((*irv)->rank >=2)) {
short ll2dim_flag = 0;
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ ird) {
if((*ird)->name == ll2d_dimname0)
ll2dim_flag++;
else if((*ird)->name == ll2d_dimname1)
ll2dim_flag++;
}
if(ll2dim_flag != 2)
coor_attr_keep_exist = true;
// Remove the following code later since the released SMAP products are different. KY 2015-12-08
if(product_type == SMAP)
coor_attr_keep_exist = true;
if (false == coor_attr_keep_exist) {
for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin();
ira !=(*irv)->attrs.end();) {
if ((*ira)->newname == co_attrname) {
delete (*ira);
ira = (*irv)->attrs.erase(ira);
}
else {
++ira;
}
}// for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin(); ...
// Generate the "coordinates" attribute only for variables that have both 2-D lat/lon dim. names.
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ ird) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if ((*ird)->name == (*ircv)->cfdimname)
co_attrvalue = (co_attrvalue.empty())
?(*ircv)->newname:co_attrvalue + " "+(*ircv)->newname;
}
}
if (false == co_attrvalue.empty()) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,co_attrname,co_attrvalue);
(*irv)->attrs.push_back(attr);
}
co_attrvalue.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
}
}
}
#endif
// Handle the "coordinates" and "units" attributes of coordinate variables.
void GMFile:: Handle_Coor_Attr() {
string co_attrname = "coordinates";
string co_attrvalue="";
string unit_attrname = "units";
string nonll_unit_attrvalue ="level";
string lat_unit_attrvalue ="degrees_north";
string lon_unit_attrvalue ="degrees_east";
//cerr<<"coming to handle 2-D lat/lon CVs first ."<<endl;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
//cerr<<"CV name is "<<(*ircv)->name << " cv type is "<<(*ircv)->cvartype <<endl;
if ((*ircv)->cvartype == CV_NONLATLON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,nonll_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
else if ((*ircv)->cvartype == CV_LAT_MISS) {
//cerr<<"Should add new attribute "<<endl;
Attribute * attr = new Attribute();
// float temp = -999.9;
// Add_One_Float_Attr(attr,unit_attrname,temp);
Add_Str_Attr(attr,unit_attrname,lat_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
//cerr<<"After adding new attribute "<<endl;
}
else if ((*ircv)->cvartype == CV_LON_MISS) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,unit_attrname,lon_unit_attrvalue);
(*ircv)->attrs.push_back(attr);
}
} // for (vector<GMCVar *>::iterator ircv = this->cvars.begin(); ...
// No need to handle MeaSUREs SeaWiFS level 2 products
if(product_type == Mea_SeaWiFS_L2)
return;
// GPM level 1 needs to be handled separately
else if(product_type == GPM_L1) {
Handle_GPM_l1_Coor_Attr();
return;
}
// Handle Lat/Lon with "coordinates" attribute.
else if(product_type == General_Product && gproduct_pattern == GENERAL_LATLON_COOR_ATTR){
Handle_LatLon_With_CoordinateAttr_Coor_Attr();
return;
}
// No need to handle products that follow COARDS.
else if (true == iscoard) {
// If we find that there are groups that should check the coordinates attribute of the variable.
// We should flatten the path inside the coordinates..
if(grp_cv_paths.size() >0) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
if(grp_cv_paths.find(HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath)) != grp_cv_paths.end()){
// Check the "coordinates" attribute and flatten the values.
Flatten_VarPath_In_Coordinates_Attr(*irv);
}
}
}
return;
}
// Now handle the 2-D lat/lon case
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2 && (*ircv)->cvartype == CV_EXIST) {
//Note: When the 2nd parameter is true in the function Is_geolatlon, it checks the lat/latitude/Latitude
// When the 2nd parameter is false in the function Is_geolatlon, it checks the lon/longitude/Longitude
// The following code makes sure that the replacement only happens with the general 2-D lat/lon case.
if(gp_latname == (*ircv)->name) {
// Only if gp_latname is not lat/latitude/Latitude, change the units
if(false == Is_geolatlon(gp_latname,true))
Replace_Var_Str_Attr((*ircv),unit_attrname,lat_unit_attrvalue);
}
else if(gp_lonname ==(*ircv)->name) {
// Only if gp_lonname is not lon/longitude/Longitude, change the units
if(false == Is_geolatlon(gp_lonname,false))
Replace_Var_Str_Attr((*ircv),unit_attrname,lon_unit_attrvalue);
}
// We meet several products that miss the 2-D latitude and longitude CF units although they
// have the CV names like latitude/longitude, we should double check this case,
// add add the correct CF units if possible. We will watch if this is the right way.
else if(true == Is_geolatlon((*ircv)->name,true))
Replace_Var_Str_Attr((*ircv),unit_attrname,lat_unit_attrvalue);
else if(true == Is_geolatlon((*ircv)->name,false))
Replace_Var_Str_Attr((*ircv),unit_attrname,lon_unit_attrvalue);
}
}
// If we find that there are groups that should check the coordinates attribute of the variable.
// We should flatten the path inside the coordinates. Note this is for 2D-latlon CV case.
if(grp_cv_paths.size() >0) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
//cerr<<"the group of this variable is "<< HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath);
if(grp_cv_paths.find(HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath)) != grp_cv_paths.end()){
// Check the "coordinates" attribute and flatten the values.
Flatten_VarPath_In_Coordinates_Attr(*irv);
}
}
}
// Check if having 2-D lat/lon CVs
bool has_ll2d_coords = false;
// Since iscoard is false up to this point, So the netCDF-4 like 2-D lat/lon case must fulfill if the program comes here.
if(General_Product == this->product_type && GENERAL_DIMSCALE == this->gproduct_pattern)
has_ll2d_coords = true;
else {// For other cases.
string ll2d_dimname0,ll2d_dimname1;
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if((*ircv)->rank == 2) {
// Note: we should still use the original dim. name to match the general variables.
ll2d_dimname0 = (*ircv)->getDimensions()[0]->name;
ll2d_dimname1 = (*ircv)->getDimensions()[1]->name;
if(ll2d_dimname0 !="" && ll2d_dimname1 !="")
has_ll2d_coords = true;
break;
}
}
}
if(true == has_ll2d_coords) {
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
bool coor_attr_keep_exist = false;
if(((*irv)->rank >=2)) {
// Check if this var is under group_cv_paths, no, then check if this var's dims are the same as the dims of 2-D CVars
if(grp_cv_paths.find(HDF5CFUtil::obtain_string_before_lastslash((*irv)->fullpath)) == grp_cv_paths.end())
// If finding this var is associated with 2-D lat/lon CVs, not keep the original "coordinates" attribute.
coor_attr_keep_exist = Check_Var_2D_CVars(*irv);
else {
coor_attr_keep_exist = true;
}
// Remove the following code later since the released SMAP products are different. KY 2015-12-08
if(product_type == SMAP)
coor_attr_keep_exist = true;
// Need to delete the original "coordinates" and rebuild the "coordinates" if this var is associated with the 2-D lat/lon CVs.
if (false == coor_attr_keep_exist) {
for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin();
ira !=(*irv)->attrs.end();) {
if ((*ira)->newname == co_attrname) {
delete (*ira);
ira = (*irv)->attrs.erase(ira);
}
else {
++ira;
}
}// for (vector<Attribute *>:: iterator ira =(*irv)->attrs.begin(); ...
// Generate the new "coordinates" attribute.
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ ird) {
for (vector<GMCVar *>::iterator ircv = this->cvars.begin();
ircv != this->cvars.end(); ++ircv) {
if ((*ird)->name == (*ircv)->cfdimname)
co_attrvalue = (co_attrvalue.empty())
?(*ircv)->newname:co_attrvalue + " "+(*ircv)->newname;
}
}
if (false == co_attrvalue.empty()) {
Attribute * attr = new Attribute();
Add_Str_Attr(attr,co_attrname,co_attrvalue);
(*irv)->attrs.push_back(attr);
}
co_attrvalue.clear();
} // for (vector<Var *>::iterator irv = this->vars.begin(); ...
}
}
}
}
// Handle GPM level 1 coordiantes attributes.
void GMFile:: Handle_GPM_l1_Coor_Attr() throw(Exception){
// Build a map from CFdimname to 2-D lat/lon variable name, should be something like: aa_list[cfdimname]=s1_latitude .
// Loop all variables
// Inner loop: for all dims of a var
// if(dimname matches the dim(not cfdim) name of one of 2-D lat/lon,
// check if the variable's full path contains the path of one of 2-D lat/lon,
// yes, build its cfdimname = path+ dimname, check this cfdimname with the cfdimname of the corresponding 2-D lat/lon
// If matched, save this latitude variable name as one of the coordinate variable.
// else this is a 3rd-dimension cv, just use the dimension name(or the corresponding cv name maybe through a map).
// Prepare 1) 2-D CVar(lat,lon) corresponding dimension name set.
// 2) cfdim name to cvar name map(don't need to use a map, just a holder. It should be fine.
// "coordinates" attribute name and value. We only need to provide this atttribute for variables that have 2-D lat/lon
string co_attrname = "coordinates";
string co_attrvalue="";
// 2-D cv dimname set.
set<string> cvar_2d_dimset;
pair<map<string,string>::iterator,bool>mapret;
// Hold the mapping from cfdimname to 2-D cvar name. Something like nscan->lat, npixel->lon
map<string,string>cfdimname_to_cvar2dname;
// Loop through cv variables to build 2-D cv dimname set and the mapping from cfdimname to 2-D cvar name.
for (vector<GMCVar *>::iterator irv = this->cvars.begin();
irv != this->cvars.end(); ++irv) {
//This CVar must be 2-D array.
if((*irv)->rank == 2) {
//cerr<<"2-D cv name is "<<(*irv)->name <<endl;
//cerr<<"2-D cv new name is "<<(*irv)->newname <<endl;
//cerr<<"(*irv)->cfdimname is "<<(*irv)->cfdimname <<endl;
for(vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird != (*irv)->dims.end(); ++ird) {
cvar_2d_dimset.insert((*ird)->name);
}
// Generate cfdimname to cvar2d map
mapret = cfdimname_to_cvar2dname.insert(pair<string,string>((*irv)->cfdimname,(*irv)->newname));
if (false == mapret.second)
throw4("The cf dimension name ",(*irv)->cfdimname," should map to 2-D coordinate variable",
(*irv)->newname);
}
}
// Loop through the variable list to build the coordinates.
for (vector<Var *>::iterator irv = this->vars.begin();
irv != this->vars.end(); ++irv) {
// Only apply to >2D variables.
if((*irv)->rank >=2) {
// The variable dimension names must be found in the 2D cvar dim. nameset.
// The flag must be at least 2.
short have_2d_dimnames_flag = 0;
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
if (cvar_2d_dimset.find((*ird)->name)!=cvar_2d_dimset.end())
have_2d_dimnames_flag++;
}
// Final candidates to have 2-D CVar coordinates.
if(have_2d_dimnames_flag >=2) {
//cerr<<"var name "<<(*irv)->name <<" has 2-D CVar coordinates "<<endl;
// Obtain the variable path
string var_path;
if((*irv)->fullpath.size() > (*irv)->name.size())
var_path=(*irv)->fullpath.substr(0,(*irv)->fullpath.size()-(*irv)->name.size());
else
throw4("The variable full path ",(*irv)->fullpath," doesn't contain the variable name ",
(*irv)->name);
// A flag to identify if this variable really needs the 2-D coordinate variables.
short cv_2d_flag = 0;
// 2-D coordinate variable names for the potential variable candidate
vector<string> cv_2d_names;
// Dimension names of the 2-D coordinate variables.
set<string> cv_2d_dimnames;
// Loop through the map from dim. name to coordinate name.
for(map<string,string>::const_iterator itm = cfdimname_to_cvar2dname.begin();
itm != cfdimname_to_cvar2dname.end();++itm) {
// Obtain the dimension name from the cfdimname.
string reduced_dimname = HDF5CFUtil::obtain_string_after_lastslash(itm->first);
//cerr<<"reduced_dimname is "<<reduced_dimname <<endl;
string cfdim_path;
if(itm->first.size() <= reduced_dimname.size())
throw2("The cf dim. name of this dimension is not right.",itm->first);
else
cfdim_path= itm->first.substr(0,itm->first.size() - reduced_dimname.size());
// cfdim_path will not be NULL only when the cfdim name is for the 2-D cv var.
//cerr<<"var_path is "<<var_path <<endl;
//cerr<<"cfdim_path is "<<cfdim_path <<endl;
// Find the correct path,
// Note:
// var_path doesn't have to be the same as cfdim_path
// consider the variable /a1/a2/foo and the latitude /a1/latitude(cfdimpath is /a1)
// If there is no /a1/a2/latitude, the /a1/latitude can be used as the coordinate of /a1/a2/foo.
// But we want to check if var_path is the same as cfdim_path first. So we check cfdimname_to_cvarname again.
if(var_path == cfdim_path) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end();++ird) {
if(reduced_dimname == (*ird)->name) {
cv_2d_flag++;
cv_2d_names.push_back(itm->second);
cv_2d_dimnames.insert((*ird)->name);
}
}
}
}
// Note:
// var_path doesn't have to be the same as cfdim_path
// consider the variable /a1/a2/foo and the latitude /a1/latitude(cfdimpath is /a1)
// If there is no /a1/a2/latitude, the /a1/latitude can be used as the coordinate of /a1/a2/foo.
// The variable has 2 coordinates(dimensions) if the flag is 2
// If the flag is not 2, we will see if the above case stands.
if(cv_2d_flag != 2) {
cv_2d_flag = 0;
// Loop through the map from dim. name to coordinate name.
for(map<string,string>::const_iterator itm = cfdimname_to_cvar2dname.begin();
itm != cfdimname_to_cvar2dname.end();++itm) {
// Obtain the dimension name from the cfdimname.
string reduced_dimname = HDF5CFUtil::obtain_string_after_lastslash(itm->first);
string cfdim_path;
if(itm->first.size() <= reduced_dimname.size())
throw2("The cf dim. name of this dimension is not right.",itm->first);
else
cfdim_path= itm->first.substr(0,itm->first.size() - reduced_dimname.size());
// cfdim_path will not be NULL only when the cfdim name is for the 2-D cv var.
// Find the correct path,
// Note:
// var_path doesn't have to be the same as cfdim_path
// consider the variable /a1/a2/foo and the latitude /a1/latitude(cfdimpath is /a1)
// If there is no /a1/a2/latitude, the /a1/latitude can be used as the coordinate of /a1/a2/foo.
//
if(var_path.find(cfdim_path)!=string::npos) {
for (vector<Dimension*>::iterator ird = (*irv)->dims.begin();
ird!=(*irv)->dims.end();++ird) {
if(reduced_dimname == (*ird)->name) {
cv_2d_flag++;
cv_2d_names.push_back(itm->second);
cv_2d_dimnames.insert((*ird)->name);
}
}
}
}
}
// Now we got all cases.
if(2 == cv_2d_flag) {
// Add latitude and longitude to the 'coordinates' attribute.
co_attrvalue = cv_2d_names[0] + " " + cv_2d_names[1];
if((*irv)->rank >2) {
for (vector<Dimension *>::iterator ird = (*irv)->dims.begin();
ird !=(*irv)->dims.end();++ird) {
// Add 3rd-dimension to the 'coordinates' attribute.
if(cv_2d_dimnames.find((*ird)->name) == cv_2d_dimnames.end())
co_attrvalue = co_attrvalue + " " +(*ird)->newname;
}
}
Attribute * attr = new Attribute();
Add_Str_Attr(attr,co_attrname,co_attrvalue);
(*irv)->attrs.push_back(attr);
}
}
}
}
}
void GMFile::Handle_LatLon_With_CoordinateAttr_Coor_Attr() throw(Exception) {
}
// Create Missing coordinate variables. Index numbers are used for these variables.
void GMFile:: Create_Missing_CV(GMCVar *GMcvar, const string& dimname) throw(Exception) {
GMcvar->name = dimname;
GMcvar->newname = GMcvar->name;
GMcvar->fullpath = GMcvar->name;
GMcvar->rank = 1;
GMcvar->dtype = H5INT32;
hsize_t gmcvar_dimsize = dimname_to_dimsize[dimname];
Dimension* gmcvar_dim = new Dimension(gmcvar_dimsize);
gmcvar_dim->name = dimname;
gmcvar_dim->newname = dimname;
GMcvar->dims.push_back(gmcvar_dim);
GMcvar->cfdimname = dimname;
GMcvar->cvartype = CV_NONLATLON_MISS;
GMcvar->product_type = product_type;
}
// Check if this is just a netCDF-4 dimension. We need to check the dimension scale dataset attribute "NAME",
// the value should start with "This is a netCDF dimension but not a netCDF variable".
bool GMFile::Is_netCDF_Dimension(Var *var) throw(Exception) {
string netcdf_dim_mark = "This is a netCDF dimension but not a netCDF variable";
bool is_only_dimension = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if ("NAME" == (*ira)->name) {
Retrieve_H5_Attr_Value(*ira,var->fullpath);
string name_value;
name_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),name_value.begin());
// Compare the attribute "NAME" value with the string netcdf_dim_mark. We only compare the string with the size of netcdf_dim_mark
if (0 == name_value.compare(0,netcdf_dim_mark.size(),netcdf_dim_mark))
is_only_dimension = true;
break;
}
} // for(vector<Attribute *>::iterator ira = var->attrs.begin(); ...
return is_only_dimension;
}
// Handle attributes for special variables.
void
GMFile::Handle_SpVar_Attr() throw(Exception) {
}
void
GMFile::release_standalone_GMCVar_vector(vector<GMCVar*>&tempgc_vars){
for (vector<GMCVar *>::iterator i = tempgc_vars.begin();
i != tempgc_vars.end(); ) {
delete(*i);
i = tempgc_vars.erase(i);
}
}
#if 0
void
GMFile::add_ignored_info_attrs(bool is_grp,bool is_first){
}
void
GMFile::add_ignored_info_objs(bool is_dim_related, bool is_first) {
}
#endif
#if 0
bool
GMFile::ignored_dimscale_ref_list(Var *var) {
bool ignored_dimscale = true;
if(General_Product == this->product_type && GENERAL_DIMSCALE== this->gproduct_pattern) {
bool has_dimscale = false;
bool has_reference_list = false;
for(vector<Attribute *>::iterator ira = var->attrs.begin();
ira != var->attrs.end();ira++) {
if((*ira)->name == "REFERENCE_LIST" &&
false == HDF5CFUtil::cf_strict_support_type((*ira)->getType()))
has_reference_list = true;
if((*ira)->name == "CLASS") {
Retrieve_H5_Attr_Value(*ira,var->fullpath);
string class_value;
class_value.resize((*ira)->value.size());
copy((*ira)->value.begin(),(*ira)->value.end(),class_value.begin());
// Compare the attribute "CLASS" value with "DIMENSION_SCALE". We only compare the string with the size of
// "DIMENSION_SCALE", which is 15.
if (0 == class_value.compare(0,15,"DIMENSION_SCALE")) {
has_dimscale = true;
}
}
if(true == has_dimscale && true == has_reference_list) {
ignored_dimscale= false;
break;
}
}
}
return ignored_dimscale;
}
#endif
|
#include "amount.h"
#include "util.h"
#include <list>
#include <sstream>
#include <cstdlib>
#include <gmp.h>
namespace ledger {
bool do_cleanup = true;
bool amount_t::keep_price = false;
bool amount_t::keep_date = false;
bool amount_t::keep_tag = false;
bool amount_t::keep_base = false;
#define BIGINT_BULK_ALLOC 0x0001
#define BIGINT_KEEP_PREC 0x0002
class amount_t::bigint_t {
public:
mpz_t val;
unsigned char prec;
unsigned char flags;
unsigned int ref;
unsigned int index;
bigint_t() : prec(0), flags(0), ref(1), index(0) {
mpz_init(val);
}
bigint_t(mpz_t _val) : prec(0), flags(0), ref(1), index(0) {
mpz_init_set(val, _val);
}
bigint_t(const bigint_t& other)
: prec(other.prec), flags(other.flags & BIGINT_KEEP_PREC),
ref(1), index(0) {
mpz_init_set(val, other.val);
}
~bigint_t();
};
unsigned int sizeof_bigint_t() {
return sizeof(amount_t::bigint_t);
}
#define MPZ(x) ((x)->val)
static mpz_t temp; // these are the global temp variables
static mpz_t divisor;
static amount_t::bigint_t true_value;
inline amount_t::bigint_t::~bigint_t() {
assert(ref == 0 || (! do_cleanup && this == &true_value));
mpz_clear(val);
}
base_commodities_map commodity_base_t::commodities;
commodity_base_t::updater_t * commodity_base_t::updater = NULL;
commodities_map commodity_t::commodities;
bool commodity_t::commodities_sorted = false;
commodity_t * commodity_t::null_commodity;
commodity_t * commodity_t::default_commodity = NULL;
static struct _init_amounts {
_init_amounts() {
mpz_init(temp);
mpz_init(divisor);
mpz_set_ui(true_value.val, 1);
commodity_base_t::updater = NULL;
commodity_t::null_commodity = commodity_t::create("");
commodity_t::default_commodity = NULL;
commodity_t::null_commodity->add_flags(COMMODITY_STYLE_NOMARKET |
COMMODITY_STYLE_BUILTIN);
// Add time commodity conversions, so that timelog's may be parsed
// in terms of seconds, but reported as minutes or hours.
commodity_t * commodity;
commodity = commodity_t::create("s");
commodity->add_flags(COMMODITY_STYLE_NOMARKET | COMMODITY_STYLE_BUILTIN);
parse_conversion("1.0m", "60s");
parse_conversion("1.0h", "60m");
#if 0
commodity = commodity_t::create("b");
commodity->add_flags(COMMODITY_STYLE_NOMARKET | COMMODITY_STYLE_BUILTIN);
parse_conversion("1.00 Kb", "1024 b");
parse_conversion("1.00 Mb", "1024 Kb");
parse_conversion("1.00 Gb", "1024 Mb");
parse_conversion("1.00 Tb", "1024 Gb");
#endif
}
~_init_amounts() {
if (! do_cleanup)
return;
mpz_clear(temp);
mpz_clear(divisor);
if (commodity_base_t::updater) {
delete commodity_base_t::updater;
commodity_base_t::updater = NULL;
}
for (commodities_map::iterator i = commodity_t::commodities.begin();
i != commodity_t::commodities.end();
i++)
delete (*i).second;
commodity_t::commodities.clear();
true_value.ref--;
}
} _init_obj;
static void mpz_round(mpz_t out, mpz_t value, int value_prec, int round_prec)
{
// Round `value', with an encoding precision of `value_prec', to a
// rounded value with precision `round_prec'. Result is stored in
// `out'.
assert(value_prec > round_prec);
mpz_t quotient;
mpz_t remainder;
mpz_init(quotient);
mpz_init(remainder);
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_tdiv_qr(quotient, remainder, value, divisor);
mpz_divexact_ui(divisor, divisor, 10);
mpz_mul_ui(divisor, divisor, 5);
if (mpz_sgn(remainder) < 0) {
mpz_neg(divisor, divisor);
if (mpz_cmp(remainder, divisor) < 0) {
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_add(remainder, divisor, remainder);
mpz_ui_sub(remainder, 0, remainder);
mpz_add(out, value, remainder);
} else {
mpz_sub(out, value, remainder);
}
} else {
if (mpz_cmp(remainder, divisor) >= 0) {
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_sub(remainder, divisor, remainder);
mpz_add(out, value, remainder);
} else {
mpz_sub(out, value, remainder);
}
}
mpz_clear(quotient);
mpz_clear(remainder);
// chop off the rounded bits
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_tdiv_q(out, out, divisor);
}
amount_t::amount_t(const bool value)
{
if (value) {
quantity = &true_value;
quantity->ref++;
} else {
quantity = NULL;
}
commodity_ = NULL;
}
amount_t::amount_t(const long value)
{
if (value != 0) {
quantity = new bigint_t;
mpz_set_si(MPZ(quantity), value);
} else {
quantity = NULL;
}
commodity_ = NULL;
}
amount_t::amount_t(const unsigned long value)
{
if (value != 0) {
quantity = new bigint_t;
mpz_set_ui(MPZ(quantity), value);
} else {
quantity = NULL;
}
commodity_ = NULL;
}
amount_t::amount_t(const double value)
{
if (value != 0.0) {
quantity = new bigint_t;
mpz_set_d(MPZ(quantity), value);
} else {
quantity = NULL;
}
commodity_ = NULL;
}
void amount_t::_release()
{
DEBUG_PRINT("amounts.refs",
quantity << " ref--, now " << (quantity->ref - 1));
if (--quantity->ref == 0) {
if (! (quantity->flags & BIGINT_BULK_ALLOC))
delete quantity;
else
quantity->~bigint_t();
}
}
void amount_t::_init()
{
if (! quantity) {
quantity = new bigint_t;
}
else if (quantity->ref > 1) {
_release();
quantity = new bigint_t;
}
}
void amount_t::_dup()
{
if (quantity->ref > 1) {
bigint_t * q = new bigint_t(*quantity);
_release();
quantity = q;
}
}
void amount_t::_copy(const amount_t& amt)
{
if (quantity != amt.quantity) {
if (quantity)
_release();
// Never maintain a pointer into a bulk allocation pool; such
// pointers are not guaranteed to remain.
if (amt.quantity->flags & BIGINT_BULK_ALLOC) {
quantity = new bigint_t(*amt.quantity);
} else {
quantity = amt.quantity;
DEBUG_PRINT("amounts.refs",
quantity << " ref++, now " << (quantity->ref + 1));
quantity->ref++;
}
}
commodity_ = amt.commodity_;
}
amount_t& amount_t::operator=(const std::string& value)
{
std::istringstream str(value);
parse(str);
return *this;
}
amount_t& amount_t::operator=(const char * value)
{
std::string valstr(value);
std::istringstream str(valstr);
parse(str);
return *this;
}
// assignment operator
amount_t& amount_t::operator=(const amount_t& amt)
{
if (this != &amt) {
if (amt.quantity)
_copy(amt);
else if (quantity)
_clear();
}
return *this;
}
amount_t& amount_t::operator=(const bool value)
{
if (! value) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
if (quantity)
_release();
quantity = &true_value;
quantity->ref++;
}
return *this;
}
amount_t& amount_t::operator=(const long value)
{
if (value == 0) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
_init();
mpz_set_si(MPZ(quantity), value);
}
return *this;
}
amount_t& amount_t::operator=(const unsigned long value)
{
if (value == 0) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
_init();
mpz_set_ui(MPZ(quantity), value);
}
return *this;
}
amount_t& amount_t::operator=(const double value)
{
if (value == 0.0) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
_init();
mpz_set_d(MPZ(quantity), value);
}
return *this;
}
void amount_t::_resize(unsigned int prec)
{
assert(prec < 256);
if (! quantity || prec == quantity->prec)
return;
_dup();
if (prec < quantity->prec) {
mpz_ui_pow_ui(divisor, 10, quantity->prec - prec);
mpz_tdiv_q(MPZ(quantity), MPZ(quantity), divisor);
} else {
mpz_ui_pow_ui(divisor, 10, prec - quantity->prec);
mpz_mul(MPZ(quantity), MPZ(quantity), divisor);
}
quantity->prec = prec;
}
amount_t& amount_t::operator+=(const amount_t& amt)
{
if (! amt.quantity)
return *this;
if (! quantity) {
_copy(amt);
return *this;
}
_dup();
if (commodity() != amt.commodity())
throw new amount_error
(std::string("Adding amounts with different commodities: ") +
commodity_->qualified_symbol + " != " +
amt.commodity_->qualified_symbol);
if (quantity->prec == amt.quantity->prec) {
mpz_add(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else if (quantity->prec < amt.quantity->prec) {
_resize(amt.quantity->prec);
mpz_add(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else {
amount_t temp = amt;
temp._resize(quantity->prec);
mpz_add(MPZ(quantity), MPZ(quantity), MPZ(temp.quantity));
}
return *this;
}
amount_t& amount_t::operator-=(const amount_t& amt)
{
if (! amt.quantity)
return *this;
if (! quantity) {
quantity = new bigint_t(*amt.quantity);
commodity_ = amt.commodity_;
mpz_neg(MPZ(quantity), MPZ(quantity));
return *this;
}
_dup();
if (commodity() != amt.commodity())
throw new amount_error
(std::string("Subtracting amounts with different commodities: ") +
commodity_->qualified_symbol + " != " +
amt.commodity_->qualified_symbol);
if (quantity->prec == amt.quantity->prec) {
mpz_sub(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else if (quantity->prec < amt.quantity->prec) {
_resize(amt.quantity->prec);
mpz_sub(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else {
amount_t temp = amt;
temp._resize(quantity->prec);
mpz_sub(MPZ(quantity), MPZ(quantity), MPZ(temp.quantity));
}
return *this;
}
amount_t& amount_t::operator*=(const amount_t& amt)
{
if (! amt.quantity)
return (*this = amt);
else if (! quantity)
return *this;
_dup();
mpz_mul(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
quantity->prec += amt.quantity->prec;
unsigned int comm_prec = commodity().precision();
if (quantity->prec > comm_prec + 6U) {
mpz_round(MPZ(quantity), MPZ(quantity), quantity->prec, comm_prec + 6U);
quantity->prec = comm_prec + 6U;
}
return *this;
}
amount_t& amount_t::operator/=(const amount_t& amt)
{
if (! amt.quantity || ! amt)
throw new amount_error("Divide by zero");
else if (! quantity)
return *this;
_dup();
// Increase the value's precision, to capture fractional parts after
// the divide.
mpz_ui_pow_ui(divisor, 10, amt.quantity->prec + 6U);
mpz_mul(MPZ(quantity), MPZ(quantity), divisor);
mpz_tdiv_q(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
quantity->prec += 6U;
unsigned int comm_prec = commodity().precision();
if (quantity->prec > comm_prec + 6U) {
mpz_round(MPZ(quantity), MPZ(quantity), quantity->prec, comm_prec + 6U);
quantity->prec = comm_prec + 6U;
}
return *this;
}
// unary negation
void amount_t::negate()
{
if (quantity) {
_dup();
mpz_neg(MPZ(quantity), MPZ(quantity));
}
}
int amount_t::sign() const
{
return quantity ? mpz_sgn(MPZ(quantity)) : 0;
}
int amount_t::compare(const amount_t& amt) const
{
if (! quantity) {
if (! amt.quantity)
return 0;
return - amt.sign();
}
if (! amt.quantity)
return sign();
if (commodity() && amt.commodity() && commodity() != amt.commodity())
throw new amount_error
(std::string("Cannot compare amounts with different commodities: ") +
commodity().symbol() + " and " + amt.commodity().symbol());
if (quantity->prec == amt.quantity->prec) {
return mpz_cmp(MPZ(quantity), MPZ(amt.quantity));
}
else if (quantity->prec < amt.quantity->prec) {
amount_t temp = *this;
temp._resize(amt.quantity->prec);
return mpz_cmp(MPZ(temp.quantity), MPZ(amt.quantity));
}
else {
amount_t temp = amt;
temp._resize(quantity->prec);
return mpz_cmp(MPZ(quantity), MPZ(temp.quantity));
}
}
bool amount_t::operator==(const amount_t& amt) const
{
if (commodity() != amt.commodity())
return false;
return compare(amt) == 0;
}
bool amount_t::operator!=(const amount_t& amt) const
{
if (commodity() != amt.commodity())
return true;
return compare(amt) != 0;
}
amount_t::operator bool() const
{
if (! quantity)
return false;
if (quantity->prec <= commodity().precision() ||
(quantity->flags & BIGINT_KEEP_PREC)) {
return mpz_sgn(MPZ(quantity)) != 0;
} else {
mpz_set(temp, MPZ(quantity));
mpz_ui_pow_ui(divisor, 10, quantity->prec - commodity().precision());
mpz_tdiv_q(temp, temp, divisor);
bool zero = mpz_sgn(temp) == 0;
return ! zero;
}
}
amount_t::operator long() const
{
if (! quantity)
return 0;
mpz_set(temp, MPZ(quantity));
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_q(temp, temp, divisor);
return mpz_get_si(temp);
}
amount_t::operator double() const
{
if (! quantity)
return 0.0;
mpz_t remainder;
mpz_init(remainder);
mpz_set(temp, MPZ(quantity));
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_qr(temp, remainder, temp, divisor);
char * quotient_s = mpz_get_str(NULL, 10, temp);
char * remainder_s = mpz_get_str(NULL, 10, remainder);
std::ostringstream num;
num << quotient_s << '.' << remainder_s;
std::free(quotient_s);
std::free(remainder_s);
mpz_clear(remainder);
return std::atof(num.str().c_str());
}
bool amount_t::realzero() const
{
if (! quantity)
return true;
return mpz_sgn(MPZ(quantity)) == 0;
}
amount_t amount_t::value(const datetime_t& moment) const
{
if (quantity) {
amount_t amt(commodity().value(moment));
if (! amt.realzero())
return (amt * *this).round();
}
return *this;
}
amount_t amount_t::round(unsigned int prec) const
{
amount_t temp = *this;
if (! quantity || quantity->prec <= prec) {
if (quantity && quantity->flags & BIGINT_KEEP_PREC) {
temp._dup();
temp.quantity->flags &= ~BIGINT_KEEP_PREC;
}
return temp;
}
temp._dup();
mpz_round(MPZ(temp.quantity), MPZ(temp.quantity), temp.quantity->prec, prec);
temp.quantity->prec = prec;
temp.quantity->flags &= ~BIGINT_KEEP_PREC;
return temp;
}
amount_t amount_t::unround() const
{
if (! quantity) {
amount_t temp(0L);
assert(temp.quantity);
temp.quantity->flags |= BIGINT_KEEP_PREC;
return temp;
}
else if (quantity->flags & BIGINT_KEEP_PREC) {
return *this;
}
amount_t temp = *this;
temp._dup();
temp.quantity->flags |= BIGINT_KEEP_PREC;
return temp;
}
std::string amount_t::quantity_string() const
{
if (! quantity)
return "0";
std::ostringstream out;
mpz_t quotient;
mpz_t rquotient;
mpz_t remainder;
mpz_init(quotient);
mpz_init(rquotient);
mpz_init(remainder);
bool negative = false;
// Ensure the value is rounded to the commodity's precision before
// outputting it. NOTE: `rquotient' is used here as a temp variable!
commodity_t& comm(commodity());
unsigned char precision;
if (! comm || quantity->flags & BIGINT_KEEP_PREC) {
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(quantity), divisor);
precision = quantity->prec;
}
else if (comm.precision() < quantity->prec) {
mpz_round(rquotient, MPZ(quantity), quantity->prec, comm.precision());
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (comm.precision() > quantity->prec) {
mpz_ui_pow_ui(divisor, 10, comm.precision() - quantity->prec);
mpz_mul(rquotient, MPZ(quantity), divisor);
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (quantity->prec) {
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(quantity), divisor);
precision = quantity->prec;
}
else {
mpz_set(quotient, MPZ(quantity));
mpz_set_ui(remainder, 0);
precision = 0;
}
if (mpz_sgn(quotient) < 0 || mpz_sgn(remainder) < 0) {
negative = true;
mpz_abs(quotient, quotient);
mpz_abs(remainder, remainder);
}
mpz_set(rquotient, remainder);
if (mpz_sgn(quotient) == 0 && mpz_sgn(rquotient) == 0)
return "0";
if (negative)
out << "-";
if (mpz_sgn(quotient) == 0) {
out << '0';
} else {
char * p = mpz_get_str(NULL, 10, quotient);
out << p;
std::free(p);
}
if (precision) {
out << '.';
out.width(precision);
out.fill('0');
char * p = mpz_get_str(NULL, 10, rquotient);
out << p;
std::free(p);
}
mpz_clear(quotient);
mpz_clear(rquotient);
mpz_clear(remainder);
return out.str();
}
std::ostream& operator<<(std::ostream& _out, const amount_t& amt)
{
if (! amt.quantity) {
_out << "0";
return _out;
}
amount_t base(amt);
if (! amount_t::keep_base && amt.commodity().larger()) {
amount_t last(amt);
while (last.commodity().larger()) {
last /= *last.commodity().larger();
last.commodity_ = last.commodity().larger()->commodity_;
if (ledger::abs(last) < 1)
break;
base = last.round();
}
}
std::ostringstream out;
mpz_t quotient;
mpz_t rquotient;
mpz_t remainder;
mpz_init(quotient);
mpz_init(rquotient);
mpz_init(remainder);
bool negative = false;
// Ensure the value is rounded to the commodity's precision before
// outputting it. NOTE: `rquotient' is used here as a temp variable!
commodity_t& comm(base.commodity());
unsigned char precision;
if (! comm || base.quantity->flags & BIGINT_KEEP_PREC) {
mpz_ui_pow_ui(divisor, 10, base.quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(base.quantity), divisor);
precision = base.quantity->prec;
}
else if (comm.precision() < base.quantity->prec) {
mpz_round(rquotient, MPZ(base.quantity), base.quantity->prec,
comm.precision());
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (comm.precision() > base.quantity->prec) {
mpz_ui_pow_ui(divisor, 10, comm.precision() - base.quantity->prec);
mpz_mul(rquotient, MPZ(base.quantity), divisor);
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (base.quantity->prec) {
mpz_ui_pow_ui(divisor, 10, base.quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(base.quantity), divisor);
precision = base.quantity->prec;
}
else {
mpz_set(quotient, MPZ(base.quantity));
mpz_set_ui(remainder, 0);
precision = 0;
}
if (mpz_sgn(quotient) < 0 || mpz_sgn(remainder) < 0) {
negative = true;
mpz_abs(quotient, quotient);
mpz_abs(remainder, remainder);
}
mpz_set(rquotient, remainder);
if (mpz_sgn(quotient) == 0 && mpz_sgn(rquotient) == 0) {
_out << "0";
return _out;
}
if (! (comm.flags() & COMMODITY_STYLE_SUFFIXED)) {
comm.write(out);
if (comm.flags() & COMMODITY_STYLE_SEPARATED)
out << " ";
}
if (negative)
out << "-";
if (mpz_sgn(quotient) == 0) {
out << '0';
}
else if (! (comm.flags() & COMMODITY_STYLE_THOUSANDS)) {
char * p = mpz_get_str(NULL, 10, quotient);
out << p;
std::free(p);
}
else {
std::list<std::string> strs;
char buf[4];
for (int powers = 0; true; powers += 3) {
if (powers > 0) {
mpz_ui_pow_ui(divisor, 10, powers);
mpz_tdiv_q(temp, quotient, divisor);
if (mpz_sgn(temp) == 0)
break;
mpz_tdiv_r_ui(temp, temp, 1000);
} else {
mpz_tdiv_r_ui(temp, quotient, 1000);
}
mpz_get_str(buf, 10, temp);
strs.push_back(buf);
}
bool printed = false;
for (std::list<std::string>::reverse_iterator i = strs.rbegin();
i != strs.rend();
i++) {
if (printed) {
out << (comm.flags() & COMMODITY_STYLE_EUROPEAN ? '.' : ',');
out.width(3);
out.fill('0');
}
out << *i;
printed = true;
}
}
if (precision) {
std::ostringstream final;
final.width(precision);
final.fill('0');
char * p = mpz_get_str(NULL, 10, rquotient);
final << p;
std::free(p);
const std::string& str(final.str());
int i, len = str.length();
const char * q = str.c_str();
for (i = len; i > 0; i--)
if (q[i - 1] != '0')
break;
std::string ender;
if (i == len)
ender = str;
else if (i < comm.precision())
ender = std::string(str, 0, comm.precision());
else
ender = std::string(str, 0, i);
if (! ender.empty()) {
out << ((comm.flags() & COMMODITY_STYLE_EUROPEAN) ? ',' : '.');
out << ender;
}
}
if (comm.flags() & COMMODITY_STYLE_SUFFIXED) {
if (comm.flags() & COMMODITY_STYLE_SEPARATED)
out << " ";
comm.write(out);
}
mpz_clear(quotient);
mpz_clear(rquotient);
mpz_clear(remainder);
// If there are any annotations associated with this commodity,
// output them now.
if (comm.annotated) {
annotated_commodity_t& ann(static_cast<annotated_commodity_t&>(comm));
assert(&ann.price != &amt);
ann.write_annotations(out);
}
// Things are output to a string first, so that if anyone has
// specified a width or fill for _out, it will be applied to the
// entire amount string, and not just the first part.
_out << out.str();
return _out;
}
void parse_quantity(std::istream& in, std::string& value)
{
char buf[256];
char c = peek_next_nonws(in);
READ_INTO(in, buf, 255, c,
std::isdigit(c) || c == '-' || c == '.' || c == ',');
int len = std::strlen(buf);
while (len > 0 && ! std::isdigit(buf[len - 1])) {
buf[--len] = '\0';
in.unget();
}
value = buf;
}
// Invalid commodity characters:
// SPACE, TAB, NEWLINE, RETURN
// 0-9 . , ; - + * / ^ ? : & | ! =
// < > { } [ ] ( ) @
int invalid_chars[256] = {
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/* 00 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
/* 10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 20 */ 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
/* 30 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 40 */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0,
/* 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0,
/* 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 90 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* a0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* b0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* c0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* d0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* e0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* f0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
void parse_commodity(std::istream& in, std::string& symbol)
{
char buf[256];
char c = peek_next_nonws(in);
if (c == '"') {
in.get(c);
READ_INTO(in, buf, 255, c, c != '"');
if (c == '"')
in.get(c);
else
throw new amount_error("Quoted commodity symbol lacks closing quote");
} else {
READ_INTO(in, buf, 255, c, ! invalid_chars[(unsigned char)c]);
}
symbol = buf;
}
void parse_annotations(std::istream& in, amount_t& price,
datetime_t& date, std::string& tag)
{
do {
char buf[256];
char c = peek_next_nonws(in);
if (c == '{') {
if (price)
throw new amount_error("Commodity specifies more than one price");
in.get(c);
READ_INTO(in, buf, 255, c, c != '}');
if (c == '}')
in.get(c);
else
throw new amount_error("Commodity price lacks closing brace");
price.parse(buf, AMOUNT_PARSE_NO_MIGRATE);
price.reduce();
// Since this price will maintain its own precision, make sure
// it is at least as large as the base commodity, since the user
// may have only specified {$1} or something similar.
if (price.quantity->prec < price.commodity().precision())
price = price.round(); // no need to retain individual precision
}
else if (c == '[') {
if (date)
throw new amount_error("Commodity specifies more than one date");
in.get(c);
READ_INTO(in, buf, 255, c, c != ']');
if (c == ']')
in.get(c);
else
throw new amount_error("Commodity date lacks closing bracket");
date = buf;
}
else if (c == '(') {
if (! tag.empty())
throw new amount_error("Commodity specifies more than one tag");
in.get(c);
READ_INTO(in, buf, 255, c, c != ')');
if (c == ')')
in.get(c);
else
throw new amount_error("Commodity tag lacks closing parenthesis");
tag = buf;
}
else {
break;
}
} while (true);
DEBUG_PRINT("amounts.commodities",
"Parsed commodity annotations: "
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
}
bool amount_t::parse(std::istream& in, unsigned char flags)
{
// The possible syntax for an amount is:
//
// [-]NUM[ ]SYM [@ AMOUNT]
// SYM[ ][-]NUM [@ AMOUNT]
std::string symbol;
std::string quant;
amount_t price;
datetime_t date;
std::string tag;
unsigned int comm_flags = COMMODITY_STYLE_DEFAULTS;
bool negative = false;
char c = peek_next_nonws(in);
if (c == '-') {
negative = true;
in.get(c);
c = peek_next_nonws(in);
}
char n;
if (std::isdigit(c)) {
parse_quantity(in, quant);
if (! in.eof() && ((n = in.peek()) != '\n')) {
if (std::isspace(n))
comm_flags |= COMMODITY_STYLE_SEPARATED;
parse_commodity(in, symbol);
if (! symbol.empty())
comm_flags |= COMMODITY_STYLE_SUFFIXED;
if (! in.eof() && ((n = in.peek()) != '\n'))
parse_annotations(in, price, date, tag);
}
} else {
parse_commodity(in, symbol);
if (! in.eof() && ((n = in.peek()) != '\n')) {
if (std::isspace(in.peek()))
comm_flags |= COMMODITY_STYLE_SEPARATED;
parse_quantity(in, quant);
if (! quant.empty() && ! in.eof() && ((n = in.peek()) != '\n'))
parse_annotations(in, price, date, tag);
}
}
if (quant.empty()) {
if (flags & AMOUNT_PARSE_SOFT_FAIL)
return false;
else
throw new amount_error("No quantity specified for amount");
}
_init();
// Create the commodity if has not already been seen, and update the
// precision if something greater was used for the quantity.
bool newly_created = false;
if (symbol.empty()) {
commodity_ = commodity_t::null_commodity;
} else {
commodity_ = commodity_t::find(symbol);
if (! commodity_) {
commodity_ = commodity_t::create(symbol);
newly_created = true;
}
assert(commodity_);
if (! price.realzero() || date || ! tag.empty())
commodity_ =
annotated_commodity_t::find_or_create(*commodity_, price, date, tag);
}
// Determine the precision of the amount, based on the usage of
// comma or period.
std::string::size_type last_comma = quant.rfind(',');
std::string::size_type last_period = quant.rfind('.');
if (last_comma != std::string::npos && last_period != std::string::npos) {
comm_flags |= COMMODITY_STYLE_THOUSANDS;
if (last_comma > last_period) {
comm_flags |= COMMODITY_STYLE_EUROPEAN;
quantity->prec = quant.length() - last_comma - 1;
} else {
quantity->prec = quant.length() - last_period - 1;
}
}
else if (last_comma != std::string::npos &&
(! commodity_t::default_commodity ||
commodity_t::default_commodity->flags() & COMMODITY_STYLE_EUROPEAN)) {
comm_flags |= COMMODITY_STYLE_EUROPEAN;
quantity->prec = quant.length() - last_comma - 1;
}
else if (last_period != std::string::npos &&
! (commodity().flags() & COMMODITY_STYLE_EUROPEAN)) {
quantity->prec = quant.length() - last_period - 1;
}
else {
quantity->prec = 0;
}
// Set the commodity's flags and precision accordingly
if (! (flags & AMOUNT_PARSE_NO_MIGRATE)) {
commodity().add_flags(comm_flags);
if (quantity->prec > commodity().precision())
commodity().set_precision(quantity->prec);
} else {
quantity->flags |= BIGINT_KEEP_PREC;
}
// Now we have the final number. Remove commas and periods, if
// necessary.
if (last_comma != std::string::npos || last_period != std::string::npos) {
int len = quant.length();
char * buf = new char[len + 1];
const char * p = quant.c_str();
char * t = buf;
while (*p) {
if (*p == ',' || *p == '.')
p++;
*t++ = *p++;
}
*t = '\0';
mpz_set_str(MPZ(quantity), buf, 10);
delete[] buf;
} else {
mpz_set_str(MPZ(quantity), quant.c_str(), 10);
}
if (negative)
negate();
if (! (flags & AMOUNT_PARSE_NO_REDUCE))
reduce();
return true;
}
void amount_t::reduce()
{
while (commodity_ && commodity().smaller()) {
*this *= *commodity().smaller();
commodity_ = commodity().smaller()->commodity_;
}
}
bool amount_t::parse(const std::string& str, unsigned char flags)
{
std::istringstream stream(str);
parse(stream, flags);
}
void parse_conversion(const std::string& larger_str,
const std::string& smaller_str)
{
amount_t larger, smaller;
larger.parse(larger_str.c_str(), AMOUNT_PARSE_NO_REDUCE);
smaller.parse(smaller_str.c_str(), AMOUNT_PARSE_NO_REDUCE);
larger *= smaller;
if (larger.commodity()) {
larger.commodity().set_smaller(smaller);
larger.commodity().add_flags(smaller.commodity().flags() |
COMMODITY_STYLE_NOMARKET);
}
if (smaller.commodity())
smaller.commodity().set_larger(larger);
}
char * bigints;
char * bigints_next;
unsigned int bigints_index;
unsigned int bigints_count;
void amount_t::read_quantity(char *& data)
{
char byte = *data++;;
if (byte == 0) {
quantity = NULL;
}
else if (byte == 1) {
quantity = new((bigint_t *)bigints_next) bigint_t;
bigints_next += sizeof(bigint_t);
unsigned short len = *((unsigned short *) data);
data += sizeof(unsigned short);
mpz_import(MPZ(quantity), len / sizeof(short), 1, sizeof(short),
0, 0, data);
data += len;
char negative = *data++;
if (negative)
mpz_neg(MPZ(quantity), MPZ(quantity));
quantity->prec = *((unsigned char *) data);
data += sizeof(unsigned char);
quantity->flags = *((unsigned char *) data);
data += sizeof(unsigned char);
quantity->flags |= BIGINT_BULK_ALLOC;
} else {
unsigned int index = *((unsigned int *) data);
data += sizeof(unsigned int);
quantity = (bigint_t *) (bigints + (index - 1) * sizeof(bigint_t));
DEBUG_PRINT("amounts.refs",
quantity << " ref++, now " << (quantity->ref + 1));
quantity->ref++;
}
}
static char buf[4096];
void amount_t::read_quantity(std::istream& in)
{
char byte;
in.read(&byte, sizeof(byte));
if (byte == 0) {
quantity = NULL;
}
else if (byte == 1) {
quantity = new bigint_t;
unsigned short len;
in.read((char *)&len, sizeof(len));
assert(len < 4096);
in.read(buf, len);
mpz_import(MPZ(quantity), len / sizeof(short), 1, sizeof(short),
0, 0, buf);
char negative;
in.read(&negative, sizeof(negative));
if (negative)
mpz_neg(MPZ(quantity), MPZ(quantity));
in.read((char *)&quantity->prec, sizeof(quantity->prec));
in.read((char *)&quantity->flags, sizeof(quantity->flags));
}
else {
assert(0);
}
}
void amount_t::write_quantity(std::ostream& out) const
{
char byte;
if (! quantity) {
byte = 0;
out.write(&byte, sizeof(byte));
return;
}
if (quantity->index == 0) {
quantity->index = ++bigints_index;
bigints_count++;
byte = 1;
out.write(&byte, sizeof(byte));
std::size_t size;
mpz_export(buf, &size, 1, sizeof(short), 0, 0, MPZ(quantity));
unsigned short len = size * sizeof(short);
out.write((char *)&len, sizeof(len));
if (len) {
assert(len < 4096);
out.write(buf, len);
}
byte = mpz_sgn(MPZ(quantity)) < 0 ? 1 : 0;
out.write(&byte, sizeof(byte));
out.write((char *)&quantity->prec, sizeof(quantity->prec));
unsigned char flags = quantity->flags & ~BIGINT_BULK_ALLOC;
assert(sizeof(flags) == sizeof(quantity->flags));
out.write((char *)&flags, sizeof(flags));
} else {
assert(quantity->ref > 1);
// Since this value has already been written, we simply write
// out a reference to which one it was.
byte = 2;
out.write(&byte, sizeof(byte));
out.write((char *)&quantity->index, sizeof(quantity->index));
}
}
bool amount_t::valid() const
{
if (quantity) {
if (quantity->ref == 0) {
DEBUG_PRINT("ledger.validate", "amount_t: quantity->ref == 0");
return false;
}
}
else if (commodity_) {
DEBUG_PRINT("ledger.validate", "amount_t: commodity_ != NULL");
return false;
}
return true;
}
void amount_t::annotate_commodity(const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
const commodity_t * this_base;
annotated_commodity_t * this_ann = NULL;
if (commodity().annotated) {
this_ann = &static_cast<annotated_commodity_t&>(commodity());
this_base = this_ann->ptr;
} else {
this_base = &commodity();
}
assert(this_base);
DEBUG_PRINT("amounts.commodities", "Annotating commodity for amount "
<< *this << std::endl
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
commodity_t * ann_comm =
annotated_commodity_t::find_or_create
(*this_base, ! price && this_ann ? this_ann->price : price,
! date && this_ann ? this_ann->date : date,
tag.empty() && this_ann ? this_ann->tag : tag);
if (ann_comm)
set_commodity(*ann_comm);
DEBUG_PRINT("amounts.commodities", " Annotated amount is " << *this);
}
amount_t amount_t::strip_annotations(const bool _keep_price,
const bool _keep_date,
const bool _keep_tag) const
{
if (! commodity().annotated ||
(_keep_price && _keep_date && _keep_tag))
return *this;
DEBUG_PRINT("amounts.commodities", "Reducing commodity for amount "
<< *this << std::endl
<< " keep price " << _keep_price << " "
<< " keep date " << _keep_date << " "
<< " keep tag " << _keep_tag);
annotated_commodity_t&
ann_comm(static_cast<annotated_commodity_t&>(commodity()));
assert(ann_comm.base);
commodity_t * new_comm;
if ((_keep_price && ann_comm.price) ||
(_keep_date && ann_comm.date) ||
(_keep_tag && ! ann_comm.tag.empty()))
{
new_comm = annotated_commodity_t::find_or_create
(*ann_comm.ptr, _keep_price ? ann_comm.price : amount_t(),
_keep_date ? ann_comm.date : datetime_t(),
_keep_tag ? ann_comm.tag : "");
} else {
new_comm = commodity_t::find_or_create(ann_comm.base_symbol());
}
assert(new_comm);
amount_t temp(*this);
temp.set_commodity(*new_comm);
DEBUG_PRINT("amounts.commodities", " Reduced amount is " << temp);
return temp;
}
amount_t amount_t::price() const
{
if (commodity_ && commodity_->annotated) {
amount_t temp(((annotated_commodity_t *)commodity_)->price);
temp *= *this;
DEBUG_PRINT("amounts.commodities",
"Returning price of " << *this << " = " << temp);
return temp;
}
return *this;
}
datetime_t amount_t::date() const
{
if (commodity_ && commodity_->annotated) {
DEBUG_PRINT("amounts.commodities",
"Returning date of " << *this << " = "
<< ((annotated_commodity_t *)commodity_)->date);
return ((annotated_commodity_t *)commodity_)->date;
}
return 0L;
}
void commodity_base_t::add_price(const datetime_t& date,
const amount_t& price)
{
if (! history)
history = new history_t;
history_map::iterator i = history->prices.find(date);
if (i != history->prices.end()) {
(*i).second = price;
} else {
std::pair<history_map::iterator, bool> result
= history->prices.insert(history_pair(date, price));
assert(result.second);
}
}
bool commodity_base_t::remove_price(const datetime_t& date)
{
if (history) {
history_map::size_type n = history->prices.erase(date);
if (n > 0) {
if (history->prices.empty())
history = NULL;
return true;
}
}
return false;
}
commodity_base_t * commodity_base_t::create(const std::string& symbol)
{
commodity_base_t * commodity = new commodity_base_t(symbol);
DEBUG_PRINT("amounts.commodities", "Creating base commodity " << symbol);
std::pair<base_commodities_map::iterator, bool> result
= commodities.insert(base_commodities_pair(symbol, commodity));
assert(result.second);
return commodity;
}
bool commodity_t::needs_quotes(const std::string& symbol)
{
for (const char * p = symbol.c_str(); *p; p++)
if (std::isspace(*p) || std::isdigit(*p) || *p == '-' || *p == '.')
return true;
return false;
}
bool commodity_t::valid() const
{
if (symbol().empty() && this != null_commodity) {
DEBUG_PRINT("ledger.validate",
"commodity_t: symbol().empty() && this != null_commodity");
return false;
}
if (annotated && ! base) {
DEBUG_PRINT("ledger.validate", "commodity_t: annotated && ! base");
return false;
}
if (precision() > 16) {
DEBUG_PRINT("ledger.validate", "commodity_t: precision() > 16");
return false;
}
return true;
}
commodity_t * commodity_t::create(const std::string& symbol)
{
std::auto_ptr<commodity_t> commodity(new commodity_t);
commodity->base = commodity_base_t::create(symbol);
if (needs_quotes(symbol)) {
commodity->qualified_symbol = "\"";
commodity->qualified_symbol += symbol;
commodity->qualified_symbol += "\"";
} else {
commodity->qualified_symbol = symbol;
}
DEBUG_PRINT("amounts.commodities",
"Creating commodity " << commodity->qualified_symbol);
std::pair<commodities_map::iterator, bool> result
= commodities.insert(commodities_pair(symbol, commodity.get()));
if (! result.second)
return NULL;
// Start out the new commodity with the default commodity's flags
// and precision, if one has been defined.
if (default_commodity)
commodity->drop_flags(COMMODITY_STYLE_THOUSANDS |
COMMODITY_STYLE_NOMARKET);
return commodity.release();
}
commodity_t * commodity_t::find_or_create(const std::string& symbol)
{
DEBUG_PRINT("amounts.commodities", "Find-or-create commodity " << symbol);
commodity_t * commodity = find(symbol);
if (commodity)
return commodity;
return create(symbol);
}
commodity_t * commodity_t::find(const std::string& symbol)
{
DEBUG_PRINT("amounts.commodities", "Find commodity " << symbol);
commodities_map::const_iterator i = commodities.find(symbol);
if (i != commodities.end())
return (*i).second;
return NULL;
}
amount_t commodity_base_t::value(const datetime_t& moment)
{
datetime_t age;
amount_t price;
if (history) {
assert(history->prices.size() > 0);
if (! moment) {
history_map::reverse_iterator r = history->prices.rbegin();
age = (*r).first;
price = (*r).second;
} else {
history_map::iterator i = history->prices.lower_bound(moment);
if (i == history->prices.end()) {
history_map::reverse_iterator r = history->prices.rbegin();
age = (*r).first;
price = (*r).second;
} else {
age = (*i).first;
if (moment != age) {
if (i != history->prices.begin()) {
--i;
age = (*i).first;
price = (*i).second;
} else {
age = 0;
}
} else {
price = (*i).second;
}
}
}
}
if (updater && ! (flags & COMMODITY_STYLE_NOMARKET))
(*updater)(*this, moment, age,
(history && history->prices.size() > 0 ?
(*history->prices.rbegin()).first : datetime_t()), price);
return price;
}
bool annotated_commodity_t::operator==(const commodity_t& comm) const
{
// If the base commodities don't match, the game's up.
if (base != comm.base)
return false;
if (price &&
(! comm.annotated ||
price != static_cast<const annotated_commodity_t&>(comm).price))
return false;
if (date &&
(! comm.annotated ||
date != static_cast<const annotated_commodity_t&>(comm).date))
return false;
if (! tag.empty() &&
(! comm.annotated ||
tag != static_cast<const annotated_commodity_t&>(comm).tag))
return false;
return true;
}
void
annotated_commodity_t::write_annotations(std::ostream& out,
const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
if (price)
out << " {" << price << '}';
if (date)
out << " [" << date << ']';
if (! tag.empty())
out << " (" << tag << ')';
}
commodity_t *
annotated_commodity_t::create(const commodity_t& comm,
const amount_t& price,
const datetime_t& date,
const std::string& tag,
const std::string& mapping_key)
{
std::auto_ptr<annotated_commodity_t> commodity(new annotated_commodity_t);
// Set the annotated bits
commodity->price = price;
commodity->date = date;
commodity->tag = tag;
commodity->ptr = &comm;
assert(commodity->ptr);
commodity->base = comm.base;
assert(commodity->base);
commodity->qualified_symbol = comm.symbol();
DEBUG_PRINT("amounts.commodities", "Creating annotated commodity "
<< "symbol " << commodity->symbol()
<< " key " << mapping_key << std::endl
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
// Add the fully annotated name to the map, so that this symbol may
// quickly be found again.
std::pair<commodities_map::iterator, bool> result
= commodities.insert(commodities_pair(mapping_key, commodity.get()));
if (! result.second)
return NULL;
return commodity.release();
}
namespace {
std::string make_qualified_name(const commodity_t& comm,
const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
if (price < 0)
throw new amount_error("A commodity's price may not be negative");
std::ostringstream name;
comm.write(name);
annotated_commodity_t::write_annotations(name, price, date, tag);
DEBUG_PRINT("amounts.commodities", "make_qualified_name for "
<< comm.qualified_symbol << std::endl
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
DEBUG_PRINT("amounts.commodities", "qualified_name is " << name.str());
return name.str();
}
}
commodity_t *
annotated_commodity_t::find_or_create(const commodity_t& comm,
const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
std::string name = make_qualified_name(comm, price, date, tag);
commodity_t * ann_comm = commodity_t::find(name);
if (ann_comm) {
assert(ann_comm->annotated);
return ann_comm;
}
return create(comm, price, date, tag, name);
}
bool compare_amount_commodities::operator()(const amount_t * left,
const amount_t * right) const
{
commodity_t& leftcomm(left->commodity());
commodity_t& rightcomm(right->commodity());
int cmp = leftcomm.base_symbol().compare(rightcomm.base_symbol());
if (cmp != 0)
return cmp < 0;
if (! leftcomm.annotated) {
assert(rightcomm.annotated);
return true;
}
else if (! rightcomm.annotated) {
assert(leftcomm.annotated);
return false;
}
else {
annotated_commodity_t& aleftcomm(static_cast<annotated_commodity_t&>(leftcomm));
annotated_commodity_t& arightcomm(static_cast<annotated_commodity_t&>(rightcomm));
if (! aleftcomm.price && arightcomm.price)
return true;
if (aleftcomm.price && ! arightcomm.price)
return false;
if (aleftcomm.price && arightcomm.price) {
amount_t leftprice(aleftcomm.price);
leftprice.reduce();
amount_t rightprice(arightcomm.price);
rightprice.reduce();
if (leftprice.commodity() == rightprice.commodity()) {
int diff = leftprice.compare(rightprice);
if (diff)
return diff;
} else {
// Since we have two different amounts, there's really no way
// to establish a true sorting order; we'll just do it based
// on the numerical values.
leftprice.clear_commodity();
rightprice.clear_commodity();
int diff = leftprice.compare(rightprice);
if (diff)
return diff;
}
}
if (! aleftcomm.date && arightcomm.date)
return true;
if (aleftcomm.date && ! arightcomm.date)
return false;
if (aleftcomm.date && arightcomm.date) {
int diff = aleftcomm.date - arightcomm.date;
if (diff)
return diff < 0;
}
if (aleftcomm.tag.empty() && ! arightcomm.tag.empty())
return true;
if (! aleftcomm.tag.empty() && arightcomm.tag.empty())
return false;
if (! aleftcomm.tag.empty() && ! arightcomm.tag.empty())
return aleftcomm.tag < arightcomm.tag;
// The two annotated commodities don't differ enough to matter. This
// should make this identical.
return true;
}
}
} // namespace ledger
#ifdef USE_BOOST_PYTHON
#include <boost/python.hpp>
#include <Python.h>
using namespace boost::python;
using namespace ledger;
int py_amount_quantity(amount_t& amount)
{
std::string quant = amount.quantity_string();
return std::atol(quant.c_str());
}
void py_parse_1(amount_t& amount, const std::string& str,
unsigned char flags) {
amount.parse(str, flags);
}
void py_parse_2(amount_t& amount, const std::string& str) {
amount.parse(str);
}
struct commodity_updater_wrap : public commodity_base_t::updater_t
{
PyObject * self;
commodity_updater_wrap(PyObject * self_) : self(self_) {}
virtual void operator()(commodity_base_t& commodity,
const datetime_t& moment,
const datetime_t& date,
const datetime_t& last,
amount_t& price) {
call_method<void>(self, "__call__", commodity, moment, date, last, price);
}
};
commodity_t * py_find_commodity(const std::string& symbol)
{
return commodity_t::find(symbol);
}
#define EXC_TRANSLATOR(type) \
void exc_translate_ ## type(const type& err) { \
PyErr_SetString(PyExc_RuntimeError, err.what()); \
}
EXC_TRANSLATOR(amount_error)
void export_amount()
{
scope().attr("AMOUNT_PARSE_NO_MIGRATE") = AMOUNT_PARSE_NO_MIGRATE;
scope().attr("AMOUNT_PARSE_NO_REDUCE") = AMOUNT_PARSE_NO_REDUCE;
class_< amount_t > ("Amount")
.def(init<amount_t>())
.def(init<std::string>())
.def(init<char *>())
.def(init<bool>())
.def(init<long>())
.def(init<unsigned long>())
.def(init<double>())
.def(self += self)
.def(self += long())
.def(self + self)
.def(self + long())
.def(self -= self)
.def(self -= long())
.def(self - self)
.def(self - long())
.def(self *= self)
.def(self *= long())
.def(self * self)
.def(self * long())
.def(self /= self)
.def(self /= long())
.def(self / self)
.def(self / long())
.def(- self)
.def(self < self)
.def(self < long())
.def(self <= self)
.def(self <= long())
.def(self > self)
.def(self > long())
.def(self >= self)
.def(self >= long())
.def(self == self)
.def(self == long())
.def(self != self)
.def(self != long())
.def(! self)
.def(self_ns::int_(self))
.def(self_ns::float_(self))
.def(self_ns::str(self))
.def(abs(self))
.add_property("commodity",
make_function(&amount_t::commodity,
return_value_policy<reference_existing_object>()),
make_function(&amount_t::set_commodity,
with_custodian_and_ward<1, 2>()))
.def("strip_annotations", &amount_t::strip_annotations)
.def("negate", &amount_t::negate)
.def("negated", &amount_t::negated)
.def("parse", py_parse_1)
.def("parse", py_parse_2)
.def("reduce", &amount_t::reduce)
.def("valid", &amount_t::valid)
;
class_< commodity_base_t::updater_t, commodity_updater_wrap,
boost::noncopyable >
("Updater")
;
scope().attr("COMMODITY_STYLE_DEFAULTS") = COMMODITY_STYLE_DEFAULTS;
scope().attr("COMMODITY_STYLE_SUFFIXED") = COMMODITY_STYLE_SUFFIXED;
scope().attr("COMMODITY_STYLE_SEPARATED") = COMMODITY_STYLE_SEPARATED;
scope().attr("COMMODITY_STYLE_EUROPEAN") = COMMODITY_STYLE_EUROPEAN;
scope().attr("COMMODITY_STYLE_THOUSANDS") = COMMODITY_STYLE_THOUSANDS;
scope().attr("COMMODITY_STYLE_NOMARKET") = COMMODITY_STYLE_NOMARKET;
scope().attr("COMMODITY_STYLE_BUILTIN") = COMMODITY_STYLE_BUILTIN;
class_< commodity_t > ("Commodity")
.add_property("symbol", &commodity_t::symbol)
#if 0
.add_property("name", &commodity_t::name, &commodity_t::set_name)
.add_property("note", &commodity_t::note, &commodity_t::set_note)
.add_property("precision", &commodity_t::precision,
&commodity_t::set_precision)
.add_property("flags", &commodity_t::flags, &commodity_t::set_flags)
.add_property("add_flags", &commodity_t::add_flags)
.add_property("drop_flags", &commodity_t::drop_flags)
#if 0
.add_property("updater", &commodity_t::updater)
#endif
.add_property("smaller",
make_getter(&commodity_t::smaller,
return_value_policy<reference_existing_object>()),
make_setter(&commodity_t::smaller,
return_value_policy<reference_existing_object>()))
.add_property("larger",
make_getter(&commodity_t::larger,
return_value_policy<reference_existing_object>()),
make_setter(&commodity_t::larger,
return_value_policy<reference_existing_object>()))
.def(self_ns::str(self))
.def("find", py_find_commodity,
return_value_policy<reference_existing_object>())
.staticmethod("find")
#endif
.def("add_price", &commodity_t::add_price)
.def("remove_price", &commodity_t::remove_price)
.def("value", &commodity_t::value)
.def("valid", &commodity_t::valid)
;
#define EXC_TRANSLATE(type) \
register_exception_translator<type>(&exc_translate_ ## type);
EXC_TRANSLATE(amount_error);
}
#endif // USE_BOOST_PYTHON
Added a header inclusion for <memory>.
#include "amount.h"
#include "util.h"
#include <list>
#include <sstream>
#include <cstdlib>
#include <memory>
#include <gmp.h>
namespace ledger {
bool do_cleanup = true;
bool amount_t::keep_price = false;
bool amount_t::keep_date = false;
bool amount_t::keep_tag = false;
bool amount_t::keep_base = false;
#define BIGINT_BULK_ALLOC 0x0001
#define BIGINT_KEEP_PREC 0x0002
class amount_t::bigint_t {
public:
mpz_t val;
unsigned char prec;
unsigned char flags;
unsigned int ref;
unsigned int index;
bigint_t() : prec(0), flags(0), ref(1), index(0) {
mpz_init(val);
}
bigint_t(mpz_t _val) : prec(0), flags(0), ref(1), index(0) {
mpz_init_set(val, _val);
}
bigint_t(const bigint_t& other)
: prec(other.prec), flags(other.flags & BIGINT_KEEP_PREC),
ref(1), index(0) {
mpz_init_set(val, other.val);
}
~bigint_t();
};
unsigned int sizeof_bigint_t() {
return sizeof(amount_t::bigint_t);
}
#define MPZ(x) ((x)->val)
static mpz_t temp; // these are the global temp variables
static mpz_t divisor;
static amount_t::bigint_t true_value;
inline amount_t::bigint_t::~bigint_t() {
assert(ref == 0 || (! do_cleanup && this == &true_value));
mpz_clear(val);
}
base_commodities_map commodity_base_t::commodities;
commodity_base_t::updater_t * commodity_base_t::updater = NULL;
commodities_map commodity_t::commodities;
bool commodity_t::commodities_sorted = false;
commodity_t * commodity_t::null_commodity;
commodity_t * commodity_t::default_commodity = NULL;
static struct _init_amounts {
_init_amounts() {
mpz_init(temp);
mpz_init(divisor);
mpz_set_ui(true_value.val, 1);
commodity_base_t::updater = NULL;
commodity_t::null_commodity = commodity_t::create("");
commodity_t::default_commodity = NULL;
commodity_t::null_commodity->add_flags(COMMODITY_STYLE_NOMARKET |
COMMODITY_STYLE_BUILTIN);
// Add time commodity conversions, so that timelog's may be parsed
// in terms of seconds, but reported as minutes or hours.
commodity_t * commodity;
commodity = commodity_t::create("s");
commodity->add_flags(COMMODITY_STYLE_NOMARKET | COMMODITY_STYLE_BUILTIN);
parse_conversion("1.0m", "60s");
parse_conversion("1.0h", "60m");
#if 0
commodity = commodity_t::create("b");
commodity->add_flags(COMMODITY_STYLE_NOMARKET | COMMODITY_STYLE_BUILTIN);
parse_conversion("1.00 Kb", "1024 b");
parse_conversion("1.00 Mb", "1024 Kb");
parse_conversion("1.00 Gb", "1024 Mb");
parse_conversion("1.00 Tb", "1024 Gb");
#endif
}
~_init_amounts() {
if (! do_cleanup)
return;
mpz_clear(temp);
mpz_clear(divisor);
if (commodity_base_t::updater) {
delete commodity_base_t::updater;
commodity_base_t::updater = NULL;
}
for (commodities_map::iterator i = commodity_t::commodities.begin();
i != commodity_t::commodities.end();
i++)
delete (*i).second;
commodity_t::commodities.clear();
true_value.ref--;
}
} _init_obj;
static void mpz_round(mpz_t out, mpz_t value, int value_prec, int round_prec)
{
// Round `value', with an encoding precision of `value_prec', to a
// rounded value with precision `round_prec'. Result is stored in
// `out'.
assert(value_prec > round_prec);
mpz_t quotient;
mpz_t remainder;
mpz_init(quotient);
mpz_init(remainder);
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_tdiv_qr(quotient, remainder, value, divisor);
mpz_divexact_ui(divisor, divisor, 10);
mpz_mul_ui(divisor, divisor, 5);
if (mpz_sgn(remainder) < 0) {
mpz_neg(divisor, divisor);
if (mpz_cmp(remainder, divisor) < 0) {
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_add(remainder, divisor, remainder);
mpz_ui_sub(remainder, 0, remainder);
mpz_add(out, value, remainder);
} else {
mpz_sub(out, value, remainder);
}
} else {
if (mpz_cmp(remainder, divisor) >= 0) {
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_sub(remainder, divisor, remainder);
mpz_add(out, value, remainder);
} else {
mpz_sub(out, value, remainder);
}
}
mpz_clear(quotient);
mpz_clear(remainder);
// chop off the rounded bits
mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
mpz_tdiv_q(out, out, divisor);
}
amount_t::amount_t(const bool value)
{
if (value) {
quantity = &true_value;
quantity->ref++;
} else {
quantity = NULL;
}
commodity_ = NULL;
}
amount_t::amount_t(const long value)
{
if (value != 0) {
quantity = new bigint_t;
mpz_set_si(MPZ(quantity), value);
} else {
quantity = NULL;
}
commodity_ = NULL;
}
amount_t::amount_t(const unsigned long value)
{
if (value != 0) {
quantity = new bigint_t;
mpz_set_ui(MPZ(quantity), value);
} else {
quantity = NULL;
}
commodity_ = NULL;
}
amount_t::amount_t(const double value)
{
if (value != 0.0) {
quantity = new bigint_t;
mpz_set_d(MPZ(quantity), value);
} else {
quantity = NULL;
}
commodity_ = NULL;
}
void amount_t::_release()
{
DEBUG_PRINT("amounts.refs",
quantity << " ref--, now " << (quantity->ref - 1));
if (--quantity->ref == 0) {
if (! (quantity->flags & BIGINT_BULK_ALLOC))
delete quantity;
else
quantity->~bigint_t();
}
}
void amount_t::_init()
{
if (! quantity) {
quantity = new bigint_t;
}
else if (quantity->ref > 1) {
_release();
quantity = new bigint_t;
}
}
void amount_t::_dup()
{
if (quantity->ref > 1) {
bigint_t * q = new bigint_t(*quantity);
_release();
quantity = q;
}
}
void amount_t::_copy(const amount_t& amt)
{
if (quantity != amt.quantity) {
if (quantity)
_release();
// Never maintain a pointer into a bulk allocation pool; such
// pointers are not guaranteed to remain.
if (amt.quantity->flags & BIGINT_BULK_ALLOC) {
quantity = new bigint_t(*amt.quantity);
} else {
quantity = amt.quantity;
DEBUG_PRINT("amounts.refs",
quantity << " ref++, now " << (quantity->ref + 1));
quantity->ref++;
}
}
commodity_ = amt.commodity_;
}
amount_t& amount_t::operator=(const std::string& value)
{
std::istringstream str(value);
parse(str);
return *this;
}
amount_t& amount_t::operator=(const char * value)
{
std::string valstr(value);
std::istringstream str(valstr);
parse(str);
return *this;
}
// assignment operator
amount_t& amount_t::operator=(const amount_t& amt)
{
if (this != &amt) {
if (amt.quantity)
_copy(amt);
else if (quantity)
_clear();
}
return *this;
}
amount_t& amount_t::operator=(const bool value)
{
if (! value) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
if (quantity)
_release();
quantity = &true_value;
quantity->ref++;
}
return *this;
}
amount_t& amount_t::operator=(const long value)
{
if (value == 0) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
_init();
mpz_set_si(MPZ(quantity), value);
}
return *this;
}
amount_t& amount_t::operator=(const unsigned long value)
{
if (value == 0) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
_init();
mpz_set_ui(MPZ(quantity), value);
}
return *this;
}
amount_t& amount_t::operator=(const double value)
{
if (value == 0.0) {
if (quantity)
_clear();
} else {
commodity_ = NULL;
_init();
mpz_set_d(MPZ(quantity), value);
}
return *this;
}
void amount_t::_resize(unsigned int prec)
{
assert(prec < 256);
if (! quantity || prec == quantity->prec)
return;
_dup();
if (prec < quantity->prec) {
mpz_ui_pow_ui(divisor, 10, quantity->prec - prec);
mpz_tdiv_q(MPZ(quantity), MPZ(quantity), divisor);
} else {
mpz_ui_pow_ui(divisor, 10, prec - quantity->prec);
mpz_mul(MPZ(quantity), MPZ(quantity), divisor);
}
quantity->prec = prec;
}
amount_t& amount_t::operator+=(const amount_t& amt)
{
if (! amt.quantity)
return *this;
if (! quantity) {
_copy(amt);
return *this;
}
_dup();
if (commodity() != amt.commodity())
throw new amount_error
(std::string("Adding amounts with different commodities: ") +
commodity_->qualified_symbol + " != " +
amt.commodity_->qualified_symbol);
if (quantity->prec == amt.quantity->prec) {
mpz_add(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else if (quantity->prec < amt.quantity->prec) {
_resize(amt.quantity->prec);
mpz_add(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else {
amount_t temp = amt;
temp._resize(quantity->prec);
mpz_add(MPZ(quantity), MPZ(quantity), MPZ(temp.quantity));
}
return *this;
}
amount_t& amount_t::operator-=(const amount_t& amt)
{
if (! amt.quantity)
return *this;
if (! quantity) {
quantity = new bigint_t(*amt.quantity);
commodity_ = amt.commodity_;
mpz_neg(MPZ(quantity), MPZ(quantity));
return *this;
}
_dup();
if (commodity() != amt.commodity())
throw new amount_error
(std::string("Subtracting amounts with different commodities: ") +
commodity_->qualified_symbol + " != " +
amt.commodity_->qualified_symbol);
if (quantity->prec == amt.quantity->prec) {
mpz_sub(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else if (quantity->prec < amt.quantity->prec) {
_resize(amt.quantity->prec);
mpz_sub(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
}
else {
amount_t temp = amt;
temp._resize(quantity->prec);
mpz_sub(MPZ(quantity), MPZ(quantity), MPZ(temp.quantity));
}
return *this;
}
amount_t& amount_t::operator*=(const amount_t& amt)
{
if (! amt.quantity)
return (*this = amt);
else if (! quantity)
return *this;
_dup();
mpz_mul(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
quantity->prec += amt.quantity->prec;
unsigned int comm_prec = commodity().precision();
if (quantity->prec > comm_prec + 6U) {
mpz_round(MPZ(quantity), MPZ(quantity), quantity->prec, comm_prec + 6U);
quantity->prec = comm_prec + 6U;
}
return *this;
}
amount_t& amount_t::operator/=(const amount_t& amt)
{
if (! amt.quantity || ! amt)
throw new amount_error("Divide by zero");
else if (! quantity)
return *this;
_dup();
// Increase the value's precision, to capture fractional parts after
// the divide.
mpz_ui_pow_ui(divisor, 10, amt.quantity->prec + 6U);
mpz_mul(MPZ(quantity), MPZ(quantity), divisor);
mpz_tdiv_q(MPZ(quantity), MPZ(quantity), MPZ(amt.quantity));
quantity->prec += 6U;
unsigned int comm_prec = commodity().precision();
if (quantity->prec > comm_prec + 6U) {
mpz_round(MPZ(quantity), MPZ(quantity), quantity->prec, comm_prec + 6U);
quantity->prec = comm_prec + 6U;
}
return *this;
}
// unary negation
void amount_t::negate()
{
if (quantity) {
_dup();
mpz_neg(MPZ(quantity), MPZ(quantity));
}
}
int amount_t::sign() const
{
return quantity ? mpz_sgn(MPZ(quantity)) : 0;
}
int amount_t::compare(const amount_t& amt) const
{
if (! quantity) {
if (! amt.quantity)
return 0;
return - amt.sign();
}
if (! amt.quantity)
return sign();
if (commodity() && amt.commodity() && commodity() != amt.commodity())
throw new amount_error
(std::string("Cannot compare amounts with different commodities: ") +
commodity().symbol() + " and " + amt.commodity().symbol());
if (quantity->prec == amt.quantity->prec) {
return mpz_cmp(MPZ(quantity), MPZ(amt.quantity));
}
else if (quantity->prec < amt.quantity->prec) {
amount_t temp = *this;
temp._resize(amt.quantity->prec);
return mpz_cmp(MPZ(temp.quantity), MPZ(amt.quantity));
}
else {
amount_t temp = amt;
temp._resize(quantity->prec);
return mpz_cmp(MPZ(quantity), MPZ(temp.quantity));
}
}
bool amount_t::operator==(const amount_t& amt) const
{
if (commodity() != amt.commodity())
return false;
return compare(amt) == 0;
}
bool amount_t::operator!=(const amount_t& amt) const
{
if (commodity() != amt.commodity())
return true;
return compare(amt) != 0;
}
amount_t::operator bool() const
{
if (! quantity)
return false;
if (quantity->prec <= commodity().precision() ||
(quantity->flags & BIGINT_KEEP_PREC)) {
return mpz_sgn(MPZ(quantity)) != 0;
} else {
mpz_set(temp, MPZ(quantity));
mpz_ui_pow_ui(divisor, 10, quantity->prec - commodity().precision());
mpz_tdiv_q(temp, temp, divisor);
bool zero = mpz_sgn(temp) == 0;
return ! zero;
}
}
amount_t::operator long() const
{
if (! quantity)
return 0;
mpz_set(temp, MPZ(quantity));
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_q(temp, temp, divisor);
return mpz_get_si(temp);
}
amount_t::operator double() const
{
if (! quantity)
return 0.0;
mpz_t remainder;
mpz_init(remainder);
mpz_set(temp, MPZ(quantity));
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_qr(temp, remainder, temp, divisor);
char * quotient_s = mpz_get_str(NULL, 10, temp);
char * remainder_s = mpz_get_str(NULL, 10, remainder);
std::ostringstream num;
num << quotient_s << '.' << remainder_s;
std::free(quotient_s);
std::free(remainder_s);
mpz_clear(remainder);
return std::atof(num.str().c_str());
}
bool amount_t::realzero() const
{
if (! quantity)
return true;
return mpz_sgn(MPZ(quantity)) == 0;
}
amount_t amount_t::value(const datetime_t& moment) const
{
if (quantity) {
amount_t amt(commodity().value(moment));
if (! amt.realzero())
return (amt * *this).round();
}
return *this;
}
amount_t amount_t::round(unsigned int prec) const
{
amount_t temp = *this;
if (! quantity || quantity->prec <= prec) {
if (quantity && quantity->flags & BIGINT_KEEP_PREC) {
temp._dup();
temp.quantity->flags &= ~BIGINT_KEEP_PREC;
}
return temp;
}
temp._dup();
mpz_round(MPZ(temp.quantity), MPZ(temp.quantity), temp.quantity->prec, prec);
temp.quantity->prec = prec;
temp.quantity->flags &= ~BIGINT_KEEP_PREC;
return temp;
}
amount_t amount_t::unround() const
{
if (! quantity) {
amount_t temp(0L);
assert(temp.quantity);
temp.quantity->flags |= BIGINT_KEEP_PREC;
return temp;
}
else if (quantity->flags & BIGINT_KEEP_PREC) {
return *this;
}
amount_t temp = *this;
temp._dup();
temp.quantity->flags |= BIGINT_KEEP_PREC;
return temp;
}
std::string amount_t::quantity_string() const
{
if (! quantity)
return "0";
std::ostringstream out;
mpz_t quotient;
mpz_t rquotient;
mpz_t remainder;
mpz_init(quotient);
mpz_init(rquotient);
mpz_init(remainder);
bool negative = false;
// Ensure the value is rounded to the commodity's precision before
// outputting it. NOTE: `rquotient' is used here as a temp variable!
commodity_t& comm(commodity());
unsigned char precision;
if (! comm || quantity->flags & BIGINT_KEEP_PREC) {
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(quantity), divisor);
precision = quantity->prec;
}
else if (comm.precision() < quantity->prec) {
mpz_round(rquotient, MPZ(quantity), quantity->prec, comm.precision());
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (comm.precision() > quantity->prec) {
mpz_ui_pow_ui(divisor, 10, comm.precision() - quantity->prec);
mpz_mul(rquotient, MPZ(quantity), divisor);
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (quantity->prec) {
mpz_ui_pow_ui(divisor, 10, quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(quantity), divisor);
precision = quantity->prec;
}
else {
mpz_set(quotient, MPZ(quantity));
mpz_set_ui(remainder, 0);
precision = 0;
}
if (mpz_sgn(quotient) < 0 || mpz_sgn(remainder) < 0) {
negative = true;
mpz_abs(quotient, quotient);
mpz_abs(remainder, remainder);
}
mpz_set(rquotient, remainder);
if (mpz_sgn(quotient) == 0 && mpz_sgn(rquotient) == 0)
return "0";
if (negative)
out << "-";
if (mpz_sgn(quotient) == 0) {
out << '0';
} else {
char * p = mpz_get_str(NULL, 10, quotient);
out << p;
std::free(p);
}
if (precision) {
out << '.';
out.width(precision);
out.fill('0');
char * p = mpz_get_str(NULL, 10, rquotient);
out << p;
std::free(p);
}
mpz_clear(quotient);
mpz_clear(rquotient);
mpz_clear(remainder);
return out.str();
}
std::ostream& operator<<(std::ostream& _out, const amount_t& amt)
{
if (! amt.quantity) {
_out << "0";
return _out;
}
amount_t base(amt);
if (! amount_t::keep_base && amt.commodity().larger()) {
amount_t last(amt);
while (last.commodity().larger()) {
last /= *last.commodity().larger();
last.commodity_ = last.commodity().larger()->commodity_;
if (ledger::abs(last) < 1)
break;
base = last.round();
}
}
std::ostringstream out;
mpz_t quotient;
mpz_t rquotient;
mpz_t remainder;
mpz_init(quotient);
mpz_init(rquotient);
mpz_init(remainder);
bool negative = false;
// Ensure the value is rounded to the commodity's precision before
// outputting it. NOTE: `rquotient' is used here as a temp variable!
commodity_t& comm(base.commodity());
unsigned char precision;
if (! comm || base.quantity->flags & BIGINT_KEEP_PREC) {
mpz_ui_pow_ui(divisor, 10, base.quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(base.quantity), divisor);
precision = base.quantity->prec;
}
else if (comm.precision() < base.quantity->prec) {
mpz_round(rquotient, MPZ(base.quantity), base.quantity->prec,
comm.precision());
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (comm.precision() > base.quantity->prec) {
mpz_ui_pow_ui(divisor, 10, comm.precision() - base.quantity->prec);
mpz_mul(rquotient, MPZ(base.quantity), divisor);
mpz_ui_pow_ui(divisor, 10, comm.precision());
mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
precision = comm.precision();
}
else if (base.quantity->prec) {
mpz_ui_pow_ui(divisor, 10, base.quantity->prec);
mpz_tdiv_qr(quotient, remainder, MPZ(base.quantity), divisor);
precision = base.quantity->prec;
}
else {
mpz_set(quotient, MPZ(base.quantity));
mpz_set_ui(remainder, 0);
precision = 0;
}
if (mpz_sgn(quotient) < 0 || mpz_sgn(remainder) < 0) {
negative = true;
mpz_abs(quotient, quotient);
mpz_abs(remainder, remainder);
}
mpz_set(rquotient, remainder);
if (mpz_sgn(quotient) == 0 && mpz_sgn(rquotient) == 0) {
_out << "0";
return _out;
}
if (! (comm.flags() & COMMODITY_STYLE_SUFFIXED)) {
comm.write(out);
if (comm.flags() & COMMODITY_STYLE_SEPARATED)
out << " ";
}
if (negative)
out << "-";
if (mpz_sgn(quotient) == 0) {
out << '0';
}
else if (! (comm.flags() & COMMODITY_STYLE_THOUSANDS)) {
char * p = mpz_get_str(NULL, 10, quotient);
out << p;
std::free(p);
}
else {
std::list<std::string> strs;
char buf[4];
for (int powers = 0; true; powers += 3) {
if (powers > 0) {
mpz_ui_pow_ui(divisor, 10, powers);
mpz_tdiv_q(temp, quotient, divisor);
if (mpz_sgn(temp) == 0)
break;
mpz_tdiv_r_ui(temp, temp, 1000);
} else {
mpz_tdiv_r_ui(temp, quotient, 1000);
}
mpz_get_str(buf, 10, temp);
strs.push_back(buf);
}
bool printed = false;
for (std::list<std::string>::reverse_iterator i = strs.rbegin();
i != strs.rend();
i++) {
if (printed) {
out << (comm.flags() & COMMODITY_STYLE_EUROPEAN ? '.' : ',');
out.width(3);
out.fill('0');
}
out << *i;
printed = true;
}
}
if (precision) {
std::ostringstream final;
final.width(precision);
final.fill('0');
char * p = mpz_get_str(NULL, 10, rquotient);
final << p;
std::free(p);
const std::string& str(final.str());
int i, len = str.length();
const char * q = str.c_str();
for (i = len; i > 0; i--)
if (q[i - 1] != '0')
break;
std::string ender;
if (i == len)
ender = str;
else if (i < comm.precision())
ender = std::string(str, 0, comm.precision());
else
ender = std::string(str, 0, i);
if (! ender.empty()) {
out << ((comm.flags() & COMMODITY_STYLE_EUROPEAN) ? ',' : '.');
out << ender;
}
}
if (comm.flags() & COMMODITY_STYLE_SUFFIXED) {
if (comm.flags() & COMMODITY_STYLE_SEPARATED)
out << " ";
comm.write(out);
}
mpz_clear(quotient);
mpz_clear(rquotient);
mpz_clear(remainder);
// If there are any annotations associated with this commodity,
// output them now.
if (comm.annotated) {
annotated_commodity_t& ann(static_cast<annotated_commodity_t&>(comm));
assert(&ann.price != &amt);
ann.write_annotations(out);
}
// Things are output to a string first, so that if anyone has
// specified a width or fill for _out, it will be applied to the
// entire amount string, and not just the first part.
_out << out.str();
return _out;
}
void parse_quantity(std::istream& in, std::string& value)
{
char buf[256];
char c = peek_next_nonws(in);
READ_INTO(in, buf, 255, c,
std::isdigit(c) || c == '-' || c == '.' || c == ',');
int len = std::strlen(buf);
while (len > 0 && ! std::isdigit(buf[len - 1])) {
buf[--len] = '\0';
in.unget();
}
value = buf;
}
// Invalid commodity characters:
// SPACE, TAB, NEWLINE, RETURN
// 0-9 . , ; - + * / ^ ? : & | ! =
// < > { } [ ] ( ) @
int invalid_chars[256] = {
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/* 00 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
/* 10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 20 */ 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
/* 30 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 40 */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0,
/* 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0,
/* 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 90 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* a0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* b0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* c0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* d0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* e0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* f0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
void parse_commodity(std::istream& in, std::string& symbol)
{
char buf[256];
char c = peek_next_nonws(in);
if (c == '"') {
in.get(c);
READ_INTO(in, buf, 255, c, c != '"');
if (c == '"')
in.get(c);
else
throw new amount_error("Quoted commodity symbol lacks closing quote");
} else {
READ_INTO(in, buf, 255, c, ! invalid_chars[(unsigned char)c]);
}
symbol = buf;
}
void parse_annotations(std::istream& in, amount_t& price,
datetime_t& date, std::string& tag)
{
do {
char buf[256];
char c = peek_next_nonws(in);
if (c == '{') {
if (price)
throw new amount_error("Commodity specifies more than one price");
in.get(c);
READ_INTO(in, buf, 255, c, c != '}');
if (c == '}')
in.get(c);
else
throw new amount_error("Commodity price lacks closing brace");
price.parse(buf, AMOUNT_PARSE_NO_MIGRATE);
price.reduce();
// Since this price will maintain its own precision, make sure
// it is at least as large as the base commodity, since the user
// may have only specified {$1} or something similar.
if (price.quantity->prec < price.commodity().precision())
price = price.round(); // no need to retain individual precision
}
else if (c == '[') {
if (date)
throw new amount_error("Commodity specifies more than one date");
in.get(c);
READ_INTO(in, buf, 255, c, c != ']');
if (c == ']')
in.get(c);
else
throw new amount_error("Commodity date lacks closing bracket");
date = buf;
}
else if (c == '(') {
if (! tag.empty())
throw new amount_error("Commodity specifies more than one tag");
in.get(c);
READ_INTO(in, buf, 255, c, c != ')');
if (c == ')')
in.get(c);
else
throw new amount_error("Commodity tag lacks closing parenthesis");
tag = buf;
}
else {
break;
}
} while (true);
DEBUG_PRINT("amounts.commodities",
"Parsed commodity annotations: "
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
}
bool amount_t::parse(std::istream& in, unsigned char flags)
{
// The possible syntax for an amount is:
//
// [-]NUM[ ]SYM [@ AMOUNT]
// SYM[ ][-]NUM [@ AMOUNT]
std::string symbol;
std::string quant;
amount_t price;
datetime_t date;
std::string tag;
unsigned int comm_flags = COMMODITY_STYLE_DEFAULTS;
bool negative = false;
char c = peek_next_nonws(in);
if (c == '-') {
negative = true;
in.get(c);
c = peek_next_nonws(in);
}
char n;
if (std::isdigit(c)) {
parse_quantity(in, quant);
if (! in.eof() && ((n = in.peek()) != '\n')) {
if (std::isspace(n))
comm_flags |= COMMODITY_STYLE_SEPARATED;
parse_commodity(in, symbol);
if (! symbol.empty())
comm_flags |= COMMODITY_STYLE_SUFFIXED;
if (! in.eof() && ((n = in.peek()) != '\n'))
parse_annotations(in, price, date, tag);
}
} else {
parse_commodity(in, symbol);
if (! in.eof() && ((n = in.peek()) != '\n')) {
if (std::isspace(in.peek()))
comm_flags |= COMMODITY_STYLE_SEPARATED;
parse_quantity(in, quant);
if (! quant.empty() && ! in.eof() && ((n = in.peek()) != '\n'))
parse_annotations(in, price, date, tag);
}
}
if (quant.empty()) {
if (flags & AMOUNT_PARSE_SOFT_FAIL)
return false;
else
throw new amount_error("No quantity specified for amount");
}
_init();
// Create the commodity if has not already been seen, and update the
// precision if something greater was used for the quantity.
bool newly_created = false;
if (symbol.empty()) {
commodity_ = commodity_t::null_commodity;
} else {
commodity_ = commodity_t::find(symbol);
if (! commodity_) {
commodity_ = commodity_t::create(symbol);
newly_created = true;
}
assert(commodity_);
if (! price.realzero() || date || ! tag.empty())
commodity_ =
annotated_commodity_t::find_or_create(*commodity_, price, date, tag);
}
// Determine the precision of the amount, based on the usage of
// comma or period.
std::string::size_type last_comma = quant.rfind(',');
std::string::size_type last_period = quant.rfind('.');
if (last_comma != std::string::npos && last_period != std::string::npos) {
comm_flags |= COMMODITY_STYLE_THOUSANDS;
if (last_comma > last_period) {
comm_flags |= COMMODITY_STYLE_EUROPEAN;
quantity->prec = quant.length() - last_comma - 1;
} else {
quantity->prec = quant.length() - last_period - 1;
}
}
else if (last_comma != std::string::npos &&
(! commodity_t::default_commodity ||
commodity_t::default_commodity->flags() & COMMODITY_STYLE_EUROPEAN)) {
comm_flags |= COMMODITY_STYLE_EUROPEAN;
quantity->prec = quant.length() - last_comma - 1;
}
else if (last_period != std::string::npos &&
! (commodity().flags() & COMMODITY_STYLE_EUROPEAN)) {
quantity->prec = quant.length() - last_period - 1;
}
else {
quantity->prec = 0;
}
// Set the commodity's flags and precision accordingly
if (! (flags & AMOUNT_PARSE_NO_MIGRATE)) {
commodity().add_flags(comm_flags);
if (quantity->prec > commodity().precision())
commodity().set_precision(quantity->prec);
} else {
quantity->flags |= BIGINT_KEEP_PREC;
}
// Now we have the final number. Remove commas and periods, if
// necessary.
if (last_comma != std::string::npos || last_period != std::string::npos) {
int len = quant.length();
char * buf = new char[len + 1];
const char * p = quant.c_str();
char * t = buf;
while (*p) {
if (*p == ',' || *p == '.')
p++;
*t++ = *p++;
}
*t = '\0';
mpz_set_str(MPZ(quantity), buf, 10);
delete[] buf;
} else {
mpz_set_str(MPZ(quantity), quant.c_str(), 10);
}
if (negative)
negate();
if (! (flags & AMOUNT_PARSE_NO_REDUCE))
reduce();
return true;
}
void amount_t::reduce()
{
while (commodity_ && commodity().smaller()) {
*this *= *commodity().smaller();
commodity_ = commodity().smaller()->commodity_;
}
}
bool amount_t::parse(const std::string& str, unsigned char flags)
{
std::istringstream stream(str);
parse(stream, flags);
}
void parse_conversion(const std::string& larger_str,
const std::string& smaller_str)
{
amount_t larger, smaller;
larger.parse(larger_str.c_str(), AMOUNT_PARSE_NO_REDUCE);
smaller.parse(smaller_str.c_str(), AMOUNT_PARSE_NO_REDUCE);
larger *= smaller;
if (larger.commodity()) {
larger.commodity().set_smaller(smaller);
larger.commodity().add_flags(smaller.commodity().flags() |
COMMODITY_STYLE_NOMARKET);
}
if (smaller.commodity())
smaller.commodity().set_larger(larger);
}
char * bigints;
char * bigints_next;
unsigned int bigints_index;
unsigned int bigints_count;
void amount_t::read_quantity(char *& data)
{
char byte = *data++;;
if (byte == 0) {
quantity = NULL;
}
else if (byte == 1) {
quantity = new((bigint_t *)bigints_next) bigint_t;
bigints_next += sizeof(bigint_t);
unsigned short len = *((unsigned short *) data);
data += sizeof(unsigned short);
mpz_import(MPZ(quantity), len / sizeof(short), 1, sizeof(short),
0, 0, data);
data += len;
char negative = *data++;
if (negative)
mpz_neg(MPZ(quantity), MPZ(quantity));
quantity->prec = *((unsigned char *) data);
data += sizeof(unsigned char);
quantity->flags = *((unsigned char *) data);
data += sizeof(unsigned char);
quantity->flags |= BIGINT_BULK_ALLOC;
} else {
unsigned int index = *((unsigned int *) data);
data += sizeof(unsigned int);
quantity = (bigint_t *) (bigints + (index - 1) * sizeof(bigint_t));
DEBUG_PRINT("amounts.refs",
quantity << " ref++, now " << (quantity->ref + 1));
quantity->ref++;
}
}
static char buf[4096];
void amount_t::read_quantity(std::istream& in)
{
char byte;
in.read(&byte, sizeof(byte));
if (byte == 0) {
quantity = NULL;
}
else if (byte == 1) {
quantity = new bigint_t;
unsigned short len;
in.read((char *)&len, sizeof(len));
assert(len < 4096);
in.read(buf, len);
mpz_import(MPZ(quantity), len / sizeof(short), 1, sizeof(short),
0, 0, buf);
char negative;
in.read(&negative, sizeof(negative));
if (negative)
mpz_neg(MPZ(quantity), MPZ(quantity));
in.read((char *)&quantity->prec, sizeof(quantity->prec));
in.read((char *)&quantity->flags, sizeof(quantity->flags));
}
else {
assert(0);
}
}
void amount_t::write_quantity(std::ostream& out) const
{
char byte;
if (! quantity) {
byte = 0;
out.write(&byte, sizeof(byte));
return;
}
if (quantity->index == 0) {
quantity->index = ++bigints_index;
bigints_count++;
byte = 1;
out.write(&byte, sizeof(byte));
std::size_t size;
mpz_export(buf, &size, 1, sizeof(short), 0, 0, MPZ(quantity));
unsigned short len = size * sizeof(short);
out.write((char *)&len, sizeof(len));
if (len) {
assert(len < 4096);
out.write(buf, len);
}
byte = mpz_sgn(MPZ(quantity)) < 0 ? 1 : 0;
out.write(&byte, sizeof(byte));
out.write((char *)&quantity->prec, sizeof(quantity->prec));
unsigned char flags = quantity->flags & ~BIGINT_BULK_ALLOC;
assert(sizeof(flags) == sizeof(quantity->flags));
out.write((char *)&flags, sizeof(flags));
} else {
assert(quantity->ref > 1);
// Since this value has already been written, we simply write
// out a reference to which one it was.
byte = 2;
out.write(&byte, sizeof(byte));
out.write((char *)&quantity->index, sizeof(quantity->index));
}
}
bool amount_t::valid() const
{
if (quantity) {
if (quantity->ref == 0) {
DEBUG_PRINT("ledger.validate", "amount_t: quantity->ref == 0");
return false;
}
}
else if (commodity_) {
DEBUG_PRINT("ledger.validate", "amount_t: commodity_ != NULL");
return false;
}
return true;
}
void amount_t::annotate_commodity(const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
const commodity_t * this_base;
annotated_commodity_t * this_ann = NULL;
if (commodity().annotated) {
this_ann = &static_cast<annotated_commodity_t&>(commodity());
this_base = this_ann->ptr;
} else {
this_base = &commodity();
}
assert(this_base);
DEBUG_PRINT("amounts.commodities", "Annotating commodity for amount "
<< *this << std::endl
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
commodity_t * ann_comm =
annotated_commodity_t::find_or_create
(*this_base, ! price && this_ann ? this_ann->price : price,
! date && this_ann ? this_ann->date : date,
tag.empty() && this_ann ? this_ann->tag : tag);
if (ann_comm)
set_commodity(*ann_comm);
DEBUG_PRINT("amounts.commodities", " Annotated amount is " << *this);
}
amount_t amount_t::strip_annotations(const bool _keep_price,
const bool _keep_date,
const bool _keep_tag) const
{
if (! commodity().annotated ||
(_keep_price && _keep_date && _keep_tag))
return *this;
DEBUG_PRINT("amounts.commodities", "Reducing commodity for amount "
<< *this << std::endl
<< " keep price " << _keep_price << " "
<< " keep date " << _keep_date << " "
<< " keep tag " << _keep_tag);
annotated_commodity_t&
ann_comm(static_cast<annotated_commodity_t&>(commodity()));
assert(ann_comm.base);
commodity_t * new_comm;
if ((_keep_price && ann_comm.price) ||
(_keep_date && ann_comm.date) ||
(_keep_tag && ! ann_comm.tag.empty()))
{
new_comm = annotated_commodity_t::find_or_create
(*ann_comm.ptr, _keep_price ? ann_comm.price : amount_t(),
_keep_date ? ann_comm.date : datetime_t(),
_keep_tag ? ann_comm.tag : "");
} else {
new_comm = commodity_t::find_or_create(ann_comm.base_symbol());
}
assert(new_comm);
amount_t temp(*this);
temp.set_commodity(*new_comm);
DEBUG_PRINT("amounts.commodities", " Reduced amount is " << temp);
return temp;
}
amount_t amount_t::price() const
{
if (commodity_ && commodity_->annotated) {
amount_t temp(((annotated_commodity_t *)commodity_)->price);
temp *= *this;
DEBUG_PRINT("amounts.commodities",
"Returning price of " << *this << " = " << temp);
return temp;
}
return *this;
}
datetime_t amount_t::date() const
{
if (commodity_ && commodity_->annotated) {
DEBUG_PRINT("amounts.commodities",
"Returning date of " << *this << " = "
<< ((annotated_commodity_t *)commodity_)->date);
return ((annotated_commodity_t *)commodity_)->date;
}
return 0L;
}
void commodity_base_t::add_price(const datetime_t& date,
const amount_t& price)
{
if (! history)
history = new history_t;
history_map::iterator i = history->prices.find(date);
if (i != history->prices.end()) {
(*i).second = price;
} else {
std::pair<history_map::iterator, bool> result
= history->prices.insert(history_pair(date, price));
assert(result.second);
}
}
bool commodity_base_t::remove_price(const datetime_t& date)
{
if (history) {
history_map::size_type n = history->prices.erase(date);
if (n > 0) {
if (history->prices.empty())
history = NULL;
return true;
}
}
return false;
}
commodity_base_t * commodity_base_t::create(const std::string& symbol)
{
commodity_base_t * commodity = new commodity_base_t(symbol);
DEBUG_PRINT("amounts.commodities", "Creating base commodity " << symbol);
std::pair<base_commodities_map::iterator, bool> result
= commodities.insert(base_commodities_pair(symbol, commodity));
assert(result.second);
return commodity;
}
bool commodity_t::needs_quotes(const std::string& symbol)
{
for (const char * p = symbol.c_str(); *p; p++)
if (std::isspace(*p) || std::isdigit(*p) || *p == '-' || *p == '.')
return true;
return false;
}
bool commodity_t::valid() const
{
if (symbol().empty() && this != null_commodity) {
DEBUG_PRINT("ledger.validate",
"commodity_t: symbol().empty() && this != null_commodity");
return false;
}
if (annotated && ! base) {
DEBUG_PRINT("ledger.validate", "commodity_t: annotated && ! base");
return false;
}
if (precision() > 16) {
DEBUG_PRINT("ledger.validate", "commodity_t: precision() > 16");
return false;
}
return true;
}
commodity_t * commodity_t::create(const std::string& symbol)
{
std::auto_ptr<commodity_t> commodity(new commodity_t);
commodity->base = commodity_base_t::create(symbol);
if (needs_quotes(symbol)) {
commodity->qualified_symbol = "\"";
commodity->qualified_symbol += symbol;
commodity->qualified_symbol += "\"";
} else {
commodity->qualified_symbol = symbol;
}
DEBUG_PRINT("amounts.commodities",
"Creating commodity " << commodity->qualified_symbol);
std::pair<commodities_map::iterator, bool> result
= commodities.insert(commodities_pair(symbol, commodity.get()));
if (! result.second)
return NULL;
// Start out the new commodity with the default commodity's flags
// and precision, if one has been defined.
if (default_commodity)
commodity->drop_flags(COMMODITY_STYLE_THOUSANDS |
COMMODITY_STYLE_NOMARKET);
return commodity.release();
}
commodity_t * commodity_t::find_or_create(const std::string& symbol)
{
DEBUG_PRINT("amounts.commodities", "Find-or-create commodity " << symbol);
commodity_t * commodity = find(symbol);
if (commodity)
return commodity;
return create(symbol);
}
commodity_t * commodity_t::find(const std::string& symbol)
{
DEBUG_PRINT("amounts.commodities", "Find commodity " << symbol);
commodities_map::const_iterator i = commodities.find(symbol);
if (i != commodities.end())
return (*i).second;
return NULL;
}
amount_t commodity_base_t::value(const datetime_t& moment)
{
datetime_t age;
amount_t price;
if (history) {
assert(history->prices.size() > 0);
if (! moment) {
history_map::reverse_iterator r = history->prices.rbegin();
age = (*r).first;
price = (*r).second;
} else {
history_map::iterator i = history->prices.lower_bound(moment);
if (i == history->prices.end()) {
history_map::reverse_iterator r = history->prices.rbegin();
age = (*r).first;
price = (*r).second;
} else {
age = (*i).first;
if (moment != age) {
if (i != history->prices.begin()) {
--i;
age = (*i).first;
price = (*i).second;
} else {
age = 0;
}
} else {
price = (*i).second;
}
}
}
}
if (updater && ! (flags & COMMODITY_STYLE_NOMARKET))
(*updater)(*this, moment, age,
(history && history->prices.size() > 0 ?
(*history->prices.rbegin()).first : datetime_t()), price);
return price;
}
bool annotated_commodity_t::operator==(const commodity_t& comm) const
{
// If the base commodities don't match, the game's up.
if (base != comm.base)
return false;
if (price &&
(! comm.annotated ||
price != static_cast<const annotated_commodity_t&>(comm).price))
return false;
if (date &&
(! comm.annotated ||
date != static_cast<const annotated_commodity_t&>(comm).date))
return false;
if (! tag.empty() &&
(! comm.annotated ||
tag != static_cast<const annotated_commodity_t&>(comm).tag))
return false;
return true;
}
void
annotated_commodity_t::write_annotations(std::ostream& out,
const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
if (price)
out << " {" << price << '}';
if (date)
out << " [" << date << ']';
if (! tag.empty())
out << " (" << tag << ')';
}
commodity_t *
annotated_commodity_t::create(const commodity_t& comm,
const amount_t& price,
const datetime_t& date,
const std::string& tag,
const std::string& mapping_key)
{
std::auto_ptr<annotated_commodity_t> commodity(new annotated_commodity_t);
// Set the annotated bits
commodity->price = price;
commodity->date = date;
commodity->tag = tag;
commodity->ptr = &comm;
assert(commodity->ptr);
commodity->base = comm.base;
assert(commodity->base);
commodity->qualified_symbol = comm.symbol();
DEBUG_PRINT("amounts.commodities", "Creating annotated commodity "
<< "symbol " << commodity->symbol()
<< " key " << mapping_key << std::endl
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
// Add the fully annotated name to the map, so that this symbol may
// quickly be found again.
std::pair<commodities_map::iterator, bool> result
= commodities.insert(commodities_pair(mapping_key, commodity.get()));
if (! result.second)
return NULL;
return commodity.release();
}
namespace {
std::string make_qualified_name(const commodity_t& comm,
const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
if (price < 0)
throw new amount_error("A commodity's price may not be negative");
std::ostringstream name;
comm.write(name);
annotated_commodity_t::write_annotations(name, price, date, tag);
DEBUG_PRINT("amounts.commodities", "make_qualified_name for "
<< comm.qualified_symbol << std::endl
<< " price " << price << " "
<< " date " << date << " "
<< " tag " << tag);
DEBUG_PRINT("amounts.commodities", "qualified_name is " << name.str());
return name.str();
}
}
commodity_t *
annotated_commodity_t::find_or_create(const commodity_t& comm,
const amount_t& price,
const datetime_t& date,
const std::string& tag)
{
std::string name = make_qualified_name(comm, price, date, tag);
commodity_t * ann_comm = commodity_t::find(name);
if (ann_comm) {
assert(ann_comm->annotated);
return ann_comm;
}
return create(comm, price, date, tag, name);
}
bool compare_amount_commodities::operator()(const amount_t * left,
const amount_t * right) const
{
commodity_t& leftcomm(left->commodity());
commodity_t& rightcomm(right->commodity());
int cmp = leftcomm.base_symbol().compare(rightcomm.base_symbol());
if (cmp != 0)
return cmp < 0;
if (! leftcomm.annotated) {
assert(rightcomm.annotated);
return true;
}
else if (! rightcomm.annotated) {
assert(leftcomm.annotated);
return false;
}
else {
annotated_commodity_t& aleftcomm(static_cast<annotated_commodity_t&>(leftcomm));
annotated_commodity_t& arightcomm(static_cast<annotated_commodity_t&>(rightcomm));
if (! aleftcomm.price && arightcomm.price)
return true;
if (aleftcomm.price && ! arightcomm.price)
return false;
if (aleftcomm.price && arightcomm.price) {
amount_t leftprice(aleftcomm.price);
leftprice.reduce();
amount_t rightprice(arightcomm.price);
rightprice.reduce();
if (leftprice.commodity() == rightprice.commodity()) {
int diff = leftprice.compare(rightprice);
if (diff)
return diff;
} else {
// Since we have two different amounts, there's really no way
// to establish a true sorting order; we'll just do it based
// on the numerical values.
leftprice.clear_commodity();
rightprice.clear_commodity();
int diff = leftprice.compare(rightprice);
if (diff)
return diff;
}
}
if (! aleftcomm.date && arightcomm.date)
return true;
if (aleftcomm.date && ! arightcomm.date)
return false;
if (aleftcomm.date && arightcomm.date) {
int diff = aleftcomm.date - arightcomm.date;
if (diff)
return diff < 0;
}
if (aleftcomm.tag.empty() && ! arightcomm.tag.empty())
return true;
if (! aleftcomm.tag.empty() && arightcomm.tag.empty())
return false;
if (! aleftcomm.tag.empty() && ! arightcomm.tag.empty())
return aleftcomm.tag < arightcomm.tag;
// The two annotated commodities don't differ enough to matter. This
// should make this identical.
return true;
}
}
} // namespace ledger
#ifdef USE_BOOST_PYTHON
#include <boost/python.hpp>
#include <Python.h>
using namespace boost::python;
using namespace ledger;
int py_amount_quantity(amount_t& amount)
{
std::string quant = amount.quantity_string();
return std::atol(quant.c_str());
}
void py_parse_1(amount_t& amount, const std::string& str,
unsigned char flags) {
amount.parse(str, flags);
}
void py_parse_2(amount_t& amount, const std::string& str) {
amount.parse(str);
}
struct commodity_updater_wrap : public commodity_base_t::updater_t
{
PyObject * self;
commodity_updater_wrap(PyObject * self_) : self(self_) {}
virtual void operator()(commodity_base_t& commodity,
const datetime_t& moment,
const datetime_t& date,
const datetime_t& last,
amount_t& price) {
call_method<void>(self, "__call__", commodity, moment, date, last, price);
}
};
commodity_t * py_find_commodity(const std::string& symbol)
{
return commodity_t::find(symbol);
}
#define EXC_TRANSLATOR(type) \
void exc_translate_ ## type(const type& err) { \
PyErr_SetString(PyExc_RuntimeError, err.what()); \
}
EXC_TRANSLATOR(amount_error)
void export_amount()
{
scope().attr("AMOUNT_PARSE_NO_MIGRATE") = AMOUNT_PARSE_NO_MIGRATE;
scope().attr("AMOUNT_PARSE_NO_REDUCE") = AMOUNT_PARSE_NO_REDUCE;
class_< amount_t > ("Amount")
.def(init<amount_t>())
.def(init<std::string>())
.def(init<char *>())
.def(init<bool>())
.def(init<long>())
.def(init<unsigned long>())
.def(init<double>())
.def(self += self)
.def(self += long())
.def(self + self)
.def(self + long())
.def(self -= self)
.def(self -= long())
.def(self - self)
.def(self - long())
.def(self *= self)
.def(self *= long())
.def(self * self)
.def(self * long())
.def(self /= self)
.def(self /= long())
.def(self / self)
.def(self / long())
.def(- self)
.def(self < self)
.def(self < long())
.def(self <= self)
.def(self <= long())
.def(self > self)
.def(self > long())
.def(self >= self)
.def(self >= long())
.def(self == self)
.def(self == long())
.def(self != self)
.def(self != long())
.def(! self)
.def(self_ns::int_(self))
.def(self_ns::float_(self))
.def(self_ns::str(self))
.def(abs(self))
.add_property("commodity",
make_function(&amount_t::commodity,
return_value_policy<reference_existing_object>()),
make_function(&amount_t::set_commodity,
with_custodian_and_ward<1, 2>()))
.def("strip_annotations", &amount_t::strip_annotations)
.def("negate", &amount_t::negate)
.def("negated", &amount_t::negated)
.def("parse", py_parse_1)
.def("parse", py_parse_2)
.def("reduce", &amount_t::reduce)
.def("valid", &amount_t::valid)
;
class_< commodity_base_t::updater_t, commodity_updater_wrap,
boost::noncopyable >
("Updater")
;
scope().attr("COMMODITY_STYLE_DEFAULTS") = COMMODITY_STYLE_DEFAULTS;
scope().attr("COMMODITY_STYLE_SUFFIXED") = COMMODITY_STYLE_SUFFIXED;
scope().attr("COMMODITY_STYLE_SEPARATED") = COMMODITY_STYLE_SEPARATED;
scope().attr("COMMODITY_STYLE_EUROPEAN") = COMMODITY_STYLE_EUROPEAN;
scope().attr("COMMODITY_STYLE_THOUSANDS") = COMMODITY_STYLE_THOUSANDS;
scope().attr("COMMODITY_STYLE_NOMARKET") = COMMODITY_STYLE_NOMARKET;
scope().attr("COMMODITY_STYLE_BUILTIN") = COMMODITY_STYLE_BUILTIN;
class_< commodity_t > ("Commodity")
.add_property("symbol", &commodity_t::symbol)
#if 0
.add_property("name", &commodity_t::name, &commodity_t::set_name)
.add_property("note", &commodity_t::note, &commodity_t::set_note)
.add_property("precision", &commodity_t::precision,
&commodity_t::set_precision)
.add_property("flags", &commodity_t::flags, &commodity_t::set_flags)
.add_property("add_flags", &commodity_t::add_flags)
.add_property("drop_flags", &commodity_t::drop_flags)
#if 0
.add_property("updater", &commodity_t::updater)
#endif
.add_property("smaller",
make_getter(&commodity_t::smaller,
return_value_policy<reference_existing_object>()),
make_setter(&commodity_t::smaller,
return_value_policy<reference_existing_object>()))
.add_property("larger",
make_getter(&commodity_t::larger,
return_value_policy<reference_existing_object>()),
make_setter(&commodity_t::larger,
return_value_policy<reference_existing_object>()))
.def(self_ns::str(self))
.def("find", py_find_commodity,
return_value_policy<reference_existing_object>())
.staticmethod("find")
#endif
.def("add_price", &commodity_t::add_price)
.def("remove_price", &commodity_t::remove_price)
.def("value", &commodity_t::value)
.def("valid", &commodity_t::valid)
;
#define EXC_TRANSLATE(type) \
register_exception_translator<type>(&exc_translate_ ## type);
EXC_TRANSLATE(amount_error);
}
#endif // USE_BOOST_PYTHON
|
/*
OFX Transform plugin.
Copyright (C) 2014 INRIA
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
INRIA
Domaine de Voluceau
Rocquencourt - B.P. 105
78153 Le Chesnay Cedex - France
The skeleton for this source file is from:
OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.
Copyright (C) 2004-2005 The Open Effects Association Ltd
Author Bruno Nicoletti bruno@thefoundry.co.uk
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name The Open Effects Association Ltd, nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The Open Effects Association Ltd
1 Wardour St
London W1D 6PA
England
*/
#include "Transform.h"
#include <cmath>
#ifdef _WINDOWS
#include <windows.h>
#endif
#include "../include/ofxsProcessing.H"
#include "GenericTransform.h"
#define kTranslateParamName "Translate"
#define kRotateParamName "Rotate"
#define kScaleParamName "Scale"
#define kSkewParamName "Skew"
#define kCenterParamName "Center"
#define kFilterParamName "Filter"
#define kBlackOutsideParamName "Black outside"
static const double pi=3.14159265358979323846264338327950288419717;
using namespace OFX;
class TransformProcessorBase : public OFX::ImageProcessor
{
public:
protected :
OFX::Image *_srcImg;
Transform2D::Matrix3x3 _transform;
int _filter;
bool _blackOutside;
OfxRectI _srcRod;
public :
TransformProcessorBase(OFX::ImageEffect &instance)
: OFX::ImageProcessor(instance)
, _srcImg(0)
{
}
void setSrcImg(OFX::Image *v) {_srcImg = v;}
void setValues(const OfxPointD& translate,
double rotate,
const OfxPointD& scale,
double skew,
const OfxPointD& center,
int filter,
bool blackOutside,
const OfxRectI& srcRod)
{
_transform = Transform2D::Matrix3x3::getTransform(translate, scale, skew, rotate, center);
_filter = filter;
_blackOutside = blackOutside;
_srcRod = srcRod;
}
};
static void normalize(double *x,double *y,double x1,double x2,double y1,double y2)
{
*x = (*x - x1) / (x2 - x1);
*y = (*y - y1) / (y2 - y1);
}
static void denormalize(double* x,double *y,const OfxRectD& rod)
{
*x = *x * (rod.x2 - rod.x1);
*y = *y * (rod.y2 - rod.y1);
}
template <class PIX, int nComponents, int maxValue>
class TransformProcessor : public TransformProcessorBase
{
public :
TransformProcessor(OFX::ImageEffect &instance)
: TransformProcessorBase(instance)
{
}
void multiThreadProcessImages(OfxRectI procWindow)
{
for(int y = procWindow.y1; y < procWindow.y2; y++)
{
///convert to a normalized 0 ,1 coordinate
Transform2D::Point3D normalizedCoords;
normalizedCoords.z = 1;
normalizedCoords.y = (double)y; //(y - dstRod.y1) / (double)(dstRod.y2 - dstRod.y1);
PIX *dstPix = (PIX *) _dstImg->getPixelAddress(procWindow.x1, y);
for(int x = procWindow.x1; x < procWindow.x2; x++)
{
normalizedCoords.x = (double)x;//(x - dstRod.x1) / (double)(dstRod.x2 - dstRod.x1);
Transform2D::Point3D transformed = _transform * normalizedCoords;
//transformed.x = transformed.x * (double)(_srcRod.x2 - _srcRod.x1);
// transformed.y = transformed.y * (double)(_srcRod.y2 - _srcRod.y1);
if (!_srcImg || transformed.z == 0.) {
// the back-transformed point is at infinity
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
} else {
double fx = transformed.x / transformed.z;
double fy = transformed.y / transformed.z;
OfxRectI bounds = _srcImg->getBounds();
if (_filter == 0) {
///nearest neighboor
int x = std::floor(fx+0.5);
int y = std::floor(fy+0.5);
if (!_blackOutside) {
x = std::max(bounds.x1,std::min(x,bounds.x2-1));
y = std::max(bounds.y1,std::min(y,bounds.y2-1));
}
PIX *srcPix = (PIX *)_srcImg->getPixelAddress(x, y);
if (srcPix) {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = srcPix[c];
}
} else {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
}
} else if (_filter == 1) {
// bilinear
int x = std::floor(fx);
int y = std::floor(fy);
int nx = x + 1;
int ny = y + 1;
if (!_blackOutside) {
x = std::max(bounds.x1,std::min(x,bounds.x2-1));
y = std::max(bounds.y1,std::min(y,bounds.y2-1));
}
nx = std::max(bounds.x1,std::min(nx,bounds.x2-1));
ny = std::max(bounds.y1,std::min(ny,bounds.y2-1));
const double dx = std::max(0., std::min(fx - x, 1.));
const double dy = std::max(0., std::min(fy - y, 1.));
PIX *Pcc = (PIX *)_srcImg->getPixelAddress( x, y);
PIX *Pnc = (PIX *)_srcImg->getPixelAddress(nx, y);
PIX *Pcn = (PIX *)_srcImg->getPixelAddress( x, ny);
PIX *Pnn = (PIX *)_srcImg->getPixelAddress(nx, ny);
if (Pcc && Pnc && Pcn && Pnn) {
for(int c = 0; c < nComponents; ++c) {
const double Icc = Pcc[c];
const double Inc = Pnc[c];
const double Icn = Pcn[c];
const double Inn = Pnn[c];
dstPix[c] = Icc + dx*(Inc-Icc + dy*(Icc+Inn-Icn-Inc)) + dy*(Icn-Icc);
}
} else {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
}
} else if (_filter == 2) {
// bicubic
int x = std::floor(fx);
int y = std::floor(fy);
int px = x - 1;
int py = y - 1;
int nx = x + 1;
int ny = y + 1;
int ax = x + 2;
int ay = y + 2;
if (!_blackOutside) {
x = std::max(bounds.x1,std::min(x,bounds.x2-1));
y = std::max(bounds.y1,std::min(y,bounds.y2-1));
}
px = std::max(bounds.x1,std::min(px,bounds.x2-1));
py = std::max(bounds.y1,std::min(py,bounds.y2-1));
nx = std::max(bounds.x1,std::min(nx,bounds.x2-1));
ny = std::max(bounds.y1,std::min(ny,bounds.y2-1));
ax = std::max(bounds.x1,std::min(ax,bounds.x2-1));
ay = std::max(bounds.y1,std::min(ay,bounds.y2-1));
const double dx = std::max(0., std::min(fx - x, 1.));
const double dy = std::max(0., std::min(fy - y, 1.));
PIX *Ppp = (PIX *)_srcImg->getPixelAddress(px, py);
PIX *Pcp = (PIX *)_srcImg->getPixelAddress( x, py);
PIX *Pnp = (PIX *)_srcImg->getPixelAddress(nx, py);
PIX *Pap = (PIX *)_srcImg->getPixelAddress(nx, py);
PIX *Ppc = (PIX *)_srcImg->getPixelAddress(px, y);
PIX *Pcc = (PIX *)_srcImg->getPixelAddress( x, y);
PIX *Pnc = (PIX *)_srcImg->getPixelAddress(nx, y);
PIX *Pac = (PIX *)_srcImg->getPixelAddress(nx, y);
PIX *Ppn = (PIX *)_srcImg->getPixelAddress(px, ny);
PIX *Pcn = (PIX *)_srcImg->getPixelAddress( x, ny);
PIX *Pnn = (PIX *)_srcImg->getPixelAddress(nx, ny);
PIX *Pan = (PIX *)_srcImg->getPixelAddress(nx, ny);
PIX *Ppa = (PIX *)_srcImg->getPixelAddress(px, ay);
PIX *Pca = (PIX *)_srcImg->getPixelAddress( x, ay);
PIX *Pna = (PIX *)_srcImg->getPixelAddress(nx, ay);
PIX *Paa = (PIX *)_srcImg->getPixelAddress(nx, ay);
if (Ppp && Pcp && Pnp && Pap && Ppc && Pcc && Pnc && Pac && Ppn && Pcn && Pnn && Pan && Ppa && Pca && Pna && Paa) {
for(int c = 0; c < nComponents; ++c) {
double Ipp = Ppp[c];
double Icp = Pcp[c];
double Inp = Pnp[c];
double Iap = Pap[c];
double Ipc = Ppc[c];
double Icc = Pcc[c];
double Inc = Pnc[c];
double Iac = Pac[c];
double Ipn = Ppn[c];
double Icn = Pcn[c];
double Inn = Pnn[c];
double Ian = Pan[c];
double Ipa = Ppa[c];
double Ica = Pca[c];
double Ina = Pna[c];
double Iaa = Paa[c];
double Ip = Icp + 0.5f*(dx*(-Ipp+Inp) + dx*dx*(2*Ipp-5*Icp+4*Inp-Iap) + dx*dx*dx*(-Ipp+3*Icp-3*Inp+Iap));
double Ic = Icc + 0.5f*(dx*(-Ipc+Inc) + dx*dx*(2*Ipc-5*Icc+4*Inc-Iac) + dx*dx*dx*(-Ipc+3*Icc-3*Inc+Iac));
double In = Icn + 0.5f*(dx*(-Ipn+Inn) + dx*dx*(2*Ipn-5*Icn+4*Inn-Ian) + dx*dx*dx*(-Ipn+3*Icn-3*Inn+Ian));
double Ia = Ica + 0.5f*(dx*(-Ipa+Ina) + dx*dx*(2*Ipa-5*Ica+4*Ina-Iaa) + dx*dx*dx*(-Ipa+3*Ica-3*Ina+Iaa));
dstPix[c] = Ic + 0.5f*(dy*(-Ip+In) + dy*dy*(2*Ip-5*Ic+4*In-Ia) + dy*dy*dy*(-Ip+3*Ic-3*In+Ia));
}
} else {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
}
}
}
dstPix += nComponents;
}
}
}
};
////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class TransformPlugin : public OFX::ImageEffect {
protected :
// do not need to delete these, the ImageEffect is managing them for us
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
OFX::Double2DParam* _translate;
OFX::DoubleParam* _rotate;
OFX::Double2DParam* _scale;
OFX::DoubleParam* _skew;
OFX::Double2DParam* _center;
OFX::ChoiceParam* _filter;
OFX::BooleanParam* _blackOutside;
public :
/** @brief ctor */
TransformPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
{
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
_translate = fetchDouble2DParam(kTranslateParamName);
_rotate = fetchDoubleParam(kRotateParamName);
_scale = fetchDouble2DParam(kScaleParamName);
_skew = fetchDoubleParam(kSkewParamName);
_center = fetchDouble2DParam(kCenterParamName);
_filter = fetchChoiceParam(kFilterParamName);
_blackOutside = fetchBooleanParam(kBlackOutsideParamName);
}
virtual bool getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod);
/* Override the render */
virtual void render(const OFX::RenderArguments &args);
virtual bool isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime);
/* set up and run a processor */
void setupAndProcess(TransformProcessorBase &, const OFX::RenderArguments &args);
};
////////////////////////////////////////////////////////////////////////////////
/** @brief render for the filter */
////////////////////////////////////////////////////////////////////////////////
// basic plugin render function, just a skelington to instantiate templates from
/* set up and run a processor */
void
TransformPlugin::setupAndProcess(TransformProcessorBase &processor, const OFX::RenderArguments &args)
{
std::auto_ptr<OFX::Image> dst(dstClip_->fetchImage(args.time));
std::auto_ptr<OFX::Image> src(srcClip_->fetchImage(args.time));
if(src.get() && dst.get())
{
OFX::BitDepthEnum dstBitDepth = dst->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dst->getPixelComponents();
OFX::BitDepthEnum srcBitDepth = src->getPixelDepth();
OFX::PixelComponentEnum srcComponents = src->getPixelComponents();
if(srcBitDepth != dstBitDepth || srcComponents != dstComponents)
throw int(1);
OfxPointD extent = getProjectExtent();
OfxPointD offset = getProjectOffset();
OfxPointD scale;
OfxPointD translate;
double rotate;
OfxPointD center;
int filter;
bool blackOutside;
double skew;
_scale->getValue(scale.x, scale.y);
_translate->getValue(translate.x, translate.y);
translate.x *= (extent.x - offset.x);
translate.y *= (extent.y - offset.y);
_rotate->getValue(rotate);
///convert to radians
rotate = rotate * pi / 180.0;
_center->getValue(center.x, center.y);
center.x *= (extent.x - offset.x);
center.y *= (extent.y - offset.y);
_filter->getValue(filter);
_blackOutside->getValue(blackOutside);
_skew->getValue(skew);
processor.setValues(translate, rotate, scale, skew, center, filter, blackOutside, src->getRegionOfDefinition());
}
processor.setDstImg(dst.get());
processor.setSrcImg(src.get());
processor.setRenderWindow(args.renderWindow);
processor.process();
}
bool
TransformPlugin::getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod)
{
OfxRectD srcRoD = srcClip_->getRegionOfDefinition(args.time);
OfxPointD extent = getProjectExtent();
OfxPointD offset = getProjectOffset();
OfxPointD scale;
OfxPointD translate;
double rotate;
OfxPointD center;
int filter;
double skew;
_scale->getValue(scale.x, scale.y);
_translate->getValue(translate.x, translate.y);
translate.x *= (extent.x - offset.x);
translate.y *= (extent.y - offset.y);
_rotate->getValue(rotate);
///convert to radians
rotate = rotate * pi / 180.0;
_center->getValue(center.x, center.y);
center.x *= (extent.x - offset.x);
center.y *= (extent.y - offset.y);
_filter->getValue(filter);
_skew->getValue(skew);
Transform2D::Matrix3x3 transform = Transform2D::Matrix3x3::getTransform(translate, scale, skew, rotate, center);
transform = transform.invert();
/// now transform the 4 corners of the initial image
Transform2D::Point3D topLeft = transform * Transform2D::Point3D(srcRoD.x1,srcRoD.y2,1);
Transform2D::Point3D topRight = transform * Transform2D::Point3D(srcRoD.x2,srcRoD.y2,1);
Transform2D::Point3D bottomLeft = transform * Transform2D::Point3D(srcRoD.x1,srcRoD.y1,1);
Transform2D::Point3D bottomRight = transform * Transform2D::Point3D(srcRoD.x2,srcRoD.y1,1);
double l = std::min(std::min(std::min(topLeft.x, bottomLeft.x),topRight.x),bottomRight.x);
double b = std::min(std::min(std::min(bottomLeft.y, bottomRight.y),topLeft.y),topRight.y);
double r = std::max(std::max(std::max(topRight.x, bottomRight.x),topLeft.x),bottomLeft.x);
double t = std::max(std::max(std::max(topLeft.y, topRight.y),bottomLeft.y),bottomRight.y);
// denormalize(&l, &b, srcRoD);
// denormalize(&r, &t, srcRoD);
rod.x1 = (int)std::ceil(l);
rod.x2 = (int)std::floor(r);
rod.y1 = (int)std::ceil(b);
rod.y2 = (int)std::floor(t);
return true;
}
// the overridden render function
void
TransformPlugin::render(const OFX::RenderArguments &args)
{
// instantiate the render code based on the pixel depth of the dst clip
OFX::BitDepthEnum dstBitDepth = dstClip_->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dstClip_->getPixelComponents();
assert(dstComponents == OFX::ePixelComponentRGB || dstComponents == OFX::ePixelComponentRGBA);
if(dstComponents == OFX::ePixelComponentRGBA)
{
switch(dstBitDepth)
{
case OFX::eBitDepthUByte :
{
TransformProcessor<unsigned char, 4, 255> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthUShort :
{
TransformProcessor<unsigned short, 4, 65535> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthFloat :
{
TransformProcessor<float,4,1> fred(*this);
setupAndProcess(fred, args);
break;
}
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
else
{
switch(dstBitDepth)
{
case OFX::eBitDepthUByte :
{
TransformProcessor<unsigned char, 3, 255> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthUShort :
{
TransformProcessor<unsigned short, 3, 65535> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthFloat :
{
TransformProcessor<float,3,1> fred(*this);
setupAndProcess(fred, args);
break;
}
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
}
bool TransformPlugin::isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime)
{
OfxPointD scale;
OfxPointD translate;
double rotate;
double skew;
_scale->getValue(scale.x, scale.y);
_translate->getValue(translate.x, translate.y);
_rotate->getValue(rotate);
_skew->getValue(skew);
if (scale.x == 1. && scale.y == 1. && translate.x == 0 && translate.y == 0 && rotate == 0 && skew == 0) {
identityClip = srcClip_;
identityTime = args.time;
return true;
}
return false;
}
void TransformPluginFactory::load()
{
}
void TransformPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabels("TransformOFX", "TransformOFX", "TransformOFX");
desc.setPluginGrouping("Transform");
desc.setPluginDescription("Translate / Rotate / Scale a 2D image.");
desc.addSupportedContext(eContextFilter);
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextPaint);
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthFloat);
// set a few flags
desc.setSingleInstance(false);
desc.setHostFrameThreading(false);
desc.setSupportsMultiResolution(true);
desc.setSupportsTiles(false);
desc.setTemporalClipAccess(false);
desc.setRenderTwiceAlways(false);
desc.setSupportsMultipleClipPARs(false);
desc.setRenderThreadSafety(OFX::eRenderFullySafe);
}
void TransformPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum context)
{
if (!OFX::getImageEffectHostDescription()->supportsParametricParameter) {
throwHostMissingSuiteException(kOfxParametricParameterSuite);
}
// Source clip only in the filter context
// create the mandated source clip
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->addSupportedComponent(ePixelComponentRGB);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(true);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->setSupportsTiles(true);
// make some pages and to things in
PageParamDescriptor *page = desc.definePageParam("Controls");
Double2DParamDescriptor* translate = desc.defineDouble2DParam(kTranslateParamName);
translate->setLabels(kTranslateParamName, kTranslateParamName, kTranslateParamName);
translate->setDoubleType(OFX::eDoubleTypeNormalisedXY);
translate->setDefault(0, 0);
page->addChild(*translate);
DoubleParamDescriptor* rotate = desc.defineDoubleParam(kRotateParamName);
rotate->setLabels(kRotateParamName, kRotateParamName, kRotateParamName);
rotate->setDefault(0);
rotate->setRange(-180, 180);
rotate->setDisplayRange(-180, 180);
page->addChild(*rotate);
Double2DParamDescriptor* scale = desc.defineDouble2DParam(kScaleParamName);
scale->setLabels(kScaleParamName, kScaleParamName, kScaleParamName);
scale->setDefault(1,1);
scale->setRange(0.1,0.1,10,10);
scale->setDisplayRange(0.1, 0.1, 10, 10);
page->addChild(*scale);
DoubleParamDescriptor* skew = desc.defineDoubleParam(kSkewParamName);
skew->setLabels(kSkewParamName, kSkewParamName, kSkewParamName);
skew->setDefault(0);
skew->setRange(-1, 1);
skew->setDisplayRange(-1,1);
page->addChild(*skew);
Double2DParamDescriptor* center = desc.defineDouble2DParam(kCenterParamName);
center->setLabels(kCenterParamName, kCenterParamName, kCenterParamName);
center->setDoubleType(OFX::eDoubleTypeNormalisedXY);
center->setDefault(0.5, 0.5);
page->addChild(*center);
ChoiceParamDescriptor* filter = desc.defineChoiceParam(kFilterParamName);
filter->setLabels(kFilterParamName, kFilterParamName, kFilterParamName);
filter->setDefault(0);
filter->appendOption("Nearest neighboor");
filter->appendOption("Bilinear");
filter->appendOption("Bicubic");
filter->setAnimates(false);
page->addChild(*filter);
BooleanParamDescriptor* blackOutside = desc.defineBooleanParam(kBlackOutsideParamName);
blackOutside->setLabels(kBlackOutsideParamName, kBlackOutsideParamName, kBlackOutsideParamName);
blackOutside->setDefault(false);
blackOutside->setAnimates(false);
page->addChild(*blackOutside);
}
OFX::ImageEffect* TransformPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)
{
return new TransformPlugin(handle);
}
Transform: mark generic and non-generic parts
/*
OFX Transform plugin.
Copyright (C) 2014 INRIA
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
INRIA
Domaine de Voluceau
Rocquencourt - B.P. 105
78153 Le Chesnay Cedex - France
The skeleton for this source file is from:
OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.
Copyright (C) 2004-2005 The Open Effects Association Ltd
Author Bruno Nicoletti bruno@thefoundry.co.uk
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name The Open Effects Association Ltd, nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The Open Effects Association Ltd
1 Wardour St
London W1D 6PA
England
*/
#include "Transform.h"
#include <cmath>
#ifdef _WINDOWS
#include <windows.h>
#endif
#include "../include/ofxsProcessing.H"
#include "GenericTransform.h"
#define kTranslateParamName "Translate"
#define kRotateParamName "Rotate"
#define kScaleParamName "Scale"
#define kSkewParamName "Skew"
#define kCenterParamName "Center"
#define kFilterParamName "Filter"
#define kBlackOutsideParamName "Black outside"
static const double pi=3.14159265358979323846264338327950288419717;
using namespace OFX;
class TransformProcessorBase : public OFX::ImageProcessor
{
protected:
OFX::Image *_srcImg;
// NON-GENERIC PARAMETERS:
Transform2D::Matrix3x3 _transform;
// GENERIC PARAMETERS:
int _filter;
bool _blackOutside;
public:
TransformProcessorBase(OFX::ImageEffect &instance)
: OFX::ImageProcessor(instance)
, _srcImg(0)
{
}
void setSrcImg(OFX::Image *v) {_srcImg = v;}
void setValues(const OfxPointD& translate, //!< non-generic
double rotate, //!< non-generic
const OfxPointD& scale, //!< non-generic
double skew, //!< non-generic
const OfxPointD& center, //!< non-generic
int filter, //!< generic
bool blackOutside) //!< generic
{
// NON-GENERIC
_transform = Transform2D::Matrix3x3::getTransform(translate, scale, skew, rotate, center);
// GENERIC
_filter = filter;
_blackOutside = blackOutside;
}
};
static void normalize(double *x,double *y,double x1,double x2,double y1,double y2)
{
*x = (*x - x1) / (x2 - x1);
*y = (*y - y1) / (y2 - y1);
}
static void denormalize(double* x,double *y,const OfxRectD& rod)
{
*x = *x * (rod.x2 - rod.x1);
*y = *y * (rod.y2 - rod.y1);
}
template <class PIX, int nComponents, int maxValue>
class TransformProcessor : public TransformProcessorBase
{
public :
TransformProcessor(OFX::ImageEffect &instance)
: TransformProcessorBase(instance)
{
}
void multiThreadProcessImages(OfxRectI procWindow)
{
for(int y = procWindow.y1; y < procWindow.y2; y++)
{
///convert to a normalized 0 ,1 coordinate
Transform2D::Point3D normalizedCoords;
normalizedCoords.z = 1;
normalizedCoords.y = (double)y; //(y - dstRod.y1) / (double)(dstRod.y2 - dstRod.y1);
PIX *dstPix = (PIX *) _dstImg->getPixelAddress(procWindow.x1, y);
for(int x = procWindow.x1; x < procWindow.x2; x++)
{
// NON-GENERIC TRANSFORM
normalizedCoords.x = (double)x;//(x - dstRod.x1) / (double)(dstRod.x2 - dstRod.x1);
Transform2D::Point3D transformed = _transform * normalizedCoords;
if (!_srcImg || transformed.z == 0.) {
// the back-transformed point is at infinity
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
} else {
double fx = transformed.x / transformed.z;
double fy = transformed.y / transformed.z;
// GENERIC TRANSFORM
// from here on, everything is generic, and should be moved to a generic transform class
OfxRectI bounds = _srcImg->getBounds();
if (_filter == 0) {
///nearest neighboor
int x = std::floor(fx+0.5);
int y = std::floor(fy+0.5);
if (!_blackOutside) {
x = std::max(bounds.x1,std::min(x,bounds.x2-1));
y = std::max(bounds.y1,std::min(y,bounds.y2-1));
}
PIX *srcPix = (PIX *)_srcImg->getPixelAddress(x, y);
if (srcPix) {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = srcPix[c];
}
} else {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
}
} else if (_filter == 1) {
// bilinear
int x = std::floor(fx);
int y = std::floor(fy);
int nx = x + 1;
int ny = y + 1;
if (!_blackOutside) {
x = std::max(bounds.x1,std::min(x,bounds.x2-1));
y = std::max(bounds.y1,std::min(y,bounds.y2-1));
}
nx = std::max(bounds.x1,std::min(nx,bounds.x2-1));
ny = std::max(bounds.y1,std::min(ny,bounds.y2-1));
const double dx = std::max(0., std::min(fx - x, 1.));
const double dy = std::max(0., std::min(fy - y, 1.));
PIX *Pcc = (PIX *)_srcImg->getPixelAddress( x, y);
PIX *Pnc = (PIX *)_srcImg->getPixelAddress(nx, y);
PIX *Pcn = (PIX *)_srcImg->getPixelAddress( x, ny);
PIX *Pnn = (PIX *)_srcImg->getPixelAddress(nx, ny);
if (Pcc && Pnc && Pcn && Pnn) {
for(int c = 0; c < nComponents; ++c) {
const double Icc = Pcc[c];
const double Inc = Pnc[c];
const double Icn = Pcn[c];
const double Inn = Pnn[c];
dstPix[c] = Icc + dx*(Inc-Icc + dy*(Icc+Inn-Icn-Inc)) + dy*(Icn-Icc);
}
} else {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
}
} else if (_filter == 2) {
// bicubic
int x = std::floor(fx);
int y = std::floor(fy);
int px = x - 1;
int py = y - 1;
int nx = x + 1;
int ny = y + 1;
int ax = x + 2;
int ay = y + 2;
if (!_blackOutside) {
x = std::max(bounds.x1,std::min(x,bounds.x2-1));
y = std::max(bounds.y1,std::min(y,bounds.y2-1));
}
px = std::max(bounds.x1,std::min(px,bounds.x2-1));
py = std::max(bounds.y1,std::min(py,bounds.y2-1));
nx = std::max(bounds.x1,std::min(nx,bounds.x2-1));
ny = std::max(bounds.y1,std::min(ny,bounds.y2-1));
ax = std::max(bounds.x1,std::min(ax,bounds.x2-1));
ay = std::max(bounds.y1,std::min(ay,bounds.y2-1));
const double dx = std::max(0., std::min(fx - x, 1.));
const double dy = std::max(0., std::min(fy - y, 1.));
PIX *Ppp = (PIX *)_srcImg->getPixelAddress(px, py);
PIX *Pcp = (PIX *)_srcImg->getPixelAddress( x, py);
PIX *Pnp = (PIX *)_srcImg->getPixelAddress(nx, py);
PIX *Pap = (PIX *)_srcImg->getPixelAddress(nx, py);
PIX *Ppc = (PIX *)_srcImg->getPixelAddress(px, y);
PIX *Pcc = (PIX *)_srcImg->getPixelAddress( x, y);
PIX *Pnc = (PIX *)_srcImg->getPixelAddress(nx, y);
PIX *Pac = (PIX *)_srcImg->getPixelAddress(nx, y);
PIX *Ppn = (PIX *)_srcImg->getPixelAddress(px, ny);
PIX *Pcn = (PIX *)_srcImg->getPixelAddress( x, ny);
PIX *Pnn = (PIX *)_srcImg->getPixelAddress(nx, ny);
PIX *Pan = (PIX *)_srcImg->getPixelAddress(nx, ny);
PIX *Ppa = (PIX *)_srcImg->getPixelAddress(px, ay);
PIX *Pca = (PIX *)_srcImg->getPixelAddress( x, ay);
PIX *Pna = (PIX *)_srcImg->getPixelAddress(nx, ay);
PIX *Paa = (PIX *)_srcImg->getPixelAddress(nx, ay);
if (Ppp && Pcp && Pnp && Pap && Ppc && Pcc && Pnc && Pac && Ppn && Pcn && Pnn && Pan && Ppa && Pca && Pna && Paa) {
for(int c = 0; c < nComponents; ++c) {
double Ipp = Ppp[c];
double Icp = Pcp[c];
double Inp = Pnp[c];
double Iap = Pap[c];
double Ipc = Ppc[c];
double Icc = Pcc[c];
double Inc = Pnc[c];
double Iac = Pac[c];
double Ipn = Ppn[c];
double Icn = Pcn[c];
double Inn = Pnn[c];
double Ian = Pan[c];
double Ipa = Ppa[c];
double Ica = Pca[c];
double Ina = Pna[c];
double Iaa = Paa[c];
double Ip = Icp + 0.5f*(dx*(-Ipp+Inp) + dx*dx*(2*Ipp-5*Icp+4*Inp-Iap) + dx*dx*dx*(-Ipp+3*Icp-3*Inp+Iap));
double Ic = Icc + 0.5f*(dx*(-Ipc+Inc) + dx*dx*(2*Ipc-5*Icc+4*Inc-Iac) + dx*dx*dx*(-Ipc+3*Icc-3*Inc+Iac));
double In = Icn + 0.5f*(dx*(-Ipn+Inn) + dx*dx*(2*Ipn-5*Icn+4*Inn-Ian) + dx*dx*dx*(-Ipn+3*Icn-3*Inn+Ian));
double Ia = Ica + 0.5f*(dx*(-Ipa+Ina) + dx*dx*(2*Ipa-5*Ica+4*Ina-Iaa) + dx*dx*dx*(-Ipa+3*Ica-3*Ina+Iaa));
dstPix[c] = Ic + 0.5f*(dy*(-Ip+In) + dy*dy*(2*Ip-5*Ic+4*In-Ia) + dy*dy*dy*(-Ip+3*Ic-3*In+Ia));
}
} else {
for(int c = 0; c < nComponents; ++c) {
dstPix[c] = 0;
}
}
}
}
dstPix += nComponents;
}
}
}
};
////////////////////////////////////////////////////////////////////////////////
/** @brief The plugin that does our work */
class TransformPlugin : public OFX::ImageEffect
{
protected:
// do not need to delete these, the ImageEffect is managing them for us
OFX::Clip *dstClip_;
OFX::Clip *srcClip_;
public:
/** @brief ctor */
TransformPlugin(OfxImageEffectHandle handle)
: ImageEffect(handle)
, dstClip_(0)
, srcClip_(0)
{
dstClip_ = fetchClip(kOfxImageEffectOutputClipName);
srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName);
// NON-GENERIC
_translate = fetchDouble2DParam(kTranslateParamName);
_rotate = fetchDoubleParam(kRotateParamName);
_scale = fetchDouble2DParam(kScaleParamName);
_skew = fetchDoubleParam(kSkewParamName);
_center = fetchDouble2DParam(kCenterParamName);
// GENERIC
_filter = fetchChoiceParam(kFilterParamName);
_blackOutside = fetchBooleanParam(kBlackOutsideParamName);
}
virtual bool getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod);
/* Override the render */
virtual void render(const OFX::RenderArguments &args);
virtual bool isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime);
/* set up and run a processor */
void setupAndProcess(TransformProcessorBase &, const OFX::RenderArguments &args);
private:
// NON-GENERIC
OFX::Double2DParam* _translate;
OFX::DoubleParam* _rotate;
OFX::Double2DParam* _scale;
OFX::DoubleParam* _skew;
OFX::Double2DParam* _center;
// GENERIC
OFX::ChoiceParam* _filter;
OFX::BooleanParam* _blackOutside;
};
////////////////////////////////////////////////////////////////////////////////
/** @brief render for the filter */
////////////////////////////////////////////////////////////////////////////////
// basic plugin render function, just a skelington to instantiate templates from
/* set up and run a processor */
void
TransformPlugin::setupAndProcess(TransformProcessorBase &processor, const OFX::RenderArguments &args)
{
std::auto_ptr<OFX::Image> dst(dstClip_->fetchImage(args.time));
std::auto_ptr<OFX::Image> src(srcClip_->fetchImage(args.time));
if(src.get() && dst.get())
{
OFX::BitDepthEnum dstBitDepth = dst->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dst->getPixelComponents();
OFX::BitDepthEnum srcBitDepth = src->getPixelDepth();
OFX::PixelComponentEnum srcComponents = src->getPixelComponents();
if(srcBitDepth != dstBitDepth || srcComponents != dstComponents)
throw int(1);
OfxPointD extent = getProjectExtent();
OfxPointD offset = getProjectOffset();
// NON-GENERIC
OfxPointD scale;
OfxPointD translate;
double rotate;
double skew;
OfxPointD center;
// GENERIC
int filter;
bool blackOutside;
// NON-GENERIC
_scale->getValue(scale.x, scale.y);
_translate->getValue(translate.x, translate.y);
translate.x *= (extent.x - offset.x);
translate.y *= (extent.y - offset.y);
_rotate->getValue(rotate);
///convert to radians
rotate = rotate * pi / 180.0;
_skew->getValue(skew);
_center->getValue(center.x, center.y);
center.x *= (extent.x - offset.x);
center.y *= (extent.y - offset.y);
// GENERIC
_filter->getValue(filter);
_blackOutside->getValue(blackOutside);
processor.setValues(translate, rotate, scale, skew, center, filter, blackOutside);
}
processor.setDstImg(dst.get());
processor.setSrcImg(src.get());
processor.setRenderWindow(args.renderWindow);
processor.process();
}
// NON-GENERIC
bool
TransformPlugin::getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod)
{
OfxRectD srcRoD = srcClip_->getRegionOfDefinition(args.time);
OfxPointD extent = getProjectExtent();
OfxPointD offset = getProjectOffset();
OfxPointD scale;
OfxPointD translate;
double rotate;
double skew;
OfxPointD center;
_scale->getValue(scale.x, scale.y);
_translate->getValue(translate.x, translate.y);
translate.x *= (extent.x - offset.x);
translate.y *= (extent.y - offset.y);
_rotate->getValue(rotate);
///convert to radians
rotate = rotate * pi / 180.0;
_center->getValue(center.x, center.y);
center.x *= (extent.x - offset.x);
center.y *= (extent.y - offset.y);
_skew->getValue(skew);
Transform2D::Matrix3x3 transform = Transform2D::Matrix3x3::getTransform(translate, scale, skew, rotate, center);
transform = transform.invert();
/// now transform the 4 corners of the initial image
Transform2D::Point3D topLeft = transform * Transform2D::Point3D(srcRoD.x1,srcRoD.y2,1);
Transform2D::Point3D topRight = transform * Transform2D::Point3D(srcRoD.x2,srcRoD.y2,1);
Transform2D::Point3D bottomLeft = transform * Transform2D::Point3D(srcRoD.x1,srcRoD.y1,1);
Transform2D::Point3D bottomRight = transform * Transform2D::Point3D(srcRoD.x2,srcRoD.y1,1);
double l = std::min(std::min(std::min(topLeft.x, bottomLeft.x),topRight.x),bottomRight.x);
double b = std::min(std::min(std::min(bottomLeft.y, bottomRight.y),topLeft.y),topRight.y);
double r = std::max(std::max(std::max(topRight.x, bottomRight.x),topLeft.x),bottomLeft.x);
double t = std::max(std::max(std::max(topLeft.y, topRight.y),bottomLeft.y),bottomRight.y);
// denormalize(&l, &b, srcRoD);
// denormalize(&r, &t, srcRoD);
rod.x1 = (int)std::ceil(l);
rod.x2 = (int)std::floor(r);
rod.y1 = (int)std::ceil(b);
rod.y2 = (int)std::floor(t);
return true;
}
// the overridden render function
void
TransformPlugin::render(const OFX::RenderArguments &args)
{
// instantiate the render code based on the pixel depth of the dst clip
OFX::BitDepthEnum dstBitDepth = dstClip_->getPixelDepth();
OFX::PixelComponentEnum dstComponents = dstClip_->getPixelComponents();
assert(dstComponents == OFX::ePixelComponentRGB || dstComponents == OFX::ePixelComponentRGBA);
if(dstComponents == OFX::ePixelComponentRGBA)
{
switch(dstBitDepth)
{
case OFX::eBitDepthUByte :
{
TransformProcessor<unsigned char, 4, 255> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthUShort :
{
TransformProcessor<unsigned short, 4, 65535> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthFloat :
{
TransformProcessor<float,4,1> fred(*this);
setupAndProcess(fred, args);
break;
}
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
else
{
switch(dstBitDepth)
{
case OFX::eBitDepthUByte :
{
TransformProcessor<unsigned char, 3, 255> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthUShort :
{
TransformProcessor<unsigned short, 3, 65535> fred(*this);
setupAndProcess(fred, args);
break;
}
case OFX::eBitDepthFloat :
{
TransformProcessor<float,3,1> fred(*this);
setupAndProcess(fred, args);
break;
}
default :
OFX::throwSuiteStatusException(kOfxStatErrUnsupported);
}
}
}
// NON-GENERIC
bool TransformPlugin::isIdentity(const RenderArguments &args, Clip * &identityClip, double &identityTime)
{
OfxPointD scale;
OfxPointD translate;
double rotate;
double skew;
_scale->getValue(scale.x, scale.y);
_translate->getValue(translate.x, translate.y);
_rotate->getValue(rotate);
_skew->getValue(skew);
if (scale.x == 1. && scale.y == 1. && translate.x == 0 && translate.y == 0 && rotate == 0 && skew == 0) {
identityClip = srcClip_;
identityTime = args.time;
return true;
}
return false;
}
void TransformPluginFactory::load()
{
}
void TransformPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
// basic labels
desc.setLabels("TransformOFX", "TransformOFX", "TransformOFX");
desc.setPluginGrouping("Transform");
desc.setPluginDescription("Translate / Rotate / Scale a 2D image.");
desc.addSupportedContext(eContextFilter);
desc.addSupportedContext(eContextGeneral);
desc.addSupportedContext(eContextPaint);
desc.addSupportedBitDepth(eBitDepthUByte);
desc.addSupportedBitDepth(eBitDepthUShort);
desc.addSupportedBitDepth(eBitDepthFloat);
// set a few flags
desc.setSingleInstance(false);
desc.setHostFrameThreading(false);
desc.setSupportsMultiResolution(true);
desc.setSupportsTiles(false);
desc.setTemporalClipAccess(false);
desc.setRenderTwiceAlways(false);
desc.setSupportsMultipleClipPARs(false);
desc.setRenderThreadSafety(OFX::eRenderFullySafe);
}
void TransformPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, OFX::ContextEnum context)
{
if (!OFX::getImageEffectHostDescription()->supportsParametricParameter) {
throwHostMissingSuiteException(kOfxParametricParameterSuite);
}
// GENERIC
// Source clip only in the filter context
// create the mandated source clip
ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName);
srcClip->addSupportedComponent(ePixelComponentRGBA);
srcClip->addSupportedComponent(ePixelComponentRGB);
srcClip->setTemporalClipAccess(false);
srcClip->setSupportsTiles(true);
srcClip->setIsMask(false);
// create the mandated output clip
ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName);
dstClip->addSupportedComponent(ePixelComponentRGBA);
dstClip->setSupportsTiles(true);
// make some pages and to things in
PageParamDescriptor *page = desc.definePageParam("Controls");
// NON-GENERIC PARAMETERS
//
Double2DParamDescriptor* translate = desc.defineDouble2DParam(kTranslateParamName);
translate->setLabels(kTranslateParamName, kTranslateParamName, kTranslateParamName);
translate->setDoubleType(OFX::eDoubleTypeNormalisedXY);
translate->setDefault(0, 0);
page->addChild(*translate);
DoubleParamDescriptor* rotate = desc.defineDoubleParam(kRotateParamName);
rotate->setLabels(kRotateParamName, kRotateParamName, kRotateParamName);
rotate->setDefault(0);
rotate->setRange(-180, 180);
rotate->setDisplayRange(-180, 180);
page->addChild(*rotate);
Double2DParamDescriptor* scale = desc.defineDouble2DParam(kScaleParamName);
scale->setLabels(kScaleParamName, kScaleParamName, kScaleParamName);
scale->setDefault(1,1);
scale->setRange(0.1,0.1,10,10);
scale->setDisplayRange(0.1, 0.1, 10, 10);
page->addChild(*scale);
DoubleParamDescriptor* skew = desc.defineDoubleParam(kSkewParamName);
skew->setLabels(kSkewParamName, kSkewParamName, kSkewParamName);
skew->setDefault(0);
skew->setRange(-1, 1);
skew->setDisplayRange(-1,1);
page->addChild(*skew);
Double2DParamDescriptor* center = desc.defineDouble2DParam(kCenterParamName);
center->setLabels(kCenterParamName, kCenterParamName, kCenterParamName);
center->setDoubleType(OFX::eDoubleTypeNormalisedXY);
center->setDefault(0.5, 0.5);
page->addChild(*center);
// GENERIC PARAMETERS
//
ChoiceParamDescriptor* filter = desc.defineChoiceParam(kFilterParamName);
filter->setLabels(kFilterParamName, kFilterParamName, kFilterParamName);
filter->setDefault(0);
filter->appendOption("Nearest neighboor");
filter->appendOption("Bilinear");
filter->appendOption("Bicubic");
filter->setAnimates(false);
page->addChild(*filter);
BooleanParamDescriptor* blackOutside = desc.defineBooleanParam(kBlackOutsideParamName);
blackOutside->setLabels(kBlackOutsideParamName, kBlackOutsideParamName, kBlackOutsideParamName);
blackOutside->setDefault(false);
blackOutside->setAnimates(false);
page->addChild(*blackOutside);
}
OFX::ImageEffect* TransformPluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)
{
return new TransformPlugin(handle);
}
|
#include "was/was_server.hxx"
#include "direct.hxx"
#include "pool.hxx"
#include "fb_pool.hxx"
#include <daemon/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <event.h>
struct instance {
WasServer *server;
};
static void
mirror_request(struct pool *pool, http_method_t method, const char *uri,
struct strmap *headers, Istream *body, void *ctx)
{
struct instance *instance = (struct instance *)ctx;
(void)pool;
(void)method;
(void)uri;
was_server_response(instance->server, HTTP_STATUS_OK, headers, body);
}
static void
mirror_free(void *ctx)
{
(void)ctx;
}
static constexpr WasServerHandler handler = {
.request = mirror_request,
.free = mirror_free,
};
int main(int argc, char **argv) {
(void)argc;
(void)argv;
daemon_log_config.verbose = 5;
int in_fd = 0, out_fd = 1, control_fd = 3;
direct_global_init();
fb_pool_init(false);
struct event_base *event_base = event_init();
struct pool *pool = pool_new_libc(nullptr, "root");
struct instance instance;
instance.server = was_server_new(pool, control_fd, in_fd, out_fd,
&handler, &instance);
event_dispatch();
was_server_free(instance.server);
pool_unref(pool);
pool_commit();
pool_recycler_clear();
event_base_free(event_base);
fb_pool_deinit();
direct_global_deinit();
}
test/was_mirror: rename struct instance to upper case
#include "was/was_server.hxx"
#include "direct.hxx"
#include "pool.hxx"
#include "fb_pool.hxx"
#include <daemon/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <event.h>
struct Instance {
WasServer *server;
};
static void
mirror_request(struct pool *pool, http_method_t method, const char *uri,
struct strmap *headers, Istream *body, void *ctx)
{
auto *instance = (Instance *)ctx;
(void)pool;
(void)method;
(void)uri;
was_server_response(instance->server, HTTP_STATUS_OK, headers, body);
}
static void
mirror_free(void *ctx)
{
(void)ctx;
}
static constexpr WasServerHandler handler = {
.request = mirror_request,
.free = mirror_free,
};
int main(int argc, char **argv) {
(void)argc;
(void)argv;
daemon_log_config.verbose = 5;
int in_fd = 0, out_fd = 1, control_fd = 3;
direct_global_init();
fb_pool_init(false);
struct event_base *event_base = event_init();
struct pool *pool = pool_new_libc(nullptr, "root");
Instance instance;
instance.server = was_server_new(pool, control_fd, in_fd, out_fd,
&handler, &instance);
event_dispatch();
was_server_free(instance.server);
pool_unref(pool);
pool_commit();
pool_recycler_clear();
event_base_free(event_base);
fb_pool_deinit();
direct_global_deinit();
}
|
//--------------------------------------------------------------------------------------
// File: UVAtlas.cpp
//
// UVAtlas command-line tool (sample for UVAtlas library)
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=512686
//--------------------------------------------------------------------------------------
#pragma warning(push)
#pragma warning(disable : 4005)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#define NODRAWTEXT
#define NOGDI
#define NOMCX
#define NOSERVICE
#define NOHELP
#pragma warning(pop)
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cwchar>
#include <cwctype>
#include <fstream>
#include <iterator>
#include <list>
#include <locale>
#include <memory>
#include <new>
#include <set>
#include <string>
#include <tuple>
#include <conio.h>
#include <dxgiformat.h>
#include "UVAtlas.h"
#include "DirectXTex.h"
#include "Mesh.h"
//Uncomment to add support for OpenEXR (.exr)
//#define USE_OPENEXR
#ifdef USE_OPENEXR
// See <https://github.com/Microsoft/DirectXTex/wiki/Adding-OpenEXR> for details
#include "DirectXTexEXR.h"
#endif
using namespace DirectX;
namespace
{
enum OPTIONS : uint64_t
{
OPT_RECURSIVE = 1,
OPT_QUALITY,
OPT_MAXCHARTS,
OPT_MAXSTRETCH,
OPT_LIMIT_MERGE_STRETCH,
OPT_LIMIT_FACE_STRETCH,
OPT_GUTTER,
OPT_WIDTH,
OPT_HEIGHT,
OPT_TOPOLOGICAL_ADJ,
OPT_GEOMETRIC_ADJ,
OPT_NORMALS,
OPT_WEIGHT_BY_AREA,
OPT_WEIGHT_BY_EQUAL,
OPT_TANGENTS,
OPT_CTF,
OPT_COLOR_MESH,
OPT_UV_MESH,
OPT_IMT_TEXFILE,
OPT_IMT_VERTEX,
OPT_OUTPUTFILE,
OPT_TOLOWER,
OPT_SDKMESH,
OPT_SDKMESH_V2,
OPT_CMO,
OPT_VBO,
OPT_WAVEFRONT_OBJ,
OPT_CLOCKWISE,
OPT_FORCE_32BIT_IB,
OPT_OVERWRITE,
OPT_NODDS,
OPT_FLIP,
OPT_FLIPU,
OPT_FLIPV,
OPT_FLIPZ,
OPT_VERT_NORMAL_FORMAT,
OPT_VERT_UV_FORMAT,
OPT_VERT_COLOR_FORMAT,
OPT_SECOND_UV,
OPT_NOLOGO,
OPT_FILELIST,
OPT_MAX
};
static_assert(OPT_MAX <= 64, "dwOptions is a unsigned int bitfield");
enum CHANNELS
{
CHANNEL_NONE = 0,
CHANNEL_NORMAL,
CHANNEL_COLOR,
CHANNEL_TEXCOORD,
};
struct SConversion
{
wchar_t szSrc[MAX_PATH];
};
template<typename T>
struct SValue
{
const wchar_t* name;
T value;
};
const XMFLOAT3 g_ColorList[8] =
{
XMFLOAT3(1.0f, 0.5f, 0.5f),
XMFLOAT3(0.5f, 1.0f, 0.5f),
XMFLOAT3(1.0f, 1.0f, 0.5f),
XMFLOAT3(0.5f, 1.0f, 1.0f),
XMFLOAT3(1.0f, 0.5f, 0.75f),
XMFLOAT3(0.0f, 0.5f, 0.75f),
XMFLOAT3(0.5f, 0.5f, 0.75f),
XMFLOAT3(0.5f, 0.5f, 1.0f),
};
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
const SValue<uint64_t> g_pOptions[] =
{
{ L"r", OPT_RECURSIVE },
{ L"q", OPT_QUALITY },
{ L"n", OPT_MAXCHARTS },
{ L"st", OPT_MAXSTRETCH },
{ L"lms", OPT_LIMIT_MERGE_STRETCH },
{ L"lfs", OPT_LIMIT_FACE_STRETCH },
{ L"g", OPT_GUTTER },
{ L"w", OPT_WIDTH },
{ L"h", OPT_HEIGHT },
{ L"ta", OPT_TOPOLOGICAL_ADJ },
{ L"ga", OPT_GEOMETRIC_ADJ },
{ L"nn", OPT_NORMALS },
{ L"na", OPT_WEIGHT_BY_AREA },
{ L"ne", OPT_WEIGHT_BY_EQUAL },
{ L"tt", OPT_TANGENTS },
{ L"tb", OPT_CTF },
{ L"c", OPT_COLOR_MESH },
{ L"t", OPT_UV_MESH },
{ L"it", OPT_IMT_TEXFILE },
{ L"iv", OPT_IMT_VERTEX },
{ L"o", OPT_OUTPUTFILE },
{ L"l", OPT_TOLOWER },
{ L"sdkmesh", OPT_SDKMESH },
{ L"sdkmesh2", OPT_SDKMESH_V2 },
{ L"cmo", OPT_CMO },
{ L"vbo", OPT_VBO },
{ L"wf", OPT_WAVEFRONT_OBJ },
{ L"cw", OPT_CLOCKWISE },
{ L"ib32", OPT_FORCE_32BIT_IB },
{ L"y", OPT_OVERWRITE },
{ L"nodds", OPT_NODDS },
{ L"flip", OPT_FLIP },
{ L"flipu", OPT_FLIPU },
{ L"flipv", OPT_FLIPV },
{ L"flipz", OPT_FLIPZ },
{ L"fn", OPT_VERT_NORMAL_FORMAT },
{ L"fuv", OPT_VERT_UV_FORMAT },
{ L"fc", OPT_VERT_COLOR_FORMAT },
{ L"uv2", OPT_SECOND_UV },
{ L"nologo", OPT_NOLOGO },
{ L"flist", OPT_FILELIST },
{ nullptr, 0 }
};
const SValue<uint32_t> g_vertexNormalFormats[] =
{
{ L"float3", DXGI_FORMAT_R32G32B32_FLOAT },
{ L"float16_4", DXGI_FORMAT_R16G16B16A16_FLOAT },
{ L"r11g11b10", DXGI_FORMAT_R11G11B10_FLOAT },
{ nullptr, 0 }
};
const SValue<uint32_t> g_vertexUVFormats[] =
{
{ L"float2", DXGI_FORMAT_R32G32_FLOAT },
{ L"float16_2", DXGI_FORMAT_R16G16_FLOAT },
{ nullptr, 0 }
};
const SValue<uint32_t> g_vertexColorFormats[] =
{
{ L"bgra", DXGI_FORMAT_B8G8R8A8_UNORM },
{ L"rgba", DXGI_FORMAT_R8G8B8A8_UNORM },
{ L"float4", DXGI_FORMAT_R32G32B32A32_FLOAT },
{ L"float16_4", DXGI_FORMAT_R16G16B16A16_FLOAT },
{ L"rgba_10", DXGI_FORMAT_R10G10B10A2_UNORM },
{ L"r11g11b10", DXGI_FORMAT_R11G11B10_FLOAT },
{ nullptr, 0 }
};
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
HRESULT LoadFromOBJ(const wchar_t* szFilename,
std::unique_ptr<Mesh>& inMesh, std::vector<Mesh::Material>& inMaterial,
bool ccw, bool dds);
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
namespace
{
inline HANDLE safe_handle(HANDLE h) noexcept { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; }
struct find_closer { void operator()(HANDLE h) noexcept { assert(h != INVALID_HANDLE_VALUE); if (h) FindClose(h); } };
using ScopedFindHandle = std::unique_ptr<void, find_closer>;
#ifdef __PREFAST__
#pragma prefast(disable : 26018, "Only used with static internal arrays")
#endif
template<typename T>
T LookupByName(const wchar_t *pName, const SValue<T> *pArray)
{
while (pArray->name)
{
if (!_wcsicmp(pName, pArray->name))
return pArray->value;
pArray++;
}
return 0;
}
void SearchForFiles(const wchar_t* path, std::list<SConversion>& files, bool recursive)
{
// Process files
WIN32_FIND_DATAW findData = {};
ScopedFindHandle hFile(safe_handle(FindFirstFileExW(path,
FindExInfoBasic, &findData,
FindExSearchNameMatch, nullptr,
FIND_FIRST_EX_LARGE_FETCH)));
if (hFile)
{
for (;;)
{
if (!(findData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_DIRECTORY)))
{
wchar_t drive[_MAX_DRIVE] = {};
wchar_t dir[_MAX_DIR] = {};
_wsplitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0);
SConversion conv = {};
_wmakepath_s(conv.szSrc, drive, dir, findData.cFileName, nullptr);
files.push_back(conv);
}
if (!FindNextFileW(hFile.get(), &findData))
break;
}
}
// Process directories
if (recursive)
{
wchar_t searchDir[MAX_PATH] = {};
{
wchar_t drive[_MAX_DRIVE] = {};
wchar_t dir[_MAX_DIR] = {};
_wsplitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0);
_wmakepath_s(searchDir, drive, dir, L"*", nullptr);
}
hFile.reset(safe_handle(FindFirstFileExW(searchDir,
FindExInfoBasic, &findData,
FindExSearchLimitToDirectories, nullptr,
FIND_FIRST_EX_LARGE_FETCH)));
if (!hFile)
return;
for (;;)
{
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (findData.cFileName[0] != L'.')
{
wchar_t subdir[MAX_PATH] = {};
{
wchar_t drive[_MAX_DRIVE] = {};
wchar_t dir[_MAX_DIR] = {};
wchar_t fname[_MAX_FNAME] = {};
wchar_t ext[_MAX_FNAME] = {};
_wsplitpath_s(path, drive, dir, fname, ext);
wcscat_s(dir, findData.cFileName);
_wmakepath_s(subdir, drive, dir, fname, ext);
}
SearchForFiles(subdir, files, recursive);
}
}
if (!FindNextFileW(hFile.get(), &findData))
break;
}
}
}
void ProcessFileList(std::wifstream& inFile, std::list<SConversion>& files)
{
std::list<SConversion> flist;
std::set<std::wstring> excludes;
wchar_t fname[1024] = {};
for (;;)
{
inFile >> fname;
if (!inFile)
break;
if (*fname == L'#')
{
// Comment
}
else if (*fname == L'-')
{
if (flist.empty())
{
wprintf(L"WARNING: Ignoring the line '%ls' in -flist\n", fname);
}
else
{
if (wcspbrk(fname, L"?*") != nullptr)
{
std::list<SConversion> removeFiles;
SearchForFiles(&fname[1], removeFiles, false);
for (auto it : removeFiles)
{
_wcslwr_s(it.szSrc);
excludes.insert(it.szSrc);
}
}
else
{
std::wstring name = (fname + 1);
std::transform(name.begin(), name.end(), name.begin(), towlower);
excludes.insert(name);
}
}
}
else if (wcspbrk(fname, L"?*") != nullptr)
{
SearchForFiles(fname, flist, false);
}
else
{
SConversion conv = {};
wcscpy_s(conv.szSrc, MAX_PATH, fname);
flist.push_back(conv);
}
inFile.ignore(1000, '\n');
}
inFile.close();
if (!excludes.empty())
{
// Remove any excluded files
for (auto it = flist.begin(); it != flist.end();)
{
std::wstring name = it->szSrc;
std::transform(name.begin(), name.end(), name.begin(), towlower);
auto item = it;
++it;
if (excludes.find(name) != excludes.end())
{
flist.erase(item);
}
}
}
if (flist.empty())
{
wprintf(L"WARNING: No file names found in -flist\n");
}
else
{
files.splice(files.end(), flist);
}
}
void PrintList(size_t cch, const SValue<uint32_t>* pValue)
{
while (pValue->name)
{
size_t cchName = wcslen(pValue->name);
if (cch + cchName + 2 >= 80)
{
wprintf(L"\n ");
cch = 6;
}
wprintf(L"%ls ", pValue->name);
cch += cchName + 2;
pValue++;
}
wprintf(L"\n");
}
void PrintLogo()
{
wchar_t version[32] = {};
wchar_t appName[_MAX_PATH] = {};
if (GetModuleFileNameW(nullptr, appName, static_cast<DWORD>(std::size(appName))))
{
DWORD size = GetFileVersionInfoSizeW(appName, nullptr);
if (size > 0)
{
auto verInfo = std::make_unique<uint8_t[]>(size);
if (GetFileVersionInfoW(appName, 0, size, verInfo.get()))
{
LPVOID lpstr = nullptr;
UINT strLen = 0;
if (VerQueryValueW(verInfo.get(), L"\\StringFileInfo\\040904B0\\ProductVersion", &lpstr, &strLen))
{
wcsncpy_s(version, reinterpret_cast<const wchar_t*>(lpstr), strLen);
}
}
}
}
if (!*version || wcscmp(version, L"1.0.0.0") == 0)
{
swprintf_s(version, L"%03d (library)", UVATLAS_VERSION);
}
wprintf(L"Microsoft (R) UVAtlas Command-line Tool Version %ls\n", version);
wprintf(L"Copyright (C) Microsoft Corp.\n");
#ifdef _DEBUG
wprintf(L"*** Debug build ***\n");
#endif
wprintf(L"\n");
}
void PrintUsage()
{
PrintLogo();
wprintf(L"Usage: uvatlas <options> <files>\n");
wprintf(L"\n");
wprintf(L" Input file type must be Wavefront Object (.obj)\n\n");
wprintf(L" Output file type:\n");
wprintf(L" -sdkmesh DirectX SDK .sdkmesh format (default)\n");
wprintf(L" -sdkmesh2 .sdkmesh format version 2 (PBR materials)\n");
wprintf(L" -cmo Visual Studio Content Pipeline .cmo format\n");
wprintf(L" -vbo Vertex Buffer Object (.vbo) format\n");
wprintf(L" -wf WaveFront Object (.obj) format\n\n");
wprintf(L" -r wildcard filename search is recursive\n");
wprintf(L" -q <level> sets quality level to DEFAULT, FAST or QUALITY\n");
wprintf(L" -n <number> maximum number of charts to generate (def: 0)\n");
wprintf(L" -st <float> maximum amount of stretch 0.0 to 1.0 (def: 0.16667)\n");
wprintf(L" -lms enable limit merge stretch option\n");
wprintf(L" -lfs enable limit face stretch option\n");
wprintf(L" -g <float> the gutter width betwen charts in texels (def: 2.0)\n");
wprintf(L" -w <number> texture width (def: 512)\n");
wprintf(L" -h <number> texture height (def: 512)\n");
wprintf(L" -ta | -ga generate topological vs. geometric adjancecy (def: ta)\n");
wprintf(L" -nn | -na | -ne generate normals weighted by angle/area/equal\n");
wprintf(L" -tt generate tangents\n");
wprintf(L" -tb generate tangents & bi-tangents\n");
wprintf(L" -cw faces are clockwise (defaults to counter-clockwise)\n");
wprintf(L" -c generate mesh with colors showing charts\n");
wprintf(L" -t generates a separate mesh with uvs - (*_texture)\n");
wprintf(L" -it <filename> calculate IMT for the mesh using this texture map\n");
wprintf(
L" -iv <channel> calculate IMT using per-vertex data\n"
L" NORMAL, COLOR, TEXCOORD\n");
wprintf(L" -nodds prevents extension renaming in exported materials\n");
wprintf(L" -flip reverse winding of faces\n");
wprintf(L" -flipu inverts the u texcoords\n");
wprintf(L" -flipv inverts the v texcoords\n");
wprintf(L" -flipz flips the handedness of the positions/normals\n");
wprintf(L" -o <filename> output filename\n");
wprintf(L" -l force output filename to lower case\n");
wprintf(L" -y overwrite existing output file (if any)\n");
wprintf(L" -nologo suppress copyright message\n");
wprintf(L" -flist <filename> use text file with a list of input files (one per line)\n");
wprintf(L"\n (sdkmesh/sdkmesh2 only)\n");
wprintf(L" -ib32 use 32-bit index buffer\n");
wprintf(L" -fn <normal-format> format to use for writing normals/tangents/normals\n");
wprintf(L" -fuv <uv-format> format to use for texture coordinates\n");
wprintf(L" -fc <color-format> format to use for writing colors\n");
wprintf(L" -uv2 place uvatlas uvs into a second texture coordinate channel\n");
wprintf(L"\n <normal-format>: ");
PrintList(13, g_vertexNormalFormats);
wprintf(L"\n <uv-format>: ");
PrintList(13, g_vertexUVFormats);
wprintf(L"\n <color-format>: ");
PrintList(13, g_vertexColorFormats);
}
const wchar_t* GetErrorDesc(HRESULT hr)
{
static wchar_t desc[1024] = {};
LPWSTR errorText = nullptr;
DWORD result = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
nullptr, static_cast<DWORD>(hr),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&errorText), 0, nullptr);
*desc = 0;
if (result > 0 && errorText)
{
swprintf_s(desc, L": %ls", errorText);
size_t len = wcslen(desc);
if (len >= 2)
{
desc[len - 2] = 0;
desc[len - 1] = 0;
}
if (errorText)
LocalFree(errorText);
}
return desc;
}
//--------------------------------------------------------------------------------------
HRESULT __cdecl UVAtlasCallback(float fPercentDone)
{
static ULONGLONG s_lastTick = 0;
ULONGLONG tick = GetTickCount64();
if ((tick - s_lastTick) > 1000)
{
wprintf(L"%.2f%% \r", double(fPercentDone) * 100);
s_lastTick = tick;
}
if (_kbhit())
{
if (_getch() == 27)
{
wprintf(L"*** ABORT ***");
return E_ABORT;
}
}
return S_OK;
}
}
//--------------------------------------------------------------------------------------
// Entry-point
//--------------------------------------------------------------------------------------
#ifdef __PREFAST__
#pragma prefast(disable : 28198, "Command-line tool, frees all memory on exit")
#endif
int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[])
{
// Parameters and defaults
size_t maxCharts = 0;
float maxStretch = 0.16667f;
float gutter = 2.f;
size_t width = 512;
size_t height = 512;
CHANNELS perVertex = CHANNEL_NONE;
UVATLAS uvOptions = UVATLAS_DEFAULT;
UVATLAS uvOptionsEx = UVATLAS_DEFAULT;
DXGI_FORMAT normalFormat = DXGI_FORMAT_R32G32B32_FLOAT;
DXGI_FORMAT uvFormat = DXGI_FORMAT_R32G32_FLOAT;
DXGI_FORMAT colorFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
wchar_t szTexFile[MAX_PATH] = {};
wchar_t szOutputFile[MAX_PATH] = {};
// Set locale for output since GetErrorDesc can get localized strings.
std::locale::global(std::locale(""));
// Initialize COM (needed for WIC)
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if (FAILED(hr))
{
wprintf(L"Failed to initialize COM (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
// Process command line
uint64_t dwOptions = 0;
std::list<SConversion> conversion;
for (int iArg = 1; iArg < argc; iArg++)
{
PWSTR pArg = argv[iArg];
if (('-' == pArg[0]) || ('/' == pArg[0]))
{
pArg++;
PWSTR pValue;
for (pValue = pArg; *pValue && (':' != *pValue); pValue++);
if (*pValue)
*pValue++ = 0;
uint64_t dwOption = LookupByName(pArg, g_pOptions);
if (!dwOption || (dwOptions & (uint64_t(1) << dwOption)))
{
wprintf(L"ERROR: unknown command-line option '%ls'\n\n", pArg);
PrintUsage();
return 1;
}
dwOptions |= (uint64_t(1) << dwOption);
// Handle options with additional value parameter
switch (dwOption)
{
case OPT_QUALITY:
case OPT_MAXCHARTS:
case OPT_MAXSTRETCH:
case OPT_GUTTER:
case OPT_WIDTH:
case OPT_HEIGHT:
case OPT_IMT_TEXFILE:
case OPT_IMT_VERTEX:
case OPT_OUTPUTFILE:
case OPT_VERT_NORMAL_FORMAT:
case OPT_VERT_UV_FORMAT:
case OPT_VERT_COLOR_FORMAT:
case OPT_FILELIST:
if (!*pValue)
{
if ((iArg + 1 >= argc))
{
wprintf(L"ERROR: missing value for command-line option '%ls'\n\n", pArg);
PrintUsage();
return 1;
}
iArg++;
pValue = argv[iArg];
}
break;
}
switch (dwOption)
{
case OPT_QUALITY:
if (!_wcsicmp(pValue, L"DEFAULT"))
{
uvOptions = UVATLAS_DEFAULT;
}
else if (!_wcsicmp(pValue, L"FAST"))
{
uvOptions = UVATLAS_GEODESIC_FAST;
}
else if (!_wcsicmp(pValue, L"QUALITY"))
{
uvOptions = UVATLAS_GEODESIC_QUALITY;
}
else
{
wprintf(L"Invalid value specified with -q (%ls)\n", pValue);
return 1;
}
break;
case OPT_LIMIT_MERGE_STRETCH:
uvOptionsEx |= UVATLAS_LIMIT_MERGE_STRETCH;
break;
case OPT_LIMIT_FACE_STRETCH:
uvOptionsEx |= UVATLAS_LIMIT_FACE_STRETCH;
break;
case OPT_MAXCHARTS:
if (swscanf_s(pValue, L"%zu", &maxCharts) != 1)
{
wprintf(L"Invalid value specified with -n (%ls)\n", pValue);
return 1;
}
break;
case OPT_MAXSTRETCH:
if (swscanf_s(pValue, L"%f", &maxStretch) != 1
|| maxStretch < 0.f
|| maxStretch > 1.f)
{
wprintf(L"Invalid value specified with -st (%ls)\n", pValue);
return 1;
}
break;
case OPT_GUTTER:
if (swscanf_s(pValue, L"%f", &gutter) != 1
|| gutter < 0.f)
{
wprintf(L"Invalid value specified with -g (%ls)\n", pValue);
return 1;
}
break;
case OPT_WIDTH:
if (swscanf_s(pValue, L"%zu", &width) != 1)
{
wprintf(L"Invalid value specified with -w (%ls)\n", pValue);
return 1;
}
break;
case OPT_HEIGHT:
if (swscanf_s(pValue, L"%zu", &height) != 1)
{
wprintf(L"Invalid value specified with -h (%ls)\n", pValue);
return 1;
}
break;
case OPT_WEIGHT_BY_AREA:
if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_EQUAL))
{
wprintf(L"Can only use one of nn, na, or ne\n");
return 1;
}
dwOptions |= (uint64_t(1) << OPT_NORMALS);
break;
case OPT_WEIGHT_BY_EQUAL:
if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_AREA))
{
wprintf(L"Can only use one of nn, na, or ne\n");
return 1;
}
dwOptions |= (uint64_t(1) << OPT_NORMALS);
break;
case OPT_IMT_TEXFILE:
if (dwOptions & (uint64_t(1) << OPT_IMT_VERTEX))
{
wprintf(L"Cannot use both if and iv at the same time\n");
return 1;
}
wcscpy_s(szTexFile, MAX_PATH, pValue);
break;
case OPT_IMT_VERTEX:
if (dwOptions & (uint64_t(1) << OPT_IMT_TEXFILE))
{
wprintf(L"Cannot use both if and iv at the same time\n");
return 1;
}
if (!_wcsicmp(pValue, L"COLOR"))
{
perVertex = CHANNEL_COLOR;
}
else if (!_wcsicmp(pValue, L"NORMAL"))
{
perVertex = CHANNEL_NORMAL;
}
else if (!_wcsicmp(pValue, L"TEXCOORD"))
{
perVertex = CHANNEL_TEXCOORD;
}
else
{
wprintf(L"Invalid value specified with -iv (%ls)\n", pValue);
return 1;
}
break;
case OPT_OUTPUTFILE:
wcscpy_s(szOutputFile, MAX_PATH, pValue);
break;
case OPT_TOPOLOGICAL_ADJ:
if (dwOptions & (uint64_t(1) << OPT_GEOMETRIC_ADJ))
{
wprintf(L"Cannot use both ta and ga at the same time\n");
return 1;
}
break;
case OPT_GEOMETRIC_ADJ:
if (dwOptions & (uint64_t(1) << OPT_TOPOLOGICAL_ADJ))
{
wprintf(L"Cannot use both ta and ga at the same time\n");
return 1;
}
break;
case OPT_SDKMESH:
case OPT_SDKMESH_V2:
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_CMO) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
if (dwOption == OPT_SDKMESH_V2)
{
dwOptions |= (uint64_t(1) << OPT_SDKMESH);
}
break;
case OPT_CMO:
if (dwOptions & (uint64_t(1) << OPT_SECOND_UV))
{
wprintf(L"-uv2 is not supported by CMO\n");
return 1;
}
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_SDKMESH) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
break;
case OPT_VBO:
if (dwOptions & (uint64_t(1) << OPT_SECOND_UV))
{
wprintf(L"-uv2 is not supported by VBO\n");
return 1;
}
if (dwOptions & ((uint64_t(1) << OPT_SDKMESH) | (uint64_t(1) << OPT_CMO) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
break;
case OPT_WAVEFRONT_OBJ:
if (dwOptions & (uint64_t(1) << OPT_SECOND_UV))
{
wprintf(L"-uv2 is not supported by Wavefront OBJ\n");
return 1;
}
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_SDKMESH) | (uint64_t(1) << OPT_CMO)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
break;
case OPT_SECOND_UV:
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_CMO) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"-uv2 is only supported by sdkmesh\n");
return 1;
}
break;
case OPT_VERT_NORMAL_FORMAT:
normalFormat = static_cast<DXGI_FORMAT>(LookupByName(pValue, g_vertexNormalFormats));
if (!normalFormat)
{
wprintf(L"Invalid value specified with -fn (%ls)\n", pValue);
wprintf(L"\n");
PrintUsage();
return 1;
}
break;
case OPT_VERT_UV_FORMAT:
uvFormat = static_cast<DXGI_FORMAT>(LookupByName(pValue, g_vertexUVFormats));
if (!uvFormat)
{
wprintf(L"Invalid value specified with -fuv (%ls)\n", pValue);
wprintf(L"\n");
PrintUsage();
return 1;
}
break;
case OPT_VERT_COLOR_FORMAT:
colorFormat = static_cast<DXGI_FORMAT>(LookupByName(pValue, g_vertexColorFormats));
if (!colorFormat)
{
wprintf(L"Invalid value specified with -fc (%ls)\n", pValue);
wprintf(L"\n");
PrintUsage();
return 1;
}
break;
case OPT_FILELIST:
{
std::wifstream inFile(pValue);
if (!inFile)
{
wprintf(L"Error opening -flist file %ls\n", pValue);
return 1;
}
ProcessFileList(inFile, conversion);
}
break;
}
}
else if (wcspbrk(pArg, L"?*") != nullptr)
{
size_t count = conversion.size();
SearchForFiles(pArg, conversion, (dwOptions & (uint64_t(1) << OPT_RECURSIVE)) != 0);
if (conversion.size() <= count)
{
wprintf(L"No matching files found for %ls\n", pArg);
return 1;
}
}
else
{
SConversion conv = {};
wcscpy_s(conv.szSrc, MAX_PATH, pArg);
conversion.push_back(conv);
}
}
if (conversion.empty())
{
PrintUsage();
return 0;
}
if (*szOutputFile && conversion.size() > 1)
{
wprintf(L"Cannot use -o with multiple input files\n");
return 1;
}
if (~dwOptions & (uint64_t(1) << OPT_NOLOGO))
PrintLogo();
// Process files
for (auto pConv = conversion.begin(); pConv != conversion.end(); ++pConv)
{
wchar_t ext[_MAX_EXT] = {};
wchar_t fname[_MAX_FNAME] = {};
_wsplitpath_s(pConv->szSrc, nullptr, 0, nullptr, 0, fname, _MAX_FNAME, ext, _MAX_EXT);
if (pConv != conversion.begin())
wprintf(L"\n");
wprintf(L"reading %ls", pConv->szSrc);
fflush(stdout);
std::unique_ptr<Mesh> inMesh;
std::vector<Mesh::Material> inMaterial;
hr = E_NOTIMPL;
if (_wcsicmp(ext, L".vbo") == 0)
{
hr = Mesh::CreateFromVBO(pConv->szSrc, inMesh);
}
else if (_wcsicmp(ext, L".sdkmesh") == 0)
{
wprintf(L"\nERROR: Importing SDKMESH files not supported\n");
return 1;
}
else if (_wcsicmp(ext, L".cmo") == 0)
{
wprintf(L"\nERROR: Importing Visual Studio CMO files not supported\n");
return 1;
}
else if (_wcsicmp(ext, L".x") == 0)
{
wprintf(L"\nERROR: Legacy Microsoft X files not supported\n");
return 1;
}
else if (_wcsicmp(ext, L".fbx") == 0)
{
wprintf(L"\nERROR: Autodesk FBX files not supported\n");
return 1;
}
else
{
hr = LoadFromOBJ(pConv->szSrc, inMesh, inMaterial,
(dwOptions & (uint64_t(1) << OPT_CLOCKWISE)) ? false : true,
(dwOptions & (uint64_t(1) << OPT_NODDS)) ? false : true);
}
if (FAILED(hr))
{
wprintf(L" FAILED (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
size_t nVerts = inMesh->GetVertexCount();
size_t nFaces = inMesh->GetFaceCount();
if (!nVerts || !nFaces)
{
wprintf(L"\nERROR: Invalid mesh\n");
return 1;
}
assert(inMesh->GetPositionBuffer() != nullptr);
assert(inMesh->GetIndexBuffer() != nullptr);
wprintf(L"\n%zu vertices, %zu faces", nVerts, nFaces);
if (dwOptions & (uint64_t(1) << OPT_FLIPU))
{
hr = inMesh->InvertUTexCoord();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed inverting u texcoord (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_FLIPV))
{
hr = inMesh->InvertVTexCoord();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed inverting v texcoord (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_FLIPZ))
{
hr = inMesh->ReverseHandedness();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed reversing handedness (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Prepare mesh for processing
{
// Adjacency
float epsilon = (dwOptions & (uint64_t(1) << OPT_GEOMETRIC_ADJ)) ? 1e-5f : 0.f;
hr = inMesh->GenerateAdjacency(epsilon);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed generating adjacency (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
// Validation
std::wstring msgs;
hr = inMesh->Validate(VALIDATE_BACKFACING | VALIDATE_BOWTIES, &msgs);
if (!msgs.empty())
{
wprintf(L"\nWARNING: \n");
wprintf(L"%ls", msgs.c_str());
}
// Clean
hr = inMesh->Clean(true);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed mesh clean (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
else
{
size_t nNewVerts = inMesh->GetVertexCount();
if (nVerts != nNewVerts)
{
wprintf(L" [%zu vertex dups] ", nNewVerts - nVerts);
nVerts = nNewVerts;
}
}
}
if (!inMesh->GetNormalBuffer())
{
dwOptions |= uint64_t(1) << OPT_NORMALS;
}
if (!inMesh->GetTangentBuffer() && (dwOptions & (uint64_t(1) << OPT_CMO)))
{
dwOptions |= uint64_t(1) << OPT_TANGENTS;
}
// Compute vertex normals from faces
if ((dwOptions & (uint64_t(1) << OPT_NORMALS))
|| ((dwOptions & ((uint64_t(1) << OPT_TANGENTS) | (uint64_t(1) << OPT_CTF))) && !inMesh->GetNormalBuffer()))
{
CNORM_FLAGS flags = CNORM_DEFAULT;
if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_EQUAL))
{
flags |= CNORM_WEIGHT_EQUAL;
}
else if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_AREA))
{
flags |= CNORM_WEIGHT_BY_AREA;
}
if (dwOptions & (uint64_t(1) << OPT_CLOCKWISE))
{
flags |= CNORM_WIND_CW;
}
hr = inMesh->ComputeNormals(flags);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed computing normals (flags:%lX, %08X%ls)\n", flags,
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Compute tangents and bitangents
if (dwOptions & ((uint64_t(1) << OPT_TANGENTS) | (uint64_t(1) << OPT_CTF)))
{
if (!inMesh->GetTexCoordBuffer())
{
wprintf(L"\nERROR: Computing tangents/bi-tangents requires texture coordinates\n");
return 1;
}
hr = inMesh->ComputeTangentFrame((dwOptions & (uint64_t(1) << OPT_CTF)) ? true : false);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed computing tangent frame (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Compute IMT
std::unique_ptr<float[]> IMTData;
if (dwOptions & ((uint64_t(1) << OPT_IMT_TEXFILE) | (uint64_t(1) << OPT_IMT_VERTEX)))
{
if (dwOptions & (uint64_t(1) << OPT_IMT_TEXFILE))
{
if (!inMesh->GetTexCoordBuffer())
{
wprintf(L"\nERROR: Computing IMT from texture requires texture coordinates\n");
return 1;
}
wchar_t txext[_MAX_EXT] = {};
_wsplitpath_s(szTexFile, nullptr, 0, nullptr, 0, nullptr, 0, txext, _MAX_EXT);
ScratchImage iimage;
if (_wcsicmp(txext, L".dds") == 0)
{
hr = LoadFromDDSFile(szTexFile, DDS_FLAGS_NONE, nullptr, iimage);
}
else if (_wcsicmp(ext, L".tga") == 0)
{
hr = LoadFromTGAFile(szTexFile, nullptr, iimage);
}
else if (_wcsicmp(ext, L".hdr") == 0)
{
hr = LoadFromHDRFile(szTexFile, nullptr, iimage);
}
#ifdef USE_OPENEXR
else if (_wcsicmp(ext, L".exr") == 0)
{
hr = LoadFromEXRFile(szTexFile, nullptr, iimage);
}
#endif
else
{
hr = LoadFromWICFile(szTexFile, WIC_FLAGS_NONE, nullptr, iimage);
}
if (FAILED(hr))
{
wprintf(L"\nWARNING: Failed to load texture for IMT (%08X%ls):\n%ls\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), szTexFile);
}
else
{
const Image* img = iimage.GetImage(0, 0, 0);
ScratchImage floatImage;
if (img->format != DXGI_FORMAT_R32G32B32A32_FLOAT)
{
hr = Convert(*iimage.GetImage(0, 0, 0), DXGI_FORMAT_R32G32B32A32_FLOAT, TEX_FILTER_DEFAULT,
TEX_THRESHOLD_DEFAULT, floatImage);
if (FAILED(hr))
{
img = nullptr;
wprintf(L"\nWARNING: Failed converting texture for IMT (%08X%ls):\n%ls\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), szTexFile);
}
else
{
img = floatImage.GetImage(0, 0, 0);
}
}
if (img)
{
wprintf(L"\nComputing IMT from file %ls...\n", szTexFile);
IMTData.reset(new (std::nothrow) float[nFaces * 3]);
if (!IMTData)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
hr = UVAtlasComputeIMTFromTexture(inMesh->GetPositionBuffer(), inMesh->GetTexCoordBuffer(), nVerts,
inMesh->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, nFaces,
reinterpret_cast<const float*>(img->pixels), img->width, img->height,
UVATLAS_IMT_DEFAULT, UVAtlasCallback, IMTData.get());
if (FAILED(hr))
{
IMTData.reset();
wprintf(L"WARNING: Failed to compute IMT from texture (%08X%ls):\n%ls\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), szTexFile);
}
}
}
}
else
{
const wchar_t* szChannel = L"*unknown*";
const float* pSignal = nullptr;
size_t signalDim = 0;
size_t signalStride = 0;
switch (perVertex)
{
case CHANNEL_NORMAL:
szChannel = L"normals";
if (inMesh->GetNormalBuffer())
{
pSignal = reinterpret_cast<const float*>(inMesh->GetNormalBuffer());
signalDim = 3;
signalStride = sizeof(XMFLOAT3);
}
break;
case CHANNEL_COLOR:
szChannel = L"vertex colors";
if (inMesh->GetColorBuffer())
{
pSignal = reinterpret_cast<const float*>(inMesh->GetColorBuffer());
signalDim = 4;
signalStride = sizeof(XMFLOAT4);
}
break;
case CHANNEL_TEXCOORD:
szChannel = L"texture coordinates";
if (inMesh->GetTexCoordBuffer())
{
pSignal = reinterpret_cast<const float*>(inMesh->GetTexCoordBuffer());
signalDim = 2;
signalStride = sizeof(XMFLOAT2);
}
break;
}
if (!pSignal)
{
wprintf(L"\nWARNING: Mesh does not have channel %ls for IMT\n", szChannel);
}
else
{
wprintf(L"\nComputing IMT from %ls...\n", szChannel);
IMTData.reset(new (std::nothrow) float[nFaces * 3]);
if (!IMTData)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
hr = UVAtlasComputeIMTFromPerVertexSignal(inMesh->GetPositionBuffer(), nVerts,
inMesh->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, nFaces,
pSignal, signalDim, signalStride, UVAtlasCallback, IMTData.get());
if (FAILED(hr))
{
IMTData.reset();
wprintf(L"WARNING: Failed to compute IMT from channel %ls (%08X%ls)\n",
szChannel, static_cast<unsigned int>(hr), GetErrorDesc(hr));
}
}
}
}
else
{
wprintf(L"\n");
}
// Perform UVAtlas isocharting
wprintf(L"Computing isochart atlas on mesh...\n");
std::vector<UVAtlasVertex> vb;
std::vector<uint8_t> ib;
float outStretch = 0.f;
size_t outCharts = 0;
std::vector<uint32_t> facePartitioning;
std::vector<uint32_t> vertexRemapArray;
hr = UVAtlasCreate(inMesh->GetPositionBuffer(), nVerts,
inMesh->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, nFaces,
maxCharts, maxStretch, width, height, gutter,
inMesh->GetAdjacencyBuffer(), nullptr,
IMTData.get(),
UVAtlasCallback, UVATLAS_DEFAULT_CALLBACK_FREQUENCY,
uvOptions | uvOptionsEx, vb, ib,
&facePartitioning,
&vertexRemapArray,
&outStretch, &outCharts);
if (FAILED(hr))
{
if (hr == HRESULT_FROM_WIN32(ERROR_INVALID_DATA))
{
wprintf(L"\nERROR: Non-manifold mesh\n");
return 1;
}
else
{
wprintf(L"\nERROR: Failed creating isocharts (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
wprintf(L"Output # of charts: %zu, resulting stretching %f, %zu verts\n", outCharts, double(outStretch), vb.size());
assert((ib.size() / sizeof(uint32_t)) == (nFaces * 3));
assert(facePartitioning.size() == nFaces);
assert(vertexRemapArray.size() == vb.size());
hr = inMesh->UpdateFaces(nFaces, reinterpret_cast<const uint32_t*>(ib.data()));
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed applying atlas indices (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
hr = inMesh->VertexRemap(vertexRemapArray.data(), vertexRemapArray.size());
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed applying atlas vertex remap (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
nVerts = vb.size();
#ifdef _DEBUG
std::wstring msgs;
hr = inMesh->Validate(VALIDATE_DEFAULT, &msgs);
if (!msgs.empty())
{
wprintf(L"\nWARNING: \n%ls\n", msgs.c_str());
}
#endif
// Copy isochart UVs into mesh
{
std::unique_ptr<XMFLOAT2[]> texcoord(new (std::nothrow) XMFLOAT2[nVerts]);
if (!texcoord)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
auto txptr = texcoord.get();
size_t j = 0;
for (auto it = vb.cbegin(); it != vb.cend() && j < nVerts; ++it, ++txptr)
{
*txptr = it->uv;
}
hr = inMesh->UpdateUVs(nVerts, texcoord.get(), (dwOptions & (uint64_t(1) << OPT_SECOND_UV)));
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed to update with isochart UVs\n");
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_COLOR_MESH))
{
inMaterial.clear();
inMaterial.reserve(std::size(g_ColorList));
for (size_t j = 0; j < std::size(g_ColorList) && (j < outCharts); ++j)
{
Mesh::Material mtl = {};
wchar_t matname[32] = {};
swprintf_s(matname, L"Chart%02zu", j + 1);
mtl.name = matname;
mtl.specularPower = 1.f;
mtl.alpha = 1.f;
XMVECTOR v = XMLoadFloat3(&g_ColorList[j]);
XMStoreFloat3(&mtl.diffuseColor, v);
v = XMVectorScale(v, 0.2f);
XMStoreFloat3(&mtl.ambientColor, v);
inMaterial.push_back(mtl);
}
std::unique_ptr<uint32_t[]> attr(new (std::nothrow) uint32_t[nFaces]);
if (!attr)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
size_t j = 0;
for (auto it = facePartitioning.cbegin(); it != facePartitioning.cend(); ++it, ++j)
{
attr[j] = *it % std::size(g_ColorList);
}
hr = inMesh->UpdateAttributes(nFaces, attr.get());
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed applying atlas attributes (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_FLIP))
{
hr = inMesh->ReverseWinding();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed reversing winding (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Write results
wprintf(L"\n\t->\n");
wchar_t outputPath[MAX_PATH] = {};
wchar_t outputExt[_MAX_EXT] = {};
if (*szOutputFile)
{
wcscpy_s(outputPath, szOutputFile);
_wsplitpath_s(szOutputFile, nullptr, 0, nullptr, 0, nullptr, 0, outputExt, _MAX_EXT);
}
else
{
if (dwOptions & (uint64_t(1) << OPT_VBO))
{
wcscpy_s(outputExt, L".vbo");
}
else if (dwOptions & (uint64_t(1) << OPT_CMO))
{
wcscpy_s(outputExt, L".cmo");
}
else if (dwOptions & (uint64_t(1) << OPT_WAVEFRONT_OBJ))
{
wcscpy_s(outputExt, L".obj");
}
else
{
wcscpy_s(outputExt, L".sdkmesh");
}
wchar_t outFilename[_MAX_FNAME] = {};
wcscpy_s(outFilename, fname);
_wmakepath_s(outputPath, nullptr, nullptr, outFilename, outputExt);
}
if (dwOptions & (uint64_t(1) << OPT_TOLOWER))
{
std::ignore = _wcslwr_s(outputPath);
}
if (~dwOptions & (uint64_t(1) << OPT_OVERWRITE))
{
if (GetFileAttributesW(outputPath) != INVALID_FILE_ATTRIBUTES)
{
wprintf(L"\nERROR: Output file already exists, use -y to overwrite:\n'%ls'\n", outputPath);
return 1;
}
}
if (!_wcsicmp(outputExt, L".vbo"))
{
if (!inMesh->GetNormalBuffer() || !inMesh->GetTexCoordBuffer())
{
wprintf(L"\nERROR: VBO requires position, normal, and texcoord\n");
return 1;
}
if (!inMesh->Is16BitIndexBuffer() || (dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)))
{
wprintf(L"\nERROR: VBO only supports 16-bit indices\n");
return 1;
}
hr = inMesh->ExportToVBO(outputPath);
}
else if (!_wcsicmp(outputExt, L".sdkmesh"))
{
hr = inMesh->ExportToSDKMESH(
outputPath,
inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data(),
(dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)) ? true : false,
(dwOptions & (uint64_t(1) << OPT_SDKMESH_V2)) ? true : false,
normalFormat,
uvFormat,
colorFormat);
}
else if (!_wcsicmp(outputExt, L".cmo"))
{
if (!inMesh->GetNormalBuffer() || !inMesh->GetTexCoordBuffer() || !inMesh->GetTangentBuffer())
{
wprintf(L"\nERROR: Visual Studio CMO requires position, normal, tangents, and texcoord\n");
return 1;
}
if (!inMesh->Is16BitIndexBuffer() || (dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)))
{
wprintf(L"\nERROR: Visual Studio CMO only supports 16-bit indices\n");
return 1;
}
hr = inMesh->ExportToCMO(outputPath, inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data());
}
else if (!_wcsicmp(outputExt, L".obj") || !_wcsicmp(outputExt, L"._obj"))
{
hr = inMesh->ExportToOBJ(outputPath, inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data());
}
else if (!_wcsicmp(outputExt, L".x"))
{
wprintf(L"\nERROR: Legacy Microsoft X files not supported\n");
return 1;
}
else
{
wprintf(L"\nERROR: Unknown output file type '%ls'\n", outputExt);
return 1;
}
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed write (%08X%ls):-> '%ls'\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), outputPath);
return 1;
}
wprintf(L" %zu vertices, %zu faces written:\n'%ls'\n", nVerts, nFaces, outputPath);
// Write out UV mesh visualization
if (dwOptions & (uint64_t(1) << OPT_UV_MESH))
{
hr = inMesh->VisualizeUVs(dwOptions & (uint64_t(1) << OPT_SECOND_UV));
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed to create UV visualization mesh\n");
return 1;
}
wchar_t uvFilename[_MAX_FNAME] = {};
wcscpy_s(uvFilename, fname);
wcscat_s(uvFilename, L"_texture");
_wmakepath_s(outputPath, nullptr, nullptr, uvFilename, outputExt);
if (dwOptions & (uint64_t(1) << OPT_TOLOWER))
{
std::ignore = _wcslwr_s(outputPath);
}
if (~dwOptions & (uint64_t(1) << OPT_OVERWRITE))
{
if (GetFileAttributesW(outputPath) != INVALID_FILE_ATTRIBUTES)
{
wprintf(L"\nERROR: UV visualization mesh file already exists, use -y to overwrite:\n'%ls'\n", outputPath);
return 1;
}
}
hr = E_NOTIMPL;
if (!_wcsicmp(outputExt, L".vbo"))
{
hr = inMesh->ExportToVBO(outputPath);
}
else if (!_wcsicmp(outputExt, L".sdkmesh"))
{
hr = inMesh->ExportToSDKMESH(
outputPath,
inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data(),
(dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)) ? true : false,
(dwOptions & (uint64_t(1) << OPT_SDKMESH_V2)) ? true : false,
normalFormat,
uvFormat,
colorFormat);
}
else if (!_wcsicmp(outputExt, L".cmo"))
{
hr = inMesh->ExportToCMO(outputPath, inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data());
}
else if (!_wcsicmp(outputExt, L".obj") || !_wcsicmp(outputExt, L"._obj"))
{
wprintf(L"\nWARNING: WaveFront Object (.obj) not supported for UV visualization (requires Vertex Colors)\n");
}
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed uv mesh write (%08X%ls):-> '%ls'\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), outputPath);
return 1;
}
wprintf(L"uv mesh visualization '%ls'\n", outputPath);
}
}
return 0;
}
Fixed potential locale issue in parsing -flist
//--------------------------------------------------------------------------------------
// File: UVAtlas.cpp
//
// UVAtlas command-line tool (sample for UVAtlas library)
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=512686
//--------------------------------------------------------------------------------------
#pragma warning(push)
#pragma warning(disable : 4005)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#define NODRAWTEXT
#define NOGDI
#define NOMCX
#define NOSERVICE
#define NOHELP
#pragma warning(pop)
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cwchar>
#include <cwctype>
#include <fstream>
#include <iterator>
#include <list>
#include <locale>
#include <memory>
#include <new>
#include <set>
#include <string>
#include <tuple>
#include <conio.h>
#include <dxgiformat.h>
#include "UVAtlas.h"
#include "DirectXTex.h"
#include "Mesh.h"
//Uncomment to add support for OpenEXR (.exr)
//#define USE_OPENEXR
#ifdef USE_OPENEXR
// See <https://github.com/Microsoft/DirectXTex/wiki/Adding-OpenEXR> for details
#include "DirectXTexEXR.h"
#endif
using namespace DirectX;
namespace
{
enum OPTIONS : uint64_t
{
OPT_RECURSIVE = 1,
OPT_QUALITY,
OPT_MAXCHARTS,
OPT_MAXSTRETCH,
OPT_LIMIT_MERGE_STRETCH,
OPT_LIMIT_FACE_STRETCH,
OPT_GUTTER,
OPT_WIDTH,
OPT_HEIGHT,
OPT_TOPOLOGICAL_ADJ,
OPT_GEOMETRIC_ADJ,
OPT_NORMALS,
OPT_WEIGHT_BY_AREA,
OPT_WEIGHT_BY_EQUAL,
OPT_TANGENTS,
OPT_CTF,
OPT_COLOR_MESH,
OPT_UV_MESH,
OPT_IMT_TEXFILE,
OPT_IMT_VERTEX,
OPT_OUTPUTFILE,
OPT_TOLOWER,
OPT_SDKMESH,
OPT_SDKMESH_V2,
OPT_CMO,
OPT_VBO,
OPT_WAVEFRONT_OBJ,
OPT_CLOCKWISE,
OPT_FORCE_32BIT_IB,
OPT_OVERWRITE,
OPT_NODDS,
OPT_FLIP,
OPT_FLIPU,
OPT_FLIPV,
OPT_FLIPZ,
OPT_VERT_NORMAL_FORMAT,
OPT_VERT_UV_FORMAT,
OPT_VERT_COLOR_FORMAT,
OPT_SECOND_UV,
OPT_NOLOGO,
OPT_FILELIST,
OPT_MAX
};
static_assert(OPT_MAX <= 64, "dwOptions is a unsigned int bitfield");
enum CHANNELS
{
CHANNEL_NONE = 0,
CHANNEL_NORMAL,
CHANNEL_COLOR,
CHANNEL_TEXCOORD,
};
struct SConversion
{
wchar_t szSrc[MAX_PATH];
};
template<typename T>
struct SValue
{
const wchar_t* name;
T value;
};
const XMFLOAT3 g_ColorList[8] =
{
XMFLOAT3(1.0f, 0.5f, 0.5f),
XMFLOAT3(0.5f, 1.0f, 0.5f),
XMFLOAT3(1.0f, 1.0f, 0.5f),
XMFLOAT3(0.5f, 1.0f, 1.0f),
XMFLOAT3(1.0f, 0.5f, 0.75f),
XMFLOAT3(0.0f, 0.5f, 0.75f),
XMFLOAT3(0.5f, 0.5f, 0.75f),
XMFLOAT3(0.5f, 0.5f, 1.0f),
};
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
const SValue<uint64_t> g_pOptions[] =
{
{ L"r", OPT_RECURSIVE },
{ L"q", OPT_QUALITY },
{ L"n", OPT_MAXCHARTS },
{ L"st", OPT_MAXSTRETCH },
{ L"lms", OPT_LIMIT_MERGE_STRETCH },
{ L"lfs", OPT_LIMIT_FACE_STRETCH },
{ L"g", OPT_GUTTER },
{ L"w", OPT_WIDTH },
{ L"h", OPT_HEIGHT },
{ L"ta", OPT_TOPOLOGICAL_ADJ },
{ L"ga", OPT_GEOMETRIC_ADJ },
{ L"nn", OPT_NORMALS },
{ L"na", OPT_WEIGHT_BY_AREA },
{ L"ne", OPT_WEIGHT_BY_EQUAL },
{ L"tt", OPT_TANGENTS },
{ L"tb", OPT_CTF },
{ L"c", OPT_COLOR_MESH },
{ L"t", OPT_UV_MESH },
{ L"it", OPT_IMT_TEXFILE },
{ L"iv", OPT_IMT_VERTEX },
{ L"o", OPT_OUTPUTFILE },
{ L"l", OPT_TOLOWER },
{ L"sdkmesh", OPT_SDKMESH },
{ L"sdkmesh2", OPT_SDKMESH_V2 },
{ L"cmo", OPT_CMO },
{ L"vbo", OPT_VBO },
{ L"wf", OPT_WAVEFRONT_OBJ },
{ L"cw", OPT_CLOCKWISE },
{ L"ib32", OPT_FORCE_32BIT_IB },
{ L"y", OPT_OVERWRITE },
{ L"nodds", OPT_NODDS },
{ L"flip", OPT_FLIP },
{ L"flipu", OPT_FLIPU },
{ L"flipv", OPT_FLIPV },
{ L"flipz", OPT_FLIPZ },
{ L"fn", OPT_VERT_NORMAL_FORMAT },
{ L"fuv", OPT_VERT_UV_FORMAT },
{ L"fc", OPT_VERT_COLOR_FORMAT },
{ L"uv2", OPT_SECOND_UV },
{ L"nologo", OPT_NOLOGO },
{ L"flist", OPT_FILELIST },
{ nullptr, 0 }
};
const SValue<uint32_t> g_vertexNormalFormats[] =
{
{ L"float3", DXGI_FORMAT_R32G32B32_FLOAT },
{ L"float16_4", DXGI_FORMAT_R16G16B16A16_FLOAT },
{ L"r11g11b10", DXGI_FORMAT_R11G11B10_FLOAT },
{ nullptr, 0 }
};
const SValue<uint32_t> g_vertexUVFormats[] =
{
{ L"float2", DXGI_FORMAT_R32G32_FLOAT },
{ L"float16_2", DXGI_FORMAT_R16G16_FLOAT },
{ nullptr, 0 }
};
const SValue<uint32_t> g_vertexColorFormats[] =
{
{ L"bgra", DXGI_FORMAT_B8G8R8A8_UNORM },
{ L"rgba", DXGI_FORMAT_R8G8B8A8_UNORM },
{ L"float4", DXGI_FORMAT_R32G32B32A32_FLOAT },
{ L"float16_4", DXGI_FORMAT_R16G16B16A16_FLOAT },
{ L"rgba_10", DXGI_FORMAT_R10G10B10A2_UNORM },
{ L"r11g11b10", DXGI_FORMAT_R11G11B10_FLOAT },
{ nullptr, 0 }
};
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
HRESULT LoadFromOBJ(const wchar_t* szFilename,
std::unique_ptr<Mesh>& inMesh, std::vector<Mesh::Material>& inMaterial,
bool ccw, bool dds);
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
namespace
{
inline HANDLE safe_handle(HANDLE h) noexcept { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; }
struct find_closer { void operator()(HANDLE h) noexcept { assert(h != INVALID_HANDLE_VALUE); if (h) FindClose(h); } };
using ScopedFindHandle = std::unique_ptr<void, find_closer>;
#ifdef __PREFAST__
#pragma prefast(disable : 26018, "Only used with static internal arrays")
#endif
template<typename T>
T LookupByName(const wchar_t *pName, const SValue<T> *pArray)
{
while (pArray->name)
{
if (!_wcsicmp(pName, pArray->name))
return pArray->value;
pArray++;
}
return 0;
}
void SearchForFiles(const wchar_t* path, std::list<SConversion>& files, bool recursive)
{
// Process files
WIN32_FIND_DATAW findData = {};
ScopedFindHandle hFile(safe_handle(FindFirstFileExW(path,
FindExInfoBasic, &findData,
FindExSearchNameMatch, nullptr,
FIND_FIRST_EX_LARGE_FETCH)));
if (hFile)
{
for (;;)
{
if (!(findData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_DIRECTORY)))
{
wchar_t drive[_MAX_DRIVE] = {};
wchar_t dir[_MAX_DIR] = {};
_wsplitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0);
SConversion conv = {};
_wmakepath_s(conv.szSrc, drive, dir, findData.cFileName, nullptr);
files.push_back(conv);
}
if (!FindNextFileW(hFile.get(), &findData))
break;
}
}
// Process directories
if (recursive)
{
wchar_t searchDir[MAX_PATH] = {};
{
wchar_t drive[_MAX_DRIVE] = {};
wchar_t dir[_MAX_DIR] = {};
_wsplitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0);
_wmakepath_s(searchDir, drive, dir, L"*", nullptr);
}
hFile.reset(safe_handle(FindFirstFileExW(searchDir,
FindExInfoBasic, &findData,
FindExSearchLimitToDirectories, nullptr,
FIND_FIRST_EX_LARGE_FETCH)));
if (!hFile)
return;
for (;;)
{
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (findData.cFileName[0] != L'.')
{
wchar_t subdir[MAX_PATH] = {};
{
wchar_t drive[_MAX_DRIVE] = {};
wchar_t dir[_MAX_DIR] = {};
wchar_t fname[_MAX_FNAME] = {};
wchar_t ext[_MAX_FNAME] = {};
_wsplitpath_s(path, drive, dir, fname, ext);
wcscat_s(dir, findData.cFileName);
_wmakepath_s(subdir, drive, dir, fname, ext);
}
SearchForFiles(subdir, files, recursive);
}
}
if (!FindNextFileW(hFile.get(), &findData))
break;
}
}
}
void ProcessFileList(std::wifstream& inFile, std::list<SConversion>& files)
{
std::list<SConversion> flist;
std::set<std::wstring> excludes;
wchar_t fname[1024] = {};
for (;;)
{
inFile >> fname;
if (!inFile)
break;
if (*fname == L'#')
{
// Comment
}
else if (*fname == L'-')
{
if (flist.empty())
{
wprintf(L"WARNING: Ignoring the line '%ls' in -flist\n", fname);
}
else
{
if (wcspbrk(fname, L"?*") != nullptr)
{
std::list<SConversion> removeFiles;
SearchForFiles(&fname[1], removeFiles, false);
for (auto it : removeFiles)
{
_wcslwr_s(it.szSrc);
excludes.insert(it.szSrc);
}
}
else
{
std::wstring name = (fname + 1);
std::transform(name.begin(), name.end(), name.begin(), towlower);
excludes.insert(name);
}
}
}
else if (wcspbrk(fname, L"?*") != nullptr)
{
SearchForFiles(fname, flist, false);
}
else
{
SConversion conv = {};
wcscpy_s(conv.szSrc, MAX_PATH, fname);
flist.push_back(conv);
}
inFile.ignore(1000, '\n');
}
inFile.close();
if (!excludes.empty())
{
// Remove any excluded files
for (auto it = flist.begin(); it != flist.end();)
{
std::wstring name = it->szSrc;
std::transform(name.begin(), name.end(), name.begin(), towlower);
auto item = it;
++it;
if (excludes.find(name) != excludes.end())
{
flist.erase(item);
}
}
}
if (flist.empty())
{
wprintf(L"WARNING: No file names found in -flist\n");
}
else
{
files.splice(files.end(), flist);
}
}
void PrintList(size_t cch, const SValue<uint32_t>* pValue)
{
while (pValue->name)
{
size_t cchName = wcslen(pValue->name);
if (cch + cchName + 2 >= 80)
{
wprintf(L"\n ");
cch = 6;
}
wprintf(L"%ls ", pValue->name);
cch += cchName + 2;
pValue++;
}
wprintf(L"\n");
}
void PrintLogo()
{
wchar_t version[32] = {};
wchar_t appName[_MAX_PATH] = {};
if (GetModuleFileNameW(nullptr, appName, static_cast<DWORD>(std::size(appName))))
{
DWORD size = GetFileVersionInfoSizeW(appName, nullptr);
if (size > 0)
{
auto verInfo = std::make_unique<uint8_t[]>(size);
if (GetFileVersionInfoW(appName, 0, size, verInfo.get()))
{
LPVOID lpstr = nullptr;
UINT strLen = 0;
if (VerQueryValueW(verInfo.get(), L"\\StringFileInfo\\040904B0\\ProductVersion", &lpstr, &strLen))
{
wcsncpy_s(version, reinterpret_cast<const wchar_t*>(lpstr), strLen);
}
}
}
}
if (!*version || wcscmp(version, L"1.0.0.0") == 0)
{
swprintf_s(version, L"%03d (library)", UVATLAS_VERSION);
}
wprintf(L"Microsoft (R) UVAtlas Command-line Tool Version %ls\n", version);
wprintf(L"Copyright (C) Microsoft Corp.\n");
#ifdef _DEBUG
wprintf(L"*** Debug build ***\n");
#endif
wprintf(L"\n");
}
void PrintUsage()
{
PrintLogo();
wprintf(L"Usage: uvatlas <options> <files>\n");
wprintf(L"\n");
wprintf(L" Input file type must be Wavefront Object (.obj)\n\n");
wprintf(L" Output file type:\n");
wprintf(L" -sdkmesh DirectX SDK .sdkmesh format (default)\n");
wprintf(L" -sdkmesh2 .sdkmesh format version 2 (PBR materials)\n");
wprintf(L" -cmo Visual Studio Content Pipeline .cmo format\n");
wprintf(L" -vbo Vertex Buffer Object (.vbo) format\n");
wprintf(L" -wf WaveFront Object (.obj) format\n\n");
wprintf(L" -r wildcard filename search is recursive\n");
wprintf(L" -q <level> sets quality level to DEFAULT, FAST or QUALITY\n");
wprintf(L" -n <number> maximum number of charts to generate (def: 0)\n");
wprintf(L" -st <float> maximum amount of stretch 0.0 to 1.0 (def: 0.16667)\n");
wprintf(L" -lms enable limit merge stretch option\n");
wprintf(L" -lfs enable limit face stretch option\n");
wprintf(L" -g <float> the gutter width betwen charts in texels (def: 2.0)\n");
wprintf(L" -w <number> texture width (def: 512)\n");
wprintf(L" -h <number> texture height (def: 512)\n");
wprintf(L" -ta | -ga generate topological vs. geometric adjancecy (def: ta)\n");
wprintf(L" -nn | -na | -ne generate normals weighted by angle/area/equal\n");
wprintf(L" -tt generate tangents\n");
wprintf(L" -tb generate tangents & bi-tangents\n");
wprintf(L" -cw faces are clockwise (defaults to counter-clockwise)\n");
wprintf(L" -c generate mesh with colors showing charts\n");
wprintf(L" -t generates a separate mesh with uvs - (*_texture)\n");
wprintf(L" -it <filename> calculate IMT for the mesh using this texture map\n");
wprintf(
L" -iv <channel> calculate IMT using per-vertex data\n"
L" NORMAL, COLOR, TEXCOORD\n");
wprintf(L" -nodds prevents extension renaming in exported materials\n");
wprintf(L" -flip reverse winding of faces\n");
wprintf(L" -flipu inverts the u texcoords\n");
wprintf(L" -flipv inverts the v texcoords\n");
wprintf(L" -flipz flips the handedness of the positions/normals\n");
wprintf(L" -o <filename> output filename\n");
wprintf(L" -l force output filename to lower case\n");
wprintf(L" -y overwrite existing output file (if any)\n");
wprintf(L" -nologo suppress copyright message\n");
wprintf(L" -flist <filename> use text file with a list of input files (one per line)\n");
wprintf(L"\n (sdkmesh/sdkmesh2 only)\n");
wprintf(L" -ib32 use 32-bit index buffer\n");
wprintf(L" -fn <normal-format> format to use for writing normals/tangents/normals\n");
wprintf(L" -fuv <uv-format> format to use for texture coordinates\n");
wprintf(L" -fc <color-format> format to use for writing colors\n");
wprintf(L" -uv2 place uvatlas uvs into a second texture coordinate channel\n");
wprintf(L"\n <normal-format>: ");
PrintList(13, g_vertexNormalFormats);
wprintf(L"\n <uv-format>: ");
PrintList(13, g_vertexUVFormats);
wprintf(L"\n <color-format>: ");
PrintList(13, g_vertexColorFormats);
}
const wchar_t* GetErrorDesc(HRESULT hr)
{
static wchar_t desc[1024] = {};
LPWSTR errorText = nullptr;
DWORD result = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
nullptr, static_cast<DWORD>(hr),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&errorText), 0, nullptr);
*desc = 0;
if (result > 0 && errorText)
{
swprintf_s(desc, L": %ls", errorText);
size_t len = wcslen(desc);
if (len >= 2)
{
desc[len - 2] = 0;
desc[len - 1] = 0;
}
if (errorText)
LocalFree(errorText);
}
return desc;
}
//--------------------------------------------------------------------------------------
HRESULT __cdecl UVAtlasCallback(float fPercentDone)
{
static ULONGLONG s_lastTick = 0;
ULONGLONG tick = GetTickCount64();
if ((tick - s_lastTick) > 1000)
{
wprintf(L"%.2f%% \r", double(fPercentDone) * 100);
s_lastTick = tick;
}
if (_kbhit())
{
if (_getch() == 27)
{
wprintf(L"*** ABORT ***");
return E_ABORT;
}
}
return S_OK;
}
}
//--------------------------------------------------------------------------------------
// Entry-point
//--------------------------------------------------------------------------------------
#ifdef __PREFAST__
#pragma prefast(disable : 28198, "Command-line tool, frees all memory on exit")
#endif
int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[])
{
// Parameters and defaults
size_t maxCharts = 0;
float maxStretch = 0.16667f;
float gutter = 2.f;
size_t width = 512;
size_t height = 512;
CHANNELS perVertex = CHANNEL_NONE;
UVATLAS uvOptions = UVATLAS_DEFAULT;
UVATLAS uvOptionsEx = UVATLAS_DEFAULT;
DXGI_FORMAT normalFormat = DXGI_FORMAT_R32G32B32_FLOAT;
DXGI_FORMAT uvFormat = DXGI_FORMAT_R32G32_FLOAT;
DXGI_FORMAT colorFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
wchar_t szTexFile[MAX_PATH] = {};
wchar_t szOutputFile[MAX_PATH] = {};
// Set locale for output since GetErrorDesc can get localized strings.
std::locale::global(std::locale(""));
// Initialize COM (needed for WIC)
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if (FAILED(hr))
{
wprintf(L"Failed to initialize COM (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
// Process command line
uint64_t dwOptions = 0;
std::list<SConversion> conversion;
for (int iArg = 1; iArg < argc; iArg++)
{
PWSTR pArg = argv[iArg];
if (('-' == pArg[0]) || ('/' == pArg[0]))
{
pArg++;
PWSTR pValue;
for (pValue = pArg; *pValue && (':' != *pValue); pValue++);
if (*pValue)
*pValue++ = 0;
uint64_t dwOption = LookupByName(pArg, g_pOptions);
if (!dwOption || (dwOptions & (uint64_t(1) << dwOption)))
{
wprintf(L"ERROR: unknown command-line option '%ls'\n\n", pArg);
PrintUsage();
return 1;
}
dwOptions |= (uint64_t(1) << dwOption);
// Handle options with additional value parameter
switch (dwOption)
{
case OPT_QUALITY:
case OPT_MAXCHARTS:
case OPT_MAXSTRETCH:
case OPT_GUTTER:
case OPT_WIDTH:
case OPT_HEIGHT:
case OPT_IMT_TEXFILE:
case OPT_IMT_VERTEX:
case OPT_OUTPUTFILE:
case OPT_VERT_NORMAL_FORMAT:
case OPT_VERT_UV_FORMAT:
case OPT_VERT_COLOR_FORMAT:
case OPT_FILELIST:
if (!*pValue)
{
if ((iArg + 1 >= argc))
{
wprintf(L"ERROR: missing value for command-line option '%ls'\n\n", pArg);
PrintUsage();
return 1;
}
iArg++;
pValue = argv[iArg];
}
break;
}
switch (dwOption)
{
case OPT_QUALITY:
if (!_wcsicmp(pValue, L"DEFAULT"))
{
uvOptions = UVATLAS_DEFAULT;
}
else if (!_wcsicmp(pValue, L"FAST"))
{
uvOptions = UVATLAS_GEODESIC_FAST;
}
else if (!_wcsicmp(pValue, L"QUALITY"))
{
uvOptions = UVATLAS_GEODESIC_QUALITY;
}
else
{
wprintf(L"Invalid value specified with -q (%ls)\n", pValue);
return 1;
}
break;
case OPT_LIMIT_MERGE_STRETCH:
uvOptionsEx |= UVATLAS_LIMIT_MERGE_STRETCH;
break;
case OPT_LIMIT_FACE_STRETCH:
uvOptionsEx |= UVATLAS_LIMIT_FACE_STRETCH;
break;
case OPT_MAXCHARTS:
if (swscanf_s(pValue, L"%zu", &maxCharts) != 1)
{
wprintf(L"Invalid value specified with -n (%ls)\n", pValue);
return 1;
}
break;
case OPT_MAXSTRETCH:
if (swscanf_s(pValue, L"%f", &maxStretch) != 1
|| maxStretch < 0.f
|| maxStretch > 1.f)
{
wprintf(L"Invalid value specified with -st (%ls)\n", pValue);
return 1;
}
break;
case OPT_GUTTER:
if (swscanf_s(pValue, L"%f", &gutter) != 1
|| gutter < 0.f)
{
wprintf(L"Invalid value specified with -g (%ls)\n", pValue);
return 1;
}
break;
case OPT_WIDTH:
if (swscanf_s(pValue, L"%zu", &width) != 1)
{
wprintf(L"Invalid value specified with -w (%ls)\n", pValue);
return 1;
}
break;
case OPT_HEIGHT:
if (swscanf_s(pValue, L"%zu", &height) != 1)
{
wprintf(L"Invalid value specified with -h (%ls)\n", pValue);
return 1;
}
break;
case OPT_WEIGHT_BY_AREA:
if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_EQUAL))
{
wprintf(L"Can only use one of nn, na, or ne\n");
return 1;
}
dwOptions |= (uint64_t(1) << OPT_NORMALS);
break;
case OPT_WEIGHT_BY_EQUAL:
if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_AREA))
{
wprintf(L"Can only use one of nn, na, or ne\n");
return 1;
}
dwOptions |= (uint64_t(1) << OPT_NORMALS);
break;
case OPT_IMT_TEXFILE:
if (dwOptions & (uint64_t(1) << OPT_IMT_VERTEX))
{
wprintf(L"Cannot use both if and iv at the same time\n");
return 1;
}
wcscpy_s(szTexFile, MAX_PATH, pValue);
break;
case OPT_IMT_VERTEX:
if (dwOptions & (uint64_t(1) << OPT_IMT_TEXFILE))
{
wprintf(L"Cannot use both if and iv at the same time\n");
return 1;
}
if (!_wcsicmp(pValue, L"COLOR"))
{
perVertex = CHANNEL_COLOR;
}
else if (!_wcsicmp(pValue, L"NORMAL"))
{
perVertex = CHANNEL_NORMAL;
}
else if (!_wcsicmp(pValue, L"TEXCOORD"))
{
perVertex = CHANNEL_TEXCOORD;
}
else
{
wprintf(L"Invalid value specified with -iv (%ls)\n", pValue);
return 1;
}
break;
case OPT_OUTPUTFILE:
wcscpy_s(szOutputFile, MAX_PATH, pValue);
break;
case OPT_TOPOLOGICAL_ADJ:
if (dwOptions & (uint64_t(1) << OPT_GEOMETRIC_ADJ))
{
wprintf(L"Cannot use both ta and ga at the same time\n");
return 1;
}
break;
case OPT_GEOMETRIC_ADJ:
if (dwOptions & (uint64_t(1) << OPT_TOPOLOGICAL_ADJ))
{
wprintf(L"Cannot use both ta and ga at the same time\n");
return 1;
}
break;
case OPT_SDKMESH:
case OPT_SDKMESH_V2:
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_CMO) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
if (dwOption == OPT_SDKMESH_V2)
{
dwOptions |= (uint64_t(1) << OPT_SDKMESH);
}
break;
case OPT_CMO:
if (dwOptions & (uint64_t(1) << OPT_SECOND_UV))
{
wprintf(L"-uv2 is not supported by CMO\n");
return 1;
}
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_SDKMESH) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
break;
case OPT_VBO:
if (dwOptions & (uint64_t(1) << OPT_SECOND_UV))
{
wprintf(L"-uv2 is not supported by VBO\n");
return 1;
}
if (dwOptions & ((uint64_t(1) << OPT_SDKMESH) | (uint64_t(1) << OPT_CMO) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
break;
case OPT_WAVEFRONT_OBJ:
if (dwOptions & (uint64_t(1) << OPT_SECOND_UV))
{
wprintf(L"-uv2 is not supported by Wavefront OBJ\n");
return 1;
}
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_SDKMESH) | (uint64_t(1) << OPT_CMO)))
{
wprintf(L"Can only use one of sdkmesh, cmo, vbo, or wf\n");
return 1;
}
break;
case OPT_SECOND_UV:
if (dwOptions & ((uint64_t(1) << OPT_VBO) | (uint64_t(1) << OPT_CMO) | (uint64_t(1) << OPT_WAVEFRONT_OBJ)))
{
wprintf(L"-uv2 is only supported by sdkmesh\n");
return 1;
}
break;
case OPT_VERT_NORMAL_FORMAT:
normalFormat = static_cast<DXGI_FORMAT>(LookupByName(pValue, g_vertexNormalFormats));
if (!normalFormat)
{
wprintf(L"Invalid value specified with -fn (%ls)\n", pValue);
wprintf(L"\n");
PrintUsage();
return 1;
}
break;
case OPT_VERT_UV_FORMAT:
uvFormat = static_cast<DXGI_FORMAT>(LookupByName(pValue, g_vertexUVFormats));
if (!uvFormat)
{
wprintf(L"Invalid value specified with -fuv (%ls)\n", pValue);
wprintf(L"\n");
PrintUsage();
return 1;
}
break;
case OPT_VERT_COLOR_FORMAT:
colorFormat = static_cast<DXGI_FORMAT>(LookupByName(pValue, g_vertexColorFormats));
if (!colorFormat)
{
wprintf(L"Invalid value specified with -fc (%ls)\n", pValue);
wprintf(L"\n");
PrintUsage();
return 1;
}
break;
case OPT_FILELIST:
{
std::wifstream inFile(pValue);
if (!inFile)
{
wprintf(L"Error opening -flist file %ls\n", pValue);
return 1;
}
inFile.imbue(std::locale::classic());
ProcessFileList(inFile, conversion);
}
break;
}
}
else if (wcspbrk(pArg, L"?*") != nullptr)
{
size_t count = conversion.size();
SearchForFiles(pArg, conversion, (dwOptions & (uint64_t(1) << OPT_RECURSIVE)) != 0);
if (conversion.size() <= count)
{
wprintf(L"No matching files found for %ls\n", pArg);
return 1;
}
}
else
{
SConversion conv = {};
wcscpy_s(conv.szSrc, MAX_PATH, pArg);
conversion.push_back(conv);
}
}
if (conversion.empty())
{
PrintUsage();
return 0;
}
if (*szOutputFile && conversion.size() > 1)
{
wprintf(L"Cannot use -o with multiple input files\n");
return 1;
}
if (~dwOptions & (uint64_t(1) << OPT_NOLOGO))
PrintLogo();
// Process files
for (auto pConv = conversion.begin(); pConv != conversion.end(); ++pConv)
{
wchar_t ext[_MAX_EXT] = {};
wchar_t fname[_MAX_FNAME] = {};
_wsplitpath_s(pConv->szSrc, nullptr, 0, nullptr, 0, fname, _MAX_FNAME, ext, _MAX_EXT);
if (pConv != conversion.begin())
wprintf(L"\n");
wprintf(L"reading %ls", pConv->szSrc);
fflush(stdout);
std::unique_ptr<Mesh> inMesh;
std::vector<Mesh::Material> inMaterial;
hr = E_NOTIMPL;
if (_wcsicmp(ext, L".vbo") == 0)
{
hr = Mesh::CreateFromVBO(pConv->szSrc, inMesh);
}
else if (_wcsicmp(ext, L".sdkmesh") == 0)
{
wprintf(L"\nERROR: Importing SDKMESH files not supported\n");
return 1;
}
else if (_wcsicmp(ext, L".cmo") == 0)
{
wprintf(L"\nERROR: Importing Visual Studio CMO files not supported\n");
return 1;
}
else if (_wcsicmp(ext, L".x") == 0)
{
wprintf(L"\nERROR: Legacy Microsoft X files not supported\n");
return 1;
}
else if (_wcsicmp(ext, L".fbx") == 0)
{
wprintf(L"\nERROR: Autodesk FBX files not supported\n");
return 1;
}
else
{
hr = LoadFromOBJ(pConv->szSrc, inMesh, inMaterial,
(dwOptions & (uint64_t(1) << OPT_CLOCKWISE)) ? false : true,
(dwOptions & (uint64_t(1) << OPT_NODDS)) ? false : true);
}
if (FAILED(hr))
{
wprintf(L" FAILED (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
size_t nVerts = inMesh->GetVertexCount();
size_t nFaces = inMesh->GetFaceCount();
if (!nVerts || !nFaces)
{
wprintf(L"\nERROR: Invalid mesh\n");
return 1;
}
assert(inMesh->GetPositionBuffer() != nullptr);
assert(inMesh->GetIndexBuffer() != nullptr);
wprintf(L"\n%zu vertices, %zu faces", nVerts, nFaces);
if (dwOptions & (uint64_t(1) << OPT_FLIPU))
{
hr = inMesh->InvertUTexCoord();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed inverting u texcoord (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_FLIPV))
{
hr = inMesh->InvertVTexCoord();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed inverting v texcoord (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_FLIPZ))
{
hr = inMesh->ReverseHandedness();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed reversing handedness (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Prepare mesh for processing
{
// Adjacency
float epsilon = (dwOptions & (uint64_t(1) << OPT_GEOMETRIC_ADJ)) ? 1e-5f : 0.f;
hr = inMesh->GenerateAdjacency(epsilon);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed generating adjacency (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
// Validation
std::wstring msgs;
hr = inMesh->Validate(VALIDATE_BACKFACING | VALIDATE_BOWTIES, &msgs);
if (!msgs.empty())
{
wprintf(L"\nWARNING: \n");
wprintf(L"%ls", msgs.c_str());
}
// Clean
hr = inMesh->Clean(true);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed mesh clean (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
else
{
size_t nNewVerts = inMesh->GetVertexCount();
if (nVerts != nNewVerts)
{
wprintf(L" [%zu vertex dups] ", nNewVerts - nVerts);
nVerts = nNewVerts;
}
}
}
if (!inMesh->GetNormalBuffer())
{
dwOptions |= uint64_t(1) << OPT_NORMALS;
}
if (!inMesh->GetTangentBuffer() && (dwOptions & (uint64_t(1) << OPT_CMO)))
{
dwOptions |= uint64_t(1) << OPT_TANGENTS;
}
// Compute vertex normals from faces
if ((dwOptions & (uint64_t(1) << OPT_NORMALS))
|| ((dwOptions & ((uint64_t(1) << OPT_TANGENTS) | (uint64_t(1) << OPT_CTF))) && !inMesh->GetNormalBuffer()))
{
CNORM_FLAGS flags = CNORM_DEFAULT;
if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_EQUAL))
{
flags |= CNORM_WEIGHT_EQUAL;
}
else if (dwOptions & (uint64_t(1) << OPT_WEIGHT_BY_AREA))
{
flags |= CNORM_WEIGHT_BY_AREA;
}
if (dwOptions & (uint64_t(1) << OPT_CLOCKWISE))
{
flags |= CNORM_WIND_CW;
}
hr = inMesh->ComputeNormals(flags);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed computing normals (flags:%lX, %08X%ls)\n", flags,
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Compute tangents and bitangents
if (dwOptions & ((uint64_t(1) << OPT_TANGENTS) | (uint64_t(1) << OPT_CTF)))
{
if (!inMesh->GetTexCoordBuffer())
{
wprintf(L"\nERROR: Computing tangents/bi-tangents requires texture coordinates\n");
return 1;
}
hr = inMesh->ComputeTangentFrame((dwOptions & (uint64_t(1) << OPT_CTF)) ? true : false);
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed computing tangent frame (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Compute IMT
std::unique_ptr<float[]> IMTData;
if (dwOptions & ((uint64_t(1) << OPT_IMT_TEXFILE) | (uint64_t(1) << OPT_IMT_VERTEX)))
{
if (dwOptions & (uint64_t(1) << OPT_IMT_TEXFILE))
{
if (!inMesh->GetTexCoordBuffer())
{
wprintf(L"\nERROR: Computing IMT from texture requires texture coordinates\n");
return 1;
}
wchar_t txext[_MAX_EXT] = {};
_wsplitpath_s(szTexFile, nullptr, 0, nullptr, 0, nullptr, 0, txext, _MAX_EXT);
ScratchImage iimage;
if (_wcsicmp(txext, L".dds") == 0)
{
hr = LoadFromDDSFile(szTexFile, DDS_FLAGS_NONE, nullptr, iimage);
}
else if (_wcsicmp(ext, L".tga") == 0)
{
hr = LoadFromTGAFile(szTexFile, nullptr, iimage);
}
else if (_wcsicmp(ext, L".hdr") == 0)
{
hr = LoadFromHDRFile(szTexFile, nullptr, iimage);
}
#ifdef USE_OPENEXR
else if (_wcsicmp(ext, L".exr") == 0)
{
hr = LoadFromEXRFile(szTexFile, nullptr, iimage);
}
#endif
else
{
hr = LoadFromWICFile(szTexFile, WIC_FLAGS_NONE, nullptr, iimage);
}
if (FAILED(hr))
{
wprintf(L"\nWARNING: Failed to load texture for IMT (%08X%ls):\n%ls\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), szTexFile);
}
else
{
const Image* img = iimage.GetImage(0, 0, 0);
ScratchImage floatImage;
if (img->format != DXGI_FORMAT_R32G32B32A32_FLOAT)
{
hr = Convert(*iimage.GetImage(0, 0, 0), DXGI_FORMAT_R32G32B32A32_FLOAT, TEX_FILTER_DEFAULT,
TEX_THRESHOLD_DEFAULT, floatImage);
if (FAILED(hr))
{
img = nullptr;
wprintf(L"\nWARNING: Failed converting texture for IMT (%08X%ls):\n%ls\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), szTexFile);
}
else
{
img = floatImage.GetImage(0, 0, 0);
}
}
if (img)
{
wprintf(L"\nComputing IMT from file %ls...\n", szTexFile);
IMTData.reset(new (std::nothrow) float[nFaces * 3]);
if (!IMTData)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
hr = UVAtlasComputeIMTFromTexture(inMesh->GetPositionBuffer(), inMesh->GetTexCoordBuffer(), nVerts,
inMesh->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, nFaces,
reinterpret_cast<const float*>(img->pixels), img->width, img->height,
UVATLAS_IMT_DEFAULT, UVAtlasCallback, IMTData.get());
if (FAILED(hr))
{
IMTData.reset();
wprintf(L"WARNING: Failed to compute IMT from texture (%08X%ls):\n%ls\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), szTexFile);
}
}
}
}
else
{
const wchar_t* szChannel = L"*unknown*";
const float* pSignal = nullptr;
size_t signalDim = 0;
size_t signalStride = 0;
switch (perVertex)
{
case CHANNEL_NORMAL:
szChannel = L"normals";
if (inMesh->GetNormalBuffer())
{
pSignal = reinterpret_cast<const float*>(inMesh->GetNormalBuffer());
signalDim = 3;
signalStride = sizeof(XMFLOAT3);
}
break;
case CHANNEL_COLOR:
szChannel = L"vertex colors";
if (inMesh->GetColorBuffer())
{
pSignal = reinterpret_cast<const float*>(inMesh->GetColorBuffer());
signalDim = 4;
signalStride = sizeof(XMFLOAT4);
}
break;
case CHANNEL_TEXCOORD:
szChannel = L"texture coordinates";
if (inMesh->GetTexCoordBuffer())
{
pSignal = reinterpret_cast<const float*>(inMesh->GetTexCoordBuffer());
signalDim = 2;
signalStride = sizeof(XMFLOAT2);
}
break;
}
if (!pSignal)
{
wprintf(L"\nWARNING: Mesh does not have channel %ls for IMT\n", szChannel);
}
else
{
wprintf(L"\nComputing IMT from %ls...\n", szChannel);
IMTData.reset(new (std::nothrow) float[nFaces * 3]);
if (!IMTData)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
hr = UVAtlasComputeIMTFromPerVertexSignal(inMesh->GetPositionBuffer(), nVerts,
inMesh->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, nFaces,
pSignal, signalDim, signalStride, UVAtlasCallback, IMTData.get());
if (FAILED(hr))
{
IMTData.reset();
wprintf(L"WARNING: Failed to compute IMT from channel %ls (%08X%ls)\n",
szChannel, static_cast<unsigned int>(hr), GetErrorDesc(hr));
}
}
}
}
else
{
wprintf(L"\n");
}
// Perform UVAtlas isocharting
wprintf(L"Computing isochart atlas on mesh...\n");
std::vector<UVAtlasVertex> vb;
std::vector<uint8_t> ib;
float outStretch = 0.f;
size_t outCharts = 0;
std::vector<uint32_t> facePartitioning;
std::vector<uint32_t> vertexRemapArray;
hr = UVAtlasCreate(inMesh->GetPositionBuffer(), nVerts,
inMesh->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, nFaces,
maxCharts, maxStretch, width, height, gutter,
inMesh->GetAdjacencyBuffer(), nullptr,
IMTData.get(),
UVAtlasCallback, UVATLAS_DEFAULT_CALLBACK_FREQUENCY,
uvOptions | uvOptionsEx, vb, ib,
&facePartitioning,
&vertexRemapArray,
&outStretch, &outCharts);
if (FAILED(hr))
{
if (hr == HRESULT_FROM_WIN32(ERROR_INVALID_DATA))
{
wprintf(L"\nERROR: Non-manifold mesh\n");
return 1;
}
else
{
wprintf(L"\nERROR: Failed creating isocharts (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
wprintf(L"Output # of charts: %zu, resulting stretching %f, %zu verts\n", outCharts, double(outStretch), vb.size());
assert((ib.size() / sizeof(uint32_t)) == (nFaces * 3));
assert(facePartitioning.size() == nFaces);
assert(vertexRemapArray.size() == vb.size());
hr = inMesh->UpdateFaces(nFaces, reinterpret_cast<const uint32_t*>(ib.data()));
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed applying atlas indices (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
hr = inMesh->VertexRemap(vertexRemapArray.data(), vertexRemapArray.size());
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed applying atlas vertex remap (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
nVerts = vb.size();
#ifdef _DEBUG
std::wstring msgs;
hr = inMesh->Validate(VALIDATE_DEFAULT, &msgs);
if (!msgs.empty())
{
wprintf(L"\nWARNING: \n%ls\n", msgs.c_str());
}
#endif
// Copy isochart UVs into mesh
{
std::unique_ptr<XMFLOAT2[]> texcoord(new (std::nothrow) XMFLOAT2[nVerts]);
if (!texcoord)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
auto txptr = texcoord.get();
size_t j = 0;
for (auto it = vb.cbegin(); it != vb.cend() && j < nVerts; ++it, ++txptr)
{
*txptr = it->uv;
}
hr = inMesh->UpdateUVs(nVerts, texcoord.get(), (dwOptions & (uint64_t(1) << OPT_SECOND_UV)));
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed to update with isochart UVs\n");
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_COLOR_MESH))
{
inMaterial.clear();
inMaterial.reserve(std::size(g_ColorList));
for (size_t j = 0; j < std::size(g_ColorList) && (j < outCharts); ++j)
{
Mesh::Material mtl = {};
wchar_t matname[32] = {};
swprintf_s(matname, L"Chart%02zu", j + 1);
mtl.name = matname;
mtl.specularPower = 1.f;
mtl.alpha = 1.f;
XMVECTOR v = XMLoadFloat3(&g_ColorList[j]);
XMStoreFloat3(&mtl.diffuseColor, v);
v = XMVectorScale(v, 0.2f);
XMStoreFloat3(&mtl.ambientColor, v);
inMaterial.push_back(mtl);
}
std::unique_ptr<uint32_t[]> attr(new (std::nothrow) uint32_t[nFaces]);
if (!attr)
{
wprintf(L"\nERROR: out of memory\n");
return 1;
}
size_t j = 0;
for (auto it = facePartitioning.cbegin(); it != facePartitioning.cend(); ++it, ++j)
{
attr[j] = *it % std::size(g_ColorList);
}
hr = inMesh->UpdateAttributes(nFaces, attr.get());
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed applying atlas attributes (%08X%ls)\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
if (dwOptions & (uint64_t(1) << OPT_FLIP))
{
hr = inMesh->ReverseWinding();
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed reversing winding (%08X%ls)\n", static_cast<unsigned int>(hr), GetErrorDesc(hr));
return 1;
}
}
// Write results
wprintf(L"\n\t->\n");
wchar_t outputPath[MAX_PATH] = {};
wchar_t outputExt[_MAX_EXT] = {};
if (*szOutputFile)
{
wcscpy_s(outputPath, szOutputFile);
_wsplitpath_s(szOutputFile, nullptr, 0, nullptr, 0, nullptr, 0, outputExt, _MAX_EXT);
}
else
{
if (dwOptions & (uint64_t(1) << OPT_VBO))
{
wcscpy_s(outputExt, L".vbo");
}
else if (dwOptions & (uint64_t(1) << OPT_CMO))
{
wcscpy_s(outputExt, L".cmo");
}
else if (dwOptions & (uint64_t(1) << OPT_WAVEFRONT_OBJ))
{
wcscpy_s(outputExt, L".obj");
}
else
{
wcscpy_s(outputExt, L".sdkmesh");
}
wchar_t outFilename[_MAX_FNAME] = {};
wcscpy_s(outFilename, fname);
_wmakepath_s(outputPath, nullptr, nullptr, outFilename, outputExt);
}
if (dwOptions & (uint64_t(1) << OPT_TOLOWER))
{
std::ignore = _wcslwr_s(outputPath);
}
if (~dwOptions & (uint64_t(1) << OPT_OVERWRITE))
{
if (GetFileAttributesW(outputPath) != INVALID_FILE_ATTRIBUTES)
{
wprintf(L"\nERROR: Output file already exists, use -y to overwrite:\n'%ls'\n", outputPath);
return 1;
}
}
if (!_wcsicmp(outputExt, L".vbo"))
{
if (!inMesh->GetNormalBuffer() || !inMesh->GetTexCoordBuffer())
{
wprintf(L"\nERROR: VBO requires position, normal, and texcoord\n");
return 1;
}
if (!inMesh->Is16BitIndexBuffer() || (dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)))
{
wprintf(L"\nERROR: VBO only supports 16-bit indices\n");
return 1;
}
hr = inMesh->ExportToVBO(outputPath);
}
else if (!_wcsicmp(outputExt, L".sdkmesh"))
{
hr = inMesh->ExportToSDKMESH(
outputPath,
inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data(),
(dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)) ? true : false,
(dwOptions & (uint64_t(1) << OPT_SDKMESH_V2)) ? true : false,
normalFormat,
uvFormat,
colorFormat);
}
else if (!_wcsicmp(outputExt, L".cmo"))
{
if (!inMesh->GetNormalBuffer() || !inMesh->GetTexCoordBuffer() || !inMesh->GetTangentBuffer())
{
wprintf(L"\nERROR: Visual Studio CMO requires position, normal, tangents, and texcoord\n");
return 1;
}
if (!inMesh->Is16BitIndexBuffer() || (dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)))
{
wprintf(L"\nERROR: Visual Studio CMO only supports 16-bit indices\n");
return 1;
}
hr = inMesh->ExportToCMO(outputPath, inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data());
}
else if (!_wcsicmp(outputExt, L".obj") || !_wcsicmp(outputExt, L"._obj"))
{
hr = inMesh->ExportToOBJ(outputPath, inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data());
}
else if (!_wcsicmp(outputExt, L".x"))
{
wprintf(L"\nERROR: Legacy Microsoft X files not supported\n");
return 1;
}
else
{
wprintf(L"\nERROR: Unknown output file type '%ls'\n", outputExt);
return 1;
}
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed write (%08X%ls):-> '%ls'\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), outputPath);
return 1;
}
wprintf(L" %zu vertices, %zu faces written:\n'%ls'\n", nVerts, nFaces, outputPath);
// Write out UV mesh visualization
if (dwOptions & (uint64_t(1) << OPT_UV_MESH))
{
hr = inMesh->VisualizeUVs(dwOptions & (uint64_t(1) << OPT_SECOND_UV));
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed to create UV visualization mesh\n");
return 1;
}
wchar_t uvFilename[_MAX_FNAME] = {};
wcscpy_s(uvFilename, fname);
wcscat_s(uvFilename, L"_texture");
_wmakepath_s(outputPath, nullptr, nullptr, uvFilename, outputExt);
if (dwOptions & (uint64_t(1) << OPT_TOLOWER))
{
std::ignore = _wcslwr_s(outputPath);
}
if (~dwOptions & (uint64_t(1) << OPT_OVERWRITE))
{
if (GetFileAttributesW(outputPath) != INVALID_FILE_ATTRIBUTES)
{
wprintf(L"\nERROR: UV visualization mesh file already exists, use -y to overwrite:\n'%ls'\n", outputPath);
return 1;
}
}
hr = E_NOTIMPL;
if (!_wcsicmp(outputExt, L".vbo"))
{
hr = inMesh->ExportToVBO(outputPath);
}
else if (!_wcsicmp(outputExt, L".sdkmesh"))
{
hr = inMesh->ExportToSDKMESH(
outputPath,
inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data(),
(dwOptions & (uint64_t(1) << OPT_FORCE_32BIT_IB)) ? true : false,
(dwOptions & (uint64_t(1) << OPT_SDKMESH_V2)) ? true : false,
normalFormat,
uvFormat,
colorFormat);
}
else if (!_wcsicmp(outputExt, L".cmo"))
{
hr = inMesh->ExportToCMO(outputPath, inMaterial.size(), inMaterial.empty() ? nullptr : inMaterial.data());
}
else if (!_wcsicmp(outputExt, L".obj") || !_wcsicmp(outputExt, L"._obj"))
{
wprintf(L"\nWARNING: WaveFront Object (.obj) not supported for UV visualization (requires Vertex Colors)\n");
}
if (FAILED(hr))
{
wprintf(L"\nERROR: Failed uv mesh write (%08X%ls):-> '%ls'\n",
static_cast<unsigned int>(hr), GetErrorDesc(hr), outputPath);
return 1;
}
wprintf(L"uv mesh visualization '%ls'\n", outputPath);
}
}
return 0;
}
|
#ifndef CLIENT_WS_HPP
#define CLIENT_WS_HPP
#include "crypto.hpp"
#include <boost/asio.hpp>
#include <unordered_map>
#include <iostream>
#include <random>
#include <atomic>
namespace SimpleWeb {
template <class socket_type>
class SocketClient;
template <class socket_type>
class SocketClientBase {
public:
class Connection {
friend class SocketClientBase<socket_type>;
friend class SocketClient<socket_type>;
public:
std::unordered_map<std::string, std::string> header;
std::string remote_endpoint_address;
unsigned short remote_endpoint_port;
Connection(socket_type* socket): socket(socket), closed(false) {}
private:
std::unique_ptr<socket_type> socket;
std::atomic<bool> closed;
void read_remote_endpoint_data() {
try {
remote_endpoint_address=socket->lowest_layer().remote_endpoint().address().to_string();
remote_endpoint_port=socket->lowest_layer().remote_endpoint().port();
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
};
std::unique_ptr<Connection> connection;
class Message : public std::istream {
friend class SocketClientBase<socket_type>;
public:
unsigned char fin_rsv_opcode;
size_t size() {
return length;
}
std::string string() {
std::stringstream ss;
ss << rdbuf();
return ss.str();
}
private:
Message(): std::istream(&streambuf) {}
size_t length;
boost::asio::streambuf streambuf;
};
class SendStream : public std::iostream {
friend class SocketClientBase<socket_type>;
private:
boost::asio::streambuf streambuf;
std::atomic<bool> sending; //Currently not in use, but might be in a future version
public:
SendStream(): std::iostream(&streambuf), sending(false) {}
size_t size() {
return streambuf.size();
}
};
std::function<void(void)> onopen;
std::function<void(std::shared_ptr<Message>)> onmessage;
std::function<void(const boost::system::error_code&)> onerror;
std::function<void(int, const std::string&)> onclose;
void start() {
connect();
asio_io_service.run();
}
void stop() {
asio_io_service.stop();
}
void send(std::shared_ptr<SendStream> send_stream, const std::function<void(const boost::system::error_code&)>& callback=nullptr,
unsigned char fin_rsv_opcode=129) {
//Create mask
std::vector<unsigned char> mask;
mask.resize(4);
std::uniform_int_distribution<int> dist(0,255);
std::random_device rd;
for(int c=0;c<4;c++) {
mask[c]=static_cast<unsigned char>(dist(rd));
}
std::shared_ptr<boost::asio::streambuf> buffer(new boost::asio::streambuf);
std::ostream stream(buffer.get());
size_t length=send_stream->size();
stream.put(fin_rsv_opcode);
//masked (first length byte>=128)
if(length>=126) {
int num_bytes;
if(length>0xffff) {
num_bytes=8;
stream.put(static_cast<unsigned char>(127+128));
}
else {
num_bytes=2;
stream.put(static_cast<unsigned char>(126+128));
}
for(int c=num_bytes-1;c>=0;c--) {
stream.put((length>>(8*c))%256);
}
}
else
stream.put(static_cast<unsigned char>(length+128));
for(int c=0;c<4;c++) {
stream.put(mask[c]);
}
for(size_t c=0;c<length;c++) {
stream.put(send_stream->get()^mask[c%4]);
}
//Need to copy the callback-function in case its destroyed
boost::asio::async_write(*connection->socket, *buffer,
[this, buffer, callback](const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(callback) {
callback(ec);
}
});
}
void send_close(int status, const std::string& reason="") {
//Send close only once (in case close is initiated by client)
if(connection->closed.load()) {
return;
}
connection->closed.store(true);
auto send_stream=std::make_shared<SendStream>();
send_stream->put(status>>8);
send_stream->put(status%256);
*send_stream << reason;
//fin_rsv_opcode=136: message close
send(send_stream, [](const boost::system::error_code& /*ec*/){}, 136);
}
protected:
const std::string ws_magic_string="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
boost::asio::io_service asio_io_service;
boost::asio::ip::tcp::endpoint asio_endpoint;
boost::asio::ip::tcp::resolver asio_resolver;
std::string host;
unsigned short port;
std::string path;
SocketClientBase(const std::string& host_port_path, unsigned short default_port) :
asio_resolver(asio_io_service) {
size_t host_end=host_port_path.find(':');
size_t host_port_end=host_port_path.find('/');
if(host_end==std::string::npos) {
host_end=host_port_end;
port=default_port;
}
else {
if(host_port_end==std::string::npos)
port=(unsigned short)stoul(host_port_path.substr(host_end+1));
else
port=(unsigned short)stoul(host_port_path.substr(host_end+1, host_port_end-(host_end+1)));
}
if(host_port_end==std::string::npos) {
path="/";
}
else {
path=host_port_path.substr(host_port_end);
}
if(host_end==std::string::npos)
host=host_port_path;
else
host=host_port_path.substr(0, host_end);
}
virtual void connect()=0;
void handshake() {
connection->read_remote_endpoint_data();
std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf);
std::ostream request(write_buffer.get());
request << "GET " << path << " HTTP/1.1" << "\r\n";
request << "Host: " << host << "\r\n";
request << "Upgrade: websocket\r\n";
request << "Connection: Upgrade\r\n";
//Make random 16-byte nonce
std::string nonce;
nonce.resize(16);
std::uniform_int_distribution<int> dist(0,255);
std::random_device rd;
for(int c=0;c<16;c++)
nonce[c]=static_cast<unsigned char>(dist(rd));
std::string nonce_base64=Crypto::Base64::encode(nonce);
request << "Sec-WebSocket-Key: " << nonce_base64 << "\r\n";
request << "Sec-WebSocket-Version: 13\r\n";
request << "\r\n";
//test this to base64::decode(Sec-WebSocket-Accept)
std::shared_ptr<std::string> accept_sha1(new std::string(Crypto::SHA1(nonce_base64+ws_magic_string)));
boost::asio::async_write(*connection->socket, *write_buffer,
[this, write_buffer, accept_sha1]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::shared_ptr<Message> message(new Message());
boost::asio::async_read_until(*connection->socket, message->streambuf, "\r\n\r\n",
[this, message, accept_sha1]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
parse_handshake(*message);
if(Crypto::Base64::decode(connection->header["Sec-WebSocket-Accept"])==*accept_sha1) {
if(onopen)
onopen();
read_message(message);
}
else
throw std::invalid_argument("WebSocket handshake failed");
}
});
}
else
throw std::invalid_argument("Failed sending handshake");
});
}
void parse_handshake(std::istream& stream) const {
std::string line;
getline(stream, line);
//Not parsing the first line
getline(stream, line);
size_t param_end=line.find(':');
while(param_end!=std::string::npos) {
size_t value_start=param_end+1;
if(line[value_start]==' ')
value_start++;
connection->header[line.substr(0, param_end)]=line.substr(value_start, line.size()-value_start-1);
getline(stream, line);
param_end=line.find(':');
}
}
void read_message(std::shared_ptr<Message> message) {
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(2),
[this, message](const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::vector<unsigned char> first_bytes;
first_bytes.resize(2);
message->read((char*)&first_bytes[0], 2);
message->fin_rsv_opcode=first_bytes[0];
//Close connection if masked message from server (protocol error)
if(first_bytes[1]>=128) {
const std::string reason="message from server masked";
send_close(1002, reason);
if(onclose)
onclose(1002, reason);
return;
}
size_t length=(first_bytes[1]&127);
if(length==126) {
//2 next bytes is the size of content
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(2),
[this, message]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::vector<unsigned char> length_bytes;
length_bytes.resize(2);
message->read((char*)&length_bytes[0], 2);
size_t length=0;
int num_bytes=2;
for(int c=0;c<num_bytes;c++)
length+=length_bytes[c]<<(8*(num_bytes-1-c));
message->length=length;
read_message_content(message);
}
else {
if(onerror)
onerror(ec);
}
});
}
else if(length==127) {
//8 next bytes is the size of content
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(8),
[this, message]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::vector<unsigned char> length_bytes;
length_bytes.resize(8);
message->read((char*)&length_bytes[0], 8);
size_t length=0;
int num_bytes=8;
for(int c=0;c<num_bytes;c++)
length+=length_bytes[c]<<(8*(num_bytes-1-c));
message->length=length;
read_message_content(message);
}
else {
if(onerror)
onerror(ec);
}
});
}
else {
message->length=length;
read_message_content(message);
}
}
else {
if(onerror)
onerror(ec);
}
});
}
void read_message_content(std::shared_ptr<Message> message) {
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(message->length),
[this, message]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
//If connection close
if((message->fin_rsv_opcode&0x0f)==8) {
int status=0;
if(message->length>=2) {
unsigned char byte1=message->get();
unsigned char byte2=message->get();
status=(byte1<<8)+byte2;
}
auto reason=message->string();
send_close(status, reason);
if(onclose)
onclose(status, reason);
return;
}
//If ping
else if((message->fin_rsv_opcode&0x0f)==9) {
//send pong
auto empty_send_stream=std::make_shared<SendStream>();
send(empty_send_stream, nullptr, message->fin_rsv_opcode+1);
}
else if(onmessage) {
onmessage(message);
}
//Next message
std::shared_ptr<Message> next_message(new Message());
read_message(next_message);
}
else {
if(onerror)
onerror(ec);
}
});
}
};
template<class socket_type>
class SocketClient : public SocketClientBase<socket_type> {};
typedef boost::asio::ip::tcp::socket WS;
template<>
class SocketClient<WS> : public SocketClientBase<WS> {
public:
SocketClient(const std::string& server_port_path) : SocketClientBase<WS>::SocketClientBase(server_port_path, 80) {};
private:
void connect() {
boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));
asio_resolver.async_resolve(query, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
connection=std::unique_ptr<Connection>(new Connection(new WS(asio_io_service)));
boost::asio::async_connect(*connection->socket, it, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
handshake();
}
else
throw std::invalid_argument(ec.message());
});
}
else
throw std::invalid_argument(ec.message());
});
}
};
}
#endif /* CLIENT_WS_HPP */
Minor changes to #15.
#ifndef CLIENT_WS_HPP
#define CLIENT_WS_HPP
#include "crypto.hpp"
#include <boost/asio.hpp>
#include <unordered_map>
#include <iostream>
#include <random>
#include <atomic>
namespace SimpleWeb {
template <class socket_type>
class SocketClient;
template <class socket_type>
class SocketClientBase {
public:
class Connection {
friend class SocketClientBase<socket_type>;
friend class SocketClient<socket_type>;
public:
std::unordered_map<std::string, std::string> header;
std::string remote_endpoint_address;
unsigned short remote_endpoint_port;
Connection(socket_type* socket): socket(socket), closed(false) {}
private:
std::unique_ptr<socket_type> socket;
std::atomic<bool> closed;
void read_remote_endpoint_data() {
try {
remote_endpoint_address=socket->lowest_layer().remote_endpoint().address().to_string();
remote_endpoint_port=socket->lowest_layer().remote_endpoint().port();
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
};
std::unique_ptr<Connection> connection;
class Message : public std::istream {
friend class SocketClientBase<socket_type>;
public:
unsigned char fin_rsv_opcode;
size_t size() {
return length;
}
std::string string() {
std::stringstream ss;
ss << rdbuf();
return ss.str();
}
private:
Message(): std::istream(&streambuf) {}
size_t length;
boost::asio::streambuf streambuf;
};
class SendStream : public std::iostream {
friend class SocketClientBase<socket_type>;
private:
boost::asio::streambuf streambuf;
std::atomic<bool> sending; //Currently not in use, but might be in a future version
public:
SendStream(): std::iostream(&streambuf), sending(false) {}
size_t size() {
return streambuf.size();
}
};
std::function<void(void)> onopen;
std::function<void(std::shared_ptr<Message>)> onmessage;
std::function<void(const boost::system::error_code&)> onerror;
std::function<void(int, const std::string&)> onclose;
void start() {
connect();
asio_io_service.run();
}
void stop() {
asio_io_service.stop();
}
void send(std::shared_ptr<SendStream> send_stream, const std::function<void(const boost::system::error_code&)>& callback=nullptr,
unsigned char fin_rsv_opcode=129) {
//Create mask
std::vector<unsigned char> mask;
mask.resize(4);
std::uniform_int_distribution<unsigned short> dist(0,255);
std::random_device rd;
for(int c=0;c<4;c++) {
mask[c]=static_cast<unsigned char>(dist(rd));
}
std::shared_ptr<boost::asio::streambuf> buffer(new boost::asio::streambuf);
std::ostream stream(buffer.get());
size_t length=send_stream->size();
stream.put(fin_rsv_opcode);
//masked (first length byte>=128)
if(length>=126) {
int num_bytes;
if(length>0xffff) {
num_bytes=8;
stream.put(static_cast<unsigned char>(127+128));
}
else {
num_bytes=2;
stream.put(static_cast<unsigned char>(126+128));
}
for(int c=num_bytes-1;c>=0;c--) {
stream.put((length>>(8*c))%256);
}
}
else
stream.put(static_cast<unsigned char>(length+128));
for(int c=0;c<4;c++) {
stream.put(mask[c]);
}
for(size_t c=0;c<length;c++) {
stream.put(send_stream->get()^mask[c%4]);
}
//Need to copy the callback-function in case its destroyed
boost::asio::async_write(*connection->socket, *buffer,
[this, buffer, callback](const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(callback) {
callback(ec);
}
});
}
void send_close(int status, const std::string& reason="") {
//Send close only once (in case close is initiated by client)
if(connection->closed.load()) {
return;
}
connection->closed.store(true);
auto send_stream=std::make_shared<SendStream>();
send_stream->put(status>>8);
send_stream->put(status%256);
*send_stream << reason;
//fin_rsv_opcode=136: message close
send(send_stream, [](const boost::system::error_code& /*ec*/){}, 136);
}
protected:
const std::string ws_magic_string="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
boost::asio::io_service asio_io_service;
boost::asio::ip::tcp::endpoint asio_endpoint;
boost::asio::ip::tcp::resolver asio_resolver;
std::string host;
unsigned short port;
std::string path;
SocketClientBase(const std::string& host_port_path, unsigned short default_port) :
asio_resolver(asio_io_service) {
size_t host_end=host_port_path.find(':');
size_t host_port_end=host_port_path.find('/');
if(host_end==std::string::npos) {
host_end=host_port_end;
port=default_port;
}
else {
if(host_port_end==std::string::npos)
port=(unsigned short)stoul(host_port_path.substr(host_end+1));
else
port=(unsigned short)stoul(host_port_path.substr(host_end+1, host_port_end-(host_end+1)));
}
if(host_port_end==std::string::npos) {
path="/";
}
else {
path=host_port_path.substr(host_port_end);
}
if(host_end==std::string::npos)
host=host_port_path;
else
host=host_port_path.substr(0, host_end);
}
virtual void connect()=0;
void handshake() {
connection->read_remote_endpoint_data();
std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf);
std::ostream request(write_buffer.get());
request << "GET " << path << " HTTP/1.1" << "\r\n";
request << "Host: " << host << "\r\n";
request << "Upgrade: websocket\r\n";
request << "Connection: Upgrade\r\n";
//Make random 16-byte nonce
std::string nonce;
nonce.resize(16);
std::uniform_int_distribution<unsigned short> dist(0,255);
std::random_device rd;
for(int c=0;c<16;c++)
nonce[c]=static_cast<unsigned char>(dist(rd));
std::string nonce_base64=Crypto::Base64::encode(nonce);
request << "Sec-WebSocket-Key: " << nonce_base64 << "\r\n";
request << "Sec-WebSocket-Version: 13\r\n";
request << "\r\n";
//test this to base64::decode(Sec-WebSocket-Accept)
std::shared_ptr<std::string> accept_sha1(new std::string(Crypto::SHA1(nonce_base64+ws_magic_string)));
boost::asio::async_write(*connection->socket, *write_buffer,
[this, write_buffer, accept_sha1]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::shared_ptr<Message> message(new Message());
boost::asio::async_read_until(*connection->socket, message->streambuf, "\r\n\r\n",
[this, message, accept_sha1]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
parse_handshake(*message);
if(Crypto::Base64::decode(connection->header["Sec-WebSocket-Accept"])==*accept_sha1) {
if(onopen)
onopen();
read_message(message);
}
else
throw std::invalid_argument("WebSocket handshake failed");
}
});
}
else
throw std::invalid_argument("Failed sending handshake");
});
}
void parse_handshake(std::istream& stream) const {
std::string line;
getline(stream, line);
//Not parsing the first line
getline(stream, line);
size_t param_end=line.find(':');
while(param_end!=std::string::npos) {
size_t value_start=param_end+1;
if(line[value_start]==' ')
value_start++;
connection->header[line.substr(0, param_end)]=line.substr(value_start, line.size()-value_start-1);
getline(stream, line);
param_end=line.find(':');
}
}
void read_message(std::shared_ptr<Message> message) {
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(2),
[this, message](const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::vector<unsigned char> first_bytes;
first_bytes.resize(2);
message->read((char*)&first_bytes[0], 2);
message->fin_rsv_opcode=first_bytes[0];
//Close connection if masked message from server (protocol error)
if(first_bytes[1]>=128) {
const std::string reason="message from server masked";
send_close(1002, reason);
if(onclose)
onclose(1002, reason);
return;
}
size_t length=(first_bytes[1]&127);
if(length==126) {
//2 next bytes is the size of content
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(2),
[this, message]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::vector<unsigned char> length_bytes;
length_bytes.resize(2);
message->read((char*)&length_bytes[0], 2);
size_t length=0;
int num_bytes=2;
for(int c=0;c<num_bytes;c++)
length+=length_bytes[c]<<(8*(num_bytes-1-c));
message->length=length;
read_message_content(message);
}
else {
if(onerror)
onerror(ec);
}
});
}
else if(length==127) {
//8 next bytes is the size of content
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(8),
[this, message]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
std::vector<unsigned char> length_bytes;
length_bytes.resize(8);
message->read((char*)&length_bytes[0], 8);
size_t length=0;
int num_bytes=8;
for(int c=0;c<num_bytes;c++)
length+=length_bytes[c]<<(8*(num_bytes-1-c));
message->length=length;
read_message_content(message);
}
else {
if(onerror)
onerror(ec);
}
});
}
else {
message->length=length;
read_message_content(message);
}
}
else {
if(onerror)
onerror(ec);
}
});
}
void read_message_content(std::shared_ptr<Message> message) {
boost::asio::async_read(*connection->socket, message->streambuf, boost::asio::transfer_exactly(message->length),
[this, message]
(const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
if(!ec) {
//If connection close
if((message->fin_rsv_opcode&0x0f)==8) {
int status=0;
if(message->length>=2) {
unsigned char byte1=message->get();
unsigned char byte2=message->get();
status=(byte1<<8)+byte2;
}
auto reason=message->string();
send_close(status, reason);
if(onclose)
onclose(status, reason);
return;
}
//If ping
else if((message->fin_rsv_opcode&0x0f)==9) {
//send pong
auto empty_send_stream=std::make_shared<SendStream>();
send(empty_send_stream, nullptr, message->fin_rsv_opcode+1);
}
else if(onmessage) {
onmessage(message);
}
//Next message
std::shared_ptr<Message> next_message(new Message());
read_message(next_message);
}
else {
if(onerror)
onerror(ec);
}
});
}
};
template<class socket_type>
class SocketClient : public SocketClientBase<socket_type> {};
typedef boost::asio::ip::tcp::socket WS;
template<>
class SocketClient<WS> : public SocketClientBase<WS> {
public:
SocketClient(const std::string& server_port_path) : SocketClientBase<WS>::SocketClientBase(server_port_path, 80) {};
private:
void connect() {
boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));
asio_resolver.async_resolve(query, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
connection=std::unique_ptr<Connection>(new Connection(new WS(asio_io_service)));
boost::asio::async_connect(*connection->socket, it, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
handshake();
}
else
throw std::invalid_argument(ec.message());
});
}
else
throw std::invalid_argument(ec.message());
});
}
};
}
#endif /* CLIENT_WS_HPP */
|
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexArrayVk.cpp:
// Implements the class methods for VertexArrayVk.
//
#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
#include "common/debug.h"
#include "libANGLE/Context.h"
#include "libANGLE/renderer/vulkan/BufferVk.h"
#include "libANGLE/renderer/vulkan/CommandGraph.h"
#include "libANGLE/renderer/vulkan/ContextVk.h"
#include "libANGLE/renderer/vulkan/FramebufferVk.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
#include "libANGLE/renderer/vulkan/vk_format_utils.h"
namespace rx
{
namespace
{
constexpr size_t kDynamicVertexDataSize = 1024 * 1024;
constexpr size_t kDynamicIndexDataSize = 1024 * 8;
} // anonymous namespace
VertexArrayVk::VertexArrayVk(const gl::VertexArrayState &state, RendererVk *renderer)
: VertexArrayImpl(state),
mCurrentArrayBufferHandles{},
mCurrentArrayBufferOffsets{},
mCurrentArrayBufferResources{},
mCurrentElementArrayBufferHandle(VK_NULL_HANDLE),
mCurrentElementArrayBufferOffset(0),
mCurrentElementArrayBufferResource(nullptr),
mDynamicVertexData(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, kDynamicVertexDataSize),
mDynamicIndexData(VK_BUFFER_USAGE_INDEX_BUFFER_BIT, kDynamicIndexDataSize),
mLineLoopHelper(renderer),
mDirtyLineLoopTranslation(true),
mVertexBuffersDirty(false),
mIndexBufferDirty(false)
{
mCurrentArrayBufferHandles.fill(VK_NULL_HANDLE);
mCurrentArrayBufferOffsets.fill(0);
mCurrentArrayBufferResources.fill(nullptr);
mPackedInputBindings.fill({0, 0});
mPackedInputAttributes.fill({0, 0, 0});
mDynamicVertexData.init(1, renderer);
mDynamicIndexData.init(1, renderer);
}
VertexArrayVk::~VertexArrayVk()
{
}
void VertexArrayVk::destroy(const gl::Context *context)
{
VkDevice device = vk::GetImpl(context)->getRenderer()->getDevice();
mDynamicVertexData.destroy(device);
mDynamicIndexData.destroy(device);
mLineLoopHelper.destroy(device);
}
gl::Error VertexArrayVk::streamVertexData(RendererVk *renderer,
const gl::AttributesMask &attribsToStream,
const gl::DrawCallParams &drawCallParams)
{
ASSERT(!attribsToStream.none());
const auto &attribs = mState.getVertexAttributes();
const auto &bindings = mState.getVertexBindings();
const size_t lastVertex = drawCallParams.firstVertex() + drawCallParams.vertexCount();
// TODO(fjhenigman): When we have a bunch of interleaved attributes, they end up
// un-interleaved, wasting space and copying time. Consider improving on that.
for (size_t attribIndex : attribsToStream)
{
const gl::VertexAttribute &attrib = attribs[attribIndex];
const gl::VertexBinding &binding = bindings[attrib.bindingIndex];
ASSERT(attrib.enabled && binding.getBuffer().get() == nullptr);
// TODO(fjhenigman): Work with more formats than just GL_FLOAT.
if (attrib.type != GL_FLOAT)
{
UNIMPLEMENTED();
return gl::InternalError();
}
// Only [firstVertex, lastVertex] is needed by the upcoming draw so that
// is all we copy, but we allocate space for [0, lastVertex] so indexing
// will work. If we don't start at zero all the indices will be off.
// TODO(fjhenigman): See if we can account for indices being off by adjusting
// the offset, thus avoiding wasted memory.
const size_t firstByte = drawCallParams.firstVertex() * binding.getStride();
const size_t lastByte =
lastVertex * binding.getStride() + gl::ComputeVertexAttributeTypeSize(attrib);
uint8_t *dst = nullptr;
uint32_t offset = 0;
ANGLE_TRY(mDynamicVertexData.allocate(
renderer, lastByte, &dst, &mCurrentArrayBufferHandles[attribIndex], &offset, nullptr));
mCurrentArrayBufferOffsets[attribIndex] = static_cast<VkDeviceSize>(offset);
memcpy(dst + firstByte, static_cast<const uint8_t *>(attrib.pointer) + firstByte,
lastByte - firstByte);
}
ANGLE_TRY(mDynamicVertexData.flush(renderer->getDevice()));
mDynamicVertexData.releaseRetainedBuffers(renderer);
return gl::NoError();
}
gl::Error VertexArrayVk::streamIndexData(RendererVk *renderer,
const gl::DrawCallParams &drawCallParams)
{
ASSERT(!mState.getElementArrayBuffer().get());
uint32_t offset = 0;
const GLsizei amount = sizeof(GLushort) * drawCallParams.indexCount();
GLubyte *dst = nullptr;
ANGLE_TRY(mDynamicIndexData.allocate(renderer, amount, &dst, &mCurrentElementArrayBufferHandle,
&offset, nullptr));
if (drawCallParams.type() == GL_UNSIGNED_BYTE)
{
// Unsigned bytes don't have direct support in Vulkan so we have to expand the
// memory to a GLushort.
const GLubyte *in = static_cast<const GLubyte *>(drawCallParams.indices());
GLushort *expandedDst = reinterpret_cast<GLushort *>(dst);
for (GLsizei index = 0; index < drawCallParams.indexCount(); index++)
{
expandedDst[index] = static_cast<GLushort>(in[index]);
}
}
else
{
memcpy(dst, drawCallParams.indices(), amount);
}
ANGLE_TRY(mDynamicIndexData.flush(renderer->getDevice()));
mDynamicIndexData.releaseRetainedBuffers(renderer);
mCurrentElementArrayBufferOffset = offset;
return gl::NoError();
}
#define ANGLE_VERTEX_DIRTY_ATTRIB_FUNC(INDEX) \
case gl::VertexArray::DIRTY_BIT_ATTRIB_0 + INDEX: \
syncDirtyAttrib(attribs[INDEX], bindings[attribs[INDEX].bindingIndex], INDEX); \
invalidatePipeline = true; \
break;
#define ANGLE_VERTEX_DIRTY_BINDING_FUNC(INDEX) \
case gl::VertexArray::DIRTY_BIT_BINDING_0 + INDEX: \
syncDirtyAttrib(attribs[INDEX], bindings[attribs[INDEX].bindingIndex], INDEX); \
invalidatePipeline = true; \
break;
#define ANGLE_VERTEX_DIRTY_BUFFER_DATA_FUNC(INDEX) \
case gl::VertexArray::DIRTY_BIT_BUFFER_DATA_0 + INDEX: \
break;
gl::Error VertexArrayVk::syncState(const gl::Context *context,
const gl::VertexArray::DirtyBits &dirtyBits,
const gl::VertexArray::DirtyAttribBitsArray &attribBits,
const gl::VertexArray::DirtyBindingBitsArray &bindingBits)
{
ASSERT(dirtyBits.any());
bool invalidatePipeline = false;
// Invalidate current pipeline.
ContextVk *contextVk = vk::GetImpl(context);
// Rebuild current attribute buffers cache. This will fail horribly if the buffer changes.
// TODO(jmadill): Handle buffer storage changes.
const auto &attribs = mState.getVertexAttributes();
const auto &bindings = mState.getVertexBindings();
for (size_t dirtyBit : dirtyBits)
{
switch (dirtyBit)
{
case gl::VertexArray::DIRTY_BIT_ELEMENT_ARRAY_BUFFER:
{
gl::Buffer *bufferGL = mState.getElementArrayBuffer().get();
if (bufferGL)
{
BufferVk *bufferVk = vk::GetImpl(bufferGL);
mCurrentElementArrayBufferResource = bufferVk;
mCurrentElementArrayBufferHandle = bufferVk->getVkBuffer().getHandle();
mCurrentElementArrayBufferOffset = 0;
}
else
{
mCurrentElementArrayBufferResource = nullptr;
mCurrentElementArrayBufferHandle = VK_NULL_HANDLE;
mCurrentElementArrayBufferOffset = 0;
}
mIndexBufferDirty = true;
mDirtyLineLoopTranslation = true;
break;
}
case gl::VertexArray::DIRTY_BIT_ELEMENT_ARRAY_BUFFER_DATA:
mLineLoopBufferFirstIndex.reset();
mLineLoopBufferLastIndex.reset();
mDirtyLineLoopTranslation = true;
break;
ANGLE_VERTEX_INDEX_CASES(ANGLE_VERTEX_DIRTY_ATTRIB_FUNC);
ANGLE_VERTEX_INDEX_CASES(ANGLE_VERTEX_DIRTY_BINDING_FUNC);
ANGLE_VERTEX_INDEX_CASES(ANGLE_VERTEX_DIRTY_BUFFER_DATA_FUNC);
default:
UNREACHABLE();
break;
}
}
if (invalidatePipeline)
{
mVertexBuffersDirty = true;
contextVk->invalidateCurrentPipeline();
}
return gl::NoError();
}
void VertexArrayVk::syncDirtyAttrib(const gl::VertexAttribute &attrib,
const gl::VertexBinding &binding,
size_t attribIndex)
{
// Invalidate the input description for pipelines.
mDirtyPackedInputs.set(attribIndex);
if (attrib.enabled)
{
gl::Buffer *bufferGL = binding.getBuffer().get();
if (bufferGL)
{
BufferVk *bufferVk = vk::GetImpl(bufferGL);
mCurrentArrayBufferResources[attribIndex] = bufferVk;
mCurrentArrayBufferHandles[attribIndex] = bufferVk->getVkBuffer().getHandle();
}
else
{
mCurrentArrayBufferResources[attribIndex] = nullptr;
mCurrentArrayBufferHandles[attribIndex] = VK_NULL_HANDLE;
}
// TODO(jmadill): Offset handling. Assume zero for now.
mCurrentArrayBufferOffsets[attribIndex] = 0;
}
else
{
UNIMPLEMENTED();
}
}
const gl::AttribArray<VkBuffer> &VertexArrayVk::getCurrentArrayBufferHandles() const
{
return mCurrentArrayBufferHandles;
}
const gl::AttribArray<VkDeviceSize> &VertexArrayVk::getCurrentArrayBufferOffsets() const
{
return mCurrentArrayBufferOffsets;
}
void VertexArrayVk::updateArrayBufferReadDependencies(vk::CommandGraphResource *drawFramebuffer,
const gl::AttributesMask &activeAttribsMask,
Serial serial)
{
// Handle the bound array buffers.
for (size_t attribIndex : activeAttribsMask)
{
if (mCurrentArrayBufferResources[attribIndex])
mCurrentArrayBufferResources[attribIndex]->addReadDependency(drawFramebuffer);
}
}
void VertexArrayVk::updateElementArrayBufferReadDependency(
vk::CommandGraphResource *drawFramebuffer,
Serial serial)
{
// Handle the bound element array buffer.
if (mCurrentElementArrayBufferResource)
{
mCurrentElementArrayBufferResource->addReadDependency(drawFramebuffer);
}
}
void VertexArrayVk::getPackedInputDescriptions(vk::PipelineDesc *pipelineDesc)
{
updatePackedInputDescriptions();
pipelineDesc->updateVertexInputInfo(mPackedInputBindings, mPackedInputAttributes);
}
void VertexArrayVk::updatePackedInputDescriptions()
{
if (!mDirtyPackedInputs.any())
{
return;
}
const auto &attribs = mState.getVertexAttributes();
const auto &bindings = mState.getVertexBindings();
for (auto attribIndex : mDirtyPackedInputs)
{
const auto &attrib = attribs[attribIndex];
const auto &binding = bindings[attrib.bindingIndex];
if (attrib.enabled)
{
updatePackedInputInfo(static_cast<uint32_t>(attribIndex), binding, attrib);
}
else
{
UNIMPLEMENTED();
}
}
mDirtyPackedInputs.reset();
}
void VertexArrayVk::updatePackedInputInfo(uint32_t attribIndex,
const gl::VertexBinding &binding,
const gl::VertexAttribute &attrib)
{
vk::PackedVertexInputBindingDesc &bindingDesc = mPackedInputBindings[attribIndex];
size_t attribSize = gl::ComputeVertexAttributeTypeSize(attrib);
ASSERT(attribSize <= std::numeric_limits<uint16_t>::max());
bindingDesc.stride = static_cast<uint16_t>(binding.getStride());
bindingDesc.inputRate = static_cast<uint16_t>(
binding.getDivisor() > 0 ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX);
gl::VertexFormatType vertexFormatType = gl::GetVertexFormatType(attrib);
VkFormat vkFormat = vk::GetNativeVertexFormat(vertexFormatType);
ASSERT(vkFormat <= std::numeric_limits<uint16_t>::max());
vk::PackedVertexInputAttributeDesc &attribDesc = mPackedInputAttributes[attribIndex];
attribDesc.format = static_cast<uint16_t>(vkFormat);
attribDesc.location = static_cast<uint16_t>(attribIndex);
attribDesc.offset = static_cast<uint32_t>(ComputeVertexAttributeOffset(attrib, binding));
}
gl::Error VertexArrayVk::drawArrays(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
ASSERT(commandBuffer->valid());
ANGLE_TRY(onDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
// Note: Vertex indexes can be arbitrarily large.
uint32_t clampedVertexCount = drawCallParams.getClampedVertexCount<uint32_t>();
if (drawCallParams.mode() != gl::PrimitiveMode::LineLoop)
{
commandBuffer->draw(clampedVertexCount, 1, drawCallParams.firstVertex(), 0);
return gl::NoError();
}
// Handle GL_LINE_LOOP drawArrays.
size_t lastVertex = static_cast<size_t>(drawCallParams.firstVertex() + clampedVertexCount);
if (!mLineLoopBufferFirstIndex.valid() || !mLineLoopBufferLastIndex.valid() ||
mLineLoopBufferFirstIndex != drawCallParams.firstVertex() ||
mLineLoopBufferLastIndex != lastVertex)
{
ANGLE_TRY(mLineLoopHelper.getIndexBufferForDrawArrays(renderer, drawCallParams,
&mCurrentElementArrayBufferHandle,
&mCurrentElementArrayBufferOffset));
mLineLoopBufferFirstIndex = drawCallParams.firstVertex();
mLineLoopBufferLastIndex = lastVertex;
}
commandBuffer->bindIndexBuffer(mCurrentElementArrayBufferHandle,
mCurrentElementArrayBufferOffset, VK_INDEX_TYPE_UINT32);
vk::LineLoopHelper::Draw(clampedVertexCount, commandBuffer);
return gl::NoError();
}
gl::Error VertexArrayVk::drawElements(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
ASSERT(commandBuffer->valid());
if (drawCallParams.mode() != gl::PrimitiveMode::LineLoop)
{
ANGLE_TRY(
onIndexedDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
commandBuffer->drawIndexed(drawCallParams.indexCount(), 1, 0, 0, 0);
return gl::NoError();
}
// Handle GL_LINE_LOOP drawElements.
if (mDirtyLineLoopTranslation)
{
gl::Buffer *elementArrayBuffer = mState.getElementArrayBuffer().get();
VkIndexType indexType = gl_vk::GetIndexType(drawCallParams.type());
if (!elementArrayBuffer)
{
ANGLE_TRY(mLineLoopHelper.getIndexBufferForClientElementArray(
renderer, drawCallParams.indices(), indexType, drawCallParams.indexCount(),
&mCurrentElementArrayBufferHandle, &mCurrentElementArrayBufferOffset));
}
else
{
// When using an element array buffer, 'indices' is an offset to the first element.
intptr_t offset = reinterpret_cast<intptr_t>(drawCallParams.indices());
BufferVk *elementArrayBufferVk = vk::GetImpl(elementArrayBuffer);
ANGLE_TRY(mLineLoopHelper.getIndexBufferForElementArrayBuffer(
renderer, elementArrayBufferVk, indexType, drawCallParams.indexCount(), offset,
&mCurrentElementArrayBufferHandle, &mCurrentElementArrayBufferOffset));
}
}
ANGLE_TRY(onIndexedDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
vk::LineLoopHelper::Draw(drawCallParams.indexCount(), commandBuffer);
return gl::NoError();
}
gl::Error VertexArrayVk::onDraw(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
const gl::State &state = context->getGLState();
const gl::Program *programGL = state.getProgram();
const gl::AttributesMask &clientAttribs = mState.getEnabledClientMemoryAttribsMask();
const gl::AttributesMask &activeAttribs = programGL->getActiveAttribLocationsMask();
uint32_t maxAttrib = programGL->getState().getMaxActiveAttribLocation();
if (clientAttribs.any())
{
const gl::AttributesMask &attribsToStream = (clientAttribs & activeAttribs);
if (attribsToStream.any())
{
ANGLE_TRY(drawCallParams.ensureIndexRangeResolved(context));
ANGLE_TRY(streamVertexData(renderer, attribsToStream, drawCallParams));
commandBuffer->bindVertexBuffers(0, maxAttrib, mCurrentArrayBufferHandles.data(),
mCurrentArrayBufferOffsets.data());
}
}
else if (mVertexBuffersDirty || newCommandBuffer)
{
if (maxAttrib > 0)
{
commandBuffer->bindVertexBuffers(0, maxAttrib, mCurrentArrayBufferHandles.data(),
mCurrentArrayBufferOffsets.data());
vk::CommandGraphResource *drawFramebuffer = vk::GetImpl(state.getDrawFramebuffer());
updateArrayBufferReadDependencies(drawFramebuffer, activeAttribs,
renderer->getCurrentQueueSerial());
}
mVertexBuffersDirty = false;
// This forces the binding to happen if we follow a drawElement call from a drawArrays call.
mIndexBufferDirty = true;
// If we've had a drawElements call with a line loop before, we want to make sure this is
// invalidated the next time drawElements is called since we use the same index buffer for
// both calls.
mDirtyLineLoopTranslation = true;
}
return gl::NoError();
}
gl::Error VertexArrayVk::onIndexedDraw(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
ANGLE_TRY(onDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
if (!mState.getElementArrayBuffer().get() &&
drawCallParams.mode() != gl::PrimitiveMode::LineLoop)
{
ANGLE_TRY(drawCallParams.ensureIndexRangeResolved(context));
ANGLE_TRY(streamIndexData(renderer, drawCallParams));
commandBuffer->bindIndexBuffer(mCurrentElementArrayBufferHandle,
mCurrentElementArrayBufferOffset,
gl_vk::GetIndexType(drawCallParams.type()));
}
else if (mIndexBufferDirty || newCommandBuffer)
{
if (drawCallParams.type() == GL_UNSIGNED_BYTE)
{
// TODO(fjhenigman): Index format translation.
UNIMPLEMENTED();
return gl::InternalError()
<< "Unsigned byte translation is not implemented for indices in a buffer object";
}
commandBuffer->bindIndexBuffer(mCurrentElementArrayBufferHandle,
mCurrentElementArrayBufferOffset,
gl_vk::GetIndexType(drawCallParams.type()));
const gl::State &glState = context->getGLState();
vk::CommandGraphResource *drawFramebuffer = vk::GetImpl(glState.getDrawFramebuffer());
updateElementArrayBufferReadDependency(drawFramebuffer, renderer->getCurrentQueueSerial());
mIndexBufferDirty = false;
// If we've had a drawArrays call with a line loop before, we want to make sure this is
// invalidated the next time drawArrays is called since we use the same index buffer for
// both calls.
mLineLoopBufferFirstIndex.reset();
mLineLoopBufferLastIndex.reset();
}
return gl::NoError();
}
} // namespace rx
Vulkan: Fix a line loop edge case causing validation errors
Bug: angleproject:2563
Change-Id: I6e908fbd3e5725dc3f355f8b0561f2177b61dff6
Reviewed-on: https://chromium-review.googlesource.com/1075291
Commit-Queue: Luc Ferron <a2389c1bcb3ee32b089866e04e35d1a302020674@chromium.org>
Reviewed-by: Geoff Lang <b6fc25fe0362055230985c05cbfa8adb741ccc0f@chromium.org>
Reviewed-by: Jamie Madill <7e492b4f1c8458024932de3ba475cbf015424c30@chromium.org>
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexArrayVk.cpp:
// Implements the class methods for VertexArrayVk.
//
#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
#include "common/debug.h"
#include "libANGLE/Context.h"
#include "libANGLE/renderer/vulkan/BufferVk.h"
#include "libANGLE/renderer/vulkan/CommandGraph.h"
#include "libANGLE/renderer/vulkan/ContextVk.h"
#include "libANGLE/renderer/vulkan/FramebufferVk.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
#include "libANGLE/renderer/vulkan/vk_format_utils.h"
namespace rx
{
namespace
{
constexpr size_t kDynamicVertexDataSize = 1024 * 1024;
constexpr size_t kDynamicIndexDataSize = 1024 * 8;
} // anonymous namespace
VertexArrayVk::VertexArrayVk(const gl::VertexArrayState &state, RendererVk *renderer)
: VertexArrayImpl(state),
mCurrentArrayBufferHandles{},
mCurrentArrayBufferOffsets{},
mCurrentArrayBufferResources{},
mCurrentElementArrayBufferHandle(VK_NULL_HANDLE),
mCurrentElementArrayBufferOffset(0),
mCurrentElementArrayBufferResource(nullptr),
mDynamicVertexData(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, kDynamicVertexDataSize),
mDynamicIndexData(VK_BUFFER_USAGE_INDEX_BUFFER_BIT, kDynamicIndexDataSize),
mLineLoopHelper(renderer),
mDirtyLineLoopTranslation(true),
mVertexBuffersDirty(false),
mIndexBufferDirty(false)
{
mCurrentArrayBufferHandles.fill(VK_NULL_HANDLE);
mCurrentArrayBufferOffsets.fill(0);
mCurrentArrayBufferResources.fill(nullptr);
mPackedInputBindings.fill({0, 0});
mPackedInputAttributes.fill({0, 0, 0});
mDynamicVertexData.init(1, renderer);
mDynamicIndexData.init(1, renderer);
}
VertexArrayVk::~VertexArrayVk()
{
}
void VertexArrayVk::destroy(const gl::Context *context)
{
VkDevice device = vk::GetImpl(context)->getRenderer()->getDevice();
mDynamicVertexData.destroy(device);
mDynamicIndexData.destroy(device);
mLineLoopHelper.destroy(device);
}
gl::Error VertexArrayVk::streamVertexData(RendererVk *renderer,
const gl::AttributesMask &attribsToStream,
const gl::DrawCallParams &drawCallParams)
{
ASSERT(!attribsToStream.none());
const auto &attribs = mState.getVertexAttributes();
const auto &bindings = mState.getVertexBindings();
const size_t lastVertex = drawCallParams.firstVertex() + drawCallParams.vertexCount();
// TODO(fjhenigman): When we have a bunch of interleaved attributes, they end up
// un-interleaved, wasting space and copying time. Consider improving on that.
for (size_t attribIndex : attribsToStream)
{
const gl::VertexAttribute &attrib = attribs[attribIndex];
const gl::VertexBinding &binding = bindings[attrib.bindingIndex];
ASSERT(attrib.enabled && binding.getBuffer().get() == nullptr);
// TODO(fjhenigman): Work with more formats than just GL_FLOAT.
if (attrib.type != GL_FLOAT)
{
UNIMPLEMENTED();
return gl::InternalError();
}
// Only [firstVertex, lastVertex] is needed by the upcoming draw so that
// is all we copy, but we allocate space for [0, lastVertex] so indexing
// will work. If we don't start at zero all the indices will be off.
// TODO(fjhenigman): See if we can account for indices being off by adjusting
// the offset, thus avoiding wasted memory.
const size_t firstByte = drawCallParams.firstVertex() * binding.getStride();
const size_t lastByte =
lastVertex * binding.getStride() + gl::ComputeVertexAttributeTypeSize(attrib);
uint8_t *dst = nullptr;
uint32_t offset = 0;
ANGLE_TRY(mDynamicVertexData.allocate(
renderer, lastByte, &dst, &mCurrentArrayBufferHandles[attribIndex], &offset, nullptr));
mCurrentArrayBufferOffsets[attribIndex] = static_cast<VkDeviceSize>(offset);
memcpy(dst + firstByte, static_cast<const uint8_t *>(attrib.pointer) + firstByte,
lastByte - firstByte);
}
ANGLE_TRY(mDynamicVertexData.flush(renderer->getDevice()));
mDynamicVertexData.releaseRetainedBuffers(renderer);
return gl::NoError();
}
gl::Error VertexArrayVk::streamIndexData(RendererVk *renderer,
const gl::DrawCallParams &drawCallParams)
{
ASSERT(!mState.getElementArrayBuffer().get());
uint32_t offset = 0;
const GLsizei amount = sizeof(GLushort) * drawCallParams.indexCount();
GLubyte *dst = nullptr;
ANGLE_TRY(mDynamicIndexData.allocate(renderer, amount, &dst, &mCurrentElementArrayBufferHandle,
&offset, nullptr));
if (drawCallParams.type() == GL_UNSIGNED_BYTE)
{
// Unsigned bytes don't have direct support in Vulkan so we have to expand the
// memory to a GLushort.
const GLubyte *in = static_cast<const GLubyte *>(drawCallParams.indices());
GLushort *expandedDst = reinterpret_cast<GLushort *>(dst);
for (GLsizei index = 0; index < drawCallParams.indexCount(); index++)
{
expandedDst[index] = static_cast<GLushort>(in[index]);
}
}
else
{
memcpy(dst, drawCallParams.indices(), amount);
}
ANGLE_TRY(mDynamicIndexData.flush(renderer->getDevice()));
mDynamicIndexData.releaseRetainedBuffers(renderer);
mCurrentElementArrayBufferOffset = offset;
return gl::NoError();
}
#define ANGLE_VERTEX_DIRTY_ATTRIB_FUNC(INDEX) \
case gl::VertexArray::DIRTY_BIT_ATTRIB_0 + INDEX: \
syncDirtyAttrib(attribs[INDEX], bindings[attribs[INDEX].bindingIndex], INDEX); \
invalidatePipeline = true; \
break;
#define ANGLE_VERTEX_DIRTY_BINDING_FUNC(INDEX) \
case gl::VertexArray::DIRTY_BIT_BINDING_0 + INDEX: \
syncDirtyAttrib(attribs[INDEX], bindings[attribs[INDEX].bindingIndex], INDEX); \
invalidatePipeline = true; \
break;
#define ANGLE_VERTEX_DIRTY_BUFFER_DATA_FUNC(INDEX) \
case gl::VertexArray::DIRTY_BIT_BUFFER_DATA_0 + INDEX: \
break;
gl::Error VertexArrayVk::syncState(const gl::Context *context,
const gl::VertexArray::DirtyBits &dirtyBits,
const gl::VertexArray::DirtyAttribBitsArray &attribBits,
const gl::VertexArray::DirtyBindingBitsArray &bindingBits)
{
ASSERT(dirtyBits.any());
bool invalidatePipeline = false;
// Invalidate current pipeline.
ContextVk *contextVk = vk::GetImpl(context);
// Rebuild current attribute buffers cache. This will fail horribly if the buffer changes.
// TODO(jmadill): Handle buffer storage changes.
const auto &attribs = mState.getVertexAttributes();
const auto &bindings = mState.getVertexBindings();
for (size_t dirtyBit : dirtyBits)
{
switch (dirtyBit)
{
case gl::VertexArray::DIRTY_BIT_ELEMENT_ARRAY_BUFFER:
{
gl::Buffer *bufferGL = mState.getElementArrayBuffer().get();
if (bufferGL)
{
BufferVk *bufferVk = vk::GetImpl(bufferGL);
mCurrentElementArrayBufferResource = bufferVk;
mCurrentElementArrayBufferHandle = bufferVk->getVkBuffer().getHandle();
}
else
{
mCurrentElementArrayBufferResource = nullptr;
mCurrentElementArrayBufferHandle = VK_NULL_HANDLE;
}
mCurrentElementArrayBufferOffset = 0;
mLineLoopBufferFirstIndex.reset();
mLineLoopBufferLastIndex.reset();
mIndexBufferDirty = true;
mDirtyLineLoopTranslation = true;
break;
}
case gl::VertexArray::DIRTY_BIT_ELEMENT_ARRAY_BUFFER_DATA:
mLineLoopBufferFirstIndex.reset();
mLineLoopBufferLastIndex.reset();
mDirtyLineLoopTranslation = true;
break;
ANGLE_VERTEX_INDEX_CASES(ANGLE_VERTEX_DIRTY_ATTRIB_FUNC);
ANGLE_VERTEX_INDEX_CASES(ANGLE_VERTEX_DIRTY_BINDING_FUNC);
ANGLE_VERTEX_INDEX_CASES(ANGLE_VERTEX_DIRTY_BUFFER_DATA_FUNC);
default:
UNREACHABLE();
break;
}
}
if (invalidatePipeline)
{
mVertexBuffersDirty = true;
contextVk->invalidateCurrentPipeline();
}
return gl::NoError();
}
void VertexArrayVk::syncDirtyAttrib(const gl::VertexAttribute &attrib,
const gl::VertexBinding &binding,
size_t attribIndex)
{
// Invalidate the input description for pipelines.
mDirtyPackedInputs.set(attribIndex);
if (attrib.enabled)
{
gl::Buffer *bufferGL = binding.getBuffer().get();
if (bufferGL)
{
BufferVk *bufferVk = vk::GetImpl(bufferGL);
mCurrentArrayBufferResources[attribIndex] = bufferVk;
mCurrentArrayBufferHandles[attribIndex] = bufferVk->getVkBuffer().getHandle();
}
else
{
mCurrentArrayBufferResources[attribIndex] = nullptr;
mCurrentArrayBufferHandles[attribIndex] = VK_NULL_HANDLE;
}
// TODO(jmadill): Offset handling. Assume zero for now.
mCurrentArrayBufferOffsets[attribIndex] = 0;
}
else
{
UNIMPLEMENTED();
}
}
const gl::AttribArray<VkBuffer> &VertexArrayVk::getCurrentArrayBufferHandles() const
{
return mCurrentArrayBufferHandles;
}
const gl::AttribArray<VkDeviceSize> &VertexArrayVk::getCurrentArrayBufferOffsets() const
{
return mCurrentArrayBufferOffsets;
}
void VertexArrayVk::updateArrayBufferReadDependencies(vk::CommandGraphResource *drawFramebuffer,
const gl::AttributesMask &activeAttribsMask,
Serial serial)
{
// Handle the bound array buffers.
for (size_t attribIndex : activeAttribsMask)
{
if (mCurrentArrayBufferResources[attribIndex])
mCurrentArrayBufferResources[attribIndex]->addReadDependency(drawFramebuffer);
}
}
void VertexArrayVk::updateElementArrayBufferReadDependency(
vk::CommandGraphResource *drawFramebuffer,
Serial serial)
{
// Handle the bound element array buffer.
if (mCurrentElementArrayBufferResource)
{
mCurrentElementArrayBufferResource->addReadDependency(drawFramebuffer);
}
}
void VertexArrayVk::getPackedInputDescriptions(vk::PipelineDesc *pipelineDesc)
{
updatePackedInputDescriptions();
pipelineDesc->updateVertexInputInfo(mPackedInputBindings, mPackedInputAttributes);
}
void VertexArrayVk::updatePackedInputDescriptions()
{
if (!mDirtyPackedInputs.any())
{
return;
}
const auto &attribs = mState.getVertexAttributes();
const auto &bindings = mState.getVertexBindings();
for (auto attribIndex : mDirtyPackedInputs)
{
const auto &attrib = attribs[attribIndex];
const auto &binding = bindings[attrib.bindingIndex];
if (attrib.enabled)
{
updatePackedInputInfo(static_cast<uint32_t>(attribIndex), binding, attrib);
}
else
{
UNIMPLEMENTED();
}
}
mDirtyPackedInputs.reset();
}
void VertexArrayVk::updatePackedInputInfo(uint32_t attribIndex,
const gl::VertexBinding &binding,
const gl::VertexAttribute &attrib)
{
vk::PackedVertexInputBindingDesc &bindingDesc = mPackedInputBindings[attribIndex];
size_t attribSize = gl::ComputeVertexAttributeTypeSize(attrib);
ASSERT(attribSize <= std::numeric_limits<uint16_t>::max());
bindingDesc.stride = static_cast<uint16_t>(binding.getStride());
bindingDesc.inputRate = static_cast<uint16_t>(
binding.getDivisor() > 0 ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX);
gl::VertexFormatType vertexFormatType = gl::GetVertexFormatType(attrib);
VkFormat vkFormat = vk::GetNativeVertexFormat(vertexFormatType);
ASSERT(vkFormat <= std::numeric_limits<uint16_t>::max());
vk::PackedVertexInputAttributeDesc &attribDesc = mPackedInputAttributes[attribIndex];
attribDesc.format = static_cast<uint16_t>(vkFormat);
attribDesc.location = static_cast<uint16_t>(attribIndex);
attribDesc.offset = static_cast<uint32_t>(ComputeVertexAttributeOffset(attrib, binding));
}
gl::Error VertexArrayVk::drawArrays(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
ASSERT(commandBuffer->valid());
ANGLE_TRY(onDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
// Note: Vertex indexes can be arbitrarily large.
uint32_t clampedVertexCount = drawCallParams.getClampedVertexCount<uint32_t>();
if (drawCallParams.mode() != gl::PrimitiveMode::LineLoop)
{
commandBuffer->draw(clampedVertexCount, 1, drawCallParams.firstVertex(), 0);
return gl::NoError();
}
// Handle GL_LINE_LOOP drawArrays.
size_t lastVertex = static_cast<size_t>(drawCallParams.firstVertex() + clampedVertexCount);
if (!mLineLoopBufferFirstIndex.valid() || !mLineLoopBufferLastIndex.valid() ||
mLineLoopBufferFirstIndex != drawCallParams.firstVertex() ||
mLineLoopBufferLastIndex != lastVertex)
{
ANGLE_TRY(mLineLoopHelper.getIndexBufferForDrawArrays(renderer, drawCallParams,
&mCurrentElementArrayBufferHandle,
&mCurrentElementArrayBufferOffset));
mLineLoopBufferFirstIndex = drawCallParams.firstVertex();
mLineLoopBufferLastIndex = lastVertex;
}
commandBuffer->bindIndexBuffer(mCurrentElementArrayBufferHandle,
mCurrentElementArrayBufferOffset, VK_INDEX_TYPE_UINT32);
vk::LineLoopHelper::Draw(clampedVertexCount, commandBuffer);
return gl::NoError();
}
gl::Error VertexArrayVk::drawElements(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
ASSERT(commandBuffer->valid());
if (drawCallParams.mode() != gl::PrimitiveMode::LineLoop)
{
ANGLE_TRY(
onIndexedDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
commandBuffer->drawIndexed(drawCallParams.indexCount(), 1, 0, 0, 0);
return gl::NoError();
}
// Handle GL_LINE_LOOP drawElements.
if (mDirtyLineLoopTranslation)
{
gl::Buffer *elementArrayBuffer = mState.getElementArrayBuffer().get();
VkIndexType indexType = gl_vk::GetIndexType(drawCallParams.type());
if (!elementArrayBuffer)
{
ANGLE_TRY(mLineLoopHelper.getIndexBufferForClientElementArray(
renderer, drawCallParams.indices(), indexType, drawCallParams.indexCount(),
&mCurrentElementArrayBufferHandle, &mCurrentElementArrayBufferOffset));
}
else
{
// When using an element array buffer, 'indices' is an offset to the first element.
intptr_t offset = reinterpret_cast<intptr_t>(drawCallParams.indices());
BufferVk *elementArrayBufferVk = vk::GetImpl(elementArrayBuffer);
ANGLE_TRY(mLineLoopHelper.getIndexBufferForElementArrayBuffer(
renderer, elementArrayBufferVk, indexType, drawCallParams.indexCount(), offset,
&mCurrentElementArrayBufferHandle, &mCurrentElementArrayBufferOffset));
}
}
ANGLE_TRY(onIndexedDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
vk::LineLoopHelper::Draw(drawCallParams.indexCount(), commandBuffer);
return gl::NoError();
}
gl::Error VertexArrayVk::onDraw(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
const gl::State &state = context->getGLState();
const gl::Program *programGL = state.getProgram();
const gl::AttributesMask &clientAttribs = mState.getEnabledClientMemoryAttribsMask();
const gl::AttributesMask &activeAttribs = programGL->getActiveAttribLocationsMask();
uint32_t maxAttrib = programGL->getState().getMaxActiveAttribLocation();
if (clientAttribs.any())
{
const gl::AttributesMask &attribsToStream = (clientAttribs & activeAttribs);
if (attribsToStream.any())
{
ANGLE_TRY(drawCallParams.ensureIndexRangeResolved(context));
ANGLE_TRY(streamVertexData(renderer, attribsToStream, drawCallParams));
commandBuffer->bindVertexBuffers(0, maxAttrib, mCurrentArrayBufferHandles.data(),
mCurrentArrayBufferOffsets.data());
}
}
else if (mVertexBuffersDirty || newCommandBuffer)
{
if (maxAttrib > 0)
{
commandBuffer->bindVertexBuffers(0, maxAttrib, mCurrentArrayBufferHandles.data(),
mCurrentArrayBufferOffsets.data());
vk::CommandGraphResource *drawFramebuffer = vk::GetImpl(state.getDrawFramebuffer());
updateArrayBufferReadDependencies(drawFramebuffer, activeAttribs,
renderer->getCurrentQueueSerial());
}
mVertexBuffersDirty = false;
// This forces the binding to happen if we follow a drawElement call from a drawArrays call.
mIndexBufferDirty = true;
// If we've had a drawElements call with a line loop before, we want to make sure this is
// invalidated the next time drawElements is called since we use the same index buffer for
// both calls.
mDirtyLineLoopTranslation = true;
}
return gl::NoError();
}
gl::Error VertexArrayVk::onIndexedDraw(const gl::Context *context,
RendererVk *renderer,
const gl::DrawCallParams &drawCallParams,
vk::CommandBuffer *commandBuffer,
bool newCommandBuffer)
{
ANGLE_TRY(onDraw(context, renderer, drawCallParams, commandBuffer, newCommandBuffer));
if (!mState.getElementArrayBuffer().get() &&
drawCallParams.mode() != gl::PrimitiveMode::LineLoop)
{
ANGLE_TRY(drawCallParams.ensureIndexRangeResolved(context));
ANGLE_TRY(streamIndexData(renderer, drawCallParams));
commandBuffer->bindIndexBuffer(mCurrentElementArrayBufferHandle,
mCurrentElementArrayBufferOffset,
gl_vk::GetIndexType(drawCallParams.type()));
}
else if (mIndexBufferDirty || newCommandBuffer)
{
if (drawCallParams.type() == GL_UNSIGNED_BYTE)
{
// TODO(fjhenigman): Index format translation.
UNIMPLEMENTED();
return gl::InternalError()
<< "Unsigned byte translation is not implemented for indices in a buffer object";
}
commandBuffer->bindIndexBuffer(mCurrentElementArrayBufferHandle,
mCurrentElementArrayBufferOffset,
gl_vk::GetIndexType(drawCallParams.type()));
const gl::State &glState = context->getGLState();
vk::CommandGraphResource *drawFramebuffer = vk::GetImpl(glState.getDrawFramebuffer());
updateElementArrayBufferReadDependency(drawFramebuffer, renderer->getCurrentQueueSerial());
mIndexBufferDirty = false;
// If we've had a drawArrays call with a line loop before, we want to make sure this is
// invalidated the next time drawArrays is called since we use the same index buffer for
// both calls.
mLineLoopBufferFirstIndex.reset();
mLineLoopBufferLastIndex.reset();
}
return gl::NoError();
}
} // namespace rx
|
//
// Copyright 2018 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// vk_utils:
// Helper functions for the Vulkan Caps.
//
#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
#include <type_traits>
#include "common/utilities.h"
#include "libANGLE/Caps.h"
#include "libANGLE/formatutils.h"
#include "libANGLE/renderer/vulkan/DisplayVk.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
#include "vk_format_utils.h"
namespace
{
constexpr unsigned int kComponentsPerVector = 4;
} // anonymous namespace
namespace rx
{
GLint LimitToInt(const uint32_t physicalDeviceValue)
{
return std::min(physicalDeviceValue,
static_cast<uint32_t>(std::numeric_limits<int32_t>::max()));
}
void RendererVk::ensureCapsInitialized() const
{
if (mCapsInitialized)
return;
mCapsInitialized = true;
ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
const VkQueueFamilyProperties &queueFamilyProperties =
mQueueFamilyProperties[mCurrentQueueFamilyIndex];
const VkPhysicalDeviceLimits &limitsVk = mPhysicalDeviceProperties.limits;
mNativeExtensions.setTextureExtensionSupport(mNativeTextureCaps);
// Vulkan technically only supports the LDR profile but driver all appear to support the HDR
// profile as well. http://anglebug.com/1185#c8
mNativeExtensions.textureCompressionASTCHDRKHR = mNativeExtensions.textureCompressionASTCLDRKHR;
// Enable this for simple buffer readback testing, but some functionality is missing.
// TODO(jmadill): Support full mapBufferRange extension.
mNativeExtensions.mapBuffer = true;
mNativeExtensions.mapBufferRange = true;
mNativeExtensions.textureStorage = true;
mNativeExtensions.drawBuffers = true;
mNativeExtensions.fragDepth = true;
mNativeExtensions.framebufferBlit = true;
mNativeExtensions.framebufferMultisample = true;
mNativeExtensions.copyTexture = true;
mNativeExtensions.copyCompressedTexture = true;
mNativeExtensions.debugMarker = true;
mNativeExtensions.robustness = true;
mNativeExtensions.textureBorderClamp = false; // not implemented yet
mNativeExtensions.translatedShaderSource = true;
mNativeExtensions.discardFramebuffer = true;
// Enable EXT_texture_type_2_10_10_10_REV
mNativeExtensions.textureFormat2101010REV = true;
// Enable ANGLE_base_vertex_base_instance
mNativeExtensions.baseVertexBaseInstance = true;
// Enable OES/EXT_draw_elements_base_vertex
mNativeExtensions.drawElementsBaseVertexOES = true;
mNativeExtensions.drawElementsBaseVertexEXT = true;
// Enable EXT_blend_minmax
mNativeExtensions.blendMinMax = true;
mNativeExtensions.eglImage = true;
mNativeExtensions.eglImageExternal = true;
mNativeExtensions.eglImageExternalEssl3 = true;
mNativeExtensions.memoryObject = true;
mNativeExtensions.memoryObjectFd = getFeatures().supportsExternalMemoryFd.enabled;
mNativeExtensions.semaphore = true;
mNativeExtensions.semaphoreFd = getFeatures().supportsExternalSemaphoreFd.enabled;
mNativeExtensions.vertexHalfFloat = true;
// Enabled in HW if VK_EXT_vertex_attribute_divisor available, otherwise emulated
mNativeExtensions.instancedArraysANGLE = true;
mNativeExtensions.instancedArraysEXT = true;
// Only expose robust buffer access if the physical device supports it.
mNativeExtensions.robustBufferAccessBehavior =
(mPhysicalDeviceFeatures.robustBufferAccess == VK_TRUE);
mNativeExtensions.eglSync = true;
mNativeExtensions.vertexAttribType1010102 = true;
// We use secondary command buffers almost everywhere and they require a feature to be
// able to execute in the presence of queries. As a result, we won't support queries
// unless that feature is available.
mNativeExtensions.occlusionQueryBoolean =
vk::CommandBuffer::SupportsQueries(mPhysicalDeviceFeatures);
// From the Vulkan specs:
// > The number of valid bits in a timestamp value is determined by the
// > VkQueueFamilyProperties::timestampValidBits property of the queue on which the timestamp is
// > written. Timestamps are supported on any queue which reports a non-zero value for
// > timestampValidBits via vkGetPhysicalDeviceQueueFamilyProperties.
mNativeExtensions.disjointTimerQuery = queueFamilyProperties.timestampValidBits > 0;
mNativeExtensions.queryCounterBitsTimeElapsed = queueFamilyProperties.timestampValidBits;
mNativeExtensions.queryCounterBitsTimestamp = queueFamilyProperties.timestampValidBits;
mNativeExtensions.textureFilterAnisotropic =
mPhysicalDeviceFeatures.samplerAnisotropy && limitsVk.maxSamplerAnisotropy > 1.0f;
mNativeExtensions.maxTextureAnisotropy =
mNativeExtensions.textureFilterAnisotropic ? limitsVk.maxSamplerAnisotropy : 0.0f;
// Vulkan natively supports non power-of-two textures
mNativeExtensions.textureNPOT = true;
mNativeExtensions.texture3DOES = true;
// Vulkan natively supports standard derivatives
mNativeExtensions.standardDerivatives = true;
// Vulkan natively supports 32-bit indices, entry in kIndexTypeMap
mNativeExtensions.elementIndexUint = true;
mNativeExtensions.fboRenderMipmap = true;
// We support getting image data for Textures and Renderbuffers.
mNativeExtensions.getImageANGLE = true;
mNativeExtensions.gpuShader5EXT = vk::CanSupportGPUShader5EXT(mPhysicalDeviceFeatures);
// https://vulkan.lunarg.com/doc/view/1.0.30.0/linux/vkspec.chunked/ch31s02.html
mNativeCaps.maxElementIndex = std::numeric_limits<GLuint>::max() - 1;
mNativeCaps.max3DTextureSize = LimitToInt(limitsVk.maxImageDimension3D);
mNativeCaps.max2DTextureSize =
std::min(limitsVk.maxFramebufferWidth, limitsVk.maxImageDimension2D);
mNativeCaps.maxArrayTextureLayers = LimitToInt(limitsVk.maxImageArrayLayers);
mNativeCaps.maxLODBias = limitsVk.maxSamplerLodBias;
mNativeCaps.maxCubeMapTextureSize = LimitToInt(limitsVk.maxImageDimensionCube);
mNativeCaps.maxRenderbufferSize =
std::min({limitsVk.maxImageDimension2D, limitsVk.maxFramebufferWidth,
limitsVk.maxFramebufferHeight});
mNativeCaps.minAliasedPointSize = std::max(1.0f, limitsVk.pointSizeRange[0]);
mNativeCaps.maxAliasedPointSize = limitsVk.pointSizeRange[1];
mNativeCaps.minAliasedLineWidth = 1.0f;
mNativeCaps.maxAliasedLineWidth = 1.0f;
mNativeCaps.maxDrawBuffers =
std::min(limitsVk.maxColorAttachments, limitsVk.maxFragmentOutputAttachments);
mNativeCaps.maxFramebufferWidth = LimitToInt(limitsVk.maxFramebufferWidth);
mNativeCaps.maxFramebufferHeight = LimitToInt(limitsVk.maxFramebufferHeight);
mNativeCaps.maxColorAttachments = LimitToInt(limitsVk.maxColorAttachments);
mNativeCaps.maxViewportWidth = LimitToInt(limitsVk.maxViewportDimensions[0]);
mNativeCaps.maxViewportHeight = LimitToInt(limitsVk.maxViewportDimensions[1]);
mNativeCaps.maxSampleMaskWords = LimitToInt(limitsVk.maxSampleMaskWords);
mNativeCaps.maxColorTextureSamples =
limitsVk.sampledImageColorSampleCounts & vk_gl::kSupportedSampleCounts;
mNativeCaps.maxDepthTextureSamples =
limitsVk.sampledImageDepthSampleCounts & vk_gl::kSupportedSampleCounts;
// TODO (ianelliott): Should mask this with vk_gl::kSupportedSampleCounts, but it causes
// end2end test failures with SwiftShader because SwiftShader returns a sample count of 1 in
// sampledImageIntegerSampleCounts.
// See: http://anglebug.com/4197
mNativeCaps.maxIntegerSamples = limitsVk.sampledImageIntegerSampleCounts;
mNativeCaps.maxVertexAttributes = LimitToInt(limitsVk.maxVertexInputAttributes);
mNativeCaps.maxVertexAttribBindings = LimitToInt(limitsVk.maxVertexInputBindings);
// Offset and stride are stored as uint16_t in PackedAttribDesc.
mNativeCaps.maxVertexAttribRelativeOffset =
std::min(static_cast<uint32_t>(std::numeric_limits<uint16_t>::max()),
limitsVk.maxVertexInputAttributeOffset);
mNativeCaps.maxVertexAttribStride =
std::min(static_cast<uint32_t>(std::numeric_limits<uint16_t>::max()),
limitsVk.maxVertexInputBindingStride);
mNativeCaps.maxElementsIndices = std::numeric_limits<GLint>::max();
mNativeCaps.maxElementsVertices = std::numeric_limits<GLint>::max();
// Looks like all floats are IEEE according to the docs here:
// https://www.khronos.org/registry/vulkan/specs/1.0-wsi_extensions/html/vkspec.html#spirvenv-precision-operation
mNativeCaps.vertexHighpFloat.setIEEEFloat();
mNativeCaps.vertexMediumpFloat.setIEEEFloat();
mNativeCaps.vertexLowpFloat.setIEEEFloat();
mNativeCaps.fragmentHighpFloat.setIEEEFloat();
mNativeCaps.fragmentMediumpFloat.setIEEEFloat();
mNativeCaps.fragmentLowpFloat.setIEEEFloat();
// Can't find documentation on the int precision in Vulkan.
mNativeCaps.vertexHighpInt.setTwosComplementInt(32);
mNativeCaps.vertexMediumpInt.setTwosComplementInt(32);
mNativeCaps.vertexLowpInt.setTwosComplementInt(32);
mNativeCaps.fragmentHighpInt.setTwosComplementInt(32);
mNativeCaps.fragmentMediumpInt.setTwosComplementInt(32);
mNativeCaps.fragmentLowpInt.setTwosComplementInt(32);
// Compute shader limits.
mNativeCaps.maxComputeWorkGroupCount[0] = LimitToInt(limitsVk.maxComputeWorkGroupCount[0]);
mNativeCaps.maxComputeWorkGroupCount[1] = LimitToInt(limitsVk.maxComputeWorkGroupCount[1]);
mNativeCaps.maxComputeWorkGroupCount[2] = LimitToInt(limitsVk.maxComputeWorkGroupCount[2]);
mNativeCaps.maxComputeWorkGroupSize[0] = LimitToInt(limitsVk.maxComputeWorkGroupSize[0]);
mNativeCaps.maxComputeWorkGroupSize[1] = LimitToInt(limitsVk.maxComputeWorkGroupSize[1]);
mNativeCaps.maxComputeWorkGroupSize[2] = LimitToInt(limitsVk.maxComputeWorkGroupSize[2]);
mNativeCaps.maxComputeWorkGroupInvocations =
LimitToInt(limitsVk.maxComputeWorkGroupInvocations);
mNativeCaps.maxComputeSharedMemorySize = LimitToInt(limitsVk.maxComputeSharedMemorySize);
// TODO(lucferron): This is something we'll need to implement custom in the back-end.
// Vulkan doesn't do any waiting for you, our back-end code is going to manage sync objects,
// and we'll have to check that we've exceeded the max wait timeout. Also, this is ES 3.0 so
// we'll defer the implementation until we tackle the next version.
// mNativeCaps.maxServerWaitTimeout
GLuint maxUniformBlockSize = limitsVk.maxUniformBufferRange;
// Clamp the maxUniformBlockSize to 64KB (majority of devices support up to this size
// currently), on AMD the maxUniformBufferRange is near uint32_t max.
maxUniformBlockSize = std::min(0x10000u, maxUniformBlockSize);
const GLuint maxUniformVectors = maxUniformBlockSize / (sizeof(GLfloat) * kComponentsPerVector);
const GLuint maxUniformComponents = maxUniformVectors * kComponentsPerVector;
// Uniforms are implemented using a uniform buffer, so the max number of uniforms we can
// support is the max buffer range divided by the size of a single uniform (4X float).
mNativeCaps.maxVertexUniformVectors = maxUniformVectors;
mNativeCaps.maxFragmentUniformVectors = maxUniformVectors;
mNativeCaps.maxFragmentInputComponents = maxUniformComponents;
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderUniformComponents[shaderType] = maxUniformComponents;
}
mNativeCaps.maxUniformLocations = maxUniformVectors;
// Every stage has 1 reserved uniform buffer for the default uniforms, and 1 for the driver
// uniforms.
constexpr uint32_t kTotalReservedPerStageUniformBuffers =
kReservedDriverUniformBindingCount + kReservedPerStageDefaultUniformBindingCount;
constexpr uint32_t kTotalReservedUniformBuffers =
kReservedDriverUniformBindingCount + kReservedDefaultUniformBindingCount;
const int32_t maxPerStageUniformBuffers = LimitToInt(
limitsVk.maxPerStageDescriptorUniformBuffers - kTotalReservedPerStageUniformBuffers);
const int32_t maxCombinedUniformBuffers =
LimitToInt(limitsVk.maxDescriptorSetUniformBuffers - kTotalReservedUniformBuffers);
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderUniformBlocks[shaderType] = maxPerStageUniformBuffers;
}
mNativeCaps.maxCombinedUniformBlocks = maxCombinedUniformBuffers;
mNativeCaps.maxUniformBufferBindings = maxCombinedUniformBuffers;
mNativeCaps.maxUniformBlockSize = maxUniformBlockSize;
mNativeCaps.uniformBufferOffsetAlignment =
static_cast<GLint>(limitsVk.minUniformBufferOffsetAlignment);
// Note that Vulkan currently implements textures as combined image+samplers, so the limit is
// the minimum of supported samplers and sampled images.
const uint32_t maxPerStageTextures = std::min(limitsVk.maxPerStageDescriptorSamplers,
limitsVk.maxPerStageDescriptorSampledImages);
const uint32_t maxCombinedTextures =
std::min(limitsVk.maxDescriptorSetSamplers, limitsVk.maxDescriptorSetSampledImages);
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderTextureImageUnits[shaderType] = LimitToInt(maxPerStageTextures);
}
mNativeCaps.maxCombinedTextureImageUnits = LimitToInt(maxCombinedTextures);
uint32_t maxPerStageStorageBuffers = limitsVk.maxPerStageDescriptorStorageBuffers;
uint32_t maxVertexStageStorageBuffers = maxPerStageStorageBuffers;
uint32_t maxCombinedStorageBuffers = limitsVk.maxDescriptorSetStorageBuffers;
// A number of storage buffer slots are used in the vertex shader to emulate transform feedback.
// Note that Vulkan requires maxPerStageDescriptorStorageBuffers to be at least 4 (i.e. the same
// as gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS).
// TODO(syoussefi): This should be conditioned to transform feedback extension not being
// present. http://anglebug.com/3206.
// TODO(syoussefi): If geometry shader is supported, emulation will be done at that stage, and
// so the reserved storage buffers should be accounted in that stage. http://anglebug.com/3606
static_assert(
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS == 4,
"Limit to ES2.0 if supported SSBO count < supporting transform feedback buffer count");
if (mPhysicalDeviceFeatures.vertexPipelineStoresAndAtomics)
{
ASSERT(maxVertexStageStorageBuffers >= gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS);
maxVertexStageStorageBuffers -= gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS;
maxCombinedStorageBuffers -= gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS;
// Cap the per-stage limit of the other stages to the combined limit, in case the combined
// limit is now lower than that.
maxPerStageStorageBuffers = std::min(maxPerStageStorageBuffers, maxCombinedStorageBuffers);
}
// Reserve up to IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS storage buffers in the fragment and
// compute stages for atomic counters. This is only possible if the number of per-stage storage
// buffers is greater than 4, which is the required GLES minimum for compute.
//
// For each stage, we'll either not support atomic counter buffers, or support exactly
// IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS. This is due to restrictions in the shader
// translator where we can't know how many atomic counter buffers we would really need after
// linking so we can't create a packed buffer array.
//
// For the vertex stage, we could support atomic counters without storage buffers, but that's
// likely not very useful, so we use the same limit (4 + MAX_ATOMIC_COUNTER_BUFFERS) for the
// vertex stage to determine if we would want to add support for atomic counter buffers.
constexpr uint32_t kMinimumStorageBuffersForAtomicCounterBufferSupport =
gl::limits::kMinimumComputeStorageBuffers + gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
uint32_t maxVertexStageAtomicCounterBuffers = 0;
uint32_t maxPerStageAtomicCounterBuffers = 0;
uint32_t maxCombinedAtomicCounterBuffers = 0;
if (maxPerStageStorageBuffers >= kMinimumStorageBuffersForAtomicCounterBufferSupport)
{
maxPerStageAtomicCounterBuffers = gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
maxCombinedAtomicCounterBuffers = gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
}
if (maxVertexStageStorageBuffers >= kMinimumStorageBuffersForAtomicCounterBufferSupport)
{
maxVertexStageAtomicCounterBuffers = gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
}
maxVertexStageStorageBuffers -= maxVertexStageAtomicCounterBuffers;
maxPerStageStorageBuffers -= maxPerStageAtomicCounterBuffers;
maxCombinedStorageBuffers -= maxCombinedAtomicCounterBuffers;
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Vertex] =
mPhysicalDeviceFeatures.vertexPipelineStoresAndAtomics
? LimitToInt(maxVertexStageStorageBuffers)
: 0;
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Fragment] =
mPhysicalDeviceFeatures.fragmentStoresAndAtomics ? LimitToInt(maxPerStageStorageBuffers)
: 0;
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Compute] =
LimitToInt(maxPerStageStorageBuffers);
mNativeCaps.maxCombinedShaderStorageBlocks = LimitToInt(maxCombinedStorageBuffers);
mNativeCaps.maxShaderStorageBufferBindings = LimitToInt(maxCombinedStorageBuffers);
mNativeCaps.maxShaderStorageBlockSize = limitsVk.maxStorageBufferRange;
mNativeCaps.shaderStorageBufferOffsetAlignment =
LimitToInt(static_cast<uint32_t>(limitsVk.minStorageBufferOffsetAlignment));
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Vertex] =
mPhysicalDeviceFeatures.vertexPipelineStoresAndAtomics
? LimitToInt(maxVertexStageAtomicCounterBuffers)
: 0;
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Fragment] =
mPhysicalDeviceFeatures.fragmentStoresAndAtomics
? LimitToInt(maxPerStageAtomicCounterBuffers)
: 0;
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Compute] =
LimitToInt(maxPerStageAtomicCounterBuffers);
mNativeCaps.maxCombinedAtomicCounterBuffers = LimitToInt(maxCombinedAtomicCounterBuffers);
mNativeCaps.maxAtomicCounterBufferBindings = LimitToInt(maxCombinedAtomicCounterBuffers);
// Emulated as storage buffers, atomic counter buffers have the same size limit. However, the
// limit is a signed integer and values above int max will end up as a negative size.
mNativeCaps.maxAtomicCounterBufferSize = LimitToInt(limitsVk.maxStorageBufferRange);
// There is no particular limit to how many atomic counters there can be, other than the size of
// a storage buffer. We nevertheless limit this to something sane (4096 arbitrarily).
const int32_t maxAtomicCounters =
std::min<int32_t>(4096, limitsVk.maxStorageBufferRange / sizeof(uint32_t));
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderAtomicCounters[shaderType] = maxAtomicCounters;
}
mNativeCaps.maxCombinedAtomicCounters = maxAtomicCounters;
// GL Images correspond to Vulkan Storage Images.
const int32_t maxPerStageImages = LimitToInt(limitsVk.maxPerStageDescriptorStorageImages);
const int32_t maxCombinedImages = LimitToInt(limitsVk.maxDescriptorSetStorageImages);
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderImageUniforms[shaderType] = maxPerStageImages;
}
mNativeCaps.maxCombinedImageUniforms = maxCombinedImages;
mNativeCaps.maxImageUnits = maxCombinedImages;
mNativeCaps.minProgramTexelOffset = limitsVk.minTexelOffset;
mNativeCaps.maxProgramTexelOffset = limitsVk.maxTexelOffset;
mNativeCaps.minProgramTextureGatherOffset = limitsVk.minTexelGatherOffset;
mNativeCaps.maxProgramTextureGatherOffset = limitsVk.maxTexelGatherOffset;
// There is no additional limit to the combined number of components. We can have up to a
// maximum number of uniform buffers, each having the maximum number of components. Note that
// this limit includes both components in and out of uniform buffers.
const uint32_t maxCombinedUniformComponents =
(maxPerStageUniformBuffers + kReservedPerStageDefaultUniformBindingCount) *
maxUniformComponents;
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxCombinedShaderUniformComponents[shaderType] = maxCombinedUniformComponents;
}
// Total number of resources available to the user are as many as Vulkan allows minus everything
// that ANGLE uses internally. That is, one dynamic uniform buffer used per stage for default
// uniforms and a single dynamic uniform buffer for driver uniforms. Additionally, Vulkan uses
// up to IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS + 1 buffers for transform feedback (Note:
// +1 is for the "counter" buffer of transform feedback, which will be necessary for transform
// feedback extension and ES3.2 transform feedback emulation, but is not yet present).
constexpr uint32_t kReservedPerStageUniformBufferCount = 1;
constexpr uint32_t kReservedPerStageBindingCount =
kReservedDriverUniformBindingCount + kReservedPerStageUniformBufferCount +
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS + 1;
// Note: maxPerStageResources is required to be at least the sum of per stage UBOs, SSBOs etc
// which total a minimum of 44 resources, so no underflow is possible here. Limit the total
// number of resources reported by Vulkan to 2 billion though to avoid seeing negative numbers
// in applications that take the value as signed int (including dEQP).
const uint32_t maxPerStageResources = limitsVk.maxPerStageResources;
mNativeCaps.maxCombinedShaderOutputResources =
LimitToInt(maxPerStageResources - kReservedPerStageBindingCount);
// The max vertex output components should not include gl_Position.
// The gles2.0 section 2.10 states that "gl_Position is not a varying variable and does
// not count against this limit.", but the Vulkan spec has no such mention in its Built-in
// vars section. It is implicit that we need to actually reserve it for Vulkan in that case.
GLint reservedVaryingVectorCount = 1;
mNativeCaps.maxVaryingVectors = LimitToInt(
(limitsVk.maxVertexOutputComponents / kComponentsPerVector) - reservedVaryingVectorCount);
mNativeCaps.maxVertexOutputComponents = LimitToInt(limitsVk.maxVertexOutputComponents);
mNativeCaps.maxTransformFeedbackInterleavedComponents =
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS;
mNativeCaps.maxTransformFeedbackSeparateAttributes =
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
mNativeCaps.maxTransformFeedbackSeparateComponents =
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS;
mNativeCaps.minProgramTexelOffset = limitsVk.minTexelOffset;
mNativeCaps.maxProgramTexelOffset = LimitToInt(limitsVk.maxTexelOffset);
const uint32_t sampleCounts =
limitsVk.framebufferColorSampleCounts & limitsVk.framebufferDepthSampleCounts &
limitsVk.framebufferStencilSampleCounts & vk_gl::kSupportedSampleCounts;
mNativeCaps.maxSamples = LimitToInt(vk_gl::GetMaxSampleCount(sampleCounts));
mNativeCaps.maxFramebufferSamples = mNativeCaps.maxSamples;
mNativeCaps.subPixelBits = limitsVk.subPixelPrecisionBits;
// Enable Program Binary extension.
mNativeExtensions.getProgramBinary = true;
mNativeCaps.programBinaryFormats.push_back(GL_PROGRAM_BINARY_ANGLE);
// Enable GL_NV_pixel_buffer_object extension.
mNativeExtensions.pixelBufferObject = true;
// Geometry shader is optional.
if (mPhysicalDeviceFeatures.geometryShader)
{
// TODO : Remove below comment when http://anglebug.com/3571 will be completed
// mNativeExtensions.geometryShader = true;
mNativeCaps.maxFramebufferLayers = LimitToInt(limitsVk.maxFramebufferLayers);
mNativeCaps.layerProvokingVertex = GL_LAST_VERTEX_CONVENTION_EXT;
mNativeCaps.maxGeometryInputComponents = LimitToInt(limitsVk.maxGeometryInputComponents);
mNativeCaps.maxGeometryOutputComponents = LimitToInt(limitsVk.maxGeometryOutputComponents);
mNativeCaps.maxGeometryOutputVertices = LimitToInt(limitsVk.maxGeometryOutputVertices);
mNativeCaps.maxGeometryTotalOutputComponents =
LimitToInt(limitsVk.maxGeometryTotalOutputComponents);
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Geometry] =
mNativeCaps.maxCombinedShaderOutputResources;
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Geometry] =
maxCombinedAtomicCounterBuffers;
mNativeCaps.maxGeometryShaderInvocations =
LimitToInt(limitsVk.maxGeometryShaderInvocations);
}
}
namespace vk
{
bool CanSupportGPUShader5EXT(const VkPhysicalDeviceFeatures &features)
{
// We use the following Vulkan features to implement EXT_gpu_shader5:
// - shaderImageGatherExtended: textureGatherOffset with non-constant offset and
// textureGatherOffsets family of functions.
// - shaderSampledImageArrayDynamicIndexing and shaderUniformBufferArrayDynamicIndexing:
// dynamically uniform indices for samplers and uniform buffers.
// - shaderStorageBufferArrayDynamicIndexing: While EXT_gpu_shader5 doesn't require dynamically
// uniform indices on storage buffers, we need it as we emulate atomic counter buffers with
// storage buffers (and atomic counter buffers *can* be indexed in that way).
return features.shaderImageGatherExtended && features.shaderSampledImageArrayDynamicIndexing &&
features.shaderUniformBufferArrayDynamicIndexing &&
features.shaderStorageBufferArrayDynamicIndexing;
}
} // namespace vk
namespace egl_vk
{
namespace
{
EGLint ComputeMaximumPBufferPixels(const VkPhysicalDeviceProperties &physicalDeviceProperties)
{
// EGLints are signed 32-bit integers, it's fairly easy to overflow them, especially since
// Vulkan's minimum guaranteed VkImageFormatProperties::maxResourceSize is 2^31 bytes.
constexpr uint64_t kMaxValueForEGLint =
static_cast<uint64_t>(std::numeric_limits<EGLint>::max());
// TODO(geofflang): Compute the maximum size of a pbuffer by using the maxResourceSize result
// from vkGetPhysicalDeviceImageFormatProperties for both the color and depth stencil format and
// the exact image creation parameters that would be used to create the pbuffer. Because it is
// always safe to return out-of-memory errors on pbuffer allocation, it's fine to simply return
// the number of pixels in a max width by max height pbuffer for now. http://anglebug.com/2622
// Storing the result of squaring a 32-bit unsigned int in a 64-bit unsigned int is safe.
static_assert(std::is_same<decltype(physicalDeviceProperties.limits.maxImageDimension2D),
uint32_t>::value,
"physicalDeviceProperties.limits.maxImageDimension2D expected to be a uint32_t.");
const uint64_t maxDimensionsSquared =
static_cast<uint64_t>(physicalDeviceProperties.limits.maxImageDimension2D) *
static_cast<uint64_t>(physicalDeviceProperties.limits.maxImageDimension2D);
return static_cast<EGLint>(std::min(maxDimensionsSquared, kMaxValueForEGLint));
}
// Generates a basic config for a combination of color format, depth stencil format and sample
// count.
egl::Config GenerateDefaultConfig(const RendererVk *renderer,
const gl::InternalFormat &colorFormat,
const gl::InternalFormat &depthStencilFormat,
EGLint sampleCount)
{
const VkPhysicalDeviceProperties &physicalDeviceProperties =
renderer->getPhysicalDeviceProperties();
gl::Version maxSupportedESVersion = renderer->getMaxSupportedESVersion();
EGLint es2Support = (maxSupportedESVersion.major >= 2 ? EGL_OPENGL_ES2_BIT : 0);
EGLint es3Support = (maxSupportedESVersion.major >= 3 ? EGL_OPENGL_ES3_BIT : 0);
egl::Config config;
config.renderTargetFormat = colorFormat.internalFormat;
config.depthStencilFormat = depthStencilFormat.internalFormat;
config.bufferSize = colorFormat.pixelBytes * 8;
config.redSize = colorFormat.redBits;
config.greenSize = colorFormat.greenBits;
config.blueSize = colorFormat.blueBits;
config.alphaSize = colorFormat.alphaBits;
config.alphaMaskSize = 0;
config.bindToTextureRGB = colorFormat.format == GL_RGB;
config.bindToTextureRGBA = colorFormat.format == GL_RGBA || colorFormat.format == GL_BGRA_EXT;
config.colorBufferType = EGL_RGB_BUFFER;
config.configCaveat = GetConfigCaveat(colorFormat.internalFormat);
config.conformant = es2Support | es3Support;
config.depthSize = depthStencilFormat.depthBits;
config.stencilSize = depthStencilFormat.stencilBits;
config.level = 0;
config.matchNativePixmap = EGL_NONE;
config.maxPBufferWidth = physicalDeviceProperties.limits.maxImageDimension2D;
config.maxPBufferHeight = physicalDeviceProperties.limits.maxImageDimension2D;
config.maxPBufferPixels = ComputeMaximumPBufferPixels(physicalDeviceProperties);
config.maxSwapInterval = 1;
config.minSwapInterval = 0;
config.nativeRenderable = EGL_TRUE;
config.nativeVisualID = 0;
config.nativeVisualType = EGL_NONE;
config.renderableType = es2Support | es3Support;
config.sampleBuffers = (sampleCount > 0) ? 1 : 0;
config.samples = sampleCount;
config.surfaceType = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
// Vulkan surfaces use a different origin than OpenGL, always prefer to be flipped vertically if
// possible.
config.optimalOrientation = EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE;
config.transparentType = EGL_NONE;
config.transparentRedValue = 0;
config.transparentGreenValue = 0;
config.transparentBlueValue = 0;
config.colorComponentType =
gl_egl::GLComponentTypeToEGLColorComponentType(colorFormat.componentType);
return config;
}
} // anonymous namespace
egl::ConfigSet GenerateConfigs(const GLenum *colorFormats,
size_t colorFormatsCount,
const GLenum *depthStencilFormats,
size_t depthStencilFormatCount,
DisplayVk *display)
{
ASSERT(colorFormatsCount > 0);
ASSERT(display != nullptr);
gl::SupportedSampleSet colorSampleCounts;
gl::SupportedSampleSet depthStencilSampleCounts;
gl::SupportedSampleSet sampleCounts;
const VkPhysicalDeviceLimits &limits =
display->getRenderer()->getPhysicalDeviceProperties().limits;
const uint32_t depthStencilSampleCountsLimit = limits.framebufferDepthSampleCounts &
limits.framebufferStencilSampleCounts &
vk_gl::kSupportedSampleCounts;
vk_gl::AddSampleCounts(limits.framebufferColorSampleCounts & vk_gl::kSupportedSampleCounts,
&colorSampleCounts);
vk_gl::AddSampleCounts(depthStencilSampleCountsLimit, &depthStencilSampleCounts);
// Always support 0 samples
colorSampleCounts.insert(0);
depthStencilSampleCounts.insert(0);
std::set_intersection(colorSampleCounts.begin(), colorSampleCounts.end(),
depthStencilSampleCounts.begin(), depthStencilSampleCounts.end(),
std::inserter(sampleCounts, sampleCounts.begin()));
egl::ConfigSet configSet;
for (size_t colorFormatIdx = 0; colorFormatIdx < colorFormatsCount; colorFormatIdx++)
{
const gl::InternalFormat &colorFormatInfo =
gl::GetSizedInternalFormatInfo(colorFormats[colorFormatIdx]);
ASSERT(colorFormatInfo.sized);
for (size_t depthStencilFormatIdx = 0; depthStencilFormatIdx < depthStencilFormatCount;
depthStencilFormatIdx++)
{
const gl::InternalFormat &depthStencilFormatInfo =
gl::GetSizedInternalFormatInfo(depthStencilFormats[depthStencilFormatIdx]);
ASSERT(depthStencilFormats[depthStencilFormatIdx] == GL_NONE ||
depthStencilFormatInfo.sized);
const gl::SupportedSampleSet *configSampleCounts = &sampleCounts;
// If there is no depth/stencil buffer, use the color samples set.
if (depthStencilFormats[depthStencilFormatIdx] == GL_NONE)
{
configSampleCounts = &colorSampleCounts;
}
// If there is no color buffer, use the depth/stencil samples set.
else if (colorFormats[colorFormatIdx] == GL_NONE)
{
configSampleCounts = &depthStencilSampleCounts;
}
for (EGLint sampleCount : *configSampleCounts)
{
egl::Config config = GenerateDefaultConfig(display->getRenderer(), colorFormatInfo,
depthStencilFormatInfo, sampleCount);
if (display->checkConfigSupport(&config))
{
configSet.add(config);
}
}
}
}
return configSet;
}
} // namespace egl_vk
} // namespace rx
Vulkan: Avoid INT_MAX resource limits
dEQP queries resource limits in all formats, including float. When
INT_MAX is queried as float, the resulting value is INT_MAX+1 due to
floating point imprecision. dEQP casts this value back to int for
verification, and trips up on the resulting negative number.
This change limits every ridiculously-large limit to INT_MAX/2 instead
of INT_MAX.
Bug: angleproject:4309
Change-Id: I11018c2c5a0c8bfb410928b0a4c34c526fab2269
Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2006813
Commit-Queue: Ian Elliott <ac50c12f27752fd82643b0b72adab33538bb2c97@google.com>
Reviewed-by: Jamie Madill <7e492b4f1c8458024932de3ba475cbf015424c30@chromium.org>
Reviewed-by: Ian Elliott <ac50c12f27752fd82643b0b72adab33538bb2c97@google.com>
//
// Copyright 2018 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// vk_utils:
// Helper functions for the Vulkan Caps.
//
#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
#include <type_traits>
#include "common/utilities.h"
#include "libANGLE/Caps.h"
#include "libANGLE/formatutils.h"
#include "libANGLE/renderer/vulkan/DisplayVk.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
#include "vk_format_utils.h"
namespace
{
constexpr unsigned int kComponentsPerVector = 4;
} // anonymous namespace
namespace rx
{
GLint LimitToInt(const uint32_t physicalDeviceValue)
{
// Limit to INT_MAX / 2 instead of INT_MAX. If the limit is queried as float, the imprecision
// in floating point can cause the value to exceed INT_MAX. This trips dEQP up.
return std::min(physicalDeviceValue,
static_cast<uint32_t>(std::numeric_limits<int32_t>::max() / 2));
}
void RendererVk::ensureCapsInitialized() const
{
if (mCapsInitialized)
return;
mCapsInitialized = true;
ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
const VkQueueFamilyProperties &queueFamilyProperties =
mQueueFamilyProperties[mCurrentQueueFamilyIndex];
const VkPhysicalDeviceLimits &limitsVk = mPhysicalDeviceProperties.limits;
mNativeExtensions.setTextureExtensionSupport(mNativeTextureCaps);
// Vulkan technically only supports the LDR profile but driver all appear to support the HDR
// profile as well. http://anglebug.com/1185#c8
mNativeExtensions.textureCompressionASTCHDRKHR = mNativeExtensions.textureCompressionASTCLDRKHR;
// Enable this for simple buffer readback testing, but some functionality is missing.
// TODO(jmadill): Support full mapBufferRange extension.
mNativeExtensions.mapBuffer = true;
mNativeExtensions.mapBufferRange = true;
mNativeExtensions.textureStorage = true;
mNativeExtensions.drawBuffers = true;
mNativeExtensions.fragDepth = true;
mNativeExtensions.framebufferBlit = true;
mNativeExtensions.framebufferMultisample = true;
mNativeExtensions.copyTexture = true;
mNativeExtensions.copyCompressedTexture = true;
mNativeExtensions.debugMarker = true;
mNativeExtensions.robustness = true;
mNativeExtensions.textureBorderClamp = false; // not implemented yet
mNativeExtensions.translatedShaderSource = true;
mNativeExtensions.discardFramebuffer = true;
// Enable EXT_texture_type_2_10_10_10_REV
mNativeExtensions.textureFormat2101010REV = true;
// Enable ANGLE_base_vertex_base_instance
mNativeExtensions.baseVertexBaseInstance = true;
// Enable OES/EXT_draw_elements_base_vertex
mNativeExtensions.drawElementsBaseVertexOES = true;
mNativeExtensions.drawElementsBaseVertexEXT = true;
// Enable EXT_blend_minmax
mNativeExtensions.blendMinMax = true;
mNativeExtensions.eglImage = true;
mNativeExtensions.eglImageExternal = true;
mNativeExtensions.eglImageExternalEssl3 = true;
mNativeExtensions.memoryObject = true;
mNativeExtensions.memoryObjectFd = getFeatures().supportsExternalMemoryFd.enabled;
mNativeExtensions.semaphore = true;
mNativeExtensions.semaphoreFd = getFeatures().supportsExternalSemaphoreFd.enabled;
mNativeExtensions.vertexHalfFloat = true;
// Enabled in HW if VK_EXT_vertex_attribute_divisor available, otherwise emulated
mNativeExtensions.instancedArraysANGLE = true;
mNativeExtensions.instancedArraysEXT = true;
// Only expose robust buffer access if the physical device supports it.
mNativeExtensions.robustBufferAccessBehavior =
(mPhysicalDeviceFeatures.robustBufferAccess == VK_TRUE);
mNativeExtensions.eglSync = true;
mNativeExtensions.vertexAttribType1010102 = true;
// We use secondary command buffers almost everywhere and they require a feature to be
// able to execute in the presence of queries. As a result, we won't support queries
// unless that feature is available.
mNativeExtensions.occlusionQueryBoolean =
vk::CommandBuffer::SupportsQueries(mPhysicalDeviceFeatures);
// From the Vulkan specs:
// > The number of valid bits in a timestamp value is determined by the
// > VkQueueFamilyProperties::timestampValidBits property of the queue on which the timestamp is
// > written. Timestamps are supported on any queue which reports a non-zero value for
// > timestampValidBits via vkGetPhysicalDeviceQueueFamilyProperties.
mNativeExtensions.disjointTimerQuery = queueFamilyProperties.timestampValidBits > 0;
mNativeExtensions.queryCounterBitsTimeElapsed = queueFamilyProperties.timestampValidBits;
mNativeExtensions.queryCounterBitsTimestamp = queueFamilyProperties.timestampValidBits;
mNativeExtensions.textureFilterAnisotropic =
mPhysicalDeviceFeatures.samplerAnisotropy && limitsVk.maxSamplerAnisotropy > 1.0f;
mNativeExtensions.maxTextureAnisotropy =
mNativeExtensions.textureFilterAnisotropic ? limitsVk.maxSamplerAnisotropy : 0.0f;
// Vulkan natively supports non power-of-two textures
mNativeExtensions.textureNPOT = true;
mNativeExtensions.texture3DOES = true;
// Vulkan natively supports standard derivatives
mNativeExtensions.standardDerivatives = true;
// Vulkan natively supports 32-bit indices, entry in kIndexTypeMap
mNativeExtensions.elementIndexUint = true;
mNativeExtensions.fboRenderMipmap = true;
// We support getting image data for Textures and Renderbuffers.
mNativeExtensions.getImageANGLE = true;
mNativeExtensions.gpuShader5EXT = vk::CanSupportGPUShader5EXT(mPhysicalDeviceFeatures);
// https://vulkan.lunarg.com/doc/view/1.0.30.0/linux/vkspec.chunked/ch31s02.html
mNativeCaps.maxElementIndex = std::numeric_limits<GLuint>::max() - 1;
mNativeCaps.max3DTextureSize = LimitToInt(limitsVk.maxImageDimension3D);
mNativeCaps.max2DTextureSize =
std::min(limitsVk.maxFramebufferWidth, limitsVk.maxImageDimension2D);
mNativeCaps.maxArrayTextureLayers = LimitToInt(limitsVk.maxImageArrayLayers);
mNativeCaps.maxLODBias = limitsVk.maxSamplerLodBias;
mNativeCaps.maxCubeMapTextureSize = LimitToInt(limitsVk.maxImageDimensionCube);
mNativeCaps.maxRenderbufferSize =
std::min({limitsVk.maxImageDimension2D, limitsVk.maxFramebufferWidth,
limitsVk.maxFramebufferHeight});
mNativeCaps.minAliasedPointSize = std::max(1.0f, limitsVk.pointSizeRange[0]);
mNativeCaps.maxAliasedPointSize = limitsVk.pointSizeRange[1];
mNativeCaps.minAliasedLineWidth = 1.0f;
mNativeCaps.maxAliasedLineWidth = 1.0f;
mNativeCaps.maxDrawBuffers =
std::min(limitsVk.maxColorAttachments, limitsVk.maxFragmentOutputAttachments);
mNativeCaps.maxFramebufferWidth = LimitToInt(limitsVk.maxFramebufferWidth);
mNativeCaps.maxFramebufferHeight = LimitToInt(limitsVk.maxFramebufferHeight);
mNativeCaps.maxColorAttachments = LimitToInt(limitsVk.maxColorAttachments);
mNativeCaps.maxViewportWidth = LimitToInt(limitsVk.maxViewportDimensions[0]);
mNativeCaps.maxViewportHeight = LimitToInt(limitsVk.maxViewportDimensions[1]);
mNativeCaps.maxSampleMaskWords = LimitToInt(limitsVk.maxSampleMaskWords);
mNativeCaps.maxColorTextureSamples =
limitsVk.sampledImageColorSampleCounts & vk_gl::kSupportedSampleCounts;
mNativeCaps.maxDepthTextureSamples =
limitsVk.sampledImageDepthSampleCounts & vk_gl::kSupportedSampleCounts;
// TODO (ianelliott): Should mask this with vk_gl::kSupportedSampleCounts, but it causes
// end2end test failures with SwiftShader because SwiftShader returns a sample count of 1 in
// sampledImageIntegerSampleCounts.
// See: http://anglebug.com/4197
mNativeCaps.maxIntegerSamples = limitsVk.sampledImageIntegerSampleCounts;
mNativeCaps.maxVertexAttributes = LimitToInt(limitsVk.maxVertexInputAttributes);
mNativeCaps.maxVertexAttribBindings = LimitToInt(limitsVk.maxVertexInputBindings);
// Offset and stride are stored as uint16_t in PackedAttribDesc.
mNativeCaps.maxVertexAttribRelativeOffset =
std::min(static_cast<uint32_t>(std::numeric_limits<uint16_t>::max()),
limitsVk.maxVertexInputAttributeOffset);
mNativeCaps.maxVertexAttribStride =
std::min(static_cast<uint32_t>(std::numeric_limits<uint16_t>::max()),
limitsVk.maxVertexInputBindingStride);
mNativeCaps.maxElementsIndices = std::numeric_limits<GLint>::max();
mNativeCaps.maxElementsVertices = std::numeric_limits<GLint>::max();
// Looks like all floats are IEEE according to the docs here:
// https://www.khronos.org/registry/vulkan/specs/1.0-wsi_extensions/html/vkspec.html#spirvenv-precision-operation
mNativeCaps.vertexHighpFloat.setIEEEFloat();
mNativeCaps.vertexMediumpFloat.setIEEEFloat();
mNativeCaps.vertexLowpFloat.setIEEEFloat();
mNativeCaps.fragmentHighpFloat.setIEEEFloat();
mNativeCaps.fragmentMediumpFloat.setIEEEFloat();
mNativeCaps.fragmentLowpFloat.setIEEEFloat();
// Can't find documentation on the int precision in Vulkan.
mNativeCaps.vertexHighpInt.setTwosComplementInt(32);
mNativeCaps.vertexMediumpInt.setTwosComplementInt(32);
mNativeCaps.vertexLowpInt.setTwosComplementInt(32);
mNativeCaps.fragmentHighpInt.setTwosComplementInt(32);
mNativeCaps.fragmentMediumpInt.setTwosComplementInt(32);
mNativeCaps.fragmentLowpInt.setTwosComplementInt(32);
// Compute shader limits.
mNativeCaps.maxComputeWorkGroupCount[0] = LimitToInt(limitsVk.maxComputeWorkGroupCount[0]);
mNativeCaps.maxComputeWorkGroupCount[1] = LimitToInt(limitsVk.maxComputeWorkGroupCount[1]);
mNativeCaps.maxComputeWorkGroupCount[2] = LimitToInt(limitsVk.maxComputeWorkGroupCount[2]);
mNativeCaps.maxComputeWorkGroupSize[0] = LimitToInt(limitsVk.maxComputeWorkGroupSize[0]);
mNativeCaps.maxComputeWorkGroupSize[1] = LimitToInt(limitsVk.maxComputeWorkGroupSize[1]);
mNativeCaps.maxComputeWorkGroupSize[2] = LimitToInt(limitsVk.maxComputeWorkGroupSize[2]);
mNativeCaps.maxComputeWorkGroupInvocations =
LimitToInt(limitsVk.maxComputeWorkGroupInvocations);
mNativeCaps.maxComputeSharedMemorySize = LimitToInt(limitsVk.maxComputeSharedMemorySize);
// TODO(lucferron): This is something we'll need to implement custom in the back-end.
// Vulkan doesn't do any waiting for you, our back-end code is going to manage sync objects,
// and we'll have to check that we've exceeded the max wait timeout. Also, this is ES 3.0 so
// we'll defer the implementation until we tackle the next version.
// mNativeCaps.maxServerWaitTimeout
GLuint maxUniformBlockSize = limitsVk.maxUniformBufferRange;
// Clamp the maxUniformBlockSize to 64KB (majority of devices support up to this size
// currently), on AMD the maxUniformBufferRange is near uint32_t max.
maxUniformBlockSize = std::min(0x10000u, maxUniformBlockSize);
const GLuint maxUniformVectors = maxUniformBlockSize / (sizeof(GLfloat) * kComponentsPerVector);
const GLuint maxUniformComponents = maxUniformVectors * kComponentsPerVector;
// Uniforms are implemented using a uniform buffer, so the max number of uniforms we can
// support is the max buffer range divided by the size of a single uniform (4X float).
mNativeCaps.maxVertexUniformVectors = maxUniformVectors;
mNativeCaps.maxFragmentUniformVectors = maxUniformVectors;
mNativeCaps.maxFragmentInputComponents = maxUniformComponents;
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderUniformComponents[shaderType] = maxUniformComponents;
}
mNativeCaps.maxUniformLocations = maxUniformVectors;
// Every stage has 1 reserved uniform buffer for the default uniforms, and 1 for the driver
// uniforms.
constexpr uint32_t kTotalReservedPerStageUniformBuffers =
kReservedDriverUniformBindingCount + kReservedPerStageDefaultUniformBindingCount;
constexpr uint32_t kTotalReservedUniformBuffers =
kReservedDriverUniformBindingCount + kReservedDefaultUniformBindingCount;
const int32_t maxPerStageUniformBuffers = LimitToInt(
limitsVk.maxPerStageDescriptorUniformBuffers - kTotalReservedPerStageUniformBuffers);
const int32_t maxCombinedUniformBuffers =
LimitToInt(limitsVk.maxDescriptorSetUniformBuffers - kTotalReservedUniformBuffers);
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderUniformBlocks[shaderType] = maxPerStageUniformBuffers;
}
mNativeCaps.maxCombinedUniformBlocks = maxCombinedUniformBuffers;
mNativeCaps.maxUniformBufferBindings = maxCombinedUniformBuffers;
mNativeCaps.maxUniformBlockSize = maxUniformBlockSize;
mNativeCaps.uniformBufferOffsetAlignment =
static_cast<GLint>(limitsVk.minUniformBufferOffsetAlignment);
// Note that Vulkan currently implements textures as combined image+samplers, so the limit is
// the minimum of supported samplers and sampled images.
const uint32_t maxPerStageTextures = std::min(limitsVk.maxPerStageDescriptorSamplers,
limitsVk.maxPerStageDescriptorSampledImages);
const uint32_t maxCombinedTextures =
std::min(limitsVk.maxDescriptorSetSamplers, limitsVk.maxDescriptorSetSampledImages);
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderTextureImageUnits[shaderType] = LimitToInt(maxPerStageTextures);
}
mNativeCaps.maxCombinedTextureImageUnits = LimitToInt(maxCombinedTextures);
uint32_t maxPerStageStorageBuffers = limitsVk.maxPerStageDescriptorStorageBuffers;
uint32_t maxVertexStageStorageBuffers = maxPerStageStorageBuffers;
uint32_t maxCombinedStorageBuffers = limitsVk.maxDescriptorSetStorageBuffers;
// A number of storage buffer slots are used in the vertex shader to emulate transform feedback.
// Note that Vulkan requires maxPerStageDescriptorStorageBuffers to be at least 4 (i.e. the same
// as gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS).
// TODO(syoussefi): This should be conditioned to transform feedback extension not being
// present. http://anglebug.com/3206.
// TODO(syoussefi): If geometry shader is supported, emulation will be done at that stage, and
// so the reserved storage buffers should be accounted in that stage. http://anglebug.com/3606
static_assert(
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS == 4,
"Limit to ES2.0 if supported SSBO count < supporting transform feedback buffer count");
if (mPhysicalDeviceFeatures.vertexPipelineStoresAndAtomics)
{
ASSERT(maxVertexStageStorageBuffers >= gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS);
maxVertexStageStorageBuffers -= gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS;
maxCombinedStorageBuffers -= gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS;
// Cap the per-stage limit of the other stages to the combined limit, in case the combined
// limit is now lower than that.
maxPerStageStorageBuffers = std::min(maxPerStageStorageBuffers, maxCombinedStorageBuffers);
}
// Reserve up to IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS storage buffers in the fragment and
// compute stages for atomic counters. This is only possible if the number of per-stage storage
// buffers is greater than 4, which is the required GLES minimum for compute.
//
// For each stage, we'll either not support atomic counter buffers, or support exactly
// IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS. This is due to restrictions in the shader
// translator where we can't know how many atomic counter buffers we would really need after
// linking so we can't create a packed buffer array.
//
// For the vertex stage, we could support atomic counters without storage buffers, but that's
// likely not very useful, so we use the same limit (4 + MAX_ATOMIC_COUNTER_BUFFERS) for the
// vertex stage to determine if we would want to add support for atomic counter buffers.
constexpr uint32_t kMinimumStorageBuffersForAtomicCounterBufferSupport =
gl::limits::kMinimumComputeStorageBuffers + gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
uint32_t maxVertexStageAtomicCounterBuffers = 0;
uint32_t maxPerStageAtomicCounterBuffers = 0;
uint32_t maxCombinedAtomicCounterBuffers = 0;
if (maxPerStageStorageBuffers >= kMinimumStorageBuffersForAtomicCounterBufferSupport)
{
maxPerStageAtomicCounterBuffers = gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
maxCombinedAtomicCounterBuffers = gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
}
if (maxVertexStageStorageBuffers >= kMinimumStorageBuffersForAtomicCounterBufferSupport)
{
maxVertexStageAtomicCounterBuffers = gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFERS;
}
maxVertexStageStorageBuffers -= maxVertexStageAtomicCounterBuffers;
maxPerStageStorageBuffers -= maxPerStageAtomicCounterBuffers;
maxCombinedStorageBuffers -= maxCombinedAtomicCounterBuffers;
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Vertex] =
mPhysicalDeviceFeatures.vertexPipelineStoresAndAtomics
? LimitToInt(maxVertexStageStorageBuffers)
: 0;
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Fragment] =
mPhysicalDeviceFeatures.fragmentStoresAndAtomics ? LimitToInt(maxPerStageStorageBuffers)
: 0;
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Compute] =
LimitToInt(maxPerStageStorageBuffers);
mNativeCaps.maxCombinedShaderStorageBlocks = LimitToInt(maxCombinedStorageBuffers);
mNativeCaps.maxShaderStorageBufferBindings = LimitToInt(maxCombinedStorageBuffers);
mNativeCaps.maxShaderStorageBlockSize = limitsVk.maxStorageBufferRange;
mNativeCaps.shaderStorageBufferOffsetAlignment =
LimitToInt(static_cast<uint32_t>(limitsVk.minStorageBufferOffsetAlignment));
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Vertex] =
mPhysicalDeviceFeatures.vertexPipelineStoresAndAtomics
? LimitToInt(maxVertexStageAtomicCounterBuffers)
: 0;
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Fragment] =
mPhysicalDeviceFeatures.fragmentStoresAndAtomics
? LimitToInt(maxPerStageAtomicCounterBuffers)
: 0;
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Compute] =
LimitToInt(maxPerStageAtomicCounterBuffers);
mNativeCaps.maxCombinedAtomicCounterBuffers = LimitToInt(maxCombinedAtomicCounterBuffers);
mNativeCaps.maxAtomicCounterBufferBindings = LimitToInt(maxCombinedAtomicCounterBuffers);
// Emulated as storage buffers, atomic counter buffers have the same size limit. However, the
// limit is a signed integer and values above int max will end up as a negative size.
mNativeCaps.maxAtomicCounterBufferSize = LimitToInt(limitsVk.maxStorageBufferRange);
// There is no particular limit to how many atomic counters there can be, other than the size of
// a storage buffer. We nevertheless limit this to something sane (4096 arbitrarily).
const int32_t maxAtomicCounters =
std::min<int32_t>(4096, limitsVk.maxStorageBufferRange / sizeof(uint32_t));
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderAtomicCounters[shaderType] = maxAtomicCounters;
}
mNativeCaps.maxCombinedAtomicCounters = maxAtomicCounters;
// GL Images correspond to Vulkan Storage Images.
const int32_t maxPerStageImages = LimitToInt(limitsVk.maxPerStageDescriptorStorageImages);
const int32_t maxCombinedImages = LimitToInt(limitsVk.maxDescriptorSetStorageImages);
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxShaderImageUniforms[shaderType] = maxPerStageImages;
}
mNativeCaps.maxCombinedImageUniforms = maxCombinedImages;
mNativeCaps.maxImageUnits = maxCombinedImages;
mNativeCaps.minProgramTexelOffset = limitsVk.minTexelOffset;
mNativeCaps.maxProgramTexelOffset = limitsVk.maxTexelOffset;
mNativeCaps.minProgramTextureGatherOffset = limitsVk.minTexelGatherOffset;
mNativeCaps.maxProgramTextureGatherOffset = limitsVk.maxTexelGatherOffset;
// There is no additional limit to the combined number of components. We can have up to a
// maximum number of uniform buffers, each having the maximum number of components. Note that
// this limit includes both components in and out of uniform buffers.
const uint32_t maxCombinedUniformComponents =
(maxPerStageUniformBuffers + kReservedPerStageDefaultUniformBindingCount) *
maxUniformComponents;
for (gl::ShaderType shaderType : gl::AllShaderTypes())
{
mNativeCaps.maxCombinedShaderUniformComponents[shaderType] = maxCombinedUniformComponents;
}
// Total number of resources available to the user are as many as Vulkan allows minus everything
// that ANGLE uses internally. That is, one dynamic uniform buffer used per stage for default
// uniforms and a single dynamic uniform buffer for driver uniforms. Additionally, Vulkan uses
// up to IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS + 1 buffers for transform feedback (Note:
// +1 is for the "counter" buffer of transform feedback, which will be necessary for transform
// feedback extension and ES3.2 transform feedback emulation, but is not yet present).
constexpr uint32_t kReservedPerStageUniformBufferCount = 1;
constexpr uint32_t kReservedPerStageBindingCount =
kReservedDriverUniformBindingCount + kReservedPerStageUniformBufferCount +
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_BUFFERS + 1;
// Note: maxPerStageResources is required to be at least the sum of per stage UBOs, SSBOs etc
// which total a minimum of 44 resources, so no underflow is possible here. Limit the total
// number of resources reported by Vulkan to 2 billion though to avoid seeing negative numbers
// in applications that take the value as signed int (including dEQP).
const uint32_t maxPerStageResources = limitsVk.maxPerStageResources;
mNativeCaps.maxCombinedShaderOutputResources =
LimitToInt(maxPerStageResources - kReservedPerStageBindingCount);
// The max vertex output components should not include gl_Position.
// The gles2.0 section 2.10 states that "gl_Position is not a varying variable and does
// not count against this limit.", but the Vulkan spec has no such mention in its Built-in
// vars section. It is implicit that we need to actually reserve it for Vulkan in that case.
GLint reservedVaryingVectorCount = 1;
mNativeCaps.maxVaryingVectors = LimitToInt(
(limitsVk.maxVertexOutputComponents / kComponentsPerVector) - reservedVaryingVectorCount);
mNativeCaps.maxVertexOutputComponents = LimitToInt(limitsVk.maxVertexOutputComponents);
mNativeCaps.maxTransformFeedbackInterleavedComponents =
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS;
mNativeCaps.maxTransformFeedbackSeparateAttributes =
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
mNativeCaps.maxTransformFeedbackSeparateComponents =
gl::IMPLEMENTATION_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS;
mNativeCaps.minProgramTexelOffset = limitsVk.minTexelOffset;
mNativeCaps.maxProgramTexelOffset = LimitToInt(limitsVk.maxTexelOffset);
const uint32_t sampleCounts =
limitsVk.framebufferColorSampleCounts & limitsVk.framebufferDepthSampleCounts &
limitsVk.framebufferStencilSampleCounts & vk_gl::kSupportedSampleCounts;
mNativeCaps.maxSamples = LimitToInt(vk_gl::GetMaxSampleCount(sampleCounts));
mNativeCaps.maxFramebufferSamples = mNativeCaps.maxSamples;
mNativeCaps.subPixelBits = limitsVk.subPixelPrecisionBits;
// Enable Program Binary extension.
mNativeExtensions.getProgramBinary = true;
mNativeCaps.programBinaryFormats.push_back(GL_PROGRAM_BINARY_ANGLE);
// Enable GL_NV_pixel_buffer_object extension.
mNativeExtensions.pixelBufferObject = true;
// Geometry shader is optional.
if (mPhysicalDeviceFeatures.geometryShader)
{
// TODO : Remove below comment when http://anglebug.com/3571 will be completed
// mNativeExtensions.geometryShader = true;
mNativeCaps.maxFramebufferLayers = LimitToInt(limitsVk.maxFramebufferLayers);
mNativeCaps.layerProvokingVertex = GL_LAST_VERTEX_CONVENTION_EXT;
mNativeCaps.maxGeometryInputComponents = LimitToInt(limitsVk.maxGeometryInputComponents);
mNativeCaps.maxGeometryOutputComponents = LimitToInt(limitsVk.maxGeometryOutputComponents);
mNativeCaps.maxGeometryOutputVertices = LimitToInt(limitsVk.maxGeometryOutputVertices);
mNativeCaps.maxGeometryTotalOutputComponents =
LimitToInt(limitsVk.maxGeometryTotalOutputComponents);
mNativeCaps.maxShaderStorageBlocks[gl::ShaderType::Geometry] =
mNativeCaps.maxCombinedShaderOutputResources;
mNativeCaps.maxShaderAtomicCounterBuffers[gl::ShaderType::Geometry] =
maxCombinedAtomicCounterBuffers;
mNativeCaps.maxGeometryShaderInvocations =
LimitToInt(limitsVk.maxGeometryShaderInvocations);
}
}
namespace vk
{
bool CanSupportGPUShader5EXT(const VkPhysicalDeviceFeatures &features)
{
// We use the following Vulkan features to implement EXT_gpu_shader5:
// - shaderImageGatherExtended: textureGatherOffset with non-constant offset and
// textureGatherOffsets family of functions.
// - shaderSampledImageArrayDynamicIndexing and shaderUniformBufferArrayDynamicIndexing:
// dynamically uniform indices for samplers and uniform buffers.
// - shaderStorageBufferArrayDynamicIndexing: While EXT_gpu_shader5 doesn't require dynamically
// uniform indices on storage buffers, we need it as we emulate atomic counter buffers with
// storage buffers (and atomic counter buffers *can* be indexed in that way).
return features.shaderImageGatherExtended && features.shaderSampledImageArrayDynamicIndexing &&
features.shaderUniformBufferArrayDynamicIndexing &&
features.shaderStorageBufferArrayDynamicIndexing;
}
} // namespace vk
namespace egl_vk
{
namespace
{
EGLint ComputeMaximumPBufferPixels(const VkPhysicalDeviceProperties &physicalDeviceProperties)
{
// EGLints are signed 32-bit integers, it's fairly easy to overflow them, especially since
// Vulkan's minimum guaranteed VkImageFormatProperties::maxResourceSize is 2^31 bytes.
constexpr uint64_t kMaxValueForEGLint =
static_cast<uint64_t>(std::numeric_limits<EGLint>::max());
// TODO(geofflang): Compute the maximum size of a pbuffer by using the maxResourceSize result
// from vkGetPhysicalDeviceImageFormatProperties for both the color and depth stencil format and
// the exact image creation parameters that would be used to create the pbuffer. Because it is
// always safe to return out-of-memory errors on pbuffer allocation, it's fine to simply return
// the number of pixels in a max width by max height pbuffer for now. http://anglebug.com/2622
// Storing the result of squaring a 32-bit unsigned int in a 64-bit unsigned int is safe.
static_assert(std::is_same<decltype(physicalDeviceProperties.limits.maxImageDimension2D),
uint32_t>::value,
"physicalDeviceProperties.limits.maxImageDimension2D expected to be a uint32_t.");
const uint64_t maxDimensionsSquared =
static_cast<uint64_t>(physicalDeviceProperties.limits.maxImageDimension2D) *
static_cast<uint64_t>(physicalDeviceProperties.limits.maxImageDimension2D);
return static_cast<EGLint>(std::min(maxDimensionsSquared, kMaxValueForEGLint));
}
// Generates a basic config for a combination of color format, depth stencil format and sample
// count.
egl::Config GenerateDefaultConfig(const RendererVk *renderer,
const gl::InternalFormat &colorFormat,
const gl::InternalFormat &depthStencilFormat,
EGLint sampleCount)
{
const VkPhysicalDeviceProperties &physicalDeviceProperties =
renderer->getPhysicalDeviceProperties();
gl::Version maxSupportedESVersion = renderer->getMaxSupportedESVersion();
EGLint es2Support = (maxSupportedESVersion.major >= 2 ? EGL_OPENGL_ES2_BIT : 0);
EGLint es3Support = (maxSupportedESVersion.major >= 3 ? EGL_OPENGL_ES3_BIT : 0);
egl::Config config;
config.renderTargetFormat = colorFormat.internalFormat;
config.depthStencilFormat = depthStencilFormat.internalFormat;
config.bufferSize = colorFormat.pixelBytes * 8;
config.redSize = colorFormat.redBits;
config.greenSize = colorFormat.greenBits;
config.blueSize = colorFormat.blueBits;
config.alphaSize = colorFormat.alphaBits;
config.alphaMaskSize = 0;
config.bindToTextureRGB = colorFormat.format == GL_RGB;
config.bindToTextureRGBA = colorFormat.format == GL_RGBA || colorFormat.format == GL_BGRA_EXT;
config.colorBufferType = EGL_RGB_BUFFER;
config.configCaveat = GetConfigCaveat(colorFormat.internalFormat);
config.conformant = es2Support | es3Support;
config.depthSize = depthStencilFormat.depthBits;
config.stencilSize = depthStencilFormat.stencilBits;
config.level = 0;
config.matchNativePixmap = EGL_NONE;
config.maxPBufferWidth = physicalDeviceProperties.limits.maxImageDimension2D;
config.maxPBufferHeight = physicalDeviceProperties.limits.maxImageDimension2D;
config.maxPBufferPixels = ComputeMaximumPBufferPixels(physicalDeviceProperties);
config.maxSwapInterval = 1;
config.minSwapInterval = 0;
config.nativeRenderable = EGL_TRUE;
config.nativeVisualID = 0;
config.nativeVisualType = EGL_NONE;
config.renderableType = es2Support | es3Support;
config.sampleBuffers = (sampleCount > 0) ? 1 : 0;
config.samples = sampleCount;
config.surfaceType = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
// Vulkan surfaces use a different origin than OpenGL, always prefer to be flipped vertically if
// possible.
config.optimalOrientation = EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE;
config.transparentType = EGL_NONE;
config.transparentRedValue = 0;
config.transparentGreenValue = 0;
config.transparentBlueValue = 0;
config.colorComponentType =
gl_egl::GLComponentTypeToEGLColorComponentType(colorFormat.componentType);
return config;
}
} // anonymous namespace
egl::ConfigSet GenerateConfigs(const GLenum *colorFormats,
size_t colorFormatsCount,
const GLenum *depthStencilFormats,
size_t depthStencilFormatCount,
DisplayVk *display)
{
ASSERT(colorFormatsCount > 0);
ASSERT(display != nullptr);
gl::SupportedSampleSet colorSampleCounts;
gl::SupportedSampleSet depthStencilSampleCounts;
gl::SupportedSampleSet sampleCounts;
const VkPhysicalDeviceLimits &limits =
display->getRenderer()->getPhysicalDeviceProperties().limits;
const uint32_t depthStencilSampleCountsLimit = limits.framebufferDepthSampleCounts &
limits.framebufferStencilSampleCounts &
vk_gl::kSupportedSampleCounts;
vk_gl::AddSampleCounts(limits.framebufferColorSampleCounts & vk_gl::kSupportedSampleCounts,
&colorSampleCounts);
vk_gl::AddSampleCounts(depthStencilSampleCountsLimit, &depthStencilSampleCounts);
// Always support 0 samples
colorSampleCounts.insert(0);
depthStencilSampleCounts.insert(0);
std::set_intersection(colorSampleCounts.begin(), colorSampleCounts.end(),
depthStencilSampleCounts.begin(), depthStencilSampleCounts.end(),
std::inserter(sampleCounts, sampleCounts.begin()));
egl::ConfigSet configSet;
for (size_t colorFormatIdx = 0; colorFormatIdx < colorFormatsCount; colorFormatIdx++)
{
const gl::InternalFormat &colorFormatInfo =
gl::GetSizedInternalFormatInfo(colorFormats[colorFormatIdx]);
ASSERT(colorFormatInfo.sized);
for (size_t depthStencilFormatIdx = 0; depthStencilFormatIdx < depthStencilFormatCount;
depthStencilFormatIdx++)
{
const gl::InternalFormat &depthStencilFormatInfo =
gl::GetSizedInternalFormatInfo(depthStencilFormats[depthStencilFormatIdx]);
ASSERT(depthStencilFormats[depthStencilFormatIdx] == GL_NONE ||
depthStencilFormatInfo.sized);
const gl::SupportedSampleSet *configSampleCounts = &sampleCounts;
// If there is no depth/stencil buffer, use the color samples set.
if (depthStencilFormats[depthStencilFormatIdx] == GL_NONE)
{
configSampleCounts = &colorSampleCounts;
}
// If there is no color buffer, use the depth/stencil samples set.
else if (colorFormats[colorFormatIdx] == GL_NONE)
{
configSampleCounts = &depthStencilSampleCounts;
}
for (EGLint sampleCount : *configSampleCounts)
{
egl::Config config = GenerateDefaultConfig(display->getRenderer(), colorFormatInfo,
depthStencilFormatInfo, sampleCount);
if (display->checkConfigSupport(&config))
{
configSet.add(config);
}
}
}
}
return configSet;
}
} // namespace egl_vk
} // namespace rx
|
#include <TSystem.h>
#include <TFile.h>
#include <TStyle.h>
#include <TTree.h>
#include <TClonesArray.h>
#include <TObjArray.h>
#include <TH2F.h>
#include <TCanvas.h>
#include <AliHMPIDHit.h>
#include <AliHMPIDCluster.h>
#include <AliHMPIDDigit.h>
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TObjArray *CreateContainer(const char *classname,TTree *pTree)
{
TObjArray *pOA=new TObjArray(7); pOA->SetOwner();
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){
TClonesArray *pCA=new TClonesArray(classname);
pOA->AddAt(pCA,iCh);
pTree->SetBranchAddress(Form("HMPID%i",iCh),&pCA);
}
return pOA;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TH1F *hHitQdc; TH2F *hHitMap[7];
void Hits(Int_t mode,TTree *pTree=0x0)
{
switch(mode){
case 1:
hHitQdc=new TH1F("HitQdc","Hit Qdc all chamber;QDC",500,0,4000);
for(Int_t iCh=0;iCh<7;iCh++) hHitMap[iCh]=new TH2F(Form("HitMap%i",iCh),Form("Ch%i;x_{Hit};y_{Hit}",iCh),160,0,160,160,0,160);
break;
case 2:
if(pTree==0) return;
TClonesArray *pHits=new TClonesArray("AliHMPIDHit"); pTree->SetBranchAddress("HMPID",&pHits);
for(Int_t iEnt=0;iEnt<pTree->GetEntriesFast();iEnt++){//entries loop
pTree->GetEntry(iEnt);
for(Int_t iHit=0;iHit<pHits->GetEntriesFast();iHit++){//hits loop
AliHMPIDHit *pHit = (AliHMPIDHit*)pHits->UncheckedAt(iHit);
hHitMap[pHit->Ch()]->Fill(pHit->LorsX(),pHit->LorsY());
hHitQdc->Fill(pHit->Q());
}//hits loop
}//entries loop
delete pHits;
break;
case 3:
TCanvas *c1=new TCanvas("HitCan","Hits",1280,800); c1->Divide(3,3);
for(Int_t iCh=0;iCh<7;iCh++){
if(iCh==6) c1->cd(1); if(iCh==5) c1->cd(2);
if(iCh==4) c1->cd(4); if(iCh==3) c1->cd(5); if(iCh==2) c1->cd(6);
if(iCh==1) c1->cd(8); if(iCh==0) c1->cd(9);
gStyle->SetPalette(1);
hHitMap[iCh]->Draw("colz");
}
c1->cd(3); gPad->SetLogy(); hHitQdc->SetFillColor(5);hHitQdc->Draw();
break;
}
}//Hits()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TH1F *hCluEvt,*hCluChi2,*hCluFlg,*hCluSize;
void Clus(Int_t mode, TTree *pTree=0x0)
{
switch(mode){
case 1:
hCluEvt=new TH1F("CluPerEvt","# clusters per event",21,-0.5,20.5);
hCluChi2 =new TH1F("CluChi2" ,"Chi2 " ,1000,0,100);
hCluFlg =new TH1F("CluFlg" ,"Cluster flag" ,14,-1.5,12.5); hCluFlg->SetFillColor(5);
hCluSize =new TH1F("CluSize" ,"Raw cluster size ",100,0,100);
break;
case 2:
if(pTree==0) return;
TObjArray *pLst=CreateContainer("AliHMPIDCluster",pTree); pTree->GetEntry(0);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){//chambers loop
TClonesArray *pClus=(TClonesArray *)pLst->UncheckedAt(iCh);
hCluEvt->Fill(pClus->GetEntriesFast());
for(Int_t iClu=0;iClu<pClus->GetEntriesFast();iClu++){//clusters loop
AliHMPIDCluster *pClu=(AliHMPIDCluster*)pClus->UncheckedAt(iClu);
hCluFlg->Fill(pClu->Status()); hCluChi2->Fill(pClu->Chi2()); hCluSize->Fill(pClu->Size());
}
}
delete pLst;
break;
case 3:
TCanvas *c1=new TCanvas("CluComCan","Clusters in common",1280,800); c1->Divide(3,3);
c1->cd(1); hCluEvt->SetFillColor(5); hCluEvt->Draw();
c1->cd(2); hCluChi2->SetFillColor(5); hCluChi2->Draw();
c1->cd(3); hCluFlg->SetFillColor(5); hCluFlg->Draw();
c1->cd(4); hCluSize->SetFillColor(5); hCluSize->Draw();
break;
}//switch
}//Clus()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TH1F *hDigPcEvt,*hDigQ, *hDigChEvt;
void Digs(Int_t mode, TTree *pTree=0x0)
{
switch(mode){
case 1:
hDigPcEvt=new TH1F("hDigPcEvt","PC occupancy per event",156,-1,77);
hDigChEvt=new TH1F("hDigChEvt","Chamber occupancy per event",32,-1,7);
hDigQ =new TH1F("Q ","Q ",3000,0,3000);
break;
case 2:
if(pTree==0) return;
TObjArray *pLst=CreateContainer("AliHMPIDDigit",pTree); pTree->GetEntry(0);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){//chambers loop
TClonesArray *pDigs=(TClonesArray *)pLst->UncheckedAt(iCh);
hDigChEvt->Fill(iCh,pDigs->GetEntriesFast()/(48.*80.*6.));
for(Int_t iDig=0;iDig<pDigs->GetEntriesFast();iDig++){//digits loop
AliHMPIDDigit *pDig=(AliHMPIDDigit*)pDigs->UncheckedAt(iDig);
hDigPcEvt->Fill(10.*iCh+pDig->Pc(),1./(48.*80.));
hDigQ->Fill(pDig->Q());
}
}
delete pLst;
break;
case 3:
TCanvas *c1=new TCanvas("DigQa","Digit Check",1280,800); c1->Divide(2,2);
c1->cd(1); hDigPcEvt->Draw(); c1->cd(2); hDigQ->Draw(); c1->cd(3); hDigChEvt->Draw();
break;
}//switch
}//Dig()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void Hqa()
{
TFile *fh=0; if(gSystem->IsFileInIncludePath("HMPID.Hits.root")) fh=TFile::Open("HMPID.Hits.root" ,"read");if(fh->IsZombie()) fh=0;
TFile *fd=0; if(gSystem->IsFileInIncludePath("HMPID.Digits.root")) fd=TFile::Open("HMPID.Digits.root" ,"read");if(fd->IsZombie()) fd=0;
TFile *fc=0; if(gSystem->IsFileInIncludePath("HMPID.RecPoints.root")) fc=TFile::Open("HMPID.RecPoints.root","read");if(fc->IsZombie()) fc=0;
if(fh==0 && fd==0 && fc==0){Printf("Nothing to do!"); return;}
if(fh) Hits(1); if(fc) Clus(1); if(fd) Digs(1);//book
Int_t iEvt=0;
while(1){
TTree *th=0; if(fh) th=(TTree*)fh->Get(Form("Event%i/TreeH",iEvt));
TTree *td=0; if(fd) td=(TTree*)fd->Get(Form("Event%i/TreeD",iEvt));
TTree *tc=0; if(fc) tc=(TTree*)fc->Get(Form("Event%i/TreeR",iEvt));
Hits(2,th); Clus(2,tc); Digs(2,td);//fill
if(th==0 && td==0 && tc==0) break;
iEvt++;
Printf("Event %i processed",iEvt);
}
if(fh) Hits(3);
if(fc) Clus(3);
if(fd) Digs(3);//plot
}
More checks
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TSystem.h>
#include <TFile.h>
#include <TStyle.h>
#include <TTree.h>
#include <TClonesArray.h>
#include <TObjArray.h>
#include <TF1.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TProfile.h>
#include <TCanvas.h>
#include <AliHMPIDParam.h>
#include <AliHMPIDHit.h>
#include <AliHMPIDCluster.h>
#include <AliHMPIDDigit.h>
#endif
Int_t nEntries = 0;
TObjArray *CreateContainer(const char *classname,TTree *pTree);
void Hits(Int_t mode,TTree *pTree=0x0);
void Digs(Int_t mode, TTree *pTree=0x0);
void Clus(Int_t mode, TTree *pTree=0x0);
void Summary();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TObjArray *CreateContainer(const char *classname,TTree *pTree)
{
TObjArray *pOA=new TObjArray(AliHMPIDParam::kMaxCh+1);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){
TClonesArray *pCA=new TClonesArray(classname);
pOA->AddAt(pCA,iCh);
}
pOA->SetOwner(kTRUE);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){
pTree->SetBranchAddress(Form("HMPID%i",iCh),&(*pOA)[iCh]);
}
return pOA;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TH1F *hHitQdc,*hHitQdcCh[AliHMPIDParam::kMaxCh+1]; TH2F *hHitMap[AliHMPIDParam::kMaxCh+1];
Double_t fHitMean[AliHMPIDParam::kMaxCh+1],fHitErr[AliHMPIDParam::kMaxCh+1];
void Hits(Int_t mode,TTree *pTree)
{
switch(mode){
case 1:
hHitQdc=new TH1F("HitQdc","Hit Qdc all chamber;QDC",4000,0,4000);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){
hHitMap[iCh]=new TH2F(Form("HitMap%i",iCh),Form("Ch%i;x_{Hit};y_{Hit}",iCh),160,0,160,160,0,160);
hHitQdcCh[iCh]=new TH1F(Form("HMPID%i",iCh),Form("Charge for HMPID%i",iCh),4000,0,4000);
}
break;
case 2:
if(pTree==0) return;
TClonesArray *pHits=new TClonesArray("AliHMPIDHit"); pTree->SetBranchAddress("HMPID",&pHits);
for(Int_t iEnt=0;iEnt<pTree->GetEntriesFast();iEnt++){//entries loop
pTree->GetEntry(iEnt);
for(Int_t iHit=0;iHit<pHits->GetEntriesFast();iHit++){//hits loop
AliHMPIDHit *pHit = (AliHMPIDHit*)pHits->UncheckedAt(iHit);
hHitMap[pHit->Ch()]->Fill(pHit->LorsX(),pHit->LorsY());
hHitQdc->Fill(pHit->Q());
hHitQdcCh[pHit->Ch()]->Fill(pHit->Q());
}//hits loop
}//entries loop
delete pHits;
break;
case 3:
TCanvas *c1=new TCanvas("HitCan","Hits",1280,800); c1->Divide(3,3);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){
if(iCh==6) c1->cd(1); if(iCh==5) c1->cd(2);
if(iCh==4) c1->cd(4); if(iCh==3) c1->cd(5); if(iCh==2) c1->cd(6);
if(iCh==1) c1->cd(8); if(iCh==0) c1->cd(9);
gStyle->SetPalette(1);
hHitMap[iCh]->Draw("colz");
}
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){
fHitMean[iCh] = 0;
fHitErr[iCh] = 0;
if((Int_t)hHitQdcCh[iCh]->GetEntries()<nEntries) continue;
c1->cd(3);hHitQdcCh[iCh]->Fit("expo","Q");
TF1 *funcfit = (TF1*)hHitQdcCh[iCh]->FindObject("expo");
fHitMean[iCh] = funcfit->GetParameter(1);
fHitErr[iCh] = funcfit->GetParError(1);
}
TPad *pad = (TPad*)c1->cd(3); hHitQdc->SetFillColor(5); pad->SetLogy(); hHitQdc->Fit("expo","Q");
break;
}
}//Hits()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TH1F *hDigQ;
TProfile *hDigHighQ,*hDigChEvt;
void Digs(Int_t mode, TTree *pTree)
{
switch(mode){
case 1:
hDigHighQ=new TProfile("hDigHighQ","Highest charge in chamber ",AliHMPIDParam::kMaxCh+1,AliHMPIDParam::kMinCh,AliHMPIDParam::kMaxCh+1);
hDigChEvt=new TProfile("hDigChEvt","Chamber occupancy per event",AliHMPIDParam::kMaxCh+1,AliHMPIDParam::kMinCh,AliHMPIDParam::kMaxCh+1);
hDigQ =new TH1F("hDigQ ","Charge of digits (ADC) ",3000,0,3000);
break;
case 2:
if(pTree==0) return;
TObjArray *pLst=CreateContainer("AliHMPIDDigit",pTree); pTree->GetEntry(0);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){//chambers loop
TClonesArray *pDigs=(TClonesArray *)pLst->UncheckedAt(iCh);
hDigChEvt->Fill(iCh,pDigs->GetEntriesFast()/(48.*80.*6.)*100.);
Double_t highQ = 0;
for(Int_t iDig=0;iDig<pDigs->GetEntriesFast();iDig++){//digits loop
AliHMPIDDigit *pDig=(AliHMPIDDigit*)pDigs->UncheckedAt(iDig);
hDigQ->Fill(pDig->Q());
if(pDig->Q()>highQ) highQ = pDig->Q();
}
hDigHighQ->Fill(iCh,highQ);
}
delete pLst;
break;
case 3:
TCanvas *c1=new TCanvas("DigQa","Digit Check",1280,800); c1->Divide(2,2);
gStyle->SetOptFit(1);
TPad *pad = (TPad*)c1->cd(1); pad->SetLogy(); hDigQ->Fit("expo","QN");
c1->cd(2); hDigHighQ->Draw();
c1->cd(3); hDigChEvt->Draw();
break;
}//switch
}//Dig()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TH1F *hCluEvt,*hCluChi2,*hCluFlg,*hCluSize,*hCluQ;
void Clus(Int_t mode, TTree *pTree)
{
switch(mode){
case 1:
hCluEvt=new TH1F("CluPerEvt","Cluster multiplicity" ,100,0,100);
hCluChi2 =new TH1F("CluChi2" ,"Chi2 " ,1000,0,100);
hCluFlg =new TH1F("CluFlg" ,"Cluster flag" ,14,-1.5,12.5); hCluFlg->SetFillColor(5);
hCluSize =new TH1F("CluSize" ,"Cluster size ",100,0,100);
hCluQ =new TH1F("CluQ" ,"Cluster charge (ADC)",1000,0,5000);
break;
case 2:
if(pTree==0) return;
TObjArray *pLst=CreateContainer("AliHMPIDCluster",pTree); pTree->GetEntry(0);
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){//chambers loop
TClonesArray *pClus=(TClonesArray *)pLst->UncheckedAt(iCh);
hCluEvt->Fill(pClus->GetEntriesFast());
for(Int_t iClu=0;iClu<pClus->GetEntriesFast();iClu++){//clusters loop
AliHMPIDCluster *pClu=(AliHMPIDCluster*)pClus->UncheckedAt(iClu);
hCluFlg->Fill(pClu->Status());
hCluChi2->Fill(pClu->Chi2());
hCluSize->Fill(pClu->Size());
hCluQ->Fill(pClu->Q());
}
}
delete pLst;
break;
case 3:
TCanvas *c1=new TCanvas("CluComCan","Clusters in common",1280,800); c1->Divide(3,3);
c1->cd(1); hCluEvt->SetFillColor(5); hCluEvt->Draw();
c1->cd(2); hCluChi2->SetFillColor(5); hCluChi2->Draw();
c1->cd(3); hCluFlg->SetFillColor(5); hCluFlg->Draw();
c1->cd(4); hCluSize->SetFillColor(5); hCluSize->Draw();
TPad *pad = (TPad*)c1->cd(5); hCluQ->SetFillColor(5); pad->SetLogy(); hCluQ->Draw();
break;
}//switch
}//Clus()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void Hqa()
{
TFile *fh=0; if(gSystem->IsFileInIncludePath("HMPID.Hits.root")) fh=TFile::Open("HMPID.Hits.root" ,"read");if(fh->IsZombie()) fh=0;
TFile *fd=0; if(gSystem->IsFileInIncludePath("HMPID.Digits.root")) fd=TFile::Open("HMPID.Digits.root" ,"read");if(fd->IsZombie()) fd=0;
TFile *fc=0; if(gSystem->IsFileInIncludePath("HMPID.RecPoints.root")) fc=TFile::Open("HMPID.RecPoints.root","read");if(fc->IsZombie()) fc=0;
if(fh==0 && fd==0 && fc==0){Printf("Nothing to do!"); return;}
if(fh) Hits(1); if(fc) Clus(1); if(fd) Digs(1);//book
Int_t iEvt=0;
while(1){
TTree *th=0; if(fh) th=(TTree*)fh->Get(Form("Event%i/TreeH",iEvt));
TTree *td=0; if(fd) td=(TTree*)fd->Get(Form("Event%i/TreeD",iEvt));
TTree *tc=0; if(fc) tc=(TTree*)fc->Get(Form("Event%i/TreeR",iEvt));
Hits(2,th); Digs(2,td); Clus(2,tc); //fill
if(th==0 && td==0 && tc==0) break;
iEvt++;
if(!(iEvt%50)) Printf("Event %i processed",iEvt);
}
nEntries = iEvt;
if(fd) Clus(3);//plot everything
if(fc) Digs(3);
if(fh) Hits(3);
Summary();
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void Summary()
{
//info for hits...
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){
Printf(" #################### Summary for HMPID %i#################### ",iCh);
//info for hits...
Printf("-----Summary of Hits----- ");
if(fHitMean[iCh]==0) {
Printf("gain %5.2f +/- %5.2f",fHitMean[iCh],fHitErr[iCh]);
} else {
Double_t gain = 1./TMath::Abs(fHitMean[iCh]);
Double_t errgain = gain*gain*fHitErr[iCh];
Printf("gain %5.2f +/- %5.2f",gain,errgain);
}
//info for digits...
Printf("-----Summary of Digits-----");
Printf(" Chamber %d with occupancy (%) %5.2f +/- %5.2f",iCh,hDigChEvt->GetBinContent(iCh+1),hDigChEvt->GetBinError(iCh+1));
Printf(" Chamber %d with higest Q (ADC) %7.0f +/- %7.0f",iCh,hDigHighQ->GetBinContent(iCh+1),hDigHighQ->GetBinError(iCh+1));
}
}
|
/* -*- c++ -*-
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2020 Alberto Gonzalez <boqwxp@airmail.cc>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/consteval.h"
#include "qbfsat.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
static inline unsigned int difference(unsigned int a, unsigned int b) {
if (a < b)
return b - a;
else
return a - b;
}
pool<std::string> validate_design_and_get_inputs(RTLIL::Module *module, bool assume_outputs) {
bool found_input = false;
bool found_hole = false;
bool found_1bit_output = false;
bool found_assert_assume = false;
pool<std::string> input_wires;
for (auto wire : module->wires()) {
if (wire->port_input) {
found_input = true;
input_wires.insert(wire->name.str());
}
if (wire->port_output && wire->width == 1)
found_1bit_output = true;
}
for (auto cell : module->cells()) {
if (cell->type == "$allconst")
found_input = true;
if (cell->type == "$anyconst")
found_hole = true;
if (cell->type.in("$assert", "$assume"))
found_assert_assume = true;
}
if (!found_input)
log_cmd_error("Can't perform QBF-SAT on a miter with no inputs!\n");
if (!found_hole)
log_cmd_error("Did not find any existentially-quantified variables. Use 'sat' instead.\n");
if (!found_1bit_output && !found_assert_assume)
log_cmd_error("Did not find any single-bit outputs or $assert/$assume cells. Is this a miter circuit?\n");
if (!found_assert_assume && !assume_outputs)
log_cmd_error("Did not find any $assert/$assume cells. Single-bit outputs were found, but `-assume-outputs` was not specified.\n");
return input_wires;
}
void specialize_from_file(RTLIL::Module *module, const std::string &file) {
YS_REGEX_TYPE hole_bit_assn_regex = YS_REGEX_COMPILE_WITH_SUBS("^(.+) ([0-9]+) ([^ ]+) \\[([0-9]+)] = ([01])$");
YS_REGEX_TYPE hole_assn_regex = YS_REGEX_COMPILE_WITH_SUBS("^(.+) ([0-9]+) ([^ ]+) = ([01])$"); //if no index specified
YS_REGEX_MATCH_TYPE bit_m, m;
//(hole_loc, hole_bit, hole_name, hole_offset) -> (value, found)
dict<pool<std::string>, RTLIL::Cell*> anyconst_loc_to_cell;
dict<RTLIL::SigBit, RTLIL::State> hole_assignments;
for (auto cell : module->cells())
if (cell->type == "$anyconst")
anyconst_loc_to_cell[cell->get_strpool_attribute(ID::src)] = cell;
std::ifstream fin(file.c_str());
if (!fin)
log_cmd_error("could not read solution file.\n");
std::string buf;
while (std::getline(fin, buf)) {
bool bit_assn = true;
if (!YS_REGEX_NS::regex_search(buf, bit_m, hole_bit_assn_regex)) {
bit_assn = false;
if (!YS_REGEX_NS::regex_search(buf, m, hole_assn_regex))
log_cmd_error("solution file is not formatted correctly: \"%s\"\n", buf.c_str());
}
std::string hole_loc = bit_assn? bit_m[1].str() : m[1].str();
unsigned int hole_bit = bit_assn? atoi(bit_m[2].str().c_str()) : atoi(m[2].str().c_str());
std::string hole_name = bit_assn? bit_m[3].str() : m[3].str();
unsigned int hole_offset = bit_assn? atoi(bit_m[4].str().c_str()) : 0;
RTLIL::State hole_value = bit_assn? (atoi(bit_m[5].str().c_str()) == 1? RTLIL::State::S1 : RTLIL::State::S0)
: (atoi(m[4].str().c_str()) == 1? RTLIL::State::S1 : RTLIL::State::S0);
//We have two options to identify holes. First, try to match wire names. If we can't find a matching wire,
//then try to find a cell with a matching location.
RTLIL::SigBit hole_sigbit;
if (module->wire(hole_name) != nullptr) {
RTLIL::Wire *hole_wire = module->wire(hole_name);
hole_sigbit = RTLIL::SigSpec(hole_wire)[hole_offset];
} else {
auto locs = split_tokens(hole_loc, "|");
pool<std::string> hole_loc_pool(locs.begin(), locs.end());
auto hole_cell_it = anyconst_loc_to_cell.find(hole_loc_pool);
if (hole_cell_it == anyconst_loc_to_cell.end())
log_cmd_error("cannot find matching wire name or $anyconst cell location for hole spec \"%s\"\n", buf.c_str());
RTLIL::Cell *hole_cell = hole_cell_it->second;
hole_sigbit = hole_cell->getPort(ID::Y)[hole_bit];
}
hole_assignments[hole_sigbit] = hole_value;
}
for (auto &it : anyconst_loc_to_cell)
module->remove(it.second);
for (auto &it : hole_assignments) {
RTLIL::SigSpec lhs(it.first);
RTLIL::SigSpec rhs(it.second);
log("Specializing %s from file with %s = %d.\n", module->name.c_str(), log_signal(it.first), it.second == RTLIL::State::S1? 1 : 0);
module->connect(lhs, rhs);
}
}
void specialize(RTLIL::Module *module, const QbfSolutionType &sol, bool quiet = false) {
auto hole_loc_idx_to_sigbit = sol.get_hole_loc_idx_sigbit_map(module);
pool<RTLIL::Cell *> anyconsts_to_remove;
for (auto cell : module->cells())
if (cell->type == "$anyconst")
if (hole_loc_idx_to_sigbit.find(std::make_pair(cell->get_strpool_attribute(ID::src), 0)) != hole_loc_idx_to_sigbit.end())
anyconsts_to_remove.insert(cell);
for (auto cell : anyconsts_to_remove)
module->remove(cell);
for (auto &it : sol.hole_to_value) {
pool<std::string> hole_loc = it.first;
std::string hole_value = it.second;
for (unsigned int i = 0; i < hole_value.size(); ++i) {
int bit_idx = GetSize(hole_value) - 1 - i;
auto it = hole_loc_idx_to_sigbit.find(std::make_pair(hole_loc, i));
log_assert(it != hole_loc_idx_to_sigbit.end());
RTLIL::SigBit hole_sigbit = it->second;
log_assert(hole_sigbit.wire != nullptr);
log_assert(hole_value[bit_idx] == '0' || hole_value[bit_idx] == '1');
RTLIL::SigSpec lhs(hole_sigbit.wire, hole_sigbit.offset, 1);
RTLIL::State hole_bit_val = hole_value[bit_idx] == '1'? RTLIL::State::S1 : RTLIL::State::S0;
if (!quiet)
log("Specializing %s with %s = %d.\n", module->name.c_str(), log_signal(hole_sigbit), hole_bit_val == RTLIL::State::S0? 0 : 1)
;
module->connect(lhs, hole_bit_val);
}
}
}
void allconstify_inputs(RTLIL::Module *module, const pool<std::string> &input_wires) {
for (auto &n : input_wires) {
RTLIL::Wire *input = module->wire(n);
#ifndef NDEBUG
log_assert(input != nullptr);
#endif
RTLIL::Cell *allconst = module->addCell("$allconst$" + n, "$allconst");
allconst->setParam(ID(WIDTH), input->width);
allconst->setPort(ID::Y, input);
allconst->set_src_attribute(input->get_src_attribute());
input->port_input = false;
log("Replaced input %s with $allconst cell.\n", n.c_str());
}
module->fixup_ports();
}
void assume_miter_outputs(RTLIL::Module *module, bool assume_neg) {
std::vector<RTLIL::Wire *> wires_to_assume;
for (auto w : module->wires())
if (w->port_output && w->width == 1)
wires_to_assume.push_back(w);
if (wires_to_assume.size() == 0)
return;
else {
log("Adding $assume cell for output(s): ");
for (auto w : wires_to_assume)
log("\"%s\" ", w->name.c_str());
log("\n");
}
if (assume_neg) {
for (unsigned int i = 0; i < wires_to_assume.size(); ++i) {
RTLIL::SigSpec n_wire = module->LogicNot(wires_to_assume[i]->name.str() + "__n__qbfsat", wires_to_assume[i], false, wires_to_assume[i]->get_src_attribute());
wires_to_assume[i] = n_wire.as_wire();
}
}
for (auto i = 0; wires_to_assume.size() > 1; ++i) {
std::vector<RTLIL::Wire *> buf;
for (auto j = 0; j + 1 < GetSize(wires_to_assume); j += 2) {
std::stringstream strstr; strstr << i << "_" << j;
RTLIL::Wire *and_wire = module->addWire("\\_qbfsat_and_" + strstr.str(), 1);
module->addLogicAnd("$_qbfsat_and_" + strstr.str(), wires_to_assume[j], wires_to_assume[j+1], and_wire, false, wires_to_assume[j]->get_src_attribute());
buf.push_back(and_wire);
}
if (wires_to_assume.size() % 2 == 1)
buf.push_back(wires_to_assume[wires_to_assume.size() - 1]);
wires_to_assume.swap(buf);
}
#ifndef NDEBUG
log_assert(wires_to_assume.size() == 1);
#endif
module->addAssume("$assume_qbfsat_miter_outputs", wires_to_assume[0], RTLIL::S1);
}
QbfSolutionType call_qbf_solver(RTLIL::Module *mod, const QbfSolveOptions &opt, const std::string &tempdir_name, const bool quiet = false, const int iter_num = 0) {
//Execute and capture stdout from `yosys-smtbmc -s z3 -t 1 -g --binary [--dump-smt2 <file>]`
QbfSolutionType ret;
const std::string yosys_smtbmc_exe = proc_self_dirname() + "yosys-smtbmc";
const std::string smt2_command = stringf("write_smt2 -stbv -wires %s/problem%d.smt2", tempdir_name.c_str(), iter_num);
const std::string smtbmc_warning = "z3: WARNING:";
const std::string smtbmc_cmd = stringf("%s -s %s %s -t 1 -g --binary %s %s/problem%d.smt2 2>&1",
yosys_smtbmc_exe.c_str(), opt.get_solver_name().c_str(),
(opt.timeout != 0? stringf("--timeout %d", opt.timeout) : "").c_str(),
(opt.dump_final_smt2? "--dump-smt2 " + opt.dump_final_smt2_file : "").c_str(),
tempdir_name.c_str(), iter_num);
Pass::call(mod->design, smt2_command);
auto process_line = [&ret, &smtbmc_warning, &opt, &quiet](const std::string &line) {
ret.stdout_lines.push_back(line.substr(0, line.size()-1)); //don't include trailing newline
auto warning_pos = line.find(smtbmc_warning);
if (warning_pos != std::string::npos)
log_warning("%s", line.substr(warning_pos + smtbmc_warning.size() + 1).c_str());
else
if (opt.show_smtbmc && !quiet)
log("smtbmc output: %s", line.c_str());
};
log_header(mod->design, "Solving QBF-SAT problem.\n");
if (!quiet) log("Launching \"%s\".\n", smtbmc_cmd.c_str());
int64_t begin = PerformanceTimer::query();
run_command(smtbmc_cmd, process_line);
int64_t end = PerformanceTimer::query();
ret.solver_time = (end - begin) / 1e9f;
if (!quiet) log("Solver finished in %.3f seconds.\n", ret.solver_time);
ret.recover_solution();
return ret;
}
QbfSolutionType qbf_solve(RTLIL::Module *mod, const QbfSolveOptions &opt) {
QbfSolutionType ret, best_soln;
const std::string tempdir_name = make_temp_dir("/tmp/yosys-qbfsat-XXXXXX");
RTLIL::Module *module = mod;
RTLIL::Design *design = module->design;
std::string module_name = module->name.str();
RTLIL::IdString wire_to_optimize_name = "";
bool maximize = false;
log_assert(module->design != nullptr);
Pass::call(design, "design -push-copy");
//Replace input wires with wires assigned $allconst cells:
pool<std::string> input_wires = validate_design_and_get_inputs(module, opt.assume_outputs);
allconstify_inputs(module, input_wires);
if (opt.assume_outputs)
assume_miter_outputs(module, opt.assume_neg);
//Find the wire to be optimized, if any:
for (auto wire : module->wires()) {
if (wire->get_bool_attribute("\\maximize") || wire->get_bool_attribute("\\minimize")) {
wire_to_optimize_name = wire->name;
maximize = wire->get_bool_attribute("\\maximize");
if (opt.nooptimize) {
if (maximize)
wire->set_bool_attribute("\\maximize", false);
else
wire->set_bool_attribute("\\minimize", false);
}
}
}
//If -O1 or -O2 was specified, use ABC to simplify the problem:
if (opt.oflag == opt.OptimizationLevel::O1)
Pass::call(module->design, "abc -g AND,NAND,OR,NOR,XOR,XNOR,MUX,NMUX -script +print_stats;strash;print_stats;drwsat;print_stats;fraig;print_stats;refactor,-N,10,-lz;print_stats;&get,-n;&dch,-pem;&nf;&put " + mod->name.str());
else if (opt.oflag == opt.OptimizationLevel::O2)
Pass::call(module->design, "abc -g AND,NAND,OR,NOR,XOR,XNOR,MUX,NMUX -script +print_stats;strash;print_stats;drwsat;print_stats;dch,-S,1000000,-C,100000,-p;print_stats;fraig;print_stats;refactor,-N,15,-lz;print_stats;dc2,-pbl;print_stats;drwsat;print_stats;&get,-n;&dch,-pem;&nf;&put " + mod->name.str());
if (opt.oflag != opt.OptimizationLevel::O0) {
Pass::call(module->design, "techmap");
Pass::call(module->design, "opt");
}
if (opt.nobisection || opt.nooptimize || wire_to_optimize_name == "") {
ret = call_qbf_solver(module, opt, tempdir_name, false, 0);
} else {
//Do the iterated bisection method:
unsigned int iter_num = 1;
unsigned int success = 0;
unsigned int failure = 0;
unsigned int cur_thresh = 0;
log_assert(wire_to_optimize_name != "");
log_assert(module->wire(wire_to_optimize_name) != nullptr);
log("%s wire \"%s\".\n", (maximize? "Maximizing" : "Minimizing"), wire_to_optimize_name.c_str());
//If maximizing, grow until we get a failure. Then bisect success and failure.
while (failure == 0 || difference(success, failure) > 1) {
Pass::call(design, "design -push-copy");
log_header(design, "Preparing QBF-SAT problem.\n");
if (cur_thresh != 0) {
//Add thresholding logic (but not on the initial run when we don't have a sense of where to start):
RTLIL::SigSpec comparator = maximize? module->Ge(NEW_ID, module->wire(wire_to_optimize_name), RTLIL::Const(cur_thresh), false)
: module->Le(NEW_ID, module->wire(wire_to_optimize_name), RTLIL::Const(cur_thresh), false);
module->addAssume(wire_to_optimize_name.str() + "__threshold", comparator, RTLIL::Const(1, 1));
log("Trying to solve with %s %s %d.\n", wire_to_optimize_name.c_str(), (maximize? ">=" : "<="), cur_thresh);
}
ret = call_qbf_solver(module, opt, tempdir_name, false, iter_num);
Pass::call(design, "design -pop");
module = design->module(module_name);
if (!ret.unknown && ret.sat) {
Pass::call(design, "design -push-copy");
specialize(module, ret, true);
RTLIL::SigSpec wire, value, undef;
RTLIL::SigSpec::parse_sel(wire, design, module, wire_to_optimize_name.str());
ConstEval ce(module);
value = wire;
if (!ce.eval(value, undef))
log_cmd_error("Failed to evaluate signal %s: Missing value for %s.\n", log_signal(wire), log_signal(undef));
log_assert(value.is_fully_const());
success = value.as_const().as_int();
best_soln = ret;
log("Problem is satisfiable with %s = %d.\n", wire_to_optimize_name.c_str(), success);
Pass::call(design, "design -pop");
module = design->module(module_name);
//sometimes this happens if we get an 'unknown' or timeout
if (!maximize && success < failure)
break;
else if (maximize && failure != 0 && success > failure)
break;
} else {
//Treat 'unknown' as UNSAT
failure = cur_thresh;
if (failure == 0) {
log("Problem is NOT satisfiable.\n");
break;
}
else
log("Problem is NOT satisfiable with %s %s %d.\n", wire_to_optimize_name.c_str(), (maximize? ">=" : "<="), failure);
}
iter_num++;
if (maximize && failure == 0 && success == 0)
cur_thresh = 2;
else if (maximize && failure == 0)
cur_thresh = 2 * success; //growth
else //if (!maximize || failure != 0)
cur_thresh = (success + failure) / 2; //bisection
}
if (success != 0 || failure != 0) {
log("Wire %s is %s at %d.\n", wire_to_optimize_name.c_str(), (maximize? "maximized" : "minimized"), success);
ret = best_soln;
}
}
if(!opt.nocleanup)
remove_directory(tempdir_name);
Pass::call(design, "design -pop");
return ret;
}
QbfSolveOptions parse_args(const std::vector<std::string> &args) {
QbfSolveOptions opt;
for (opt.argidx = 1; opt.argidx < args.size(); opt.argidx++) {
if (args[opt.argidx] == "-nocleanup") {
opt.nocleanup = true;
continue;
}
else if (args[opt.argidx] == "-specialize") {
opt.specialize = true;
continue;
}
else if (args[opt.argidx] == "-assume-outputs") {
opt.assume_outputs = true;
continue;
}
else if (args[opt.argidx] == "-assume-negative-polarity") {
opt.assume_neg = true;
continue;
}
else if (args[opt.argidx] == "-nooptimize") {
opt.nooptimize = true;
continue;
}
else if (args[opt.argidx] == "-nobisection") {
opt.nobisection = true;
continue;
}
else if (args[opt.argidx] == "-solver") {
if (args.size() <= opt.argidx + 1)
log_cmd_error("solver not specified.\n");
else {
if (args[opt.argidx+1] == "z3")
opt.solver = opt.Solver::Z3;
else if (args[opt.argidx+1] == "yices")
opt.solver = opt.Solver::Yices;
else if (args[opt.argidx+1] == "cvc4")
opt.solver = opt.Solver::CVC4;
else
log_cmd_error("Unknown solver \"%s\".\n", args[opt.argidx+1].c_str());
opt.argidx++;
}
continue;
}
else if (args[opt.argidx] == "-timeout") {
if (args.size() <= opt.argidx + 1)
log_cmd_error("timeout not specified.\n");
else {
int timeout = atoi(args[opt.argidx+1].c_str());
if (timeout > 0)
opt.timeout = timeout;
else
log_cmd_error("timeout must be greater than 0.\n");
opt.argidx++;
}
continue;
}
else if (args[opt.argidx].substr(0, 2) == "-O" && args[opt.argidx].size() == 3) {
switch (args[opt.argidx][2]) {
case '0':
opt.oflag = opt.OptimizationLevel::O0;
break;
case '1':
opt.oflag = opt.OptimizationLevel::O1;
break;
case '2':
opt.oflag = opt.OptimizationLevel::O2;
break;
default:
log_cmd_error("unknown argument %s\n", args[opt.argidx].c_str());
}
continue;
}
else if (args[opt.argidx] == "-sat") {
opt.sat = true;
continue;
}
else if (args[opt.argidx] == "-unsat") {
opt.unsat = true;
continue;
}
else if (args[opt.argidx] == "-show-smtbmc") {
opt.show_smtbmc = true;
continue;
}
else if (args[opt.argidx] == "-dump-final-smt2") {
opt.dump_final_smt2 = true;
if (args.size() <= opt.argidx + 1)
log_cmd_error("smt2 file not specified.\n");
else
opt.dump_final_smt2_file = args[++opt.argidx];
continue;
}
else if (args[opt.argidx] == "-specialize-from-file") {
opt.specialize_from_file = true;
if (args.size() <= opt.argidx + 1)
log_cmd_error("solution file not specified.\n");
else
opt.specialize_soln_file = args[++opt.argidx];
continue;
}
else if (args[opt.argidx] == "-write-solution") {
opt.write_solution = true;
if (args.size() <= opt.argidx + 1)
log_cmd_error("solution file not specified.\n");
else
opt.write_soln_soln_file = args[++opt.argidx];
continue;
}
break;
}
return opt;
}
struct QbfSatPass : public Pass {
QbfSatPass() : Pass("qbfsat", "solve a 2QBF-SAT problem in the circuit") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" qbfsat [options] [selection]\n");
log("\n");
log("This command solves an \"exists-forall\" 2QBF-SAT problem defined over the currently\n");
log("selected module. Existentially-quantified variables are declared by assigning a wire\n");
log("\"$anyconst\". Universally-quantified variables may be explicitly declared by assigning\n");
log("a wire \"$allconst\", but module inputs will be treated as universally-quantified\n");
log("variables by default.\n");
log("\n");
log(" -nocleanup\n");
log(" Do not delete temporary files and directories. Useful for debugging.\n");
log("\n");
log(" -dump-final-smt2 <file>\n");
log(" Pass the --dump-smt2 option to yosys-smtbmc.\n");
log("\n");
log(" -assume-outputs\n");
log(" Add an \"$assume\" cell for the conjunction of all one-bit module output wires.\n");
log("\n");
log(" -assume-negative-polarity\n");
log(" When adding $assume cells for one-bit module output wires, assume they are\n");
log(" negative polarity signals and should always be low, for example like the\n");
log(" miters created with the `miter` command.\n");
log("\n");
log(" -nooptimize\n");
log(" Ignore \"\\minimize\" and \"\\maximize\" attributes, do not emit \"(maximize)\" or\n");
log(" \"(minimize)\" in the SMT-LIBv2, and generally make no attempt to optimize anything.\n");
log("\n");
log(" -nobisection\n");
log(" If a wire is marked with the \"\\minimize\" or \"\\maximize\" attribute, do not\n");
log(" attempt to optimize that value with the default iterated solving and threshold\n");
log(" bisection approach. Instead, have yosys-smtbmc emit a \"(minimize)\" or \"(maximize)\"\n");
log(" command in the SMT-LIBv2 output and hope that the solver supports optimizing\n");
log(" quantified bitvector problems.\n");
log("\n");
log(" -solver <solver>\n");
log(" Use a particular solver. Choose one of: \"z3\", \"yices\", and \"cvc4\".\n");
log(" (default: yices)\n");
log("\n");
log(" -timeout <value>\n");
log(" Set the per-iteration timeout in seconds.\n");
log(" (default: no timeout)\n");
log("\n");
log(" -O0, -O1, -O2\n");
log(" Control the use of ABC to simplify the QBF-SAT problem before solving.\n");
log("\n");
log(" -sat\n");
log(" Generate an error if the solver does not return \"sat\".\n");
log("\n");
log(" -unsat\n");
log(" Generate an error if the solver does not return \"unsat\".\n");
log("\n");
log(" -show-smtbmc\n");
log(" Print the output from yosys-smtbmc.\n");
log("\n");
log(" -specialize\n");
log(" If the problem is satisfiable, replace each \"$anyconst\" cell with its\n");
log(" corresponding constant value from the model produced by the solver.\n");
log("\n");
log(" -specialize-from-file <solution file>\n");
log(" Do not run the solver, but instead only attempt to replace each \"$anyconst\"\n");
log(" cell in the current module with a constant value provided by the specified file.\n");
log("\n");
log(" -write-solution <solution file>\n");
log(" If the problem is satisfiable, write the corresponding constant value for each\n");
log(" \"$anyconst\" cell from the model produced by the solver to the specified file.");
log("\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
log_header(design, "Executing QBFSAT pass (solving QBF-SAT problems in the circuit).\n");
QbfSolveOptions opt = parse_args(args);
extra_args(args, opt.argidx, design);
RTLIL::Module *module = nullptr;
for (auto mod : design->selected_modules()) {
if (module)
log_cmd_error("Only one module must be selected for the QBF-SAT pass! (selected: %s and %s)\n", log_id(module), log_id(mod));
module = mod;
}
if (module == nullptr)
log_cmd_error("Can't perform QBF-SAT on an empty selection!\n");
log_push();
if (!opt.specialize_from_file) {
//Save the design to restore after modiyfing the current module.
std::string module_name = module->name.str();
QbfSolutionType ret = qbf_solve(module, opt);
module = design->module(module_name);
if (ret.unknown) {
if (opt.sat || opt.unsat)
log_cmd_error("expected problem to be %s\n", opt.sat? "SAT" : "UNSAT");
}
else if (ret.sat) {
print_qed();
if (opt.write_solution) {
ret.write_solution(module, opt.write_soln_soln_file);
}
if (opt.specialize) {
specialize(module, ret);
} else {
ret.dump_model(module);
}
if (opt.unsat)
log_cmd_error("expected problem to be UNSAT\n");
}
else {
print_proof_failed();
if (opt.sat)
log_cmd_error("expected problem to be SAT\n");
}
} else
specialize_from_file(module, opt.specialize_soln_file);
log_pop();
}
} QbfSatPass;
PRIVATE_NAMESPACE_END
qbfsat: Remove useless comment and #ifndef guards.
/* -*- c++ -*-
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2020 Alberto Gonzalez <boqwxp@airmail.cc>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/consteval.h"
#include "qbfsat.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
static inline unsigned int difference(unsigned int a, unsigned int b) {
if (a < b)
return b - a;
else
return a - b;
}
pool<std::string> validate_design_and_get_inputs(RTLIL::Module *module, bool assume_outputs) {
bool found_input = false;
bool found_hole = false;
bool found_1bit_output = false;
bool found_assert_assume = false;
pool<std::string> input_wires;
for (auto wire : module->wires()) {
if (wire->port_input) {
found_input = true;
input_wires.insert(wire->name.str());
}
if (wire->port_output && wire->width == 1)
found_1bit_output = true;
}
for (auto cell : module->cells()) {
if (cell->type == "$allconst")
found_input = true;
if (cell->type == "$anyconst")
found_hole = true;
if (cell->type.in("$assert", "$assume"))
found_assert_assume = true;
}
if (!found_input)
log_cmd_error("Can't perform QBF-SAT on a miter with no inputs!\n");
if (!found_hole)
log_cmd_error("Did not find any existentially-quantified variables. Use 'sat' instead.\n");
if (!found_1bit_output && !found_assert_assume)
log_cmd_error("Did not find any single-bit outputs or $assert/$assume cells. Is this a miter circuit?\n");
if (!found_assert_assume && !assume_outputs)
log_cmd_error("Did not find any $assert/$assume cells. Single-bit outputs were found, but `-assume-outputs` was not specified.\n");
return input_wires;
}
void specialize_from_file(RTLIL::Module *module, const std::string &file) {
YS_REGEX_TYPE hole_bit_assn_regex = YS_REGEX_COMPILE_WITH_SUBS("^(.+) ([0-9]+) ([^ ]+) \\[([0-9]+)] = ([01])$");
YS_REGEX_TYPE hole_assn_regex = YS_REGEX_COMPILE_WITH_SUBS("^(.+) ([0-9]+) ([^ ]+) = ([01])$"); //if no index specified
YS_REGEX_MATCH_TYPE bit_m, m;
dict<pool<std::string>, RTLIL::Cell*> anyconst_loc_to_cell;
dict<RTLIL::SigBit, RTLIL::State> hole_assignments;
for (auto cell : module->cells())
if (cell->type == "$anyconst")
anyconst_loc_to_cell[cell->get_strpool_attribute(ID::src)] = cell;
std::ifstream fin(file.c_str());
if (!fin)
log_cmd_error("could not read solution file.\n");
std::string buf;
while (std::getline(fin, buf)) {
bool bit_assn = true;
if (!YS_REGEX_NS::regex_search(buf, bit_m, hole_bit_assn_regex)) {
bit_assn = false;
if (!YS_REGEX_NS::regex_search(buf, m, hole_assn_regex))
log_cmd_error("solution file is not formatted correctly: \"%s\"\n", buf.c_str());
}
std::string hole_loc = bit_assn? bit_m[1].str() : m[1].str();
unsigned int hole_bit = bit_assn? atoi(bit_m[2].str().c_str()) : atoi(m[2].str().c_str());
std::string hole_name = bit_assn? bit_m[3].str() : m[3].str();
unsigned int hole_offset = bit_assn? atoi(bit_m[4].str().c_str()) : 0;
RTLIL::State hole_value = bit_assn? (atoi(bit_m[5].str().c_str()) == 1? RTLIL::State::S1 : RTLIL::State::S0)
: (atoi(m[4].str().c_str()) == 1? RTLIL::State::S1 : RTLIL::State::S0);
//We have two options to identify holes. First, try to match wire names. If we can't find a matching wire,
//then try to find a cell with a matching location.
RTLIL::SigBit hole_sigbit;
if (module->wire(hole_name) != nullptr) {
RTLIL::Wire *hole_wire = module->wire(hole_name);
hole_sigbit = RTLIL::SigSpec(hole_wire)[hole_offset];
} else {
auto locs = split_tokens(hole_loc, "|");
pool<std::string> hole_loc_pool(locs.begin(), locs.end());
auto hole_cell_it = anyconst_loc_to_cell.find(hole_loc_pool);
if (hole_cell_it == anyconst_loc_to_cell.end())
log_cmd_error("cannot find matching wire name or $anyconst cell location for hole spec \"%s\"\n", buf.c_str());
RTLIL::Cell *hole_cell = hole_cell_it->second;
hole_sigbit = hole_cell->getPort(ID::Y)[hole_bit];
}
hole_assignments[hole_sigbit] = hole_value;
}
for (auto &it : anyconst_loc_to_cell)
module->remove(it.second);
for (auto &it : hole_assignments) {
RTLIL::SigSpec lhs(it.first);
RTLIL::SigSpec rhs(it.second);
log("Specializing %s from file with %s = %d.\n", module->name.c_str(), log_signal(it.first), it.second == RTLIL::State::S1? 1 : 0);
module->connect(lhs, rhs);
}
}
void specialize(RTLIL::Module *module, const QbfSolutionType &sol, bool quiet = false) {
auto hole_loc_idx_to_sigbit = sol.get_hole_loc_idx_sigbit_map(module);
pool<RTLIL::Cell *> anyconsts_to_remove;
for (auto cell : module->cells())
if (cell->type == "$anyconst")
if (hole_loc_idx_to_sigbit.find(std::make_pair(cell->get_strpool_attribute(ID::src), 0)) != hole_loc_idx_to_sigbit.end())
anyconsts_to_remove.insert(cell);
for (auto cell : anyconsts_to_remove)
module->remove(cell);
for (auto &it : sol.hole_to_value) {
pool<std::string> hole_loc = it.first;
std::string hole_value = it.second;
for (unsigned int i = 0; i < hole_value.size(); ++i) {
int bit_idx = GetSize(hole_value) - 1 - i;
auto it = hole_loc_idx_to_sigbit.find(std::make_pair(hole_loc, i));
log_assert(it != hole_loc_idx_to_sigbit.end());
RTLIL::SigBit hole_sigbit = it->second;
log_assert(hole_sigbit.wire != nullptr);
log_assert(hole_value[bit_idx] == '0' || hole_value[bit_idx] == '1');
RTLIL::SigSpec lhs(hole_sigbit.wire, hole_sigbit.offset, 1);
RTLIL::State hole_bit_val = hole_value[bit_idx] == '1'? RTLIL::State::S1 : RTLIL::State::S0;
if (!quiet)
log("Specializing %s with %s = %d.\n", module->name.c_str(), log_signal(hole_sigbit), hole_bit_val == RTLIL::State::S0? 0 : 1)
;
module->connect(lhs, hole_bit_val);
}
}
}
void allconstify_inputs(RTLIL::Module *module, const pool<std::string> &input_wires) {
for (auto &n : input_wires) {
RTLIL::Wire *input = module->wire(n);
log_assert(input != nullptr);
RTLIL::Cell *allconst = module->addCell("$allconst$" + n, "$allconst");
allconst->setParam(ID(WIDTH), input->width);
allconst->setPort(ID::Y, input);
allconst->set_src_attribute(input->get_src_attribute());
input->port_input = false;
log("Replaced input %s with $allconst cell.\n", n.c_str());
}
module->fixup_ports();
}
void assume_miter_outputs(RTLIL::Module *module, bool assume_neg) {
std::vector<RTLIL::Wire *> wires_to_assume;
for (auto w : module->wires())
if (w->port_output && w->width == 1)
wires_to_assume.push_back(w);
if (wires_to_assume.size() == 0)
return;
else {
log("Adding $assume cell for output(s): ");
for (auto w : wires_to_assume)
log("\"%s\" ", w->name.c_str());
log("\n");
}
if (assume_neg) {
for (unsigned int i = 0; i < wires_to_assume.size(); ++i) {
RTLIL::SigSpec n_wire = module->LogicNot(wires_to_assume[i]->name.str() + "__n__qbfsat", wires_to_assume[i], false, wires_to_assume[i]->get_src_attribute());
wires_to_assume[i] = n_wire.as_wire();
}
}
for (auto i = 0; wires_to_assume.size() > 1; ++i) {
std::vector<RTLIL::Wire *> buf;
for (auto j = 0; j + 1 < GetSize(wires_to_assume); j += 2) {
std::stringstream strstr; strstr << i << "_" << j;
RTLIL::Wire *and_wire = module->addWire("\\_qbfsat_and_" + strstr.str(), 1);
module->addLogicAnd("$_qbfsat_and_" + strstr.str(), wires_to_assume[j], wires_to_assume[j+1], and_wire, false, wires_to_assume[j]->get_src_attribute());
buf.push_back(and_wire);
}
if (wires_to_assume.size() % 2 == 1)
buf.push_back(wires_to_assume[wires_to_assume.size() - 1]);
wires_to_assume.swap(buf);
}
log_assert(wires_to_assume.size() == 1);
module->addAssume("$assume_qbfsat_miter_outputs", wires_to_assume[0], RTLIL::S1);
}
QbfSolutionType call_qbf_solver(RTLIL::Module *mod, const QbfSolveOptions &opt, const std::string &tempdir_name, const bool quiet = false, const int iter_num = 0) {
//Execute and capture stdout from `yosys-smtbmc -s z3 -t 1 -g --binary [--dump-smt2 <file>]`
QbfSolutionType ret;
const std::string yosys_smtbmc_exe = proc_self_dirname() + "yosys-smtbmc";
const std::string smt2_command = stringf("write_smt2 -stbv -wires %s/problem%d.smt2", tempdir_name.c_str(), iter_num);
const std::string smtbmc_warning = "z3: WARNING:";
const std::string smtbmc_cmd = stringf("%s -s %s %s -t 1 -g --binary %s %s/problem%d.smt2 2>&1",
yosys_smtbmc_exe.c_str(), opt.get_solver_name().c_str(),
(opt.timeout != 0? stringf("--timeout %d", opt.timeout) : "").c_str(),
(opt.dump_final_smt2? "--dump-smt2 " + opt.dump_final_smt2_file : "").c_str(),
tempdir_name.c_str(), iter_num);
Pass::call(mod->design, smt2_command);
auto process_line = [&ret, &smtbmc_warning, &opt, &quiet](const std::string &line) {
ret.stdout_lines.push_back(line.substr(0, line.size()-1)); //don't include trailing newline
auto warning_pos = line.find(smtbmc_warning);
if (warning_pos != std::string::npos)
log_warning("%s", line.substr(warning_pos + smtbmc_warning.size() + 1).c_str());
else
if (opt.show_smtbmc && !quiet)
log("smtbmc output: %s", line.c_str());
};
log_header(mod->design, "Solving QBF-SAT problem.\n");
if (!quiet) log("Launching \"%s\".\n", smtbmc_cmd.c_str());
int64_t begin = PerformanceTimer::query();
run_command(smtbmc_cmd, process_line);
int64_t end = PerformanceTimer::query();
ret.solver_time = (end - begin) / 1e9f;
if (!quiet) log("Solver finished in %.3f seconds.\n", ret.solver_time);
ret.recover_solution();
return ret;
}
QbfSolutionType qbf_solve(RTLIL::Module *mod, const QbfSolveOptions &opt) {
QbfSolutionType ret, best_soln;
const std::string tempdir_name = make_temp_dir("/tmp/yosys-qbfsat-XXXXXX");
RTLIL::Module *module = mod;
RTLIL::Design *design = module->design;
std::string module_name = module->name.str();
RTLIL::IdString wire_to_optimize_name = "";
bool maximize = false;
log_assert(module->design != nullptr);
Pass::call(design, "design -push-copy");
//Replace input wires with wires assigned $allconst cells:
pool<std::string> input_wires = validate_design_and_get_inputs(module, opt.assume_outputs);
allconstify_inputs(module, input_wires);
if (opt.assume_outputs)
assume_miter_outputs(module, opt.assume_neg);
//Find the wire to be optimized, if any:
for (auto wire : module->wires()) {
if (wire->get_bool_attribute("\\maximize") || wire->get_bool_attribute("\\minimize")) {
wire_to_optimize_name = wire->name;
maximize = wire->get_bool_attribute("\\maximize");
if (opt.nooptimize) {
if (maximize)
wire->set_bool_attribute("\\maximize", false);
else
wire->set_bool_attribute("\\minimize", false);
}
}
}
//If -O1 or -O2 was specified, use ABC to simplify the problem:
if (opt.oflag == opt.OptimizationLevel::O1)
Pass::call(module->design, "abc -g AND,NAND,OR,NOR,XOR,XNOR,MUX,NMUX -script +print_stats;strash;print_stats;drwsat;print_stats;fraig;print_stats;refactor,-N,10,-lz;print_stats;&get,-n;&dch,-pem;&nf;&put " + mod->name.str());
else if (opt.oflag == opt.OptimizationLevel::O2)
Pass::call(module->design, "abc -g AND,NAND,OR,NOR,XOR,XNOR,MUX,NMUX -script +print_stats;strash;print_stats;drwsat;print_stats;dch,-S,1000000,-C,100000,-p;print_stats;fraig;print_stats;refactor,-N,15,-lz;print_stats;dc2,-pbl;print_stats;drwsat;print_stats;&get,-n;&dch,-pem;&nf;&put " + mod->name.str());
if (opt.oflag != opt.OptimizationLevel::O0) {
Pass::call(module->design, "techmap");
Pass::call(module->design, "opt");
}
if (opt.nobisection || opt.nooptimize || wire_to_optimize_name == "") {
ret = call_qbf_solver(module, opt, tempdir_name, false, 0);
} else {
//Do the iterated bisection method:
unsigned int iter_num = 1;
unsigned int success = 0;
unsigned int failure = 0;
unsigned int cur_thresh = 0;
log_assert(wire_to_optimize_name != "");
log_assert(module->wire(wire_to_optimize_name) != nullptr);
log("%s wire \"%s\".\n", (maximize? "Maximizing" : "Minimizing"), wire_to_optimize_name.c_str());
//If maximizing, grow until we get a failure. Then bisect success and failure.
while (failure == 0 || difference(success, failure) > 1) {
Pass::call(design, "design -push-copy");
log_header(design, "Preparing QBF-SAT problem.\n");
if (cur_thresh != 0) {
//Add thresholding logic (but not on the initial run when we don't have a sense of where to start):
RTLIL::SigSpec comparator = maximize? module->Ge(NEW_ID, module->wire(wire_to_optimize_name), RTLIL::Const(cur_thresh), false)
: module->Le(NEW_ID, module->wire(wire_to_optimize_name), RTLIL::Const(cur_thresh), false);
module->addAssume(wire_to_optimize_name.str() + "__threshold", comparator, RTLIL::Const(1, 1));
log("Trying to solve with %s %s %d.\n", wire_to_optimize_name.c_str(), (maximize? ">=" : "<="), cur_thresh);
}
ret = call_qbf_solver(module, opt, tempdir_name, false, iter_num);
Pass::call(design, "design -pop");
module = design->module(module_name);
if (!ret.unknown && ret.sat) {
Pass::call(design, "design -push-copy");
specialize(module, ret, true);
RTLIL::SigSpec wire, value, undef;
RTLIL::SigSpec::parse_sel(wire, design, module, wire_to_optimize_name.str());
ConstEval ce(module);
value = wire;
if (!ce.eval(value, undef))
log_cmd_error("Failed to evaluate signal %s: Missing value for %s.\n", log_signal(wire), log_signal(undef));
log_assert(value.is_fully_const());
success = value.as_const().as_int();
best_soln = ret;
log("Problem is satisfiable with %s = %d.\n", wire_to_optimize_name.c_str(), success);
Pass::call(design, "design -pop");
module = design->module(module_name);
//sometimes this happens if we get an 'unknown' or timeout
if (!maximize && success < failure)
break;
else if (maximize && failure != 0 && success > failure)
break;
} else {
//Treat 'unknown' as UNSAT
failure = cur_thresh;
if (failure == 0) {
log("Problem is NOT satisfiable.\n");
break;
}
else
log("Problem is NOT satisfiable with %s %s %d.\n", wire_to_optimize_name.c_str(), (maximize? ">=" : "<="), failure);
}
iter_num++;
if (maximize && failure == 0 && success == 0)
cur_thresh = 2;
else if (maximize && failure == 0)
cur_thresh = 2 * success; //growth
else //if (!maximize || failure != 0)
cur_thresh = (success + failure) / 2; //bisection
}
if (success != 0 || failure != 0) {
log("Wire %s is %s at %d.\n", wire_to_optimize_name.c_str(), (maximize? "maximized" : "minimized"), success);
ret = best_soln;
}
}
if(!opt.nocleanup)
remove_directory(tempdir_name);
Pass::call(design, "design -pop");
return ret;
}
QbfSolveOptions parse_args(const std::vector<std::string> &args) {
QbfSolveOptions opt;
for (opt.argidx = 1; opt.argidx < args.size(); opt.argidx++) {
if (args[opt.argidx] == "-nocleanup") {
opt.nocleanup = true;
continue;
}
else if (args[opt.argidx] == "-specialize") {
opt.specialize = true;
continue;
}
else if (args[opt.argidx] == "-assume-outputs") {
opt.assume_outputs = true;
continue;
}
else if (args[opt.argidx] == "-assume-negative-polarity") {
opt.assume_neg = true;
continue;
}
else if (args[opt.argidx] == "-nooptimize") {
opt.nooptimize = true;
continue;
}
else if (args[opt.argidx] == "-nobisection") {
opt.nobisection = true;
continue;
}
else if (args[opt.argidx] == "-solver") {
if (args.size() <= opt.argidx + 1)
log_cmd_error("solver not specified.\n");
else {
if (args[opt.argidx+1] == "z3")
opt.solver = opt.Solver::Z3;
else if (args[opt.argidx+1] == "yices")
opt.solver = opt.Solver::Yices;
else if (args[opt.argidx+1] == "cvc4")
opt.solver = opt.Solver::CVC4;
else
log_cmd_error("Unknown solver \"%s\".\n", args[opt.argidx+1].c_str());
opt.argidx++;
}
continue;
}
else if (args[opt.argidx] == "-timeout") {
if (args.size() <= opt.argidx + 1)
log_cmd_error("timeout not specified.\n");
else {
int timeout = atoi(args[opt.argidx+1].c_str());
if (timeout > 0)
opt.timeout = timeout;
else
log_cmd_error("timeout must be greater than 0.\n");
opt.argidx++;
}
continue;
}
else if (args[opt.argidx].substr(0, 2) == "-O" && args[opt.argidx].size() == 3) {
switch (args[opt.argidx][2]) {
case '0':
opt.oflag = opt.OptimizationLevel::O0;
break;
case '1':
opt.oflag = opt.OptimizationLevel::O1;
break;
case '2':
opt.oflag = opt.OptimizationLevel::O2;
break;
default:
log_cmd_error("unknown argument %s\n", args[opt.argidx].c_str());
}
continue;
}
else if (args[opt.argidx] == "-sat") {
opt.sat = true;
continue;
}
else if (args[opt.argidx] == "-unsat") {
opt.unsat = true;
continue;
}
else if (args[opt.argidx] == "-show-smtbmc") {
opt.show_smtbmc = true;
continue;
}
else if (args[opt.argidx] == "-dump-final-smt2") {
opt.dump_final_smt2 = true;
if (args.size() <= opt.argidx + 1)
log_cmd_error("smt2 file not specified.\n");
else
opt.dump_final_smt2_file = args[++opt.argidx];
continue;
}
else if (args[opt.argidx] == "-specialize-from-file") {
opt.specialize_from_file = true;
if (args.size() <= opt.argidx + 1)
log_cmd_error("solution file not specified.\n");
else
opt.specialize_soln_file = args[++opt.argidx];
continue;
}
else if (args[opt.argidx] == "-write-solution") {
opt.write_solution = true;
if (args.size() <= opt.argidx + 1)
log_cmd_error("solution file not specified.\n");
else
opt.write_soln_soln_file = args[++opt.argidx];
continue;
}
break;
}
return opt;
}
struct QbfSatPass : public Pass {
QbfSatPass() : Pass("qbfsat", "solve a 2QBF-SAT problem in the circuit") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" qbfsat [options] [selection]\n");
log("\n");
log("This command solves an \"exists-forall\" 2QBF-SAT problem defined over the currently\n");
log("selected module. Existentially-quantified variables are declared by assigning a wire\n");
log("\"$anyconst\". Universally-quantified variables may be explicitly declared by assigning\n");
log("a wire \"$allconst\", but module inputs will be treated as universally-quantified\n");
log("variables by default.\n");
log("\n");
log(" -nocleanup\n");
log(" Do not delete temporary files and directories. Useful for debugging.\n");
log("\n");
log(" -dump-final-smt2 <file>\n");
log(" Pass the --dump-smt2 option to yosys-smtbmc.\n");
log("\n");
log(" -assume-outputs\n");
log(" Add an \"$assume\" cell for the conjunction of all one-bit module output wires.\n");
log("\n");
log(" -assume-negative-polarity\n");
log(" When adding $assume cells for one-bit module output wires, assume they are\n");
log(" negative polarity signals and should always be low, for example like the\n");
log(" miters created with the `miter` command.\n");
log("\n");
log(" -nooptimize\n");
log(" Ignore \"\\minimize\" and \"\\maximize\" attributes, do not emit \"(maximize)\" or\n");
log(" \"(minimize)\" in the SMT-LIBv2, and generally make no attempt to optimize anything.\n");
log("\n");
log(" -nobisection\n");
log(" If a wire is marked with the \"\\minimize\" or \"\\maximize\" attribute, do not\n");
log(" attempt to optimize that value with the default iterated solving and threshold\n");
log(" bisection approach. Instead, have yosys-smtbmc emit a \"(minimize)\" or \"(maximize)\"\n");
log(" command in the SMT-LIBv2 output and hope that the solver supports optimizing\n");
log(" quantified bitvector problems.\n");
log("\n");
log(" -solver <solver>\n");
log(" Use a particular solver. Choose one of: \"z3\", \"yices\", and \"cvc4\".\n");
log(" (default: yices)\n");
log("\n");
log(" -timeout <value>\n");
log(" Set the per-iteration timeout in seconds.\n");
log(" (default: no timeout)\n");
log("\n");
log(" -O0, -O1, -O2\n");
log(" Control the use of ABC to simplify the QBF-SAT problem before solving.\n");
log("\n");
log(" -sat\n");
log(" Generate an error if the solver does not return \"sat\".\n");
log("\n");
log(" -unsat\n");
log(" Generate an error if the solver does not return \"unsat\".\n");
log("\n");
log(" -show-smtbmc\n");
log(" Print the output from yosys-smtbmc.\n");
log("\n");
log(" -specialize\n");
log(" If the problem is satisfiable, replace each \"$anyconst\" cell with its\n");
log(" corresponding constant value from the model produced by the solver.\n");
log("\n");
log(" -specialize-from-file <solution file>\n");
log(" Do not run the solver, but instead only attempt to replace each \"$anyconst\"\n");
log(" cell in the current module with a constant value provided by the specified file.\n");
log("\n");
log(" -write-solution <solution file>\n");
log(" If the problem is satisfiable, write the corresponding constant value for each\n");
log(" \"$anyconst\" cell from the model produced by the solver to the specified file.");
log("\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
log_header(design, "Executing QBFSAT pass (solving QBF-SAT problems in the circuit).\n");
QbfSolveOptions opt = parse_args(args);
extra_args(args, opt.argidx, design);
RTLIL::Module *module = nullptr;
for (auto mod : design->selected_modules()) {
if (module)
log_cmd_error("Only one module must be selected for the QBF-SAT pass! (selected: %s and %s)\n", log_id(module), log_id(mod));
module = mod;
}
if (module == nullptr)
log_cmd_error("Can't perform QBF-SAT on an empty selection!\n");
log_push();
if (!opt.specialize_from_file) {
//Save the design to restore after modiyfing the current module.
std::string module_name = module->name.str();
QbfSolutionType ret = qbf_solve(module, opt);
module = design->module(module_name);
if (ret.unknown) {
if (opt.sat || opt.unsat)
log_cmd_error("expected problem to be %s\n", opt.sat? "SAT" : "UNSAT");
}
else if (ret.sat) {
print_qed();
if (opt.write_solution) {
ret.write_solution(module, opt.write_soln_soln_file);
}
if (opt.specialize) {
specialize(module, ret);
} else {
ret.dump_model(module);
}
if (opt.unsat)
log_cmd_error("expected problem to be UNSAT\n");
}
else {
print_proof_failed();
if (opt.sat)
log_cmd_error("expected problem to be SAT\n");
}
} else
specialize_from_file(module, opt.specialize_soln_file);
log_pop();
}
} QbfSatPass;
PRIVATE_NAMESPACE_END
|
#include "MotorFaultView.h"
namespace
{
int HEIGHT = 25;
int WIDTH = 665;
QString ERROR_STYLESHEET = "font: 20px 'Arial';\nfont-weight:500;color:#5690A1; margin-left: 10px;";
QString LIMIT_STYLESHEET = "font: 20px 'Arial';\nfont-weight:500;color:#8167BB; margin-left: 10px;";
QString SCROLLBAR_STYLESHEET = "QScrollBar:vertical {"
" background:rgba(83, 83, 84);"
" width:10px; "
" margin: 0px 0px 0px 0px;"
"}"
"QScrollBar::handle:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(255, 192, 33), stop: 0.5 rgb(255, 192, 33), stop:1 rgb(255, 192, 33));"
" min-height: 0px;"
" border-radius: 5px;"
"}"
"QScrollBar::add-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(255, 192, 33), stop: 0.5 rgb(255, 192, 33), stop:1 rgb(255, 192, 33));"
" height: 0px;"
" subcontrol-position: bottom;"
" subcontrol-origin: margin;"
"}"
"QScrollBar::sub-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(255, 192, 33), stop: 0.5 rgb(255, 192, 33), stop:1 rgb(255, 192, 33));"
" height: 0 px;"
" subcontrol-position: top;"
" subcontrol-origin: margin;"
"}";
int LABEL_RESIZE_LIMIT = 5;
}
MotorFaultView::MotorFaultView(MotorFaultsPresenter& motorFaultsPresenter,
BatteryFaultsPresenter& batteryFaultsPresenter,
I_MotorFaultUi& ui)
: motorFaultsPresenter_(motorFaultsPresenter)
, batteryFaultsPresenter_(batteryFaultsPresenter)
, ui_(ui)
, badMotorPositionHallSequence0Fault_("Bad Motor Position Hall Sequence Error")
, configReadError0Fault_("Config Read Error")
, dcBusOverVoltage0Fault_("DC Bus Over Voltage Error")
, desaturationFault0Fault_("Desaturation Fault Error")
, motorOverSpeed0Fault_("Motor Over Speed Error")
, railUnderVoltageLockOut0Fault_("Rail Under Voltage Lockout Error")
, watchdogCausedLastReset0Fault_("Watchdog Caused Last Reset Error")
, softwareOverCurrent0Fault_("Software Over Current Error")
, busCurrentLimit0Fault_("Bus Current Limit")
, busVoltageUpperLimit0Fault_("Bus Voltage Upper Limit")
, busVoltageLowerLimit0Fault_ ("Bus Voltage Lower Limit")
, ipmOrMotorTelemetryLimit0Fault_ ("IPM or Motor Telemetry Limit")
, motorCurrentLimit0Fault_ ("Motor Current Limit")
, outputVoltagePwmLimit0Fault_ ("Output Voltage PWM Limit")
, velocityLimit0Fault_ ("Velocity Limit")
, label0Count_(0)
, badMotorPositionHallSequence1Fault_("Bad Motor Position Hall Sequence Error")
, configReadError1Fault_("Config Read Error")
, dcBusOverVoltage1Fault_("DC Bus Over Voltage Error")
, desaturationFault1Fault_("Desaturation Fault Error")
, motorOverSpeed1Fault_("Motor Over Speed Error")
, railUnderVoltageLockOut1Fault_("Rail Under Voltage Lockout Error")
, watchdogCausedLastReset1Fault_("Watchdog Caused Last Reset Error")
, softwareOverCurrent1Fault_("Software Over Current Error")
, busCurrentLimit1Fault_("Bus Current Limit")
, busVoltageUpperLimit1Fault_("Bus Voltage Upper Limit")
, busVoltageLowerLimit1Fault_ ("Bus Voltage Lower Limit")
, ipmOrMotorTelemetryLimit1Fault_ ("IPM or Motor Telemetry Limit")
, motorCurrentLimit1Fault_ ("Motor Current Limit")
, outputVoltagePwmLimit1Fault_ ("Output Voltage PWM Limit")
, velocityLimit1Fault_ ("Velocity Limit")
, label1Count_(0)
, alwaysOnSupplyFault_ ("Always On Supply Fault")
, canbusCommunicationsFault_ ("CAN Bus Communications Fault")
, chargeLimitEnforcementFault_ ("Charge Limit Enforcement Fault")
, chargerSafetyRelayFault_ ("Charger Safety Relay Fault")
, currentSensorFault_ ("Current Sensor Fault")
, dischargeLimitEnforcementFault_ ("Discharge Limit Enforcement Fault")
, fanMonitorFault_ ("Fan Monitor Fault")
, highVoltageIsolationFault_ ("High Voltage Isolation Fault")
, internalCommununicationFault_ ("Internal Communication Fault")
, internalConversionFault_ ("Internal Conversion Fault")
, internalLogicFault_ ("Internal Logic Fault")
, internalMemoryFault_ ("Internal Memory Fault")
, internalThermistorFault_ ("Internal Thermistor Fault")
, lowCellVoltageFault_ ("Low Cell Voltage Fault")
, openWiringFault_ ("Open Wiring Fault")
, packVoltageSensorFault_ ("Pack Voltage Sensor Fault")
, powerSupplyFault12V_ ("12V Power Supply Fault")
, thermistorFault_ ("Thermistor Fault")
, voltageRedundancyFault_ ("Voltage Redundancy Fault")
, weakCellFault_ ("Weak Cell Fault")
, weakPackFault_ ("Weak Pack Fault")
, cclReducedDueToAlternateCurrentLimit_ ("CCL Reduced Due To Alternate Current")
, cclReducedDueToChargerLatch_ ("CCL Reduced Due To Charger Latch")
, cclReducedDueToHighCellResistance_ ("CCL Reduced Due To High Cell Resistance")
, cclReducedDueToHighCellVoltage_ ("CCL Reduced Due To High Cell Voltage")
, cclReducedDueToHighPackVoltage_ ("CCL Reduced Due To High Pack Voltage")
, cclReducedDueToHighSoc_ ("CCL Reduced Due To High SOC")
, cclReducedDueToTemperature_ ("CCL Reduced Due To Temperature")
, dclandCclReducedDueToCommunicationFailsafe_ ("DCL and CCL Reduced Due To Communication Fail Safe")
, dclandCclReducedDueToVoltageFailsafe_ ("DCL and CCL Reduced Due To Voltage Fail Safe")
, dclReducedDueToHighCellResistance_ ("DCL Reduced Due To High Cell Resistance")
, dclReducedDueToLowCellVoltage_ ("DCL Reduced Due To Low Cell Voltage")
, dclReducedDueToLowPackVoltage_ ("DCL Reduced Due To Low Pack Voltage")
, dclReducedDueToLowSoc_ ("DCL Reduced Due To Low SOC")
, dclReducedDueToTemperature_ ("DCL Reduced Due To Temperature")
, labelBCount_ (0)
{
// Setting up Vertical bar
QScrollBar* verticalBar0 = new QScrollBar();
QScrollBar* verticalBar1 = new QScrollBar();
QScrollBar* verticalBarB = new QScrollBar();
verticalBar0->setStyleSheet(SCROLLBAR_STYLESHEET);
verticalBar1->setStyleSheet(SCROLLBAR_STYLESHEET);
verticalBarB->setStyleSheet(SCROLLBAR_STYLESHEET);
ui_.motor0ScrollArea().setVerticalScrollBar(verticalBar0);
ui_.motor1ScrollArea().setVerticalScrollBar(verticalBar1);
ui_.batteryScrollArea().setVerticalScrollBar(verticalBarB);
QLayout* layout0 = ui_.motor0ContentsWidget().layout();
QLayout* layout1 = ui_.motor1ContentsWidget().layout();
QLayout* layoutB = ui_.batteryContentsWidget().layout();
// Motor 0
initializeLabel(badMotorPositionHallSequence0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(configReadError0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(dcBusOverVoltage0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(desaturationFault0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(motorOverSpeed0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(railUnderVoltageLockOut0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(watchdogCausedLastReset0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(softwareOverCurrent0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(busCurrentLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(busVoltageLowerLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(busVoltageUpperLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(ipmOrMotorTelemetryLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(motorCurrentLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(outputVoltagePwmLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(velocityLimit0Fault_, layout0, LIMIT_STYLESHEET);
// Motor 1
initializeLabel(badMotorPositionHallSequence1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(configReadError1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(dcBusOverVoltage1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(desaturationFault1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(motorOverSpeed1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(railUnderVoltageLockOut1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(watchdogCausedLastReset1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(softwareOverCurrent1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(busCurrentLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(busVoltageLowerLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(busVoltageUpperLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(ipmOrMotorTelemetryLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(motorCurrentLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(outputVoltagePwmLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(velocityLimit1Fault_, layout1, LIMIT_STYLESHEET);
// Battery
initializeLabel(alwaysOnSupplyFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(canbusCommunicationsFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(chargeLimitEnforcementFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(chargerSafetyRelayFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(currentSensorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(dischargeLimitEnforcementFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(fanMonitorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(highVoltageIsolationFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalCommununicationFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalConversionFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalLogicFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalMemoryFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalThermistorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(lowCellVoltageFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(openWiringFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(packVoltageSensorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(powerSupplyFault12V_, layoutB, ERROR_STYLESHEET);
initializeLabel(thermistorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(voltageRedundancyFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(weakCellFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(weakPackFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(cclReducedDueToAlternateCurrentLimit_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToChargerLatch_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighCellResistance_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighCellVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighPackVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighSoc_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToTemperature_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclandCclReducedDueToCommunicationFailsafe_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclandCclReducedDueToVoltageFailsafe_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToHighCellResistance_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToLowCellVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToLowPackVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToLowSoc_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToTemperature_, layoutB, LIMIT_STYLESHEET);
ui_.motor0ContentsWidget().setLayout(layout0);
ui_.motor1ContentsWidget().setLayout(layout1);
ui_.batteryContentsWidget().setLayout(layoutB);
connectMotorFaults(motorFaultsPresenter_);
connectBatteryFaults(batteryFaultsPresenter_);
}
MotorFaultView::~MotorFaultView()
{
}
void MotorFaultView::initializeLabel(QLabel& label, QLayout*& layout, QString& styleSheet)
{
label.resize(WIDTH, HEIGHT);
label.setStyleSheet(styleSheet);
label.setFixedSize(WIDTH, HEIGHT);
layout->addWidget(&label);
label.hide();
}
void MotorFaultView::updateLabel(const bool& receivedValue, QLabel& label, QWidget& contentsWidget, int& labelCount)
{
if (receivedValue)
{
if (!label.isVisible())
{
labelCount++;
if (labelCount >= LABEL_RESIZE_LIMIT)
{
contentsWidget.setFixedSize(contentsWidget.width(), contentsWidget.height() + HEIGHT);
}
label.show();
}
}
else
{
if (label.isVisible())
{
if (labelCount >= LABEL_RESIZE_LIMIT)
{
contentsWidget.setFixedSize(contentsWidget.width(), contentsWidget.height() - HEIGHT);
}
labelCount--;
label.hide();
}
}
}
void MotorFaultView::connectMotorFaults(MotorFaultsPresenter& motorFaultsPresenter)
{
connect(&motorFaultsPresenter, SIGNAL(motorZeroErrorFlagsReceived(ErrorFlags)),
this, SLOT(motorZeroErrorFlagsReceived(ErrorFlags)));
connect(&motorFaultsPresenter, SIGNAL(motorZeroLimitFlagsReceived(LimitFlags)),
this, SLOT(motorZeroLimitFlagsReceived(LimitFlags)));
connect(&motorFaultsPresenter, SIGNAL(motorOneErrorFlagsReceived(ErrorFlags)),
this, SLOT(motorOneErrorFlagsReceived(ErrorFlags)));
connect(&motorFaultsPresenter, SIGNAL(motorOneLimitFlagsReceived(LimitFlags)),
this, SLOT(motorOneLimitFlagsReceived(LimitFlags)));
}
void MotorFaultView::connectBatteryFaults(BatteryFaultsPresenter& batteryFaultsPresenter)
{
connect(&batteryFaultsPresenter, SIGNAL(errorFlagsReceived(BatteryErrorFlags)),
this, SLOT(errorFlagsReceived(BatteryErrorFlags)));
connect(&batteryFaultsPresenter, SIGNAL(limitFlagsReceived(BatteryLimitFlags)),
this, SLOT(limitFlagsReceived(BatteryLimitFlags)));
}
void MotorFaultView::motorZeroErrorFlagsReceived(ErrorFlags motorZeroErrorFlags)
{
updateLabel(motorZeroErrorFlags.badMotorPositionHallSequence(), badMotorPositionHallSequence0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.configReadError(), configReadError0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.dcBusOverVoltage(), dcBusOverVoltage0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.desaturationFault(), desaturationFault0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.motorOverSpeed(), motorOverSpeed0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.railUnderVoltageLockOut(), railUnderVoltageLockOut0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.watchdogCausedLastReset(), watchdogCausedLastReset0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.softwareOverCurrent(), softwareOverCurrent0Fault_, ui_.motor0ContentsWidget(), label0Count_);
}
void MotorFaultView::motorZeroLimitFlagsReceived(LimitFlags motorZeroLimitFlags)
{
updateLabel(motorZeroLimitFlags.busCurrentLimit(), busCurrentLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.busVoltageUpperLimit(), busVoltageUpperLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.busVoltageLowerLimit(), busVoltageLowerLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.ipmOrMotorTelemetryLimit(), ipmOrMotorTelemetryLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.motorCurrentLimit(), motorCurrentLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.outputVoltagePwmLimit(), outputVoltagePwmLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.velocityLimit(), velocityLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
}
void MotorFaultView::motorOneErrorFlagsReceived(ErrorFlags motorOneErrorFlags)
{
updateLabel(motorOneErrorFlags.badMotorPositionHallSequence(), badMotorPositionHallSequence1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.configReadError(), configReadError1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.dcBusOverVoltage(), dcBusOverVoltage1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.desaturationFault(), desaturationFault1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.motorOverSpeed(), motorOverSpeed1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.railUnderVoltageLockOut(), railUnderVoltageLockOut1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.watchdogCausedLastReset(), watchdogCausedLastReset1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.softwareOverCurrent(), softwareOverCurrent1Fault_, ui_.motor1ContentsWidget(), label1Count_);
}
void MotorFaultView::motorOneLimitFlagsReceived(LimitFlags motorOneLimitFlags)
{
updateLabel(motorOneLimitFlags.busCurrentLimit(), busCurrentLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.busVoltageUpperLimit(), busVoltageUpperLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.busVoltageLowerLimit(), busVoltageLowerLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.ipmOrMotorTelemetryLimit(), ipmOrMotorTelemetryLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.motorCurrentLimit(), motorCurrentLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.outputVoltagePwmLimit(), outputVoltagePwmLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.velocityLimit(), velocityLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
}
void MotorFaultView::errorFlagsReceived(BatteryErrorFlags batteryErrorFlags)
{
updateLabel(batteryErrorFlags.alwaysOnSupplyFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.canbusCommunicationsFault(), canbusCommunicationsFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.chargeLimitEnforcementFault(), chargeLimitEnforcementFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.chargerSafetyRelayFault(), chargerSafetyRelayFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.currentSensorFault(), currentSensorFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.dischargeLimitEnforcementFault(), dischargeLimitEnforcementFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.fanMonitorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.highVoltageIsolationFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalCommununicationFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalConversionFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalLogicFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalMemoryFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalThermistorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.lowCellVoltageFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.openWiringFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.packVoltageSensorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.powerSupplyFault12V(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.thermistorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.voltageRedundancyFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.weakCellFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.weakPackFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
}
void MotorFaultView::limitFlagsReceived(BatteryLimitFlags batteryLimitFlags)
{
updateLabel(batteryLimitFlags.cclReducedDueToAlternateCurrentLimit(), cclReducedDueToAlternateCurrentLimit_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToChargerLatch(), cclReducedDueToChargerLatch_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighCellResistance(), cclReducedDueToHighCellResistance_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighCellVoltage(), cclReducedDueToHighCellVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighPackVoltage(), cclReducedDueToHighPackVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighSoc(), cclReducedDueToHighSoc_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToTemperature(), cclReducedDueToTemperature_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclandCclReducedDueToCommunicationFailsafe(), dclandCclReducedDueToCommunicationFailsafe_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclandCclReducedDueToVoltageFailsafe(), dclandCclReducedDueToVoltageFailsafe_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToHighCellResistance(), dclReducedDueToHighCellResistance_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToLowCellVoltage(), dclReducedDueToLowCellVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToLowPackVoltage(), dclReducedDueToLowPackVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToLowSoc(), dclReducedDueToLowSoc_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToTemperature(), dclReducedDueToTemperature_, ui_.batteryContentsWidget(), labelBCount_);
}
Made label colours lighter
#include "MotorFaultView.h"
namespace
{
int HEIGHT = 25;
int WIDTH = 665;
QString ERROR_STYLESHEET = "font: 20px 'Arial';\nfont-weight:500;color:#89c2d3; margin-left: 10px;";
QString LIMIT_STYLESHEET = "font: 20px 'Arial';\nfont-weight:500;color:#a18cce; margin-left: 10px;";
QString SCROLLBAR_STYLESHEET = "QScrollBar:vertical {"
" background:rgba(83, 83, 84);"
" width:10px; "
" margin: 0px 0px 0px 0px;"
"}"
"QScrollBar::handle:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(255, 192, 33), stop: 0.5 rgb(255, 192, 33), stop:1 rgb(255, 192, 33));"
" min-height: 0px;"
" border-radius: 5px;"
"}"
"QScrollBar::add-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(255, 192, 33), stop: 0.5 rgb(255, 192, 33), stop:1 rgb(255, 192, 33));"
" height: 0px;"
" subcontrol-position: bottom;"
" subcontrol-origin: margin;"
"}"
"QScrollBar::sub-line:vertical {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop: 0 rgb(255, 192, 33), stop: 0.5 rgb(255, 192, 33), stop:1 rgb(255, 192, 33));"
" height: 0 px;"
" subcontrol-position: top;"
" subcontrol-origin: margin;"
"}";
int LABEL_RESIZE_LIMIT = 5;
}
MotorFaultView::MotorFaultView(MotorFaultsPresenter& motorFaultsPresenter,
BatteryFaultsPresenter& batteryFaultsPresenter,
I_MotorFaultUi& ui)
: motorFaultsPresenter_(motorFaultsPresenter)
, batteryFaultsPresenter_(batteryFaultsPresenter)
, ui_(ui)
, badMotorPositionHallSequence0Fault_("Bad Motor Position Hall Sequence Error")
, configReadError0Fault_("Config Read Error")
, dcBusOverVoltage0Fault_("DC Bus Over Voltage Error")
, desaturationFault0Fault_("Desaturation Fault Error")
, motorOverSpeed0Fault_("Motor Over Speed Error")
, railUnderVoltageLockOut0Fault_("Rail Under Voltage Lockout Error")
, watchdogCausedLastReset0Fault_("Watchdog Caused Last Reset Error")
, softwareOverCurrent0Fault_("Software Over Current Error")
, busCurrentLimit0Fault_("Bus Current Limit")
, busVoltageUpperLimit0Fault_("Bus Voltage Upper Limit")
, busVoltageLowerLimit0Fault_ ("Bus Voltage Lower Limit")
, ipmOrMotorTelemetryLimit0Fault_ ("IPM or Motor Telemetry Limit")
, motorCurrentLimit0Fault_ ("Motor Current Limit")
, outputVoltagePwmLimit0Fault_ ("Output Voltage PWM Limit")
, velocityLimit0Fault_ ("Velocity Limit")
, label0Count_(0)
, badMotorPositionHallSequence1Fault_("Bad Motor Position Hall Sequence Error")
, configReadError1Fault_("Config Read Error")
, dcBusOverVoltage1Fault_("DC Bus Over Voltage Error")
, desaturationFault1Fault_("Desaturation Fault Error")
, motorOverSpeed1Fault_("Motor Over Speed Error")
, railUnderVoltageLockOut1Fault_("Rail Under Voltage Lockout Error")
, watchdogCausedLastReset1Fault_("Watchdog Caused Last Reset Error")
, softwareOverCurrent1Fault_("Software Over Current Error")
, busCurrentLimit1Fault_("Bus Current Limit")
, busVoltageUpperLimit1Fault_("Bus Voltage Upper Limit")
, busVoltageLowerLimit1Fault_ ("Bus Voltage Lower Limit")
, ipmOrMotorTelemetryLimit1Fault_ ("IPM or Motor Telemetry Limit")
, motorCurrentLimit1Fault_ ("Motor Current Limit")
, outputVoltagePwmLimit1Fault_ ("Output Voltage PWM Limit")
, velocityLimit1Fault_ ("Velocity Limit")
, label1Count_(0)
, alwaysOnSupplyFault_ ("Always On Supply Fault")
, canbusCommunicationsFault_ ("CAN Bus Communications Fault")
, chargeLimitEnforcementFault_ ("Charge Limit Enforcement Fault")
, chargerSafetyRelayFault_ ("Charger Safety Relay Fault")
, currentSensorFault_ ("Current Sensor Fault")
, dischargeLimitEnforcementFault_ ("Discharge Limit Enforcement Fault")
, fanMonitorFault_ ("Fan Monitor Fault")
, highVoltageIsolationFault_ ("High Voltage Isolation Fault")
, internalCommununicationFault_ ("Internal Communication Fault")
, internalConversionFault_ ("Internal Conversion Fault")
, internalLogicFault_ ("Internal Logic Fault")
, internalMemoryFault_ ("Internal Memory Fault")
, internalThermistorFault_ ("Internal Thermistor Fault")
, lowCellVoltageFault_ ("Low Cell Voltage Fault")
, openWiringFault_ ("Open Wiring Fault")
, packVoltageSensorFault_ ("Pack Voltage Sensor Fault")
, powerSupplyFault12V_ ("12V Power Supply Fault")
, thermistorFault_ ("Thermistor Fault")
, voltageRedundancyFault_ ("Voltage Redundancy Fault")
, weakCellFault_ ("Weak Cell Fault")
, weakPackFault_ ("Weak Pack Fault")
, cclReducedDueToAlternateCurrentLimit_ ("CCL Reduced Due To Alternate Current")
, cclReducedDueToChargerLatch_ ("CCL Reduced Due To Charger Latch")
, cclReducedDueToHighCellResistance_ ("CCL Reduced Due To High Cell Resistance")
, cclReducedDueToHighCellVoltage_ ("CCL Reduced Due To High Cell Voltage")
, cclReducedDueToHighPackVoltage_ ("CCL Reduced Due To High Pack Voltage")
, cclReducedDueToHighSoc_ ("CCL Reduced Due To High SOC")
, cclReducedDueToTemperature_ ("CCL Reduced Due To Temperature")
, dclandCclReducedDueToCommunicationFailsafe_ ("DCL and CCL Reduced Due To Communication Fail Safe")
, dclandCclReducedDueToVoltageFailsafe_ ("DCL and CCL Reduced Due To Voltage Fail Safe")
, dclReducedDueToHighCellResistance_ ("DCL Reduced Due To High Cell Resistance")
, dclReducedDueToLowCellVoltage_ ("DCL Reduced Due To Low Cell Voltage")
, dclReducedDueToLowPackVoltage_ ("DCL Reduced Due To Low Pack Voltage")
, dclReducedDueToLowSoc_ ("DCL Reduced Due To Low SOC")
, dclReducedDueToTemperature_ ("DCL Reduced Due To Temperature")
, labelBCount_ (0)
{
// Setting up Vertical bar
QScrollBar* verticalBar0 = new QScrollBar();
QScrollBar* verticalBar1 = new QScrollBar();
QScrollBar* verticalBarB = new QScrollBar();
verticalBar0->setStyleSheet(SCROLLBAR_STYLESHEET);
verticalBar1->setStyleSheet(SCROLLBAR_STYLESHEET);
verticalBarB->setStyleSheet(SCROLLBAR_STYLESHEET);
ui_.motor0ScrollArea().setVerticalScrollBar(verticalBar0);
ui_.motor1ScrollArea().setVerticalScrollBar(verticalBar1);
ui_.batteryScrollArea().setVerticalScrollBar(verticalBarB);
QLayout* layout0 = ui_.motor0ContentsWidget().layout();
QLayout* layout1 = ui_.motor1ContentsWidget().layout();
QLayout* layoutB = ui_.batteryContentsWidget().layout();
// Motor 0
initializeLabel(badMotorPositionHallSequence0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(configReadError0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(dcBusOverVoltage0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(desaturationFault0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(motorOverSpeed0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(railUnderVoltageLockOut0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(watchdogCausedLastReset0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(softwareOverCurrent0Fault_, layout0, ERROR_STYLESHEET);
initializeLabel(busCurrentLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(busVoltageLowerLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(busVoltageUpperLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(ipmOrMotorTelemetryLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(motorCurrentLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(outputVoltagePwmLimit0Fault_, layout0, LIMIT_STYLESHEET);
initializeLabel(velocityLimit0Fault_, layout0, LIMIT_STYLESHEET);
// Motor 1
initializeLabel(badMotorPositionHallSequence1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(configReadError1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(dcBusOverVoltage1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(desaturationFault1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(motorOverSpeed1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(railUnderVoltageLockOut1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(watchdogCausedLastReset1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(softwareOverCurrent1Fault_, layout1, ERROR_STYLESHEET);
initializeLabel(busCurrentLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(busVoltageLowerLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(busVoltageUpperLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(ipmOrMotorTelemetryLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(motorCurrentLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(outputVoltagePwmLimit1Fault_, layout1, LIMIT_STYLESHEET);
initializeLabel(velocityLimit1Fault_, layout1, LIMIT_STYLESHEET);
// Battery
initializeLabel(alwaysOnSupplyFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(canbusCommunicationsFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(chargeLimitEnforcementFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(chargerSafetyRelayFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(currentSensorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(dischargeLimitEnforcementFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(fanMonitorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(highVoltageIsolationFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalCommununicationFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalConversionFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalLogicFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalMemoryFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(internalThermistorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(lowCellVoltageFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(openWiringFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(packVoltageSensorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(powerSupplyFault12V_, layoutB, ERROR_STYLESHEET);
initializeLabel(thermistorFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(voltageRedundancyFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(weakCellFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(weakPackFault_, layoutB, ERROR_STYLESHEET);
initializeLabel(cclReducedDueToAlternateCurrentLimit_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToChargerLatch_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighCellResistance_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighCellVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighPackVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToHighSoc_, layoutB, LIMIT_STYLESHEET);
initializeLabel(cclReducedDueToTemperature_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclandCclReducedDueToCommunicationFailsafe_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclandCclReducedDueToVoltageFailsafe_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToHighCellResistance_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToLowCellVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToLowPackVoltage_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToLowSoc_, layoutB, LIMIT_STYLESHEET);
initializeLabel(dclReducedDueToTemperature_, layoutB, LIMIT_STYLESHEET);
ui_.motor0ContentsWidget().setLayout(layout0);
ui_.motor1ContentsWidget().setLayout(layout1);
ui_.batteryContentsWidget().setLayout(layoutB);
connectMotorFaults(motorFaultsPresenter_);
connectBatteryFaults(batteryFaultsPresenter_);
ErrorFlags teste;
teste.setBadMotorPositionHallSequence(true);
LimitFlags testl;
testl.setBusCurrentLimit(true);
motorZeroErrorFlagsReceived(teste);
motorZeroLimitFlagsReceived(testl);
}
MotorFaultView::~MotorFaultView()
{
}
void MotorFaultView::initializeLabel(QLabel& label, QLayout*& layout, QString& styleSheet)
{
label.resize(WIDTH, HEIGHT);
label.setStyleSheet(styleSheet);
label.setFixedSize(WIDTH, HEIGHT);
layout->addWidget(&label);
label.hide();
}
void MotorFaultView::updateLabel(const bool& receivedValue, QLabel& label, QWidget& contentsWidget, int& labelCount)
{
if (receivedValue)
{
if (!label.isVisible())
{
labelCount++;
if (labelCount >= LABEL_RESIZE_LIMIT)
{
contentsWidget.setFixedSize(contentsWidget.width(), contentsWidget.height() + HEIGHT);
}
label.show();
}
}
else
{
if (label.isVisible())
{
if (labelCount >= LABEL_RESIZE_LIMIT)
{
contentsWidget.setFixedSize(contentsWidget.width(), contentsWidget.height() - HEIGHT);
}
labelCount--;
label.hide();
}
}
}
void MotorFaultView::connectMotorFaults(MotorFaultsPresenter& motorFaultsPresenter)
{
connect(&motorFaultsPresenter, SIGNAL(motorZeroErrorFlagsReceived(ErrorFlags)),
this, SLOT(motorZeroErrorFlagsReceived(ErrorFlags)));
connect(&motorFaultsPresenter, SIGNAL(motorZeroLimitFlagsReceived(LimitFlags)),
this, SLOT(motorZeroLimitFlagsReceived(LimitFlags)));
connect(&motorFaultsPresenter, SIGNAL(motorOneErrorFlagsReceived(ErrorFlags)),
this, SLOT(motorOneErrorFlagsReceived(ErrorFlags)));
connect(&motorFaultsPresenter, SIGNAL(motorOneLimitFlagsReceived(LimitFlags)),
this, SLOT(motorOneLimitFlagsReceived(LimitFlags)));
}
void MotorFaultView::connectBatteryFaults(BatteryFaultsPresenter& batteryFaultsPresenter)
{
connect(&batteryFaultsPresenter, SIGNAL(errorFlagsReceived(BatteryErrorFlags)),
this, SLOT(errorFlagsReceived(BatteryErrorFlags)));
connect(&batteryFaultsPresenter, SIGNAL(limitFlagsReceived(BatteryLimitFlags)),
this, SLOT(limitFlagsReceived(BatteryLimitFlags)));
}
void MotorFaultView::motorZeroErrorFlagsReceived(ErrorFlags motorZeroErrorFlags)
{
updateLabel(motorZeroErrorFlags.badMotorPositionHallSequence(), badMotorPositionHallSequence0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.configReadError(), configReadError0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.dcBusOverVoltage(), dcBusOverVoltage0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.desaturationFault(), desaturationFault0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.motorOverSpeed(), motorOverSpeed0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.railUnderVoltageLockOut(), railUnderVoltageLockOut0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.watchdogCausedLastReset(), watchdogCausedLastReset0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroErrorFlags.softwareOverCurrent(), softwareOverCurrent0Fault_, ui_.motor0ContentsWidget(), label0Count_);
}
void MotorFaultView::motorZeroLimitFlagsReceived(LimitFlags motorZeroLimitFlags)
{
updateLabel(motorZeroLimitFlags.busCurrentLimit(), busCurrentLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.busVoltageUpperLimit(), busVoltageUpperLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.busVoltageLowerLimit(), busVoltageLowerLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.ipmOrMotorTelemetryLimit(), ipmOrMotorTelemetryLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.motorCurrentLimit(), motorCurrentLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.outputVoltagePwmLimit(), outputVoltagePwmLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
updateLabel(motorZeroLimitFlags.velocityLimit(), velocityLimit0Fault_, ui_.motor0ContentsWidget(), label0Count_);
}
void MotorFaultView::motorOneErrorFlagsReceived(ErrorFlags motorOneErrorFlags)
{
updateLabel(motorOneErrorFlags.badMotorPositionHallSequence(), badMotorPositionHallSequence1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.configReadError(), configReadError1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.dcBusOverVoltage(), dcBusOverVoltage1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.desaturationFault(), desaturationFault1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.motorOverSpeed(), motorOverSpeed1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.railUnderVoltageLockOut(), railUnderVoltageLockOut1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.watchdogCausedLastReset(), watchdogCausedLastReset1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneErrorFlags.softwareOverCurrent(), softwareOverCurrent1Fault_, ui_.motor1ContentsWidget(), label1Count_);
}
void MotorFaultView::motorOneLimitFlagsReceived(LimitFlags motorOneLimitFlags)
{
updateLabel(motorOneLimitFlags.busCurrentLimit(), busCurrentLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.busVoltageUpperLimit(), busVoltageUpperLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.busVoltageLowerLimit(), busVoltageLowerLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.ipmOrMotorTelemetryLimit(), ipmOrMotorTelemetryLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.motorCurrentLimit(), motorCurrentLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.outputVoltagePwmLimit(), outputVoltagePwmLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
updateLabel(motorOneLimitFlags.velocityLimit(), velocityLimit1Fault_, ui_.motor1ContentsWidget(), label1Count_);
}
void MotorFaultView::errorFlagsReceived(BatteryErrorFlags batteryErrorFlags)
{
updateLabel(batteryErrorFlags.alwaysOnSupplyFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.canbusCommunicationsFault(), canbusCommunicationsFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.chargeLimitEnforcementFault(), chargeLimitEnforcementFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.chargerSafetyRelayFault(), chargerSafetyRelayFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.currentSensorFault(), currentSensorFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.dischargeLimitEnforcementFault(), dischargeLimitEnforcementFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.fanMonitorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.highVoltageIsolationFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalCommununicationFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalConversionFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalLogicFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalMemoryFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.internalThermistorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.lowCellVoltageFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.openWiringFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.packVoltageSensorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.powerSupplyFault12V(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.thermistorFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.voltageRedundancyFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.weakCellFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryErrorFlags.weakPackFault(), alwaysOnSupplyFault_, ui_.batteryContentsWidget(), labelBCount_);
}
void MotorFaultView::limitFlagsReceived(BatteryLimitFlags batteryLimitFlags)
{
updateLabel(batteryLimitFlags.cclReducedDueToAlternateCurrentLimit(), cclReducedDueToAlternateCurrentLimit_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToChargerLatch(), cclReducedDueToChargerLatch_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighCellResistance(), cclReducedDueToHighCellResistance_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighCellVoltage(), cclReducedDueToHighCellVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighPackVoltage(), cclReducedDueToHighPackVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToHighSoc(), cclReducedDueToHighSoc_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.cclReducedDueToTemperature(), cclReducedDueToTemperature_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclandCclReducedDueToCommunicationFailsafe(), dclandCclReducedDueToCommunicationFailsafe_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclandCclReducedDueToVoltageFailsafe(), dclandCclReducedDueToVoltageFailsafe_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToHighCellResistance(), dclReducedDueToHighCellResistance_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToLowCellVoltage(), dclReducedDueToLowCellVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToLowPackVoltage(), dclReducedDueToLowPackVoltage_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToLowSoc(), dclReducedDueToLowSoc_, ui_.batteryContentsWidget(), labelBCount_);
updateLabel(batteryLimitFlags.dclReducedDueToTemperature(), dclReducedDueToTemperature_, ui_.batteryContentsWidget(), labelBCount_);
}
|
/*************************************************************************
*
* $RCSfile: breakiteratorImpl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: er $ $Date: 2002-03-26 16:55:00 $
*
* 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 EXPRESSED 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): _______________________________________
*
*
************************************************************************/
#include <breakiteratorImpl.hxx>
#include <unicode.hxx>
#include <rtl/ustrbuf.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
BreakIteratorImpl::BreakIteratorImpl( const Reference < XMultiServiceFactory >& rxMSF ) : xMSF( rxMSF )
{
}
BreakIteratorImpl::BreakIteratorImpl()
{
}
BreakIteratorImpl::~BreakIteratorImpl()
{
// Clear lookuptable
for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();
listItem; listItem = (lookupTableItem*)lookupTable.Next())
delete listItem;
lookupTable.Clear();
}
static ScriptTypeList CTLlist[] = {
{ UnicodeScript_kHebrew, UnicodeScript_kHebrew }, // 10,
{ UnicodeScript_kArabic, UnicodeScript_kArabic }, // 11,
{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari }, // 14,
{ UnicodeScript_kThai, UnicodeScript_kThai }, // 24,
{ UnicodeScript_kScriptCount, UnicodeScript_kScriptCount } // 88
};
// This method is a tmporary solution for CTL implementation, since writer is not passing right rLocale ye
// Unising the method has performance drawback, since it has to convert script type to Locale for every call.
const Locale& SAL_CALL
BreakIteratorImpl::getLocaleByScriptType(const Locale& rLocale, const OUString& Text,
sal_Int32 nStartPos, sal_Bool forward, sal_Bool skipWhiteSpace) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
sal_Char* language = NULL;
if (rLocale.Language.getLength() == 0)
language = "en";
if (!forward) nStartPos--;
if (skipWhiteSpace) {
if (forward)
while(nStartPos < len && unicode::isWhiteSpace(Text[nStartPos])) nStartPos++;
else
while(nStartPos >= 0 && unicode::isWhiteSpace(Text[nStartPos])) nStartPos--;
}
if (nStartPos >= 0 && nStartPos < len) {
switch(unicode::getUnicodeScriptType(Text[nStartPos], CTLlist )) {
case UnicodeScript_kThai: language = "th"; break;
case UnicodeScript_kArabic: language = "ar"; break;
case UnicodeScript_kHebrew: language = "he"; break;
case UnicodeScript_kDevanagari: language = "hi"; break;
}
}
if (language) {
static Locale locale;
locale.Language = OUString::createFromAscii(language);
return locale;
} else
return rLocale;
}
sal_Int32 SAL_CALL BreakIteratorImpl::nextCharacters( const OUString& Text, sal_Int32 nStartPos,
const Locale &rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone )
throw(RuntimeException)
{
if (nCount < 0) throw RuntimeException();
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_True,
sal_False))->nextCharacters( Text, nStartPos, rLocale, nCharacterIteratorMode, nCount, nDone);
}
sal_Int32 SAL_CALL BreakIteratorImpl::previousCharacters( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone )
throw(RuntimeException)
{
if (nCount < 0) throw RuntimeException();
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_False,
sal_False))->previousCharacters( Text, nStartPos, rLocale, nCharacterIteratorMode, nCount, nDone);
}
Boundary SAL_CALL BreakIteratorImpl::nextWord( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 rWordType ) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if( nStartPos < 0 || len == 0 ) {
result.endPos = result.startPos = 0;
return result;
} else if (nStartPos >= len) {
result.endPos = result.startPos = len;
return result;
}
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_True,
rWordType == WordType::ANYWORD_IGNOREWHITESPACES))->nextWord(Text, nStartPos, rLocale, rWordType);
}
static inline sal_Bool SAL_CALL isCJK( const Locale& rLocale ) {
return rLocale.Language.equalsAscii("zh") || rLocale.Language.equalsAscii("ja") || rLocale.Language.equalsAscii("ko");
}
Boundary SAL_CALL BreakIteratorImpl::previousWord( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 rWordType) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if( nStartPos <= 0 || len == 0 ) {
result.endPos = result.startPos = 0;
return result;
} else if (nStartPos > len) {
result.endPos = result.startPos = len;
return result;
}
if(rWordType == WordType::ANYWORD_IGNOREWHITESPACES || rWordType == WordType::DICTIONARY_WORD) {
sal_Int32 oPos = nStartPos;
while(nStartPos > 1 && unicode::isWhiteSpace(Text[nStartPos - 1])) nStartPos--;
if( !nStartPos ) {
result.startPos = result.endPos = nStartPos;
return result;
}
// if some spaces are skiped, and the script type is Asian with no CJK rLocale, we have to return
// (nStartPos, -1) for caller to send correct rLocale for loading correct dictionary.
if (oPos != nStartPos && !isCJK(rLocale) && getScriptClass(Text[nStartPos-1]) == ScriptType::ASIAN) {
result.startPos = nStartPos;
result.endPos = -1;
return result;
}
}
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_False,
sal_False))->previousWord(Text, nStartPos, rLocale, rWordType);
}
Boundary SAL_CALL BreakIteratorImpl::getWordBoundary( const OUString& Text, sal_Int32 nPos, const Locale& rLocale,
sal_Int16 rWordType, sal_Bool bDirection ) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if( nPos < 0 || len == 0 ) {
result.endPos = result.startPos = 0;
return result;
} else if (nPos > len) {
result.endPos = result.startPos = len;
return result;
}
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nPos, sal_True,
rWordType == WordType::ANYWORD_IGNOREWHITESPACES))->getWordBoundary(Text, nPos, rLocale, rWordType, bDirection);
}
sal_Bool SAL_CALL BreakIteratorImpl::isBeginWord( const OUString& Text, sal_Int32 nPos,
const Locale& rLocale, sal_Int16 rWordType ) throw(RuntimeException)
{
if (unicode::isWhiteSpace(Text[nPos])) return false;
result = getWordBoundary(Text, nPos, rLocale, rWordType, false);
return result.startPos == nPos;
}
sal_Bool SAL_CALL BreakIteratorImpl::isEndWord( const OUString& Text, sal_Int32 nPos,
const Locale& rLocale, sal_Int16 rWordType ) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if (nPos < 0 || nPos > len ||
rWordType == WordType::ANYWORD_IGNOREWHITESPACES && unicode::isWhiteSpace(Text[nPos]))
return false;
result = getWordBoundary(Text, nPos, rLocale, rWordType, false);
if (result.endPos == len && rWordType == WordType::ANYWORD_IGNOREWHITESPACES)
return false;
return (result.endPos == nPos && !unicode::isWhiteSpace(Text[result.startPos]));
}
sal_Int32 SAL_CALL BreakIteratorImpl::beginOfSentence( const OUString& Text, sal_Int32 nStartPos,
const Locale &rLocale ) throw(RuntimeException)
{
return getLocaleSpecificBreakIterator(rLocale)->beginOfSentence(Text, nStartPos, rLocale);
}
sal_Int32 SAL_CALL BreakIteratorImpl::endOfSentence( const OUString& Text, sal_Int32 nStartPos,
const Locale &rLocale ) throw(RuntimeException)
{
return getLocaleSpecificBreakIterator(rLocale)->endOfSentence(Text, nStartPos, rLocale);
}
LineBreakResults SAL_CALL BreakIteratorImpl::getLineBreak( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int32 nMinBreakPos, const LineBreakHyphenationOptions& hOptions,
const LineBreakUserOptions& bOptions ) throw(RuntimeException)
{
return getLocaleSpecificBreakIterator(rLocale)->getLineBreak(Text, nStartPos, rLocale,
nMinBreakPos, hOptions, bOptions);
}
sal_Int16 SAL_CALL BreakIteratorImpl::getScriptType( const OUString& Text, sal_Int32 nPos )
throw(RuntimeException)
{
return getScriptClass(Text[nPos]);
}
sal_Int32 SAL_CALL BreakIteratorImpl::beginOfScript( const OUString& Text,
sal_Int32 nStartPos, sal_Int16 ScriptType ) throw(RuntimeException)
{
if(ScriptType != getScriptClass(Text[nStartPos]))
return -1;
while (--nStartPos >= 0 && ScriptType == getScriptClass(Text[nStartPos])) {}
return ++nStartPos;
}
sal_Int32 SAL_CALL BreakIteratorImpl::endOfScript( const OUString& Text,
sal_Int32 nStartPos, sal_Int16 ScriptType ) throw(RuntimeException)
{
if(ScriptType != getScriptClass(Text[nStartPos]))
return -1;
sal_Int32 strLen = Text.getLength();
while(++nStartPos < strLen ) {
sal_Int16 currentCharScriptType = getScriptClass(Text[nStartPos]);
if(ScriptType != currentCharScriptType && currentCharScriptType != ScriptType::WEAK)
break;
}
return nStartPos;
}
sal_Int32 SAL_CALL BreakIteratorImpl::previousScript( const OUString& Text,
sal_Int32 nStartPos, sal_Int16 ScriptType ) throw(RuntimeException)
{
sal_Int16 numberOfChange = (ScriptType == getScriptClass(Text[nStartPos])) ? 3 : 2;
while (numberOfChange > 0 && --nStartPos >= 0) {
if (nStartPos == 0 ||
(((numberOfChange % 2) == 0) ^ (ScriptType != getScriptClass(Text[nStartPos]))))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos + 1 : -1;
}
sal_Int32 SAL_CALL BreakIteratorImpl::nextScript( const OUString& Text, sal_Int32 nStartPos,
sal_Int16 ScriptType ) throw(RuntimeException)
{
sal_Int16 numberOfChange = (ScriptType == getScriptClass(Text[nStartPos])) ? 2 : 1;
sal_Int32 strLen = Text.getLength();
while (numberOfChange > 0 && ++nStartPos < strLen) {
sal_Int16 currentCharScriptType = getScriptClass(Text[nStartPos]);
if ((numberOfChange == 1) ? (ScriptType != currentCharScriptType) :
(ScriptType == currentCharScriptType || currentCharScriptType == ScriptType::WEAK))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos : -1;
}
sal_Int32 SAL_CALL BreakIteratorImpl::beginOfCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
if (CharType == CharType::ANY_CHAR) return 0;
if (CharType != unicode::getUnicodeType(Text[nStartPos])) return -1;
while(nStartPos-- > 0 && CharType == unicode::getUnicodeType(Text[nStartPos])) {}
return nStartPos + 1; // begin of char block is inclusive
}
sal_Int32 SAL_CALL BreakIteratorImpl::endOfCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
sal_Int32 strLen = Text.getLength();
if(CharType == CharType::ANY_CHAR) return strLen; // end of char block is exclusive
if(CharType != unicode::getUnicodeType(Text[nStartPos])) return -1;
while(++nStartPos < strLen && CharType == unicode::getUnicodeType(Text[nStartPos])) {}
return nStartPos; // end of char block is exclusive
}
sal_Int32 SAL_CALL BreakIteratorImpl::nextCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
if (CharType == CharType::ANY_CHAR) return -1;
sal_Int16 numberOfChange = (CharType == unicode::getUnicodeType(Text[nStartPos])) ? 2 : 1;
sal_Int32 strLen = Text.getLength();
while (numberOfChange > 0 && ++nStartPos < strLen) {
if ((numberOfChange == 1) ^ (CharType != unicode::getUnicodeType(Text[nStartPos])))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos : -1;
}
sal_Int32 SAL_CALL BreakIteratorImpl::previousCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
if(CharType == CharType::ANY_CHAR) return -1;
sal_Int16 numberOfChange = (CharType == unicode::getUnicodeType(Text[nStartPos])) ? 3 : 2;
while (numberOfChange > 0 && --nStartPos >= 0) {
if (nStartPos == 0 ||
(((numberOfChange % 2) == 0) ^ (CharType != unicode::getUnicodeType(Text[nStartPos]))))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos + 1 : -1;
}
sal_Int16 SAL_CALL BreakIteratorImpl::getWordType( const OUString& Text,
sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException)
{
return 0;
}
static ScriptTypeList typeList[] = {
{ UnicodeScript_kBasicLatin, ScriptType::LATIN }, // 0,
{ UnicodeScript_kLatin1Supplement, ScriptType::LATIN }, // 1,
{ UnicodeScript_kLatinExtendedA, ScriptType::LATIN }, // 2,
{ UnicodeScript_kLatinExtendedB, ScriptType::LATIN }, // 3,
{ UnicodeScript_kIPAExtension, ScriptType::LATIN }, // 4,
{ UnicodeScript_kSpacingModifier, ScriptType::LATIN }, // 5,
{ UnicodeScript_kCombiningDiacritical, ScriptType::LATIN }, // 6,
{ UnicodeScript_kGreek, ScriptType::LATIN }, // 7,
{ UnicodeScript_kCyrillic, ScriptType::LATIN }, // 8,
{ UnicodeScript_kHebrew, ScriptType::COMPLEX }, // 10,
{ UnicodeScript_kArabic, ScriptType::COMPLEX }, // 11,
{ UnicodeScript_kDevanagari, ScriptType::COMPLEX }, // 14,
{ UnicodeScript_kThai, ScriptType::COMPLEX }, // 24,
{ UnicodeScript_kTibetan, ScriptType::LATIN }, // 26,
{ UnicodeScript_kCJKRadicalsSupplement, ScriptType::ASIAN }, // 57,
{ UnicodeScript_kKangxiRadicals, ScriptType::ASIAN }, // 58,
{ UnicodeScript_kIdeographicDescriptionCharacters, ScriptType::ASIAN }, // 59,
{ UnicodeScript_kCJKSymbolPunctuation, ScriptType::ASIAN }, // 60,
{ UnicodeScript_kHiragana, ScriptType::ASIAN }, // 61,
{ UnicodeScript_kKatakana, ScriptType::ASIAN }, // 62,
{ UnicodeScript_kBopomofo, ScriptType::ASIAN }, // 63,
{ UnicodeScript_kHangulCompatibilityJamo, ScriptType::ASIAN }, // 64,
{ UnicodeScript_kKanbun, ScriptType::ASIAN }, // 65,
{ UnicodeScript_kBopomofoExtended, ScriptType::ASIAN }, // 66,
{ UnicodeScript_kEnclosedCJKLetterMonth, ScriptType::ASIAN }, // 67,
{ UnicodeScript_kCJKCompatibility, ScriptType::ASIAN }, // 68,
{ UnicodeScript_kCJKUnifiedIdeographsExtensionA, ScriptType::ASIAN }, // 69,
{ UnicodeScript_kCJKUnifiedIdeograph, ScriptType::ASIAN }, // 70,
{ UnicodeScript_kYiSyllables, ScriptType::ASIAN }, // 71,
{ UnicodeScript_kYiRadicals, ScriptType::ASIAN }, // 72,
{ UnicodeScript_kHangulSyllable, ScriptType::ASIAN }, // 73,
{ UnicodeScript_kCJKCompatibilityIdeograph, ScriptType::ASIAN }, // 78,
{ UnicodeScript_kCombiningHalfMark, ScriptType::ASIAN }, // 81,
{ UnicodeScript_kCJKCompatibilityForm, ScriptType::ASIAN }, // 82,
{ UnicodeScript_kSmallFormVariant, ScriptType::ASIAN }, // 83,
{ UnicodeScript_kHalfwidthFullwidthForm, ScriptType::ASIAN }, // 86,
{ UnicodeScript_kScriptCount, ScriptType::WEAK } // 88
};
sal_Int16 BreakIteratorImpl::getScriptClass(sal_Unicode currentChar )
{
static sal_Unicode lastChar = 0;
static sal_Int16 nRet = 0;
if (currentChar != lastChar) {
lastChar = currentChar;
//JP 21.9.2001: handle specific characters - always as weak
// definition of 1 - this breaks a word
// 2 - this can be inside a word
if( 1 == currentChar || 2 == currentChar )
nRet = ScriptType::WEAK;
else
nRet = unicode::getUnicodeScriptType( currentChar, typeList, ScriptType::WEAK );
}
return nRet;
}
static inline sal_Bool operator == (const Locale& l1, const Locale& l2) {
return l1.Language == l2.Language && l1.Country == l2.Country && l1.Variant == l2.Variant;
}
sal_Bool SAL_CALL BreakIteratorImpl::createLocaleSpecificBreakIterator(const OUString& aLocaleName) throw( RuntimeException )
{
// to share service between same Language but different Country code, like zh_CN and zh_TW
for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();
listItem; listItem = (lookupTableItem*)lookupTable.Next()) {
if (aLocaleName == listItem->aLocale.Language) {
xBI = listItem->xBI;
return sal_True;
}
}
Reference < uno::XInterface > xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.BreakIterator_") + aLocaleName);
if ( xI.is() ) {
xI->queryInterface( getCppuType((const Reference< XBreakIterator>*)0) ) >>= xBI;
if (xBI.is()) {
lookupTable.Insert(new lookupTableItem(Locale(aLocaleName, aLocaleName, aLocaleName), xBI));
return sal_True;
}
}
return sal_False;
}
Reference < XBreakIterator > SAL_CALL
BreakIteratorImpl::getLocaleSpecificBreakIterator(const Locale& rLocale) throw (RuntimeException)
{
if (xBI.is() && rLocale == aLocale)
return xBI;
else if (xMSF.is()) {
aLocale = rLocale;
for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();
listItem; listItem = (lookupTableItem*)lookupTable.Next()) {
if (rLocale == listItem->aLocale)
return xBI = listItem->xBI;
}
static sal_Unicode under = (sal_Unicode)'_';
static OUString tw(OUString::createFromAscii("TW"));
static OUString unicode(OUString::createFromAscii("Unicode"));
sal_Int32 l = rLocale.Language.getLength();
sal_Int32 c = rLocale.Country.getLength();
sal_Int32 v = rLocale.Variant.getLength();
OUStringBuffer aBuf(l+c+v+3);
if ((l > 0 && c > 0 && v > 0 &&
// load service with name <base>_<lang>_<country>_<varian>
createLocaleSpecificBreakIterator(aBuf.append(rLocale.Language).append(under).append(
rLocale.Country).append(under).append(rLocale.Variant).makeStringAndClear())) ||
(l > 0 && c > 0 &&
// load service with name <base>_<lang>_<country>
createLocaleSpecificBreakIterator(aBuf.append(rLocale.Language).append(under).append(
rLocale.Country).makeStringAndClear())) ||
(l > 0 && c > 0 && rLocale.Language.compareToAscii("zh") == 0 &&
(rLocale.Country.compareToAscii("HK") == 0 ||
rLocale.Country.compareToAscii("MO") == 0) &&
// if the country code is HK or MO, one more step to try TW.
createLocaleSpecificBreakIterator(aBuf.append(rLocale.Language).append(under).append(
tw).makeStringAndClear())) ||
(l > 0 &&
// load service with name <base>_<lang>
createLocaleSpecificBreakIterator(rLocale.Language)) ||
// load default service with name <base>_Unicode
createLocaleSpecificBreakIterator(unicode)) {
lookupTable.Insert( new lookupTableItem(aLocale, xBI) );
return xBI;
}
}
throw RuntimeException();
}
const sal_Char cBreakIterator[] = "com.sun.star.i18n.BreakIterator";
OUString SAL_CALL
BreakIteratorImpl::getImplementationName(void) throw( RuntimeException )
{
return OUString::createFromAscii(cBreakIterator);
}
sal_Bool SAL_CALL
BreakIteratorImpl::supportsService(const OUString& rServiceName) throw( RuntimeException )
{
return !rServiceName.compareToAscii(cBreakIterator);
}
Sequence< OUString > SAL_CALL
BreakIteratorImpl::getSupportedServiceNames(void) throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(cBreakIterator);
return aRet;
}
} } } }
#97583# typos of released API and its fixed enums have to be inherited
/*************************************************************************
*
* $RCSfile: breakiteratorImpl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: er $ $Date: 2002-03-27 12:09:19 $
*
* 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 EXPRESSED 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): _______________________________________
*
*
************************************************************************/
#include <breakiteratorImpl.hxx>
#include <unicode.hxx>
#include <rtl/ustrbuf.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
BreakIteratorImpl::BreakIteratorImpl( const Reference < XMultiServiceFactory >& rxMSF ) : xMSF( rxMSF )
{
}
BreakIteratorImpl::BreakIteratorImpl()
{
}
BreakIteratorImpl::~BreakIteratorImpl()
{
// Clear lookuptable
for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();
listItem; listItem = (lookupTableItem*)lookupTable.Next())
delete listItem;
lookupTable.Clear();
}
static ScriptTypeList CTLlist[] = {
{ UnicodeScript_kHebrew, UnicodeScript_kHebrew }, // 10,
{ UnicodeScript_kArabic, UnicodeScript_kArabic }, // 11,
{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari }, // 14,
{ UnicodeScript_kThai, UnicodeScript_kThai }, // 24,
{ UnicodeScript_kScriptCount, UnicodeScript_kScriptCount } // 88
};
// This method is a tmporary solution for CTL implementation, since writer is not passing right rLocale ye
// Unising the method has performance drawback, since it has to convert script type to Locale for every call.
const Locale& SAL_CALL
BreakIteratorImpl::getLocaleByScriptType(const Locale& rLocale, const OUString& Text,
sal_Int32 nStartPos, sal_Bool forward, sal_Bool skipWhiteSpace) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
sal_Char* language = NULL;
if (rLocale.Language.getLength() == 0)
language = "en";
if (!forward) nStartPos--;
if (skipWhiteSpace) {
if (forward)
while(nStartPos < len && unicode::isWhiteSpace(Text[nStartPos])) nStartPos++;
else
while(nStartPos >= 0 && unicode::isWhiteSpace(Text[nStartPos])) nStartPos--;
}
if (nStartPos >= 0 && nStartPos < len) {
switch(unicode::getUnicodeScriptType(Text[nStartPos], CTLlist )) {
case UnicodeScript_kThai: language = "th"; break;
case UnicodeScript_kArabic: language = "ar"; break;
case UnicodeScript_kHebrew: language = "he"; break;
case UnicodeScript_kDevanagari: language = "hi"; break;
}
}
if (language) {
static Locale locale;
locale.Language = OUString::createFromAscii(language);
return locale;
} else
return rLocale;
}
sal_Int32 SAL_CALL BreakIteratorImpl::nextCharacters( const OUString& Text, sal_Int32 nStartPos,
const Locale &rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone )
throw(RuntimeException)
{
if (nCount < 0) throw RuntimeException();
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_True,
sal_False))->nextCharacters( Text, nStartPos, rLocale, nCharacterIteratorMode, nCount, nDone);
}
sal_Int32 SAL_CALL BreakIteratorImpl::previousCharacters( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount, sal_Int32& nDone )
throw(RuntimeException)
{
if (nCount < 0) throw RuntimeException();
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_False,
sal_False))->previousCharacters( Text, nStartPos, rLocale, nCharacterIteratorMode, nCount, nDone);
}
Boundary SAL_CALL BreakIteratorImpl::nextWord( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 rWordType ) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if( nStartPos < 0 || len == 0 ) {
result.endPos = result.startPos = 0;
return result;
} else if (nStartPos >= len) {
result.endPos = result.startPos = len;
return result;
}
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_True,
rWordType == WordType::ANYWORD_IGNOREWHITESPACES))->nextWord(Text, nStartPos, rLocale, rWordType);
}
static inline sal_Bool SAL_CALL isCJK( const Locale& rLocale ) {
return rLocale.Language.equalsAscii("zh") || rLocale.Language.equalsAscii("ja") || rLocale.Language.equalsAscii("ko");
}
Boundary SAL_CALL BreakIteratorImpl::previousWord( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 rWordType) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if( nStartPos <= 0 || len == 0 ) {
result.endPos = result.startPos = 0;
return result;
} else if (nStartPos > len) {
result.endPos = result.startPos = len;
return result;
}
if(rWordType == WordType::ANYWORD_IGNOREWHITESPACES || rWordType == WordType::DICTIONARY_WORD) {
sal_Int32 oPos = nStartPos;
while(nStartPos > 1 && unicode::isWhiteSpace(Text[nStartPos - 1])) nStartPos--;
if( !nStartPos ) {
result.startPos = result.endPos = nStartPos;
return result;
}
// if some spaces are skiped, and the script type is Asian with no CJK rLocale, we have to return
// (nStartPos, -1) for caller to send correct rLocale for loading correct dictionary.
if (oPos != nStartPos && !isCJK(rLocale) && getScriptClass(Text[nStartPos-1]) == ScriptType::ASIAN) {
result.startPos = nStartPos;
result.endPos = -1;
return result;
}
}
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nStartPos, sal_False,
sal_False))->previousWord(Text, nStartPos, rLocale, rWordType);
}
Boundary SAL_CALL BreakIteratorImpl::getWordBoundary( const OUString& Text, sal_Int32 nPos, const Locale& rLocale,
sal_Int16 rWordType, sal_Bool bDirection ) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if( nPos < 0 || len == 0 ) {
result.endPos = result.startPos = 0;
return result;
} else if (nPos > len) {
result.endPos = result.startPos = len;
return result;
}
return getLocaleSpecificBreakIterator(getLocaleByScriptType(rLocale, Text, nPos, sal_True,
rWordType == WordType::ANYWORD_IGNOREWHITESPACES))->getWordBoundary(Text, nPos, rLocale, rWordType, bDirection);
}
sal_Bool SAL_CALL BreakIteratorImpl::isBeginWord( const OUString& Text, sal_Int32 nPos,
const Locale& rLocale, sal_Int16 rWordType ) throw(RuntimeException)
{
if (unicode::isWhiteSpace(Text[nPos])) return false;
result = getWordBoundary(Text, nPos, rLocale, rWordType, false);
return result.startPos == nPos;
}
sal_Bool SAL_CALL BreakIteratorImpl::isEndWord( const OUString& Text, sal_Int32 nPos,
const Locale& rLocale, sal_Int16 rWordType ) throw(RuntimeException)
{
sal_Int32 len = Text.getLength();
if (nPos < 0 || nPos > len ||
rWordType == WordType::ANYWORD_IGNOREWHITESPACES && unicode::isWhiteSpace(Text[nPos]))
return false;
result = getWordBoundary(Text, nPos, rLocale, rWordType, false);
if (result.endPos == len && rWordType == WordType::ANYWORD_IGNOREWHITESPACES)
return false;
return (result.endPos == nPos && !unicode::isWhiteSpace(Text[result.startPos]));
}
sal_Int32 SAL_CALL BreakIteratorImpl::beginOfSentence( const OUString& Text, sal_Int32 nStartPos,
const Locale &rLocale ) throw(RuntimeException)
{
return getLocaleSpecificBreakIterator(rLocale)->beginOfSentence(Text, nStartPos, rLocale);
}
sal_Int32 SAL_CALL BreakIteratorImpl::endOfSentence( const OUString& Text, sal_Int32 nStartPos,
const Locale &rLocale ) throw(RuntimeException)
{
return getLocaleSpecificBreakIterator(rLocale)->endOfSentence(Text, nStartPos, rLocale);
}
LineBreakResults SAL_CALL BreakIteratorImpl::getLineBreak( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int32 nMinBreakPos, const LineBreakHyphenationOptions& hOptions,
const LineBreakUserOptions& bOptions ) throw(RuntimeException)
{
return getLocaleSpecificBreakIterator(rLocale)->getLineBreak(Text, nStartPos, rLocale,
nMinBreakPos, hOptions, bOptions);
}
sal_Int16 SAL_CALL BreakIteratorImpl::getScriptType( const OUString& Text, sal_Int32 nPos )
throw(RuntimeException)
{
return getScriptClass(Text[nPos]);
}
sal_Int32 SAL_CALL BreakIteratorImpl::beginOfScript( const OUString& Text,
sal_Int32 nStartPos, sal_Int16 ScriptType ) throw(RuntimeException)
{
if(ScriptType != getScriptClass(Text[nStartPos]))
return -1;
while (--nStartPos >= 0 && ScriptType == getScriptClass(Text[nStartPos])) {}
return ++nStartPos;
}
sal_Int32 SAL_CALL BreakIteratorImpl::endOfScript( const OUString& Text,
sal_Int32 nStartPos, sal_Int16 ScriptType ) throw(RuntimeException)
{
if(ScriptType != getScriptClass(Text[nStartPos]))
return -1;
sal_Int32 strLen = Text.getLength();
while(++nStartPos < strLen ) {
sal_Int16 currentCharScriptType = getScriptClass(Text[nStartPos]);
if(ScriptType != currentCharScriptType && currentCharScriptType != ScriptType::WEAK)
break;
}
return nStartPos;
}
sal_Int32 SAL_CALL BreakIteratorImpl::previousScript( const OUString& Text,
sal_Int32 nStartPos, sal_Int16 ScriptType ) throw(RuntimeException)
{
sal_Int16 numberOfChange = (ScriptType == getScriptClass(Text[nStartPos])) ? 3 : 2;
while (numberOfChange > 0 && --nStartPos >= 0) {
if (nStartPos == 0 ||
(((numberOfChange % 2) == 0) ^ (ScriptType != getScriptClass(Text[nStartPos]))))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos + 1 : -1;
}
sal_Int32 SAL_CALL BreakIteratorImpl::nextScript( const OUString& Text, sal_Int32 nStartPos,
sal_Int16 ScriptType ) throw(RuntimeException)
{
sal_Int16 numberOfChange = (ScriptType == getScriptClass(Text[nStartPos])) ? 2 : 1;
sal_Int32 strLen = Text.getLength();
while (numberOfChange > 0 && ++nStartPos < strLen) {
sal_Int16 currentCharScriptType = getScriptClass(Text[nStartPos]);
if ((numberOfChange == 1) ? (ScriptType != currentCharScriptType) :
(ScriptType == currentCharScriptType || currentCharScriptType == ScriptType::WEAK))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos : -1;
}
sal_Int32 SAL_CALL BreakIteratorImpl::beginOfCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
if (CharType == CharType::ANY_CHAR) return 0;
if (CharType != unicode::getUnicodeType(Text[nStartPos])) return -1;
while(nStartPos-- > 0 && CharType == unicode::getUnicodeType(Text[nStartPos])) {}
return nStartPos + 1; // begin of char block is inclusive
}
sal_Int32 SAL_CALL BreakIteratorImpl::endOfCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
sal_Int32 strLen = Text.getLength();
if(CharType == CharType::ANY_CHAR) return strLen; // end of char block is exclusive
if(CharType != unicode::getUnicodeType(Text[nStartPos])) return -1;
while(++nStartPos < strLen && CharType == unicode::getUnicodeType(Text[nStartPos])) {}
return nStartPos; // end of char block is exclusive
}
sal_Int32 SAL_CALL BreakIteratorImpl::nextCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
if (CharType == CharType::ANY_CHAR) return -1;
sal_Int16 numberOfChange = (CharType == unicode::getUnicodeType(Text[nStartPos])) ? 2 : 1;
sal_Int32 strLen = Text.getLength();
while (numberOfChange > 0 && ++nStartPos < strLen) {
if ((numberOfChange == 1) ^ (CharType != unicode::getUnicodeType(Text[nStartPos])))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos : -1;
}
sal_Int32 SAL_CALL BreakIteratorImpl::previousCharBlock( const OUString& Text, sal_Int32 nStartPos,
const Locale& rLocale, sal_Int16 CharType ) throw(RuntimeException)
{
if(CharType == CharType::ANY_CHAR) return -1;
sal_Int16 numberOfChange = (CharType == unicode::getUnicodeType(Text[nStartPos])) ? 3 : 2;
while (numberOfChange > 0 && --nStartPos >= 0) {
if (nStartPos == 0 ||
(((numberOfChange % 2) == 0) ^ (CharType != unicode::getUnicodeType(Text[nStartPos]))))
numberOfChange--;
}
return numberOfChange == 0 ? nStartPos + 1 : -1;
}
sal_Int16 SAL_CALL BreakIteratorImpl::getWordType( const OUString& Text,
sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException)
{
return 0;
}
static ScriptTypeList typeList[] = {
{ UnicodeScript_kBasicLatin, ScriptType::LATIN }, // 0,
{ UnicodeScript_kLatin1Supplement, ScriptType::LATIN }, // 1,
{ UnicodeScript_kLatinExtendedA, ScriptType::LATIN }, // 2,
{ UnicodeScript_kLatinExtendedB, ScriptType::LATIN }, // 3,
{ UnicodeScript_kIPAExtension, ScriptType::LATIN }, // 4,
{ UnicodeScript_kSpacingModifier, ScriptType::LATIN }, // 5,
{ UnicodeScript_kCombiningDiacritical, ScriptType::LATIN }, // 6,
{ UnicodeScript_kGreek, ScriptType::LATIN }, // 7,
{ UnicodeScript_kCyrillic, ScriptType::LATIN }, // 8,
{ UnicodeScript_kHebrew, ScriptType::COMPLEX }, // 10,
{ UnicodeScript_kArabic, ScriptType::COMPLEX }, // 11,
{ UnicodeScript_kDevanagari, ScriptType::COMPLEX }, // 14,
{ UnicodeScript_kThai, ScriptType::COMPLEX }, // 24,
{ UnicodeScript_kTibetan, ScriptType::LATIN }, // 26,
{ UnicodeScript_kCJKRadicalsSupplement, ScriptType::ASIAN }, // 57,
{ UnicodeScript_kKangxiRadicals, ScriptType::ASIAN }, // 58,
{ UnicodeScript_kIdeographicDescriptionCharacters, ScriptType::ASIAN }, // 59,
{ UnicodeScript_kCJKSymbolPunctuation, ScriptType::ASIAN }, // 60,
{ UnicodeScript_kHiragana, ScriptType::ASIAN }, // 61,
{ UnicodeScript_kKatakana, ScriptType::ASIAN }, // 62,
{ UnicodeScript_kBopomofo, ScriptType::ASIAN }, // 63,
{ UnicodeScript_kHangulCompatibilityJamo, ScriptType::ASIAN }, // 64,
{ UnicodeScript_kKanbun, ScriptType::ASIAN }, // 65,
{ UnicodeScript_kBopomofoExtended, ScriptType::ASIAN }, // 66,
{ UnicodeScript_kEnclosedCJKLetterMonth, ScriptType::ASIAN }, // 67,
{ UnicodeScript_kCJKCompatibility, ScriptType::ASIAN }, // 68,
{ UnicodeScript_k_CJKUnifiedIdeographsExtensionA, ScriptType::ASIAN }, // 69,
{ UnicodeScript_kCJKUnifiedIdeograph, ScriptType::ASIAN }, // 70,
{ UnicodeScript_kYiSyllables, ScriptType::ASIAN }, // 71,
{ UnicodeScript_kYiRadicals, ScriptType::ASIAN }, // 72,
{ UnicodeScript_kHangulSyllable, ScriptType::ASIAN }, // 73,
{ UnicodeScript_kCJKCompatibilityIdeograph, ScriptType::ASIAN }, // 78,
{ UnicodeScript_kCombiningHalfMark, ScriptType::ASIAN }, // 81,
{ UnicodeScript_kCJKCompatibilityForm, ScriptType::ASIAN }, // 82,
{ UnicodeScript_kSmallFormVariant, ScriptType::ASIAN }, // 83,
{ UnicodeScript_kHalfwidthFullwidthForm, ScriptType::ASIAN }, // 86,
{ UnicodeScript_kScriptCount, ScriptType::WEAK } // 88
};
sal_Int16 BreakIteratorImpl::getScriptClass(sal_Unicode currentChar )
{
static sal_Unicode lastChar = 0;
static sal_Int16 nRet = 0;
if (currentChar != lastChar) {
lastChar = currentChar;
//JP 21.9.2001: handle specific characters - always as weak
// definition of 1 - this breaks a word
// 2 - this can be inside a word
if( 1 == currentChar || 2 == currentChar )
nRet = ScriptType::WEAK;
else
nRet = unicode::getUnicodeScriptType( currentChar, typeList, ScriptType::WEAK );
}
return nRet;
}
static inline sal_Bool operator == (const Locale& l1, const Locale& l2) {
return l1.Language == l2.Language && l1.Country == l2.Country && l1.Variant == l2.Variant;
}
sal_Bool SAL_CALL BreakIteratorImpl::createLocaleSpecificBreakIterator(const OUString& aLocaleName) throw( RuntimeException )
{
// to share service between same Language but different Country code, like zh_CN and zh_TW
for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();
listItem; listItem = (lookupTableItem*)lookupTable.Next()) {
if (aLocaleName == listItem->aLocale.Language) {
xBI = listItem->xBI;
return sal_True;
}
}
Reference < uno::XInterface > xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.BreakIterator_") + aLocaleName);
if ( xI.is() ) {
xI->queryInterface( getCppuType((const Reference< XBreakIterator>*)0) ) >>= xBI;
if (xBI.is()) {
lookupTable.Insert(new lookupTableItem(Locale(aLocaleName, aLocaleName, aLocaleName), xBI));
return sal_True;
}
}
return sal_False;
}
Reference < XBreakIterator > SAL_CALL
BreakIteratorImpl::getLocaleSpecificBreakIterator(const Locale& rLocale) throw (RuntimeException)
{
if (xBI.is() && rLocale == aLocale)
return xBI;
else if (xMSF.is()) {
aLocale = rLocale;
for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();
listItem; listItem = (lookupTableItem*)lookupTable.Next()) {
if (rLocale == listItem->aLocale)
return xBI = listItem->xBI;
}
static sal_Unicode under = (sal_Unicode)'_';
static OUString tw(OUString::createFromAscii("TW"));
static OUString unicode(OUString::createFromAscii("Unicode"));
sal_Int32 l = rLocale.Language.getLength();
sal_Int32 c = rLocale.Country.getLength();
sal_Int32 v = rLocale.Variant.getLength();
OUStringBuffer aBuf(l+c+v+3);
if ((l > 0 && c > 0 && v > 0 &&
// load service with name <base>_<lang>_<country>_<varian>
createLocaleSpecificBreakIterator(aBuf.append(rLocale.Language).append(under).append(
rLocale.Country).append(under).append(rLocale.Variant).makeStringAndClear())) ||
(l > 0 && c > 0 &&
// load service with name <base>_<lang>_<country>
createLocaleSpecificBreakIterator(aBuf.append(rLocale.Language).append(under).append(
rLocale.Country).makeStringAndClear())) ||
(l > 0 && c > 0 && rLocale.Language.compareToAscii("zh") == 0 &&
(rLocale.Country.compareToAscii("HK") == 0 ||
rLocale.Country.compareToAscii("MO") == 0) &&
// if the country code is HK or MO, one more step to try TW.
createLocaleSpecificBreakIterator(aBuf.append(rLocale.Language).append(under).append(
tw).makeStringAndClear())) ||
(l > 0 &&
// load service with name <base>_<lang>
createLocaleSpecificBreakIterator(rLocale.Language)) ||
// load default service with name <base>_Unicode
createLocaleSpecificBreakIterator(unicode)) {
lookupTable.Insert( new lookupTableItem(aLocale, xBI) );
return xBI;
}
}
throw RuntimeException();
}
const sal_Char cBreakIterator[] = "com.sun.star.i18n.BreakIterator";
OUString SAL_CALL
BreakIteratorImpl::getImplementationName(void) throw( RuntimeException )
{
return OUString::createFromAscii(cBreakIterator);
}
sal_Bool SAL_CALL
BreakIteratorImpl::supportsService(const OUString& rServiceName) throw( RuntimeException )
{
return !rServiceName.compareToAscii(cBreakIterator);
}
Sequence< OUString > SAL_CALL
BreakIteratorImpl::getSupportedServiceNames(void) throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(cBreakIterator);
return aRet;
}
} } } }
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// 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.
//
// Interface header.
#include "latlongmapenvironmentedf.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/lighting/imageimportancesampler.h"
#include "renderer/kernel/texturing/texturecache.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/modeling/environmentedf/environmentedf.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/input/texturesource.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/modeling/texture/texture.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/color.h"
#include "foundation/image/colorspace.h"
#include "foundation/math/sampling.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/types.h"
#include "foundation/utility/containers/dictionary.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <cstddef>
#include <memory>
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Latitude-longitude environment map EDF.
//
// Reference:
//
// http://www.cs.virginia.edu/~gfx/courses/2007/ImageSynthesis/assignments/envsample.pdf
//
// Light probes:
//
// http://www.debevec.org/probes/
// http://gl.ict.usc.edu/Data/HighResProbes/
// http://www.cs.kuleuven.be/~graphics/index.php/environment-maps
//
class ImageSampler
{
public:
ImageSampler(
TextureCache& texture_cache,
Source* source,
const size_t width,
const size_t height,
const double u_shift,
const double v_shift)
: m_texture_cache(texture_cache)
, m_source(source)
, m_rcp_width(1.0 / width)
, m_rcp_height(1.0 / height)
, m_u_shift(u_shift)
, m_v_shift(v_shift)
, m_out_of_range_luminance_error_count(0)
{
}
double operator()(const size_t x, const size_t y)
{
if (m_source == 0)
return 0.0;
const Vector2d uv(
x * m_rcp_width + m_u_shift,
1.0 - y * m_rcp_height + m_v_shift);
Color3f linear_rgb;
Alpha alpha;
m_source->evaluate(
m_texture_cache,
uv,
linear_rgb,
alpha);
const double MaxLuminance = 1.0e4;
double lum = static_cast<double>(luminance(linear_rgb));
if (lum < 0.0)
{
lum = 0.0;
++m_out_of_range_luminance_error_count;
}
if (lum > MaxLuminance)
{
lum = MaxLuminance;
++m_out_of_range_luminance_error_count;
}
return lum;
}
size_t get_out_of_range_luminance_error_count() const
{
return m_out_of_range_luminance_error_count;
}
private:
TextureCache& m_texture_cache;
Source* m_source;
const double m_rcp_width;
const double m_rcp_height;
const double m_u_shift;
const double m_v_shift;
size_t m_out_of_range_luminance_error_count;
};
const char* Model = "latlong_map_environment_edf";
class LatLongMapEnvironmentEDF
: public EnvironmentEDF
{
public:
LatLongMapEnvironmentEDF(
const char* name,
const ParamArray& params)
: EnvironmentEDF(name, params)
, m_importance_map_width(0)
, m_importance_map_height(0)
, m_probability_scale(0.0)
{
m_inputs.declare("exitance", InputFormatSpectrum);
m_u_shift = m_params.get_optional<double>("horizontal_shift", 0.0) / 360.0;
m_v_shift = m_params.get_optional<double>("vertical_shift", 0.0) / 360.0;
}
virtual void release()
{
delete this;
}
virtual const char* get_model() const
{
return Model;
}
virtual void on_frame_begin(const Project& project)
{
EnvironmentEDF::on_frame_begin(project);
if (m_importance_sampler.get() == 0)
build_importance_map(*project.get_scene());
}
virtual void sample(
InputEvaluator& input_evaluator,
const Vector2d& s,
Vector3d& outgoing,
Spectrum& value,
double& probability) const
{
// Sample the importance map.
size_t x, y;
double prob_xy;
m_importance_sampler->sample(s, x, y, prob_xy);
// Compute the coordinates in [0,1]^2 of the sample.
const double u = (2.0 * x + 1.0) / (2.0 * m_importance_map_width);
const double v = (2.0 * y + 1.0) / (2.0 * m_importance_map_height);
double theta, phi;
unit_square_to_angles(u, v, theta, phi);
// Compute the world space emission direction.
outgoing = Vector3d::unit_vector(theta, phi);
lookup_environment_map(input_evaluator, u, v, value);
probability = prob_xy * m_probability_scale / sin(theta);
}
virtual void evaluate(
InputEvaluator& input_evaluator,
const Vector3d& outgoing,
Spectrum& value) const
{
assert(is_normalized(outgoing));
double theta, phi;
unit_vector_to_angles(outgoing, theta, phi);
double u, v;
angles_to_unit_square(theta, phi, u, v);
lookup_environment_map(input_evaluator, u, v, value);
}
virtual void evaluate(
InputEvaluator& input_evaluator,
const Vector3d& outgoing,
Spectrum& value,
double& probability) const
{
assert(is_normalized(outgoing));
double theta, phi;
unit_vector_to_angles(outgoing, theta, phi);
double u, v;
angles_to_unit_square(theta, phi, u, v);
lookup_environment_map(input_evaluator, u, v, value);
probability = compute_pdf(u, v, theta);
}
virtual double evaluate_pdf(
InputEvaluator& input_evaluator,
const Vector3d& outgoing) const
{
assert(is_normalized(outgoing));
double theta, phi;
unit_vector_to_angles(outgoing, theta, phi);
double u, v;
angles_to_unit_square(theta, phi, u, v);
return compute_pdf(u, v, theta);
}
private:
struct InputValues
{
Spectrum m_exitance;
Alpha m_exitance_alpha; // unused
};
typedef ImageImportanceSampler<double> ImageImportanceSamplerType;
double m_u_shift;
double m_v_shift;
size_t m_importance_map_width;
size_t m_importance_map_height;
double m_probability_scale;
auto_ptr<ImageImportanceSamplerType> m_importance_sampler;
// Compute the spherical coordinates of a given direction.
static void unit_vector_to_angles(
const Vector3d& v, // unit length
double& theta, // in [0, Pi]
double& phi) // in [-Pi, Pi]
{
assert(is_normalized(v));
theta = acos(v[1]);
phi = atan2(v[2], v[0]);
}
// Convert a given direction from spherical coordinates to [0,1]^2.
static void angles_to_unit_square(
const double theta, // in [0, Pi]
const double phi, // in [-Pi, Pi]
double& u, // in [0, 1]
double& v) // in [0, 1]
{
assert(theta >= 0.0);
assert(theta <= Pi);
assert(phi >= -Pi);
assert(phi <= Pi);
u = (0.5 / Pi) * (phi + Pi);
v = (1.0 / Pi) * theta;
}
// Convert a given direction from [0,1]^2 to spherical coordinates.
static void unit_square_to_angles(
const double u, // in [0, 1]
const double v, // in [0, 1]
double& theta, // in [0, Pi]
double& phi) // in [-Pi, Pi]
{
assert(u >= 0.0);
assert(u <= 1.0);
assert(v >= 0.0);
assert(v <= 1.0);
theta = Pi * v;
phi = Pi * (2.0 * u - 1.0);
}
void build_importance_map(const Scene& scene)
{
const TextureSource* exitance_source =
dynamic_cast<const TextureSource*>(m_inputs.source("exitance"));
if (exitance_source)
{
const CanvasProperties& texture_props = exitance_source->get_texture(scene).properties();
m_importance_map_width = texture_props.m_canvas_width;
m_importance_map_height = texture_props.m_canvas_height;
}
else
{
m_importance_map_width = 1;
m_importance_map_height = 1;
}
const size_t texel_count = m_importance_map_width * m_importance_map_height;
m_probability_scale = texel_count / (2.0 * Pi * Pi);
TextureStore texture_store(scene);
TextureCache texture_cache(texture_store);
ImageSampler sampler(
texture_cache,
m_inputs.source("exitance"),
m_importance_map_width,
m_importance_map_height,
m_u_shift,
m_v_shift);
RENDERER_LOG_INFO(
"building " FMT_SIZE_T "x" FMT_SIZE_T " importance map "
"for environment edf \"%s\"...",
m_importance_map_width,
m_importance_map_height,
get_name());
m_importance_sampler.reset(
new ImageImportanceSamplerType(
m_importance_map_width,
m_importance_map_height,
sampler));
const size_t oor_error_count = sampler.get_out_of_range_luminance_error_count();
if (oor_error_count > 0)
{
RENDERER_LOG_WARNING(
"while building importance map for environment edf \"%s\": "
"found %s pixel%s with out-of-range luminance; rendering artifacts are to be expected.",
get_name(),
pretty_uint(oor_error_count).c_str(),
oor_error_count > 1 ? "s" : "");
}
RENDERER_LOG_INFO(
"built importance map for environment edf \"%s\".",
get_name());
}
void lookup_environment_map(
InputEvaluator& input_evaluator,
const double u,
const double v,
Spectrum& value) const
{
const Vector2d uv(u + m_u_shift, 1.0 - v + m_v_shift);
const InputValues* values =
input_evaluator.evaluate<InputValues>(m_inputs, uv);
value = values->m_exitance;
}
double compute_pdf(
const double u,
const double v,
const double theta) const
{
// Compute the probability density of this sample in the importance map.
const size_t x = truncate<size_t>(m_importance_map_width * u);
const size_t y = truncate<size_t>(m_importance_map_height * v);
const double prob_xy = m_importance_sampler->get_pdf(x, y);
// Compute the probability density of the emission direction.
return prob_xy * m_probability_scale / sin(theta);
}
};
}
//
// LatLongMapEnvironmentEDFFactory class implementation.
//
const char* LatLongMapEnvironmentEDFFactory::get_model() const
{
return Model;
}
const char* LatLongMapEnvironmentEDFFactory::get_human_readable_model() const
{
return "Latitude-Longitude Map Environment EDF";
}
DictionaryArray LatLongMapEnvironmentEDFFactory::get_widget_definitions() const
{
DictionaryArray definitions;
definitions.push_back(
Dictionary()
.insert("name", "exitance")
.insert("label", "Exitance")
.insert("widget", "entity_picker")
.insert("entity_types",
Dictionary()
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", ""));
definitions.push_back(
Dictionary()
.insert("name", "horizontal_shift")
.insert("label", "Horizontal Shift")
.insert("widget", "text_box")
.insert("default", "0.0")
.insert("use", "optional"));
definitions.push_back(
Dictionary()
.insert("name", "vertical_shift")
.insert("label", "Vertical Shift")
.insert("widget", "text_box")
.insert("default", "0.0")
.insert("use", "optional"));
return definitions;
}
auto_release_ptr<EnvironmentEDF> LatLongMapEnvironmentEDFFactory::create(
const char* name,
const ParamArray& params) const
{
return
auto_release_ptr<EnvironmentEDF>(
new LatLongMapEnvironmentEDF(name, params));
}
} // namespace renderer
code tweaks.
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// 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.
//
// Interface header.
#include "latlongmapenvironmentedf.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/lighting/imageimportancesampler.h"
#include "renderer/kernel/texturing/texturecache.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/modeling/environmentedf/environmentedf.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/input/texturesource.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/modeling/texture/texture.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/color.h"
#include "foundation/image/colorspace.h"
#include "foundation/math/sampling.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/types.h"
#include "foundation/utility/containers/dictionary.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <cstddef>
#include <memory>
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Latitude-longitude environment map EDF.
//
// Reference:
//
// http://www.cs.virginia.edu/~gfx/courses/2007/ImageSynthesis/assignments/envsample.pdf
//
// Light probes:
//
// http://www.debevec.org/probes/
// http://gl.ict.usc.edu/Data/HighResProbes/
// http://www.cs.kuleuven.be/~graphics/index.php/environment-maps
//
class ImageSampler
{
public:
ImageSampler(
TextureCache& texture_cache,
const Source* source,
const size_t width,
const size_t height,
const double u_shift,
const double v_shift)
: m_texture_cache(texture_cache)
, m_source(source)
, m_rcp_width(1.0 / width)
, m_rcp_height(1.0 / height)
, m_u_shift(u_shift)
, m_v_shift(v_shift)
, m_out_of_range_luminance_error_count(0)
{
}
double operator()(const size_t x, const size_t y)
{
if (m_source == 0)
return 0.0;
const Vector2d uv(
x * m_rcp_width + m_u_shift,
1.0 - y * m_rcp_height + m_v_shift);
Color3f linear_rgb;
Alpha alpha;
m_source->evaluate(
m_texture_cache,
uv,
linear_rgb,
alpha);
const double MaxLuminance = 1.0e4;
double lum = static_cast<double>(luminance(linear_rgb));
if (lum < 0.0)
{
lum = 0.0;
++m_out_of_range_luminance_error_count;
}
if (lum > MaxLuminance)
{
lum = MaxLuminance;
++m_out_of_range_luminance_error_count;
}
return lum;
}
size_t get_out_of_range_luminance_error_count() const
{
return m_out_of_range_luminance_error_count;
}
private:
TextureCache& m_texture_cache;
const Source* m_source;
const double m_rcp_width;
const double m_rcp_height;
const double m_u_shift;
const double m_v_shift;
size_t m_out_of_range_luminance_error_count;
};
const char* Model = "latlong_map_environment_edf";
class LatLongMapEnvironmentEDF
: public EnvironmentEDF
{
public:
LatLongMapEnvironmentEDF(
const char* name,
const ParamArray& params)
: EnvironmentEDF(name, params)
, m_importance_map_width(0)
, m_importance_map_height(0)
, m_probability_scale(0.0)
{
m_inputs.declare("exitance", InputFormatSpectrum);
m_u_shift = m_params.get_optional<double>("horizontal_shift", 0.0) / 360.0;
m_v_shift = m_params.get_optional<double>("vertical_shift", 0.0) / 360.0;
}
virtual void release()
{
delete this;
}
virtual const char* get_model() const
{
return Model;
}
virtual void on_frame_begin(const Project& project)
{
EnvironmentEDF::on_frame_begin(project);
if (m_importance_sampler.get() == 0)
build_importance_map(*project.get_scene());
}
virtual void sample(
InputEvaluator& input_evaluator,
const Vector2d& s,
Vector3d& outgoing,
Spectrum& value,
double& probability) const
{
// Sample the importance map.
size_t x, y;
double prob_xy;
m_importance_sampler->sample(s, x, y, prob_xy);
// Compute the coordinates in [0,1]^2 of the sample.
const double u = (2.0 * x + 1.0) / (2.0 * m_importance_map_width);
const double v = (2.0 * y + 1.0) / (2.0 * m_importance_map_height);
double theta, phi;
unit_square_to_angles(u, v, theta, phi);
// Compute the world space emission direction.
outgoing = Vector3d::unit_vector(theta, phi);
lookup_environment_map(input_evaluator, u, v, value);
probability = prob_xy * m_probability_scale / sin(theta);
}
virtual void evaluate(
InputEvaluator& input_evaluator,
const Vector3d& outgoing,
Spectrum& value) const
{
assert(is_normalized(outgoing));
double theta, phi;
unit_vector_to_angles(outgoing, theta, phi);
double u, v;
angles_to_unit_square(theta, phi, u, v);
lookup_environment_map(input_evaluator, u, v, value);
}
virtual void evaluate(
InputEvaluator& input_evaluator,
const Vector3d& outgoing,
Spectrum& value,
double& probability) const
{
assert(is_normalized(outgoing));
double theta, phi;
unit_vector_to_angles(outgoing, theta, phi);
double u, v;
angles_to_unit_square(theta, phi, u, v);
lookup_environment_map(input_evaluator, u, v, value);
probability = compute_pdf(u, v, theta);
}
virtual double evaluate_pdf(
InputEvaluator& input_evaluator,
const Vector3d& outgoing) const
{
assert(is_normalized(outgoing));
double theta, phi;
unit_vector_to_angles(outgoing, theta, phi);
double u, v;
angles_to_unit_square(theta, phi, u, v);
return compute_pdf(u, v, theta);
}
private:
struct InputValues
{
Spectrum m_exitance;
Alpha m_exitance_alpha; // unused
};
typedef ImageImportanceSampler<double> ImageImportanceSamplerType;
double m_u_shift;
double m_v_shift;
size_t m_importance_map_width;
size_t m_importance_map_height;
double m_probability_scale;
auto_ptr<ImageImportanceSamplerType> m_importance_sampler;
// Compute the spherical coordinates of a given direction.
static void unit_vector_to_angles(
const Vector3d& v, // unit length
double& theta, // in [0, Pi]
double& phi) // in [-Pi, Pi]
{
assert(is_normalized(v));
theta = acos(v[1]);
phi = atan2(v[2], v[0]);
}
// Convert a given direction from spherical coordinates to [0,1]^2.
static void angles_to_unit_square(
const double theta, // in [0, Pi]
const double phi, // in [-Pi, Pi]
double& u, // in [0, 1]
double& v) // in [0, 1]
{
assert(theta >= 0.0);
assert(theta <= Pi);
assert(phi >= -Pi);
assert(phi <= Pi);
u = (0.5 / Pi) * (phi + Pi);
v = (1.0 / Pi) * theta;
}
// Convert a given direction from [0,1]^2 to spherical coordinates.
static void unit_square_to_angles(
const double u, // in [0, 1]
const double v, // in [0, 1]
double& theta, // in [0, Pi]
double& phi) // in [-Pi, Pi]
{
assert(u >= 0.0);
assert(u <= 1.0);
assert(v >= 0.0);
assert(v <= 1.0);
theta = Pi * v;
phi = Pi * (2.0 * u - 1.0);
}
void build_importance_map(const Scene& scene)
{
const Source* exitance_source = m_inputs.source("exitance");
assert(exitance_source);
if (dynamic_cast<const TextureSource*>(exitance_source))
{
const CanvasProperties& texture_props =
static_cast<const TextureSource*>(exitance_source)->get_texture(scene).properties();
m_importance_map_width = texture_props.m_canvas_width;
m_importance_map_height = texture_props.m_canvas_height;
}
else
{
m_importance_map_width = 1;
m_importance_map_height = 1;
}
const size_t texel_count = m_importance_map_width * m_importance_map_height;
m_probability_scale = texel_count / (2.0 * Pi * Pi);
TextureStore texture_store(scene);
TextureCache texture_cache(texture_store);
ImageSampler sampler(
texture_cache,
exitance_source,
m_importance_map_width,
m_importance_map_height,
m_u_shift,
m_v_shift);
RENDERER_LOG_INFO(
"building " FMT_SIZE_T "x" FMT_SIZE_T " importance map "
"for environment edf \"%s\"...",
m_importance_map_width,
m_importance_map_height,
get_name());
m_importance_sampler.reset(
new ImageImportanceSamplerType(
m_importance_map_width,
m_importance_map_height,
sampler));
const size_t oor_error_count = sampler.get_out_of_range_luminance_error_count();
if (oor_error_count > 0)
{
RENDERER_LOG_WARNING(
"while building importance map for environment edf \"%s\": "
"found %s pixel%s with out-of-range luminance; rendering artifacts are to be expected.",
get_name(),
pretty_uint(oor_error_count).c_str(),
oor_error_count > 1 ? "s" : "");
}
RENDERER_LOG_INFO(
"built importance map for environment edf \"%s\".",
get_name());
}
void lookup_environment_map(
InputEvaluator& input_evaluator,
const double u,
const double v,
Spectrum& value) const
{
const Vector2d uv(u + m_u_shift, 1.0 - v + m_v_shift);
const InputValues* values =
input_evaluator.evaluate<InputValues>(m_inputs, uv);
value = values->m_exitance;
}
double compute_pdf(
const double u,
const double v,
const double theta) const
{
// Compute the probability density of this sample in the importance map.
const size_t x = truncate<size_t>(m_importance_map_width * u);
const size_t y = truncate<size_t>(m_importance_map_height * v);
const double prob_xy = m_importance_sampler->get_pdf(x, y);
// Compute the probability density of the emission direction.
return prob_xy * m_probability_scale / sin(theta);
}
};
}
//
// LatLongMapEnvironmentEDFFactory class implementation.
//
const char* LatLongMapEnvironmentEDFFactory::get_model() const
{
return Model;
}
const char* LatLongMapEnvironmentEDFFactory::get_human_readable_model() const
{
return "Latitude-Longitude Map Environment EDF";
}
DictionaryArray LatLongMapEnvironmentEDFFactory::get_widget_definitions() const
{
DictionaryArray definitions;
definitions.push_back(
Dictionary()
.insert("name", "exitance")
.insert("label", "Exitance")
.insert("widget", "entity_picker")
.insert("entity_types",
Dictionary()
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", ""));
definitions.push_back(
Dictionary()
.insert("name", "horizontal_shift")
.insert("label", "Horizontal Shift")
.insert("widget", "text_box")
.insert("default", "0.0")
.insert("use", "optional"));
definitions.push_back(
Dictionary()
.insert("name", "vertical_shift")
.insert("label", "Vertical Shift")
.insert("widget", "text_box")
.insert("default", "0.0")
.insert("use", "optional"));
return definitions;
}
auto_release_ptr<EnvironmentEDF> LatLongMapEnvironmentEDFFactory::create(
const char* name,
const ParamArray& params) const
{
return
auto_release_ptr<EnvironmentEDF>(
new LatLongMapEnvironmentEDF(name, params));
}
} // namespace renderer
|
// Copyright (c) 2020 - 2021 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2020 - 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_hoofs/cxx/convert.hpp"
#include "iceoryx_hoofs/testing/timing_test.hpp"
#include "iceoryx_hoofs/testing/watch_dog.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/popo/publisher.hpp"
#include "iceoryx_posh/popo/subscriber.hpp"
#include "iceoryx_posh/popo/untyped_client.hpp"
#include "iceoryx_posh/popo/untyped_server.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "iceoryx_posh/testing/roudi_environment/roudi_environment.hpp"
#include "mocks/posh_runtime_mock.hpp"
#include "test.hpp"
#include <type_traits>
namespace
{
using namespace ::testing;
using namespace iox::runtime;
using namespace iox::capro;
using namespace iox::cxx;
using namespace iox::popo;
using iox::roudi::RouDiEnvironment;
class PoshRuntime_test : public Test
{
public:
PoshRuntime_test()
{
}
virtual ~PoshRuntime_test()
{
}
virtual void SetUp()
{
testing::internal::CaptureStdout();
};
virtual void TearDown()
{
std::string output = testing::internal::GetCapturedStdout();
if (Test::HasFailure())
{
std::cout << output << std::endl;
}
};
void InterOpWait()
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
void checkClientInitialization(const ClientPortData* const portData,
const ServiceDescription& sd,
const ClientOptions& options,
const iox::mepoo::MemoryInfo& memoryInfo) const
{
ASSERT_THAT(portData, Ne(nullptr));
EXPECT_EQ(portData->m_serviceDescription, sd);
EXPECT_EQ(portData->m_runtimeName, m_runtimeName);
EXPECT_EQ(portData->m_nodeName, options.nodeName);
EXPECT_EQ(portData->m_connectRequested, options.connectOnCreate);
EXPECT_EQ(portData->m_chunkReceiverData.m_queue.capacity(), options.responseQueueCapacity);
EXPECT_EQ(portData->m_chunkReceiverData.m_queueFullPolicy, options.responseQueueFullPolicy);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.memoryType, memoryInfo.memoryType);
EXPECT_EQ(portData->m_chunkSenderData.m_historyCapacity, iox::popo::ClientPortData::HISTORY_CAPACITY_ZERO);
EXPECT_EQ(portData->m_chunkSenderData.m_consumerTooSlowPolicy, options.serverTooSlowPolicy);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.memoryType, memoryInfo.memoryType);
}
void checkServerInitialization(const ServerPortData* const portData,
const ServiceDescription& sd,
const ServerOptions& options,
const iox::mepoo::MemoryInfo& memoryInfo) const
{
ASSERT_THAT(portData, Ne(nullptr));
EXPECT_EQ(portData->m_serviceDescription, sd);
EXPECT_EQ(portData->m_runtimeName, m_runtimeName);
EXPECT_EQ(portData->m_nodeName, options.nodeName);
EXPECT_EQ(portData->m_offeringRequested, options.offerOnCreate);
EXPECT_EQ(portData->m_chunkReceiverData.m_queue.capacity(), options.requestQueueCapacity);
EXPECT_EQ(portData->m_chunkReceiverData.m_queueFullPolicy, options.requestQueueFullPolicy);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.memoryType, memoryInfo.memoryType);
EXPECT_EQ(portData->m_chunkSenderData.m_historyCapacity, iox::popo::ServerPortData::HISTORY_REQUEST_OF_ZERO);
EXPECT_EQ(portData->m_chunkSenderData.m_consumerTooSlowPolicy, options.clientTooSlowPolicy);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.memoryType, memoryInfo.memoryType);
}
const iox::RuntimeName_t m_runtimeName{"publisher"};
RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
PoshRuntime* m_runtime{&iox::runtime::PoshRuntime::initRuntime(m_runtimeName)};
IpcMessage m_sendBuffer;
IpcMessage m_receiveBuffer;
const iox::NodeName_t m_nodeName{"testNode"};
const iox::NodeName_t m_invalidNodeName{"invalidNode,"};
};
TEST_F(PoshRuntime_test, ValidAppName)
{
::testing::Test::RecordProperty("TEST_ID", "2f4f5dc1-dde0-4520-a341-79a5edd19900");
iox::RuntimeName_t appName("valid_name");
EXPECT_NO_FATAL_FAILURE({ PoshRuntime::initRuntime(appName); });
}
TEST_F(PoshRuntime_test, MaxAppNameLength)
{
::testing::Test::RecordProperty("TEST_ID", "dfdf3ce1-c7d4-4c57-94ea-6ed9479371e3");
std::string maxValidName(iox::MAX_RUNTIME_NAME_LENGTH, 's');
auto& runtime = PoshRuntime::initRuntime(iox::RuntimeName_t(iox::cxx::TruncateToCapacity, maxValidName));
EXPECT_THAT(maxValidName, StrEq(runtime.getInstanceName().c_str()));
}
TEST_F(PoshRuntime_test, NoAppName)
{
::testing::Test::RecordProperty("TEST_ID", "e053d114-c79c-4391-91e1-8fcfe90ee8e4");
const iox::RuntimeName_t invalidAppName("");
EXPECT_DEATH({ PoshRuntime::initRuntime(invalidAppName); },
"Cannot initialize runtime. Application name must not be empty!");
}
// To be able to test the singleton and avoid return the exisiting instance, we don't use the test fixture
TEST(PoshRuntime, LeadingSlashAppName)
{
::testing::Test::RecordProperty("TEST_ID", "77542d11-6230-4c1e-94b2-6cf3b8fa9c6e");
RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
const iox::RuntimeName_t invalidAppName = "/miau";
auto errorHandlerCalled{false};
iox::Error receivedError{iox::Error::kNO_ERROR};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&errorHandlerCalled,
&receivedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
errorHandlerCalled = true;
receivedError = error;
});
PoshRuntime::initRuntime(invalidAppName);
EXPECT_TRUE(errorHandlerCalled);
ASSERT_THAT(receivedError, Eq(iox::Error::kPOSH__RUNTIME_LEADING_SLASH_PROVIDED));
}
// since getInstance is a singleton and test class creates instance of Poshruntime
// when getInstance() is called without parameter, it returns existing instance
// To be able to test this, we don't use the test fixture
TEST(PoshRuntime, AppNameEmpty)
{
::testing::Test::RecordProperty("TEST_ID", "63900656-4fbb-466d-b6cc-f2139121092c");
EXPECT_DEATH({ iox::runtime::PoshRuntime::getInstance(); },
"Cannot initialize runtime. Application name has not been specified!");
}
TEST_F(PoshRuntime_test, GetInstanceNameIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "b82d419c-2c72-43b0-9eb1-b24bb41366ce");
const iox::RuntimeName_t appname = "app";
auto& sut = PoshRuntime::initRuntime(appname);
EXPECT_EQ(sut.getInstanceName(), appname);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterfaceWithInvalidNodeNameIsNotSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "d207e121-d7c2-4a23-a202-1af311f6982b");
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL, m_invalidNodeName);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_GET_MW_INTERFACE_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, GetMiddlewareInterfaceIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "50b1d15d-0cee-41b3-a9cd-146eca553cc2");
const auto interfacePortData = m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL, m_nodeName);
ASSERT_NE(nullptr, interfacePortData);
EXPECT_EQ(m_runtimeName, interfacePortData->m_runtimeName);
EXPECT_EQ(false, interfacePortData->m_toBeDestroyed);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterfaceInterfacelistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "0e164d07-dede-46c3-b2a3-ad78a11c0691");
auto interfacelistOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&interfacelistOverflowDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
interfacelistOverflowDetected = true;
EXPECT_THAT(error, Eq(iox::Error::kPORT_POOL__INTERFACELIST_OVERFLOW));
});
for (auto i = 0U; i < iox::MAX_INTERFACE_NUMBER; ++i)
{
auto interfacePort = m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL);
ASSERT_NE(nullptr, interfacePort);
}
EXPECT_FALSE(interfacelistOverflowDetected);
auto interfacePort = m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL);
EXPECT_EQ(nullptr, interfacePort);
EXPECT_TRUE(interfacelistOverflowDetected);
}
TEST_F(PoshRuntime_test, SendRequestToRouDiValidMessage)
{
::testing::Test::RecordProperty("TEST_ID", "334e49d8-e826-4e21-9f9f-bb9c341d4706");
m_sendBuffer << IpcMessageTypeToString(IpcMessageType::CREATE_INTERFACE) << m_runtimeName
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_nodeName;
const auto successfullySent = m_runtime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_TRUE(m_receiveBuffer.isValid());
EXPECT_TRUE(successfullySent);
}
TEST_F(PoshRuntime_test, SendRequestToRouDiInvalidMessage)
{
::testing::Test::RecordProperty("TEST_ID", "b3f4563a-7237-4f57-8952-c39ac3dbfef2");
m_sendBuffer << IpcMessageTypeToString(IpcMessageType::CREATE_INTERFACE) << m_runtimeName
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidNodeName;
const auto successfullySent = m_runtime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_FALSE(successfullySent);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "2cb2e64b-8f21-4049-a35a-dbd7a1d6cbf4");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.historyCapacity = 13U;
publisherOptions.nodeName = m_nodeName;
const auto publisherPort = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription("99", "1", "20"), publisherOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
ASSERT_NE(nullptr, publisherPort);
EXPECT_EQ(iox::capro::ServiceDescription("99", "1", "20"), publisherPort->m_serviceDescription);
EXPECT_EQ(publisherOptions.historyCapacity, publisherPort->m_chunkSenderData.m_historyCapacity);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithHistoryGreaterMaxCapacityClampsHistoryToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "407f27bb-e507-4c1c-aab1-e5b1b8d06f46");
// arrange
iox::popo::PublisherOptions publisherOptions;
publisherOptions.historyCapacity = iox::MAX_PUBLISHER_HISTORY + 1U;
// act
const auto publisherPort =
m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("99", "1", "20"), publisherOptions);
// assert
ASSERT_NE(nullptr, publisherPort);
EXPECT_EQ(publisherPort->m_chunkSenderData.m_historyCapacity, iox::MAX_PUBLISHER_HISTORY);
}
TEST_F(PoshRuntime_test, getMiddlewarePublisherDefaultArgs)
{
::testing::Test::RecordProperty("TEST_ID", "1eae6dfa-c3f2-478b-9354-768c43bd8d96");
const auto publisherPort = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("99", "1", "20"));
ASSERT_NE(nullptr, publisherPort);
}
TEST_F(PoshRuntime_test, getMiddlewarePublisherPublisherlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "f1f1a662-9580-40a1-a116-6ea1cb791516");
auto publisherlistOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&publisherlistOverflowDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__PUBLISHERLIST_OVERFLOW)
{
publisherlistOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < (iox::MAX_PUBLISHERS - iox::NUMBER_OF_INTERNAL_PUBLISHERS); ++i)
{
auto publisherPort = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_NE(nullptr, publisherPort);
}
EXPECT_FALSE(publisherlistOverflowDetected);
auto publisherPort = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_EQ(nullptr, publisherPort);
EXPECT_TRUE(publisherlistOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithSameServiceDescriptionsAndOneToManyPolicyFails)
{
::testing::Test::RecordProperty("TEST_ID", "77fb6dfd-a00d-459e-9dd3-90010d7b8af7");
auto publisherDuplicateDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&publisherDuplicateDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPOSH__RUNTIME_PUBLISHER_PORT_NOT_UNIQUE)
{
publisherDuplicateDetected = true;
}
});
auto sameServiceDescription = iox::capro::ServiceDescription("99", "1", "20");
const auto publisherPort1 = m_runtime->getMiddlewarePublisher(
sameServiceDescription, iox::popo::PublisherOptions(), iox::runtime::PortConfigInfo(11U, 22U, 33U));
const auto publisherPort2 = m_runtime->getMiddlewarePublisher(
sameServiceDescription, iox::popo::PublisherOptions(), iox::runtime::PortConfigInfo(11U, 22U, 33U));
ASSERT_NE(nullptr, publisherPort1);
if (std::is_same<iox::build::CommunicationPolicy, iox::build::OneToManyPolicy>::value)
{
ASSERT_EQ(nullptr, publisherPort2);
EXPECT_TRUE(publisherDuplicateDetected);
}
else if (std::is_same<iox::build::CommunicationPolicy, iox::build::ManyToManyPolicy>::value)
{
ASSERT_NE(nullptr, publisherPort2);
}
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithoutOfferOnCreateLeadsToNotOfferedPublisherBeingCreated)
{
::testing::Test::RecordProperty("TEST_ID", "5002dc8c-1f6e-4593-a2b3-4de04685c919");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.offerOnCreate = false;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("69", "96", "1893"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_FALSE(publisherPortData->m_offeringRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithOfferOnCreateLeadsToOfferedPublisherBeingCreated)
{
::testing::Test::RecordProperty("TEST_ID", "639b1a0e-218d-4cde-a447-e2eec0cf2c75");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.offerOnCreate = true;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription("17", "4", "21"), publisherOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_TRUE(publisherPortData->m_offeringRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithoutExplicitlySetQueueFullPolicyLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "208418e2-64fd-47f4-b2e2-58aa4371a6a6");
iox::popo::PublisherOptions publisherOptions;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("9", "13", "1550"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(publisherPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
Eq(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithQueueFullPolicySetToDiscardOldestDataLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "67362686-3165-4a49-a15c-ac9fcaf704d8");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.subscriberTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA;
const auto publisherPortData =
m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("90", "130", "1550"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(publisherPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
Eq(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithQueueFullPolicySetToWaitForSubscriberLeadsToWaitForSubscriber)
{
::testing::Test::RecordProperty("TEST_ID", "f6439a76-69c7-422d-bcc9-7c1d82cd2990");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.subscriberTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("18", "31", "400"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(publisherPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
Eq(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER));
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "0cc05fe7-752e-4e2a-a8f2-be7cb8b384d2");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.historyRequest = 13U;
subscriberOptions.queueCapacity = 42U;
subscriberOptions.nodeName = m_nodeName;
auto subscriberPort = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("99", "1", "20"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
ASSERT_NE(nullptr, subscriberPort);
EXPECT_EQ(iox::capro::ServiceDescription("99", "1", "20"), subscriberPort->m_serviceDescription);
EXPECT_EQ(subscriberOptions.historyRequest, subscriberPort->m_options.historyRequest);
EXPECT_EQ(subscriberOptions.queueCapacity, subscriberPort->m_chunkReceiverData.m_queue.capacity());
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueGreaterMaxCapacityClampsQueueToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "85e2d246-bcba-4ead-a997-4c4137f05607");
iox::popo::SubscriberOptions subscriberOptions;
constexpr uint64_t MAX_QUEUE_CAPACITY = iox::popo::SubscriberPortUser::MemberType_t::ChunkQueueData_t::MAX_CAPACITY;
subscriberOptions.queueCapacity = MAX_QUEUE_CAPACITY + 1U;
auto subscriberPort = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("99", "1", "20"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_EQ(MAX_QUEUE_CAPACITY, subscriberPort->m_chunkReceiverData.m_queue.capacity());
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueCapacityZeroClampsQueueCapacityToOne)
{
::testing::Test::RecordProperty("TEST_ID", "9da3f4da-abe8-454c-9bc6-7f866d6d0545");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.queueCapacity = 0U;
auto subscriberPort = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription("34", "4", "4"), subscriberOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_EQ(1U, subscriberPort->m_chunkReceiverData.m_queue.capacity());
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberDefaultArgs)
{
::testing::Test::RecordProperty("TEST_ID", "e06b999c-e237-4e32-b826-a5ffdb6bb737");
auto subscriberPort = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("99", "1", "20"));
ASSERT_NE(nullptr, subscriberPort);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberSubscriberlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "d1281cbd-6520-424e-aace-fbd3aa5d73e9");
auto subscriberlistOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&subscriberlistOverflowDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__SUBSCRIBERLIST_OVERFLOW)
{
subscriberlistOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < iox::MAX_SUBSCRIBERS; ++i)
{
auto subscriberPort = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_NE(nullptr, subscriberPort);
}
EXPECT_FALSE(subscriberlistOverflowDetected);
auto subscriberPort = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_EQ(nullptr, subscriberPort);
EXPECT_TRUE(subscriberlistOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithoutSubscribeOnCreateLeadsToSubscriberThatDoesNotWantToBeSubscribed)
{
::testing::Test::RecordProperty("TEST_ID", "a59e3629-9aae-43e1-b88b-5dab441b1f17");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.subscribeOnCreate = false;
auto subscriberPortData = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("17", "17", "17"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_FALSE(subscriberPortData->m_subscribeRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithSubscribeOnCreateLeadsToSubscriberThatWantsToBeSubscribed)
{
::testing::Test::RecordProperty("TEST_ID", "975a6edc-cc39-46d0-9bb7-79ab69f18fc3");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.subscribeOnCreate = true;
auto subscriberPortData = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription("1", "2", "3"), subscriberOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_TRUE(subscriberPortData->m_subscribeRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithoutExplicitlySetQueueFullPolicyLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "7fdd60c2-8b18-481c-8bad-5f6f70431196");
iox::popo::SubscriberOptions subscriberOptions;
const auto subscriberPortData =
m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("9", "13", "1550"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(subscriberPortData->m_chunkReceiverData.m_queueFullPolicy,
Eq(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueFullPolicySetToDiscardOldestDataLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "9e5df6bf-a752-4db8-9e27-ba5ae1f02a52");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.queueFullPolicy = iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA;
const auto subscriberPortData =
m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("90", "130", "1550"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(subscriberPortData->m_chunkReceiverData.m_queueFullPolicy,
Eq(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueFullPolicySetToBlockPublisherLeadsToBlockPublisher)
{
::testing::Test::RecordProperty("TEST_ID", "ab60b748-6425-4ebf-8041-285a29a92756");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.queueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
const auto subscriberPortData =
m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("18", "31", "400"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(subscriberPortData->m_chunkReceiverData.m_queueFullPolicy,
Eq(iox::popo::QueueFullPolicy::BLOCK_PRODUCER));
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithDefaultArgsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "2db35746-e402-443f-b374-3b6a239ab5fd");
const iox::capro::ServiceDescription sd{"911", "1", "20"};
iox::popo::ClientOptions defaultOptions;
iox::runtime::PortConfigInfo defaultPortConfigInfo;
auto clientPort = m_runtime->getMiddlewareClient(sd);
ASSERT_THAT(clientPort, Ne(nullptr));
checkClientInitialization(clientPort, sd, defaultOptions, defaultPortConfigInfo.memoryInfo);
EXPECT_EQ(clientPort->m_connectionState, iox::ConnectionState::WAIT_FOR_OFFER);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithCustomClientOptionsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "f61a81f4-f610-4e61-853b-ac114d9a801c");
const iox::capro::ServiceDescription sd{"911", "1", "20"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 13U;
clientOptions.nodeName = m_nodeName;
clientOptions.connectOnCreate = false;
clientOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
clientOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
const iox::runtime::PortConfigInfo portConfig{11U, 22U, 33U};
auto clientPort = m_runtime->getMiddlewareClient(sd, clientOptions, portConfig);
ASSERT_THAT(clientPort, Ne(nullptr));
checkClientInitialization(clientPort, sd, clientOptions, portConfig.memoryInfo);
EXPECT_EQ(clientPort->m_connectionState, iox::ConnectionState::NOT_CONNECTED);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithQueueGreaterMaxCapacityClampsQueueToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "8e34f962-e7c9-40ac-9796-a12f92c4d674");
constexpr uint64_t MAX_QUEUE_CAPACITY = iox::popo::ClientChunkQueueConfig::MAX_QUEUE_CAPACITY;
const iox::capro::ServiceDescription sd{"919", "1", "20"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = MAX_QUEUE_CAPACITY + 1U;
auto clientPort = m_runtime->getMiddlewareClient(sd, clientOptions);
ASSERT_THAT(clientPort, Ne(nullptr));
EXPECT_EQ(clientPort->m_chunkReceiverData.m_queue.capacity(), MAX_QUEUE_CAPACITY);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithQueueCapacityZeroClampsQueueCapacityToOne)
{
::testing::Test::RecordProperty("TEST_ID", "7b6ffd68-46d4-4339-a0df-6fecb621f765");
const iox::capro::ServiceDescription sd{"99", "19", "20"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 0U;
auto clientPort = m_runtime->getMiddlewareClient(sd, clientOptions);
ASSERT_THAT(clientPort, Ne(nullptr));
EXPECT_EQ(clientPort->m_chunkReceiverData.m_queue.capacity(), 1U);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWhenMaxClientsAreUsedResultsInClientlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "6f2de2bf-5e7e-47b1-be42-92cf3fa71ba6");
auto clientOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__CLIENTLIST_OVERFLOW)
{
clientOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < iox::MAX_CLIENTS; ++i)
{
auto clientPort = m_runtime->getMiddlewareClient(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_THAT(clientPort, Ne(nullptr));
}
EXPECT_FALSE(clientOverflowDetected);
auto clientPort = m_runtime->getMiddlewareClient(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_THAT(clientPort, Eq(nullptr));
EXPECT_TRUE(clientOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithInvalidNodeNameLeadsToErrorHandlerCall)
{
::testing::Test::RecordProperty("TEST_ID", "b4433dfd-d2f8-4567-9483-aed956275ce8");
const iox::capro::ServiceDescription sd{"99", "19", "200"};
iox::popo::ClientOptions clientOptions;
clientOptions.nodeName = m_invalidNodeName;
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->getMiddlewareClient(sd, clientOptions);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_REQUEST_CLIENT_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithDefaultArgsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "cb3c1b4d-0d81-494c-954d-c1de10c244d7");
const iox::capro::ServiceDescription sd{"811", "1", "20"};
iox::popo::ServerOptions defaultOptions;
iox::runtime::PortConfigInfo defaultPortConfigInfo;
auto serverPort = m_runtime->getMiddlewareServer(sd);
ASSERT_THAT(serverPort, Ne(nullptr));
checkServerInitialization(serverPort, sd, defaultOptions, defaultPortConfigInfo.memoryInfo);
EXPECT_EQ(serverPort->m_offered, true);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithCustomServerOptionsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "881c342c-58b9-4094-9e77-b4e68ab9a52a");
const iox::capro::ServiceDescription sd{"811", "1", "20"};
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 13U;
serverOptions.nodeName = m_nodeName;
serverOptions.offerOnCreate = false;
serverOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
serverOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
const iox::runtime::PortConfigInfo portConfig{11U, 22U, 33U};
auto serverPort = m_runtime->getMiddlewareServer(sd, serverOptions, portConfig);
ASSERT_THAT(serverPort, Ne(nullptr));
checkServerInitialization(serverPort, sd, serverOptions, portConfig.memoryInfo);
EXPECT_EQ(serverPort->m_offered, false);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithQueueGreaterMaxCapacityClampsQueueToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "91b21e80-0f98-4ae3-982c-54deaab93d96");
constexpr uint64_t MAX_QUEUE_CAPACITY = iox::popo::ServerChunkQueueConfig::MAX_QUEUE_CAPACITY;
const iox::capro::ServiceDescription sd{"819", "1", "20"};
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = MAX_QUEUE_CAPACITY + 1U;
auto serverPort = m_runtime->getMiddlewareServer(sd, serverOptions);
ASSERT_THAT(serverPort, Ne(nullptr));
EXPECT_EQ(serverPort->m_chunkReceiverData.m_queue.capacity(), MAX_QUEUE_CAPACITY);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithQueueCapacityZeroClampsQueueCapacityToOne)
{
::testing::Test::RecordProperty("TEST_ID", "a28a30eb-f3be-43c9-a948-26c71c5f12c9");
const iox::capro::ServiceDescription sd{"89", "19", "20"};
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 0U;
auto serverPort = m_runtime->getMiddlewareServer(sd, serverOptions);
ASSERT_THAT(serverPort, Ne(nullptr));
EXPECT_EQ(serverPort->m_chunkReceiverData.m_queue.capacity(), 1U);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWhenMaxServerAreUsedResultsInServerlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "8f679838-3332-440c-aa95-d5c82d53a7cd");
auto serverOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__SERVERLIST_OVERFLOW)
{
serverOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < iox::MAX_SERVERS; ++i)
{
auto serverPort = m_runtime->getMiddlewareServer(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_THAT(serverPort, Ne(nullptr));
}
EXPECT_FALSE(serverOverflowDetected);
auto serverPort = m_runtime->getMiddlewareServer(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_THAT(serverPort, Eq(nullptr));
EXPECT_TRUE(serverOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithInvalidNodeNameLeadsToErrorHandlerCall)
{
::testing::Test::RecordProperty("TEST_ID", "95603ddc-1051-4dd7-a163-1c621f8a211a");
const iox::capro::ServiceDescription sd{"89", "19", "200"};
iox::popo::ServerOptions serverOptions;
serverOptions.nodeName = m_invalidNodeName;
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->getMiddlewareServer(sd, serverOptions);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_REQUEST_SERVER_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, GetMiddlewareConditionVariableIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "f2ccdca8-53ec-46d8-a34e-f56f996f57e0");
auto conditionVariable = m_runtime->getMiddlewareConditionVariable();
ASSERT_NE(nullptr, conditionVariable);
}
TEST_F(PoshRuntime_test, GetMiddlewareConditionVariableListOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "6776a648-03c7-4bd0-ab24-72ed7e118e4f");
auto conditionVariableListOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&conditionVariableListOverflowDetected](
const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__CONDITION_VARIABLE_LIST_OVERFLOW)
{
conditionVariableListOverflowDetected = true;
}
});
for (uint32_t i = 0U; i < iox::MAX_NUMBER_OF_CONDITION_VARIABLES; ++i)
{
auto conditionVariable = m_runtime->getMiddlewareConditionVariable();
ASSERT_NE(nullptr, conditionVariable);
}
EXPECT_FALSE(conditionVariableListOverflowDetected);
auto conditionVariable = m_runtime->getMiddlewareConditionVariable();
EXPECT_EQ(nullptr, conditionVariable);
EXPECT_TRUE(conditionVariableListOverflowDetected);
}
TEST_F(PoshRuntime_test, CreateNodeReturnValue)
{
::testing::Test::RecordProperty("TEST_ID", "9f56126d-6920-491f-ba6b-d8e543a15c6a");
const uint32_t nodeDeviceIdentifier = 1U;
iox::runtime::NodeProperty nodeProperty(m_nodeName, nodeDeviceIdentifier);
auto nodeData = m_runtime->createNode(nodeProperty);
EXPECT_EQ(m_runtimeName, nodeData->m_runtimeName);
EXPECT_EQ(m_nodeName, nodeData->m_nodeName);
/// @todo I am passing nodeDeviceIdentifier as 1, but it returns 0, is this expected?
// EXPECT_EQ(nodeDeviceIdentifier, nodeData->m_nodeDeviceIdentifier);
}
TEST_F(PoshRuntime_test, CreatingNodeWithInvalidNodeNameLeadsToErrorHandlerCall)
{
::testing::Test::RecordProperty("TEST_ID", "de0254ab-c413-4dbe-83c5-2b16fb8fb88f");
const uint32_t nodeDeviceIdentifier = 1U;
iox::runtime::NodeProperty nodeProperty(m_invalidNodeName, nodeDeviceIdentifier);
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->createNode(nodeProperty);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_CREATE_NODE_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, ShutdownUnblocksBlockingPublisher)
{
::testing::Test::RecordProperty("TEST_ID", "c3a97770-ee9a-46a4-baf7-80ebbac74f4b");
// get publisher and subscriber
iox::capro::ServiceDescription serviceDescription{"don't", "stop", "me"};
iox::popo::PublisherOptions publisherOptions{
0U, iox::NodeName_t("node"), true, iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER};
iox::popo::SubscriberOptions subscriberOptions{
1U, 0U, iox::NodeName_t("node"), true, iox::popo::QueueFullPolicy::BLOCK_PRODUCER};
iox::popo::Publisher<uint8_t> publisher{serviceDescription, publisherOptions};
iox::popo::Subscriber<uint8_t> subscriber{serviceDescription, subscriberOptions};
ASSERT_TRUE(publisher.hasSubscribers());
ASSERT_THAT(subscriber.getSubscriptionState(), Eq(iox::SubscribeState::SUBSCRIBED));
// send samples to fill subscriber queue
ASSERT_FALSE(publisher.publishCopyOf(42U).has_error());
auto threadSyncSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U);
std::atomic_bool wasSampleSent{false};
constexpr iox::units::Duration DEADLOCK_TIMEOUT{5_s};
Watchdog deadlockWatchdog{DEADLOCK_TIMEOUT};
deadlockWatchdog.watchAndActOnFailure([] { std::terminate(); });
// block in a separate thread
std::thread blockingPublisher([&] {
ASSERT_FALSE(threadSyncSemaphore->post().has_error());
ASSERT_FALSE(publisher.publishCopyOf(42U).has_error());
wasSampleSent = true;
});
// wait some time to check if the publisher is blocked
constexpr int64_t SLEEP_IN_MS = 100;
ASSERT_FALSE(threadSyncSemaphore->wait().has_error());
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_IN_MS));
EXPECT_THAT(wasSampleSent.load(), Eq(false));
m_runtime->shutdown();
blockingPublisher.join(); // ensure the wasChunkSent store happens before the read
EXPECT_THAT(wasSampleSent.load(), Eq(true));
}
TEST_F(PoshRuntime_test, ShutdownUnblocksBlockingClient)
{
::testing::Test::RecordProperty("TEST_ID", "f67db1c5-8db9-4798-b73c-7175255c90fd");
// get publisher and subscriber
iox::capro::ServiceDescription serviceDescription{"don't", "stop", "me"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 10U;
clientOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
clientOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 1U;
serverOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
serverOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::UntypedClient client{serviceDescription, clientOptions};
iox::popo::UntypedServer server{serviceDescription, serverOptions};
std::this_thread::sleep_for(std::chrono::milliseconds(300));
ASSERT_TRUE(server.hasClients());
ASSERT_THAT(client.getConnectionState(), Eq(iox::ConnectionState::CONNECTED));
auto threadSyncSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U);
std::atomic_bool wasRequestSent{false};
constexpr iox::units::Duration DEADLOCK_TIMEOUT{5_s};
Watchdog deadlockWatchdog{DEADLOCK_TIMEOUT};
deadlockWatchdog.watchAndActOnFailure([] { std::terminate(); });
// block in a separate thread
std::thread blockingServer([&] {
auto sendRequest = [&]() {
auto clientLoanResult = client.loan(sizeof(uint64_t), alignof(uint64_t));
ASSERT_FALSE(clientLoanResult.has_error());
client.send(clientLoanResult.value());
};
// send request till queue is full
for (uint64_t i = 0; i < serverOptions.requestQueueCapacity; ++i)
{
sendRequest();
}
// signal that an blocking send is expected
ASSERT_FALSE(threadSyncSemaphore->post().has_error());
sendRequest();
wasRequestSent = true;
});
// wait some time to check if the client is blocked
constexpr int64_t SLEEP_IN_MS = 100;
ASSERT_FALSE(threadSyncSemaphore->wait().has_error());
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_IN_MS));
EXPECT_THAT(wasRequestSent.load(), Eq(false));
m_runtime->shutdown();
blockingServer.join(); // ensure the wasRequestSent store happens before the read
EXPECT_THAT(wasRequestSent.load(), Eq(true));
}
TEST_F(PoshRuntime_test, ShutdownUnblocksBlockingServer)
{
::testing::Test::RecordProperty("TEST_ID", "f67db1c5-8db9-4798-b73c-7175255c90fd");
// get publisher and subscriber
iox::capro::ServiceDescription serviceDescription{"don't", "stop", "me"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 1U;
clientOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
clientOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 10U;
serverOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
serverOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::UntypedClient client{serviceDescription, clientOptions};
iox::popo::UntypedServer server{serviceDescription, serverOptions};
std::this_thread::sleep_for(std::chrono::milliseconds(300));
ASSERT_TRUE(server.hasClients());
ASSERT_THAT(client.getConnectionState(), Eq(iox::ConnectionState::CONNECTED));
// send requests to fill request queue
for (uint64_t i = 0; i < clientOptions.responseQueueCapacity + 1; ++i)
{
auto clientLoanResult = client.loan(sizeof(uint64_t), alignof(uint64_t));
ASSERT_FALSE(clientLoanResult.has_error());
client.send(clientLoanResult.value());
}
auto threadSyncSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U);
std::atomic_bool wasResponseSent{false};
constexpr iox::units::Duration DEADLOCK_TIMEOUT{5_s};
Watchdog deadlockWatchdog{DEADLOCK_TIMEOUT};
deadlockWatchdog.watchAndActOnFailure([] { std::terminate(); });
// block in a separate thread
std::thread blockingServer([&] {
auto processRequest = [&]() {
auto takeResult = server.take();
ASSERT_FALSE(takeResult.has_error());
auto loanResult = server.loan(
iox::popo::RequestHeader::fromPayload(takeResult.value()), sizeof(uint64_t), alignof(uint64_t));
ASSERT_FALSE(loanResult.has_error());
server.send(loanResult.value());
};
for (uint64_t i = 0; i < clientOptions.responseQueueCapacity; ++i)
{
processRequest();
}
ASSERT_FALSE(threadSyncSemaphore->post().has_error());
processRequest();
wasResponseSent = true;
});
// wait some time to check if the server is blocked
constexpr int64_t SLEEP_IN_MS = 100;
ASSERT_FALSE(threadSyncSemaphore->wait().has_error());
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_IN_MS));
EXPECT_THAT(wasResponseSent.load(), Eq(false));
m_runtime->shutdown();
blockingServer.join(); // ensure the wasResponseSent store happens before the read
EXPECT_THAT(wasResponseSent.load(), Eq(true));
}
TEST(PoshRuntimeFactory_test, SetValidRuntimeFactorySucceeds)
{
::testing::Test::RecordProperty("TEST_ID", "59c4e1e6-36f6-4f6d-b4c2-e84fa891f014");
constexpr const char HYPNOTOAD[]{"hypnotoad"};
constexpr const char BRAIN_SLUG[]{"brain-slug"};
auto mockRuntime = PoshRuntimeMock::create(HYPNOTOAD);
EXPECT_THAT(PoshRuntime::getInstance().getInstanceName().c_str(), StrEq(HYPNOTOAD));
mockRuntime.reset();
// if the PoshRuntimeMock could not change the runtime factory, the instance name would still be the old one
mockRuntime = PoshRuntimeMock::create(BRAIN_SLUG);
EXPECT_THAT(PoshRuntime::getInstance().getInstanceName().c_str(), StrEq(BRAIN_SLUG));
}
TEST(PoshRuntimeFactory_test, SetEmptyRuntimeFactoryFails)
{
::testing::Test::RecordProperty("TEST_ID", "530ec778-b480-4a1e-8562-94f93cee2f5c");
// this ensures resetting of the runtime factory in case the death test doesn't succeed
auto mockRuntime = PoshRuntimeMock::create("hypnotoad");
// do not use the setRuntimeFactory in a test with a running RouDiEnvironment
EXPECT_DEATH(
{
class FactoryAccess : public PoshRuntime
{
public:
using PoshRuntime::factory_t;
using PoshRuntime::setRuntimeFactory;
private:
FactoryAccess(iox::cxx::optional<const iox::RuntimeName_t*> s)
: PoshRuntime(s)
{
}
};
FactoryAccess::setRuntimeFactory(FactoryAccess::factory_t());
},
"Cannot set runtime factory. Passed factory must not be empty!");
}
} // namespace
iox-#27 Randomize test service descriptions
// Copyright (c) 2020 - 2021 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2020 - 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_hoofs/cxx/convert.hpp"
#include "iceoryx_hoofs/testing/timing_test.hpp"
#include "iceoryx_hoofs/testing/watch_dog.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/popo/publisher.hpp"
#include "iceoryx_posh/popo/subscriber.hpp"
#include "iceoryx_posh/popo/untyped_client.hpp"
#include "iceoryx_posh/popo/untyped_server.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "iceoryx_posh/testing/roudi_environment/roudi_environment.hpp"
#include "mocks/posh_runtime_mock.hpp"
#include "test.hpp"
#include <type_traits>
namespace
{
using namespace ::testing;
using namespace iox::runtime;
using namespace iox::capro;
using namespace iox::cxx;
using namespace iox::popo;
using iox::roudi::RouDiEnvironment;
class PoshRuntime_test : public Test
{
public:
PoshRuntime_test()
{
}
virtual ~PoshRuntime_test()
{
}
virtual void SetUp()
{
testing::internal::CaptureStdout();
};
virtual void TearDown()
{
std::string output = testing::internal::GetCapturedStdout();
if (Test::HasFailure())
{
std::cout << output << std::endl;
}
};
void InterOpWait()
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
void checkClientInitialization(const ClientPortData* const portData,
const ServiceDescription& sd,
const ClientOptions& options,
const iox::mepoo::MemoryInfo& memoryInfo) const
{
ASSERT_THAT(portData, Ne(nullptr));
EXPECT_EQ(portData->m_serviceDescription, sd);
EXPECT_EQ(portData->m_runtimeName, m_runtimeName);
EXPECT_EQ(portData->m_nodeName, options.nodeName);
EXPECT_EQ(portData->m_connectRequested, options.connectOnCreate);
EXPECT_EQ(portData->m_chunkReceiverData.m_queue.capacity(), options.responseQueueCapacity);
EXPECT_EQ(portData->m_chunkReceiverData.m_queueFullPolicy, options.responseQueueFullPolicy);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.memoryType, memoryInfo.memoryType);
EXPECT_EQ(portData->m_chunkSenderData.m_historyCapacity, iox::popo::ClientPortData::HISTORY_CAPACITY_ZERO);
EXPECT_EQ(portData->m_chunkSenderData.m_consumerTooSlowPolicy, options.serverTooSlowPolicy);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.memoryType, memoryInfo.memoryType);
}
void checkServerInitialization(const ServerPortData* const portData,
const ServiceDescription& sd,
const ServerOptions& options,
const iox::mepoo::MemoryInfo& memoryInfo) const
{
ASSERT_THAT(portData, Ne(nullptr));
EXPECT_EQ(portData->m_serviceDescription, sd);
EXPECT_EQ(portData->m_runtimeName, m_runtimeName);
EXPECT_EQ(portData->m_nodeName, options.nodeName);
EXPECT_EQ(portData->m_offeringRequested, options.offerOnCreate);
EXPECT_EQ(portData->m_chunkReceiverData.m_queue.capacity(), options.requestQueueCapacity);
EXPECT_EQ(portData->m_chunkReceiverData.m_queueFullPolicy, options.requestQueueFullPolicy);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkReceiverData.m_memoryInfo.memoryType, memoryInfo.memoryType);
EXPECT_EQ(portData->m_chunkSenderData.m_historyCapacity, iox::popo::ServerPortData::HISTORY_REQUEST_OF_ZERO);
EXPECT_EQ(portData->m_chunkSenderData.m_consumerTooSlowPolicy, options.clientTooSlowPolicy);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.deviceId, memoryInfo.deviceId);
EXPECT_EQ(portData->m_chunkSenderData.m_memoryInfo.memoryType, memoryInfo.memoryType);
}
const iox::RuntimeName_t m_runtimeName{"publisher"};
RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
PoshRuntime* m_runtime{&iox::runtime::PoshRuntime::initRuntime(m_runtimeName)};
IpcMessage m_sendBuffer;
IpcMessage m_receiveBuffer;
const iox::NodeName_t m_nodeName{"testNode"};
const iox::NodeName_t m_invalidNodeName{"invalidNode,"};
};
TEST_F(PoshRuntime_test, ValidAppName)
{
::testing::Test::RecordProperty("TEST_ID", "2f4f5dc1-dde0-4520-a341-79a5edd19900");
iox::RuntimeName_t appName("valid_name");
EXPECT_NO_FATAL_FAILURE({ PoshRuntime::initRuntime(appName); });
}
TEST_F(PoshRuntime_test, MaxAppNameLength)
{
::testing::Test::RecordProperty("TEST_ID", "dfdf3ce1-c7d4-4c57-94ea-6ed9479371e3");
std::string maxValidName(iox::MAX_RUNTIME_NAME_LENGTH, 's');
auto& runtime = PoshRuntime::initRuntime(iox::RuntimeName_t(iox::cxx::TruncateToCapacity, maxValidName));
EXPECT_THAT(maxValidName, StrEq(runtime.getInstanceName().c_str()));
}
TEST_F(PoshRuntime_test, NoAppName)
{
::testing::Test::RecordProperty("TEST_ID", "e053d114-c79c-4391-91e1-8fcfe90ee8e4");
const iox::RuntimeName_t invalidAppName("");
EXPECT_DEATH({ PoshRuntime::initRuntime(invalidAppName); },
"Cannot initialize runtime. Application name must not be empty!");
}
// To be able to test the singleton and avoid return the exisiting instance, we don't use the test fixture
TEST(PoshRuntime, LeadingSlashAppName)
{
::testing::Test::RecordProperty("TEST_ID", "77542d11-6230-4c1e-94b2-6cf3b8fa9c6e");
RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
const iox::RuntimeName_t invalidAppName = "/miau";
auto errorHandlerCalled{false};
iox::Error receivedError{iox::Error::kNO_ERROR};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&errorHandlerCalled,
&receivedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
errorHandlerCalled = true;
receivedError = error;
});
PoshRuntime::initRuntime(invalidAppName);
EXPECT_TRUE(errorHandlerCalled);
ASSERT_THAT(receivedError, Eq(iox::Error::kPOSH__RUNTIME_LEADING_SLASH_PROVIDED));
}
// since getInstance is a singleton and test class creates instance of Poshruntime
// when getInstance() is called without parameter, it returns existing instance
// To be able to test this, we don't use the test fixture
TEST(PoshRuntime, AppNameEmpty)
{
::testing::Test::RecordProperty("TEST_ID", "63900656-4fbb-466d-b6cc-f2139121092c");
EXPECT_DEATH({ iox::runtime::PoshRuntime::getInstance(); },
"Cannot initialize runtime. Application name has not been specified!");
}
TEST_F(PoshRuntime_test, GetInstanceNameIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "b82d419c-2c72-43b0-9eb1-b24bb41366ce");
const iox::RuntimeName_t appname = "app";
auto& sut = PoshRuntime::initRuntime(appname);
EXPECT_EQ(sut.getInstanceName(), appname);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterfaceWithInvalidNodeNameIsNotSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "d207e121-d7c2-4a23-a202-1af311f6982b");
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL, m_invalidNodeName);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_GET_MW_INTERFACE_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, GetMiddlewareInterfaceIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "50b1d15d-0cee-41b3-a9cd-146eca553cc2");
const auto interfacePortData = m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL, m_nodeName);
ASSERT_NE(nullptr, interfacePortData);
EXPECT_EQ(m_runtimeName, interfacePortData->m_runtimeName);
EXPECT_EQ(false, interfacePortData->m_toBeDestroyed);
}
TEST_F(PoshRuntime_test, GetMiddlewareInterfaceInterfacelistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "0e164d07-dede-46c3-b2a3-ad78a11c0691");
auto interfacelistOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&interfacelistOverflowDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
interfacelistOverflowDetected = true;
EXPECT_THAT(error, Eq(iox::Error::kPORT_POOL__INTERFACELIST_OVERFLOW));
});
for (auto i = 0U; i < iox::MAX_INTERFACE_NUMBER; ++i)
{
auto interfacePort = m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL);
ASSERT_NE(nullptr, interfacePort);
}
EXPECT_FALSE(interfacelistOverflowDetected);
auto interfacePort = m_runtime->getMiddlewareInterface(iox::capro::Interfaces::INTERNAL);
EXPECT_EQ(nullptr, interfacePort);
EXPECT_TRUE(interfacelistOverflowDetected);
}
TEST_F(PoshRuntime_test, SendRequestToRouDiValidMessage)
{
::testing::Test::RecordProperty("TEST_ID", "334e49d8-e826-4e21-9f9f-bb9c341d4706");
m_sendBuffer << IpcMessageTypeToString(IpcMessageType::CREATE_INTERFACE) << m_runtimeName
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_nodeName;
const auto successfullySent = m_runtime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_TRUE(m_receiveBuffer.isValid());
EXPECT_TRUE(successfullySent);
}
TEST_F(PoshRuntime_test, SendRequestToRouDiInvalidMessage)
{
::testing::Test::RecordProperty("TEST_ID", "b3f4563a-7237-4f57-8952-c39ac3dbfef2");
m_sendBuffer << IpcMessageTypeToString(IpcMessageType::CREATE_INTERFACE) << m_runtimeName
<< static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidNodeName;
const auto successfullySent = m_runtime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);
EXPECT_FALSE(successfullySent);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "2cb2e64b-8f21-4049-a35a-dbd7a1d6cbf4");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.historyCapacity = 13U;
publisherOptions.nodeName = m_nodeName;
const auto publisherPort = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription("99", "1", "20"), publisherOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
ASSERT_NE(nullptr, publisherPort);
EXPECT_EQ(iox::capro::ServiceDescription("99", "1", "20"), publisherPort->m_serviceDescription);
EXPECT_EQ(publisherOptions.historyCapacity, publisherPort->m_chunkSenderData.m_historyCapacity);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithHistoryGreaterMaxCapacityClampsHistoryToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "407f27bb-e507-4c1c-aab1-e5b1b8d06f46");
// arrange
iox::popo::PublisherOptions publisherOptions;
publisherOptions.historyCapacity = iox::MAX_PUBLISHER_HISTORY + 1U;
// act
const auto publisherPort =
m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("99", "1", "20"), publisherOptions);
// assert
ASSERT_NE(nullptr, publisherPort);
EXPECT_EQ(publisherPort->m_chunkSenderData.m_historyCapacity, iox::MAX_PUBLISHER_HISTORY);
}
TEST_F(PoshRuntime_test, getMiddlewarePublisherDefaultArgs)
{
::testing::Test::RecordProperty("TEST_ID", "1eae6dfa-c3f2-478b-9354-768c43bd8d96");
const auto publisherPort = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("99", "1", "20"));
ASSERT_NE(nullptr, publisherPort);
}
TEST_F(PoshRuntime_test, getMiddlewarePublisherPublisherlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "f1f1a662-9580-40a1-a116-6ea1cb791516");
auto publisherlistOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&publisherlistOverflowDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__PUBLISHERLIST_OVERFLOW)
{
publisherlistOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < (iox::MAX_PUBLISHERS - iox::NUMBER_OF_INTERNAL_PUBLISHERS); ++i)
{
auto publisherPort = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_NE(nullptr, publisherPort);
}
EXPECT_FALSE(publisherlistOverflowDetected);
auto publisherPort = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_EQ(nullptr, publisherPort);
EXPECT_TRUE(publisherlistOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithSameServiceDescriptionsAndOneToManyPolicyFails)
{
::testing::Test::RecordProperty("TEST_ID", "77fb6dfd-a00d-459e-9dd3-90010d7b8af7");
auto publisherDuplicateDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&publisherDuplicateDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPOSH__RUNTIME_PUBLISHER_PORT_NOT_UNIQUE)
{
publisherDuplicateDetected = true;
}
});
auto sameServiceDescription = iox::capro::ServiceDescription("99", "1", "20");
const auto publisherPort1 = m_runtime->getMiddlewarePublisher(
sameServiceDescription, iox::popo::PublisherOptions(), iox::runtime::PortConfigInfo(11U, 22U, 33U));
const auto publisherPort2 = m_runtime->getMiddlewarePublisher(
sameServiceDescription, iox::popo::PublisherOptions(), iox::runtime::PortConfigInfo(11U, 22U, 33U));
ASSERT_NE(nullptr, publisherPort1);
if (std::is_same<iox::build::CommunicationPolicy, iox::build::OneToManyPolicy>::value)
{
ASSERT_EQ(nullptr, publisherPort2);
EXPECT_TRUE(publisherDuplicateDetected);
}
else if (std::is_same<iox::build::CommunicationPolicy, iox::build::ManyToManyPolicy>::value)
{
ASSERT_NE(nullptr, publisherPort2);
}
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithoutOfferOnCreateLeadsToNotOfferedPublisherBeingCreated)
{
::testing::Test::RecordProperty("TEST_ID", "5002dc8c-1f6e-4593-a2b3-4de04685c919");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.offerOnCreate = false;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("69", "96", "1893"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_FALSE(publisherPortData->m_offeringRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithOfferOnCreateLeadsToOfferedPublisherBeingCreated)
{
::testing::Test::RecordProperty("TEST_ID", "639b1a0e-218d-4cde-a447-e2eec0cf2c75");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.offerOnCreate = true;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(
iox::capro::ServiceDescription("17", "4", "21"), publisherOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_TRUE(publisherPortData->m_offeringRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithoutExplicitlySetQueueFullPolicyLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "208418e2-64fd-47f4-b2e2-58aa4371a6a6");
iox::popo::PublisherOptions publisherOptions;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("9", "13", "1550"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(publisherPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
Eq(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithQueueFullPolicySetToDiscardOldestDataLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "67362686-3165-4a49-a15c-ac9fcaf704d8");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.subscriberTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA;
const auto publisherPortData =
m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("90", "130", "1550"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(publisherPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
Eq(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewarePublisherWithQueueFullPolicySetToWaitForSubscriberLeadsToWaitForSubscriber)
{
::testing::Test::RecordProperty("TEST_ID", "f6439a76-69c7-422d-bcc9-7c1d82cd2990");
iox::popo::PublisherOptions publisherOptions;
publisherOptions.subscriberTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
const auto publisherPortData = m_runtime->getMiddlewarePublisher(iox::capro::ServiceDescription("18", "31", "400"),
publisherOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(publisherPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
Eq(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER));
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "0cc05fe7-752e-4e2a-a8f2-be7cb8b384d2");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.historyRequest = 13U;
subscriberOptions.queueCapacity = 42U;
subscriberOptions.nodeName = m_nodeName;
auto subscriberPort = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("99", "1", "20"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
ASSERT_NE(nullptr, subscriberPort);
EXPECT_EQ(iox::capro::ServiceDescription("99", "1", "20"), subscriberPort->m_serviceDescription);
EXPECT_EQ(subscriberOptions.historyRequest, subscriberPort->m_options.historyRequest);
EXPECT_EQ(subscriberOptions.queueCapacity, subscriberPort->m_chunkReceiverData.m_queue.capacity());
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueGreaterMaxCapacityClampsQueueToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "85e2d246-bcba-4ead-a997-4c4137f05607");
iox::popo::SubscriberOptions subscriberOptions;
constexpr uint64_t MAX_QUEUE_CAPACITY = iox::popo::SubscriberPortUser::MemberType_t::ChunkQueueData_t::MAX_CAPACITY;
subscriberOptions.queueCapacity = MAX_QUEUE_CAPACITY + 1U;
auto subscriberPort = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("99", "1", "20"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_EQ(MAX_QUEUE_CAPACITY, subscriberPort->m_chunkReceiverData.m_queue.capacity());
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueCapacityZeroClampsQueueCapacityToOne)
{
::testing::Test::RecordProperty("TEST_ID", "9da3f4da-abe8-454c-9bc6-7f866d6d0545");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.queueCapacity = 0U;
auto subscriberPort = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription("34", "4", "4"), subscriberOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_EQ(1U, subscriberPort->m_chunkReceiverData.m_queue.capacity());
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberDefaultArgs)
{
::testing::Test::RecordProperty("TEST_ID", "e06b999c-e237-4e32-b826-a5ffdb6bb737");
auto subscriberPort = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("99", "1", "20"));
ASSERT_NE(nullptr, subscriberPort);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberSubscriberlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "d1281cbd-6520-424e-aace-fbd3aa5d73e9");
auto subscriberlistOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&subscriberlistOverflowDetected](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__SUBSCRIBERLIST_OVERFLOW)
{
subscriberlistOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < iox::MAX_SUBSCRIBERS; ++i)
{
auto subscriberPort = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_NE(nullptr, subscriberPort);
}
EXPECT_FALSE(subscriberlistOverflowDetected);
auto subscriberPort = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_EQ(nullptr, subscriberPort);
EXPECT_TRUE(subscriberlistOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithoutSubscribeOnCreateLeadsToSubscriberThatDoesNotWantToBeSubscribed)
{
::testing::Test::RecordProperty("TEST_ID", "a59e3629-9aae-43e1-b88b-5dab441b1f17");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.subscribeOnCreate = false;
auto subscriberPortData = m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("17", "17", "17"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_FALSE(subscriberPortData->m_subscribeRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithSubscribeOnCreateLeadsToSubscriberThatWantsToBeSubscribed)
{
::testing::Test::RecordProperty("TEST_ID", "975a6edc-cc39-46d0-9bb7-79ab69f18fc3");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.subscribeOnCreate = true;
auto subscriberPortData = m_runtime->getMiddlewareSubscriber(
iox::capro::ServiceDescription("1", "2", "3"), subscriberOptions, iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_TRUE(subscriberPortData->m_subscribeRequested);
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithoutExplicitlySetQueueFullPolicyLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "7fdd60c2-8b18-481c-8bad-5f6f70431196");
iox::popo::SubscriberOptions subscriberOptions;
const auto subscriberPortData =
m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("9", "13", "1550"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(subscriberPortData->m_chunkReceiverData.m_queueFullPolicy,
Eq(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueFullPolicySetToDiscardOldestDataLeadsToDiscardOldestData)
{
::testing::Test::RecordProperty("TEST_ID", "9e5df6bf-a752-4db8-9e27-ba5ae1f02a52");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.queueFullPolicy = iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA;
const auto subscriberPortData =
m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("90", "130", "1550"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(subscriberPortData->m_chunkReceiverData.m_queueFullPolicy,
Eq(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA));
}
TEST_F(PoshRuntime_test, GetMiddlewareSubscriberWithQueueFullPolicySetToBlockPublisherLeadsToBlockPublisher)
{
::testing::Test::RecordProperty("TEST_ID", "ab60b748-6425-4ebf-8041-285a29a92756");
iox::popo::SubscriberOptions subscriberOptions;
subscriberOptions.queueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
const auto subscriberPortData =
m_runtime->getMiddlewareSubscriber(iox::capro::ServiceDescription("18", "31", "400"),
subscriberOptions,
iox::runtime::PortConfigInfo(11U, 22U, 33U));
EXPECT_THAT(subscriberPortData->m_chunkReceiverData.m_queueFullPolicy,
Eq(iox::popo::QueueFullPolicy::BLOCK_PRODUCER));
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithDefaultArgsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "2db35746-e402-443f-b374-3b6a239ab5fd");
const iox::capro::ServiceDescription sd{"moon", "light", "drive"};
iox::popo::ClientOptions defaultOptions;
iox::runtime::PortConfigInfo defaultPortConfigInfo;
auto clientPort = m_runtime->getMiddlewareClient(sd);
ASSERT_THAT(clientPort, Ne(nullptr));
checkClientInitialization(clientPort, sd, defaultOptions, defaultPortConfigInfo.memoryInfo);
EXPECT_EQ(clientPort->m_connectionState, iox::ConnectionState::WAIT_FOR_OFFER);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithCustomClientOptionsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "f61a81f4-f610-4e61-853b-ac114d9a801c");
const iox::capro::ServiceDescription sd{"my", "guitar", "weeps"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 13U;
clientOptions.nodeName = m_nodeName;
clientOptions.connectOnCreate = false;
clientOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
clientOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
const iox::runtime::PortConfigInfo portConfig{11U, 22U, 33U};
auto clientPort = m_runtime->getMiddlewareClient(sd, clientOptions, portConfig);
ASSERT_THAT(clientPort, Ne(nullptr));
checkClientInitialization(clientPort, sd, clientOptions, portConfig.memoryInfo);
EXPECT_EQ(clientPort->m_connectionState, iox::ConnectionState::NOT_CONNECTED);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithQueueGreaterMaxCapacityClampsQueueToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "8e34f962-e7c9-40ac-9796-a12f92c4d674");
constexpr uint64_t MAX_QUEUE_CAPACITY = iox::popo::ClientChunkQueueConfig::MAX_QUEUE_CAPACITY;
const iox::capro::ServiceDescription sd{"take", "guns", "down"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = MAX_QUEUE_CAPACITY + 1U;
auto clientPort = m_runtime->getMiddlewareClient(sd, clientOptions);
ASSERT_THAT(clientPort, Ne(nullptr));
EXPECT_EQ(clientPort->m_chunkReceiverData.m_queue.capacity(), MAX_QUEUE_CAPACITY);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithQueueCapacityZeroClampsQueueCapacityToOne)
{
::testing::Test::RecordProperty("TEST_ID", "7b6ffd68-46d4-4339-a0df-6fecb621f765");
const iox::capro::ServiceDescription sd{"rock", "and", "roll"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 0U;
auto clientPort = m_runtime->getMiddlewareClient(sd, clientOptions);
ASSERT_THAT(clientPort, Ne(nullptr));
EXPECT_EQ(clientPort->m_chunkReceiverData.m_queue.capacity(), 1U);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWhenMaxClientsAreUsedResultsInClientlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "6f2de2bf-5e7e-47b1-be42-92cf3fa71ba6");
auto clientOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__CLIENTLIST_OVERFLOW)
{
clientOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < iox::MAX_CLIENTS; ++i)
{
auto clientPort = m_runtime->getMiddlewareClient(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_THAT(clientPort, Ne(nullptr));
}
EXPECT_FALSE(clientOverflowDetected);
auto clientPort = m_runtime->getMiddlewareClient(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_THAT(clientPort, Eq(nullptr));
EXPECT_TRUE(clientOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewareClientWithInvalidNodeNameLeadsToErrorHandlerCall)
{
::testing::Test::RecordProperty("TEST_ID", "b4433dfd-d2f8-4567-9483-aed956275ce8");
const iox::capro::ServiceDescription sd{"great", "gig", "sky"};
iox::popo::ClientOptions clientOptions;
clientOptions.nodeName = m_invalidNodeName;
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->getMiddlewareClient(sd, clientOptions);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_REQUEST_CLIENT_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithDefaultArgsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "cb3c1b4d-0d81-494c-954d-c1de10c244d7");
const iox::capro::ServiceDescription sd{"ghouls", "night", "out"};
iox::popo::ServerOptions defaultOptions;
iox::runtime::PortConfigInfo defaultPortConfigInfo;
auto serverPort = m_runtime->getMiddlewareServer(sd);
ASSERT_THAT(serverPort, Ne(nullptr));
checkServerInitialization(serverPort, sd, defaultOptions, defaultPortConfigInfo.memoryInfo);
EXPECT_EQ(serverPort->m_offered, true);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithCustomServerOptionsIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "881c342c-58b9-4094-9e77-b4e68ab9a52a");
const iox::capro::ServiceDescription sd{"take", "power", "back"};
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 13U;
serverOptions.nodeName = m_nodeName;
serverOptions.offerOnCreate = false;
serverOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
serverOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
const iox::runtime::PortConfigInfo portConfig{11U, 22U, 33U};
auto serverPort = m_runtime->getMiddlewareServer(sd, serverOptions, portConfig);
ASSERT_THAT(serverPort, Ne(nullptr));
checkServerInitialization(serverPort, sd, serverOptions, portConfig.memoryInfo);
EXPECT_EQ(serverPort->m_offered, false);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithQueueGreaterMaxCapacityClampsQueueToMaximum)
{
::testing::Test::RecordProperty("TEST_ID", "91b21e80-0f98-4ae3-982c-54deaab93d96");
constexpr uint64_t MAX_QUEUE_CAPACITY = iox::popo::ServerChunkQueueConfig::MAX_QUEUE_CAPACITY;
const iox::capro::ServiceDescription sd{"stray", "cat", "blues"};
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = MAX_QUEUE_CAPACITY + 1U;
auto serverPort = m_runtime->getMiddlewareServer(sd, serverOptions);
ASSERT_THAT(serverPort, Ne(nullptr));
EXPECT_EQ(serverPort->m_chunkReceiverData.m_queue.capacity(), MAX_QUEUE_CAPACITY);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithQueueCapacityZeroClampsQueueCapacityToOne)
{
::testing::Test::RecordProperty("TEST_ID", "a28a30eb-f3be-43c9-a948-26c71c5f12c9");
const iox::capro::ServiceDescription sd{"she", "talks", "rainbow"};
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 0U;
auto serverPort = m_runtime->getMiddlewareServer(sd, serverOptions);
ASSERT_THAT(serverPort, Ne(nullptr));
EXPECT_EQ(serverPort->m_chunkReceiverData.m_queue.capacity(), 1U);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWhenMaxServerAreUsedResultsInServerlistOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "8f679838-3332-440c-aa95-d5c82d53a7cd");
auto serverOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__SERVERLIST_OVERFLOW)
{
serverOverflowDetected = true;
}
});
uint32_t i{0U};
for (; i < iox::MAX_SERVERS; ++i)
{
auto serverPort = m_runtime->getMiddlewareServer(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
ASSERT_THAT(serverPort, Ne(nullptr));
}
EXPECT_FALSE(serverOverflowDetected);
auto serverPort = m_runtime->getMiddlewareServer(
iox::capro::ServiceDescription(iox::capro::IdString_t(TruncateToCapacity, convert::toString(i)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 1U)),
iox::capro::IdString_t(TruncateToCapacity, convert::toString(i + 2U))));
EXPECT_THAT(serverPort, Eq(nullptr));
EXPECT_TRUE(serverOverflowDetected);
}
TEST_F(PoshRuntime_test, GetMiddlewareServerWithInvalidNodeNameLeadsToErrorHandlerCall)
{
::testing::Test::RecordProperty("TEST_ID", "95603ddc-1051-4dd7-a163-1c621f8a211a");
const iox::capro::ServiceDescription sd{"it's", "over", "now"};
iox::popo::ServerOptions serverOptions;
serverOptions.nodeName = m_invalidNodeName;
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->getMiddlewareServer(sd, serverOptions);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_REQUEST_SERVER_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, GetMiddlewareConditionVariableIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "f2ccdca8-53ec-46d8-a34e-f56f996f57e0");
auto conditionVariable = m_runtime->getMiddlewareConditionVariable();
ASSERT_NE(nullptr, conditionVariable);
}
TEST_F(PoshRuntime_test, GetMiddlewareConditionVariableListOverflow)
{
::testing::Test::RecordProperty("TEST_ID", "6776a648-03c7-4bd0-ab24-72ed7e118e4f");
auto conditionVariableListOverflowDetected{false};
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&conditionVariableListOverflowDetected](
const iox::Error error, const std::function<void()>, const iox::ErrorLevel) {
if (error == iox::Error::kPORT_POOL__CONDITION_VARIABLE_LIST_OVERFLOW)
{
conditionVariableListOverflowDetected = true;
}
});
for (uint32_t i = 0U; i < iox::MAX_NUMBER_OF_CONDITION_VARIABLES; ++i)
{
auto conditionVariable = m_runtime->getMiddlewareConditionVariable();
ASSERT_NE(nullptr, conditionVariable);
}
EXPECT_FALSE(conditionVariableListOverflowDetected);
auto conditionVariable = m_runtime->getMiddlewareConditionVariable();
EXPECT_EQ(nullptr, conditionVariable);
EXPECT_TRUE(conditionVariableListOverflowDetected);
}
TEST_F(PoshRuntime_test, CreateNodeReturnValue)
{
::testing::Test::RecordProperty("TEST_ID", "9f56126d-6920-491f-ba6b-d8e543a15c6a");
const uint32_t nodeDeviceIdentifier = 1U;
iox::runtime::NodeProperty nodeProperty(m_nodeName, nodeDeviceIdentifier);
auto nodeData = m_runtime->createNode(nodeProperty);
EXPECT_EQ(m_runtimeName, nodeData->m_runtimeName);
EXPECT_EQ(m_nodeName, nodeData->m_nodeName);
/// @todo I am passing nodeDeviceIdentifier as 1, but it returns 0, is this expected?
// EXPECT_EQ(nodeDeviceIdentifier, nodeData->m_nodeDeviceIdentifier);
}
TEST_F(PoshRuntime_test, CreatingNodeWithInvalidNodeNameLeadsToErrorHandlerCall)
{
::testing::Test::RecordProperty("TEST_ID", "de0254ab-c413-4dbe-83c5-2b16fb8fb88f");
const uint32_t nodeDeviceIdentifier = 1U;
iox::runtime::NodeProperty nodeProperty(m_invalidNodeName, nodeDeviceIdentifier);
iox::cxx::optional<iox::Error> detectedError;
auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
[&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
detectedError.emplace(error);
EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::SEVERE));
});
m_runtime->createNode(nodeProperty);
ASSERT_THAT(detectedError.has_value(), Eq(true));
EXPECT_THAT(detectedError.value(), Eq(iox::Error::kPOSH__RUNTIME_ROUDI_CREATE_NODE_INVALID_RESPONSE));
}
TEST_F(PoshRuntime_test, ShutdownUnblocksBlockingPublisher)
{
::testing::Test::RecordProperty("TEST_ID", "c3a97770-ee9a-46a4-baf7-80ebbac74f4b");
// get publisher and subscriber
iox::capro::ServiceDescription serviceDescription{"don't", "stop", "me"};
iox::popo::PublisherOptions publisherOptions{
0U, iox::NodeName_t("node"), true, iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER};
iox::popo::SubscriberOptions subscriberOptions{
1U, 0U, iox::NodeName_t("node"), true, iox::popo::QueueFullPolicy::BLOCK_PRODUCER};
iox::popo::Publisher<uint8_t> publisher{serviceDescription, publisherOptions};
iox::popo::Subscriber<uint8_t> subscriber{serviceDescription, subscriberOptions};
ASSERT_TRUE(publisher.hasSubscribers());
ASSERT_THAT(subscriber.getSubscriptionState(), Eq(iox::SubscribeState::SUBSCRIBED));
// send samples to fill subscriber queue
ASSERT_FALSE(publisher.publishCopyOf(42U).has_error());
auto threadSyncSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U);
std::atomic_bool wasSampleSent{false};
constexpr iox::units::Duration DEADLOCK_TIMEOUT{5_s};
Watchdog deadlockWatchdog{DEADLOCK_TIMEOUT};
deadlockWatchdog.watchAndActOnFailure([] { std::terminate(); });
// block in a separate thread
std::thread blockingPublisher([&] {
ASSERT_FALSE(threadSyncSemaphore->post().has_error());
ASSERT_FALSE(publisher.publishCopyOf(42U).has_error());
wasSampleSent = true;
});
// wait some time to check if the publisher is blocked
constexpr int64_t SLEEP_IN_MS = 100;
ASSERT_FALSE(threadSyncSemaphore->wait().has_error());
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_IN_MS));
EXPECT_THAT(wasSampleSent.load(), Eq(false));
m_runtime->shutdown();
blockingPublisher.join(); // ensure the wasChunkSent store happens before the read
EXPECT_THAT(wasSampleSent.load(), Eq(true));
}
TEST_F(PoshRuntime_test, ShutdownUnblocksBlockingClient)
{
::testing::Test::RecordProperty("TEST_ID", "f67db1c5-8db9-4798-b73c-7175255c90fd");
// get client and server
iox::capro::ServiceDescription serviceDescription{"stop", "and", "smell"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 10U;
clientOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
clientOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 1U;
serverOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
serverOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::UntypedClient client{serviceDescription, clientOptions};
iox::popo::UntypedServer server{serviceDescription, serverOptions};
std::this_thread::sleep_for(std::chrono::milliseconds(300));
ASSERT_TRUE(server.hasClients());
ASSERT_THAT(client.getConnectionState(), Eq(iox::ConnectionState::CONNECTED));
auto threadSyncSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U);
std::atomic_bool wasRequestSent{false};
constexpr iox::units::Duration DEADLOCK_TIMEOUT{5_s};
Watchdog deadlockWatchdog{DEADLOCK_TIMEOUT};
deadlockWatchdog.watchAndActOnFailure([] { std::terminate(); });
// block in a separate thread
std::thread blockingServer([&] {
auto sendRequest = [&]() {
auto clientLoanResult = client.loan(sizeof(uint64_t), alignof(uint64_t));
ASSERT_FALSE(clientLoanResult.has_error());
client.send(clientLoanResult.value());
};
// send request till queue is full
for (uint64_t i = 0; i < serverOptions.requestQueueCapacity; ++i)
{
sendRequest();
}
// signal that an blocking send is expected
ASSERT_FALSE(threadSyncSemaphore->post().has_error());
sendRequest();
wasRequestSent = true;
});
// wait some time to check if the client is blocked
constexpr int64_t SLEEP_IN_MS = 100;
ASSERT_FALSE(threadSyncSemaphore->wait().has_error());
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_IN_MS));
EXPECT_THAT(wasRequestSent.load(), Eq(false));
m_runtime->shutdown();
blockingServer.join(); // ensure the wasRequestSent store happens before the read
EXPECT_THAT(wasRequestSent.load(), Eq(true));
}
TEST_F(PoshRuntime_test, ShutdownUnblocksBlockingServer)
{
::testing::Test::RecordProperty("TEST_ID", "f67db1c5-8db9-4798-b73c-7175255c90fd");
// get client and server
iox::capro::ServiceDescription serviceDescription{"stop", "name", "love"};
iox::popo::ClientOptions clientOptions;
clientOptions.responseQueueCapacity = 1U;
clientOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
clientOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::ServerOptions serverOptions;
serverOptions.requestQueueCapacity = 10U;
serverOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
serverOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::UntypedClient client{serviceDescription, clientOptions};
iox::popo::UntypedServer server{serviceDescription, serverOptions};
std::this_thread::sleep_for(std::chrono::milliseconds(300));
ASSERT_TRUE(server.hasClients());
ASSERT_THAT(client.getConnectionState(), Eq(iox::ConnectionState::CONNECTED));
// send requests to fill request queue
for (uint64_t i = 0; i < clientOptions.responseQueueCapacity + 1; ++i)
{
auto clientLoanResult = client.loan(sizeof(uint64_t), alignof(uint64_t));
ASSERT_FALSE(clientLoanResult.has_error());
client.send(clientLoanResult.value());
}
auto threadSyncSemaphore = iox::posix::Semaphore::create(iox::posix::CreateUnnamedSingleProcessSemaphore, 0U);
std::atomic_bool wasResponseSent{false};
constexpr iox::units::Duration DEADLOCK_TIMEOUT{5_s};
Watchdog deadlockWatchdog{DEADLOCK_TIMEOUT};
deadlockWatchdog.watchAndActOnFailure([] { std::terminate(); });
// block in a separate thread
std::thread blockingServer([&] {
auto processRequest = [&]() {
auto takeResult = server.take();
ASSERT_FALSE(takeResult.has_error());
auto loanResult = server.loan(
iox::popo::RequestHeader::fromPayload(takeResult.value()), sizeof(uint64_t), alignof(uint64_t));
ASSERT_FALSE(loanResult.has_error());
server.send(loanResult.value());
};
for (uint64_t i = 0; i < clientOptions.responseQueueCapacity; ++i)
{
processRequest();
}
ASSERT_FALSE(threadSyncSemaphore->post().has_error());
processRequest();
wasResponseSent = true;
});
// wait some time to check if the server is blocked
constexpr int64_t SLEEP_IN_MS = 100;
ASSERT_FALSE(threadSyncSemaphore->wait().has_error());
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_IN_MS));
EXPECT_THAT(wasResponseSent.load(), Eq(false));
m_runtime->shutdown();
blockingServer.join(); // ensure the wasResponseSent store happens before the read
EXPECT_THAT(wasResponseSent.load(), Eq(true));
}
TEST(PoshRuntimeFactory_test, SetValidRuntimeFactorySucceeds)
{
::testing::Test::RecordProperty("TEST_ID", "59c4e1e6-36f6-4f6d-b4c2-e84fa891f014");
constexpr const char HYPNOTOAD[]{"hypnotoad"};
constexpr const char BRAIN_SLUG[]{"brain-slug"};
auto mockRuntime = PoshRuntimeMock::create(HYPNOTOAD);
EXPECT_THAT(PoshRuntime::getInstance().getInstanceName().c_str(), StrEq(HYPNOTOAD));
mockRuntime.reset();
// if the PoshRuntimeMock could not change the runtime factory, the instance name would still be the old one
mockRuntime = PoshRuntimeMock::create(BRAIN_SLUG);
EXPECT_THAT(PoshRuntime::getInstance().getInstanceName().c_str(), StrEq(BRAIN_SLUG));
}
TEST(PoshRuntimeFactory_test, SetEmptyRuntimeFactoryFails)
{
::testing::Test::RecordProperty("TEST_ID", "530ec778-b480-4a1e-8562-94f93cee2f5c");
// this ensures resetting of the runtime factory in case the death test doesn't succeed
auto mockRuntime = PoshRuntimeMock::create("hypnotoad");
// do not use the setRuntimeFactory in a test with a running RouDiEnvironment
EXPECT_DEATH(
{
class FactoryAccess : public PoshRuntime
{
public:
using PoshRuntime::factory_t;
using PoshRuntime::setRuntimeFactory;
private:
FactoryAccess(iox::cxx::optional<const iox::RuntimeName_t*> s)
: PoshRuntime(s)
{
}
};
FactoryAccess::setRuntimeFactory(FactoryAccess::factory_t());
},
"Cannot set runtime factory. Passed factory must not be empty!");
}
} // namespace
|
#include <clog/clog.h>
#include <clog/config.h>
#include <nomagic.h>
#include <functional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "macros.h"
namespace {
using nomagic::loc;
using nomagic::Test;
using clogcmn::Content;
class Spy {
public:
static Content* last() {
return p;
}
static void out(const Content& content) {
if (q == 0)
q = new Content(content.message);
p = q;
*p = content;
}
static void reset() {
p = 0;
}
private:
static Content* p;
static Content* q;
};
Content* Spy::p(0);
Content* Spy::q(0);
namespace nspy {
void t1(const char* ms)
{
Test t(ms);
t.a(Spy::last() == 0, L);
}
void test_out(Test& t, const char* m)
{
Content c(m);
Spy::out(c);
Content* r(Spy::last());
t.a(r != 0, L);
t.a(r->message == m, L);
}
void t2(const char* ms)
{
Test t(ms);
test_out(t, "a message 1");
Spy::reset();
test_out(t, "a message 2");
}
void t3(const char* ms)
{
Test t(ms);
Content c("a message");
Spy::out(c);
Spy::reset();
Content* r(Spy::last());
t.a(r == 0, L);
}
} // nspy
namespace nlogcmn {
class F {
public:
F() {
clog::outfn = Spy::out;
}
};
namespace nf {
bool called;
class A {
public:
A() : v1(0), v2(0) {
}
A(const A& op)
: v1(op.v1), v2(op.v2) {
copied = true;
}
int v1;
int v2;
static bool copied;
};
bool A::copied;
A a;
A arg;
const int default_v1(1);
const int default_v2(2);
void reset()
{
called = false;
a = A();
a.v1 = 1;
a.v2 = 2;
arg = A();
A::copied = false;
}
struct E {
};
} // nf
} // nlogcmn
namespace nlog {
using nlogcmn::F;
namespace nf = nlogcmn::nf;
void f1()
{
nf::called = true;
}
namespace d {
using std::enable_if;
using std::is_void;
template<class T>
struct enable_void : enable_if<is_void<T>::value> {
};
template<class T>
struct disable_void : enable_if<!is_void<T>::value> {
};
} // d
class Test_common {
public:
Test_common(const char* ms)
: t(ms), m("message") {
}
void operator()() {
F f;
m = "message";
nf::reset();
prepare_call();
call_and_assert();
verify();
}
protected:
virtual void call_and_assert() = 0;
virtual void prepare_call() {
}
virtual void verify() = 0;
Test t;
const char* m;
};
template<class F>
class Test_0 : public Test_common {
public:
Test_0(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
}
F f;
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))();
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))() == 1, L);
}
};
class Extended_impl {
public:
Extended_impl() {
config_list = clogcmn::Config_list::create(configs);
clog::config_list = &config_list;
configs[0].message = "message";
configs[0].measure_etime = false;
}
protected:
clogcmn::Config_list config_list;
clogcmn::Config configs[1];
};
template<class F>
class Test_extended_0 : public Test_0<F>, private Extended_impl {
private:
using Test_0<F>::m;
using Test_0<F>::f;
using Test_0<F>::t;
public:
Test_extended_0(F f, const char* ms)
: Test_0<F>(f, ms) {
}
protected:
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(0, f))();
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(0, f))() == 1, L);
}
};
using std::logic_error;
template<class F>
class Test_ex : public Test_common {
public:
Test_ex(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void call_and_assert() {
try {
call();
logic_error("test");
}
catch (const nf::E&) {
}
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(Spy::last()->exception, L);
}
virtual void call() = 0;
F f;
};
template<class F>
class Test_0_ex : public Test_ex<F> {
public:
Test_0_ex(F f, const char* ms)
: Test_ex<F>(f, ms) {
}
protected:
using Test_ex<F>::f;
using Test_ex<F>::m;
void call() {
(clog::out(m, f))();
}
};
template<class F>
class Test_1_ex : public Test_ex<F> {
public:
Test_1_ex(F f, const char* ms)
: Test_ex<F>(f, ms) {
}
protected:
using Test_ex<F>::f;
using Test_ex<F>::m;
void call() {
(clog::out(m, f))(1);
}
};
template<class F>
inline Test_0_ex<F> test_0_ex(F f, const char* ms)
{
return Test_0_ex<F>(f, ms);
}
template<class F>
inline Test_1_ex<F> test_1_ex(F f, const char* ms)
{
return Test_1_ex<F>(f, ms);
}
template<class F>
inline Test_0<F> test_0(F f, const char* ms)
{
return Test_0<F>(f, ms);
}
template<class F>
inline Test_extended_0<F> test_extended_0(F f, const char* ms)
{
return Test_extended_0<F>(f, ms);
}
namespace nsimple {
void t1(const char* ms)
{
(test_0(f1, ms))();
}
} // nsimple
namespace nextended {
void t1(const char* ms)
{
(test_extended_0(f1, ms))();
}
} // nextended
void f2(int a)
{
nf::called = true;
nf::arg.v1 = a;
}
template<class F>
class Test_1 : public Test_common {
public:
Test_1(F f, const char* ms) : Test_common(ms), f(f) {
}
protected:
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
t.a(nf::arg.v1 == nf::a.v1, L);
t.a(nf::A::copied == false, L);
}
F f;
};
template<class F>
class Test_2 : public Test_common {
public:
Test_2(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void prepare_call() {
nf::a.v1 = nf::default_v1 + 1;
nf::a.v2 = nf::default_v2 + 1;
}
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
t.a(nf::arg.v1 == nf::a.v1, L);
t.a(nf::arg.v2 == nf::a.v2, L);
}
F f;
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))(nf::a.v1, nf::a.v2);
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))(nf::a.v1, nf::a.v2) == 10, L);
}
};
template<class F>
class Test_extended_2 : public Test_2<F>, private Extended_impl {
public:
Test_extended_2(F f, const char* ms)
: Test_2<F>(f, ms) {
}
protected:
using Test_2<F>::f;
void call_and_assert() {
(clog::out(0, f))(nf::a.v1, nf::a.v2);
}
};
template<class F>
class Test_1v : public Test_1<F> {
public:
Test_1v(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_1<F>::m;
using Test_1<F>::t;
using Test_1<F>::f;
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
void prepare_call() {
nf::a.v1 = 2;
nf::a.v2 = nf::arg.v2;
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))(nf::a.v1) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))(nf::a.v1);
}
};
template<class F>
class Test_extended_1v : public Test_1v<F>, private Extended_impl {
public:
Test_extended_1v(F f, const char* ms)
: Test_1v<F>(f, ms) {
}
protected:
using Test_1v<F>::f;
void call_and_assert() {
(clog::out(0, f))(nf::a.v1);
}
};
template<class F>
inline Test_1v<F> test_1v(F f, const char* ms)
{
return Test_1v<F>(f, ms);
}
template<class F>
inline Test_extended_1v<F> test_extended_1v(F f, const char* ms)
{
return Test_extended_1v<F>(f, ms);
}
namespace nsimple {
void t2(const char* ms)
{
(test_1v(f2, ms))();
}
} // nsimple
namespace nextended {
void t2(const char* ms)
{
(test_extended_1v(f2, ms))();
}
} // nextended
void f3(nf::A& a)
{
nf::called = true;
nf::arg = a;
}
void f3c(const nf::A& a)
{
nf::called = true;
nf::arg = a;
}
template<class F>
class Test_1r : public Test_1<F> {
public:
Test_1r(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_1<F>::m;
using Test_1<F>::t;
using Test_1<F>::f;
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))(nf::a) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))(nf::a);
}
};
template<class F>
inline Test_1r<F> test_1r(F f, const char* ms)
{
return Test_1r<F>(f, ms);
}
namespace nsimple {
void t3(const char* ms)
{
(test_1r(f3, ms))();
}
} // nsimple
int f1_1r(nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
int f1_1rc(const nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
namespace nsimple {
void t7(const char* ms)
{
(test_1r(f1_1r, ms))();
}
void t8(const char* ms)
{
(test_1r(f1_1rc, ms))();
}
void t4(const char* ms)
{
(test_1r(f3c, ms))();
}
} // nsimple
int f1_0()
{
nf::called = true;
return 1;
}
namespace nsimple {
void t5(const char* ms)
{
(test_0(f1_0, ms))();
}
} // nsimple
namespace nextended {
void t5(const char* ms)
{
(test_extended_0(f1_0, ms))();
}
} // nextended
int f1_1(int v)
{
nf::called = true;
nf::arg.v1 = v;
return 1;
}
namespace nsimple {
void t6(const char* ms)
{
(test_1v(f1_1, ms))();
}
} // nsimple
namespace nextended {
void t6(const char* ms)
{
(test_extended_1v(f1_1, ms))();
}
} // nextended
void f0e()
{
throw nf::E();
}
namespace nsimple {
void t9(const char* ms)
{
(test_0_ex(f0e, ms))();
}
} // nsimple
int f0ei()
{
throw nf::E();
}
namespace nsimple {
void t10(const char* ms)
{
(test_0_ex(f0ei, ms))();
}
} // nsimple
void f1e(int a)
{
throw nf::E();
}
int f1ei(int a)
{
throw nf::E();
}
namespace nsimple {
void t11(const char* ms)
{
(test_1_ex(f1e, ms))();
}
void t12(const char* ms)
{
(test_1_ex(f1ei, ms))();
}
} // nsimple
template<class F>
inline Test_2<F> test_2(F f, const char* ms)
{
return Test_2<F>(f, ms);
}
template<class F>
inline Test_extended_2<F> test_extended_2(F f, const char* ms)
{
return Test_extended_2<F>(f, ms);
}
void fv2(int v1, int v2)
{
nf::called = true;
nf::arg.v1 = v1;
nf::arg.v2 = v2;
}
namespace nsimple {
void t14(const char* ms)
{
(test_2(fv2, ms))();
}
} // nsimple
namespace nextended {
void t14(const char* ms)
{
(test_extended_2(fv2, ms))();
}
} // nextended
int fi2(int v1, int v2)
{
nf::called = true;
nf::arg.v1 = v1;
nf::arg.v2 = v2;
return 10;
}
namespace nsimple {
void t15(const char* ms)
{
(test_2(fi2, ms))();
}
} // nsimple
} // nlog
namespace nlogm {
using nlogcmn::F;
namespace nf = nlogcmn::nf;
class Sample {
public:
Sample()
: called(false) {
}
bool is_called() const {
return called;
}
void mv0() {
receive_call();
}
void mv0c() const {
receive_call();
}
void mv1(nf::A& a) {
receive_call();
nf::arg = a;
}
void mv1c(nf::A& a) const {
receive_call();
nf::arg = a;
}
int mi0() {
receive_call();
return 1;
}
int mi0c() const {
receive_call();
return 1;
}
private:
void receive_call() const {
called = true;
}
mutable bool called;
};
class Test_0 : protected Test, private F {
public:
Test_0(const char* ms)
: Test(ms), m("message") {
}
void start() {
Spy::reset();
nf::reset();
call_and_assert();
a(Spy::last()->message == m, L);
a(sample.is_called(), L);
verify();
}
protected:
virtual void call_and_assert() = 0;
virtual void verify() {
}
const char* m;
Sample sample;
};
class Test_v0 : public Test_0 {
public:
Test_v0(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv0))(sample);
}
};
class Test_v0c : public Test_0 {
public:
Test_v0c(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv0c))(sample);
}
};
class Test_1 : public Test_0 {
public:
Test_1(const char* ms)
: Test_0(ms) {
}
protected:
void verify() {
a(nf::arg.v1 == nf::a.v1, L);
a(!nf::A::copied, L);
}
};
class Test_v1 : public Test_1 {
public:
Test_v1(const char* ms)
: Test_1(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv1))(sample, nf::a);
}
};
class Test_v1c : public Test_1 {
public:
Test_v1c(const char* ms)
: Test_1(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv1c))(sample, nf::a);
}
};
class Test_i0 : public Test_0 {
public:
Test_i0(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
a((clog::out(m, &Sample::mi0))(sample) == 1, L);
}
};
class Test_i0c : public Test_0 {
public:
Test_i0c(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
a((clog::out(m, &Sample::mi0c))(sample) == 1, L);
}
};
void t1(const char* ms)
{
(Test_v0(ms)).start();
}
void t2(const char* ms)
{
(Test_i0(ms)).start();
}
void t3(const char* ms)
{
(Test_v0c(ms)).start();
}
void t4(const char* ms)
{
(Test_i0c(ms)).start();
}
void t5(const char* ms)
{
(Test_v1(ms)).start();
}
void t6(const char* ms)
{
(Test_v1c(ms)).start();
}
} // nlogm
using nomagic::run;
void spy_tests()
{
using namespace nspy;
run( "Spy returns null when it is asked to "
"provide the last log output but there is not.", t1);
run("Spy returns the last log object", t2);
run("Spy resets the last log", t3);
}
void log_tests()
{
std::cerr << "simple log tests" << std::endl;
using namespace nlog::nsimple;
run("return(void), arg(0)", t1);
run("return(void), arg(1)", t2);
run("return(void), arg(1, ref)", t3);
run("return(void), arg(1, cref)", t4);
run("return(int), arg(0)", t5);
run("return(int), arg(1)", t6);
run("return(int), arg(1, ref)", t7);
run("return(int), arg(1, cref)", t8);
run("return(void), arg(0), exception", t9);
run("return(int), arg(0), exception", t10);
run("return(void), arg(1)", t11);
run("return(int), arg(1)", t12);
run("return(void), arg(2)", t14);
run("return(int), arg(2)", t15);
}
void log_extended_tests()
{
std::cerr << "extended log tests" << std::endl;
using namespace nlog::nextended;
run("return(void), arg(0)", t1);
run("return(void), arg(1)", t2);
run("return(int), arg(0)", t5);
run("return(int), arg(1)", t6);
run("return(void), arg(2)", t14);
}
void log_method_tests()
{
using namespace nlogm;
run("method, return(void), arg(0)", t1);
run("method, return(int), arg(0)", t2);
run("method, return(void), arg(0), const", t3);
run("method, return(int), arg(0), const", t4);
run("method, return(void), arg(1)", t5);
run("method, return(void), arg(1), const", t6);
}
} // unnamed
#include "test.h"
namespace test {
void run_clog_tests()
{
spy_tests();
log_tests();
log_extended_tests();
log_method_tests();
}
} // test
This commit fixes test bugs.
#include <clog/clog.h>
#include <clog/config.h>
#include <nomagic.h>
#include <functional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "macros.h"
namespace {
using nomagic::loc;
using nomagic::Test;
using clogcmn::Content;
class Spy {
public:
static Content* last() {
return p;
}
static void out(const Content& content) {
if (q == 0)
q = new Content(content.message);
p = q;
*p = content;
}
static void reset() {
p = 0;
}
private:
static Content* p;
static Content* q;
};
Content* Spy::p(0);
Content* Spy::q(0);
namespace nspy {
void t1(const char* ms)
{
Test t(ms);
t.a(Spy::last() == 0, L);
}
void test_out(Test& t, const char* m)
{
Content c(m);
Spy::out(c);
Content* r(Spy::last());
t.a(r != 0, L);
t.a(r->message == m, L);
}
void t2(const char* ms)
{
Test t(ms);
test_out(t, "a message 1");
Spy::reset();
test_out(t, "a message 2");
}
void t3(const char* ms)
{
Test t(ms);
Content c("a message");
Spy::out(c);
Spy::reset();
Content* r(Spy::last());
t.a(r == 0, L);
}
} // nspy
namespace nlogcmn {
class F {
public:
F() {
clog::outfn = Spy::out;
}
};
namespace nf {
bool called;
class A {
public:
A() : v1(0), v2(0) {
}
A(const A& op)
: v1(op.v1), v2(op.v2) {
copied = true;
}
int v1;
int v2;
static bool copied;
};
bool A::copied;
A a;
A arg;
const int default_v1(1);
const int default_v2(2);
void reset()
{
called = false;
a = A();
a.v1 = 1;
a.v2 = 2;
arg = A();
A::copied = false;
}
struct E {
};
} // nf
} // nlogcmn
namespace nlog {
using nlogcmn::F;
namespace nf = nlogcmn::nf;
void f1()
{
nf::called = true;
}
namespace d {
using std::enable_if;
using std::is_void;
template<class T>
struct enable_void : enable_if<is_void<T>::value> {
};
template<class T>
struct disable_void : enable_if<!is_void<T>::value> {
};
} // d
class Test_common {
public:
Test_common(const char* ms)
: t(ms), m("message") {
}
void operator()() {
F f;
m = "message";
nf::reset();
prepare_call();
call_and_assert();
verify();
}
protected:
virtual void call_and_assert() = 0;
virtual void prepare_call() {
}
virtual void verify() = 0;
Test t;
const char* m;
};
template<class F>
class Test_0 : public Test_common {
public:
Test_0(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
}
F f;
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))();
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))() == 1, L);
}
};
class Extended_impl {
public:
Extended_impl() {
config_list = clogcmn::Config_list::create(configs);
clog::config_list = &config_list;
configs[0].message = "message";
configs[0].measure_etime = false;
}
protected:
clogcmn::Config_list config_list;
clogcmn::Config configs[1];
};
template<class F>
class Test_extended_0 : public Test_0<F>, private Extended_impl {
private:
using Test_0<F>::m;
using Test_0<F>::f;
using Test_0<F>::t;
public:
Test_extended_0(F f, const char* ms)
: Test_0<F>(f, ms) {
}
protected:
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(0, f))();
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(0, f))() == 1, L);
}
};
using std::logic_error;
template<class F>
class Test_ex : public Test_common {
public:
Test_ex(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void call_and_assert() {
try {
call();
logic_error("test");
}
catch (const nf::E&) {
}
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(Spy::last()->exception, L);
}
virtual void call() = 0;
F f;
};
template<class F>
class Test_0_ex : public Test_ex<F> {
public:
Test_0_ex(F f, const char* ms)
: Test_ex<F>(f, ms) {
}
protected:
using Test_ex<F>::f;
using Test_ex<F>::m;
void call() {
(clog::out(m, f))();
}
};
template<class F>
class Test_1_ex : public Test_ex<F> {
public:
Test_1_ex(F f, const char* ms)
: Test_ex<F>(f, ms) {
}
protected:
using Test_ex<F>::f;
using Test_ex<F>::m;
void call() {
(clog::out(m, f))(1);
}
};
template<class F>
inline Test_0_ex<F> test_0_ex(F f, const char* ms)
{
return Test_0_ex<F>(f, ms);
}
template<class F>
inline Test_1_ex<F> test_1_ex(F f, const char* ms)
{
return Test_1_ex<F>(f, ms);
}
template<class F>
inline Test_0<F> test_0(F f, const char* ms)
{
return Test_0<F>(f, ms);
}
template<class F>
inline Test_extended_0<F> test_extended_0(F f, const char* ms)
{
return Test_extended_0<F>(f, ms);
}
namespace nsimple {
void t1(const char* ms)
{
(test_0(f1, ms))();
}
} // nsimple
namespace nextended {
void t1(const char* ms)
{
(test_extended_0(f1, ms))();
}
} // nextended
void f2(int a)
{
nf::called = true;
nf::arg.v1 = a;
}
template<class F>
class Test_1 : public Test_common {
public:
Test_1(F f, const char* ms) : Test_common(ms), f(f) {
}
protected:
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
t.a(nf::arg.v1 == nf::a.v1, L);
t.a(nf::A::copied == false, L);
}
F f;
};
template<class F>
class Test_2 : public Test_common {
public:
Test_2(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void prepare_call() {
nf::a.v1 = nf::default_v1 + 1;
nf::a.v2 = nf::default_v2 + 1;
}
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
t.a(nf::arg.v1 == nf::a.v1, L);
t.a(nf::arg.v2 == nf::a.v2, L);
}
F f;
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))(nf::a.v1, nf::a.v2);
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))(nf::a.v1, nf::a.v2) == 10, L);
}
};
template<class F>
class Test_extended_2 : public Test_2<F>, private Extended_impl {
public:
Test_extended_2(F f, const char* ms)
: Test_2<F>(f, ms) {
}
protected:
using Test_2<F>::f;
using Test_2<F>::t;
void call_and_assert() {
(clog::out(0, f))(nf::a.v1, nf::a.v2);
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(0, f))(nf::a.v1, nf::a.v2) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(0, f))(nf::a.v1, nf::a.v2);
}
};
template<class F>
class Test_1v : public Test_1<F> {
public:
Test_1v(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_1<F>::m;
using Test_1<F>::t;
using Test_1<F>::f;
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
void prepare_call() {
nf::a.v1 = 2;
nf::a.v2 = nf::arg.v2;
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))(nf::a.v1) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))(nf::a.v1);
}
};
template<class F>
class Test_extended_1v : public Test_1v<F>, private Extended_impl {
public:
Test_extended_1v(F f, const char* ms)
: Test_1v<F>(f, ms) {
}
protected:
using Test_1v<F>::f;
using Test_1v<F>::t;
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(0, f))(nf::a.v1) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(0, f))(nf::a.v1);
}
};
template<class F>
inline Test_1v<F> test_1v(F f, const char* ms)
{
return Test_1v<F>(f, ms);
}
template<class F>
inline Test_extended_1v<F> test_extended_1v(F f, const char* ms)
{
return Test_extended_1v<F>(f, ms);
}
namespace nsimple {
void t2(const char* ms)
{
(test_1v(f2, ms))();
}
} // nsimple
namespace nextended {
void t2(const char* ms)
{
(test_extended_1v(f2, ms))();
}
} // nextended
void f3(nf::A& a)
{
nf::called = true;
nf::arg = a;
}
void f3c(const nf::A& a)
{
nf::called = true;
nf::arg = a;
}
template<class F>
class Test_1r : public Test_1<F> {
public:
Test_1r(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_1<F>::m;
using Test_1<F>::t;
using Test_1<F>::f;
void call_and_assert() {
call<typename clog::Out_result<F>::type>();
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a((clog::out(m, f))(nf::a) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
(clog::out(m, f))(nf::a);
}
};
template<class F>
inline Test_1r<F> test_1r(F f, const char* ms)
{
return Test_1r<F>(f, ms);
}
namespace nsimple {
void t3(const char* ms)
{
(test_1r(f3, ms))();
}
} // nsimple
int f1_1r(nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
int f1_1rc(const nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
namespace nsimple {
void t7(const char* ms)
{
(test_1r(f1_1r, ms))();
}
void t8(const char* ms)
{
(test_1r(f1_1rc, ms))();
}
void t4(const char* ms)
{
(test_1r(f3c, ms))();
}
} // nsimple
int f1_0()
{
nf::called = true;
return 1;
}
namespace nsimple {
void t5(const char* ms)
{
(test_0(f1_0, ms))();
}
} // nsimple
namespace nextended {
void t5(const char* ms)
{
(test_extended_0(f1_0, ms))();
}
} // nextended
int f1_1(int v)
{
nf::called = true;
nf::arg.v1 = v;
return 1;
}
namespace nsimple {
void t6(const char* ms)
{
(test_1v(f1_1, ms))();
}
} // nsimple
namespace nextended {
void t6(const char* ms)
{
(test_extended_1v(f1_1, ms))();
}
} // nextended
void f0e()
{
throw nf::E();
}
namespace nsimple {
void t9(const char* ms)
{
(test_0_ex(f0e, ms))();
}
} // nsimple
int f0ei()
{
throw nf::E();
}
namespace nsimple {
void t10(const char* ms)
{
(test_0_ex(f0ei, ms))();
}
} // nsimple
void f1e(int a)
{
throw nf::E();
}
int f1ei(int a)
{
throw nf::E();
}
namespace nsimple {
void t11(const char* ms)
{
(test_1_ex(f1e, ms))();
}
void t12(const char* ms)
{
(test_1_ex(f1ei, ms))();
}
} // nsimple
template<class F>
inline Test_2<F> test_2(F f, const char* ms)
{
return Test_2<F>(f, ms);
}
template<class F>
inline Test_extended_2<F> test_extended_2(F f, const char* ms)
{
return Test_extended_2<F>(f, ms);
}
void fv2(int v1, int v2)
{
nf::called = true;
nf::arg.v1 = v1;
nf::arg.v2 = v2;
}
namespace nsimple {
void t14(const char* ms)
{
(test_2(fv2, ms))();
}
} // nsimple
namespace nextended {
void t14(const char* ms)
{
(test_extended_2(fv2, ms))();
}
} // nextended
int fi2(int v1, int v2)
{
nf::called = true;
nf::arg.v1 = v1;
nf::arg.v2 = v2;
return 10;
}
namespace nsimple {
void t15(const char* ms)
{
(test_2(fi2, ms))();
}
} // nsimple
} // nlog
namespace nlogm {
using nlogcmn::F;
namespace nf = nlogcmn::nf;
class Sample {
public:
Sample()
: called(false) {
}
bool is_called() const {
return called;
}
void mv0() {
receive_call();
}
void mv0c() const {
receive_call();
}
void mv1(nf::A& a) {
receive_call();
nf::arg = a;
}
void mv1c(nf::A& a) const {
receive_call();
nf::arg = a;
}
int mi0() {
receive_call();
return 1;
}
int mi0c() const {
receive_call();
return 1;
}
private:
void receive_call() const {
called = true;
}
mutable bool called;
};
class Test_0 : protected Test, private F {
public:
Test_0(const char* ms)
: Test(ms), m("message") {
}
void start() {
Spy::reset();
nf::reset();
call_and_assert();
a(Spy::last()->message == m, L);
a(sample.is_called(), L);
verify();
}
protected:
virtual void call_and_assert() = 0;
virtual void verify() {
}
const char* m;
Sample sample;
};
class Test_v0 : public Test_0 {
public:
Test_v0(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv0))(sample);
}
};
class Test_v0c : public Test_0 {
public:
Test_v0c(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv0c))(sample);
}
};
class Test_1 : public Test_0 {
public:
Test_1(const char* ms)
: Test_0(ms) {
}
protected:
void verify() {
a(nf::arg.v1 == nf::a.v1, L);
a(!nf::A::copied, L);
}
};
class Test_v1 : public Test_1 {
public:
Test_v1(const char* ms)
: Test_1(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv1))(sample, nf::a);
}
};
class Test_v1c : public Test_1 {
public:
Test_v1c(const char* ms)
: Test_1(ms) {
}
protected:
void call_and_assert() {
(clog::out(m, &Sample::mv1c))(sample, nf::a);
}
};
class Test_i0 : public Test_0 {
public:
Test_i0(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
a((clog::out(m, &Sample::mi0))(sample) == 1, L);
}
};
class Test_i0c : public Test_0 {
public:
Test_i0c(const char* ms)
: Test_0(ms) {
}
protected:
void call_and_assert() {
a((clog::out(m, &Sample::mi0c))(sample) == 1, L);
}
};
void t1(const char* ms)
{
(Test_v0(ms)).start();
}
void t2(const char* ms)
{
(Test_i0(ms)).start();
}
void t3(const char* ms)
{
(Test_v0c(ms)).start();
}
void t4(const char* ms)
{
(Test_i0c(ms)).start();
}
void t5(const char* ms)
{
(Test_v1(ms)).start();
}
void t6(const char* ms)
{
(Test_v1c(ms)).start();
}
} // nlogm
using nomagic::run;
void spy_tests()
{
using namespace nspy;
run( "Spy returns null when it is asked to "
"provide the last log output but there is not.", t1);
run("Spy returns the last log object", t2);
run("Spy resets the last log", t3);
}
void log_tests()
{
std::cerr << "simple log tests" << std::endl;
using namespace nlog::nsimple;
run("return(void), arg(0)", t1);
run("return(void), arg(1)", t2);
run("return(void), arg(1, ref)", t3);
run("return(void), arg(1, cref)", t4);
run("return(int), arg(0)", t5);
run("return(int), arg(1)", t6);
run("return(int), arg(1, ref)", t7);
run("return(int), arg(1, cref)", t8);
run("return(void), arg(0), exception", t9);
run("return(int), arg(0), exception", t10);
run("return(void), arg(1)", t11);
run("return(int), arg(1)", t12);
run("return(void), arg(2)", t14);
run("return(int), arg(2)", t15);
}
void log_extended_tests()
{
std::cerr << "extended log tests" << std::endl;
using namespace nlog::nextended;
run("return(void), arg(0)", t1);
run("return(void), arg(1)", t2);
run("return(int), arg(0)", t5);
run("return(int), arg(1)", t6);
run("return(void), arg(2)", t14);
}
void log_method_tests()
{
using namespace nlogm;
run("method, return(void), arg(0)", t1);
run("method, return(int), arg(0)", t2);
run("method, return(void), arg(0), const", t3);
run("method, return(int), arg(0), const", t4);
run("method, return(void), arg(1)", t5);
run("method, return(void), arg(1), const", t6);
}
} // unnamed
#include "test.h"
namespace test {
void run_clog_tests()
{
spy_tests();
log_tests();
log_extended_tests();
log_method_tests();
}
} // test
|
#include <clog/clog.h>
#include <nomagic.h>
#include <functional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "macros.h"
namespace {
using nomagic::loc;
using nomagic::Test;
using clogcmn::Content;
class Spy {
public:
static Content* last() {
return p;
}
static void out(const Content& content) {
if (q == 0)
q = new Content(content.message);
p = q;
*p = content;
}
static void reset() {
p = 0;
}
private:
static Content* p;
static Content* q;
};
Content* Spy::p(0);
Content* Spy::q(0);
namespace nspy {
void t1(const char* ms)
{
Test t(ms);
t.a(Spy::last() == 0, L);
}
void test_out(Test& t, const char* m)
{
Content c(m);
Spy::out(c);
Content* r(Spy::last());
t.a(r != 0, L);
t.a(r->message == m, L);
}
void t2(const char* ms)
{
Test t(ms);
test_out(t, "a message 1");
Spy::reset();
test_out(t, "a message 2");
}
void t3(const char* ms)
{
Test t(ms);
Content c("a message");
Spy::out(c);
Spy::reset();
Content* r(Spy::last());
t.a(r == 0, L);
}
} // nspy
namespace nlog {
class F {
public:
F() {
clog::outfn = Spy::out;
}
};
namespace nf {
bool called;
class A {
public:
A() : v(0) {
}
A(const A& op)
: v(op.v) {
copied = true;
}
int v;
static bool copied;
};
bool A::copied;
A a;
A arg;
void reset()
{
called = false;
a = A();
a.v = 1;
arg = A();
A::copied = false;
}
struct E {
};
} // nf
void f1()
{
nf::called = true;
}
namespace d {
using std::enable_if;
using std::is_void;
template<class T>
struct enable_void : enable_if<is_void<T>::value> {
};
template<class T>
struct disable_void : enable_if<!is_void<T>::value> {
};
} // d
class Test_common {
public:
Test_common(const char* ms)
: t(ms) {
}
void operator()() {
F f;
m = "message";
nf::reset();
prepare_call();
call_and_assert();
verify();
}
protected:
virtual void call_and_assert() = 0;
virtual void prepare_call() {
}
virtual void verify() = 0;
Test t;
const char* m;
};
template<class F>
class Test_0 : public Test_common {
public:
Test_0(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void call_and_assert() {
call<decltype(clog::out(m, f))>();
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
}
F f;
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
clog::out(m, f);
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a(clog::out(m, f) == 1, L);
}
};
template<class F>
inline Test_0<F> test_0(F f, const char* ms)
{
return Test_0<F>(f, ms);
}
void t1(const char* ms)
{
(test_0(f1, ms))();
}
void f2(int a)
{
nf::called = true;
nf::arg.v = a;
}
template<class F>
class Test_1 : public Test_common {
public:
Test_1(F f, const char* ms) : Test_common(ms), f(f) {
}
protected:
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
t.a(nf::arg.v == nf::a.v, L);
t.a(nf::A::copied == false, L);
}
F f;
};
template<class F>
class Test_1v : public Test_1<F> {
public:
Test_1v(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_common::m;
using Test_1<F>::f;
void call_and_assert() {
call<decltype(clog::out(m, f, nf::a.v))>();
}
void prepare_call() {
nf::a.v = 2;
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
Test_common::t.a(clog::out(m, f, nf::a.v) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
clog::out(m, f, nf::a.v);
}
};
template<class F>
inline Test_1v<F> test_1v(F f, const char* ms)
{
return Test_1v<F>(f, ms);
}
void t2(const char* ms)
{
(test_1v(f2, ms))();
}
void f3(nf::A& a)
{
nf::called = true;
nf::arg = a;
}
void f3c(const nf::A& a)
{
nf::called = true;
nf::arg = a;
}
template<class F>
class Test_1r : public Test_1<F> {
public:
Test_1r(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_common::m;
using Test_1<F>::f;
void call_and_assert() {
call<decltype(clog::out(m, f, nf::a))>();
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
Test_common::t.a(clog::out(m, f, nf::a) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
clog::out(m, f, nf::a);
}
};
template<class F>
inline Test_1r<F> test_1r(F f, const char* ms)
{
return Test_1r<F>(f, ms);
}
void t3(const char* ms)
{
(test_1r(f3, ms))();
}
int f1_1r(nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
int f1_1rc(const nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
void t8(const char* ms)
{
(test_1r(f1_1r, ms))();
}
void t9(const char* ms)
{
(test_1r(f1_1rc, ms))();
}
void t4(const char* ms)
{
(test_1r(f3c, ms))();
}
int f1_0()
{
nf::called = true;
return 1;
}
void t5(const char* ms)
{
(test_0(f1_0, ms))();
}
int f1_1(int v)
{
nf::called = true;
nf::arg.v = v;
return 1;
}
void t6(const char* ms)
{
(test_1v(f1_1, ms))();
}
void f0e()
{
throw nf::E();
}
void t7(const char* ms)
{
Test t(ms);
F f;
const char* m("message");
nf::reset();
try {
clog::out(m, f0e);
throw std::logic_error("test");
}
catch (const nf::E&) {
}
t.a(Spy::last()->message == m, L);
t.a(Spy::last()->exception, L);
}
} // nlog
using nomagic::run;
void spy_tests()
{
using namespace nspy;
run( "Spy returns null when it is asked to "
"provide the last log output but there is not.", t1);
run("Spy returns the last log object", t2);
run("Spy resets the last log", t3);
}
void log_tests()
{
using namespace nlog;
run("return(void), arg(0)", t1);
run("return(void), arg(1)", t2);
run("return(void), arg(1, ref)", t3);
run("return(void), arg(1, cref)", t4);
run("return(int), arg(0)", t5);
run("return(int), arg(1)", t6);
run("return(int), arg(1, ref)", t8);
run("return(int), arg(1, cref)", t9);
run("return(void), arg(0), exception", t7);
}
} // unnamed
#include "test.h"
namespace test {
void run_clog_tests()
{
spy_tests();
log_tests();
}
} // test
This commit makes code beatifull slightly.
#include <clog/clog.h>
#include <nomagic.h>
#include <functional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "macros.h"
namespace {
using nomagic::loc;
using nomagic::Test;
using clogcmn::Content;
class Spy {
public:
static Content* last() {
return p;
}
static void out(const Content& content) {
if (q == 0)
q = new Content(content.message);
p = q;
*p = content;
}
static void reset() {
p = 0;
}
private:
static Content* p;
static Content* q;
};
Content* Spy::p(0);
Content* Spy::q(0);
namespace nspy {
void t1(const char* ms)
{
Test t(ms);
t.a(Spy::last() == 0, L);
}
void test_out(Test& t, const char* m)
{
Content c(m);
Spy::out(c);
Content* r(Spy::last());
t.a(r != 0, L);
t.a(r->message == m, L);
}
void t2(const char* ms)
{
Test t(ms);
test_out(t, "a message 1");
Spy::reset();
test_out(t, "a message 2");
}
void t3(const char* ms)
{
Test t(ms);
Content c("a message");
Spy::out(c);
Spy::reset();
Content* r(Spy::last());
t.a(r == 0, L);
}
} // nspy
namespace nlog {
class F {
public:
F() {
clog::outfn = Spy::out;
}
};
namespace nf {
bool called;
class A {
public:
A() : v(0) {
}
A(const A& op)
: v(op.v) {
copied = true;
}
int v;
static bool copied;
};
bool A::copied;
A a;
A arg;
void reset()
{
called = false;
a = A();
a.v = 1;
arg = A();
A::copied = false;
}
struct E {
};
} // nf
void f1()
{
nf::called = true;
}
namespace d {
using std::enable_if;
using std::is_void;
template<class T>
struct enable_void : enable_if<is_void<T>::value> {
};
template<class T>
struct disable_void : enable_if<!is_void<T>::value> {
};
} // d
class Test_common {
public:
Test_common(const char* ms)
: t(ms) {
}
void operator()() {
F f;
m = "message";
nf::reset();
prepare_call();
call_and_assert();
verify();
}
protected:
virtual void call_and_assert() = 0;
virtual void prepare_call() {
}
virtual void verify() = 0;
Test t;
const char* m;
};
template<class F>
class Test_0 : public Test_common {
public:
Test_0(F f, const char* ms)
: Test_common(ms), f(f) {
}
protected:
void call_and_assert() {
call<decltype(clog::out(m, f))>();
}
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
}
F f;
private:
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
clog::out(m, f);
}
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a(clog::out(m, f) == 1, L);
}
};
template<class F>
inline Test_0<F> test_0(F f, const char* ms)
{
return Test_0<F>(f, ms);
}
void t1(const char* ms)
{
(test_0(f1, ms))();
}
void f2(int a)
{
nf::called = true;
nf::arg.v = a;
}
template<class F>
class Test_1 : public Test_common {
public:
Test_1(F f, const char* ms) : Test_common(ms), f(f) {
}
protected:
void verify() {
t.a(Spy::last()->message == m, L);
t.a(nf::called, L);
t.a(nf::arg.v == nf::a.v, L);
t.a(nf::A::copied == false, L);
}
F f;
};
template<class F>
class Test_1v : public Test_1<F> {
public:
Test_1v(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_1<F>::m;
using Test_1<F>::t;
using Test_1<F>::f;
void call_and_assert() {
call<decltype(clog::out(m, f, nf::a.v))>();
}
void prepare_call() {
nf::a.v = 2;
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a(clog::out(m, f, nf::a.v) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
clog::out(m, f, nf::a.v);
}
};
template<class F>
inline Test_1v<F> test_1v(F f, const char* ms)
{
return Test_1v<F>(f, ms);
}
void t2(const char* ms)
{
(test_1v(f2, ms))();
}
void f3(nf::A& a)
{
nf::called = true;
nf::arg = a;
}
void f3c(const nf::A& a)
{
nf::called = true;
nf::arg = a;
}
template<class F>
class Test_1r : public Test_1<F> {
public:
Test_1r(F f, const char* ms) : Test_1<F>(f, ms) {
}
protected:
using Test_1<F>::m;
using Test_1<F>::t;
using Test_1<F>::f;
void call_and_assert() {
call<decltype(clog::out(m, f, nf::a))>();
}
private:
template<class T>
void call(typename d::disable_void<T>::type* = 0) {
t.a(clog::out(m, f, nf::a) == 1, L);
}
template<class T>
void call(typename d::enable_void<T>::type* = 0) {
clog::out(m, f, nf::a);
}
};
template<class F>
inline Test_1r<F> test_1r(F f, const char* ms)
{
return Test_1r<F>(f, ms);
}
void t3(const char* ms)
{
(test_1r(f3, ms))();
}
int f1_1r(nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
int f1_1rc(const nf::A& a)
{
nf::called = true;
nf::arg = a;
return 1;
}
void t8(const char* ms)
{
(test_1r(f1_1r, ms))();
}
void t9(const char* ms)
{
(test_1r(f1_1rc, ms))();
}
void t4(const char* ms)
{
(test_1r(f3c, ms))();
}
int f1_0()
{
nf::called = true;
return 1;
}
void t5(const char* ms)
{
(test_0(f1_0, ms))();
}
int f1_1(int v)
{
nf::called = true;
nf::arg.v = v;
return 1;
}
void t6(const char* ms)
{
(test_1v(f1_1, ms))();
}
void f0e()
{
throw nf::E();
}
void t7(const char* ms)
{
Test t(ms);
F f;
const char* m("message");
nf::reset();
try {
clog::out(m, f0e);
throw std::logic_error("test");
}
catch (const nf::E&) {
}
t.a(Spy::last()->message == m, L);
t.a(Spy::last()->exception, L);
}
} // nlog
using nomagic::run;
void spy_tests()
{
using namespace nspy;
run( "Spy returns null when it is asked to "
"provide the last log output but there is not.", t1);
run("Spy returns the last log object", t2);
run("Spy resets the last log", t3);
}
void log_tests()
{
using namespace nlog;
run("return(void), arg(0)", t1);
run("return(void), arg(1)", t2);
run("return(void), arg(1, ref)", t3);
run("return(void), arg(1, cref)", t4);
run("return(int), arg(0)", t5);
run("return(int), arg(1)", t6);
run("return(int), arg(1, ref)", t8);
run("return(int), arg(1, cref)", t9);
run("return(void), arg(0), exception", t7);
}
} // unnamed
#include "test.h"
namespace test {
void run_clog_tests()
{
spy_tests();
log_tests();
}
} // test
|
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/visualization/common/common.h>
#include <pcl/conversions.h>
#include <vtkVersion.h>
#include <vtkTextActor.h>
#include <vtkTextProperty.h>
#include <vtkCellData.h>
#include <vtkWorldPointPicker.h>
#include <vtkPropPicker.h>
#include <vtkPlatonicSolidSource.h>
#include <vtkLoopSubdivisionFilter.h>
#include <vtkTriangle.h>
#include <vtkTransform.h>
#include <vtkPolyDataNormals.h>
#include <vtkMapper.h>
#include <vtkDataSetMapper.h>
#if VTK_MAJOR_VERSION>=6 || (VTK_MAJOR_VERSION==5 && VTK_MINOR_VERSION>4)
#include <vtkHardwareSelector.h>
#include <vtkSelectionNode.h>
#else
#include <vtkVisibleCellSelector.h>
#endif
#include <vtkSelection.h>
#include <vtkPointPicker.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/vtk/vtkRenderWindowInteractorFix.h>
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
#include <pcl/visualization/vtk/vtkVertexBufferObjectMapper.h>
#endif
#include <vtkPolyLine.h>
#include <vtkPolyDataMapper.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRendererCollection.h>
#include <vtkCamera.h>
#include <vtkAppendPolyData.h>
#include <vtkPointData.h>
#include <vtkTransformFilter.h>
#include <vtkProperty.h>
#include <vtkPLYReader.h>
#include <vtkAxes.h>
#include <vtkTubeFilter.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkAxesActor.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkAreaPicker.h>
#include <vtkXYPlotActor.h>
#include <vtkOpenGLRenderWindow.h>
#include <vtkJPEGReader.h>
#include <vtkBMPReader.h>
#include <vtkPNMReader.h>
#include <vtkPNGReader.h>
#include <vtkTIFFReader.h>
#include <vtkLookupTable.h>
#include <vtkTextureUnitManager.h>
#include <pcl/visualization/common/shapes.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/common/common.h>
#include <pcl/common/time.h>
#include <boost/uuid/sha1.hpp>
#include <boost/filesystem.hpp>
#include <pcl/console/parse.h>
// Support for VTK 7.1 upwards
#ifdef vtkGenericDataArray_h
#define SetTupleValue SetTypedTuple
#define InsertNextTupleValue InsertNextTypedTuple
#define GetTupleValue GetTypedTuple
#endif
#if defined(_WIN32)
// Remove macros defined in Windows.h
#undef near
#undef far
#endif
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (const std::string &name, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (vtkSmartPointer<vtkRenderWindow>::New ())
, style_ (vtkSmartPointer<pcl::visualization::PCLVisualizerInteractorStyle>::New ())
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New ();
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setDefaultWindowSizeAndPos ();
setupStyle ();
if (create_interactor)
createInteractor ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (int &argc, char **argv, const std::string &name, PCLVisualizerInteractorStyle* style, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (vtkSmartPointer<vtkRenderWindow>::New ())
, style_ (style)
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New ();
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setupStyle ();
setupCamera (argc, argv);
if(!camera_set_ && !camera_file_loaded_)
setDefaultWindowSizeAndPos ();
if (create_interactor)
createInteractor ();
//window name should be reset due to its reset somewhere in camera initialization
win_->SetWindowName (name.c_str ());
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (vtkSmartPointer<vtkRenderer> ren, vtkSmartPointer<vtkRenderWindow> wind,
const std::string &name, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (wind)
, style_ (vtkSmartPointer<pcl::visualization::PCLVisualizerInteractorStyle>::New ())
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setDefaultWindowSizeAndPos ();
setupStyle ();
if (create_interactor)
createInteractor ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (int &argc, char **argv, vtkSmartPointer<vtkRenderer> ren, vtkSmartPointer<vtkRenderWindow> wind,
const std::string &name, PCLVisualizerInteractorStyle* style, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (wind)
, style_ (style)
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setupStyle ();
setupCamera (argc, argv);
if (!camera_set_ && !camera_file_loaded_)
setDefaultWindowSizeAndPos ();
if (create_interactor)
createInteractor ();
//window name should be reset due to its reset somewhere in camera initialization
win_->SetWindowName (name.c_str ());
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createInteractor ()
{
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_ = vtkSmartPointer<PCLVisualizerInteractor>::New ();
#else
//interactor_ = vtkSmartPointer<vtkRenderWindowInteractor>::New ();
interactor_ = vtkSmartPointer <vtkRenderWindowInteractor>::Take (vtkRenderWindowInteractorFixNew ());
#endif
//win_->PointSmoothingOn ();
//win_->LineSmoothingOn ();
//win_->PolygonSmoothingOn ();
win_->AlphaBitPlanesOff ();
win_->PointSmoothingOff ();
win_->LineSmoothingOff ();
win_->PolygonSmoothingOff ();
win_->SwapBuffersOn ();
win_->SetStereoTypeToAnaglyph ();
interactor_->SetRenderWindow (win_);
interactor_->SetInteractorStyle (style_);
//interactor_->SetStillUpdateRate (30.0);
interactor_->SetDesiredUpdateRate (30.0);
// Initialize and create timer, also create window
interactor_->Initialize ();
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_->timer_id_ = interactor_->CreateRepeatingTimer (5000L);
#else
timer_id_ = interactor_->CreateRepeatingTimer (5000L);
#endif
// Set a simple PointPicker
vtkSmartPointer<vtkPointPicker> pp = vtkSmartPointer<vtkPointPicker>::New ();
pp->SetTolerance (pp->GetTolerance () * 2);
interactor_->SetPicker (pp);
exit_main_loop_timer_callback_ = vtkSmartPointer<ExitMainLoopTimerCallback>::New ();
exit_main_loop_timer_callback_->pcl_visualizer = this;
exit_main_loop_timer_callback_->right_timer_id = -1;
interactor_->AddObserver (vtkCommand::TimerEvent, exit_main_loop_timer_callback_);
exit_callback_ = vtkSmartPointer<ExitCallback>::New ();
exit_callback_->pcl_visualizer = this;
interactor_->AddObserver (vtkCommand::ExitEvent, exit_callback_);
resetStoppedFlag ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setupInteractor (
vtkRenderWindowInteractor *iren,
vtkRenderWindow *win)
{
win->AlphaBitPlanesOff ();
win->PointSmoothingOff ();
win->LineSmoothingOff ();
win->PolygonSmoothingOff ();
win->SwapBuffersOn ();
win->SetStereoTypeToAnaglyph ();
iren->SetRenderWindow (win);
iren->SetInteractorStyle (style_);
//iren->SetStillUpdateRate (30.0);
iren->SetDesiredUpdateRate (30.0);
// Initialize and create timer, also create window
iren->Initialize ();
// Set a simple PointPicker
vtkSmartPointer<vtkPointPicker> pp = vtkSmartPointer<vtkPointPicker>::New ();
pp->SetTolerance (pp->GetTolerance () * 2);
iren->SetPicker (pp);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setupInteractor (
vtkRenderWindowInteractor *iren,
vtkRenderWindow *win,
vtkInteractorStyle *style)
{
win->AlphaBitPlanesOff ();
win->PointSmoothingOff ();
win->LineSmoothingOff ();
win->PolygonSmoothingOff ();
win->SwapBuffersOn ();
win->SetStereoTypeToAnaglyph ();
iren->SetRenderWindow (win);
iren->SetInteractorStyle (style);
//iren->SetStillUpdateRate (30.0);
iren->SetDesiredUpdateRate (30.0);
// Initialize and create timer, also create window
iren->Initialize ();
// Set a simple PointPicker
// vtkSmartPointer<vtkPointPicker> pp = vtkSmartPointer<vtkPointPicker>::New ();
// pp->SetTolerance (pp->GetTolerance () * 2);
// iren->SetPicker (pp);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupRenderer (vtkSmartPointer<vtkRenderer> ren)
{
if (!ren)
PCL_ERROR ("Passed pointer to renderer is null");
ren->AddObserver (vtkCommand::EndEvent, update_fps_);
// Add it to the list of renderers
rens_->AddItem (ren);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupFPSCallback (const vtkSmartPointer<vtkRenderer>& ren)
{
if (!ren)
PCL_ERROR ("Passed pointer to renderer is null");
// FPS callback
vtkSmartPointer<vtkTextActor> txt = vtkSmartPointer<vtkTextActor>::New ();
update_fps_->actor = txt;
update_fps_->pcl_visualizer = this;
update_fps_->decimated = false;
ren->AddActor (txt);
txt->SetInput ("0 FPS");
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupRenderWindow (const std::string& name)
{
if (!win_)
PCL_ERROR ("Pointer to render window is null");
win_->SetWindowName (name.c_str ());
// By default, don't use vertex buffer objects
use_vbos_ = false;
// Add all renderers to the window
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
win_->AddRenderer (renderer);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupStyle ()
{
if (!style_)
PCL_ERROR ("Pointer to style is null");
// Set rend erer window in case no interactor is created
style_->setRenderWindow (win_);
// Create the interactor style
style_->Initialize ();
style_->setRendererCollection (rens_);
style_->setCloudActorMap (cloud_actor_map_);
style_->setShapeActorMap (shape_actor_map_);
style_->UseTimersOn ();
style_->setUseVbos (use_vbos_);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setDefaultWindowSizeAndPos ()
{
if (!win_)
PCL_ERROR ("Pointer to render window is null");
int scr_size_x = win_->GetScreenSize ()[0];
int scr_size_y = win_->GetScreenSize ()[1];
win_->SetSize (scr_size_x / 2, scr_size_y / 2);
win_->SetPosition (0, 0);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupCamera (int &argc, char **argv)
{
initCameraParameters ();
// Parse the camera settings and update the internal camera
camera_set_ = getCameraParameters (argc, argv);
// Calculate unique camera filename for camera parameter saving/restoring
if (!camera_set_)
{
std::string camera_file = getUniqueCameraFile (argc, argv);
if (!camera_file.empty ())
{
if (boost::filesystem::exists (camera_file) && style_->loadCameraParameters (camera_file))
{
camera_file_loaded_ = true;
}
else
{
style_->setCameraFile (camera_file);
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::~PCLVisualizer ()
{
if (interactor_ != NULL)
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_->DestroyTimer (interactor_->timer_id_);
#else
interactor_->DestroyTimer (timer_id_);
#endif
// Clear the collections
rens_->RemoveAllItems ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::saveScreenshot (const std::string &file)
{
style_->saveScreenshot (file);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::saveCameraParameters (const std::string &file)
{
style_->saveCameraParameters (file);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::getCameraParameters (pcl::visualization::Camera &camera)
{
style_->getCameraParameters (camera);
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerKeyboardCallback (boost::function<void (const pcl::visualization::KeyboardEvent&)> callback)
{
return (style_->registerKeyboardCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerMouseCallback (boost::function<void (const pcl::visualization::MouseEvent&)> callback)
{
return (style_->registerMouseCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerPointPickingCallback (boost::function<void (const pcl::visualization::PointPickingEvent&)> callback)
{
return (style_->registerPointPickingCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerPointPickingCallback (void (*callback) (const pcl::visualization::PointPickingEvent&, void*), void* cookie)
{
return (registerPointPickingCallback (boost::bind (callback, _1, cookie)));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerAreaPickingCallback (boost::function<void (const pcl::visualization::AreaPickingEvent&)> callback)
{
return (style_->registerAreaPickingCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerAreaPickingCallback (void (*callback) (const pcl::visualization::AreaPickingEvent&, void*), void* cookie)
{
return (registerAreaPickingCallback (boost::bind (callback, _1, cookie)));
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::spin ()
{
resetStoppedFlag ();
// Render the window before we start the interactor
win_->Render ();
if (interactor_)
interactor_->Start ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::spinOnce (int time, bool force_redraw)
{
resetStoppedFlag ();
#if (defined (__APPLE__)\
&& ( (VTK_MAJOR_VERSION > 6) || ( (VTK_MAJOR_VERSION == 6) && (VTK_MINOR_VERSION >= 1))))
if (!win_->IsDrawable ())
{
close ();
return;
}
#endif
if (!interactor_)
return;
if (time <= 0)
time = 1;
if (force_redraw)
interactor_->Render ();
DO_EVERY (1.0 / interactor_->GetDesiredUpdateRate (),
exit_main_loop_timer_callback_->right_timer_id = interactor_->CreateRepeatingTimer (time);
interactor_->Start ();
interactor_->DestroyTimer (exit_main_loop_timer_callback_->right_timer_id);
);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addOrientationMarkerWidgetAxes (vtkRenderWindowInteractor* interactor)
{
if ( !axes_widget_ )
{
vtkSmartPointer<vtkAxesActor> axes = vtkSmartPointer<vtkAxesActor>::New ();
axes_widget_ = vtkSmartPointer<vtkOrientationMarkerWidget>::New ();
axes_widget_->SetOutlineColor (0.9300, 0.5700, 0.1300);
axes_widget_->SetOrientationMarker (axes);
axes_widget_->SetInteractor (interactor);
axes_widget_->SetViewport (0.0, 0.0, 0.4, 0.4);
axes_widget_->SetEnabled (true);
axes_widget_->InteractiveOn ();
}
else
{
axes_widget_->SetEnabled (true);
pcl::console::print_warn (stderr, "Orientation Widget Axes already exists, just enabling it");
}
}
////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::removeOrientationMarkerWidgetAxes ()
{
if (axes_widget_)
{
if (axes_widget_->GetEnabled ())
axes_widget_->SetEnabled (false);
else
pcl::console::print_warn (stderr, "Orientation Widget Axes was already disabled, doing nothing.");
}
else
{
pcl::console::print_error ("Attempted to delete Orientation Widget Axes which does not exist!\n");
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addCoordinateSystem (double scale, const std::string &id, int viewport)
{
if (scale <= 0.0)
scale = 1.0;
vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New ();
axes->SetOrigin (0, 0, 0);
axes->SetScaleFactor (scale);
axes->Update ();
vtkSmartPointer<vtkFloatArray> axes_colors = vtkSmartPointer<vtkFloatArray>::New ();
axes_colors->Allocate (6);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (1.0);
axes_colors->InsertNextValue (1.0);
vtkSmartPointer<vtkPolyData> axes_data = axes->GetOutput ();
axes_data->GetPointData ()->SetScalars (axes_colors);
vtkSmartPointer<vtkTubeFilter> axes_tubes = vtkSmartPointer<vtkTubeFilter>::New ();
#if VTK_MAJOR_VERSION < 6
axes_tubes->SetInput (axes_data);
#else
axes_tubes->SetInputData (axes_data);
#endif
axes_tubes->SetRadius (axes->GetScaleFactor () / 50.0);
axes_tubes->SetNumberOfSides (6);
vtkSmartPointer<vtkPolyDataMapper> axes_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
axes_mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
axes_mapper->SetInput (axes_tubes->GetOutput ());
#else
axes_mapper->SetInputConnection (axes_tubes->GetOutputPort ());
#endif
vtkSmartPointer<vtkLODActor> axes_actor = vtkSmartPointer<vtkLODActor>::New ();
axes_actor->SetMapper (axes_mapper);
// Save the ID and actor pair to the global actor map
(*coordinate_actor_map_) [id] = axes_actor;
addActorToRenderer (axes_actor, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addCoordinateSystem (double scale, float x, float y, float z, const std::string& id, int viewport)
{
if (scale <= 0.0)
scale = 1.0;
vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New ();
axes->SetOrigin (0, 0, 0);
axes->SetScaleFactor (scale);
axes->Update ();
vtkSmartPointer<vtkFloatArray> axes_colors = vtkSmartPointer<vtkFloatArray>::New ();
axes_colors->Allocate (6);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (1.0);
axes_colors->InsertNextValue (1.0);
vtkSmartPointer<vtkPolyData> axes_data = axes->GetOutput ();
axes_data->GetPointData ()->SetScalars (axes_colors);
vtkSmartPointer<vtkTubeFilter> axes_tubes = vtkSmartPointer<vtkTubeFilter>::New ();
#if VTK_MAJOR_VERSION < 6
axes_tubes->SetInput (axes_data);
#else
axes_tubes->SetInputData (axes_data);
#endif
axes_tubes->SetRadius (axes->GetScaleFactor () / 50.0);
axes_tubes->SetNumberOfSides (6);
vtkSmartPointer<vtkPolyDataMapper> axes_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
axes_mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
axes_mapper->SetInput (axes_tubes->GetOutput ());
#else
axes_mapper->SetInputConnection (axes_tubes->GetOutputPort ());
#endif
vtkSmartPointer<vtkLODActor> axes_actor = vtkSmartPointer<vtkLODActor>::New ();
axes_actor->SetMapper (axes_mapper);
axes_actor->SetPosition (x, y, z);
// Save the ID and actor pair to the global actor map
(*coordinate_actor_map_) [id] = axes_actor;
addActorToRenderer (axes_actor, viewport);
}
int
feq (double a, double b) {
return fabs (a - b) < 1e-9;
}
void
quat_to_angle_axis (const Eigen::Quaternionf &qx, double &theta, double axis[3])
{
double q[4];
q[0] = qx.w();
q[1] = qx.x();
q[2] = qx.y();
q[3] = qx.z();
double halftheta = acos (q[0]);
theta = halftheta * 2;
double sinhalftheta = sin (halftheta);
if (feq (halftheta, 0)) {
axis[0] = 0;
axis[1] = 0;
axis[2] = 1;
theta = 0;
} else {
axis[0] = q[1] / sinhalftheta;
axis[1] = q[2] / sinhalftheta;
axis[2] = q[3] / sinhalftheta;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addCoordinateSystem (double scale, const Eigen::Affine3f& t, const std::string& id, int viewport)
{
if (scale <= 0.0)
scale = 1.0;
vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New ();
axes->SetOrigin (0, 0, 0);
axes->SetScaleFactor (scale);
axes->Update ();
vtkSmartPointer<vtkFloatArray> axes_colors = vtkSmartPointer<vtkFloatArray>::New ();
axes_colors->Allocate (6);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (1.0);
axes_colors->InsertNextValue (1.0);
vtkSmartPointer<vtkPolyData> axes_data = axes->GetOutput ();
axes_data->GetPointData ()->SetScalars (axes_colors);
vtkSmartPointer<vtkTubeFilter> axes_tubes = vtkSmartPointer<vtkTubeFilter>::New ();
#if VTK_MAJOR_VERSION < 6
axes_tubes->SetInput (axes_data);
#else
axes_tubes->SetInputData (axes_data);
#endif
axes_tubes->SetRadius (axes->GetScaleFactor () / 50.0);
axes_tubes->SetNumberOfSides (6);
vtkSmartPointer<vtkPolyDataMapper> axes_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
axes_mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
axes_mapper->SetInput (axes_tubes->GetOutput ());
#else
axes_mapper->SetInputConnection (axes_tubes->GetOutputPort ());
#endif
vtkSmartPointer<vtkLODActor> axes_actor = vtkSmartPointer<vtkLODActor>::New ();
axes_actor->SetMapper (axes_mapper);
axes_actor->SetPosition (t (0, 3), t(1, 3), t(2, 3));
Eigen::Matrix3f m;
m =t.rotation();
Eigen::Quaternionf rf;
rf = Eigen::Quaternionf(m);
double r_angle;
double r_axis[3];
quat_to_angle_axis(rf,r_angle,r_axis);
//
axes_actor->SetOrientation(0,0,0);
axes_actor->RotateWXYZ(r_angle*180/M_PI,r_axis[0],r_axis[1],r_axis[2]);
//WAS: axes_actor->SetOrientation (roll, pitch, yaw);
// Save the ID and actor pair to the global actor map
(*coordinate_actor_map_) [id] = axes_actor;
addActorToRenderer (axes_actor, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeCoordinateSystem (const std::string& id, int viewport)
{
// Check to see if the given ID entry exists
CoordinateActorMap::iterator am_it = coordinate_actor_map_->find (id);
if (am_it == coordinate_actor_map_->end ())
return (false);
// Remove it from all renderers
if (removeActorFromRenderer (am_it->second, viewport))
{
// Remove the ID pair to the global actor map
coordinate_actor_map_->erase (am_it);
return (true);
}
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removePointCloud (const std::string &id, int viewport)
{
// Check to see if the given ID entry exists
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Remove it from all renderers
if (removeActorFromRenderer (am_it->second.actor, viewport))
{
// Remove the pointer/ID pair to the global actor map
cloud_actor_map_->erase (am_it);
return (true);
}
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeShape (const std::string &id, int viewport)
{
// Check to see if the given ID entry exists
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
// Extra step: check if there is a cloud with the same ID
CloudActorMap::iterator ca_it = cloud_actor_map_->find (id);
bool shape = true;
// Try to find a shape first
if (am_it == shape_actor_map_->end ())
{
// There is no cloud or shape with this ID, so just exit
if (ca_it == cloud_actor_map_->end ())
return (false);
// Cloud found, set shape to false
shape = false;
}
// Remove the pointer/ID pair to the global actor map
if (shape)
{
if (removeActorFromRenderer (am_it->second, viewport))
{
bool update_LUT (true);
if (!style_->lut_actor_id_.empty() && am_it->first != style_->lut_actor_id_)
update_LUT = false;
shape_actor_map_->erase (am_it);
if (update_LUT)
style_->updateLookUpTableDisplay (false);
return (true);
}
}
else
{
if (removeActorFromRenderer (ca_it->second.actor, viewport))
{
bool update_LUT (true);
if (!style_->lut_actor_id_.empty() && ca_it->first != style_->lut_actor_id_)
update_LUT = false;
cloud_actor_map_->erase (ca_it);
if (update_LUT)
style_->updateLookUpTableDisplay (false);
return (true);
}
}
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeText3D (const std::string &id, int viewport)
{
if (viewport < 0)
return false;
bool success = true;
// If there is no custom viewport and the viewport number is not 0, exit
if (rens_->GetNumberOfItems () <= viewport)
{
PCL_ERROR ("[removeText3D] The viewport [%d] doesn't exist (id <%s>)! ",
viewport,
id.c_str ());
return false;
}
// check all or an individual viewport for a similar id
rens_->InitTraversal ();
for (size_t i = viewport; rens_->GetNextItem () != NULL; ++i)
{
const std::string uid = id + std::string (i, '*');
ShapeActorMap::iterator am_it = shape_actor_map_->find (uid);
// was it found
if (am_it == shape_actor_map_->end ())
{
if (viewport > 0)
return (false);
continue;
}
// Remove it from all renderers
if (removeActorFromRenderer (am_it->second, i))
{
// Remove the pointer/ID pair to the global actor map
shape_actor_map_->erase (am_it);
if (viewport > 0)
return (true);
success &= true;
}
else
success = false;
}
return success;
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeAllPointClouds (int viewport)
{
// Check to see if the given ID entry exists
CloudActorMap::iterator am_it = cloud_actor_map_->begin ();
while (am_it != cloud_actor_map_->end () )
{
if (removePointCloud (am_it->first, viewport))
am_it = cloud_actor_map_->begin ();
else
++am_it;
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeAllShapes (int viewport)
{
bool display_lut (style_->lut_enabled_);
style_->lut_enabled_ = false; // Temporally disable LUT to fasten shape removal
// Check to see if the given ID entry exists
ShapeActorMap::iterator am_it = shape_actor_map_->begin ();
while (am_it != shape_actor_map_->end ())
{
if (removeShape (am_it->first, viewport))
am_it = shape_actor_map_->begin ();
else
++am_it;
}
if (display_lut)
{
style_->lut_enabled_ = true;
style_->updateLookUpTableDisplay (true);
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeAllCoordinateSystems (int viewport)
{
// Check to see if the given ID entry exists
CoordinateActorMap::iterator am_it = coordinate_actor_map_->begin ();
while (am_it != coordinate_actor_map_->end () )
{
if (removeCoordinateSystem (am_it->first, viewport))
am_it = coordinate_actor_map_->begin ();
else
++am_it;
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeActorFromRenderer (const vtkSmartPointer<vtkLODActor> &actor, int viewport)
{
vtkLODActor* actor_to_remove = vtkLODActor::SafeDownCast (actor);
// Add it to all renderers
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we remove the actor from all renderers?
if (viewport == 0)
{
renderer->RemoveActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
// Iterate over all actors in this renderer
vtkPropCollection* actors = renderer->GetViewProps ();
actors->InitTraversal ();
vtkProp* current_actor = NULL;
while ((current_actor = actors->GetNextProp ()) != NULL)
{
if (current_actor != actor_to_remove)
continue;
renderer->RemoveActor (actor);
// Found the correct viewport and removed the actor
return (true);
}
}
++i;
}
if (viewport == 0) return (true);
return (false);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeActorFromRenderer (const vtkSmartPointer<vtkActor> &actor, int viewport)
{
vtkActor* actor_to_remove = vtkActor::SafeDownCast (actor);
// Add it to all renderers
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we remove the actor from all renderers?
if (viewport == 0)
{
renderer->RemoveActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
// Iterate over all actors in this renderer
vtkPropCollection* actors = renderer->GetViewProps ();
actors->InitTraversal ();
vtkProp* current_actor = NULL;
while ((current_actor = actors->GetNextProp ()) != NULL)
{
if (current_actor != actor_to_remove)
continue;
renderer->RemoveActor (actor);
// Found the correct viewport and removed the actor
return (true);
}
}
++i;
}
if (viewport == 0) return (true);
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addActorToRenderer (const vtkSmartPointer<vtkProp> &actor, int viewport)
{
// Add it to all renderers
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we add the actor to all renderers?
if (viewport == 0)
{
renderer->AddActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
renderer->AddActor (actor);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeActorFromRenderer (const vtkSmartPointer<vtkProp> &actor, int viewport)
{
vtkProp* actor_to_remove = vtkProp::SafeDownCast (actor);
// Initialize traversal
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we remove the actor from all renderers?
if (viewport == 0)
{
renderer->RemoveActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
// Iterate over all actors in this renderer
vtkPropCollection* actors = renderer->GetViewProps ();
actors->InitTraversal ();
vtkProp* current_actor = NULL;
while ((current_actor = actors->GetNextProp ()) != NULL)
{
if (current_actor != actor_to_remove)
continue;
renderer->RemoveActor (actor);
// Found the correct viewport and removed the actor
return (true);
}
}
++i;
}
if (viewport == 0) return (true);
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
namespace
{
// Helper function called by createActorFromVTKDataSet () methods.
// This function determines the default setting of vtkMapper::InterpolateScalarsBeforeMapping.
// Return 0, interpolation off, if data is a vtkPolyData that contains only vertices.
// Return 1, interpolation on, for anything else.
int
getDefaultScalarInterpolationForDataSet (vtkDataSet* data)
{
vtkPolyData* polyData = vtkPolyData::SafeDownCast (data); // Check that polyData != NULL in case of segfault
return (polyData && polyData->GetNumberOfCells () != polyData->GetNumberOfVerts ());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createActorFromVTKDataSet (const vtkSmartPointer<vtkDataSet> &data,
vtkSmartPointer<vtkLODActor> &actor,
bool use_scalars)
{
// If actor is not initialized, initialize it here
if (!actor)
actor = vtkSmartPointer<vtkLODActor>::New ();
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
if (use_vbos_)
{
vtkSmartPointer<vtkVertexBufferObjectMapper> mapper = vtkSmartPointer<vtkVertexBufferObjectMapper>::New ();
mapper->SetInput (data);
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
else
#endif
{
vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (data);
#else
mapper->SetInputData (data);
#endif
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
mapper->ImmediateModeRenderingOff ();
#endif
actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createActorFromVTKDataSet (const vtkSmartPointer<vtkDataSet> &data,
vtkSmartPointer<vtkActor> &actor,
bool use_scalars)
{
// If actor is not initialized, initialize it here
if (!actor)
actor = vtkSmartPointer<vtkActor>::New ();
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
if (use_vbos_)
{
vtkSmartPointer<vtkVertexBufferObjectMapper> mapper = vtkSmartPointer<vtkVertexBufferObjectMapper>::New ();
mapper->SetInput (data);
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
//actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
else
#endif
{
vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (data);
#else
mapper->SetInputData (data);
#endif
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
mapper->ImmediateModeRenderingOff ();
#endif
//actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
//actor->SetNumberOfCloudPoints (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10));
actor->GetProperty ()->SetInterpolationToFlat ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertPointCloudToVTKPolyData (
const GeometryHandlerConstPtr &geometry_handler,
vtkSmartPointer<vtkPolyData> &polydata,
vtkSmartPointer<vtkIdTypeArray> &initcells)
{
vtkSmartPointer<vtkCellArray> vertices;
if (!polydata)
{
allocVtkPolyData (polydata);
vertices = vtkSmartPointer<vtkCellArray>::New ();
polydata->SetVerts (vertices);
}
// Use the handler to obtain the geometry
vtkSmartPointer<vtkPoints> points;
geometry_handler->getGeometry (points);
polydata->SetPoints (points);
vtkIdType nr_points = points->GetNumberOfPoints ();
// Create the supporting structures
vertices = polydata->GetVerts ();
if (!vertices)
vertices = vtkSmartPointer<vtkCellArray>::New ();
vtkSmartPointer<vtkIdTypeArray> cells = vertices->GetData ();
updateCells (cells, initcells, nr_points);
// Set the cells and the vertices
vertices->SetCells (nr_points, cells);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setBackgroundColor (
const double &r, const double &g, const double &b, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we add the actor to all renderers?
if (viewport == 0)
{
renderer->SetBackground (r, g, b);
}
else if (viewport == i) // add the actor only to the specified viewport
{
renderer->SetBackground (r, g, b);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudRenderingProperties (
int property, double val1, double val2, double val3, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_COLOR:
{
if (val1 > 1.0 || val2 > 1.0 || val3 > 1.0)
PCL_WARN ("[setPointCloudRenderingProperties] Colors go from 0.0 to 1.0!\n");
actor->GetProperty ()->SetColor (val1, val2, val3);
actor->GetMapper ()->ScalarVisibilityOff ();
actor->Modified ();
break;
}
default:
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudRenderingProperties (
int property, double val1, double val2, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Check that range values are correct
if (val1 >= val2)
{
PCL_WARN ("[setPointCloudRenderingProperties] Range max must be greater than range min!\n");
return (false);
}
// Update LUT
actor->GetMapper ()->GetLookupTable ()->SetRange (val1, val2);
actor->GetMapper()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
default:
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::getPointCloudRenderingProperties (int property, double &value, const std::string &id)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_POINT_SIZE:
{
value = actor->GetProperty ()->GetPointSize ();
actor->Modified ();
break;
}
case PCL_VISUALIZER_OPACITY:
{
value = actor->GetProperty ()->GetOpacity ();
actor->Modified ();
break;
}
case PCL_VISUALIZER_LINE_WIDTH:
{
value = actor->GetProperty ()->GetLineWidth ();
actor->Modified ();
break;
}
default:
{
pcl::console::print_error ("[getPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::getPointCloudRenderingProperties (RenderingProperties property,
double &val1,
double &val2,
double &val3,
const std::string &id)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_COLOR:
{
double rgb[3];
actor->GetProperty ()->GetColor (rgb);
val1 = rgb[0];
val2 = rgb[1];
val3 = rgb[2];
break;
}
default:
{
pcl::console::print_error ("[getPointCloudRenderingProperties] "
"Property (%d) is either unknown or it requires a different "
"number of variables to retrieve its contents.\n",
property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudRenderingProperties (
int property, double value, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_POINT_SIZE:
{
actor->GetProperty ()->SetPointSize (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_OPACITY:
{
actor->GetProperty ()->SetOpacity (value);
actor->Modified ();
break;
}
// Turn on/off flag to control whether data is rendered using immediate
// mode or note. Immediate mode rendering tends to be slower but it can
// handle larger datasets. The default value is immediate mode off. If you
// are having problems rendering a large dataset you might want to consider
// using immediate more rendering.
case PCL_VISUALIZER_IMMEDIATE_RENDERING:
{
actor->GetMapper ()->SetImmediateModeRendering (int (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_LINE_WIDTH:
{
actor->GetProperty ()->SetLineWidth (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_LUT:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Get range limits from existing LUT
double *range;
range = actor->GetMapper ()->GetLookupTable ()->GetRange ();
actor->GetMapper ()->ScalarVisibilityOn ();
actor->GetMapper ()->SetScalarRange (range[0], range[1]);
vtkSmartPointer<vtkLookupTable> table;
if (!pcl::visualization::getColormapLUT (static_cast<LookUpTableRepresentationProperties>(static_cast<int>(value)), table))
break;
table->SetRange (range[0], range[1]);
actor->GetMapper ()->SetLookupTable (table);
style_->updateLookUpTableDisplay (false);
break;
}
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
switch (int(value))
{
case PCL_VISUALIZER_LUT_RANGE_AUTO:
double range[2];
actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->GetRange (range);
actor->GetMapper ()->GetLookupTable ()->SetRange (range[0], range[1]);
actor->GetMapper ()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
break;
}
default:
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudSelected (const bool selected, const std::string &id)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
if (selected)
{
actor->GetProperty ()->EdgeVisibilityOn ();
actor->GetProperty ()->SetEdgeColor (1.0, 0.0, 0.0);
actor->Modified ();
}
else
{
actor->GetProperty ()->EdgeVisibilityOff ();
actor->Modified ();
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setShapeRenderingProperties (
int property, double val1, double val2, double val3, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it == shape_actor_map_->end ())
{
pcl::console::print_error ("[setShapeRenderingProperties] Could not find any shape with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkActor* actor = vtkActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_COLOR:
{
if (val1 > 1.0 || val2 > 1.0 || val3 > 1.0)
PCL_WARN ("[setShapeRenderingProperties] Colors go from 0.0 to 1.0!\n");
actor->GetMapper ()->ScalarVisibilityOff ();
actor->GetProperty ()->SetColor (val1, val2, val3);
actor->GetProperty ()->SetEdgeColor (val1, val2, val3);
// The following 3 are set by SetColor automatically according to the VTK docs
//actor->GetProperty ()->SetAmbientColor (val1, val2, val3);
//actor->GetProperty ()->SetDiffuseColor (val1, val2, val3);
//actor->GetProperty ()->SetSpecularColor (val1, val2, val3);
actor->GetProperty ()->SetAmbient (0.8);
actor->GetProperty ()->SetDiffuse (0.8);
actor->GetProperty ()->SetSpecular (0.8);
actor->Modified ();
break;
}
default:
{
pcl::console::print_error ("[setShapeRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setShapeRenderingProperties (
int property, double val1, double val2, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it == shape_actor_map_->end ())
{
pcl::console::print_error ("[setShapeRenderingProperties] Could not find any shape with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkActor* actor = vtkActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Check that range values are correct
if (val1 >= val2)
{
PCL_WARN ("[setShapeRenderingProperties] Range max must be greater than range min!\n");
return (false);
}
// Update LUT
actor->GetMapper ()->GetLookupTable ()->SetRange (val1, val2);
actor->GetMapper()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
default:
{
pcl::console::print_error ("[setShapeRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setShapeRenderingProperties (
int property, double value, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it == shape_actor_map_->end ())
{
pcl::console::print_error ("[setShapeRenderingProperties] Could not find any shape with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkActor* actor = vtkActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_POINT_SIZE:
{
actor->GetProperty ()->SetPointSize (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_OPACITY:
{
actor->GetProperty ()->SetOpacity (value);
actor->Modified ();
break;
}
case PCL_VISUALIZER_LINE_WIDTH:
{
actor->GetProperty ()->SetLineWidth (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_FONT_SIZE:
{
vtkTextActor* text_actor = vtkTextActor::SafeDownCast (am_it->second);
if (!text_actor)
return (false);
vtkSmartPointer<vtkTextProperty> tprop = text_actor->GetTextProperty ();
tprop->SetFontSize (int (value));
text_actor->Modified ();
break;
}
case PCL_VISUALIZER_REPRESENTATION:
{
switch (int (value))
{
case PCL_VISUALIZER_REPRESENTATION_POINTS:
{
actor->GetProperty ()->SetRepresentationToPoints ();
break;
}
case PCL_VISUALIZER_REPRESENTATION_WIREFRAME:
{
actor->GetProperty ()->SetRepresentationToWireframe ();
break;
}
case PCL_VISUALIZER_REPRESENTATION_SURFACE:
{
actor->GetProperty ()->SetRepresentationToSurface ();
break;
}
}
actor->Modified ();
break;
}
case PCL_VISUALIZER_SHADING:
{
switch (int (value))
{
case PCL_VISUALIZER_SHADING_FLAT:
{
actor->GetProperty ()->SetInterpolationToFlat ();
break;
}
case PCL_VISUALIZER_SHADING_GOURAUD:
{
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetNormals ())
{
PCL_INFO ("[pcl::visualization::PCLVisualizer::setShapeRenderingProperties] Normals do not exist in the dataset, but Gouraud shading was requested. Estimating normals...\n");
vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New ();
#if VTK_MAJOR_VERSION < 6
normals->SetInput (actor->GetMapper ()->GetInput ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInput (normals->GetOutput ());
#else
normals->SetInputConnection (actor->GetMapper ()->GetInputAlgorithm ()->GetOutputPort ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInputConnection (normals->GetOutputPort ());
#endif
}
actor->GetProperty ()->SetInterpolationToGouraud ();
break;
}
case PCL_VISUALIZER_SHADING_PHONG:
{
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetNormals ())
{
PCL_INFO ("[pcl::visualization::PCLVisualizer::setShapeRenderingProperties] Normals do not exist in the dataset, but Phong shading was requested. Estimating normals...\n");
vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New ();
#if VTK_MAJOR_VERSION < 6
normals->SetInput (actor->GetMapper ()->GetInput ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInput (normals->GetOutput ());
#else
normals->SetInputConnection (actor->GetMapper ()->GetInputAlgorithm ()->GetOutputPort ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInputConnection (normals->GetOutputPort ());
#endif
}
actor->GetProperty ()->SetInterpolationToPhong ();
break;
}
}
actor->Modified ();
break;
}
case PCL_VISUALIZER_LUT:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Get range limits from existing LUT
double *range;
range = actor->GetMapper ()->GetLookupTable ()->GetRange ();
actor->GetMapper ()->ScalarVisibilityOn ();
actor->GetMapper ()->SetScalarRange (range[0], range[1]);
vtkSmartPointer<vtkLookupTable> table;
if (!pcl::visualization::getColormapLUT (static_cast<LookUpTableRepresentationProperties>(static_cast<int>(value)), table))
break;
table->SetRange (range[0], range[1]);
actor->GetMapper ()->SetLookupTable (table);
style_->updateLookUpTableDisplay (false);
}
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
switch (int(value))
{
case PCL_VISUALIZER_LUT_RANGE_AUTO:
double range[2];
actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->GetRange (range);
actor->GetMapper ()->GetLookupTable ()->SetRange (range[0], range[1]);
actor->GetMapper ()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
break;
}
default:
{
pcl::console::print_error ("[setShapeRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::initCameraParameters ()
{
Camera camera_temp;
// Set default camera parameters to something meaningful
camera_temp.clip[0] = 0.01;
camera_temp.clip[1] = 1000.01;
// Look straight along the z-axis
camera_temp.focal[0] = 0.;
camera_temp.focal[1] = 0.;
camera_temp.focal[2] = 1.;
// Position the camera at the origin
camera_temp.pos[0] = 0.;
camera_temp.pos[1] = 0.;
camera_temp.pos[2] = 0.;
// Set the up-vector of the camera to be the y-axis
camera_temp.view[0] = 0.;
camera_temp.view[1] = 1.;
camera_temp.view[2] = 0.;
// Set the camera field of view to about
camera_temp.fovy = 0.8575;
int scr_size_x = win_->GetScreenSize ()[0];
int scr_size_y = win_->GetScreenSize ()[1];
camera_temp.window_size[0] = scr_size_x / 2;
camera_temp.window_size[1] = scr_size_y / 2;
setCameraParameters (camera_temp);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::cameraParamsSet () const
{
return (camera_set_);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::cameraFileLoaded () const
{
return (camera_file_loaded_);
}
/////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::visualization::PCLVisualizer::getCameraFile () const
{
return (style_->getCameraFile ());
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::updateCamera ()
{
PCL_WARN ("[pcl::visualization::PCLVisualizer::updateCamera()] This method was deprecated, just re-rendering all scenes now.");
rens_->InitTraversal ();
// Update the camera parameters
win_->Render ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateShapePose (const std::string &id, const Eigen::Affine3f& pose)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
vtkLODActor* actor;
if (am_it == shape_actor_map_->end ())
return (false);
else
actor = vtkLODActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (pose.matrix (), matrix);
actor->SetUserMatrix (matrix);
actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateCoordinateSystemPose (const std::string &id, const Eigen::Affine3f& pose)
{
ShapeActorMap::iterator am_it = coordinate_actor_map_->find (id);
vtkLODActor* actor;
if (am_it == coordinate_actor_map_->end ())
return (false);
else
actor = vtkLODActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (pose.matrix (), matrix);
actor->SetUserMatrix (matrix);
actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updatePointCloudPose (const std::string &id, const Eigen::Affine3f& pose)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (pose.matrix (), transformation);
am_it->second.viewpoint_transformation_ = transformation;
am_it->second.actor->SetUserMatrix (transformation);
am_it->second.actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::getCameras (std::vector<pcl::visualization::Camera>& cameras)
{
cameras.clear ();
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
cameras.push_back (Camera ());
cameras.back ().pos[0] = renderer->GetActiveCamera ()->GetPosition ()[0];
cameras.back ().pos[1] = renderer->GetActiveCamera ()->GetPosition ()[1];
cameras.back ().pos[2] = renderer->GetActiveCamera ()->GetPosition ()[2];
cameras.back ().focal[0] = renderer->GetActiveCamera ()->GetFocalPoint ()[0];
cameras.back ().focal[1] = renderer->GetActiveCamera ()->GetFocalPoint ()[1];
cameras.back ().focal[2] = renderer->GetActiveCamera ()->GetFocalPoint ()[2];
cameras.back ().clip[0] = renderer->GetActiveCamera ()->GetClippingRange ()[0];
cameras.back ().clip[1] = renderer->GetActiveCamera ()->GetClippingRange ()[1];
cameras.back ().view[0] = renderer->GetActiveCamera ()->GetViewUp ()[0];
cameras.back ().view[1] = renderer->GetActiveCamera ()->GetViewUp ()[1];
cameras.back ().view[2] = renderer->GetActiveCamera ()->GetViewUp ()[2];
cameras.back ().fovy = renderer->GetActiveCamera ()->GetViewAngle () / 180.0 * M_PI;
cameras.back ().window_size[0] = renderer->GetRenderWindow ()->GetSize ()[0];
cameras.back ().window_size[1] = renderer->GetRenderWindow ()->GetSize ()[1];
cameras.back ().window_pos[0] = 0;
cameras.back ().window_pos[1] = 0;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
Eigen::Affine3f
pcl::visualization::PCLVisualizer::getViewerPose (int viewport)
{
Eigen::Affine3f ret (Eigen::Affine3f::Identity ());
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
if (viewport == 0)
viewport = 1;
int viewport_i = 1;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
if (viewport_i == viewport)
{
vtkCamera& camera = *renderer->GetActiveCamera ();
Eigen::Vector3d pos, x_axis, y_axis, z_axis;
camera.GetPosition (pos[0], pos[1], pos[2]);
camera.GetViewUp (y_axis[0], y_axis[1], y_axis[2]);
camera.GetFocalPoint (z_axis[0], z_axis[1], z_axis[2]);
z_axis = (z_axis - pos).normalized ();
x_axis = y_axis.cross (z_axis).normalized ();
ret.translation () = pos.cast<float> ();
ret.linear ().col (0) << x_axis.cast<float> ();
ret.linear ().col (1) << y_axis.cast<float> ();
ret.linear ().col (2) << z_axis.cast<float> ();
return ret;
}
viewport_i ++;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::resetCamera ()
{
// Update the camera parameters
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
renderer->ResetCamera ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraPosition (
double pos_x, double pos_y, double pos_z,
double view_x, double view_y, double view_z,
double up_x, double up_y, double up_z,
int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetPosition (pos_x, pos_y, pos_z);
cam->SetFocalPoint (view_x, view_y, view_z);
cam->SetViewUp (up_x, up_y, up_z);
renderer->ResetCameraClippingRange ();
}
++i;
}
win_->Render ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraPosition (
double pos_x, double pos_y, double pos_z,
double up_x, double up_y, double up_z, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetPosition (pos_x, pos_y, pos_z);
cam->SetViewUp (up_x, up_y, up_z);
}
++i;
}
win_->Render ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraParameters (const Eigen::Matrix3f &intrinsics,
const Eigen::Matrix4f &extrinsics,
int viewport)
{
style_->setCameraParameters (intrinsics, extrinsics, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraParameters (const pcl::visualization::Camera &camera, int viewport)
{
style_->setCameraParameters (camera, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraClipDistances (double near, double far, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetClippingRange (near, far);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraFieldOfView (double fovy, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetUseHorizontalViewAngle (0);
cam->SetViewAngle (fovy * 180.0 / M_PI);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::resetCameraViewpoint (const std::string &id)
{
vtkSmartPointer<vtkMatrix4x4> camera_pose;
static CloudActorMap::iterator it = cloud_actor_map_->find (id);
if (it != cloud_actor_map_->end ())
camera_pose = it->second.viewpoint_transformation_;
else
return;
// Prevent a segfault
if (!camera_pose)
return;
// set all renderer to this viewpoint
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetPosition (camera_pose->GetElement (0, 3),
camera_pose->GetElement (1, 3),
camera_pose->GetElement (2, 3));
cam->SetFocalPoint (camera_pose->GetElement (0, 3) - camera_pose->GetElement (0, 2),
camera_pose->GetElement (1, 3) - camera_pose->GetElement (1, 2),
camera_pose->GetElement (2, 3) - camera_pose->GetElement (2, 2));
cam->SetViewUp (camera_pose->GetElement (0, 1),
camera_pose->GetElement (1, 1),
camera_pose->GetElement (2, 1));
renderer->SetActiveCamera (cam);
renderer->ResetCameraClippingRange ();
}
win_->Render ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::getCameraParameters (int argc, char **argv)
{
for (int i = 1; i < argc; i++)
{
if ((strcmp (argv[i], "-cam") == 0) && (++i < argc))
{
std::string camfile = std::string (argv[i]);
if (camfile.find (".cam") == std::string::npos)
{
// Assume we have clip/focal/pos/view
std::vector<std::string> camera;
boost::split (camera, argv[i], boost::is_any_of ("/"), boost::token_compress_on);
return (style_->getCameraParameters (camera));
}
else
{
// Assume that if we don't have clip/focal/pos/view, a filename.cam was given as a parameter
return (style_->loadCameraParameters (camfile));
}
}
}
return (false);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::loadCameraParameters (const std::string &file)
{
return (style_->loadCameraParameters (file));
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCylinder (const pcl::ModelCoefficients &coefficients,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCylinder] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 7)
{
PCL_WARN ("[addCylinder] Coefficients size does not match expected size (expected 7).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCylinder (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCube (const pcl::ModelCoefficients &coefficients,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCube] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 10)
{
PCL_WARN ("[addCube] Coefficients size does not match expected size (expected 10).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCube (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCube (
const Eigen::Vector3f &translation, const Eigen::Quaternionf &rotation,
double width, double height, double depth,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCube] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCube (translation, rotation, width, height, depth);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCube (float x_min, float x_max,
float y_min, float y_max,
float z_min, float z_max,
double r, double g, double b,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCube] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCube (x_min, x_max, y_min, y_max, z_min, z_max);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
actor->GetProperty ()->SetColor (r, g, b);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addSphere (const pcl::ModelCoefficients &coefficients,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addSphere] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 4)
{
PCL_WARN ("[addSphere] Coefficients size does not match expected size (expected 4).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createSphere (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPolyData (
vtkSmartPointer<vtkPolyData> polydata, const std::string & id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPolyData] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (polydata, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPolyData (
vtkSmartPointer<vtkPolyData> polydata, vtkSmartPointer<vtkTransform> transform, const std::string & id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPolyData] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer <vtkTransformFilter> trans_filter = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter->SetTransform (transform);
#if VTK_MAJOR_VERSION < 6
trans_filter->SetInput (polydata);
#else
trans_filter->SetInputData (polydata);
#endif
trans_filter->Update ();
// Create an Actor
vtkSmartPointer <vtkLODActor> actor;
createActorFromVTKDataSet (trans_filter->GetOutput (), actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPLYFile (const std::string &filename,
const std::string &id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPLYFile] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer<vtkPLYReader> reader = vtkSmartPointer<vtkPLYReader>::New ();
reader->SetFileName (filename.c_str ());
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (reader->GetOutput (), actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPLYFile (const std::string &filename,
vtkSmartPointer<vtkTransform> transform, const std::string &id,
int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPLYFile] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer <vtkPLYReader > reader = vtkSmartPointer<vtkPLYReader>::New ();
reader->SetFileName (filename.c_str ());
//create transformation filter
vtkSmartPointer <vtkTransformFilter> trans_filter = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter->SetTransform (transform);
trans_filter->SetInputConnection (reader->GetOutputPort ());
// Create an Actor
vtkSmartPointer <vtkLODActor> actor;
createActorFromVTKDataSet (trans_filter->GetOutput (), actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addLine (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addLine] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 6)
{
PCL_WARN ("[addLine] Coefficients size does not match expected size (expected 6).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createLine (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
/** \brief Add a plane from a set of given model coefficients
* \param coefficients the model coefficients (a, b, c, d with ax+by+cz+d=0)
* \param id the plane id/name (default: "plane")
* \param viewport (optional) the id of the new viewport (default: 0)
*/
bool
pcl::visualization::PCLVisualizer::addPlane (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addPlane] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 4)
{
PCL_WARN ("[addPlane] Coefficients size does not match expected size (expected 4).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createPlane (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
bool
pcl::visualization::PCLVisualizer::addPlane (const pcl::ModelCoefficients &coefficients, double x, double y, double z, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addPlane] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 4)
{
PCL_WARN ("[addPlane] Coefficients size does not match expected size (expected 4).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createPlane (coefficients, x, y, z);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCircle (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCircle] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 3)
{
PCL_WARN ("[addCircle] Coefficients size does not match expected size (expected 3).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = create2DCircle (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCone (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCone] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 7)
{
PCL_WARN ("[addCone] Coefficients size does not match expected size (expected 7).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCone (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createViewPort (double xmin, double ymin, double xmax, double ymax, int &viewport)
{
// Create a new renderer
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New ();
ren->SetViewport (xmin, ymin, xmax, ymax);
if (rens_->GetNumberOfItems () > 0)
ren->SetActiveCamera (rens_->GetFirstRenderer ()->GetActiveCamera ());
ren->ResetCamera ();
// Add it to the list of renderers
rens_->AddItem (ren);
if (rens_->GetNumberOfItems () <= 1) // If only one renderer
viewport = 0; // set viewport to 'all'
else
viewport = rens_->GetNumberOfItems () - 1;
win_->AddRenderer (ren);
win_->Modified ();
}
//////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createViewPortCamera (const int viewport)
{
vtkSmartPointer<vtkCamera> cam = vtkSmartPointer<vtkCamera>::New ();
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
if (viewport == 0)
continue;
else if (viewport == i)
{
renderer->SetActiveCamera (cam);
renderer->ResetCamera ();
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addText (const std::string &text, int xpos, int ypos, const std::string &id, int viewport)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addText] A text with id <%s> already exists! Please choose a different id and retry.\n", tid.c_str ());
return (false);
}
// Create an Actor
vtkSmartPointer<vtkTextActor> actor = vtkSmartPointer<vtkTextActor>::New ();
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetFontSize (10);
tprop->SetFontFamilyToArial ();
tprop->SetJustificationToLeft ();
tprop->BoldOn ();
tprop->SetColor (1, 1, 1);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[tid] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addText (const std::string &text, int xpos, int ypos, double r, double g, double b, const std::string &id, int viewport)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addText] A text with id <%s> already exists! Please choose a different id and retry.\n", tid.c_str ());
return (false);
}
// Create an Actor
vtkSmartPointer<vtkTextActor> actor = vtkSmartPointer<vtkTextActor>::New ();
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetFontSize (10);
tprop->SetFontFamilyToArial ();
tprop->SetJustificationToLeft ();
tprop->BoldOn ();
tprop->SetColor (r, g, b);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[tid] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addText (const std::string &text, int xpos, int ypos, int fontsize, double r, double g, double b, const std::string &id, int viewport)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addText] A text with id <%s> already exists! Please choose a different id and retry.\n", tid.c_str ());
return (false);
}
// Create an Actor
vtkSmartPointer<vtkTextActor> actor = vtkSmartPointer<vtkTextActor>::New ();
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetFontSize (fontsize);
tprop->SetFontFamilyToArial ();
tprop->SetJustificationToLeft ();
tprop->BoldOn ();
tprop->SetColor (r, g, b);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[tid] = actor;
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateText (const std::string &text, int xpos, int ypos, const std::string &id)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it == shape_actor_map_->end ())
return (false);
// Retrieve the Actor
vtkTextActor* actor = vtkTextActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
actor->Modified ();
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateText (const std::string &text, int xpos, int ypos, double r, double g, double b, const std::string &id)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it == shape_actor_map_->end ())
return (false);
// Create the Actor
vtkTextActor* actor = vtkTextActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetColor (r, g, b);
actor->Modified ();
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateText (const std::string &text, int xpos, int ypos, int fontsize, double r, double g, double b, const std::string &id)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it == shape_actor_map_->end ())
return (false);
// Retrieve the Actor
vtkTextActor *actor = vtkTextActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkTextProperty* tprop = actor->GetTextProperty ();
tprop->SetFontSize (fontsize);
tprop->SetColor (r, g, b);
actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateColorHandlerIndex (const std::string &id, int index)
{
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[updateColorHandlerIndex] PointCloud with id <%s> doesn't exist!\n", id.c_str ());
return (false);
}
size_t color_handler_size = am_it->second.color_handlers.size ();
if (!(size_t (index) < color_handler_size))
{
pcl::console::print_warn (stderr, "[updateColorHandlerIndex] Invalid index <%d> given! Index must be less than %d.\n", index, int (color_handler_size));
return (false);
}
// Get the handler
PointCloudColorHandler<pcl::PCLPointCloud2>::ConstPtr color_handler = am_it->second.color_handlers[index];
vtkSmartPointer<vtkDataArray> scalars;
color_handler->getColor (scalars);
double minmax[2];
scalars->GetRange (minmax);
// Update the data
vtkPolyData *data = static_cast<vtkPolyData*>(am_it->second.actor->GetMapper ()->GetInput ());
data->GetPointData ()->SetScalars (scalars);
// Modify the mapper
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
if (use_vbos_)
{
vtkVertexBufferObjectMapper* mapper = static_cast<vtkVertexBufferObjectMapper*>(am_it->second.actor->GetMapper ());
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInput (data);
// Modify the actor
am_it->second.actor->SetMapper (mapper);
am_it->second.actor->Modified ();
am_it->second.color_handler_index_ = index;
//style_->setCloudActorMap (cloud_actor_map_);
}
else
#endif
{
vtkPolyDataMapper* mapper = static_cast<vtkPolyDataMapper*>(am_it->second.actor->GetMapper ());
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (data);
#else
mapper->SetInputData (data);
#endif
// Modify the actor
am_it->second.actor->SetMapper (mapper);
am_it->second.actor->Modified ();
am_it->second.color_handler_index_ = index;
//style_->setCloudActorMap (cloud_actor_map_);
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPolygonMesh (const pcl::PolygonMesh &poly_mesh,
const std::string &id,
int viewport)
{
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addPolygonMesh] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
// Create points from polyMesh.cloud
vtkSmartPointer<vtkPoints> poly_points = vtkSmartPointer<vtkPoints>::New ();
pcl::PointCloud<pcl::PointXYZ>::Ptr point_cloud (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::fromPCLPointCloud2 (poly_mesh.cloud, *point_cloud);
poly_points->SetNumberOfPoints (point_cloud->points.size ());
for (size_t i = 0; i < point_cloud->points.size (); ++i)
{
const pcl::PointXYZ& p = point_cloud->points[i];
poly_points->InsertPoint (i, p.x, p.y, p.z);
}
bool has_color = false;
vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New ();
if (pcl::getFieldIndex(poly_mesh.cloud, "rgb") != -1)
{
has_color = true;
colors->SetNumberOfComponents (3);
colors->SetName ("Colors");
pcl::PointCloud<pcl::PointXYZRGB> cloud;
pcl::fromPCLPointCloud2 (poly_mesh.cloud, cloud);
for (size_t i = 0; i < cloud.points.size (); ++i)
{
const unsigned char color[3] = { cloud.points[i].r, cloud.points[i].g, cloud.points[i].b };
colors->InsertNextTupleValue (color);
}
}
if (pcl::getFieldIndex (poly_mesh.cloud, "rgba") != -1)
{
has_color = true;
colors->SetNumberOfComponents (3);
colors->SetName ("Colors");
pcl::PointCloud<pcl::PointXYZRGBA> cloud;
pcl::fromPCLPointCloud2 (poly_mesh.cloud, cloud);
for (size_t i = 0; i < cloud.points.size (); ++i)
{
const unsigned char color[3] = { cloud.points[i].r, cloud.points[i].g, cloud.points[i].b };
colors->InsertNextTupleValue (color);
}
}
vtkSmartPointer<vtkLODActor> actor;
if (poly_mesh.polygons.size () > 1)
{
//create polys from polyMesh.polygons
vtkSmartPointer<vtkCellArray> cell_array = vtkSmartPointer<vtkCellArray>::New ();
for (size_t i = 0; i < poly_mesh.polygons.size (); i++)
{
size_t n_points (poly_mesh.polygons[i].vertices.size ());
cell_array->InsertNextCell (int (n_points));
for (size_t j = 0; j < n_points; j++)
cell_array->InsertCellPoint (poly_mesh.polygons[i].vertices[j]);
}
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New ();
// polydata->SetStrips (cell_array);
polydata->SetPolys (cell_array);
polydata->SetPoints (poly_points);
if (has_color)
polydata->GetPointData ()->SetScalars (colors);
createActorFromVTKDataSet (polydata, actor);
}
else if (poly_mesh.polygons.size () == 1)
{
vtkSmartPointer<vtkPolygon> polygon = vtkSmartPointer<vtkPolygon>::New ();
size_t n_points = poly_mesh.polygons[0].vertices.size ();
polygon->GetPointIds ()->SetNumberOfIds (n_points - 1);
for (size_t j = 0; j < (n_points - 1); j++)
polygon->GetPointIds ()->SetId (j, poly_mesh.polygons[0].vertices[j]);
vtkSmartPointer<vtkUnstructuredGrid> poly_grid = vtkSmartPointer<vtkUnstructuredGrid>::New ();
poly_grid->Allocate (1, 1);
poly_grid->InsertNextCell (polygon->GetCellType (), polygon->GetPointIds ());
poly_grid->SetPoints (poly_points);
createActorFromVTKDataSet (poly_grid, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
}
else
{
PCL_ERROR ("PCLVisualizer::addPolygonMesh: No polygons\n");
return false;
}
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*cloud_actor_map_)[id].actor = actor;
// Save the viewpoint transformation matrix to the global actor map
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (point_cloud->sensor_origin_, point_cloud->sensor_orientation_, transformation);
(*cloud_actor_map_)[id].viewpoint_transformation_ = transformation;
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updatePolygonMesh (
const pcl::PolygonMesh &poly_mesh,
const std::string &id)
{
if (poly_mesh.polygons.empty ())
{
pcl::console::print_error ("[updatePolygonMesh] No vertices given!\n");
return (false);
}
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Create points from polyMesh.cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::fromPCLPointCloud2 (poly_mesh.cloud, *cloud);
std::vector<pcl::Vertices> verts (poly_mesh.polygons); // copy vector
// Get the current poly data
vtkSmartPointer<vtkPolyData> polydata = static_cast<vtkPolyDataMapper*>(am_it->second.actor->GetMapper ())->GetInput ();
if (!polydata)
return (false);
vtkSmartPointer<vtkCellArray> cells = polydata->GetStrips ();
if (!cells)
return (false);
vtkSmartPointer<vtkPoints> points = polydata->GetPoints ();
// Copy the new point array in
vtkIdType nr_points = cloud->points.size ();
points->SetNumberOfPoints (nr_points);
// Get a pointer to the beginning of the data array
float *data = static_cast<vtkFloatArray*> (points->GetData ())->GetPointer (0);
int ptr = 0;
std::vector<int> lookup;
// If the dataset is dense (no NaNs)
if (cloud->is_dense)
{
for (vtkIdType i = 0; i < nr_points; ++i, ptr += 3)
std::copy (&cloud->points[i].x, &cloud->points[i].x + 3, &data[ptr]);
}
else
{
lookup.resize (nr_points);
vtkIdType j = 0; // true point index
for (vtkIdType i = 0; i < nr_points; ++i)
{
// Check if the point is invalid
if (!isFinite (cloud->points[i]))
continue;
lookup[i] = static_cast<int> (j);
std::copy (&cloud->points[i].x, &cloud->points[i].x + 3, &data[ptr]);
j++;
ptr += 3;
}
nr_points = j;
points->SetNumberOfPoints (nr_points);
}
// Get the maximum size of a polygon
int max_size_of_polygon = -1;
for (size_t i = 0; i < verts.size (); ++i)
if (max_size_of_polygon < static_cast<int> (verts[i].vertices.size ()))
max_size_of_polygon = static_cast<int> (verts[i].vertices.size ());
// Update the cells
cells = vtkSmartPointer<vtkCellArray>::New ();
vtkIdType *cell = cells->WritePointer (verts.size (), verts.size () * (max_size_of_polygon + 1));
int idx = 0;
if (lookup.size () > 0)
{
for (size_t i = 0; i < verts.size (); ++i, ++idx)
{
size_t n_points = verts[i].vertices.size ();
*cell++ = n_points;
for (size_t j = 0; j < n_points; j++, cell++, ++idx)
*cell = lookup[verts[i].vertices[j]];
}
}
else
{
for (size_t i = 0; i < verts.size (); ++i, ++idx)
{
size_t n_points = verts[i].vertices.size ();
*cell++ = n_points;
for (size_t j = 0; j < n_points; j++, cell++, ++idx)
*cell = verts[i].vertices[j];
}
}
cells->GetData ()->SetNumberOfValues (idx);
cells->Squeeze ();
// Set the the vertices
polydata->SetStrips (cells);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPolylineFromPolygonMesh (
const pcl::PolygonMesh &polymesh, const std::string &id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addPolylineFromPolygonMesh] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
// Create points from polyMesh.cloud
vtkSmartPointer<vtkPoints> poly_points = vtkSmartPointer<vtkPoints>::New ();
pcl::PointCloud<pcl::PointXYZ> point_cloud;
pcl::fromPCLPointCloud2 (polymesh.cloud, point_cloud);
poly_points->SetNumberOfPoints (point_cloud.points.size ());
size_t i;
for (i = 0; i < point_cloud.points.size (); ++i)
poly_points->InsertPoint (i, point_cloud.points[i].x, point_cloud.points[i].y, point_cloud.points[i].z);
// Create a cell array to store the lines in and add the lines to it
vtkSmartPointer <vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New ();
vtkSmartPointer <vtkPolyData> polyData;
allocVtkPolyData (polyData);
for (i = 0; i < polymesh.polygons.size (); i++)
{
vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New();
polyLine->GetPointIds()->SetNumberOfIds(polymesh.polygons[i].vertices.size());
for(unsigned int k = 0; k < polymesh.polygons[i].vertices.size(); k++)
{
polyLine->GetPointIds ()->SetId (k, polymesh.polygons[i].vertices[k]);
}
cells->InsertNextCell (polyLine);
}
// Add the points to the dataset
polyData->SetPoints (poly_points);
// Add the lines to the dataset
polyData->SetLines (cells);
// Setup actor and mapper
vtkSmartPointer < vtkPolyDataMapper > mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (polyData);
#else
mapper->SetInputData (polyData);
#endif
vtkSmartPointer < vtkActor > actor = vtkSmartPointer<vtkActor>::New ();
actor->SetMapper (mapper);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addTextureMesh (const pcl::TextureMesh &mesh,
const std::string &id,
int viewport)
{
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] A shape with id <%s> already exists!"
" Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
// no texture materials --> exit
if (mesh.tex_materials.size () == 0)
{
PCL_ERROR("[PCLVisualizer::addTextureMesh] No textures found!\n");
return (false);
}
// polygons are mapped to texture materials
if (mesh.tex_materials.size () != mesh.tex_polygons.size ())
{
PCL_ERROR("[PCLVisualizer::addTextureMesh] Materials number %lu differs from polygons number %lu!\n",
mesh.tex_materials.size (), mesh.tex_polygons.size ());
return (false);
}
// each texture material should have its coordinates set
if (mesh.tex_materials.size () != mesh.tex_coordinates.size ())
{
PCL_ERROR("[PCLVisualizer::addTextureMesh] Coordinates number %lu differs from materials number %lu!\n",
mesh.tex_coordinates.size (), mesh.tex_materials.size ());
return (false);
}
// total number of vertices
std::size_t nb_vertices = 0;
for (std::size_t i = 0; i < mesh.tex_polygons.size (); ++i)
nb_vertices += mesh.tex_polygons[i].size ();
// no vertices --> exit
if (nb_vertices == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] No vertices found!\n");
return (false);
}
// total number of coordinates
std::size_t nb_coordinates = 0;
for (std::size_t i = 0; i < mesh.tex_coordinates.size (); ++i)
nb_coordinates += mesh.tex_coordinates[i].size ();
// no texture coordinates --> exit
if (nb_coordinates == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] No textures coordinates found!\n");
return (false);
}
// Create points from mesh.cloud
vtkSmartPointer<vtkPoints> poly_points = vtkSmartPointer<vtkPoints>::New ();
vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New ();
bool has_color = false;
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
if ((pcl::getFieldIndex(mesh.cloud, "rgba") != -1) ||
(pcl::getFieldIndex(mesh.cloud, "rgb") != -1))
{
pcl::PointCloud<pcl::PointXYZRGB> cloud;
pcl::fromPCLPointCloud2 (mesh.cloud, cloud);
if (cloud.points.size () == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] Cloud is empty!\n");
return (false);
}
convertToVtkMatrix (cloud.sensor_origin_, cloud.sensor_orientation_, transformation);
has_color = true;
colors->SetNumberOfComponents (3);
colors->SetName ("Colors");
poly_points->SetNumberOfPoints (cloud.size ());
for (std::size_t i = 0; i < cloud.points.size (); ++i)
{
const pcl::PointXYZRGB &p = cloud.points[i];
poly_points->InsertPoint (i, p.x, p.y, p.z);
const unsigned char color[3] = { p.r, p.g, p.b };
colors->InsertNextTupleValue (color);
}
}
else
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::fromPCLPointCloud2 (mesh.cloud, *cloud);
// no points --> exit
if (cloud->points.size () == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] Cloud is empty!\n");
return (false);
}
convertToVtkMatrix (cloud->sensor_origin_, cloud->sensor_orientation_, transformation);
poly_points->SetNumberOfPoints (cloud->points.size ());
for (std::size_t i = 0; i < cloud->points.size (); ++i)
{
const pcl::PointXYZ &p = cloud->points[i];
poly_points->InsertPoint (i, p.x, p.y, p.z);
}
}
//create polys from polyMesh.tex_polygons
vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New ();
for (std::size_t i = 0; i < mesh.tex_polygons.size (); i++)
{
for (std::size_t j = 0; j < mesh.tex_polygons[i].size (); j++)
{
std::size_t n_points = mesh.tex_polygons[i][j].vertices.size ();
polys->InsertNextCell (int (n_points));
for (std::size_t k = 0; k < n_points; k++)
polys->InsertCellPoint (mesh.tex_polygons[i][j].vertices[k]);
}
}
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New ();
polydata->SetPolys (polys);
polydata->SetPoints (poly_points);
if (has_color)
polydata->GetPointData ()->SetScalars (colors);
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (polydata);
#else
mapper->SetInputData (polydata);
#endif
vtkSmartPointer<vtkLODActor> actor = vtkSmartPointer<vtkLODActor>::New ();
vtkTextureUnitManager* tex_manager = vtkOpenGLRenderWindow::SafeDownCast (win_)->GetTextureUnitManager ();
if (!tex_manager)
return (false);
// Check if hardware support multi texture
int texture_units = tex_manager->GetNumberOfTextureUnits ();
if ((mesh.tex_materials.size () > 1) && (texture_units > 1))
{
if ((size_t) texture_units < mesh.tex_materials.size ())
PCL_WARN ("[PCLVisualizer::addTextureMesh] GPU texture units %d < mesh textures %d!\n",
texture_units, mesh.tex_materials.size ());
// Load textures
std::size_t last_tex_id = std::min (static_cast<int> (mesh.tex_materials.size ()), texture_units);
int tu = vtkProperty::VTK_TEXTURE_UNIT_0;
std::size_t tex_id = 0;
while (tex_id < last_tex_id)
{
vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New ();
if (textureFromTexMaterial (mesh.tex_materials[tex_id], texture))
{
PCL_WARN ("[PCLVisualizer::addTextureMesh] Failed to load texture %s, skipping!\n",
mesh.tex_materials[tex_id].tex_name.c_str ());
continue;
}
// the first texture is in REPLACE mode others are in ADD mode
if (tex_id == 0)
texture->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_REPLACE);
else
texture->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
// add a texture coordinates array per texture
vtkSmartPointer<vtkFloatArray> coordinates = vtkSmartPointer<vtkFloatArray>::New ();
coordinates->SetNumberOfComponents (2);
std::stringstream ss; ss << "TCoords" << tex_id;
std::string this_coordinates_name = ss.str ();
coordinates->SetName (this_coordinates_name.c_str ());
for (std::size_t t = 0; t < mesh.tex_coordinates.size (); ++t)
if (t == tex_id)
for (std::size_t tc = 0; tc < mesh.tex_coordinates[t].size (); ++tc)
coordinates->InsertNextTuple2 (mesh.tex_coordinates[t][tc][0],
mesh.tex_coordinates[t][tc][1]);
else
for (std::size_t tc = 0; tc < mesh.tex_coordinates[t].size (); ++tc)
coordinates->InsertNextTuple2 (-1.0, -1.0);
mapper->MapDataArrayToMultiTextureAttribute(tu,
this_coordinates_name.c_str (),
vtkDataObject::FIELD_ASSOCIATION_POINTS);
polydata->GetPointData ()->AddArray (coordinates);
actor->GetProperty ()->SetTexture (tu, texture);
++tex_id;
++tu;
}
} // end of multi texturing
else
{
if ((mesh.tex_materials.size () > 1) && (texture_units < 2))
PCL_WARN ("[PCLVisualizer::addTextureMesh] Your GPU doesn't support multi texturing. "
"Will use first one only!\n");
vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New ();
// fill vtkTexture from pcl::TexMaterial structure
if (textureFromTexMaterial (mesh.tex_materials[0], texture))
PCL_WARN ("[PCLVisualizer::addTextureMesh] Failed to create vtkTexture from %s!\n",
mesh.tex_materials[0].tex_name.c_str ());
// set texture coordinates
vtkSmartPointer<vtkFloatArray> coordinates = vtkSmartPointer<vtkFloatArray>::New ();
coordinates->SetNumberOfComponents (2);
coordinates->SetNumberOfTuples (mesh.tex_coordinates[0].size ());
for (std::size_t tc = 0; tc < mesh.tex_coordinates[0].size (); ++tc)
{
const Eigen::Vector2f &uv = mesh.tex_coordinates[0][tc];
coordinates->SetTuple2 (tc, uv[0], uv[1]);
}
coordinates->SetName ("TCoords");
polydata->GetPointData ()->SetTCoords (coordinates);
// apply texture
actor->SetTexture (texture);
} // end of one texture
// set mapper
actor->SetMapper (mapper);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*cloud_actor_map_)[id].actor = actor;
// Save the viewpoint transformation matrix to the global actor map
(*cloud_actor_map_)[id].viewpoint_transformation_ = transformation;
return (true);
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setRepresentationToSurfaceForAllActors ()
{
ShapeActorMap::iterator am_it;
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkActorCollection * actors = renderer->GetActors ();
actors->InitTraversal ();
vtkActor * actor;
while ((actor = actors->GetNextActor ()) != NULL)
{
actor->GetProperty ()->SetRepresentationToSurface ();
actor->GetProperty ()->SetLighting (true);
}
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setRepresentationToPointsForAllActors ()
{
ShapeActorMap::iterator am_it;
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkActorCollection * actors = renderer->GetActors ();
actors->InitTraversal ();
vtkActor * actor;
while ((actor = actors->GetNextActor ()) != NULL)
{
actor->GetProperty ()->SetRepresentationToPoints ();
}
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setRepresentationToWireframeForAllActors ()
{
ShapeActorMap::iterator am_it;
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkActorCollection * actors = renderer->GetActors ();
actors->InitTraversal ();
vtkActor * actor;
while ((actor = actors->GetNextActor ()) != NULL)
{
actor->GetProperty ()->SetRepresentationToWireframe ();
actor->GetProperty ()->SetLighting (false);
}
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setShowFPS (bool show_fps)
{
update_fps_->actor->SetVisibility (show_fps);
}
///////////////////////////////////////////////////////////////////////////////////
float
pcl::visualization::PCLVisualizer::getFPS () const
{
return (update_fps_->last_fps);
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::renderViewTesselatedSphere (
int xres,
int yres,
pcl::PointCloud<pcl::PointXYZ>::CloudVectorType &clouds,
std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<
Eigen::Matrix4f> > & poses,
std::vector<float> & enthropies, int tesselation_level,
float view_angle, float radius_sphere, bool use_vertices)
{
if (rens_->GetNumberOfItems () > 1)
{
PCL_WARN ("[renderViewTesselatedSphere] Method works only with one renderer.\n");
return;
}
rens_->InitTraversal ();
vtkRenderer* renderer_pcl_vis = rens_->GetNextItem ();
vtkActorCollection * actors = renderer_pcl_vis->GetActors ();
if (actors->GetNumberOfItems () > 1)
PCL_INFO ("[renderViewTesselatedSphere] Method only consider the first actor on the scene, more than one found.\n");
//get vtk object from the visualizer
actors->InitTraversal ();
vtkActor * actor = actors->GetNextActor ();
vtkSmartPointer<vtkPolyData> polydata;
allocVtkPolyData (polydata);
polydata->CopyStructure (actor->GetMapper ()->GetInput ());
//center object
double CoM[3];
vtkIdType npts_com = 0, *ptIds_com = NULL;
vtkSmartPointer<vtkCellArray> cells_com = polydata->GetPolys ();
double center[3], p1_com[3], p2_com[3], p3_com[3], area_com, totalArea_com = 0;
double comx = 0, comy = 0, comz = 0;
for (cells_com->InitTraversal (); cells_com->GetNextCell (npts_com, ptIds_com);)
{
polydata->GetPoint (ptIds_com[0], p1_com);
polydata->GetPoint (ptIds_com[1], p2_com);
polydata->GetPoint (ptIds_com[2], p3_com);
vtkTriangle::TriangleCenter (p1_com, p2_com, p3_com, center);
area_com = vtkTriangle::TriangleArea (p1_com, p2_com, p3_com);
comx += center[0] * area_com;
comy += center[1] * area_com;
comz += center[2] * area_com;
totalArea_com += area_com;
}
CoM[0] = comx / totalArea_com;
CoM[1] = comy / totalArea_com;
CoM[2] = comz / totalArea_com;
vtkSmartPointer<vtkTransform> trans_center = vtkSmartPointer<vtkTransform>::New ();
trans_center->Translate (-CoM[0], -CoM[1], -CoM[2]);
vtkSmartPointer<vtkMatrix4x4> matrixCenter = trans_center->GetMatrix ();
vtkSmartPointer<vtkTransformFilter> trans_filter_center = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter_center->SetTransform (trans_center);
#if VTK_MAJOR_VERSION < 6
trans_filter_center->SetInput (polydata);
#else
trans_filter_center->SetInputData (polydata);
#endif
trans_filter_center->Update ();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
mapper->SetInputConnection (trans_filter_center->GetOutputPort ());
mapper->Update ();
//scale so it fits in the unit sphere!
double bb[6];
mapper->GetBounds (bb);
double ms = (std::max) ((std::fabs) (bb[0] - bb[1]),
(std::max) ((std::fabs) (bb[2] - bb[3]), (std::fabs) (bb[4] - bb[5])));
double max_side = radius_sphere / 2.0;
double scale_factor = max_side / ms;
vtkSmartPointer<vtkTransform> trans_scale = vtkSmartPointer<vtkTransform>::New ();
trans_scale->Scale (scale_factor, scale_factor, scale_factor);
vtkSmartPointer<vtkMatrix4x4> matrixScale = trans_scale->GetMatrix ();
vtkSmartPointer<vtkTransformFilter> trans_filter_scale = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter_scale->SetTransform (trans_scale);
trans_filter_scale->SetInputConnection (trans_filter_center->GetOutputPort ());
trans_filter_scale->Update ();
mapper->SetInputConnection (trans_filter_scale->GetOutputPort ());
mapper->Update ();
//////////////////////////////
// * Compute area of the mesh
//////////////////////////////
vtkSmartPointer<vtkCellArray> cells = mapper->GetInput ()->GetPolys ();
vtkIdType npts = 0, *ptIds = NULL;
double p1[3], p2[3], p3[3], area, totalArea = 0;
for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds);)
{
polydata->GetPoint (ptIds[0], p1);
polydata->GetPoint (ptIds[1], p2);
polydata->GetPoint (ptIds[2], p3);
area = vtkTriangle::TriangleArea (p1, p2, p3);
totalArea += area;
}
//create icosahedron
vtkSmartPointer<vtkPlatonicSolidSource> ico = vtkSmartPointer<vtkPlatonicSolidSource>::New ();
ico->SetSolidTypeToIcosahedron ();
ico->Update ();
//tesselate cells from icosahedron
vtkSmartPointer<vtkLoopSubdivisionFilter> subdivide = vtkSmartPointer<vtkLoopSubdivisionFilter>::New ();
subdivide->SetNumberOfSubdivisions (tesselation_level);
subdivide->SetInputConnection (ico->GetOutputPort ());
subdivide->Update ();
// Get camera positions
vtkPolyData *sphere = subdivide->GetOutput ();
std::vector<Eigen::Vector3f, Eigen::aligned_allocator<Eigen::Vector3f> > cam_positions;
if (!use_vertices)
{
vtkSmartPointer<vtkCellArray> cells_sphere = sphere->GetPolys ();
cam_positions.resize (sphere->GetNumberOfPolys ());
size_t i = 0;
for (cells_sphere->InitTraversal (); cells_sphere->GetNextCell (npts_com, ptIds_com);)
{
sphere->GetPoint (ptIds_com[0], p1_com);
sphere->GetPoint (ptIds_com[1], p2_com);
sphere->GetPoint (ptIds_com[2], p3_com);
vtkTriangle::TriangleCenter (p1_com, p2_com, p3_com, center);
cam_positions[i] = Eigen::Vector3f (float (center[0]), float (center[1]), float (center[2]));
cam_positions[i].normalize ();
i++;
}
}
else
{
cam_positions.resize (sphere->GetNumberOfPoints ());
for (int i = 0; i < sphere->GetNumberOfPoints (); i++)
{
double cam_pos[3];
sphere->GetPoint (i, cam_pos);
cam_positions[i] = Eigen::Vector3f (float (cam_pos[0]), float (cam_pos[1]), float (cam_pos[2]));
cam_positions[i].normalize ();
}
}
double camera_radius = radius_sphere;
double cam_pos[3];
double first_cam_pos[3];
first_cam_pos[0] = cam_positions[0][0] * radius_sphere;
first_cam_pos[1] = cam_positions[0][1] * radius_sphere;
first_cam_pos[2] = cam_positions[0][2] * radius_sphere;
//create renderer and window
vtkSmartPointer<vtkRenderWindow> render_win = vtkSmartPointer<vtkRenderWindow>::New ();
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New ();
render_win->AddRenderer (renderer);
render_win->SetSize (xres, yres);
renderer->SetBackground (1.0, 0, 0);
//create picker
vtkSmartPointer<vtkWorldPointPicker> worldPicker = vtkSmartPointer<vtkWorldPointPicker>::New ();
vtkSmartPointer<vtkCamera> cam = vtkSmartPointer<vtkCamera>::New ();
cam->SetFocalPoint (0, 0, 0);
Eigen::Vector3f cam_pos_3f = cam_positions[0];
Eigen::Vector3f perp = cam_pos_3f.cross (Eigen::Vector3f::UnitY ());
cam->SetViewUp (perp[0], perp[1], perp[2]);
cam->SetPosition (first_cam_pos);
cam->SetViewAngle (view_angle);
cam->Modified ();
//For each camera position, traposesnsform the object and render view
for (size_t i = 0; i < cam_positions.size (); i++)
{
cam_pos[0] = cam_positions[i][0];
cam_pos[1] = cam_positions[i][1];
cam_pos[2] = cam_positions[i][2];
//create temporal virtual camera
vtkSmartPointer<vtkCamera> cam_tmp = vtkSmartPointer<vtkCamera>::New ();
cam_tmp->SetViewAngle (view_angle);
Eigen::Vector3f cam_pos_3f (static_cast<float> (cam_pos[0]), static_cast<float> (cam_pos[1]), static_cast<float> (cam_pos[2]));
cam_pos_3f = cam_pos_3f.normalized ();
Eigen::Vector3f test = Eigen::Vector3f::UnitY ();
//If the view up is parallel to ray cam_pos - focalPoint then the transformation
//is singular and no points are rendered...
//make sure it is perpendicular
if (fabs (cam_pos_3f.dot (test)) == 1)
{
//parallel, create
test = cam_pos_3f.cross (Eigen::Vector3f::UnitX ());
}
cam_tmp->SetViewUp (test[0], test[1], test[2]);
for (int k = 0; k < 3; k++)
{
cam_pos[k] = cam_pos[k] * camera_radius;
}
cam_tmp->SetPosition (cam_pos);
cam_tmp->SetFocalPoint (0, 0, 0);
cam_tmp->Modified ();
//rotate model so it looks the same as if we would look from the new position
vtkSmartPointer<vtkMatrix4x4> view_trans_inverted = vtkSmartPointer<vtkMatrix4x4>::New ();
vtkMatrix4x4::Invert (cam->GetViewTransformMatrix (), view_trans_inverted);
vtkSmartPointer<vtkTransform> trans_rot_pose = vtkSmartPointer<vtkTransform>::New ();
trans_rot_pose->Identity ();
trans_rot_pose->Concatenate (view_trans_inverted);
trans_rot_pose->Concatenate (cam_tmp->GetViewTransformMatrix ());
vtkSmartPointer<vtkTransformFilter> trans_rot_pose_filter = vtkSmartPointer<vtkTransformFilter>::New ();
trans_rot_pose_filter->SetTransform (trans_rot_pose);
trans_rot_pose_filter->SetInputConnection (trans_filter_scale->GetOutputPort ());
//translate model so we can place camera at (0,0,0)
vtkSmartPointer<vtkTransform> translation = vtkSmartPointer<vtkTransform>::New ();
translation->Translate (first_cam_pos[0] * -1, first_cam_pos[1] * -1, first_cam_pos[2] * -1);
vtkSmartPointer<vtkTransformFilter> translation_filter = vtkSmartPointer<vtkTransformFilter>::New ();
translation_filter->SetTransform (translation);
translation_filter->SetInputConnection (trans_rot_pose_filter->GetOutputPort ());
//modify camera
cam_tmp->SetPosition (0, 0, 0);
cam_tmp->SetFocalPoint (first_cam_pos[0] * -1, first_cam_pos[1] * -1, first_cam_pos[2] * -1);
cam_tmp->Modified ();
//notice transformations for final pose
vtkSmartPointer<vtkMatrix4x4> matrixRotModel = trans_rot_pose->GetMatrix ();
vtkSmartPointer<vtkMatrix4x4> matrixTranslation = translation->GetMatrix ();
mapper->SetInputConnection (translation_filter->GetOutputPort ());
mapper->Update ();
//render view
vtkSmartPointer<vtkActor> actor_view = vtkSmartPointer<vtkActor>::New ();
actor_view->SetMapper (mapper);
renderer->SetActiveCamera (cam_tmp);
renderer->AddActor (actor_view);
renderer->Modified ();
//renderer->ResetCameraClippingRange ();
render_win->Render ();
//back to real scale transform
vtkSmartPointer<vtkTransform> backToRealScale = vtkSmartPointer<vtkTransform>::New ();
backToRealScale->PostMultiply ();
backToRealScale->Identity ();
backToRealScale->Concatenate (matrixScale);
backToRealScale->Concatenate (matrixTranslation);
backToRealScale->Inverse ();
backToRealScale->Modified ();
backToRealScale->Concatenate (matrixTranslation);
backToRealScale->Modified ();
Eigen::Matrix4f backToRealScale_eigen;
backToRealScale_eigen.setIdentity ();
for (int x = 0; x < 4; x++)
for (int y = 0; y < 4; y++)
backToRealScale_eigen (x, y) = static_cast<float> (backToRealScale->GetMatrix ()->GetElement (x, y));
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
cloud->points.resize (xres * yres);
cloud->width = xres * yres;
cloud->height = 1;
double coords[3];
float * depth = new float[xres * yres];
render_win->GetZbufferData (0, 0, xres - 1, yres - 1, &(depth[0]));
int count_valid_depth_pixels = 0;
size_t xresolution (xres);
size_t yresolution (yres);
for (size_t x = 0; x < xresolution; x++)
{
for (size_t y = 0; y < yresolution; y++)
{
float value = depth[y * xres + x];
if (value == 1.0)
continue;
worldPicker->Pick (static_cast<double> (x), static_cast<double> (y), value, renderer);
worldPicker->GetPickPosition (coords);
cloud->points[count_valid_depth_pixels].x = static_cast<float> (coords[0]);
cloud->points[count_valid_depth_pixels].y = static_cast<float> (coords[1]);
cloud->points[count_valid_depth_pixels].z = static_cast<float> (coords[2]);
cloud->points[count_valid_depth_pixels].getVector4fMap () = backToRealScale_eigen
* cloud->points[count_valid_depth_pixels].getVector4fMap ();
count_valid_depth_pixels++;
}
}
delete[] depth;
//////////////////////////////
// * Compute area of the mesh
//////////////////////////////
vtkSmartPointer<vtkPolyData> polydata = mapper->GetInput ();
polydata->BuildCells ();
vtkSmartPointer<vtkCellArray> cells = polydata->GetPolys ();
vtkIdType npts = 0, *ptIds = NULL;
double p1[3], p2[3], p3[3], area, totalArea = 0;
for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds);)
{
polydata->GetPoint (ptIds[0], p1);
polydata->GetPoint (ptIds[1], p2);
polydata->GetPoint (ptIds[2], p3);
area = vtkTriangle::TriangleArea (p1, p2, p3);
totalArea += area;
}
/////////////////////////////////////
// * Select visible cells (triangles)
/////////////////////////////////////
#if (VTK_MAJOR_VERSION==5 && VTK_MINOR_VERSION<6)
vtkSmartPointer<vtkVisibleCellSelector> selector = vtkSmartPointer<vtkVisibleCellSelector>::New ();
vtkSmartPointer<vtkIdTypeArray> selection = vtkSmartPointer<vtkIdTypeArray>::New ();
selector->SetRenderer (renderer);
selector->SetArea (0, 0, xres - 1, yres - 1);
selector->Select ();
selector->GetSelectedIds (selection);
double visible_area = 0;
for (int sel_id = 3; sel_id < (selection->GetNumberOfTuples () * selection->GetNumberOfComponents ()); sel_id
+= selection->GetNumberOfComponents ())
{
int id_mesh = selection->GetValue (sel_id);
if (id_mesh >= polydata->GetNumberOfCells ())
continue;
vtkCell * cell = polydata->GetCell (id_mesh);
vtkTriangle* triangle = dynamic_cast<vtkTriangle*> (cell);
double p0[3];
double p1[3];
double p2[3];
triangle->GetPoints ()->GetPoint (0, p0);
triangle->GetPoints ()->GetPoint (1, p1);
triangle->GetPoints ()->GetPoint (2, p2);
visible_area += vtkTriangle::TriangleArea (p0, p1, p2);
}
#else
//THIS CAN BE USED WHEN VTK >= 5.4 IS REQUIRED... vtkVisibleCellSelector is deprecated from VTK5.4
vtkSmartPointer<vtkHardwareSelector> hardware_selector = vtkSmartPointer<vtkHardwareSelector>::New ();
hardware_selector->ClearBuffers ();
vtkSmartPointer<vtkSelection> hdw_selection = vtkSmartPointer<vtkSelection>::New ();
hardware_selector->SetRenderer (renderer);
hardware_selector->SetArea (0, 0, xres - 1, yres - 1);
hardware_selector->SetFieldAssociation (vtkDataObject::FIELD_ASSOCIATION_CELLS);
hdw_selection = hardware_selector->Select ();
if (!hdw_selection || !hdw_selection->GetNode (0) || !hdw_selection->GetNode (0)->GetSelectionList ())
{
PCL_WARN ("[renderViewTesselatedSphere] Invalid selection, skipping!\n");
continue;
}
vtkSmartPointer<vtkIdTypeArray> ids;
ids = vtkIdTypeArray::SafeDownCast (hdw_selection->GetNode (0)->GetSelectionList ());
if (!ids)
return;
double visible_area = 0;
for (int sel_id = 0; sel_id < (ids->GetNumberOfTuples ()); sel_id++)
{
int id_mesh = static_cast<int> (ids->GetValue (sel_id));
vtkCell * cell = polydata->GetCell (id_mesh);
vtkTriangle* triangle = dynamic_cast<vtkTriangle*> (cell);
if (!triangle)
{
PCL_WARN ("[renderViewTesselatedSphere] Invalid triangle %d, skipping!\n", id_mesh);
continue;
}
double p0[3];
double p1[3];
double p2[3];
triangle->GetPoints ()->GetPoint (0, p0);
triangle->GetPoints ()->GetPoint (1, p1);
triangle->GetPoints ()->GetPoint (2, p2);
area = vtkTriangle::TriangleArea (p0, p1, p2);
visible_area += area;
}
#endif
enthropies.push_back (static_cast<float> (visible_area / totalArea));
cloud->points.resize (count_valid_depth_pixels);
cloud->width = count_valid_depth_pixels;
//transform cloud to give camera coordinates instead of world coordinates!
vtkSmartPointer<vtkMatrix4x4> view_transform = cam_tmp->GetViewTransformMatrix ();
Eigen::Matrix4f trans_view;
trans_view.setIdentity ();
for (int x = 0; x < 4; x++)
for (int y = 0; y < 4; y++)
trans_view (x, y) = static_cast<float> (view_transform->GetElement (x, y));
//NOTE: vtk view coordinate system is different than the standard camera coordinates (z forward, y down, x right)
//thus, the fliping in y and z
for (size_t i = 0; i < cloud->points.size (); i++)
{
cloud->points[i].getVector4fMap () = trans_view * cloud->points[i].getVector4fMap ();
cloud->points[i].y *= -1.0f;
cloud->points[i].z *= -1.0f;
}
renderer->RemoveActor (actor_view);
clouds.push_back (*cloud);
//create pose, from OBJECT coordinates to CAMERA coordinates!
vtkSmartPointer<vtkTransform> transOCtoCC = vtkSmartPointer<vtkTransform>::New ();
transOCtoCC->PostMultiply ();
transOCtoCC->Identity ();
transOCtoCC->Concatenate (matrixCenter);
transOCtoCC->Concatenate (matrixRotModel);
transOCtoCC->Concatenate (matrixTranslation);
transOCtoCC->Concatenate (cam_tmp->GetViewTransformMatrix ());
//NOTE: vtk view coordinate system is different than the standard camera coordinates (z forward, y down, x right)
//thus, the fliping in y and z
vtkSmartPointer<vtkMatrix4x4> cameraSTD = vtkSmartPointer<vtkMatrix4x4>::New ();
cameraSTD->Identity ();
cameraSTD->SetElement (0, 0, 1);
cameraSTD->SetElement (1, 1, -1);
cameraSTD->SetElement (2, 2, -1);
transOCtoCC->Concatenate (cameraSTD);
transOCtoCC->Modified ();
Eigen::Matrix4f pose_view;
pose_view.setIdentity ();
for (int x = 0; x < 4; x++)
for (int y = 0; y < 4; y++)
pose_view (x, y) = static_cast<float> (transOCtoCC->GetMatrix ()->GetElement (x, y));
poses.push_back (pose_view);
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::renderView (int xres, int yres, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud)
{
if (rens_->GetNumberOfItems () > 1)
{
PCL_WARN ("[renderView] Method will render only the first viewport\n");
return;
}
win_->SetSize (xres, yres);
win_->Render ();
float dwidth = 2.0f / float (xres),
dheight = 2.0f / float (yres);
cloud->points.resize (xres * yres);
cloud->width = xres;
cloud->height = yres;
float *depth = new float[xres * yres];
win_->GetZbufferData (0, 0, xres - 1, yres - 1, &(depth[0]));
// Transform cloud to give camera coordinates instead of world coordinates!
vtkRenderer *ren = rens_->GetFirstRenderer ();
vtkCamera *camera = ren->GetActiveCamera ();
vtkSmartPointer<vtkMatrix4x4> composite_projection_transform = camera->GetCompositeProjectionTransformMatrix (ren->GetTiledAspectRatio (), 0, 1);
vtkSmartPointer<vtkMatrix4x4> view_transform = camera->GetViewTransformMatrix ();
Eigen::Matrix4f mat1, mat2;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
mat1 (i, j) = static_cast<float> (composite_projection_transform->Element[i][j]);
mat2 (i, j) = static_cast<float> (view_transform->Element[i][j]);
}
mat1 = mat1.inverse ().eval ();
int ptr = 0;
for (int y = 0; y < yres; ++y)
{
for (int x = 0; x < xres; ++x, ++ptr)
{
pcl::PointXYZ &pt = (*cloud)[ptr];
if (depth[ptr] == 1.0)
{
pt.x = pt.y = pt.z = std::numeric_limits<float>::quiet_NaN ();
continue;
}
Eigen::Vector4f world_coords (dwidth * float (x) - 1.0f,
dheight * float (y) - 1.0f,
depth[ptr],
1.0f);
world_coords = mat2 * mat1 * world_coords;
float w3 = 1.0f / world_coords[3];
world_coords[0] *= w3;
// vtk view coordinate system is different than the standard camera coordinates (z forward, y down, x right), thus, the fliping in y and z
world_coords[1] *= -w3;
world_coords[2] *= -w3;
pt.x = static_cast<float> (world_coords[0]);
pt.y = static_cast<float> (world_coords[1]);
pt.z = static_cast<float> (world_coords[2]);
}
}
delete[] depth;
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::fromHandlersToScreen (
const GeometryHandlerConstPtr &geometry_handler,
const ColorHandlerConstPtr &color_handler,
const std::string &id,
int viewport,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation)
{
if (!geometry_handler->isCapable ())
{
PCL_WARN ("[fromHandlersToScreen] PointCloud <%s> requested with an invalid geometry handler (%s)!\n", id.c_str (), geometry_handler->getName ().c_str ());
return (false);
}
if (!color_handler->isCapable ())
{
PCL_WARN ("[fromHandlersToScreen] PointCloud <%s> requested with an invalid color handler (%s)!\n", id.c_str (), color_handler->getName ().c_str ());
return (false);
}
vtkSmartPointer<vtkPolyData> polydata;
vtkSmartPointer<vtkIdTypeArray> initcells;
// Convert the PointCloud to VTK PolyData
convertPointCloudToVTKPolyData (geometry_handler, polydata, initcells);
// use the given geometry handler
// Get the colors from the handler
bool has_colors = false;
double minmax[2];
vtkSmartPointer<vtkDataArray> scalars;
if (color_handler->getColor (scalars))
{
polydata->GetPointData ()->SetScalars (scalars);
scalars->GetRange (minmax);
has_colors = true;
}
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (polydata, actor);
if (has_colors)
actor->GetMapper ()->SetScalarRange (minmax);
// Add it to all renderers
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
CloudActor& cloud_actor = (*cloud_actor_map_)[id];
cloud_actor.actor = actor;
cloud_actor.cells = reinterpret_cast<vtkPolyDataMapper*>(actor->GetMapper ())->GetInput ()->GetVerts ()->GetData ();
cloud_actor.geometry_handlers.push_back (geometry_handler);
cloud_actor.color_handlers.push_back (color_handler);
// Save the viewpoint transformation matrix to the global actor map
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (sensor_origin, sensor_orientation, transformation);
cloud_actor.viewpoint_transformation_ = transformation;
cloud_actor.actor->SetUserMatrix (transformation);
cloud_actor.actor->Modified ();
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::updateCells (vtkSmartPointer<vtkIdTypeArray> &cells,
vtkSmartPointer<vtkIdTypeArray> &initcells,
vtkIdType nr_points)
{
// If no init cells and cells has not been initialized...
if (!cells)
cells = vtkSmartPointer<vtkIdTypeArray>::New ();
// If we have less values then we need to recreate the array
if (cells->GetNumberOfTuples () < nr_points)
{
cells = vtkSmartPointer<vtkIdTypeArray>::New ();
// If init cells is given, and there's enough data in it, use it
if (initcells && initcells->GetNumberOfTuples () >= nr_points)
{
cells->DeepCopy (initcells);
cells->SetNumberOfComponents (2);
cells->SetNumberOfTuples (nr_points);
}
else
{
// If the number of tuples is still too small, we need to recreate the array
cells->SetNumberOfComponents (2);
cells->SetNumberOfTuples (nr_points);
vtkIdType *cell = cells->GetPointer (0);
for (vtkIdType i = 0; i < nr_points; ++i, cell += 2)
{
*cell = 1;
*(cell + 1) = i;
}
// Save the results in initcells
initcells = vtkSmartPointer<vtkIdTypeArray>::New ();
initcells->DeepCopy (cells);
}
}
else
{
// The assumption here is that the current set of cells has more data than needed
cells->SetNumberOfComponents (2);
cells->SetNumberOfTuples (nr_points);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::allocVtkPolyData (vtkSmartPointer<vtkAppendPolyData> &polydata)
{
polydata = vtkSmartPointer<vtkAppendPolyData>::New ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::allocVtkPolyData (vtkSmartPointer<vtkPolyData> &polydata)
{
polydata = vtkSmartPointer<vtkPolyData>::New ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::allocVtkUnstructuredGrid (vtkSmartPointer<vtkUnstructuredGrid> &polydata)
{
polydata = vtkSmartPointer<vtkUnstructuredGrid>::New ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::getTransformationMatrix (
const Eigen::Vector4f &origin,
const Eigen::Quaternion<float> &orientation,
Eigen::Matrix4f &transformation)
{
transformation.setIdentity ();
transformation.block<3, 3> (0, 0) = orientation.toRotationMatrix ();
transformation.block<3, 1> (0, 3) = origin.head (3);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertToVtkMatrix (
const Eigen::Vector4f &origin,
const Eigen::Quaternion<float> &orientation,
vtkSmartPointer<vtkMatrix4x4> &vtk_matrix)
{
// set rotation
Eigen::Matrix3f rot = orientation.toRotationMatrix ();
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++)
vtk_matrix->SetElement (i, k, rot (i, k));
// set translation
vtk_matrix->SetElement (0, 3, origin (0));
vtk_matrix->SetElement (1, 3, origin (1));
vtk_matrix->SetElement (2, 3, origin (2));
vtk_matrix->SetElement (3, 3, 1.0f);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertToVtkMatrix (
const Eigen::Matrix4f &m,
vtkSmartPointer<vtkMatrix4x4> &vtk_matrix)
{
for (int i = 0; i < 4; i++)
for (int k = 0; k < 4; k++)
vtk_matrix->SetElement (i, k, m (i, k));
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertToEigenMatrix (
const vtkSmartPointer<vtkMatrix4x4> &vtk_matrix,
Eigen::Matrix4f &m)
{
for (int i = 0; i < 4; i++)
for (int k = 0; k < 4; k++)
m (i, k) = static_cast<float> (vtk_matrix->GetElement (i, k));
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPointCloud (
const pcl::PCLPointCloud2::ConstPtr &,
const GeometryHandlerConstPtr &geometry_handler,
const ColorHandlerConstPtr &color_handler,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation,
const std::string &id, int viewport)
{
// Check to see if this entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
// Here we're just pushing the handlers onto the queue. If needed, something fancier could
// be done such as checking if a specific handler already exists, etc.
am_it->second.geometry_handlers.push_back (geometry_handler);
am_it->second.color_handlers.push_back (color_handler);
return (true);
}
return (fromHandlersToScreen (geometry_handler, color_handler, id, viewport, sensor_origin, sensor_orientation));
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPointCloud (
const pcl::PCLPointCloud2::ConstPtr &cloud,
const GeometryHandlerConstPtr &geometry_handler,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
// Here we're just pushing the handlers onto the queue. If needed, something fancier could
// be done such as checking if a specific handler already exists, etc.
am_it->second.geometry_handlers.push_back (geometry_handler);
return (true);
}
PointCloudColorHandlerCustom<pcl::PCLPointCloud2>::Ptr color_handler (new PointCloudColorHandlerCustom<pcl::PCLPointCloud2> (cloud, 255, 255, 255));
return (fromHandlersToScreen (geometry_handler, color_handler, id, viewport, sensor_origin, sensor_orientation));
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPointCloud (
const pcl::PCLPointCloud2::ConstPtr &cloud,
const ColorHandlerConstPtr &color_handler,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation,
const std::string &id, int viewport)
{
// Check to see if this entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
// Here we're just pushing the handlers onto the queue. If needed, something fancier could
// be done such as checking if a specific handler already exists, etc.
am_it->second.color_handlers.push_back (color_handler);
return (true);
}
PointCloudGeometryHandlerXYZ<pcl::PCLPointCloud2>::Ptr geometry_handler (new PointCloudGeometryHandlerXYZ<pcl::PCLPointCloud2> (cloud));
return (fromHandlersToScreen (geometry_handler, color_handler, id, viewport, sensor_origin, sensor_orientation));
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setFullScreen (bool mode)
{
if (win_)
win_->SetFullScreen (mode);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setWindowName (const std::string &name)
{
if (win_)
win_->SetWindowName (name.c_str ());
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setWindowBorders (bool mode)
{
if (win_)
win_->SetBorders (mode);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setPosition (int x, int y)
{
if (win_)
{
win_->SetPosition (x, y);
win_->Render ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setSize (int xw, int yw)
{
if (win_)
{
win_->SetSize (xw, yw);
win_->Render ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::close ()
{
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
if (interactor_)
{
interactor_->stopped = true;
// This tends to close the window...
interactor_->stopLoop ();
}
#else
stopped_ = true;
// This tends to close the window...
win_->Finalize ();
if (interactor_)
interactor_->TerminateApp ();
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::removeCorrespondences (
const std::string &id, int viewport)
{
removeShape (id, viewport);
}
//////////////////////////////////////////////////////////////////////////////////////////////
int
pcl::visualization::PCLVisualizer::getColorHandlerIndex (const std::string &id)
{
CloudActorMap::iterator am_it = style_->getCloudActorMap ()->find (id);
if (am_it == cloud_actor_map_->end ())
return (-1);
return (am_it->second.color_handler_index_);
}
//////////////////////////////////////////////////////////////////////////////////////////////
int
pcl::visualization::PCLVisualizer::getGeometryHandlerIndex (const std::string &id)
{
CloudActorMap::iterator am_it = style_->getCloudActorMap ()->find (id);
if (am_it != cloud_actor_map_->end ())
return (-1);
return (am_it->second.geometry_handler_index_);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::wasStopped () const
{
if (interactor_ != NULL)
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
return (interactor_->stopped);
#else
return (stopped_);
#endif
else
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::resetStoppedFlag ()
{
if (interactor_ != NULL)
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_->stopped = false;
#else
stopped_ = false;
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setUseVbos (bool use_vbos)
{
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
use_vbos_ = use_vbos;
style_->setUseVbos (use_vbos_);
#else
PCL_WARN ("[PCLVisualizer::setUseVbos] Has no effect when OpenGL version is ≥ 2\n");
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setLookUpTableID (const std::string id)
{
style_->lut_actor_id_ = id;
style_->updateLookUpTableDisplay (false);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::ExitMainLoopTimerCallback::Execute (
vtkObject*, unsigned long event_id, void* call_data)
{
if (event_id != vtkCommand::TimerEvent)
return;
int timer_id = *static_cast<int*> (call_data);
//PCL_WARN ("[pcl::visualization::PCLVisualizer::ExitMainLoopTimerCallback] Timer %d called.\n", timer_id);
if (timer_id != right_timer_id)
return;
// Stop vtk loop and send notification to app to wake it up
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
pcl_visualizer->interactor_->stopLoop ();
#else
pcl_visualizer->interactor_->TerminateApp ();
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::ExitCallback::Execute (
vtkObject*, unsigned long event_id, void*)
{
if (event_id != vtkCommand::ExitEvent)
return;
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
if (pcl_visualizer->interactor_)
{
pcl_visualizer->interactor_->stopped = true;
// This tends to close the window...
pcl_visualizer->interactor_->stopLoop ();
}
#else
pcl_visualizer->stopped_ = true;
// This tends to close the window...
if (pcl_visualizer->interactor_)
pcl_visualizer->interactor_->TerminateApp ();
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::FPSCallback::Execute (
vtkObject* caller, unsigned long, void*)
{
vtkRenderer *ren = reinterpret_cast<vtkRenderer *> (caller);
last_fps = 1.0f / static_cast<float> (ren->GetLastRenderTimeInSeconds ());
char buf[128];
sprintf (buf, "%.1f FPS", last_fps);
actor->SetInput (buf);
}
/////////////////////////////////////////////////////////////////////////////////////////////
int
pcl::visualization::PCLVisualizer::textureFromTexMaterial (const pcl::TexMaterial& tex_mat,
vtkTexture* vtk_tex) const
{
if (tex_mat.tex_file == "")
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] No texture file given for material %s!\n",
tex_mat.tex_name.c_str ());
return (-1);
}
boost::filesystem::path full_path (tex_mat.tex_file.c_str ());
if (!boost::filesystem::exists (full_path))
{
boost::filesystem::path parent_dir = full_path.parent_path ();
std::string upper_filename = tex_mat.tex_file;
boost::to_upper (upper_filename);
std::string real_name = "";
try
{
if (!boost::filesystem::exists (parent_dir))
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Parent directory '%s' doesn't exist!\n",
parent_dir.string ().c_str ());
return (-1);
}
if (!boost::filesystem::is_directory (parent_dir))
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Parent '%s' is not a directory !\n",
parent_dir.string ().c_str ());
return (-1);
}
typedef std::vector<boost::filesystem::path> paths_vector;
paths_vector paths;
std::copy (boost::filesystem::directory_iterator (parent_dir),
boost::filesystem::directory_iterator (),
back_inserter (paths));
for (paths_vector::const_iterator it = paths.begin (); it != paths.end (); ++it)
{
if (boost::filesystem::is_regular_file (*it))
{
std::string name = it->string ();
boost::to_upper (name);
if (name == upper_filename)
{
real_name = it->string ();
break;
}
}
}
// Check texture file existence
if (real_name == "")
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Can not find texture file %s!\n",
tex_mat.tex_file.c_str ());
return (-1);
}
}
catch (const boost::filesystem::filesystem_error& ex)
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Error %s when looking for file %s\n!",
ex.what (), tex_mat.tex_file.c_str ());
return (-1);
}
//Save the real path
full_path = real_name.c_str ();
}
std::string extension = full_path.extension ().string ();
//!!! nizar 20131206 : The list is far from being exhaustive I am afraid.
if ((extension == ".jpg") || (extension == ".JPG"))
{
vtkSmartPointer<vtkJPEGReader> jpeg_reader = vtkSmartPointer<vtkJPEGReader>::New ();
jpeg_reader->SetFileName (full_path.string ().c_str ());
jpeg_reader->Update ();
vtk_tex->SetInputConnection (jpeg_reader->GetOutputPort ());
}
else if ((extension == ".bmp") || (extension == ".BMP"))
{
vtkSmartPointer<vtkBMPReader> bmp_reader = vtkSmartPointer<vtkBMPReader>::New ();
bmp_reader->SetFileName (full_path.string ().c_str ());
bmp_reader->Update ();
vtk_tex->SetInputConnection (bmp_reader->GetOutputPort ());
}
else if ((extension == ".pnm") || (extension == ".PNM"))
{
vtkSmartPointer<vtkPNMReader> pnm_reader = vtkSmartPointer<vtkPNMReader>::New ();
pnm_reader->SetFileName (full_path.string ().c_str ());
pnm_reader->Update ();
vtk_tex->SetInputConnection (pnm_reader->GetOutputPort ());
}
else if ((extension == ".png") || (extension == ".PNG"))
{
vtkSmartPointer<vtkPNGReader> png_reader = vtkSmartPointer<vtkPNGReader>::New ();
png_reader->SetFileName (full_path.string ().c_str ());
png_reader->Update ();
vtk_tex->SetInputConnection (png_reader->GetOutputPort ());
}
else if ((extension == ".tiff") || (extension == ".TIFF"))
{
vtkSmartPointer<vtkTIFFReader> tiff_reader = vtkSmartPointer<vtkTIFFReader>::New ();
tiff_reader->SetFileName (full_path.string ().c_str ());
tiff_reader->Update ();
vtk_tex->SetInputConnection (tiff_reader->GetOutputPort ());
}
else
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Unhandled image %s for material %s!\n",
full_path.c_str (), tex_mat.tex_name.c_str ());
return (-1);
}
return (0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::visualization::PCLVisualizer::getUniqueCameraFile (int argc, char **argv)
{
std::vector<int> p_file_indices;
boost::uuids::detail::sha1 sha1;
unsigned int digest[5];
const char *str;
std::ostringstream sstream;
bool valid = false;
p_file_indices = pcl::console::parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 0)
{
// Calculate sha1 using canonical paths
for (size_t i = 0; i < p_file_indices.size (); ++i)
{
boost::filesystem::path path (argv[p_file_indices[i]]);
if (boost::filesystem::exists (path))
{
#if BOOST_VERSION >= 104800
path = boost::filesystem::canonical (path);
#endif
str = path.string ().c_str ();
sha1.process_bytes (str, std::strlen (str));
valid = true;
}
}
// Build camera filename
if (valid)
{
sha1.get_digest (digest);
sstream << ".";
sstream << std::hex << digest[0] << digest[1] << digest[2] << digest[3] << digest[4];
sstream << ".cam";
}
}
return (sstream.str ());
}
handle VTK legacy function
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/visualization/common/common.h>
#include <pcl/conversions.h>
#include <vtkVersion.h>
#include <vtkTextActor.h>
#include <vtkTextProperty.h>
#include <vtkCellData.h>
#include <vtkWorldPointPicker.h>
#include <vtkPropPicker.h>
#include <vtkPlatonicSolidSource.h>
#include <vtkLoopSubdivisionFilter.h>
#include <vtkTriangle.h>
#include <vtkTransform.h>
#include <vtkPolyDataNormals.h>
#include <vtkMapper.h>
#include <vtkDataSetMapper.h>
#if VTK_MAJOR_VERSION>=6 || (VTK_MAJOR_VERSION==5 && VTK_MINOR_VERSION>4)
#include <vtkHardwareSelector.h>
#include <vtkSelectionNode.h>
#else
#include <vtkVisibleCellSelector.h>
#endif
#include <vtkSelection.h>
#include <vtkPointPicker.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/vtk/vtkRenderWindowInteractorFix.h>
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
#include <pcl/visualization/vtk/vtkVertexBufferObjectMapper.h>
#endif
#include <vtkPolyLine.h>
#include <vtkPolyDataMapper.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRendererCollection.h>
#include <vtkCamera.h>
#include <vtkAppendPolyData.h>
#include <vtkPointData.h>
#include <vtkTransformFilter.h>
#include <vtkProperty.h>
#include <vtkPLYReader.h>
#include <vtkAxes.h>
#include <vtkTubeFilter.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkAxesActor.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkAreaPicker.h>
#include <vtkXYPlotActor.h>
#include <vtkOpenGLRenderWindow.h>
#include <vtkJPEGReader.h>
#include <vtkBMPReader.h>
#include <vtkPNMReader.h>
#include <vtkPNGReader.h>
#include <vtkTIFFReader.h>
#include <vtkLookupTable.h>
#include <vtkTextureUnitManager.h>
#include <pcl/visualization/common/shapes.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/common/common.h>
#include <pcl/common/time.h>
#include <boost/uuid/sha1.hpp>
#include <boost/filesystem.hpp>
#include <pcl/console/parse.h>
// Support for VTK 7.1 upwards
#ifdef vtkGenericDataArray_h
#define SetTupleValue SetTypedTuple
#define InsertNextTupleValue InsertNextTypedTuple
#define GetTupleValue GetTypedTuple
#endif
#if defined(_WIN32)
// Remove macros defined in Windows.h
#undef near
#undef far
#endif
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (const std::string &name, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (vtkSmartPointer<vtkRenderWindow>::New ())
, style_ (vtkSmartPointer<pcl::visualization::PCLVisualizerInteractorStyle>::New ())
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New ();
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setDefaultWindowSizeAndPos ();
setupStyle ();
if (create_interactor)
createInteractor ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (int &argc, char **argv, const std::string &name, PCLVisualizerInteractorStyle* style, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (vtkSmartPointer<vtkRenderWindow>::New ())
, style_ (style)
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New ();
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setupStyle ();
setupCamera (argc, argv);
if(!camera_set_ && !camera_file_loaded_)
setDefaultWindowSizeAndPos ();
if (create_interactor)
createInteractor ();
//window name should be reset due to its reset somewhere in camera initialization
win_->SetWindowName (name.c_str ());
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (vtkSmartPointer<vtkRenderer> ren, vtkSmartPointer<vtkRenderWindow> wind,
const std::string &name, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (wind)
, style_ (vtkSmartPointer<pcl::visualization::PCLVisualizerInteractorStyle>::New ())
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setDefaultWindowSizeAndPos ();
setupStyle ();
if (create_interactor)
createInteractor ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::PCLVisualizer (int &argc, char **argv, vtkSmartPointer<vtkRenderer> ren, vtkSmartPointer<vtkRenderWindow> wind,
const std::string &name, PCLVisualizerInteractorStyle* style, const bool create_interactor)
: interactor_ ()
, update_fps_ (vtkSmartPointer<FPSCallback>::New ())
#if !((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
, stopped_ ()
, timer_id_ ()
#endif
, exit_main_loop_timer_callback_ ()
, exit_callback_ ()
, rens_ (vtkSmartPointer<vtkRendererCollection>::New ())
, win_ (wind)
, style_ (style)
, cloud_actor_map_ (new CloudActorMap)
, shape_actor_map_ (new ShapeActorMap)
, coordinate_actor_map_ (new CoordinateActorMap)
, camera_set_ ()
, camera_file_loaded_ (false)
{
setupRenderer (ren);
setupFPSCallback (ren);
setupRenderWindow (name);
setupStyle ();
setupCamera (argc, argv);
if (!camera_set_ && !camera_file_loaded_)
setDefaultWindowSizeAndPos ();
if (create_interactor)
createInteractor ();
//window name should be reset due to its reset somewhere in camera initialization
win_->SetWindowName (name.c_str ());
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createInteractor ()
{
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_ = vtkSmartPointer<PCLVisualizerInteractor>::New ();
#else
//interactor_ = vtkSmartPointer<vtkRenderWindowInteractor>::New ();
interactor_ = vtkSmartPointer <vtkRenderWindowInteractor>::Take (vtkRenderWindowInteractorFixNew ());
#endif
//win_->PointSmoothingOn ();
//win_->LineSmoothingOn ();
//win_->PolygonSmoothingOn ();
win_->AlphaBitPlanesOff ();
win_->PointSmoothingOff ();
win_->LineSmoothingOff ();
win_->PolygonSmoothingOff ();
win_->SwapBuffersOn ();
win_->SetStereoTypeToAnaglyph ();
interactor_->SetRenderWindow (win_);
interactor_->SetInteractorStyle (style_);
//interactor_->SetStillUpdateRate (30.0);
interactor_->SetDesiredUpdateRate (30.0);
// Initialize and create timer, also create window
interactor_->Initialize ();
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_->timer_id_ = interactor_->CreateRepeatingTimer (5000L);
#else
timer_id_ = interactor_->CreateRepeatingTimer (5000L);
#endif
// Set a simple PointPicker
vtkSmartPointer<vtkPointPicker> pp = vtkSmartPointer<vtkPointPicker>::New ();
pp->SetTolerance (pp->GetTolerance () * 2);
interactor_->SetPicker (pp);
exit_main_loop_timer_callback_ = vtkSmartPointer<ExitMainLoopTimerCallback>::New ();
exit_main_loop_timer_callback_->pcl_visualizer = this;
exit_main_loop_timer_callback_->right_timer_id = -1;
interactor_->AddObserver (vtkCommand::TimerEvent, exit_main_loop_timer_callback_);
exit_callback_ = vtkSmartPointer<ExitCallback>::New ();
exit_callback_->pcl_visualizer = this;
interactor_->AddObserver (vtkCommand::ExitEvent, exit_callback_);
resetStoppedFlag ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setupInteractor (
vtkRenderWindowInteractor *iren,
vtkRenderWindow *win)
{
win->AlphaBitPlanesOff ();
win->PointSmoothingOff ();
win->LineSmoothingOff ();
win->PolygonSmoothingOff ();
win->SwapBuffersOn ();
win->SetStereoTypeToAnaglyph ();
iren->SetRenderWindow (win);
iren->SetInteractorStyle (style_);
//iren->SetStillUpdateRate (30.0);
iren->SetDesiredUpdateRate (30.0);
// Initialize and create timer, also create window
iren->Initialize ();
// Set a simple PointPicker
vtkSmartPointer<vtkPointPicker> pp = vtkSmartPointer<vtkPointPicker>::New ();
pp->SetTolerance (pp->GetTolerance () * 2);
iren->SetPicker (pp);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setupInteractor (
vtkRenderWindowInteractor *iren,
vtkRenderWindow *win,
vtkInteractorStyle *style)
{
win->AlphaBitPlanesOff ();
win->PointSmoothingOff ();
win->LineSmoothingOff ();
win->PolygonSmoothingOff ();
win->SwapBuffersOn ();
win->SetStereoTypeToAnaglyph ();
iren->SetRenderWindow (win);
iren->SetInteractorStyle (style);
//iren->SetStillUpdateRate (30.0);
iren->SetDesiredUpdateRate (30.0);
// Initialize and create timer, also create window
iren->Initialize ();
// Set a simple PointPicker
// vtkSmartPointer<vtkPointPicker> pp = vtkSmartPointer<vtkPointPicker>::New ();
// pp->SetTolerance (pp->GetTolerance () * 2);
// iren->SetPicker (pp);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupRenderer (vtkSmartPointer<vtkRenderer> ren)
{
if (!ren)
PCL_ERROR ("Passed pointer to renderer is null");
ren->AddObserver (vtkCommand::EndEvent, update_fps_);
// Add it to the list of renderers
rens_->AddItem (ren);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupFPSCallback (const vtkSmartPointer<vtkRenderer>& ren)
{
if (!ren)
PCL_ERROR ("Passed pointer to renderer is null");
// FPS callback
vtkSmartPointer<vtkTextActor> txt = vtkSmartPointer<vtkTextActor>::New ();
update_fps_->actor = txt;
update_fps_->pcl_visualizer = this;
update_fps_->decimated = false;
ren->AddActor (txt);
txt->SetInput ("0 FPS");
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupRenderWindow (const std::string& name)
{
if (!win_)
PCL_ERROR ("Pointer to render window is null");
win_->SetWindowName (name.c_str ());
// By default, don't use vertex buffer objects
use_vbos_ = false;
// Add all renderers to the window
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
win_->AddRenderer (renderer);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupStyle ()
{
if (!style_)
PCL_ERROR ("Pointer to style is null");
// Set rend erer window in case no interactor is created
style_->setRenderWindow (win_);
// Create the interactor style
style_->Initialize ();
style_->setRendererCollection (rens_);
style_->setCloudActorMap (cloud_actor_map_);
style_->setShapeActorMap (shape_actor_map_);
style_->UseTimersOn ();
style_->setUseVbos (use_vbos_);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setDefaultWindowSizeAndPos ()
{
if (!win_)
PCL_ERROR ("Pointer to render window is null");
int scr_size_x = win_->GetScreenSize ()[0];
int scr_size_y = win_->GetScreenSize ()[1];
win_->SetSize (scr_size_x / 2, scr_size_y / 2);
win_->SetPosition (0, 0);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void pcl::visualization::PCLVisualizer::setupCamera (int &argc, char **argv)
{
initCameraParameters ();
// Parse the camera settings and update the internal camera
camera_set_ = getCameraParameters (argc, argv);
// Calculate unique camera filename for camera parameter saving/restoring
if (!camera_set_)
{
std::string camera_file = getUniqueCameraFile (argc, argv);
if (!camera_file.empty ())
{
if (boost::filesystem::exists (camera_file) && style_->loadCameraParameters (camera_file))
{
camera_file_loaded_ = true;
}
else
{
style_->setCameraFile (camera_file);
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLVisualizer::~PCLVisualizer ()
{
if (interactor_ != NULL)
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_->DestroyTimer (interactor_->timer_id_);
#else
interactor_->DestroyTimer (timer_id_);
#endif
// Clear the collections
rens_->RemoveAllItems ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::saveScreenshot (const std::string &file)
{
style_->saveScreenshot (file);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::saveCameraParameters (const std::string &file)
{
style_->saveCameraParameters (file);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::getCameraParameters (pcl::visualization::Camera &camera)
{
style_->getCameraParameters (camera);
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerKeyboardCallback (boost::function<void (const pcl::visualization::KeyboardEvent&)> callback)
{
return (style_->registerKeyboardCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerMouseCallback (boost::function<void (const pcl::visualization::MouseEvent&)> callback)
{
return (style_->registerMouseCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerPointPickingCallback (boost::function<void (const pcl::visualization::PointPickingEvent&)> callback)
{
return (style_->registerPointPickingCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerPointPickingCallback (void (*callback) (const pcl::visualization::PointPickingEvent&, void*), void* cookie)
{
return (registerPointPickingCallback (boost::bind (callback, _1, cookie)));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerAreaPickingCallback (boost::function<void (const pcl::visualization::AreaPickingEvent&)> callback)
{
return (style_->registerAreaPickingCallback (callback));
}
/////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::visualization::PCLVisualizer::registerAreaPickingCallback (void (*callback) (const pcl::visualization::AreaPickingEvent&, void*), void* cookie)
{
return (registerAreaPickingCallback (boost::bind (callback, _1, cookie)));
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::spin ()
{
resetStoppedFlag ();
// Render the window before we start the interactor
win_->Render ();
if (interactor_)
interactor_->Start ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::spinOnce (int time, bool force_redraw)
{
resetStoppedFlag ();
#if (defined (__APPLE__)\
&& ( (VTK_MAJOR_VERSION > 6) || ( (VTK_MAJOR_VERSION == 6) && (VTK_MINOR_VERSION >= 1))))
if (!win_->IsDrawable ())
{
close ();
return;
}
#endif
if (!interactor_)
return;
if (time <= 0)
time = 1;
if (force_redraw)
interactor_->Render ();
DO_EVERY (1.0 / interactor_->GetDesiredUpdateRate (),
exit_main_loop_timer_callback_->right_timer_id = interactor_->CreateRepeatingTimer (time);
interactor_->Start ();
interactor_->DestroyTimer (exit_main_loop_timer_callback_->right_timer_id);
);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addOrientationMarkerWidgetAxes (vtkRenderWindowInteractor* interactor)
{
if ( !axes_widget_ )
{
vtkSmartPointer<vtkAxesActor> axes = vtkSmartPointer<vtkAxesActor>::New ();
axes_widget_ = vtkSmartPointer<vtkOrientationMarkerWidget>::New ();
axes_widget_->SetOutlineColor (0.9300, 0.5700, 0.1300);
axes_widget_->SetOrientationMarker (axes);
axes_widget_->SetInteractor (interactor);
axes_widget_->SetViewport (0.0, 0.0, 0.4, 0.4);
axes_widget_->SetEnabled (true);
axes_widget_->InteractiveOn ();
}
else
{
axes_widget_->SetEnabled (true);
pcl::console::print_warn (stderr, "Orientation Widget Axes already exists, just enabling it");
}
}
////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::removeOrientationMarkerWidgetAxes ()
{
if (axes_widget_)
{
if (axes_widget_->GetEnabled ())
axes_widget_->SetEnabled (false);
else
pcl::console::print_warn (stderr, "Orientation Widget Axes was already disabled, doing nothing.");
}
else
{
pcl::console::print_error ("Attempted to delete Orientation Widget Axes which does not exist!\n");
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addCoordinateSystem (double scale, const std::string &id, int viewport)
{
if (scale <= 0.0)
scale = 1.0;
vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New ();
axes->SetOrigin (0, 0, 0);
axes->SetScaleFactor (scale);
axes->Update ();
vtkSmartPointer<vtkFloatArray> axes_colors = vtkSmartPointer<vtkFloatArray>::New ();
axes_colors->Allocate (6);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (1.0);
axes_colors->InsertNextValue (1.0);
vtkSmartPointer<vtkPolyData> axes_data = axes->GetOutput ();
axes_data->GetPointData ()->SetScalars (axes_colors);
vtkSmartPointer<vtkTubeFilter> axes_tubes = vtkSmartPointer<vtkTubeFilter>::New ();
#if VTK_MAJOR_VERSION < 6
axes_tubes->SetInput (axes_data);
#else
axes_tubes->SetInputData (axes_data);
#endif
axes_tubes->SetRadius (axes->GetScaleFactor () / 50.0);
axes_tubes->SetNumberOfSides (6);
vtkSmartPointer<vtkPolyDataMapper> axes_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
axes_mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
axes_mapper->SetInput (axes_tubes->GetOutput ());
#else
axes_mapper->SetInputConnection (axes_tubes->GetOutputPort ());
#endif
vtkSmartPointer<vtkLODActor> axes_actor = vtkSmartPointer<vtkLODActor>::New ();
axes_actor->SetMapper (axes_mapper);
// Save the ID and actor pair to the global actor map
(*coordinate_actor_map_) [id] = axes_actor;
addActorToRenderer (axes_actor, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addCoordinateSystem (double scale, float x, float y, float z, const std::string& id, int viewport)
{
if (scale <= 0.0)
scale = 1.0;
vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New ();
axes->SetOrigin (0, 0, 0);
axes->SetScaleFactor (scale);
axes->Update ();
vtkSmartPointer<vtkFloatArray> axes_colors = vtkSmartPointer<vtkFloatArray>::New ();
axes_colors->Allocate (6);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (1.0);
axes_colors->InsertNextValue (1.0);
vtkSmartPointer<vtkPolyData> axes_data = axes->GetOutput ();
axes_data->GetPointData ()->SetScalars (axes_colors);
vtkSmartPointer<vtkTubeFilter> axes_tubes = vtkSmartPointer<vtkTubeFilter>::New ();
#if VTK_MAJOR_VERSION < 6
axes_tubes->SetInput (axes_data);
#else
axes_tubes->SetInputData (axes_data);
#endif
axes_tubes->SetRadius (axes->GetScaleFactor () / 50.0);
axes_tubes->SetNumberOfSides (6);
vtkSmartPointer<vtkPolyDataMapper> axes_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
axes_mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
axes_mapper->SetInput (axes_tubes->GetOutput ());
#else
axes_mapper->SetInputConnection (axes_tubes->GetOutputPort ());
#endif
vtkSmartPointer<vtkLODActor> axes_actor = vtkSmartPointer<vtkLODActor>::New ();
axes_actor->SetMapper (axes_mapper);
axes_actor->SetPosition (x, y, z);
// Save the ID and actor pair to the global actor map
(*coordinate_actor_map_) [id] = axes_actor;
addActorToRenderer (axes_actor, viewport);
}
int
feq (double a, double b) {
return fabs (a - b) < 1e-9;
}
void
quat_to_angle_axis (const Eigen::Quaternionf &qx, double &theta, double axis[3])
{
double q[4];
q[0] = qx.w();
q[1] = qx.x();
q[2] = qx.y();
q[3] = qx.z();
double halftheta = acos (q[0]);
theta = halftheta * 2;
double sinhalftheta = sin (halftheta);
if (feq (halftheta, 0)) {
axis[0] = 0;
axis[1] = 0;
axis[2] = 1;
theta = 0;
} else {
axis[0] = q[1] / sinhalftheta;
axis[1] = q[2] / sinhalftheta;
axis[2] = q[3] / sinhalftheta;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addCoordinateSystem (double scale, const Eigen::Affine3f& t, const std::string& id, int viewport)
{
if (scale <= 0.0)
scale = 1.0;
vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New ();
axes->SetOrigin (0, 0, 0);
axes->SetScaleFactor (scale);
axes->Update ();
vtkSmartPointer<vtkFloatArray> axes_colors = vtkSmartPointer<vtkFloatArray>::New ();
axes_colors->Allocate (6);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.0);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (0.5);
axes_colors->InsertNextValue (1.0);
axes_colors->InsertNextValue (1.0);
vtkSmartPointer<vtkPolyData> axes_data = axes->GetOutput ();
axes_data->GetPointData ()->SetScalars (axes_colors);
vtkSmartPointer<vtkTubeFilter> axes_tubes = vtkSmartPointer<vtkTubeFilter>::New ();
#if VTK_MAJOR_VERSION < 6
axes_tubes->SetInput (axes_data);
#else
axes_tubes->SetInputData (axes_data);
#endif
axes_tubes->SetRadius (axes->GetScaleFactor () / 50.0);
axes_tubes->SetNumberOfSides (6);
vtkSmartPointer<vtkPolyDataMapper> axes_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
axes_mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
axes_mapper->SetInput (axes_tubes->GetOutput ());
#else
axes_mapper->SetInputConnection (axes_tubes->GetOutputPort ());
#endif
vtkSmartPointer<vtkLODActor> axes_actor = vtkSmartPointer<vtkLODActor>::New ();
axes_actor->SetMapper (axes_mapper);
axes_actor->SetPosition (t (0, 3), t(1, 3), t(2, 3));
Eigen::Matrix3f m;
m =t.rotation();
Eigen::Quaternionf rf;
rf = Eigen::Quaternionf(m);
double r_angle;
double r_axis[3];
quat_to_angle_axis(rf,r_angle,r_axis);
//
axes_actor->SetOrientation(0,0,0);
axes_actor->RotateWXYZ(r_angle*180/M_PI,r_axis[0],r_axis[1],r_axis[2]);
//WAS: axes_actor->SetOrientation (roll, pitch, yaw);
// Save the ID and actor pair to the global actor map
(*coordinate_actor_map_) [id] = axes_actor;
addActorToRenderer (axes_actor, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeCoordinateSystem (const std::string& id, int viewport)
{
// Check to see if the given ID entry exists
CoordinateActorMap::iterator am_it = coordinate_actor_map_->find (id);
if (am_it == coordinate_actor_map_->end ())
return (false);
// Remove it from all renderers
if (removeActorFromRenderer (am_it->second, viewport))
{
// Remove the ID pair to the global actor map
coordinate_actor_map_->erase (am_it);
return (true);
}
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removePointCloud (const std::string &id, int viewport)
{
// Check to see if the given ID entry exists
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Remove it from all renderers
if (removeActorFromRenderer (am_it->second.actor, viewport))
{
// Remove the pointer/ID pair to the global actor map
cloud_actor_map_->erase (am_it);
return (true);
}
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeShape (const std::string &id, int viewport)
{
// Check to see if the given ID entry exists
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
// Extra step: check if there is a cloud with the same ID
CloudActorMap::iterator ca_it = cloud_actor_map_->find (id);
bool shape = true;
// Try to find a shape first
if (am_it == shape_actor_map_->end ())
{
// There is no cloud or shape with this ID, so just exit
if (ca_it == cloud_actor_map_->end ())
return (false);
// Cloud found, set shape to false
shape = false;
}
// Remove the pointer/ID pair to the global actor map
if (shape)
{
if (removeActorFromRenderer (am_it->second, viewport))
{
bool update_LUT (true);
if (!style_->lut_actor_id_.empty() && am_it->first != style_->lut_actor_id_)
update_LUT = false;
shape_actor_map_->erase (am_it);
if (update_LUT)
style_->updateLookUpTableDisplay (false);
return (true);
}
}
else
{
if (removeActorFromRenderer (ca_it->second.actor, viewport))
{
bool update_LUT (true);
if (!style_->lut_actor_id_.empty() && ca_it->first != style_->lut_actor_id_)
update_LUT = false;
cloud_actor_map_->erase (ca_it);
if (update_LUT)
style_->updateLookUpTableDisplay (false);
return (true);
}
}
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeText3D (const std::string &id, int viewport)
{
if (viewport < 0)
return false;
bool success = true;
// If there is no custom viewport and the viewport number is not 0, exit
if (rens_->GetNumberOfItems () <= viewport)
{
PCL_ERROR ("[removeText3D] The viewport [%d] doesn't exist (id <%s>)! ",
viewport,
id.c_str ());
return false;
}
// check all or an individual viewport for a similar id
rens_->InitTraversal ();
for (size_t i = viewport; rens_->GetNextItem () != NULL; ++i)
{
const std::string uid = id + std::string (i, '*');
ShapeActorMap::iterator am_it = shape_actor_map_->find (uid);
// was it found
if (am_it == shape_actor_map_->end ())
{
if (viewport > 0)
return (false);
continue;
}
// Remove it from all renderers
if (removeActorFromRenderer (am_it->second, i))
{
// Remove the pointer/ID pair to the global actor map
shape_actor_map_->erase (am_it);
if (viewport > 0)
return (true);
success &= true;
}
else
success = false;
}
return success;
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeAllPointClouds (int viewport)
{
// Check to see if the given ID entry exists
CloudActorMap::iterator am_it = cloud_actor_map_->begin ();
while (am_it != cloud_actor_map_->end () )
{
if (removePointCloud (am_it->first, viewport))
am_it = cloud_actor_map_->begin ();
else
++am_it;
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeAllShapes (int viewport)
{
bool display_lut (style_->lut_enabled_);
style_->lut_enabled_ = false; // Temporally disable LUT to fasten shape removal
// Check to see if the given ID entry exists
ShapeActorMap::iterator am_it = shape_actor_map_->begin ();
while (am_it != shape_actor_map_->end ())
{
if (removeShape (am_it->first, viewport))
am_it = shape_actor_map_->begin ();
else
++am_it;
}
if (display_lut)
{
style_->lut_enabled_ = true;
style_->updateLookUpTableDisplay (true);
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeAllCoordinateSystems (int viewport)
{
// Check to see if the given ID entry exists
CoordinateActorMap::iterator am_it = coordinate_actor_map_->begin ();
while (am_it != coordinate_actor_map_->end () )
{
if (removeCoordinateSystem (am_it->first, viewport))
am_it = coordinate_actor_map_->begin ();
else
++am_it;
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeActorFromRenderer (const vtkSmartPointer<vtkLODActor> &actor, int viewport)
{
vtkLODActor* actor_to_remove = vtkLODActor::SafeDownCast (actor);
// Add it to all renderers
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we remove the actor from all renderers?
if (viewport == 0)
{
renderer->RemoveActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
// Iterate over all actors in this renderer
vtkPropCollection* actors = renderer->GetViewProps ();
actors->InitTraversal ();
vtkProp* current_actor = NULL;
while ((current_actor = actors->GetNextProp ()) != NULL)
{
if (current_actor != actor_to_remove)
continue;
renderer->RemoveActor (actor);
// Found the correct viewport and removed the actor
return (true);
}
}
++i;
}
if (viewport == 0) return (true);
return (false);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeActorFromRenderer (const vtkSmartPointer<vtkActor> &actor, int viewport)
{
vtkActor* actor_to_remove = vtkActor::SafeDownCast (actor);
// Add it to all renderers
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we remove the actor from all renderers?
if (viewport == 0)
{
renderer->RemoveActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
// Iterate over all actors in this renderer
vtkPropCollection* actors = renderer->GetViewProps ();
actors->InitTraversal ();
vtkProp* current_actor = NULL;
while ((current_actor = actors->GetNextProp ()) != NULL)
{
if (current_actor != actor_to_remove)
continue;
renderer->RemoveActor (actor);
// Found the correct viewport and removed the actor
return (true);
}
}
++i;
}
if (viewport == 0) return (true);
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::addActorToRenderer (const vtkSmartPointer<vtkProp> &actor, int viewport)
{
// Add it to all renderers
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we add the actor to all renderers?
if (viewport == 0)
{
renderer->AddActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
renderer->AddActor (actor);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::removeActorFromRenderer (const vtkSmartPointer<vtkProp> &actor, int viewport)
{
vtkProp* actor_to_remove = vtkProp::SafeDownCast (actor);
// Initialize traversal
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we remove the actor from all renderers?
if (viewport == 0)
{
renderer->RemoveActor (actor);
}
else if (viewport == i) // add the actor only to the specified viewport
{
// Iterate over all actors in this renderer
vtkPropCollection* actors = renderer->GetViewProps ();
actors->InitTraversal ();
vtkProp* current_actor = NULL;
while ((current_actor = actors->GetNextProp ()) != NULL)
{
if (current_actor != actor_to_remove)
continue;
renderer->RemoveActor (actor);
// Found the correct viewport and removed the actor
return (true);
}
}
++i;
}
if (viewport == 0) return (true);
return (false);
}
/////////////////////////////////////////////////////////////////////////////////////////////
namespace
{
// Helper function called by createActorFromVTKDataSet () methods.
// This function determines the default setting of vtkMapper::InterpolateScalarsBeforeMapping.
// Return 0, interpolation off, if data is a vtkPolyData that contains only vertices.
// Return 1, interpolation on, for anything else.
int
getDefaultScalarInterpolationForDataSet (vtkDataSet* data)
{
vtkPolyData* polyData = vtkPolyData::SafeDownCast (data); // Check that polyData != NULL in case of segfault
return (polyData && polyData->GetNumberOfCells () != polyData->GetNumberOfVerts ());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createActorFromVTKDataSet (const vtkSmartPointer<vtkDataSet> &data,
vtkSmartPointer<vtkLODActor> &actor,
bool use_scalars)
{
// If actor is not initialized, initialize it here
if (!actor)
actor = vtkSmartPointer<vtkLODActor>::New ();
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
if (use_vbos_)
{
vtkSmartPointer<vtkVertexBufferObjectMapper> mapper = vtkSmartPointer<vtkVertexBufferObjectMapper>::New ();
mapper->SetInput (data);
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
else
#endif
{
vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (data);
#else
mapper->SetInputData (data);
#endif
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
mapper->ImmediateModeRenderingOff ();
#endif
actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createActorFromVTKDataSet (const vtkSmartPointer<vtkDataSet> &data,
vtkSmartPointer<vtkActor> &actor,
bool use_scalars)
{
// If actor is not initialized, initialize it here
if (!actor)
actor = vtkSmartPointer<vtkActor>::New ();
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
if (use_vbos_)
{
vtkSmartPointer<vtkVertexBufferObjectMapper> mapper = vtkSmartPointer<vtkVertexBufferObjectMapper>::New ();
mapper->SetInput (data);
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
//actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
else
#endif
{
vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (data);
#else
mapper->SetInputData (data);
#endif
if (use_scalars)
{
vtkSmartPointer<vtkDataArray> scalars = data->GetPointData ()->GetScalars ();
double minmax[2];
if (scalars)
{
scalars->GetRange (minmax);
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInterpolateScalarsBeforeMapping (getDefaultScalarInterpolationForDataSet (data));
mapper->ScalarVisibilityOn ();
}
}
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
mapper->ImmediateModeRenderingOff ();
#endif
//actor->SetNumberOfCloudPoints (int (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10)));
actor->GetProperty ()->SetInterpolationToFlat ();
/// FIXME disabling backface culling due to known VTK bug: vtkTextActors are not
/// shown when there is a vtkActor with backface culling on present in the scene
/// Please see VTK bug tracker for more details: http://www.vtk.org/Bug/view.php?id=12588
// actor->GetProperty ()->BackfaceCullingOn ();
actor->SetMapper (mapper);
}
//actor->SetNumberOfCloudPoints (std::max<vtkIdType> (1, data->GetNumberOfPoints () / 10));
actor->GetProperty ()->SetInterpolationToFlat ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertPointCloudToVTKPolyData (
const GeometryHandlerConstPtr &geometry_handler,
vtkSmartPointer<vtkPolyData> &polydata,
vtkSmartPointer<vtkIdTypeArray> &initcells)
{
vtkSmartPointer<vtkCellArray> vertices;
if (!polydata)
{
allocVtkPolyData (polydata);
vertices = vtkSmartPointer<vtkCellArray>::New ();
polydata->SetVerts (vertices);
}
// Use the handler to obtain the geometry
vtkSmartPointer<vtkPoints> points;
geometry_handler->getGeometry (points);
polydata->SetPoints (points);
vtkIdType nr_points = points->GetNumberOfPoints ();
// Create the supporting structures
vertices = polydata->GetVerts ();
if (!vertices)
vertices = vtkSmartPointer<vtkCellArray>::New ();
vtkSmartPointer<vtkIdTypeArray> cells = vertices->GetData ();
updateCells (cells, initcells, nr_points);
// Set the cells and the vertices
vertices->SetCells (nr_points, cells);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setBackgroundColor (
const double &r, const double &g, const double &b, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Should we add the actor to all renderers?
if (viewport == 0)
{
renderer->SetBackground (r, g, b);
}
else if (viewport == i) // add the actor only to the specified viewport
{
renderer->SetBackground (r, g, b);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudRenderingProperties (
int property, double val1, double val2, double val3, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_COLOR:
{
if (val1 > 1.0 || val2 > 1.0 || val3 > 1.0)
PCL_WARN ("[setPointCloudRenderingProperties] Colors go from 0.0 to 1.0!\n");
actor->GetProperty ()->SetColor (val1, val2, val3);
actor->GetMapper ()->ScalarVisibilityOff ();
actor->Modified ();
break;
}
default:
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudRenderingProperties (
int property, double val1, double val2, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Check that range values are correct
if (val1 >= val2)
{
PCL_WARN ("[setPointCloudRenderingProperties] Range max must be greater than range min!\n");
return (false);
}
// Update LUT
actor->GetMapper ()->GetLookupTable ()->SetRange (val1, val2);
actor->GetMapper()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
default:
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::getPointCloudRenderingProperties (int property, double &value, const std::string &id)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_POINT_SIZE:
{
value = actor->GetProperty ()->GetPointSize ();
actor->Modified ();
break;
}
case PCL_VISUALIZER_OPACITY:
{
value = actor->GetProperty ()->GetOpacity ();
actor->Modified ();
break;
}
case PCL_VISUALIZER_LINE_WIDTH:
{
value = actor->GetProperty ()->GetLineWidth ();
actor->Modified ();
break;
}
default:
{
pcl::console::print_error ("[getPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::getPointCloudRenderingProperties (RenderingProperties property,
double &val1,
double &val2,
double &val3,
const std::string &id)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_COLOR:
{
double rgb[3];
actor->GetProperty ()->GetColor (rgb);
val1 = rgb[0];
val2 = rgb[1];
val3 = rgb[2];
break;
}
default:
{
pcl::console::print_error ("[getPointCloudRenderingProperties] "
"Property (%d) is either unknown or it requires a different "
"number of variables to retrieve its contents.\n",
property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudRenderingProperties (
int property, double value, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_POINT_SIZE:
{
actor->GetProperty ()->SetPointSize (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_OPACITY:
{
actor->GetProperty ()->SetOpacity (value);
actor->Modified ();
break;
}
// Turn on/off flag to control whether data is rendered using immediate
// mode or note. Immediate mode rendering tends to be slower but it can
// handle larger datasets. The default value is immediate mode off. If you
// are having problems rendering a large dataset you might want to consider
// using immediate more rendering.
case PCL_VISUALIZER_IMMEDIATE_RENDERING:
{
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
actor->GetMapper ()->SetImmediateModeRendering (int (value));
#endif
actor->Modified ();
break;
}
case PCL_VISUALIZER_LINE_WIDTH:
{
actor->GetProperty ()->SetLineWidth (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_LUT:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Get range limits from existing LUT
double *range;
range = actor->GetMapper ()->GetLookupTable ()->GetRange ();
actor->GetMapper ()->ScalarVisibilityOn ();
actor->GetMapper ()->SetScalarRange (range[0], range[1]);
vtkSmartPointer<vtkLookupTable> table;
if (!pcl::visualization::getColormapLUT (static_cast<LookUpTableRepresentationProperties>(static_cast<int>(value)), table))
break;
table->SetRange (range[0], range[1]);
actor->GetMapper ()->SetLookupTable (table);
style_->updateLookUpTableDisplay (false);
break;
}
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
switch (int(value))
{
case PCL_VISUALIZER_LUT_RANGE_AUTO:
double range[2];
actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->GetRange (range);
actor->GetMapper ()->GetLookupTable ()->SetRange (range[0], range[1]);
actor->GetMapper ()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
break;
}
default:
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setPointCloudSelected (const bool selected, const std::string &id)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_error ("[setPointCloudRenderingProperties] Could not find any PointCloud datasets with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkLODActor* actor = vtkLODActor::SafeDownCast (am_it->second.actor);
if (!actor)
return (false);
if (selected)
{
actor->GetProperty ()->EdgeVisibilityOn ();
actor->GetProperty ()->SetEdgeColor (1.0, 0.0, 0.0);
actor->Modified ();
}
else
{
actor->GetProperty ()->EdgeVisibilityOff ();
actor->Modified ();
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setShapeRenderingProperties (
int property, double val1, double val2, double val3, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it == shape_actor_map_->end ())
{
pcl::console::print_error ("[setShapeRenderingProperties] Could not find any shape with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkActor* actor = vtkActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_COLOR:
{
if (val1 > 1.0 || val2 > 1.0 || val3 > 1.0)
PCL_WARN ("[setShapeRenderingProperties] Colors go from 0.0 to 1.0!\n");
actor->GetMapper ()->ScalarVisibilityOff ();
actor->GetProperty ()->SetColor (val1, val2, val3);
actor->GetProperty ()->SetEdgeColor (val1, val2, val3);
// The following 3 are set by SetColor automatically according to the VTK docs
//actor->GetProperty ()->SetAmbientColor (val1, val2, val3);
//actor->GetProperty ()->SetDiffuseColor (val1, val2, val3);
//actor->GetProperty ()->SetSpecularColor (val1, val2, val3);
actor->GetProperty ()->SetAmbient (0.8);
actor->GetProperty ()->SetDiffuse (0.8);
actor->GetProperty ()->SetSpecular (0.8);
actor->Modified ();
break;
}
default:
{
pcl::console::print_error ("[setShapeRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setShapeRenderingProperties (
int property, double val1, double val2, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it == shape_actor_map_->end ())
{
pcl::console::print_error ("[setShapeRenderingProperties] Could not find any shape with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkActor* actor = vtkActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Check that range values are correct
if (val1 >= val2)
{
PCL_WARN ("[setShapeRenderingProperties] Range max must be greater than range min!\n");
return (false);
}
// Update LUT
actor->GetMapper ()->GetLookupTable ()->SetRange (val1, val2);
actor->GetMapper()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
default:
{
pcl::console::print_error ("[setShapeRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::setShapeRenderingProperties (
int property, double value, const std::string &id, int)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it == shape_actor_map_->end ())
{
pcl::console::print_error ("[setShapeRenderingProperties] Could not find any shape with id <%s>!\n", id.c_str ());
return (false);
}
// Get the actor pointer
vtkActor* actor = vtkActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
switch (property)
{
case PCL_VISUALIZER_POINT_SIZE:
{
actor->GetProperty ()->SetPointSize (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_OPACITY:
{
actor->GetProperty ()->SetOpacity (value);
actor->Modified ();
break;
}
case PCL_VISUALIZER_LINE_WIDTH:
{
actor->GetProperty ()->SetLineWidth (float (value));
actor->Modified ();
break;
}
case PCL_VISUALIZER_FONT_SIZE:
{
vtkTextActor* text_actor = vtkTextActor::SafeDownCast (am_it->second);
if (!text_actor)
return (false);
vtkSmartPointer<vtkTextProperty> tprop = text_actor->GetTextProperty ();
tprop->SetFontSize (int (value));
text_actor->Modified ();
break;
}
case PCL_VISUALIZER_REPRESENTATION:
{
switch (int (value))
{
case PCL_VISUALIZER_REPRESENTATION_POINTS:
{
actor->GetProperty ()->SetRepresentationToPoints ();
break;
}
case PCL_VISUALIZER_REPRESENTATION_WIREFRAME:
{
actor->GetProperty ()->SetRepresentationToWireframe ();
break;
}
case PCL_VISUALIZER_REPRESENTATION_SURFACE:
{
actor->GetProperty ()->SetRepresentationToSurface ();
break;
}
}
actor->Modified ();
break;
}
case PCL_VISUALIZER_SHADING:
{
switch (int (value))
{
case PCL_VISUALIZER_SHADING_FLAT:
{
actor->GetProperty ()->SetInterpolationToFlat ();
break;
}
case PCL_VISUALIZER_SHADING_GOURAUD:
{
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetNormals ())
{
PCL_INFO ("[pcl::visualization::PCLVisualizer::setShapeRenderingProperties] Normals do not exist in the dataset, but Gouraud shading was requested. Estimating normals...\n");
vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New ();
#if VTK_MAJOR_VERSION < 6
normals->SetInput (actor->GetMapper ()->GetInput ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInput (normals->GetOutput ());
#else
normals->SetInputConnection (actor->GetMapper ()->GetInputAlgorithm ()->GetOutputPort ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInputConnection (normals->GetOutputPort ());
#endif
}
actor->GetProperty ()->SetInterpolationToGouraud ();
break;
}
case PCL_VISUALIZER_SHADING_PHONG:
{
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetNormals ())
{
PCL_INFO ("[pcl::visualization::PCLVisualizer::setShapeRenderingProperties] Normals do not exist in the dataset, but Phong shading was requested. Estimating normals...\n");
vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New ();
#if VTK_MAJOR_VERSION < 6
normals->SetInput (actor->GetMapper ()->GetInput ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInput (normals->GetOutput ());
#else
normals->SetInputConnection (actor->GetMapper ()->GetInputAlgorithm ()->GetOutputPort ());
vtkDataSetMapper::SafeDownCast (actor->GetMapper ())->SetInputConnection (normals->GetOutputPort ());
#endif
}
actor->GetProperty ()->SetInterpolationToPhong ();
break;
}
}
actor->Modified ();
break;
}
case PCL_VISUALIZER_LUT:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
// Get range limits from existing LUT
double *range;
range = actor->GetMapper ()->GetLookupTable ()->GetRange ();
actor->GetMapper ()->ScalarVisibilityOn ();
actor->GetMapper ()->SetScalarRange (range[0], range[1]);
vtkSmartPointer<vtkLookupTable> table;
if (!pcl::visualization::getColormapLUT (static_cast<LookUpTableRepresentationProperties>(static_cast<int>(value)), table))
break;
table->SetRange (range[0], range[1]);
actor->GetMapper ()->SetLookupTable (table);
style_->updateLookUpTableDisplay (false);
}
case PCL_VISUALIZER_LUT_RANGE:
{
// Check if the mapper has scalars
if (!actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ())
break;
// Check that scalars are not unisgned char (i.e. check if a LUT is used to colormap scalars assuming vtk ColorMode is Default)
if (actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->IsA ("vtkUnsignedCharArray"))
break;
switch (int(value))
{
case PCL_VISUALIZER_LUT_RANGE_AUTO:
double range[2];
actor->GetMapper ()->GetInput ()->GetPointData ()->GetScalars ()->GetRange (range);
actor->GetMapper ()->GetLookupTable ()->SetRange (range[0], range[1]);
actor->GetMapper ()->UseLookupTableScalarRangeOn ();
style_->updateLookUpTableDisplay (false);
break;
}
break;
}
default:
{
pcl::console::print_error ("[setShapeRenderingProperties] Unknown property (%d) specified!\n", property);
return (false);
}
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::initCameraParameters ()
{
Camera camera_temp;
// Set default camera parameters to something meaningful
camera_temp.clip[0] = 0.01;
camera_temp.clip[1] = 1000.01;
// Look straight along the z-axis
camera_temp.focal[0] = 0.;
camera_temp.focal[1] = 0.;
camera_temp.focal[2] = 1.;
// Position the camera at the origin
camera_temp.pos[0] = 0.;
camera_temp.pos[1] = 0.;
camera_temp.pos[2] = 0.;
// Set the up-vector of the camera to be the y-axis
camera_temp.view[0] = 0.;
camera_temp.view[1] = 1.;
camera_temp.view[2] = 0.;
// Set the camera field of view to about
camera_temp.fovy = 0.8575;
int scr_size_x = win_->GetScreenSize ()[0];
int scr_size_y = win_->GetScreenSize ()[1];
camera_temp.window_size[0] = scr_size_x / 2;
camera_temp.window_size[1] = scr_size_y / 2;
setCameraParameters (camera_temp);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::cameraParamsSet () const
{
return (camera_set_);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::cameraFileLoaded () const
{
return (camera_file_loaded_);
}
/////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::visualization::PCLVisualizer::getCameraFile () const
{
return (style_->getCameraFile ());
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::updateCamera ()
{
PCL_WARN ("[pcl::visualization::PCLVisualizer::updateCamera()] This method was deprecated, just re-rendering all scenes now.");
rens_->InitTraversal ();
// Update the camera parameters
win_->Render ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateShapePose (const std::string &id, const Eigen::Affine3f& pose)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
vtkLODActor* actor;
if (am_it == shape_actor_map_->end ())
return (false);
else
actor = vtkLODActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (pose.matrix (), matrix);
actor->SetUserMatrix (matrix);
actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateCoordinateSystemPose (const std::string &id, const Eigen::Affine3f& pose)
{
ShapeActorMap::iterator am_it = coordinate_actor_map_->find (id);
vtkLODActor* actor;
if (am_it == coordinate_actor_map_->end ())
return (false);
else
actor = vtkLODActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (pose.matrix (), matrix);
actor->SetUserMatrix (matrix);
actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updatePointCloudPose (const std::string &id, const Eigen::Affine3f& pose)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (pose.matrix (), transformation);
am_it->second.viewpoint_transformation_ = transformation;
am_it->second.actor->SetUserMatrix (transformation);
am_it->second.actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::getCameras (std::vector<pcl::visualization::Camera>& cameras)
{
cameras.clear ();
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
cameras.push_back (Camera ());
cameras.back ().pos[0] = renderer->GetActiveCamera ()->GetPosition ()[0];
cameras.back ().pos[1] = renderer->GetActiveCamera ()->GetPosition ()[1];
cameras.back ().pos[2] = renderer->GetActiveCamera ()->GetPosition ()[2];
cameras.back ().focal[0] = renderer->GetActiveCamera ()->GetFocalPoint ()[0];
cameras.back ().focal[1] = renderer->GetActiveCamera ()->GetFocalPoint ()[1];
cameras.back ().focal[2] = renderer->GetActiveCamera ()->GetFocalPoint ()[2];
cameras.back ().clip[0] = renderer->GetActiveCamera ()->GetClippingRange ()[0];
cameras.back ().clip[1] = renderer->GetActiveCamera ()->GetClippingRange ()[1];
cameras.back ().view[0] = renderer->GetActiveCamera ()->GetViewUp ()[0];
cameras.back ().view[1] = renderer->GetActiveCamera ()->GetViewUp ()[1];
cameras.back ().view[2] = renderer->GetActiveCamera ()->GetViewUp ()[2];
cameras.back ().fovy = renderer->GetActiveCamera ()->GetViewAngle () / 180.0 * M_PI;
cameras.back ().window_size[0] = renderer->GetRenderWindow ()->GetSize ()[0];
cameras.back ().window_size[1] = renderer->GetRenderWindow ()->GetSize ()[1];
cameras.back ().window_pos[0] = 0;
cameras.back ().window_pos[1] = 0;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
Eigen::Affine3f
pcl::visualization::PCLVisualizer::getViewerPose (int viewport)
{
Eigen::Affine3f ret (Eigen::Affine3f::Identity ());
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
if (viewport == 0)
viewport = 1;
int viewport_i = 1;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
if (viewport_i == viewport)
{
vtkCamera& camera = *renderer->GetActiveCamera ();
Eigen::Vector3d pos, x_axis, y_axis, z_axis;
camera.GetPosition (pos[0], pos[1], pos[2]);
camera.GetViewUp (y_axis[0], y_axis[1], y_axis[2]);
camera.GetFocalPoint (z_axis[0], z_axis[1], z_axis[2]);
z_axis = (z_axis - pos).normalized ();
x_axis = y_axis.cross (z_axis).normalized ();
ret.translation () = pos.cast<float> ();
ret.linear ().col (0) << x_axis.cast<float> ();
ret.linear ().col (1) << y_axis.cast<float> ();
ret.linear ().col (2) << z_axis.cast<float> ();
return ret;
}
viewport_i ++;
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::resetCamera ()
{
// Update the camera parameters
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
renderer->ResetCamera ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraPosition (
double pos_x, double pos_y, double pos_z,
double view_x, double view_y, double view_z,
double up_x, double up_y, double up_z,
int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetPosition (pos_x, pos_y, pos_z);
cam->SetFocalPoint (view_x, view_y, view_z);
cam->SetViewUp (up_x, up_y, up_z);
renderer->ResetCameraClippingRange ();
}
++i;
}
win_->Render ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraPosition (
double pos_x, double pos_y, double pos_z,
double up_x, double up_y, double up_z, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetPosition (pos_x, pos_y, pos_z);
cam->SetViewUp (up_x, up_y, up_z);
}
++i;
}
win_->Render ();
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraParameters (const Eigen::Matrix3f &intrinsics,
const Eigen::Matrix4f &extrinsics,
int viewport)
{
style_->setCameraParameters (intrinsics, extrinsics, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraParameters (const pcl::visualization::Camera &camera, int viewport)
{
style_->setCameraParameters (camera, viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraClipDistances (double near, double far, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetClippingRange (near, far);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setCameraFieldOfView (double fovy, int viewport)
{
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
// Modify all renderer's cameras
if (viewport == 0 || viewport == i)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetUseHorizontalViewAngle (0);
cam->SetViewAngle (fovy * 180.0 / M_PI);
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::resetCameraViewpoint (const std::string &id)
{
vtkSmartPointer<vtkMatrix4x4> camera_pose;
static CloudActorMap::iterator it = cloud_actor_map_->find (id);
if (it != cloud_actor_map_->end ())
camera_pose = it->second.viewpoint_transformation_;
else
return;
// Prevent a segfault
if (!camera_pose)
return;
// set all renderer to this viewpoint
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkSmartPointer<vtkCamera> cam = renderer->GetActiveCamera ();
cam->SetPosition (camera_pose->GetElement (0, 3),
camera_pose->GetElement (1, 3),
camera_pose->GetElement (2, 3));
cam->SetFocalPoint (camera_pose->GetElement (0, 3) - camera_pose->GetElement (0, 2),
camera_pose->GetElement (1, 3) - camera_pose->GetElement (1, 2),
camera_pose->GetElement (2, 3) - camera_pose->GetElement (2, 2));
cam->SetViewUp (camera_pose->GetElement (0, 1),
camera_pose->GetElement (1, 1),
camera_pose->GetElement (2, 1));
renderer->SetActiveCamera (cam);
renderer->ResetCameraClippingRange ();
}
win_->Render ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::getCameraParameters (int argc, char **argv)
{
for (int i = 1; i < argc; i++)
{
if ((strcmp (argv[i], "-cam") == 0) && (++i < argc))
{
std::string camfile = std::string (argv[i]);
if (camfile.find (".cam") == std::string::npos)
{
// Assume we have clip/focal/pos/view
std::vector<std::string> camera;
boost::split (camera, argv[i], boost::is_any_of ("/"), boost::token_compress_on);
return (style_->getCameraParameters (camera));
}
else
{
// Assume that if we don't have clip/focal/pos/view, a filename.cam was given as a parameter
return (style_->loadCameraParameters (camfile));
}
}
}
return (false);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::loadCameraParameters (const std::string &file)
{
return (style_->loadCameraParameters (file));
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCylinder (const pcl::ModelCoefficients &coefficients,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCylinder] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 7)
{
PCL_WARN ("[addCylinder] Coefficients size does not match expected size (expected 7).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCylinder (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCube (const pcl::ModelCoefficients &coefficients,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCube] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 10)
{
PCL_WARN ("[addCube] Coefficients size does not match expected size (expected 10).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCube (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCube (
const Eigen::Vector3f &translation, const Eigen::Quaternionf &rotation,
double width, double height, double depth,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCube] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCube (translation, rotation, width, height, depth);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCube (float x_min, float x_max,
float y_min, float y_max,
float z_min, float z_max,
double r, double g, double b,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCube] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCube (x_min, x_max, y_min, y_max, z_min, z_max);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
actor->GetProperty ()->SetColor (r, g, b);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addSphere (const pcl::ModelCoefficients &coefficients,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addSphere] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 4)
{
PCL_WARN ("[addSphere] Coefficients size does not match expected size (expected 4).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createSphere (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPolyData (
vtkSmartPointer<vtkPolyData> polydata, const std::string & id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPolyData] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (polydata, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPolyData (
vtkSmartPointer<vtkPolyData> polydata, vtkSmartPointer<vtkTransform> transform, const std::string & id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPolyData] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer <vtkTransformFilter> trans_filter = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter->SetTransform (transform);
#if VTK_MAJOR_VERSION < 6
trans_filter->SetInput (polydata);
#else
trans_filter->SetInputData (polydata);
#endif
trans_filter->Update ();
// Create an Actor
vtkSmartPointer <vtkLODActor> actor;
createActorFromVTKDataSet (trans_filter->GetOutput (), actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPLYFile (const std::string &filename,
const std::string &id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPLYFile] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer<vtkPLYReader> reader = vtkSmartPointer<vtkPLYReader>::New ();
reader->SetFileName (filename.c_str ());
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (reader->GetOutput (), actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addModelFromPLYFile (const std::string &filename,
vtkSmartPointer<vtkTransform> transform, const std::string &id,
int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addModelFromPLYFile] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
vtkSmartPointer <vtkPLYReader > reader = vtkSmartPointer<vtkPLYReader>::New ();
reader->SetFileName (filename.c_str ());
//create transformation filter
vtkSmartPointer <vtkTransformFilter> trans_filter = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter->SetTransform (transform);
trans_filter->SetInputConnection (reader->GetOutputPort ());
// Create an Actor
vtkSmartPointer <vtkLODActor> actor;
createActorFromVTKDataSet (trans_filter->GetOutput (), actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addLine (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addLine] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 6)
{
PCL_WARN ("[addLine] Coefficients size does not match expected size (expected 6).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createLine (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
/** \brief Add a plane from a set of given model coefficients
* \param coefficients the model coefficients (a, b, c, d with ax+by+cz+d=0)
* \param id the plane id/name (default: "plane")
* \param viewport (optional) the id of the new viewport (default: 0)
*/
bool
pcl::visualization::PCLVisualizer::addPlane (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addPlane] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 4)
{
PCL_WARN ("[addPlane] Coefficients size does not match expected size (expected 4).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createPlane (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
bool
pcl::visualization::PCLVisualizer::addPlane (const pcl::ModelCoefficients &coefficients, double x, double y, double z, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addPlane] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 4)
{
PCL_WARN ("[addPlane] Coefficients size does not match expected size (expected 4).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createPlane (coefficients, x, y, z);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCircle (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCircle] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 3)
{
PCL_WARN ("[addCircle] Coefficients size does not match expected size (expected 3).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = create2DCircle (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addCone (const pcl::ModelCoefficients &coefficients, const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addCone] A shape with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
return (false);
}
if (coefficients.values.size () != 7)
{
PCL_WARN ("[addCone] Coefficients size does not match expected size (expected 7).\n");
return (false);
}
vtkSmartPointer<vtkDataSet> data = createCone (coefficients);
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (data, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createViewPort (double xmin, double ymin, double xmax, double ymax, int &viewport)
{
// Create a new renderer
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New ();
ren->SetViewport (xmin, ymin, xmax, ymax);
if (rens_->GetNumberOfItems () > 0)
ren->SetActiveCamera (rens_->GetFirstRenderer ()->GetActiveCamera ());
ren->ResetCamera ();
// Add it to the list of renderers
rens_->AddItem (ren);
if (rens_->GetNumberOfItems () <= 1) // If only one renderer
viewport = 0; // set viewport to 'all'
else
viewport = rens_->GetNumberOfItems () - 1;
win_->AddRenderer (ren);
win_->Modified ();
}
//////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::createViewPortCamera (const int viewport)
{
vtkSmartPointer<vtkCamera> cam = vtkSmartPointer<vtkCamera>::New ();
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
int i = 0;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
if (viewport == 0)
continue;
else if (viewport == i)
{
renderer->SetActiveCamera (cam);
renderer->ResetCamera ();
}
++i;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addText (const std::string &text, int xpos, int ypos, const std::string &id, int viewport)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addText] A text with id <%s> already exists! Please choose a different id and retry.\n", tid.c_str ());
return (false);
}
// Create an Actor
vtkSmartPointer<vtkTextActor> actor = vtkSmartPointer<vtkTextActor>::New ();
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetFontSize (10);
tprop->SetFontFamilyToArial ();
tprop->SetJustificationToLeft ();
tprop->BoldOn ();
tprop->SetColor (1, 1, 1);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[tid] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addText (const std::string &text, int xpos, int ypos, double r, double g, double b, const std::string &id, int viewport)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addText] A text with id <%s> already exists! Please choose a different id and retry.\n", tid.c_str ());
return (false);
}
// Create an Actor
vtkSmartPointer<vtkTextActor> actor = vtkSmartPointer<vtkTextActor>::New ();
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetFontSize (10);
tprop->SetFontFamilyToArial ();
tprop->SetJustificationToLeft ();
tprop->BoldOn ();
tprop->SetColor (r, g, b);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[tid] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addText (const std::string &text, int xpos, int ypos, int fontsize, double r, double g, double b, const std::string &id, int viewport)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[addText] A text with id <%s> already exists! Please choose a different id and retry.\n", tid.c_str ());
return (false);
}
// Create an Actor
vtkSmartPointer<vtkTextActor> actor = vtkSmartPointer<vtkTextActor>::New ();
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetFontSize (fontsize);
tprop->SetFontFamilyToArial ();
tprop->SetJustificationToLeft ();
tprop->BoldOn ();
tprop->SetColor (r, g, b);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[tid] = actor;
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateText (const std::string &text, int xpos, int ypos, const std::string &id)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it == shape_actor_map_->end ())
return (false);
// Retrieve the Actor
vtkTextActor* actor = vtkTextActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
actor->Modified ();
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateText (const std::string &text, int xpos, int ypos, double r, double g, double b, const std::string &id)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it == shape_actor_map_->end ())
return (false);
// Create the Actor
vtkTextActor* actor = vtkTextActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkSmartPointer<vtkTextProperty> tprop = actor->GetTextProperty ();
tprop->SetColor (r, g, b);
actor->Modified ();
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateText (const std::string &text, int xpos, int ypos, int fontsize, double r, double g, double b, const std::string &id)
{
std::string tid;
if (id.empty ())
tid = text;
else
tid = id;
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
ShapeActorMap::iterator am_it = shape_actor_map_->find (tid);
if (am_it == shape_actor_map_->end ())
return (false);
// Retrieve the Actor
vtkTextActor *actor = vtkTextActor::SafeDownCast (am_it->second);
if (!actor)
return (false);
actor->SetPosition (xpos, ypos);
actor->SetInput (text.c_str ());
vtkTextProperty* tprop = actor->GetTextProperty ();
tprop->SetFontSize (fontsize);
tprop->SetColor (r, g, b);
actor->Modified ();
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updateColorHandlerIndex (const std::string &id, int index)
{
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
{
pcl::console::print_warn (stderr, "[updateColorHandlerIndex] PointCloud with id <%s> doesn't exist!\n", id.c_str ());
return (false);
}
size_t color_handler_size = am_it->second.color_handlers.size ();
if (!(size_t (index) < color_handler_size))
{
pcl::console::print_warn (stderr, "[updateColorHandlerIndex] Invalid index <%d> given! Index must be less than %d.\n", index, int (color_handler_size));
return (false);
}
// Get the handler
PointCloudColorHandler<pcl::PCLPointCloud2>::ConstPtr color_handler = am_it->second.color_handlers[index];
vtkSmartPointer<vtkDataArray> scalars;
color_handler->getColor (scalars);
double minmax[2];
scalars->GetRange (minmax);
// Update the data
vtkPolyData *data = static_cast<vtkPolyData*>(am_it->second.actor->GetMapper ()->GetInput ());
data->GetPointData ()->SetScalars (scalars);
// Modify the mapper
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
if (use_vbos_)
{
vtkVertexBufferObjectMapper* mapper = static_cast<vtkVertexBufferObjectMapper*>(am_it->second.actor->GetMapper ());
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
mapper->SetInput (data);
// Modify the actor
am_it->second.actor->SetMapper (mapper);
am_it->second.actor->Modified ();
am_it->second.color_handler_index_ = index;
//style_->setCloudActorMap (cloud_actor_map_);
}
else
#endif
{
vtkPolyDataMapper* mapper = static_cast<vtkPolyDataMapper*>(am_it->second.actor->GetMapper ());
mapper->SetScalarRange (minmax);
mapper->SetScalarModeToUsePointData ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (data);
#else
mapper->SetInputData (data);
#endif
// Modify the actor
am_it->second.actor->SetMapper (mapper);
am_it->second.actor->Modified ();
am_it->second.color_handler_index_ = index;
//style_->setCloudActorMap (cloud_actor_map_);
}
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPolygonMesh (const pcl::PolygonMesh &poly_mesh,
const std::string &id,
int viewport)
{
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addPolygonMesh] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
// Create points from polyMesh.cloud
vtkSmartPointer<vtkPoints> poly_points = vtkSmartPointer<vtkPoints>::New ();
pcl::PointCloud<pcl::PointXYZ>::Ptr point_cloud (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::fromPCLPointCloud2 (poly_mesh.cloud, *point_cloud);
poly_points->SetNumberOfPoints (point_cloud->points.size ());
for (size_t i = 0; i < point_cloud->points.size (); ++i)
{
const pcl::PointXYZ& p = point_cloud->points[i];
poly_points->InsertPoint (i, p.x, p.y, p.z);
}
bool has_color = false;
vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New ();
if (pcl::getFieldIndex(poly_mesh.cloud, "rgb") != -1)
{
has_color = true;
colors->SetNumberOfComponents (3);
colors->SetName ("Colors");
pcl::PointCloud<pcl::PointXYZRGB> cloud;
pcl::fromPCLPointCloud2 (poly_mesh.cloud, cloud);
for (size_t i = 0; i < cloud.points.size (); ++i)
{
const unsigned char color[3] = { cloud.points[i].r, cloud.points[i].g, cloud.points[i].b };
colors->InsertNextTupleValue (color);
}
}
if (pcl::getFieldIndex (poly_mesh.cloud, "rgba") != -1)
{
has_color = true;
colors->SetNumberOfComponents (3);
colors->SetName ("Colors");
pcl::PointCloud<pcl::PointXYZRGBA> cloud;
pcl::fromPCLPointCloud2 (poly_mesh.cloud, cloud);
for (size_t i = 0; i < cloud.points.size (); ++i)
{
const unsigned char color[3] = { cloud.points[i].r, cloud.points[i].g, cloud.points[i].b };
colors->InsertNextTupleValue (color);
}
}
vtkSmartPointer<vtkLODActor> actor;
if (poly_mesh.polygons.size () > 1)
{
//create polys from polyMesh.polygons
vtkSmartPointer<vtkCellArray> cell_array = vtkSmartPointer<vtkCellArray>::New ();
for (size_t i = 0; i < poly_mesh.polygons.size (); i++)
{
size_t n_points (poly_mesh.polygons[i].vertices.size ());
cell_array->InsertNextCell (int (n_points));
for (size_t j = 0; j < n_points; j++)
cell_array->InsertCellPoint (poly_mesh.polygons[i].vertices[j]);
}
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New ();
// polydata->SetStrips (cell_array);
polydata->SetPolys (cell_array);
polydata->SetPoints (poly_points);
if (has_color)
polydata->GetPointData ()->SetScalars (colors);
createActorFromVTKDataSet (polydata, actor);
}
else if (poly_mesh.polygons.size () == 1)
{
vtkSmartPointer<vtkPolygon> polygon = vtkSmartPointer<vtkPolygon>::New ();
size_t n_points = poly_mesh.polygons[0].vertices.size ();
polygon->GetPointIds ()->SetNumberOfIds (n_points - 1);
for (size_t j = 0; j < (n_points - 1); j++)
polygon->GetPointIds ()->SetId (j, poly_mesh.polygons[0].vertices[j]);
vtkSmartPointer<vtkUnstructuredGrid> poly_grid = vtkSmartPointer<vtkUnstructuredGrid>::New ();
poly_grid->Allocate (1, 1);
poly_grid->InsertNextCell (polygon->GetCellType (), polygon->GetPointIds ());
poly_grid->SetPoints (poly_points);
createActorFromVTKDataSet (poly_grid, actor);
actor->GetProperty ()->SetRepresentationToSurface ();
}
else
{
PCL_ERROR ("PCLVisualizer::addPolygonMesh: No polygons\n");
return false;
}
actor->GetProperty ()->SetRepresentationToSurface ();
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*cloud_actor_map_)[id].actor = actor;
// Save the viewpoint transformation matrix to the global actor map
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (point_cloud->sensor_origin_, point_cloud->sensor_orientation_, transformation);
(*cloud_actor_map_)[id].viewpoint_transformation_ = transformation;
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::updatePolygonMesh (
const pcl::PolygonMesh &poly_mesh,
const std::string &id)
{
if (poly_mesh.polygons.empty ())
{
pcl::console::print_error ("[updatePolygonMesh] No vertices given!\n");
return (false);
}
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it == cloud_actor_map_->end ())
return (false);
// Create points from polyMesh.cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::fromPCLPointCloud2 (poly_mesh.cloud, *cloud);
std::vector<pcl::Vertices> verts (poly_mesh.polygons); // copy vector
// Get the current poly data
vtkSmartPointer<vtkPolyData> polydata = static_cast<vtkPolyDataMapper*>(am_it->second.actor->GetMapper ())->GetInput ();
if (!polydata)
return (false);
vtkSmartPointer<vtkCellArray> cells = polydata->GetStrips ();
if (!cells)
return (false);
vtkSmartPointer<vtkPoints> points = polydata->GetPoints ();
// Copy the new point array in
vtkIdType nr_points = cloud->points.size ();
points->SetNumberOfPoints (nr_points);
// Get a pointer to the beginning of the data array
float *data = static_cast<vtkFloatArray*> (points->GetData ())->GetPointer (0);
int ptr = 0;
std::vector<int> lookup;
// If the dataset is dense (no NaNs)
if (cloud->is_dense)
{
for (vtkIdType i = 0; i < nr_points; ++i, ptr += 3)
std::copy (&cloud->points[i].x, &cloud->points[i].x + 3, &data[ptr]);
}
else
{
lookup.resize (nr_points);
vtkIdType j = 0; // true point index
for (vtkIdType i = 0; i < nr_points; ++i)
{
// Check if the point is invalid
if (!isFinite (cloud->points[i]))
continue;
lookup[i] = static_cast<int> (j);
std::copy (&cloud->points[i].x, &cloud->points[i].x + 3, &data[ptr]);
j++;
ptr += 3;
}
nr_points = j;
points->SetNumberOfPoints (nr_points);
}
// Get the maximum size of a polygon
int max_size_of_polygon = -1;
for (size_t i = 0; i < verts.size (); ++i)
if (max_size_of_polygon < static_cast<int> (verts[i].vertices.size ()))
max_size_of_polygon = static_cast<int> (verts[i].vertices.size ());
// Update the cells
cells = vtkSmartPointer<vtkCellArray>::New ();
vtkIdType *cell = cells->WritePointer (verts.size (), verts.size () * (max_size_of_polygon + 1));
int idx = 0;
if (lookup.size () > 0)
{
for (size_t i = 0; i < verts.size (); ++i, ++idx)
{
size_t n_points = verts[i].vertices.size ();
*cell++ = n_points;
for (size_t j = 0; j < n_points; j++, cell++, ++idx)
*cell = lookup[verts[i].vertices[j]];
}
}
else
{
for (size_t i = 0; i < verts.size (); ++i, ++idx)
{
size_t n_points = verts[i].vertices.size ();
*cell++ = n_points;
for (size_t j = 0; j < n_points; j++, cell++, ++idx)
*cell = verts[i].vertices[j];
}
}
cells->GetData ()->SetNumberOfValues (idx);
cells->Squeeze ();
// Set the the vertices
polydata->SetStrips (cells);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPolylineFromPolygonMesh (
const pcl::PolygonMesh &polymesh, const std::string &id, int viewport)
{
ShapeActorMap::iterator am_it = shape_actor_map_->find (id);
if (am_it != shape_actor_map_->end ())
{
pcl::console::print_warn (stderr,
"[addPolylineFromPolygonMesh] A shape with id <%s> already exists! Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
// Create points from polyMesh.cloud
vtkSmartPointer<vtkPoints> poly_points = vtkSmartPointer<vtkPoints>::New ();
pcl::PointCloud<pcl::PointXYZ> point_cloud;
pcl::fromPCLPointCloud2 (polymesh.cloud, point_cloud);
poly_points->SetNumberOfPoints (point_cloud.points.size ());
size_t i;
for (i = 0; i < point_cloud.points.size (); ++i)
poly_points->InsertPoint (i, point_cloud.points[i].x, point_cloud.points[i].y, point_cloud.points[i].z);
// Create a cell array to store the lines in and add the lines to it
vtkSmartPointer <vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New ();
vtkSmartPointer <vtkPolyData> polyData;
allocVtkPolyData (polyData);
for (i = 0; i < polymesh.polygons.size (); i++)
{
vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New();
polyLine->GetPointIds()->SetNumberOfIds(polymesh.polygons[i].vertices.size());
for(unsigned int k = 0; k < polymesh.polygons[i].vertices.size(); k++)
{
polyLine->GetPointIds ()->SetId (k, polymesh.polygons[i].vertices[k]);
}
cells->InsertNextCell (polyLine);
}
// Add the points to the dataset
polyData->SetPoints (poly_points);
// Add the lines to the dataset
polyData->SetLines (cells);
// Setup actor and mapper
vtkSmartPointer < vtkPolyDataMapper > mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (polyData);
#else
mapper->SetInputData (polyData);
#endif
vtkSmartPointer < vtkActor > actor = vtkSmartPointer<vtkActor>::New ();
actor->SetMapper (mapper);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*shape_actor_map_)[id] = actor;
return (true);
}
/////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addTextureMesh (const pcl::TextureMesh &mesh,
const std::string &id,
int viewport)
{
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] A shape with id <%s> already exists!"
" Please choose a different id and retry.\n",
id.c_str ());
return (false);
}
// no texture materials --> exit
if (mesh.tex_materials.size () == 0)
{
PCL_ERROR("[PCLVisualizer::addTextureMesh] No textures found!\n");
return (false);
}
// polygons are mapped to texture materials
if (mesh.tex_materials.size () != mesh.tex_polygons.size ())
{
PCL_ERROR("[PCLVisualizer::addTextureMesh] Materials number %lu differs from polygons number %lu!\n",
mesh.tex_materials.size (), mesh.tex_polygons.size ());
return (false);
}
// each texture material should have its coordinates set
if (mesh.tex_materials.size () != mesh.tex_coordinates.size ())
{
PCL_ERROR("[PCLVisualizer::addTextureMesh] Coordinates number %lu differs from materials number %lu!\n",
mesh.tex_coordinates.size (), mesh.tex_materials.size ());
return (false);
}
// total number of vertices
std::size_t nb_vertices = 0;
for (std::size_t i = 0; i < mesh.tex_polygons.size (); ++i)
nb_vertices += mesh.tex_polygons[i].size ();
// no vertices --> exit
if (nb_vertices == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] No vertices found!\n");
return (false);
}
// total number of coordinates
std::size_t nb_coordinates = 0;
for (std::size_t i = 0; i < mesh.tex_coordinates.size (); ++i)
nb_coordinates += mesh.tex_coordinates[i].size ();
// no texture coordinates --> exit
if (nb_coordinates == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] No textures coordinates found!\n");
return (false);
}
// Create points from mesh.cloud
vtkSmartPointer<vtkPoints> poly_points = vtkSmartPointer<vtkPoints>::New ();
vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New ();
bool has_color = false;
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
if ((pcl::getFieldIndex(mesh.cloud, "rgba") != -1) ||
(pcl::getFieldIndex(mesh.cloud, "rgb") != -1))
{
pcl::PointCloud<pcl::PointXYZRGB> cloud;
pcl::fromPCLPointCloud2 (mesh.cloud, cloud);
if (cloud.points.size () == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] Cloud is empty!\n");
return (false);
}
convertToVtkMatrix (cloud.sensor_origin_, cloud.sensor_orientation_, transformation);
has_color = true;
colors->SetNumberOfComponents (3);
colors->SetName ("Colors");
poly_points->SetNumberOfPoints (cloud.size ());
for (std::size_t i = 0; i < cloud.points.size (); ++i)
{
const pcl::PointXYZRGB &p = cloud.points[i];
poly_points->InsertPoint (i, p.x, p.y, p.z);
const unsigned char color[3] = { p.r, p.g, p.b };
colors->InsertNextTupleValue (color);
}
}
else
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::fromPCLPointCloud2 (mesh.cloud, *cloud);
// no points --> exit
if (cloud->points.size () == 0)
{
PCL_ERROR ("[PCLVisualizer::addTextureMesh] Cloud is empty!\n");
return (false);
}
convertToVtkMatrix (cloud->sensor_origin_, cloud->sensor_orientation_, transformation);
poly_points->SetNumberOfPoints (cloud->points.size ());
for (std::size_t i = 0; i < cloud->points.size (); ++i)
{
const pcl::PointXYZ &p = cloud->points[i];
poly_points->InsertPoint (i, p.x, p.y, p.z);
}
}
//create polys from polyMesh.tex_polygons
vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New ();
for (std::size_t i = 0; i < mesh.tex_polygons.size (); i++)
{
for (std::size_t j = 0; j < mesh.tex_polygons[i].size (); j++)
{
std::size_t n_points = mesh.tex_polygons[i][j].vertices.size ();
polys->InsertNextCell (int (n_points));
for (std::size_t k = 0; k < n_points; k++)
polys->InsertCellPoint (mesh.tex_polygons[i][j].vertices[k]);
}
}
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New ();
polydata->SetPolys (polys);
polydata->SetPoints (poly_points);
if (has_color)
polydata->GetPointData ()->SetScalars (colors);
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
#if VTK_MAJOR_VERSION < 6
mapper->SetInput (polydata);
#else
mapper->SetInputData (polydata);
#endif
vtkSmartPointer<vtkLODActor> actor = vtkSmartPointer<vtkLODActor>::New ();
vtkTextureUnitManager* tex_manager = vtkOpenGLRenderWindow::SafeDownCast (win_)->GetTextureUnitManager ();
if (!tex_manager)
return (false);
// Check if hardware support multi texture
int texture_units = tex_manager->GetNumberOfTextureUnits ();
if ((mesh.tex_materials.size () > 1) && (texture_units > 1))
{
if ((size_t) texture_units < mesh.tex_materials.size ())
PCL_WARN ("[PCLVisualizer::addTextureMesh] GPU texture units %d < mesh textures %d!\n",
texture_units, mesh.tex_materials.size ());
// Load textures
std::size_t last_tex_id = std::min (static_cast<int> (mesh.tex_materials.size ()), texture_units);
int tu = vtkProperty::VTK_TEXTURE_UNIT_0;
std::size_t tex_id = 0;
while (tex_id < last_tex_id)
{
vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New ();
if (textureFromTexMaterial (mesh.tex_materials[tex_id], texture))
{
PCL_WARN ("[PCLVisualizer::addTextureMesh] Failed to load texture %s, skipping!\n",
mesh.tex_materials[tex_id].tex_name.c_str ());
continue;
}
// the first texture is in REPLACE mode others are in ADD mode
if (tex_id == 0)
texture->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_REPLACE);
else
texture->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
// add a texture coordinates array per texture
vtkSmartPointer<vtkFloatArray> coordinates = vtkSmartPointer<vtkFloatArray>::New ();
coordinates->SetNumberOfComponents (2);
std::stringstream ss; ss << "TCoords" << tex_id;
std::string this_coordinates_name = ss.str ();
coordinates->SetName (this_coordinates_name.c_str ());
for (std::size_t t = 0; t < mesh.tex_coordinates.size (); ++t)
if (t == tex_id)
for (std::size_t tc = 0; tc < mesh.tex_coordinates[t].size (); ++tc)
coordinates->InsertNextTuple2 (mesh.tex_coordinates[t][tc][0],
mesh.tex_coordinates[t][tc][1]);
else
for (std::size_t tc = 0; tc < mesh.tex_coordinates[t].size (); ++tc)
coordinates->InsertNextTuple2 (-1.0, -1.0);
mapper->MapDataArrayToMultiTextureAttribute(tu,
this_coordinates_name.c_str (),
vtkDataObject::FIELD_ASSOCIATION_POINTS);
polydata->GetPointData ()->AddArray (coordinates);
actor->GetProperty ()->SetTexture (tu, texture);
++tex_id;
++tu;
}
} // end of multi texturing
else
{
if ((mesh.tex_materials.size () > 1) && (texture_units < 2))
PCL_WARN ("[PCLVisualizer::addTextureMesh] Your GPU doesn't support multi texturing. "
"Will use first one only!\n");
vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New ();
// fill vtkTexture from pcl::TexMaterial structure
if (textureFromTexMaterial (mesh.tex_materials[0], texture))
PCL_WARN ("[PCLVisualizer::addTextureMesh] Failed to create vtkTexture from %s!\n",
mesh.tex_materials[0].tex_name.c_str ());
// set texture coordinates
vtkSmartPointer<vtkFloatArray> coordinates = vtkSmartPointer<vtkFloatArray>::New ();
coordinates->SetNumberOfComponents (2);
coordinates->SetNumberOfTuples (mesh.tex_coordinates[0].size ());
for (std::size_t tc = 0; tc < mesh.tex_coordinates[0].size (); ++tc)
{
const Eigen::Vector2f &uv = mesh.tex_coordinates[0][tc];
coordinates->SetTuple2 (tc, uv[0], uv[1]);
}
coordinates->SetName ("TCoords");
polydata->GetPointData ()->SetTCoords (coordinates);
// apply texture
actor->SetTexture (texture);
} // end of one texture
// set mapper
actor->SetMapper (mapper);
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
(*cloud_actor_map_)[id].actor = actor;
// Save the viewpoint transformation matrix to the global actor map
(*cloud_actor_map_)[id].viewpoint_transformation_ = transformation;
return (true);
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setRepresentationToSurfaceForAllActors ()
{
ShapeActorMap::iterator am_it;
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkActorCollection * actors = renderer->GetActors ();
actors->InitTraversal ();
vtkActor * actor;
while ((actor = actors->GetNextActor ()) != NULL)
{
actor->GetProperty ()->SetRepresentationToSurface ();
actor->GetProperty ()->SetLighting (true);
}
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setRepresentationToPointsForAllActors ()
{
ShapeActorMap::iterator am_it;
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkActorCollection * actors = renderer->GetActors ();
actors->InitTraversal ();
vtkActor * actor;
while ((actor = actors->GetNextActor ()) != NULL)
{
actor->GetProperty ()->SetRepresentationToPoints ();
}
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setRepresentationToWireframeForAllActors ()
{
ShapeActorMap::iterator am_it;
rens_->InitTraversal ();
vtkRenderer* renderer = NULL;
while ((renderer = rens_->GetNextItem ()) != NULL)
{
vtkActorCollection * actors = renderer->GetActors ();
actors->InitTraversal ();
vtkActor * actor;
while ((actor = actors->GetNextActor ()) != NULL)
{
actor->GetProperty ()->SetRepresentationToWireframe ();
actor->GetProperty ()->SetLighting (false);
}
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setShowFPS (bool show_fps)
{
update_fps_->actor->SetVisibility (show_fps);
}
///////////////////////////////////////////////////////////////////////////////////
float
pcl::visualization::PCLVisualizer::getFPS () const
{
return (update_fps_->last_fps);
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::renderViewTesselatedSphere (
int xres,
int yres,
pcl::PointCloud<pcl::PointXYZ>::CloudVectorType &clouds,
std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<
Eigen::Matrix4f> > & poses,
std::vector<float> & enthropies, int tesselation_level,
float view_angle, float radius_sphere, bool use_vertices)
{
if (rens_->GetNumberOfItems () > 1)
{
PCL_WARN ("[renderViewTesselatedSphere] Method works only with one renderer.\n");
return;
}
rens_->InitTraversal ();
vtkRenderer* renderer_pcl_vis = rens_->GetNextItem ();
vtkActorCollection * actors = renderer_pcl_vis->GetActors ();
if (actors->GetNumberOfItems () > 1)
PCL_INFO ("[renderViewTesselatedSphere] Method only consider the first actor on the scene, more than one found.\n");
//get vtk object from the visualizer
actors->InitTraversal ();
vtkActor * actor = actors->GetNextActor ();
vtkSmartPointer<vtkPolyData> polydata;
allocVtkPolyData (polydata);
polydata->CopyStructure (actor->GetMapper ()->GetInput ());
//center object
double CoM[3];
vtkIdType npts_com = 0, *ptIds_com = NULL;
vtkSmartPointer<vtkCellArray> cells_com = polydata->GetPolys ();
double center[3], p1_com[3], p2_com[3], p3_com[3], area_com, totalArea_com = 0;
double comx = 0, comy = 0, comz = 0;
for (cells_com->InitTraversal (); cells_com->GetNextCell (npts_com, ptIds_com);)
{
polydata->GetPoint (ptIds_com[0], p1_com);
polydata->GetPoint (ptIds_com[1], p2_com);
polydata->GetPoint (ptIds_com[2], p3_com);
vtkTriangle::TriangleCenter (p1_com, p2_com, p3_com, center);
area_com = vtkTriangle::TriangleArea (p1_com, p2_com, p3_com);
comx += center[0] * area_com;
comy += center[1] * area_com;
comz += center[2] * area_com;
totalArea_com += area_com;
}
CoM[0] = comx / totalArea_com;
CoM[1] = comy / totalArea_com;
CoM[2] = comz / totalArea_com;
vtkSmartPointer<vtkTransform> trans_center = vtkSmartPointer<vtkTransform>::New ();
trans_center->Translate (-CoM[0], -CoM[1], -CoM[2]);
vtkSmartPointer<vtkMatrix4x4> matrixCenter = trans_center->GetMatrix ();
vtkSmartPointer<vtkTransformFilter> trans_filter_center = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter_center->SetTransform (trans_center);
#if VTK_MAJOR_VERSION < 6
trans_filter_center->SetInput (polydata);
#else
trans_filter_center->SetInputData (polydata);
#endif
trans_filter_center->Update ();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
mapper->SetInputConnection (trans_filter_center->GetOutputPort ());
mapper->Update ();
//scale so it fits in the unit sphere!
double bb[6];
mapper->GetBounds (bb);
double ms = (std::max) ((std::fabs) (bb[0] - bb[1]),
(std::max) ((std::fabs) (bb[2] - bb[3]), (std::fabs) (bb[4] - bb[5])));
double max_side = radius_sphere / 2.0;
double scale_factor = max_side / ms;
vtkSmartPointer<vtkTransform> trans_scale = vtkSmartPointer<vtkTransform>::New ();
trans_scale->Scale (scale_factor, scale_factor, scale_factor);
vtkSmartPointer<vtkMatrix4x4> matrixScale = trans_scale->GetMatrix ();
vtkSmartPointer<vtkTransformFilter> trans_filter_scale = vtkSmartPointer<vtkTransformFilter>::New ();
trans_filter_scale->SetTransform (trans_scale);
trans_filter_scale->SetInputConnection (trans_filter_center->GetOutputPort ());
trans_filter_scale->Update ();
mapper->SetInputConnection (trans_filter_scale->GetOutputPort ());
mapper->Update ();
//////////////////////////////
// * Compute area of the mesh
//////////////////////////////
vtkSmartPointer<vtkCellArray> cells = mapper->GetInput ()->GetPolys ();
vtkIdType npts = 0, *ptIds = NULL;
double p1[3], p2[3], p3[3], area, totalArea = 0;
for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds);)
{
polydata->GetPoint (ptIds[0], p1);
polydata->GetPoint (ptIds[1], p2);
polydata->GetPoint (ptIds[2], p3);
area = vtkTriangle::TriangleArea (p1, p2, p3);
totalArea += area;
}
//create icosahedron
vtkSmartPointer<vtkPlatonicSolidSource> ico = vtkSmartPointer<vtkPlatonicSolidSource>::New ();
ico->SetSolidTypeToIcosahedron ();
ico->Update ();
//tesselate cells from icosahedron
vtkSmartPointer<vtkLoopSubdivisionFilter> subdivide = vtkSmartPointer<vtkLoopSubdivisionFilter>::New ();
subdivide->SetNumberOfSubdivisions (tesselation_level);
subdivide->SetInputConnection (ico->GetOutputPort ());
subdivide->Update ();
// Get camera positions
vtkPolyData *sphere = subdivide->GetOutput ();
std::vector<Eigen::Vector3f, Eigen::aligned_allocator<Eigen::Vector3f> > cam_positions;
if (!use_vertices)
{
vtkSmartPointer<vtkCellArray> cells_sphere = sphere->GetPolys ();
cam_positions.resize (sphere->GetNumberOfPolys ());
size_t i = 0;
for (cells_sphere->InitTraversal (); cells_sphere->GetNextCell (npts_com, ptIds_com);)
{
sphere->GetPoint (ptIds_com[0], p1_com);
sphere->GetPoint (ptIds_com[1], p2_com);
sphere->GetPoint (ptIds_com[2], p3_com);
vtkTriangle::TriangleCenter (p1_com, p2_com, p3_com, center);
cam_positions[i] = Eigen::Vector3f (float (center[0]), float (center[1]), float (center[2]));
cam_positions[i].normalize ();
i++;
}
}
else
{
cam_positions.resize (sphere->GetNumberOfPoints ());
for (int i = 0; i < sphere->GetNumberOfPoints (); i++)
{
double cam_pos[3];
sphere->GetPoint (i, cam_pos);
cam_positions[i] = Eigen::Vector3f (float (cam_pos[0]), float (cam_pos[1]), float (cam_pos[2]));
cam_positions[i].normalize ();
}
}
double camera_radius = radius_sphere;
double cam_pos[3];
double first_cam_pos[3];
first_cam_pos[0] = cam_positions[0][0] * radius_sphere;
first_cam_pos[1] = cam_positions[0][1] * radius_sphere;
first_cam_pos[2] = cam_positions[0][2] * radius_sphere;
//create renderer and window
vtkSmartPointer<vtkRenderWindow> render_win = vtkSmartPointer<vtkRenderWindow>::New ();
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New ();
render_win->AddRenderer (renderer);
render_win->SetSize (xres, yres);
renderer->SetBackground (1.0, 0, 0);
//create picker
vtkSmartPointer<vtkWorldPointPicker> worldPicker = vtkSmartPointer<vtkWorldPointPicker>::New ();
vtkSmartPointer<vtkCamera> cam = vtkSmartPointer<vtkCamera>::New ();
cam->SetFocalPoint (0, 0, 0);
Eigen::Vector3f cam_pos_3f = cam_positions[0];
Eigen::Vector3f perp = cam_pos_3f.cross (Eigen::Vector3f::UnitY ());
cam->SetViewUp (perp[0], perp[1], perp[2]);
cam->SetPosition (first_cam_pos);
cam->SetViewAngle (view_angle);
cam->Modified ();
//For each camera position, traposesnsform the object and render view
for (size_t i = 0; i < cam_positions.size (); i++)
{
cam_pos[0] = cam_positions[i][0];
cam_pos[1] = cam_positions[i][1];
cam_pos[2] = cam_positions[i][2];
//create temporal virtual camera
vtkSmartPointer<vtkCamera> cam_tmp = vtkSmartPointer<vtkCamera>::New ();
cam_tmp->SetViewAngle (view_angle);
Eigen::Vector3f cam_pos_3f (static_cast<float> (cam_pos[0]), static_cast<float> (cam_pos[1]), static_cast<float> (cam_pos[2]));
cam_pos_3f = cam_pos_3f.normalized ();
Eigen::Vector3f test = Eigen::Vector3f::UnitY ();
//If the view up is parallel to ray cam_pos - focalPoint then the transformation
//is singular and no points are rendered...
//make sure it is perpendicular
if (fabs (cam_pos_3f.dot (test)) == 1)
{
//parallel, create
test = cam_pos_3f.cross (Eigen::Vector3f::UnitX ());
}
cam_tmp->SetViewUp (test[0], test[1], test[2]);
for (int k = 0; k < 3; k++)
{
cam_pos[k] = cam_pos[k] * camera_radius;
}
cam_tmp->SetPosition (cam_pos);
cam_tmp->SetFocalPoint (0, 0, 0);
cam_tmp->Modified ();
//rotate model so it looks the same as if we would look from the new position
vtkSmartPointer<vtkMatrix4x4> view_trans_inverted = vtkSmartPointer<vtkMatrix4x4>::New ();
vtkMatrix4x4::Invert (cam->GetViewTransformMatrix (), view_trans_inverted);
vtkSmartPointer<vtkTransform> trans_rot_pose = vtkSmartPointer<vtkTransform>::New ();
trans_rot_pose->Identity ();
trans_rot_pose->Concatenate (view_trans_inverted);
trans_rot_pose->Concatenate (cam_tmp->GetViewTransformMatrix ());
vtkSmartPointer<vtkTransformFilter> trans_rot_pose_filter = vtkSmartPointer<vtkTransformFilter>::New ();
trans_rot_pose_filter->SetTransform (trans_rot_pose);
trans_rot_pose_filter->SetInputConnection (trans_filter_scale->GetOutputPort ());
//translate model so we can place camera at (0,0,0)
vtkSmartPointer<vtkTransform> translation = vtkSmartPointer<vtkTransform>::New ();
translation->Translate (first_cam_pos[0] * -1, first_cam_pos[1] * -1, first_cam_pos[2] * -1);
vtkSmartPointer<vtkTransformFilter> translation_filter = vtkSmartPointer<vtkTransformFilter>::New ();
translation_filter->SetTransform (translation);
translation_filter->SetInputConnection (trans_rot_pose_filter->GetOutputPort ());
//modify camera
cam_tmp->SetPosition (0, 0, 0);
cam_tmp->SetFocalPoint (first_cam_pos[0] * -1, first_cam_pos[1] * -1, first_cam_pos[2] * -1);
cam_tmp->Modified ();
//notice transformations for final pose
vtkSmartPointer<vtkMatrix4x4> matrixRotModel = trans_rot_pose->GetMatrix ();
vtkSmartPointer<vtkMatrix4x4> matrixTranslation = translation->GetMatrix ();
mapper->SetInputConnection (translation_filter->GetOutputPort ());
mapper->Update ();
//render view
vtkSmartPointer<vtkActor> actor_view = vtkSmartPointer<vtkActor>::New ();
actor_view->SetMapper (mapper);
renderer->SetActiveCamera (cam_tmp);
renderer->AddActor (actor_view);
renderer->Modified ();
//renderer->ResetCameraClippingRange ();
render_win->Render ();
//back to real scale transform
vtkSmartPointer<vtkTransform> backToRealScale = vtkSmartPointer<vtkTransform>::New ();
backToRealScale->PostMultiply ();
backToRealScale->Identity ();
backToRealScale->Concatenate (matrixScale);
backToRealScale->Concatenate (matrixTranslation);
backToRealScale->Inverse ();
backToRealScale->Modified ();
backToRealScale->Concatenate (matrixTranslation);
backToRealScale->Modified ();
Eigen::Matrix4f backToRealScale_eigen;
backToRealScale_eigen.setIdentity ();
for (int x = 0; x < 4; x++)
for (int y = 0; y < 4; y++)
backToRealScale_eigen (x, y) = static_cast<float> (backToRealScale->GetMatrix ()->GetElement (x, y));
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
cloud->points.resize (xres * yres);
cloud->width = xres * yres;
cloud->height = 1;
double coords[3];
float * depth = new float[xres * yres];
render_win->GetZbufferData (0, 0, xres - 1, yres - 1, &(depth[0]));
int count_valid_depth_pixels = 0;
size_t xresolution (xres);
size_t yresolution (yres);
for (size_t x = 0; x < xresolution; x++)
{
for (size_t y = 0; y < yresolution; y++)
{
float value = depth[y * xres + x];
if (value == 1.0)
continue;
worldPicker->Pick (static_cast<double> (x), static_cast<double> (y), value, renderer);
worldPicker->GetPickPosition (coords);
cloud->points[count_valid_depth_pixels].x = static_cast<float> (coords[0]);
cloud->points[count_valid_depth_pixels].y = static_cast<float> (coords[1]);
cloud->points[count_valid_depth_pixels].z = static_cast<float> (coords[2]);
cloud->points[count_valid_depth_pixels].getVector4fMap () = backToRealScale_eigen
* cloud->points[count_valid_depth_pixels].getVector4fMap ();
count_valid_depth_pixels++;
}
}
delete[] depth;
//////////////////////////////
// * Compute area of the mesh
//////////////////////////////
vtkSmartPointer<vtkPolyData> polydata = mapper->GetInput ();
polydata->BuildCells ();
vtkSmartPointer<vtkCellArray> cells = polydata->GetPolys ();
vtkIdType npts = 0, *ptIds = NULL;
double p1[3], p2[3], p3[3], area, totalArea = 0;
for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds);)
{
polydata->GetPoint (ptIds[0], p1);
polydata->GetPoint (ptIds[1], p2);
polydata->GetPoint (ptIds[2], p3);
area = vtkTriangle::TriangleArea (p1, p2, p3);
totalArea += area;
}
/////////////////////////////////////
// * Select visible cells (triangles)
/////////////////////////////////////
#if (VTK_MAJOR_VERSION==5 && VTK_MINOR_VERSION<6)
vtkSmartPointer<vtkVisibleCellSelector> selector = vtkSmartPointer<vtkVisibleCellSelector>::New ();
vtkSmartPointer<vtkIdTypeArray> selection = vtkSmartPointer<vtkIdTypeArray>::New ();
selector->SetRenderer (renderer);
selector->SetArea (0, 0, xres - 1, yres - 1);
selector->Select ();
selector->GetSelectedIds (selection);
double visible_area = 0;
for (int sel_id = 3; sel_id < (selection->GetNumberOfTuples () * selection->GetNumberOfComponents ()); sel_id
+= selection->GetNumberOfComponents ())
{
int id_mesh = selection->GetValue (sel_id);
if (id_mesh >= polydata->GetNumberOfCells ())
continue;
vtkCell * cell = polydata->GetCell (id_mesh);
vtkTriangle* triangle = dynamic_cast<vtkTriangle*> (cell);
double p0[3];
double p1[3];
double p2[3];
triangle->GetPoints ()->GetPoint (0, p0);
triangle->GetPoints ()->GetPoint (1, p1);
triangle->GetPoints ()->GetPoint (2, p2);
visible_area += vtkTriangle::TriangleArea (p0, p1, p2);
}
#else
//THIS CAN BE USED WHEN VTK >= 5.4 IS REQUIRED... vtkVisibleCellSelector is deprecated from VTK5.4
vtkSmartPointer<vtkHardwareSelector> hardware_selector = vtkSmartPointer<vtkHardwareSelector>::New ();
hardware_selector->ClearBuffers ();
vtkSmartPointer<vtkSelection> hdw_selection = vtkSmartPointer<vtkSelection>::New ();
hardware_selector->SetRenderer (renderer);
hardware_selector->SetArea (0, 0, xres - 1, yres - 1);
hardware_selector->SetFieldAssociation (vtkDataObject::FIELD_ASSOCIATION_CELLS);
hdw_selection = hardware_selector->Select ();
if (!hdw_selection || !hdw_selection->GetNode (0) || !hdw_selection->GetNode (0)->GetSelectionList ())
{
PCL_WARN ("[renderViewTesselatedSphere] Invalid selection, skipping!\n");
continue;
}
vtkSmartPointer<vtkIdTypeArray> ids;
ids = vtkIdTypeArray::SafeDownCast (hdw_selection->GetNode (0)->GetSelectionList ());
if (!ids)
return;
double visible_area = 0;
for (int sel_id = 0; sel_id < (ids->GetNumberOfTuples ()); sel_id++)
{
int id_mesh = static_cast<int> (ids->GetValue (sel_id));
vtkCell * cell = polydata->GetCell (id_mesh);
vtkTriangle* triangle = dynamic_cast<vtkTriangle*> (cell);
if (!triangle)
{
PCL_WARN ("[renderViewTesselatedSphere] Invalid triangle %d, skipping!\n", id_mesh);
continue;
}
double p0[3];
double p1[3];
double p2[3];
triangle->GetPoints ()->GetPoint (0, p0);
triangle->GetPoints ()->GetPoint (1, p1);
triangle->GetPoints ()->GetPoint (2, p2);
area = vtkTriangle::TriangleArea (p0, p1, p2);
visible_area += area;
}
#endif
enthropies.push_back (static_cast<float> (visible_area / totalArea));
cloud->points.resize (count_valid_depth_pixels);
cloud->width = count_valid_depth_pixels;
//transform cloud to give camera coordinates instead of world coordinates!
vtkSmartPointer<vtkMatrix4x4> view_transform = cam_tmp->GetViewTransformMatrix ();
Eigen::Matrix4f trans_view;
trans_view.setIdentity ();
for (int x = 0; x < 4; x++)
for (int y = 0; y < 4; y++)
trans_view (x, y) = static_cast<float> (view_transform->GetElement (x, y));
//NOTE: vtk view coordinate system is different than the standard camera coordinates (z forward, y down, x right)
//thus, the fliping in y and z
for (size_t i = 0; i < cloud->points.size (); i++)
{
cloud->points[i].getVector4fMap () = trans_view * cloud->points[i].getVector4fMap ();
cloud->points[i].y *= -1.0f;
cloud->points[i].z *= -1.0f;
}
renderer->RemoveActor (actor_view);
clouds.push_back (*cloud);
//create pose, from OBJECT coordinates to CAMERA coordinates!
vtkSmartPointer<vtkTransform> transOCtoCC = vtkSmartPointer<vtkTransform>::New ();
transOCtoCC->PostMultiply ();
transOCtoCC->Identity ();
transOCtoCC->Concatenate (matrixCenter);
transOCtoCC->Concatenate (matrixRotModel);
transOCtoCC->Concatenate (matrixTranslation);
transOCtoCC->Concatenate (cam_tmp->GetViewTransformMatrix ());
//NOTE: vtk view coordinate system is different than the standard camera coordinates (z forward, y down, x right)
//thus, the fliping in y and z
vtkSmartPointer<vtkMatrix4x4> cameraSTD = vtkSmartPointer<vtkMatrix4x4>::New ();
cameraSTD->Identity ();
cameraSTD->SetElement (0, 0, 1);
cameraSTD->SetElement (1, 1, -1);
cameraSTD->SetElement (2, 2, -1);
transOCtoCC->Concatenate (cameraSTD);
transOCtoCC->Modified ();
Eigen::Matrix4f pose_view;
pose_view.setIdentity ();
for (int x = 0; x < 4; x++)
for (int y = 0; y < 4; y++)
pose_view (x, y) = static_cast<float> (transOCtoCC->GetMatrix ()->GetElement (x, y));
poses.push_back (pose_view);
}
}
///////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::renderView (int xres, int yres, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud)
{
if (rens_->GetNumberOfItems () > 1)
{
PCL_WARN ("[renderView] Method will render only the first viewport\n");
return;
}
win_->SetSize (xres, yres);
win_->Render ();
float dwidth = 2.0f / float (xres),
dheight = 2.0f / float (yres);
cloud->points.resize (xres * yres);
cloud->width = xres;
cloud->height = yres;
float *depth = new float[xres * yres];
win_->GetZbufferData (0, 0, xres - 1, yres - 1, &(depth[0]));
// Transform cloud to give camera coordinates instead of world coordinates!
vtkRenderer *ren = rens_->GetFirstRenderer ();
vtkCamera *camera = ren->GetActiveCamera ();
vtkSmartPointer<vtkMatrix4x4> composite_projection_transform = camera->GetCompositeProjectionTransformMatrix (ren->GetTiledAspectRatio (), 0, 1);
vtkSmartPointer<vtkMatrix4x4> view_transform = camera->GetViewTransformMatrix ();
Eigen::Matrix4f mat1, mat2;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
{
mat1 (i, j) = static_cast<float> (composite_projection_transform->Element[i][j]);
mat2 (i, j) = static_cast<float> (view_transform->Element[i][j]);
}
mat1 = mat1.inverse ().eval ();
int ptr = 0;
for (int y = 0; y < yres; ++y)
{
for (int x = 0; x < xres; ++x, ++ptr)
{
pcl::PointXYZ &pt = (*cloud)[ptr];
if (depth[ptr] == 1.0)
{
pt.x = pt.y = pt.z = std::numeric_limits<float>::quiet_NaN ();
continue;
}
Eigen::Vector4f world_coords (dwidth * float (x) - 1.0f,
dheight * float (y) - 1.0f,
depth[ptr],
1.0f);
world_coords = mat2 * mat1 * world_coords;
float w3 = 1.0f / world_coords[3];
world_coords[0] *= w3;
// vtk view coordinate system is different than the standard camera coordinates (z forward, y down, x right), thus, the fliping in y and z
world_coords[1] *= -w3;
world_coords[2] *= -w3;
pt.x = static_cast<float> (world_coords[0]);
pt.y = static_cast<float> (world_coords[1]);
pt.z = static_cast<float> (world_coords[2]);
}
}
delete[] depth;
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::fromHandlersToScreen (
const GeometryHandlerConstPtr &geometry_handler,
const ColorHandlerConstPtr &color_handler,
const std::string &id,
int viewport,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation)
{
if (!geometry_handler->isCapable ())
{
PCL_WARN ("[fromHandlersToScreen] PointCloud <%s> requested with an invalid geometry handler (%s)!\n", id.c_str (), geometry_handler->getName ().c_str ());
return (false);
}
if (!color_handler->isCapable ())
{
PCL_WARN ("[fromHandlersToScreen] PointCloud <%s> requested with an invalid color handler (%s)!\n", id.c_str (), color_handler->getName ().c_str ());
return (false);
}
vtkSmartPointer<vtkPolyData> polydata;
vtkSmartPointer<vtkIdTypeArray> initcells;
// Convert the PointCloud to VTK PolyData
convertPointCloudToVTKPolyData (geometry_handler, polydata, initcells);
// use the given geometry handler
// Get the colors from the handler
bool has_colors = false;
double minmax[2];
vtkSmartPointer<vtkDataArray> scalars;
if (color_handler->getColor (scalars))
{
polydata->GetPointData ()->SetScalars (scalars);
scalars->GetRange (minmax);
has_colors = true;
}
// Create an Actor
vtkSmartPointer<vtkLODActor> actor;
createActorFromVTKDataSet (polydata, actor);
if (has_colors)
actor->GetMapper ()->SetScalarRange (minmax);
// Add it to all renderers
addActorToRenderer (actor, viewport);
// Save the pointer/ID pair to the global actor map
CloudActor& cloud_actor = (*cloud_actor_map_)[id];
cloud_actor.actor = actor;
cloud_actor.cells = reinterpret_cast<vtkPolyDataMapper*>(actor->GetMapper ())->GetInput ()->GetVerts ()->GetData ();
cloud_actor.geometry_handlers.push_back (geometry_handler);
cloud_actor.color_handlers.push_back (color_handler);
// Save the viewpoint transformation matrix to the global actor map
vtkSmartPointer<vtkMatrix4x4> transformation = vtkSmartPointer<vtkMatrix4x4>::New ();
convertToVtkMatrix (sensor_origin, sensor_orientation, transformation);
cloud_actor.viewpoint_transformation_ = transformation;
cloud_actor.actor->SetUserMatrix (transformation);
cloud_actor.actor->Modified ();
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::updateCells (vtkSmartPointer<vtkIdTypeArray> &cells,
vtkSmartPointer<vtkIdTypeArray> &initcells,
vtkIdType nr_points)
{
// If no init cells and cells has not been initialized...
if (!cells)
cells = vtkSmartPointer<vtkIdTypeArray>::New ();
// If we have less values then we need to recreate the array
if (cells->GetNumberOfTuples () < nr_points)
{
cells = vtkSmartPointer<vtkIdTypeArray>::New ();
// If init cells is given, and there's enough data in it, use it
if (initcells && initcells->GetNumberOfTuples () >= nr_points)
{
cells->DeepCopy (initcells);
cells->SetNumberOfComponents (2);
cells->SetNumberOfTuples (nr_points);
}
else
{
// If the number of tuples is still too small, we need to recreate the array
cells->SetNumberOfComponents (2);
cells->SetNumberOfTuples (nr_points);
vtkIdType *cell = cells->GetPointer (0);
for (vtkIdType i = 0; i < nr_points; ++i, cell += 2)
{
*cell = 1;
*(cell + 1) = i;
}
// Save the results in initcells
initcells = vtkSmartPointer<vtkIdTypeArray>::New ();
initcells->DeepCopy (cells);
}
}
else
{
// The assumption here is that the current set of cells has more data than needed
cells->SetNumberOfComponents (2);
cells->SetNumberOfTuples (nr_points);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::allocVtkPolyData (vtkSmartPointer<vtkAppendPolyData> &polydata)
{
polydata = vtkSmartPointer<vtkAppendPolyData>::New ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::allocVtkPolyData (vtkSmartPointer<vtkPolyData> &polydata)
{
polydata = vtkSmartPointer<vtkPolyData>::New ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::allocVtkUnstructuredGrid (vtkSmartPointer<vtkUnstructuredGrid> &polydata)
{
polydata = vtkSmartPointer<vtkUnstructuredGrid>::New ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::getTransformationMatrix (
const Eigen::Vector4f &origin,
const Eigen::Quaternion<float> &orientation,
Eigen::Matrix4f &transformation)
{
transformation.setIdentity ();
transformation.block<3, 3> (0, 0) = orientation.toRotationMatrix ();
transformation.block<3, 1> (0, 3) = origin.head (3);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertToVtkMatrix (
const Eigen::Vector4f &origin,
const Eigen::Quaternion<float> &orientation,
vtkSmartPointer<vtkMatrix4x4> &vtk_matrix)
{
// set rotation
Eigen::Matrix3f rot = orientation.toRotationMatrix ();
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++)
vtk_matrix->SetElement (i, k, rot (i, k));
// set translation
vtk_matrix->SetElement (0, 3, origin (0));
vtk_matrix->SetElement (1, 3, origin (1));
vtk_matrix->SetElement (2, 3, origin (2));
vtk_matrix->SetElement (3, 3, 1.0f);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertToVtkMatrix (
const Eigen::Matrix4f &m,
vtkSmartPointer<vtkMatrix4x4> &vtk_matrix)
{
for (int i = 0; i < 4; i++)
for (int k = 0; k < 4; k++)
vtk_matrix->SetElement (i, k, m (i, k));
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::convertToEigenMatrix (
const vtkSmartPointer<vtkMatrix4x4> &vtk_matrix,
Eigen::Matrix4f &m)
{
for (int i = 0; i < 4; i++)
for (int k = 0; k < 4; k++)
m (i, k) = static_cast<float> (vtk_matrix->GetElement (i, k));
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPointCloud (
const pcl::PCLPointCloud2::ConstPtr &,
const GeometryHandlerConstPtr &geometry_handler,
const ColorHandlerConstPtr &color_handler,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation,
const std::string &id, int viewport)
{
// Check to see if this entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
// Here we're just pushing the handlers onto the queue. If needed, something fancier could
// be done such as checking if a specific handler already exists, etc.
am_it->second.geometry_handlers.push_back (geometry_handler);
am_it->second.color_handlers.push_back (color_handler);
return (true);
}
return (fromHandlersToScreen (geometry_handler, color_handler, id, viewport, sensor_origin, sensor_orientation));
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPointCloud (
const pcl::PCLPointCloud2::ConstPtr &cloud,
const GeometryHandlerConstPtr &geometry_handler,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation,
const std::string &id, int viewport)
{
// Check to see if this ID entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
// Here we're just pushing the handlers onto the queue. If needed, something fancier could
// be done such as checking if a specific handler already exists, etc.
am_it->second.geometry_handlers.push_back (geometry_handler);
return (true);
}
PointCloudColorHandlerCustom<pcl::PCLPointCloud2>::Ptr color_handler (new PointCloudColorHandlerCustom<pcl::PCLPointCloud2> (cloud, 255, 255, 255));
return (fromHandlersToScreen (geometry_handler, color_handler, id, viewport, sensor_origin, sensor_orientation));
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::addPointCloud (
const pcl::PCLPointCloud2::ConstPtr &cloud,
const ColorHandlerConstPtr &color_handler,
const Eigen::Vector4f& sensor_origin,
const Eigen::Quaternion<float>& sensor_orientation,
const std::string &id, int viewport)
{
// Check to see if this entry already exists (has it been already added to the visualizer?)
CloudActorMap::iterator am_it = cloud_actor_map_->find (id);
if (am_it != cloud_actor_map_->end ())
{
// Here we're just pushing the handlers onto the queue. If needed, something fancier could
// be done such as checking if a specific handler already exists, etc.
am_it->second.color_handlers.push_back (color_handler);
return (true);
}
PointCloudGeometryHandlerXYZ<pcl::PCLPointCloud2>::Ptr geometry_handler (new PointCloudGeometryHandlerXYZ<pcl::PCLPointCloud2> (cloud));
return (fromHandlersToScreen (geometry_handler, color_handler, id, viewport, sensor_origin, sensor_orientation));
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setFullScreen (bool mode)
{
if (win_)
win_->SetFullScreen (mode);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setWindowName (const std::string &name)
{
if (win_)
win_->SetWindowName (name.c_str ());
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setWindowBorders (bool mode)
{
if (win_)
win_->SetBorders (mode);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setPosition (int x, int y)
{
if (win_)
{
win_->SetPosition (x, y);
win_->Render ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setSize (int xw, int yw)
{
if (win_)
{
win_->SetSize (xw, yw);
win_->Render ();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::close ()
{
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
if (interactor_)
{
interactor_->stopped = true;
// This tends to close the window...
interactor_->stopLoop ();
}
#else
stopped_ = true;
// This tends to close the window...
win_->Finalize ();
if (interactor_)
interactor_->TerminateApp ();
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::removeCorrespondences (
const std::string &id, int viewport)
{
removeShape (id, viewport);
}
//////////////////////////////////////////////////////////////////////////////////////////////
int
pcl::visualization::PCLVisualizer::getColorHandlerIndex (const std::string &id)
{
CloudActorMap::iterator am_it = style_->getCloudActorMap ()->find (id);
if (am_it == cloud_actor_map_->end ())
return (-1);
return (am_it->second.color_handler_index_);
}
//////////////////////////////////////////////////////////////////////////////////////////////
int
pcl::visualization::PCLVisualizer::getGeometryHandlerIndex (const std::string &id)
{
CloudActorMap::iterator am_it = style_->getCloudActorMap ()->find (id);
if (am_it != cloud_actor_map_->end ())
return (-1);
return (am_it->second.geometry_handler_index_);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLVisualizer::wasStopped () const
{
if (interactor_ != NULL)
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
return (interactor_->stopped);
#else
return (stopped_);
#endif
else
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::resetStoppedFlag ()
{
if (interactor_ != NULL)
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
interactor_->stopped = false;
#else
stopped_ = false;
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setUseVbos (bool use_vbos)
{
#if VTK_RENDERING_BACKEND_OPENGL_VERSION < 2
use_vbos_ = use_vbos;
style_->setUseVbos (use_vbos_);
#else
PCL_WARN ("[PCLVisualizer::setUseVbos] Has no effect when OpenGL version is ≥ 2\n");
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::setLookUpTableID (const std::string id)
{
style_->lut_actor_id_ = id;
style_->updateLookUpTableDisplay (false);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::ExitMainLoopTimerCallback::Execute (
vtkObject*, unsigned long event_id, void* call_data)
{
if (event_id != vtkCommand::TimerEvent)
return;
int timer_id = *static_cast<int*> (call_data);
//PCL_WARN ("[pcl::visualization::PCLVisualizer::ExitMainLoopTimerCallback] Timer %d called.\n", timer_id);
if (timer_id != right_timer_id)
return;
// Stop vtk loop and send notification to app to wake it up
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
pcl_visualizer->interactor_->stopLoop ();
#else
pcl_visualizer->interactor_->TerminateApp ();
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::ExitCallback::Execute (
vtkObject*, unsigned long event_id, void*)
{
if (event_id != vtkCommand::ExitEvent)
return;
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
if (pcl_visualizer->interactor_)
{
pcl_visualizer->interactor_->stopped = true;
// This tends to close the window...
pcl_visualizer->interactor_->stopLoop ();
}
#else
pcl_visualizer->stopped_ = true;
// This tends to close the window...
if (pcl_visualizer->interactor_)
pcl_visualizer->interactor_->TerminateApp ();
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLVisualizer::FPSCallback::Execute (
vtkObject* caller, unsigned long, void*)
{
vtkRenderer *ren = reinterpret_cast<vtkRenderer *> (caller);
last_fps = 1.0f / static_cast<float> (ren->GetLastRenderTimeInSeconds ());
char buf[128];
sprintf (buf, "%.1f FPS", last_fps);
actor->SetInput (buf);
}
/////////////////////////////////////////////////////////////////////////////////////////////
int
pcl::visualization::PCLVisualizer::textureFromTexMaterial (const pcl::TexMaterial& tex_mat,
vtkTexture* vtk_tex) const
{
if (tex_mat.tex_file == "")
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] No texture file given for material %s!\n",
tex_mat.tex_name.c_str ());
return (-1);
}
boost::filesystem::path full_path (tex_mat.tex_file.c_str ());
if (!boost::filesystem::exists (full_path))
{
boost::filesystem::path parent_dir = full_path.parent_path ();
std::string upper_filename = tex_mat.tex_file;
boost::to_upper (upper_filename);
std::string real_name = "";
try
{
if (!boost::filesystem::exists (parent_dir))
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Parent directory '%s' doesn't exist!\n",
parent_dir.string ().c_str ());
return (-1);
}
if (!boost::filesystem::is_directory (parent_dir))
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Parent '%s' is not a directory !\n",
parent_dir.string ().c_str ());
return (-1);
}
typedef std::vector<boost::filesystem::path> paths_vector;
paths_vector paths;
std::copy (boost::filesystem::directory_iterator (parent_dir),
boost::filesystem::directory_iterator (),
back_inserter (paths));
for (paths_vector::const_iterator it = paths.begin (); it != paths.end (); ++it)
{
if (boost::filesystem::is_regular_file (*it))
{
std::string name = it->string ();
boost::to_upper (name);
if (name == upper_filename)
{
real_name = it->string ();
break;
}
}
}
// Check texture file existence
if (real_name == "")
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Can not find texture file %s!\n",
tex_mat.tex_file.c_str ());
return (-1);
}
}
catch (const boost::filesystem::filesystem_error& ex)
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Error %s when looking for file %s\n!",
ex.what (), tex_mat.tex_file.c_str ());
return (-1);
}
//Save the real path
full_path = real_name.c_str ();
}
std::string extension = full_path.extension ().string ();
//!!! nizar 20131206 : The list is far from being exhaustive I am afraid.
if ((extension == ".jpg") || (extension == ".JPG"))
{
vtkSmartPointer<vtkJPEGReader> jpeg_reader = vtkSmartPointer<vtkJPEGReader>::New ();
jpeg_reader->SetFileName (full_path.string ().c_str ());
jpeg_reader->Update ();
vtk_tex->SetInputConnection (jpeg_reader->GetOutputPort ());
}
else if ((extension == ".bmp") || (extension == ".BMP"))
{
vtkSmartPointer<vtkBMPReader> bmp_reader = vtkSmartPointer<vtkBMPReader>::New ();
bmp_reader->SetFileName (full_path.string ().c_str ());
bmp_reader->Update ();
vtk_tex->SetInputConnection (bmp_reader->GetOutputPort ());
}
else if ((extension == ".pnm") || (extension == ".PNM"))
{
vtkSmartPointer<vtkPNMReader> pnm_reader = vtkSmartPointer<vtkPNMReader>::New ();
pnm_reader->SetFileName (full_path.string ().c_str ());
pnm_reader->Update ();
vtk_tex->SetInputConnection (pnm_reader->GetOutputPort ());
}
else if ((extension == ".png") || (extension == ".PNG"))
{
vtkSmartPointer<vtkPNGReader> png_reader = vtkSmartPointer<vtkPNGReader>::New ();
png_reader->SetFileName (full_path.string ().c_str ());
png_reader->Update ();
vtk_tex->SetInputConnection (png_reader->GetOutputPort ());
}
else if ((extension == ".tiff") || (extension == ".TIFF"))
{
vtkSmartPointer<vtkTIFFReader> tiff_reader = vtkSmartPointer<vtkTIFFReader>::New ();
tiff_reader->SetFileName (full_path.string ().c_str ());
tiff_reader->Update ();
vtk_tex->SetInputConnection (tiff_reader->GetOutputPort ());
}
else
{
PCL_WARN ("[PCLVisualizer::textureFromTexMaterial] Unhandled image %s for material %s!\n",
full_path.c_str (), tex_mat.tex_name.c_str ());
return (-1);
}
return (0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
std::string
pcl::visualization::PCLVisualizer::getUniqueCameraFile (int argc, char **argv)
{
std::vector<int> p_file_indices;
boost::uuids::detail::sha1 sha1;
unsigned int digest[5];
const char *str;
std::ostringstream sstream;
bool valid = false;
p_file_indices = pcl::console::parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 0)
{
// Calculate sha1 using canonical paths
for (size_t i = 0; i < p_file_indices.size (); ++i)
{
boost::filesystem::path path (argv[p_file_indices[i]]);
if (boost::filesystem::exists (path))
{
#if BOOST_VERSION >= 104800
path = boost::filesystem::canonical (path);
#endif
str = path.string ().c_str ();
sha1.process_bytes (str, std::strlen (str));
valid = true;
}
}
// Build camera filename
if (valid)
{
sha1.get_digest (digest);
sstream << ".";
sstream << std::hex << digest[0] << digest[1] << digest[2] << digest[3] << digest[4];
sstream << ".cam";
}
}
return (sstream.str ());
}
|
/******************************************************************************
* Copyright (c) 2008 - 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Ungar, IBM Research - Initial Implementation
* Sam Adams, IBM Research - Initial Implementation
* Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems
******************************************************************************/
#include "headers.h"
void Abstract_Object_Heap::initialize() {
int size_in_oops = heap_byte_size() / sizeof(Oop);
int size_in_bytes = size_in_oops * sizeof(Oop);
initialize(allocate_my_space(size_in_bytes), size_in_bytes);
}
void Abstract_Object_Heap::initialize(void* mem, int size) {
_start = _next = (Oop*)mem;
_end = _next + size/sizeof(Oop);
zap_unused_portion();
lowSpaceThreshold = 1000;
}
// ObjectMemory object enumeration
Object* Abstract_Object_Heap::firstAccessibleObject() {
FOR_EACH_OBJECT_IN_HEAP(this, obj)
if (!obj->isFreeObject()) return obj;
return NULL;
}
Oop Abstract_Object_Heap::initialInstanceOf(Oop classPointer) {
// "Support for instance enumeration. Return the first instance of the given class, or nilObj if it has no instances."
FOR_EACH_OBJECT_IN_HEAP(this, obj)
if (!obj->isFreeObject() && obj->fetchClass() == classPointer )
return obj->as_oop();
return The_Squeak_Interpreter()->roots.nilObj;
}
Object* Abstract_Object_Heap::first_object_or_null() {
if (_start == _next)
return NULL;
return object_from_chunk((Chunk*)startOfMemory());
}
Object* Abstract_Object_Heap::first_object_without_preheader() {
if (_start == _next)
return NULL;
return object_from_chunk_without_preheader((Chunk*)startOfMemory());
}
bool Abstract_Object_Heap::verify() {
if (!is_initialized()) return true;
bool ok = true;
Object *prev_obj = NULL;
__attribute__((unused)) Object *prev_prev_obj = NULL; // debugging
FOR_EACH_OBJECT_IN_HEAP(this, obj) {
if (obj->is_marked()) {
lprintf("object 0x%x should not be marked but is; header is 0x%x, in heaps[%d][%d]\n",
obj, obj->baseHeader, obj->rank(), obj->mutability());
fatal("");
}
if (!obj->isFreeObject() && obj->is_current_copy())
ok = obj->verify() && ok;
prev_prev_obj = prev_obj;
prev_obj = obj;
}
dittoing_stdout_printer->printf("Object_Heap %sverified\n", ok ? "" : "NOT ");
return ok;
}
void Abstract_Object_Heap::check_multiple_stores_for_generations_only( Oop dsts[], oop_int_t n) {
return; // unused
for (oop_int_t i = 0; i < n; ++i)
check_store( &dsts[i] );
}
void Abstract_Object_Heap::multistore( Oop* dst, Oop* end, Oop src) {
multistore(dst, src, end - dst);
}
void Abstract_Object_Heap::multistore( Oop* dst, Oop src, oop_int_t n) {
assert(The_Memory_System()->contains(dst));
oopset_no_store_check(dst, src, n /* never read-mostly */);
check_multiple_stores_for_generations_only(dst, n);
}
void Abstract_Object_Heap::multistore( Oop* dst, Oop* src, oop_int_t n) {
assert(The_Memory_System()->contains(dst));
The_Memory_System()->enforce_coherence_before_store(dst, n << ShiftForWord /* never read-mostly */);
DEBUG_MULTIMOVE_CHECK(dst, src, n);
memmove(dst, src, n * bytes_per_oop);
The_Memory_System()->enforce_coherence_after_store(dst, n << ShiftForWord);
check_multiple_stores_for_generations_only(dst, n);
}
// verify does it anyway
void Abstract_Object_Heap::ensure_all_unmarked() {
FOR_EACH_OBJECT_IN_HEAP(this, obj)
assert_always(!obj->is_marked());
}
void Abstract_Object_Heap::do_all_oops(Oop_Closure* oc) {
FOR_EACH_OBJECT_IN_HEAP(this, obj)
obj->do_all_oops_of_object(oc);
}
void Abstract_Object_Heap::scan_compact_or_make_free_objects(bool compacting, Abstract_Mark_Sweep_Collector* gc_or_null) {
bool for_gc = gc_or_null != NULL;
// enforce mutability at higher level
if (for_gc || compacting)
The_Memory_System()->object_table->pre_store_whole_enchillada();
if (compacting) ++compactionsSinceLastQuery;
Chunk* dst_chunk = (Chunk*)startOfMemory();
for (__attribute__((unused))
Chunk *src_chunk = dst_chunk,
*next_src_chunk = NULL,
*prev_src_chunk = NULL; // prev is only for debugging
src_chunk < (Chunk*)end_objects();
prev_src_chunk = src_chunk, src_chunk = next_src_chunk) {
Object* obj = src_chunk->object_from_chunk();
next_src_chunk = obj->nextChunk();
if (obj->isFreeObject())
continue;
Oop oop = obj->as_oop();
if (for_gc) {
if (!obj->is_marked()) {
The_Memory_System()->object_table->free_oop(oop COMMA_FALSE_OR_NOTHING);
if (!compacting)
src_chunk->make_free_object((char*)next_src_chunk - (char*)src_chunk, 0);
continue;
}
obj->unmark_without_store_barrier();
}
if (!compacting)
continue;
Object_p new_obj_addr = (Object_p)(Object*)((char*)dst_chunk + ((char*)obj - (char*)src_chunk));
if (src_chunk == dst_chunk)
dst_chunk = next_src_chunk;
else {
The_Memory_System()->object_table->set_object_for(oop, new_obj_addr COMMA_FALSE_OR_NOTHING); // noop unless indirect oops
int n_oops = (Oop*)next_src_chunk - (Oop*)src_chunk;
// no mutability barrier wanted here, may need generational store barrier in the future
DEBUG_MULTIMOVE_CHECK(dst_chunk, src_chunk, n_oops);
memmove(dst_chunk, src_chunk, n_oops * sizeof(Oop));
src_chunk = next_src_chunk;
dst_chunk = (Chunk*)&((Oop*)dst_chunk)[n_oops];
}
}
if (compacting)
set_end_objects((Oop*)dst_chunk);
if (for_gc || compacting)
The_Memory_System()->object_table->post_store_whole_enchillada();
// enforce coherence at higher level
}
void Abstract_Object_Heap::zap_unused_portion() {
assert_always(end_of_space() != NULL);
if (check_many_assertions) {
enforce_coherence_before_store(end_objects(), (char*)end_of_space() - (char*)end_objects());
for (Oop* p = (Oop*)end_objects();
p < (Oop*)end_of_space();
*p++ = Oop::from_bits(Oop::Illegals::zapped)) {}
enforce_coherence_after_store(end_objects(), (char*)end_of_space() - (char*)end_objects());
}
}
void Abstract_Object_Heap::print(FILE*) {
lprintf("start 0x%x, next 0x%x, end 0x%x\n", _start, _next, _end);
}
Added a debugging printout for objects that failed to verify
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
/******************************************************************************
* Copyright (c) 2008 - 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Ungar, IBM Research - Initial Implementation
* Sam Adams, IBM Research - Initial Implementation
* Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems
******************************************************************************/
#include "headers.h"
void Abstract_Object_Heap::initialize() {
int size_in_oops = heap_byte_size() / sizeof(Oop);
int size_in_bytes = size_in_oops * sizeof(Oop);
initialize(allocate_my_space(size_in_bytes), size_in_bytes);
}
void Abstract_Object_Heap::initialize(void* mem, int size) {
_start = _next = (Oop*)mem;
_end = _next + size/sizeof(Oop);
zap_unused_portion();
lowSpaceThreshold = 1000;
}
// ObjectMemory object enumeration
Object* Abstract_Object_Heap::firstAccessibleObject() {
FOR_EACH_OBJECT_IN_HEAP(this, obj)
if (!obj->isFreeObject()) return obj;
return NULL;
}
Oop Abstract_Object_Heap::initialInstanceOf(Oop classPointer) {
// "Support for instance enumeration. Return the first instance of the given class, or nilObj if it has no instances."
FOR_EACH_OBJECT_IN_HEAP(this, obj)
if (!obj->isFreeObject() && obj->fetchClass() == classPointer )
return obj->as_oop();
return The_Squeak_Interpreter()->roots.nilObj;
}
Object* Abstract_Object_Heap::first_object_or_null() {
if (_start == _next)
return NULL;
return object_from_chunk((Chunk*)startOfMemory());
}
Object* Abstract_Object_Heap::first_object_without_preheader() {
if (_start == _next)
return NULL;
return object_from_chunk_without_preheader((Chunk*)startOfMemory());
}
bool Abstract_Object_Heap::verify() {
if (!is_initialized()) return true;
bool ok = true;
Object *prev_obj = NULL;
__attribute__((unused)) Object *prev_prev_obj = NULL; // debugging
FOR_EACH_OBJECT_IN_HEAP(this, obj) {
if (obj->is_marked()) {
lprintf("object 0x%x should not be marked but is; header is 0x%x, in heaps[%d][%d]\n",
obj, obj->baseHeader, obj->rank(), obj->mutability());
fatal("");
}
if (!obj->isFreeObject() && obj->is_current_copy())
ok = obj->verify() && ok;
if (not ok) dittoing_stdout_printer->printf("Failed to verify obj at %p\n", obj);
prev_prev_obj = prev_obj;
prev_obj = obj;
}
dittoing_stdout_printer->printf("Object_Heap %sverified\n", ok ? "" : "NOT ");
return ok;
}
void Abstract_Object_Heap::check_multiple_stores_for_generations_only( Oop dsts[], oop_int_t n) {
return; // unused
for (oop_int_t i = 0; i < n; ++i)
check_store( &dsts[i] );
}
void Abstract_Object_Heap::multistore( Oop* dst, Oop* end, Oop src) {
multistore(dst, src, end - dst);
}
void Abstract_Object_Heap::multistore( Oop* dst, Oop src, oop_int_t n) {
assert(The_Memory_System()->contains(dst));
oopset_no_store_check(dst, src, n /* never read-mostly */);
check_multiple_stores_for_generations_only(dst, n);
}
void Abstract_Object_Heap::multistore( Oop* dst, Oop* src, oop_int_t n) {
assert(The_Memory_System()->contains(dst));
The_Memory_System()->enforce_coherence_before_store(dst, n << ShiftForWord /* never read-mostly */);
DEBUG_MULTIMOVE_CHECK(dst, src, n);
memmove(dst, src, n * bytes_per_oop);
The_Memory_System()->enforce_coherence_after_store(dst, n << ShiftForWord);
check_multiple_stores_for_generations_only(dst, n);
}
// verify does it anyway
void Abstract_Object_Heap::ensure_all_unmarked() {
FOR_EACH_OBJECT_IN_HEAP(this, obj)
assert_always(!obj->is_marked());
}
void Abstract_Object_Heap::do_all_oops(Oop_Closure* oc) {
FOR_EACH_OBJECT_IN_HEAP(this, obj)
obj->do_all_oops_of_object(oc);
}
void Abstract_Object_Heap::scan_compact_or_make_free_objects(bool compacting, Abstract_Mark_Sweep_Collector* gc_or_null) {
bool for_gc = gc_or_null != NULL;
// enforce mutability at higher level
if (for_gc || compacting)
The_Memory_System()->object_table->pre_store_whole_enchillada();
if (compacting) ++compactionsSinceLastQuery;
Chunk* dst_chunk = (Chunk*)startOfMemory();
for (__attribute__((unused))
Chunk *src_chunk = dst_chunk,
*next_src_chunk = NULL,
*prev_src_chunk = NULL; // prev is only for debugging
src_chunk < (Chunk*)end_objects();
prev_src_chunk = src_chunk, src_chunk = next_src_chunk) {
Object* obj = src_chunk->object_from_chunk();
next_src_chunk = obj->nextChunk();
if (obj->isFreeObject())
continue;
Oop oop = obj->as_oop();
if (for_gc) {
if (!obj->is_marked()) {
The_Memory_System()->object_table->free_oop(oop COMMA_FALSE_OR_NOTHING);
if (!compacting)
src_chunk->make_free_object((char*)next_src_chunk - (char*)src_chunk, 0);
continue;
}
obj->unmark_without_store_barrier();
}
if (!compacting)
continue;
Object_p new_obj_addr = (Object_p)(Object*)((char*)dst_chunk + ((char*)obj - (char*)src_chunk));
if (src_chunk == dst_chunk)
dst_chunk = next_src_chunk;
else {
The_Memory_System()->object_table->set_object_for(oop, new_obj_addr COMMA_FALSE_OR_NOTHING); // noop unless indirect oops
int n_oops = (Oop*)next_src_chunk - (Oop*)src_chunk;
// no mutability barrier wanted here, may need generational store barrier in the future
DEBUG_MULTIMOVE_CHECK(dst_chunk, src_chunk, n_oops);
memmove(dst_chunk, src_chunk, n_oops * sizeof(Oop));
src_chunk = next_src_chunk;
dst_chunk = (Chunk*)&((Oop*)dst_chunk)[n_oops];
}
}
if (compacting)
set_end_objects((Oop*)dst_chunk);
if (for_gc || compacting)
The_Memory_System()->object_table->post_store_whole_enchillada();
// enforce coherence at higher level
}
void Abstract_Object_Heap::zap_unused_portion() {
assert_always(end_of_space() != NULL);
if (check_many_assertions) {
enforce_coherence_before_store(end_objects(), (char*)end_of_space() - (char*)end_objects());
for (Oop* p = (Oop*)end_objects();
p < (Oop*)end_of_space();
*p++ = Oop::from_bits(Oop::Illegals::zapped)) {}
enforce_coherence_after_store(end_objects(), (char*)end_of_space() - (char*)end_objects());
}
}
void Abstract_Object_Heap::print(FILE*) {
lprintf("start 0x%x, next 0x%x, end 0x%x\n", _start, _next, _end);
}
|
////////////////////////////////////////////////////////////////////////
//
// Harvard University
// CS175 : Computer Graphics
// Professor Steven Gortler
//
////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <cstddef>
#include <vector>
#include <math.h>
#include <string>
#include <memory>
#include <stdexcept>
#include <list>
#if __GNUG__
# include <tr1/memory>
#endif
#ifdef __MAC__
# include <OpenGL/gl3.h>
# include <GLUT/glut.h>
#else
# include <GL/glew.h>
# include <GL/glut.h>
#endif
#include "ppm.h"
#include "cvec.h"
#include "matrix4.h"
#include "rigtform.h"
#include "glsupport.h"
#include "geometrymaker.h"
#include "arcball.h"
#include "scenegraph.h"
#include "asstcommon.h"
#include "drawer.h"
#include "picker.h"
#include "sgutils.h"
#include "geometry.h"
#include "mesh.h"
using namespace std;
using namespace tr1;
#define KF_UNDEF -1
// G L O B A L S ///////////////////////////////////////////////////
// --------- IMPORTANT --------------------------------------------------------
// Before you start working on this assignment, set the following variable
// properly to indicate whether you want to use OpenGL 2.x with GLSL 1.0 or
// OpenGL 3.x+ with GLSL 1.5.
//
// Set g_Gl2Compatible = true to use GLSL 1.0 and g_Gl2Compatible = false to
// use GLSL 1.5. Use GLSL 1.5 unless your system does not support it.
//
// If g_Gl2Compatible=true, shaders with -gl2 suffix will be loaded.
// If g_Gl2Compatible=false, shaders with -gl3 suffix will be loaded.
// To complete the assignment you only need to edit the shader files that get
// loaded
// ----------------------------------------------------------------------------
#ifdef __MAC__
const bool g_Gl2Compatible = false;
#else
const bool g_Gl2Compatible = true;
#endif
static const float g_frustMinFov = 60.0; // A minimal of 60 degree field of view
static float g_frustFovY = g_frustMinFov; // FOV in y direction (updated by updateFrustFovY)
static const float g_frustNear = -0.1; // near plane
static const float g_frustFar = -50.0; // far plane
static const float g_groundY = -2.0; // y coordinate of the ground
static const float g_groundSize = 10.0; // half the ground length
static const int g_divcap = 6;
enum SkyMode {WORLD_SKY=0, SKY_SKY=1};
static double g_horiz_scale = 4.0;
static int g_div_level = 0;
static int g_windowWidth = 512;
static int g_windowHeight = 512;
static bool g_mouseClickDown = false; // is the mouse button pressed
static bool g_mouseLClickButton, g_mouseRClickButton, g_mouseMClickButton;
static bool g_spaceDown = false; // space state, for middle mouse emulation
static bool g_flat = false; // smooth vs flat shading
static int g_mouseClickX, g_mouseClickY; // coordinates for mouse click event
static int g_activeShader = 0;
static Mesh cubeMesh;
static vector<double> vertex_speeds;
static vector<vector<int> > vertex_signs;
static bool meshLoaded = false;
static SkyMode g_activeCameraFrame = WORLD_SKY;
static bool g_displayArcball = true;
static double g_arcballScreenRadius = 100; // number of pixels
static double g_arcballScale = 1;
static bool g_pickingMode = false;
// -------- Shaders
static shared_ptr<Material> g_redDiffuseMat,
g_blueDiffuseMat,
g_bumpFloorMat,
g_arcballMat,
g_pickingMat,
g_lightMat,
g_specular,
g_bunnyMat;
shared_ptr<Material> g_overridingMaterial;
static vector<shared_ptr<Material> > g_bunnyShellMats; // for bunny shells
// New Geometry
static const int g_numShells = 24; // constants defining how many layers of shells
static double g_furHeight = 0.21;
static double g_hairyness = 0.7;
static shared_ptr<SimpleGeometryPN> g_bunnyGeometry;
static vector<shared_ptr<SimpleGeometryPNX> > g_bunnyShellGeometries;
static Mesh g_bunnyMesh;
// New Scene node
static shared_ptr<SgRbtNode> g_bunnyNode;
// linked list of frame vectors
static list<vector<RigTForm> > key_frames;
static int cur_frame = -1;
// --------- Geometry
typedef SgGeometryShapeNode MyShapeNode;
// Vertex buffer and index buffer associated with the ground and cube geometry
static shared_ptr<Geometry> g_ground, g_cube, g_sphere;
static shared_ptr<SimpleGeometryPN> g_cubeGeometryPN;
// --------- Scene
static const Cvec3 g_light1(2.0, 3.0, 14.0), g_light2(-2, 3.0, -14.0); // define two lights positions in world space
static shared_ptr<SgTransformNode> g_light1Node, g_light2Node;
static shared_ptr<SgRootNode> g_world;
static shared_ptr<SgRbtNode> g_skyNode, g_groundNode, g_mesh_cube, g_robot1Node, g_robot2Node;
static shared_ptr<SgRbtNode> g_currentCameraNode;
static shared_ptr<SgRbtNode> g_currentPickedRbtNode;
static int g_msBetweenKeyFrames = 2000;
static int g_animateFramesPerSecond = 60;
static bool animating = false;
static const Cvec3 g_gravity(0, -0.5, 0); // gavity vector
static double g_timeStep = 0.02;
static double g_numStepsPerFrame = 10;
static double g_damping = 0.96;
static double g_stiffness = 4;
static int g_simulationsPerSecond = 60;
static std::vector<Cvec3> g_tipPos, // should be hair tip pos in world-space coordinates
g_tipVelocity; // should be hair tip velocity in world-space coordinates
///////////////// END OF G L O B A L S //////////////////////////////////////////////////
static void updateShellGeometry() {
// TASK 1 and 3 TODO: finish this function as part of Task 1 and Task 3
}
static void hairsSimulationCallback(int dontCare) {
// TASK 2 TODO: wrte dynamics simulation code here as part of TASK2
// schedule this to get called again
glutTimerFunc(1000/g_simulationsPerSecond, hairsSimulationCallback, 0);
glutPostRedisplay(); // signal redisplaying
}
// New function that initialize the dynamics simulation
static void initSimulation() {
g_tipPos.resize(g_bunnyMesh.getNumVertices(), Cvec3(0));
g_tipVelocity = g_tipPos;
// TASK 1 TODO: initialize g_tipPos to "at-rest" hair tips in world coordinates
// Starts hair tip simulation
hairsSimulationCallback(0);
}
static void make_frame() {
vector<shared_ptr<SgRbtNode> > graph_vector;
dumpSgRbtNodes(g_world, graph_vector);
vector<RigTForm> new_frame;
for (int i = 0; i < graph_vector.size(); ++i) {
new_frame.push_back(graph_vector[i]->getRbt());
}
if (cur_frame == KF_UNDEF || cur_frame == key_frames.size() - 1) {
// undef is -1, so adding one sets the position to 0
key_frames.push_back(new_frame);
++cur_frame;
}
else {
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
key_frames.insert(it, new_frame);
++cur_frame;
}
return;
}
static void next_frame() {
if (cur_frame == KF_UNDEF || cur_frame == key_frames.size() - 1) {
cout << "can't advance frame" << endl;
return;
}
++cur_frame;
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
// this linked list of arrays is getting the previous vectors stacked on top of each other
fillSgRbtNodes(g_world, *it);
return;
}
static void prev_frame() {
if (cur_frame < 1) {
cout << "can't rewind frame "<< endl;
return;
}
--cur_frame;
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
fillSgRbtNodes(g_world, *it);
return;
}
static void delete_frame() {
if (cur_frame == KF_UNDEF) {
return;
}
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
key_frames.erase(it);
if (key_frames.empty()) {
cur_frame = KF_UNDEF;
return;
}
else if (cur_frame != 0) {
--cur_frame;
}
fillSgRbtNodes(g_world, *it);
return;
}
static void write_frame() {
list<vector<RigTForm> >::iterator it = key_frames.begin();
FILE* output = fopen("animation.txt", "w");
int n = (*it).size();
fprintf(output, "%d %d\n", key_frames.size(), n);
while (it != key_frames.end()) {
vector<RigTForm> frame = *it;
for (int i = 0; i < frame.size(); ++i) {
RigTForm r = frame[i];
Cvec3 transFact = r.getTranslation();
Quat linFact = r.getRotation();
fprintf(output, "%.3f %.3f %.3f %.3f %.3f %.3f %.3f\n",
transFact[0], transFact[1], transFact[2],
linFact[0], linFact[1], linFact[2], linFact[3]
);
}
++it;
}
fclose(output);
}
static void read_frame() {
FILE* input = fopen("animation.txt", "r");
if (input == NULL) {
return;
}
int nFrames;
int nRbts;
fscanf(input, "%d %d\n", &nFrames, &nRbts);
key_frames.clear();
for (int i = 0; i < nFrames; ++i) {
vector<RigTForm> frame;
for (int j = 0; j < nRbts; ++j) {
Cvec3 transFact;
Quat linFact;
fscanf(input, "%lf %lf %lf %lf %lf %lf %lf\n",
&transFact[0], &transFact[1], &transFact[2],
&linFact[0], &linFact[1], &linFact[2], &linFact[3]
);
RigTForm r = RigTForm(transFact, linFact);
frame.push_back(r);
}
key_frames.push_back(frame);
}
cur_frame = 0;
fillSgRbtNodes(g_world, key_frames.front());
fclose(input);
}
static Quat slerp(Quat src, Quat dest, float alpha);
static Cvec3 lerp(Cvec3 src, Cvec3 dest, float alpha);
static Quat cond_neg(Quat q);
static Quat qpow(Quat q, float alpha);
Cvec3 getDTrans(Cvec3 c_i_1, Cvec3 c_i_neg_1, Cvec3 c_i) {
return (c_i_1 - c_i_neg_1)/6 + c_i;
}
Cvec3 getETrans(Cvec3 c_i_2, Cvec3 c_i_1, Cvec3 c_i) {
return (c_i_2 - c_i)/-6 + c_i_1;
}
Cvec3 bezierTrans(Cvec3 c_i_neg_1, Cvec3 c_i, Cvec3 c_i_1, Cvec3 c_i_2, int i, float t) {
Cvec3 d = getDTrans(c_i_1, c_i_neg_1, c_i);
Cvec3 e = getETrans(c_i_2, c_i_1, c_i);
Cvec3 f = c_i*(1 - t + i) + d*(t - i);
Cvec3 g = d*(1 - t + i) + e*(t - i);
Cvec3 h = e*(1 - t + i) + c_i_1*(t - i);
Cvec3 m = f*(1 - t + i) + g*(t - i);
Cvec3 n = g*(1 - t + i) + h*(t - i);
return m*(1 - t + i) + n*(t - i);
}
Quat getDRot(Quat c_i_1, Quat c_i_neg_1, Quat c_i) {
return qpow(cond_neg(c_i_1 * inv(c_i_neg_1)), 1.0/6.0) * c_i;
}
Quat getERot(Quat c_i_2, Quat c_i_1, Quat c_i) {
return qpow(cond_neg(c_i_2 * inv(c_i)), -1.0/6.0) * c_i_1;
}
Quat bezierRot(Quat c_i_neg_1, Quat c_i, Quat c_i_1, Quat c_i_2, int i, float t) {
Quat d = getDRot(c_i_1, c_i_neg_1, c_i);
Quat e = getERot(c_i_2, c_i_1, c_i);
Quat f = slerp(c_i, d, t -i);
Quat g = slerp(d, e, t - i);
Quat h = slerp(e, c_i_1, t - i);
Quat m = slerp(f, g, t - i);
Quat n = slerp(g, h, t - i);
return slerp(m, n, t - i);
}
bool interpolateAndDisplay(float t) {
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, (int) t);
++it;
vector<RigTForm> frame_1 = *it;
++it;
vector<RigTForm> frame_2 = *it;
++it;
if (it == key_frames.end()) {
return true;
}
vector<RigTForm> post_frame = *it;
// minus operator not overloaded for iterators. sad face.
--it; --it; --it;
vector<RigTForm> pre_frame = *it;
// d ci ci+1 e
float alpha = t - (int) t;
vector<RigTForm> frame;
int n = frame_1.size();
for (int i = 0; i < n; ++i) {
Cvec3 c_i_neg_1 = pre_frame[i].getTranslation();
Cvec3 c_i = frame_1[i].getTranslation();
Cvec3 c_i_1 = frame_2[i].getTranslation();
Cvec3 c_i_2 = post_frame[i].getTranslation();
Quat c_i_neg_1_r = pre_frame[i].getRotation();
Quat c_i_r = frame_1[i].getRotation();
Quat c_i_1_r = frame_2[i].getRotation();
Quat c_i_2_r = post_frame[i].getRotation();
Cvec3 trans = bezierTrans(c_i_neg_1, c_i, c_i_1, c_i_2, (int) t, t);
Quat rot = bezierRot(c_i_neg_1_r, c_i_r, c_i_1_r, c_i_2_r, (int) t, t);
frame.push_back(RigTForm(trans, rot));
}
fillSgRbtNodes(g_world, frame);
glutPostRedisplay();
return false;
}
static void animateTimerCallback(int ms) {
float t = (float) ms / (float) g_msBetweenKeyFrames;
bool endReached = interpolateAndDisplay(t);
if (!endReached) {
glutTimerFunc(1000/g_animateFramesPerSecond,
animateTimerCallback,
ms + 1000/g_animateFramesPerSecond);
}
else {
animating = false;
cur_frame = key_frames.size() - 2;
glutPostRedisplay();
}
}
static Cvec3 getFaceVertex(vector<Cvec3> & verts) {
// pass in the n vertices surrounding a face
float m_f = (float(1)/verts.size());
Cvec3 out = Cvec3 (0,0,0);
for (int i = 0; i < verts.size(); ++i) {
out += verts[i];
}
out *= m_f;
return out;
}
static Cvec3 getEdgeVertex(vector<Cvec3> & verts) {
// pass in two vertices on an edge, and the two face vertices of the
// faces they have in common
return getFaceVertex(verts);
}
static Cvec3 getVertexVertex(Cvec3 v, vector<Cvec3> & verts, vector<Cvec3> & faceverts) {
// pass in a vertex v, adjacent vertices verts, and
// the vertices of all adjacent faces faceverts.
Cvec3 out = Cvec3(0,0,0);
int n_v = verts.size();
out += v * (float(n_v - 2) / n_v);
Cvec3 out2 = Cvec3(0,0,0);
for (int i = 0; i < n_v; ++i) {
out2 += verts[i] + faceverts[i];
}
return out + (out2 * (float(1)/(n_v * n_v)));
}
static void simpleShadeCube(Mesh& mesh);
static void shadeCube(Mesh& mesh);
static void initBunnyMeshes() {
g_bunnyMesh.load("bunny.mesh");
// TODO: Init the per vertex normal of g_bunnyMesh, using codes from asst7
// ...
shadeCube(g_bunnyMesh);
// cout << "Finished shading bunny" << endl;
// TODO: Initialize g_bunnyGeometry from g_bunnyMesh, similar to
vector<VertexPN> verts;
for (int i = 0; i < g_bunnyMesh.getNumFaces(); ++i) {
const Mesh::Face f = g_bunnyMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
if (g_flat)
normal = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// add vertices to bunny geometry
int numVertices = verts.size();
VertexPN *vertices = (VertexPN *) malloc(numVertices * sizeof(VertexPN));
for (int i = 0; i < numVertices; ++i) {
Cvec3f pos = verts[i].p;
vertices[i] = verts[i];
}
g_bunnyGeometry.reset(new SimpleGeometryPN());
g_bunnyGeometry->upload(vertices, numVertices);
// Now allocate array of SimpleGeometryPNX to for shells, one per layer
g_bunnyShellGeometries.resize(g_numShells);
for (int i = 0; i < g_numShells; ++i) {
g_bunnyShellGeometries[i].reset(new SimpleGeometryPNX());
}
}
static void initGround() {
int ibLen, vbLen;
getPlaneVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makePlane(g_groundSize*2, vtx.begin(), idx.begin());
g_ground.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void simpleShadeCube(Mesh& mesh) {
Cvec3 normal = Cvec3(0, 1, 0);
for (int i = 0; i < mesh.getNumFaces(); ++i) {
const Mesh::Face f = mesh.getFace(i);
Cvec3 facenorm = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
v.setNormal(facenorm);
}
}
}
static void shadeCube(Mesh& mesh) {
Cvec3 normal = Cvec3(0, 0, 0);
for (int i = 0; i < mesh.getNumVertices(); ++i) {
mesh.getVertex(i).setNormal(normal);
}
for (int i = 0; i < mesh.getNumFaces(); ++i) {
const Mesh::Face f = mesh.getFace(i);
Cvec3 facenorm = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
v.setNormal(facenorm + v.getNormal());
}
}
for (int i = 0; i < mesh.getNumVertices(); ++i) {
const Mesh::Vertex v = mesh.getVertex(i);
v.setNormal(normalize(v.getNormal()));
}
}
void collectEdgeVertices(Mesh& m);
void collectFaceVertices(Mesh& m);
void collectVertexVertices(Mesh& m);
static void initCubeMesh() {
if (!meshLoaded) {
cubeMesh.load("./cube.mesh");
meshLoaded = true;
}
// set normals
shadeCube(cubeMesh);
// collect vertices from each face and map quads to triangles
vector<VertexPN> verts;
for (int i = 0; i < cubeMesh.getNumFaces(); ++i) {
const Mesh::Face f = cubeMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
if (g_flat)
normal = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// add vertices to cube geometry
int numVertices = verts.size();
VertexPN *vertices = (VertexPN *) malloc(numVertices * sizeof(VertexPN));
for (int i = 0; i < numVertices; ++i) {
Cvec3f pos = verts[i].p;
vertices[i] = verts[i];
}
if (!g_cubeGeometryPN) {
g_cubeGeometryPN.reset(new SimpleGeometryPN());
}
g_cubeGeometryPN->upload(vertices, numVertices);
}
static void initCubeAnimation() {
// set the speeds of each vertex
srand(time(NULL));
for (int i = 0; i < cubeMesh.getNumVertices(); ++i) {
// create random speed
vertex_speeds.push_back((double) rand() / RAND_MAX);
Cvec3 pos = cubeMesh.getVertex(i).getPosition();
// store sign
int xSign = (pos[0] < 0) ? -1 : 1;
int ySign = (pos[1] < 0) ? -1 : 1;
int zSign = (pos[2] < 0) ? -1 : 1;
vector<int> signs;
signs.push_back(xSign);
signs.push_back(ySign);
signs.push_back(zSign);
vertex_signs.push_back(signs);
}
}
static void initCubes() {
int ibLen, vbLen;
getCubeVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeCube(1, vtx.begin(), idx.begin());
g_cube.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void initSphere() {
int ibLen, vbLen;
getSphereVbIbLen(20, 10, vbLen, ibLen);
// Temporary storage for sphere Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeSphere(1, 20, 10, vtx.begin(), idx.begin());
g_sphere.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vtx.size(), idx.size()));
}
static void initRobots() {
// Init whatever geometry needed for the robots
}
// takes a projection matrix and send to the the shaders
inline void sendProjectionMatrix(Uniforms& uniforms, const Matrix4& projMatrix) {
uniforms.put("uProjMatrix", projMatrix);
}
// update g_frustFovY from g_frustMinFov, g_windowWidth, and g_windowHeight
static void updateFrustFovY() {
if (g_windowWidth >= g_windowHeight)
g_frustFovY = g_frustMinFov;
else {
const double RAD_PER_DEG = 0.5 * CS175_PI/180;
g_frustFovY = atan2(sin(g_frustMinFov * RAD_PER_DEG) * g_windowHeight / g_windowWidth, cos(g_frustMinFov * RAD_PER_DEG)) / RAD_PER_DEG;
}
}
static void animateCube(int ms) {
float t = (float) ms / (float) g_msBetweenKeyFrames;
// scale all vertices in cube
for (int i = 0; i < cubeMesh.getNumVertices(); ++i) {
const Mesh::Vertex v = cubeMesh.getVertex(i);
Cvec3 pos = v.getPosition();
double factor = (1 + (float(g_div_level)/10)) * ((-1 * sin((double) (g_horiz_scale * ms) / (1000 * (vertex_speeds[i] + .5))) + 1) / 2 + .5);
pos[0] = vertex_signs[i][0] * (factor / sqrt(3));
pos[1] = vertex_signs[i][1] * (factor / sqrt(3));
pos[2] = vertex_signs[i][2] * (factor / sqrt(3));
v.setPosition(pos);
}
// copy mesh to temporary mesh for rendering
Mesh renderMesh = cubeMesh;
// subdivision
for (int i = 0; i < g_div_level; ++i) {
collectFaceVertices(renderMesh);
collectEdgeVertices(renderMesh);
collectVertexVertices(renderMesh);
renderMesh.subdivide();
}
// set normals
shadeCube(renderMesh);
// collect vertices for each face
vector<VertexPN> verts;
int q = 0;
for (int i = 0; i < renderMesh.getNumFaces(); ++i) {
const Mesh::Face f = renderMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
else
normal = f.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
else
normal = f.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// dump into geometry
int numVertices = verts.size();
VertexPN *vertices = (VertexPN *) malloc(numVertices * sizeof(VertexPN));
for (int i = 0; i < numVertices; ++i) {
Cvec3f pos = verts[i].p;
vertices[i] = verts[i];
}
g_cubeGeometryPN->upload(vertices, numVertices);
glutPostRedisplay();
glutTimerFunc(1000/g_animateFramesPerSecond,
animateCube,
ms + 1000/g_animateFramesPerSecond);
}
void collectFaceVertices(Mesh& m) {
for (int i = 0; i < m.getNumFaces(); ++i) {
Mesh::Face f = m.getFace(i);
vector<Cvec3> vertices;
for (int j = 0; j < f.getNumVertices(); ++j) {
vertices.push_back(f.getVertex(j).getPosition());
}
m.setNewFaceVertex(f, getFaceVertex(vertices));
}
}
void collectEdgeVertices(Mesh& m) {
for (int i = 0; i < m.getNumEdges(); ++i) {
Mesh::Edge e = m.getEdge(i);
// get faces adjacent to edges
Cvec3 f0 = m.getNewFaceVertex(e.getFace(0));
Cvec3 f1 = m.getNewFaceVertex(e.getFace(1));
Cvec3 pos0 = e.getVertex(0).getPosition();
Cvec3 pos1 = e.getVertex(1).getPosition();
vector<Cvec3> vertices;
vertices.push_back(f0);
vertices.push_back(f1);
vertices.push_back(pos0);
vertices.push_back(pos1);
Cvec3 newEdge = getEdgeVertex(vertices);
m.setNewEdgeVertex(e, newEdge);
}
}
void collectVertexVertices(Mesh& m) {
vector<vector<Cvec3> > vertexVertices;
for (int i = 0; i < m.getNumVertices(); ++i) {
const Mesh::Vertex v = m.getVertex(i);
Mesh::VertexIterator it(v.getIterator()), it0(it);
vector<Cvec3> vertices;
vector<Cvec3> faces;
do {
vertices.push_back(it.getVertex().getPosition());
faces.push_back(m.getNewFaceVertex(it.getFace()));
}
while (++it != it0); // go around once the 1ring
Cvec3 vertex = getVertexVertex(v.getPosition(), vertices, faces);
m.setNewVertexVertex(v, vertex);
}
}
static Cvec3 lerp(Cvec3 src, Cvec3 dest, float alpha) {
assert(0 <= alpha && alpha <= 1.0);
float xout = ((1-alpha) * src[0]) + (alpha * dest[0]);
float yout = ((1-alpha) * src[1]) + (alpha * dest[1]);
float zout = ((1-alpha) * src[2]) + (alpha * dest[2]);
return Cvec3(xout, yout, zout);
}
static Quat cond_neg(Quat q) {
if (q[0] < 0) {
return Quat(-q[0], -q[1], -q[2], -q[3]);
}
return q;
}
static Quat qpow(Quat q, float alpha) {
Cvec3 axis = Cvec3(q[1], q[2], q[3]);
float theta = atan2(sqrt(norm2(axis)), q[0]);
if (norm2(axis) <= .001) {
return Quat();
}
axis = normalize(axis);
float q_outw = cos(alpha * theta);
float q_outx = axis[0] * sin(alpha * theta);
float q_outy = axis[1] * sin(alpha * theta);
float q_outz = axis[2] * sin(alpha * theta);
return normalize(Quat(q_outw, q_outx, q_outy, q_outz));
}
static Quat slerp(Quat src, Quat dest, float alpha) {
assert(0 <= alpha && alpha <= 1.0);
return normalize(qpow(cond_neg(dest * inv(src)), alpha) * src);
}
static Matrix4 makeProjectionMatrix() {
return Matrix4::makeProjection(
g_frustFovY, g_windowWidth / static_cast <double> (g_windowHeight),
g_frustNear, g_frustFar);
}
enum ManipMode {
ARCBALL_ON_PICKED,
ARCBALL_ON_SKY,
EGO_MOTION
};
static ManipMode getManipMode() {
// if nothing is picked or the picked transform is the transfrom we are viewing from
if (g_currentPickedRbtNode == NULL || g_currentPickedRbtNode == g_currentCameraNode) {
if (g_currentCameraNode == g_skyNode && g_activeCameraFrame == WORLD_SKY)
return ARCBALL_ON_SKY;
else
return EGO_MOTION;
}
else
return ARCBALL_ON_PICKED;
}
static bool shouldUseArcball() {
return getManipMode() != EGO_MOTION;
}
// The translation part of the aux frame either comes from the current
// active object, or is the identity matrix when
static RigTForm getArcballRbt() {
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
return getPathAccumRbt(g_world, g_currentPickedRbtNode);
case ARCBALL_ON_SKY:
return RigTForm();
case EGO_MOTION:
return getPathAccumRbt(g_world, g_currentCameraNode);
default:
throw runtime_error("Invalid ManipMode");
}
}
static void updateArcballScale() {
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
double depth = arcballEye.getTranslation()[2];
if (depth > -CS175_EPS)
g_arcballScale = 0.02;
else
g_arcballScale = getScreenToEyeScale(depth, g_frustFovY, g_windowHeight);
}
static void drawArcBall(Uniforms& uniforms) {
// switch to wire frame mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
Matrix4 MVM = rigTFormToMatrix(arcballEye) * Matrix4::makeScale(Cvec3(1, 1, 1) * g_arcballScale * g_arcballScreenRadius);
sendModelViewNormalMatrix(uniforms, MVM, normalMatrix(MVM));
uniforms.put("uColor", Cvec3 (0.27, 0.82, 0.35));
// switch back to solid mode
g_arcballMat->draw(*g_sphere, uniforms);
}
static void drawStuff(bool picking) {
Uniforms uniforms;
// if we are not translating, update arcball scale
if (!(g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton) || (g_mouseLClickButton && !g_mouseRClickButton && g_spaceDown)))
updateArcballScale();
// build & send proj. matrix to vshader
const Matrix4 projmat = makeProjectionMatrix();
sendProjectionMatrix(uniforms, projmat);
const RigTForm eyeRbt = getPathAccumRbt(g_world, g_currentCameraNode);
const RigTForm invEyeRbt = inv(eyeRbt);
// const Cvec3 eyeLight1 = Cvec3(invEyeRbt * Cvec4(g_light1, 1));
// const Cvec3 eyeLight2 = Cvec3(invEyeRbt * Cvec4(g_light2, 1));
const Cvec3 eyeLight1 = getPathAccumRbt(g_world, g_light1Node).getTranslation();
const Cvec3 eyeLight2 = getPathAccumRbt(g_world, g_light2Node).getTranslation();
uniforms.put("uLight", (Cvec3) (invEyeRbt * Cvec4(eyeLight1,1)));
uniforms.put("uLight2", (Cvec3) (invEyeRbt * Cvec4(eyeLight2,1)));
if (!picking) {
Drawer drawer(invEyeRbt, uniforms);
g_world->accept(drawer);
if (g_displayArcball && shouldUseArcball())
drawArcBall(uniforms);
}
else {
Picker picker(invEyeRbt, uniforms);
g_overridingMaterial = g_pickingMat;
g_world->accept(picker);
g_overridingMaterial.reset();
glFlush();
g_currentPickedRbtNode = picker.getRbtNodeAtXY(g_mouseClickX, g_mouseClickY);
if (g_currentPickedRbtNode == g_groundNode)
g_currentPickedRbtNode = shared_ptr<SgRbtNode>(); // set to NULL
cout << (g_currentPickedRbtNode ? "Part picked" : "No part picked") << endl;
}
}
static void display() {
// No more glUseProgram
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawStuff(false); // no more curSS
glutSwapBuffers();
checkGlErrors();
}
static void pick() {
// We need to set the clear color to black, for pick rendering.
// so let's save the clear color
GLdouble clearColor[4];
glGetDoublev(GL_COLOR_CLEAR_VALUE, clearColor);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// No more glUseProgram
drawStuff(true); // no more curSS
// Uncomment below and comment out the glutPostRedisplay in mouse(...) call back
// to see result of the pick rendering pass
// glutSwapBuffers();
//Now set back the clear color
glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
checkGlErrors();
}
static void reshape(const int w, const int h) {
g_windowWidth = w;
g_windowHeight = h;
glViewport(0, 0, w, h);
cerr << "Size of window is now " << w << "x" << h << endl;
g_arcballScreenRadius = max(1.0, min(h, w) * 0.25);
updateFrustFovY();
glutPostRedisplay();
}
static Cvec3 getArcballDirection(const Cvec2& p, const double r) {
double n2 = norm2(p);
if (n2 >= r*r)
return normalize(Cvec3(p, 0));
else
return normalize(Cvec3(p, sqrt(r*r - n2)));
}
static RigTForm moveArcball(const Cvec2& p0, const Cvec2& p1) {
const Matrix4 projMatrix = makeProjectionMatrix();
const RigTForm eyeInverse = inv(getPathAccumRbt(g_world, g_currentCameraNode));
const Cvec3 arcballCenter = getArcballRbt().getTranslation();
const Cvec3 arcballCenter_ec = Cvec3(eyeInverse * Cvec4(arcballCenter, 1));
if (arcballCenter_ec[2] > -CS175_EPS)
return RigTForm();
Cvec2 ballScreenCenter = getScreenSpaceCoord(arcballCenter_ec,
projMatrix, g_frustNear, g_frustFovY, g_windowWidth, g_windowHeight);
const Cvec3 v0 = getArcballDirection(p0 - ballScreenCenter, g_arcballScreenRadius);
const Cvec3 v1 = getArcballDirection(p1 - ballScreenCenter, g_arcballScreenRadius);
return RigTForm(Quat(0.0, v1[0], v1[1], v1[2]) * Quat(0.0, -v0[0], -v0[1], -v0[2]));
}
static RigTForm doMtoOwrtA(const RigTForm& M, const RigTForm& O, const RigTForm& A) {
return A * M * inv(A) * O;
}
static RigTForm getMRbt(const double dx, const double dy) {
RigTForm M;
if (g_mouseLClickButton && !g_mouseRClickButton && !g_spaceDown) {
if (shouldUseArcball())
M = moveArcball(Cvec2(g_mouseClickX, g_mouseClickY), Cvec2(g_mouseClickX + dx, g_mouseClickY + dy));
else
M = RigTForm(Quat::makeXRotation(-dy) * Quat::makeYRotation(dx));
}
else {
double movementScale = getManipMode() == EGO_MOTION ? 0.02 : g_arcballScale;
if (g_mouseRClickButton && !g_mouseLClickButton) {
M = RigTForm(Cvec3(dx, dy, 0) * movementScale);
}
else if (g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton) || (g_mouseLClickButton && g_spaceDown)) {
M = RigTForm(Cvec3(0, 0, -dy) * movementScale);
}
}
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
break;
case ARCBALL_ON_SKY:
M = inv(M);
break;
case EGO_MOTION:
if (g_mouseLClickButton && !g_mouseRClickButton && !g_spaceDown) // only invert rotation
M = inv(M);
break;
}
return M;
}
static RigTForm makeMixedFrame(const RigTForm& objRbt, const RigTForm& eyeRbt) {
return transFact(objRbt) * linFact(eyeRbt);
}
// l = w X Y Z
// o = l O
// a = w A = l (Z Y X)^1 A = l A'
// o = a (A')^-1 O
// => a M (A')^-1 O = l A' M (A')^-1 O
static void motion(const int x, const int y) {
if (!g_mouseClickDown)
return;
const double dx = x - g_mouseClickX;
const double dy = g_windowHeight - y - 1 - g_mouseClickY;
const RigTForm M = getMRbt(dx, dy); // the "action" matrix
// the matrix for the auxiliary frame (the w.r.t.)
RigTForm A = makeMixedFrame(getArcballRbt(), getPathAccumRbt(g_world, g_currentCameraNode));
shared_ptr<SgRbtNode> target;
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
target = g_currentPickedRbtNode;
break;
case ARCBALL_ON_SKY:
target = g_skyNode;
break;
case EGO_MOTION:
target = g_currentCameraNode;
break;
}
A = inv(getPathAccumRbt(g_world, target, 1)) * A;
target->setRbt(doMtoOwrtA(M, target->getRbt(), A));
g_mouseClickX += dx;
g_mouseClickY += dy;
glutPostRedisplay(); // we always redraw if we changed the scene
}
static void mouse(const int button, const int state, const int x, const int y) {
g_mouseClickX = x;
g_mouseClickY = g_windowHeight - y - 1; // conversion from GLUT window-coordinate-system to OpenGL window-coordinate-system
g_mouseLClickButton |= (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN);
g_mouseRClickButton |= (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN);
g_mouseMClickButton |= (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN);
g_mouseLClickButton &= !(button == GLUT_LEFT_BUTTON && state == GLUT_UP);
g_mouseRClickButton &= !(button == GLUT_RIGHT_BUTTON && state == GLUT_UP);
g_mouseMClickButton &= !(button == GLUT_MIDDLE_BUTTON && state == GLUT_UP);
g_mouseClickDown = g_mouseLClickButton || g_mouseRClickButton || g_mouseMClickButton;
if (g_pickingMode && button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
pick();
g_pickingMode = false;
cerr << "Picking mode is off" << endl;
glutPostRedisplay(); // request redisplay since the arcball will have moved
}
glutPostRedisplay();
}
static void keyboardUp(const unsigned char key, const int x, const int y) {
switch (key) {
case ' ':
g_spaceDown = false;
break;
}
glutPostRedisplay();
}
static void keyboard(const unsigned char key, const int x, const int y) {
if (animating) {
return;
}
switch (key) {
case ' ':
g_spaceDown = true;
break;
case 27:
exit(0); // ESC
case 'h':
cout << " ============== H E L P ==============\n\n"
<< "h\t\thelp menu\n"
<< "s\t\tsave screenshot\n"
<< "f\t\tToggle flat shading on/off.\n"
<< "p\t\tUse mouse to pick a part to edit\n"
<< "v\t\tCycle view\n"
<< "drag left mouse to rotate\n" << endl;
break;
case 's':
glFlush();
writePpmScreenshot(g_windowWidth, g_windowHeight, "out.ppm");
break;
case 'f':
if (g_flat = !g_flat) {
cout << "Flat shading mode." << endl;
goto f_breakout;
}
cout << "Smooth shading mode." << endl;
f_breakout:
initCubeMesh();
break;
case '7':
g_horiz_scale /= 2;
cout << "Deforming cube half as fast." << endl;
break;
case '8':
g_horiz_scale *= 2;
cout << "Deforming cube twice as fast." << endl;
break;
case '0':
if (g_div_level == g_divcap)
cout << "Cannot subdivide further." << endl;
else {
++g_div_level;
cout << "Increased subdivision level to " << g_div_level << "." << endl;
}
break;
case '9':
if (g_div_level == 0)
cout << "Cannot decrease subdivision further." << endl;
else {
--g_div_level;
cout << "Decreased subdivision level to " << g_div_level << "." << endl;
}
break;
case 'v':
{
shared_ptr<SgRbtNode> viewers[] = {g_skyNode, g_robot1Node, g_robot2Node};
for (int i = 0; i < 3; ++i) {
if (g_currentCameraNode == viewers[i]) {
g_currentCameraNode = viewers[(i+1)%3];
break;
}
}
}
break;
case 'p':
g_pickingMode = !g_pickingMode;
cerr << "Picking mode is " << (g_pickingMode ? "on" : "off") << endl;
break;
case 'm':
g_activeCameraFrame = SkyMode((g_activeCameraFrame+1) % 2);
cerr << "Editing sky eye w.r.t. " << (g_activeCameraFrame == WORLD_SKY ? "world-sky frame\n" : "sky-sky frame\n") << endl;
break;
case 'c':
cout << "clicked c" << endl;
break;
case 'u':
cout << "clicked u" << endl;
break;
case '>':
next_frame();
cout << "clicked >" << endl;
break;
case '<':
prev_frame();
cout << "clicked <" << endl;
break;
case 'n':
cout << "making snapshot of current scene graph" << endl;
make_frame();
break;
case 'd':
cout << "clicked d" << endl;
delete_frame();
break;
case 'i':
cout << "Reading animation from animation.txt" << endl;
read_frame();
break;
case 'w':
cout << "Writing animation to animation.txt" << endl;
write_frame();
break;
case 'y':
if (key_frames.size() < 4) {
cout << "Cannot play animation with fewer than 4 keyframes." << endl;
break;
}
animating = !animating;
animateTimerCallback(0);
break;
case '+':
g_msBetweenKeyFrames -= 100;
cout << g_msBetweenKeyFrames << " ms between keyframes." << endl;
break;
case '-':
g_msBetweenKeyFrames += 100;
cout << g_msBetweenKeyFrames << " ms between keyframes." << endl;
break;
}
glutPostRedisplay();
}
static void specialKeyboard(const int key, const int x, const int y) {
switch (key) {
case GLUT_KEY_RIGHT:
g_furHeight *= 1.05;
cerr << "fur height = " << g_furHeight << std::endl;
break;
case GLUT_KEY_LEFT:
g_furHeight /= 1.05;
std::cerr << "fur height = " << g_furHeight << std::endl;
break;
case GLUT_KEY_UP:
g_hairyness *= 1.05;
cerr << "hairyness = " << g_hairyness << std::endl;
break;
case GLUT_KEY_DOWN:
g_hairyness /= 1.05;
cerr << "hairyness = " << g_hairyness << std::endl;
break;
}
glutPostRedisplay();
}
static void initGlutState(int argc, char * argv[]) {
glutInit(&argc, argv); // initialize Glut based on cmd-line args
#ifdef __MAC__
glutInitDisplayMode(GLUT_3_2_CORE_PROFILE|GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); // core profile flag is required for GL 3.2 on Mac
#else
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); // RGBA pixel channels and double buffering
#endif
glutInitWindowSize(g_windowWidth, g_windowHeight); // create a window
glutCreateWindow("Assignment 7"); // title the window
glutIgnoreKeyRepeat(true); // avoids repeated keyboard calls when holding space to emulate middle mouse
glutDisplayFunc(display); // display rendering callback
glutReshapeFunc(reshape); // window reshape callback
glutMotionFunc(motion); // mouse movement callback
glutMouseFunc(mouse); // mouse click callback
glutKeyboardFunc(keyboard);
glutKeyboardUpFunc(keyboardUp);
glutSpecialFunc(specialKeyboard); // special keyboard callback
}
static void initGLState() {
glClearColor(128./255., 200./255., 255./255., 0.);
glClearDepth(0.);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_GREATER);
glReadBuffer(GL_BACK);
if (!g_Gl2Compatible)
glEnable(GL_FRAMEBUFFER_SRGB);
}
static void initMaterials() {
// Create some prototype materials
Material diffuse("./shaders/basic-gl3.vshader", "./shaders/diffuse-gl3.fshader");
Material solid("./shaders/basic-gl3.vshader", "./shaders/solid-gl3.fshader");
Material specular("./shaders/basic-gl3.vshader", "./shaders/specular-gl3.fshader");
// add specular material
g_specular.reset(new Material(specular));
// make it green yo
g_specular->getUniforms().put("uColor", Cvec3f(0,1,0));
// copy diffuse prototype and set red color
g_redDiffuseMat.reset(new Material(diffuse));
g_redDiffuseMat->getUniforms().put("uColor", Cvec3f(1, 0, 0));
// copy diffuse prototype and set blue color
g_blueDiffuseMat.reset(new Material(diffuse));
g_blueDiffuseMat->getUniforms().put("uColor", Cvec3f(0, 0, 1));
// normal mapping material
g_bumpFloorMat.reset(new Material("./shaders/normal-gl3.vshader", "./shaders/normal-gl3.fshader"));
g_bumpFloorMat->getUniforms().put("uTexColor", shared_ptr<ImageTexture>(new ImageTexture("Fieldstone.ppm", true)));
g_bumpFloorMat->getUniforms().put("uTexNormal", shared_ptr<ImageTexture>(new ImageTexture("FieldstoneNormal.ppm", false)));
// copy solid prototype, and set to wireframed rendering
g_arcballMat.reset(new Material(solid));
g_arcballMat->getUniforms().put("uColor", Cvec3f(0.27f, 0.82f, 0.35f));
g_arcballMat->getRenderStates().polygonMode(GL_FRONT_AND_BACK, GL_LINE);
// copy solid prototype, and set to color white
g_lightMat.reset(new Material(solid));
g_lightMat->getUniforms().put("uColor", Cvec3f(1, 1, 1));
// pick shader
g_pickingMat.reset(new Material("./shaders/basic-gl3.vshader", "./shaders/pick-gl3.fshader"));
// bunny material
g_bunnyMat.reset(new Material("./shaders/basic-gl3.vshader", "./shaders/bunny-gl3.fshader"));
g_bunnyMat->getUniforms()
.put("uColorAmbient", Cvec3f(0.45f, 0.3f, 0.3f))
.put("uColorDiffuse", Cvec3f(0.2f, 0.2f, 0.2f));
// bunny shell materials;
shared_ptr<ImageTexture> shellTexture(new ImageTexture("shell.ppm", false)); // common shell texture
// needs to enable repeating of texture coordinates
shellTexture->bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// eachy layer of the shell uses a different material, though the materials will share the
// same shader files and some common uniforms. hence we create a prototype here, and will
// copy from the prototype later
Material bunnyShellMatPrototype("./shaders/bunny-shell-gl3.vshader", "./shaders/bunny-shell-gl3.fshader");
bunnyShellMatPrototype.getUniforms().put("uTexShell", shellTexture);
bunnyShellMatPrototype.getRenderStates()
.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) // set blending mode
.enable(GL_BLEND) // enable blending
.disable(GL_CULL_FACE); // disable culling
// allocate array of materials
g_bunnyShellMats.resize(g_numShells);
for (int i = 0; i < g_numShells; ++i) {
g_bunnyShellMats[i].reset(new Material(bunnyShellMatPrototype)); // copy from the prototype
// but set a different exponent for blending transparency
g_bunnyShellMats[i]->getUniforms().put("uAlphaExponent", 2.f + 5.f * float(i + 1)/g_numShells);
}
};
static void initGeometry() {
initGround();
initCubes();
initSphere();
initRobots();
initCubeMesh();
initCubeAnimation();
initBunnyMeshes();
}
static void constructRobot(shared_ptr<SgTransformNode> base, shared_ptr<Material> material) {
const double ARM_LEN = 0.7,
ARM_THICK = 0.25,
LEG_LEN = 1,
LEG_THICK = 0.25,
TORSO_LEN = 1.5,
TORSO_THICK = 0.25,
TORSO_WIDTH = 1,
HEAD_SIZE = 0.7;
const int NUM_JOINTS = 10,
NUM_SHAPES = 10;
struct JointDesc {
int parent;
float x, y, z;
};
JointDesc jointDesc[NUM_JOINTS] = {
{-1}, // torso
{0, TORSO_WIDTH/2, TORSO_LEN/2, 0}, // upper right arm
{0, -TORSO_WIDTH/2, TORSO_LEN/2, 0}, // upper left arm
{1, ARM_LEN, 0, 0}, // lower right arm
{2, -ARM_LEN, 0, 0}, // lower left arm
{0, TORSO_WIDTH/2-LEG_THICK/2, -TORSO_LEN/2, 0}, // upper right leg
{0, -TORSO_WIDTH/2+LEG_THICK/2, -TORSO_LEN/2, 0}, // upper left leg
{5, 0, -LEG_LEN, 0}, // lower right leg
{6, 0, -LEG_LEN, 0}, // lower left
{0, 0, TORSO_LEN/2, 0} // head
};
struct ShapeDesc {
int parentJointId;
float x, y, z, sx, sy, sz;
shared_ptr<Geometry> geometry;
};
ShapeDesc shapeDesc[NUM_SHAPES] = {
{0, 0, 0, 0, TORSO_WIDTH, TORSO_LEN, TORSO_THICK, g_cube}, // torso
{1, ARM_LEN/2, 0, 0, ARM_LEN/2, ARM_THICK/2, ARM_THICK/2, g_sphere}, // upper right arm
{2, -ARM_LEN/2, 0, 0, ARM_LEN/2, ARM_THICK/2, ARM_THICK/2, g_sphere}, // upper left arm
{3, ARM_LEN/2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK, g_cube}, // lower right arm
{4, -ARM_LEN/2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK, g_cube}, // lower left arm
{5, 0, -LEG_LEN/2, 0, LEG_THICK/2, LEG_LEN/2, LEG_THICK/2, g_sphere}, // upper right leg
{6, 0, -LEG_LEN/2, 0, LEG_THICK/2, LEG_LEN/2, LEG_THICK/2, g_sphere}, // upper left leg
{7, 0, -LEG_LEN/2, 0, LEG_THICK, LEG_LEN, LEG_THICK, g_cube}, // lower right leg
{8, 0, -LEG_LEN/2, 0, LEG_THICK, LEG_LEN, LEG_THICK, g_cube}, // lower left leg
{9, 0, HEAD_SIZE/2 * 1.5, 0, HEAD_SIZE/2, HEAD_SIZE/2, HEAD_SIZE/2, g_sphere}, // head
};
shared_ptr<SgTransformNode> jointNodes[NUM_JOINTS];
for (int i = 0; i < NUM_JOINTS; ++i) {
if (jointDesc[i].parent == -1)
jointNodes[i] = base;
else {
jointNodes[i].reset(new SgRbtNode(RigTForm(Cvec3(jointDesc[i].x, jointDesc[i].y, jointDesc[i].z))));
jointNodes[jointDesc[i].parent]->addChild(jointNodes[i]);
}
}
for (int i = 0; i < NUM_SHAPES; ++i) {
shared_ptr<SgGeometryShapeNode> shape(
new MyShapeNode(shapeDesc[i].geometry,
material, // USE MATERIAL as opposed to color
Cvec3(shapeDesc[i].x, shapeDesc[i].y, shapeDesc[i].z),
Cvec3(0, 0, 0),
Cvec3(shapeDesc[i].sx, shapeDesc[i].sy, shapeDesc[i].sz)));
jointNodes[shapeDesc[i].parentJointId]->addChild(shape);
}
}
static void initScene() {
g_world.reset(new SgRootNode());
g_light1Node.reset(new SgRbtNode(RigTForm(g_light1)));
g_light2Node.reset(new SgRbtNode(RigTForm(g_light2)));
g_bunnyNode.reset(new SgRbtNode());
g_skyNode.reset(new SgRbtNode(RigTForm(Cvec3(0.0, 0.25, 4.0))));
g_groundNode.reset(new SgRbtNode());
g_groundNode->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_ground, g_bumpFloorMat, Cvec3(0, g_groundY, 0))));
g_robot1Node.reset(new SgRbtNode(RigTForm(Cvec3(-8, 1, 0))));
g_robot2Node.reset(new SgRbtNode(RigTForm(Cvec3(8, 1, 0))));
constructRobot(g_robot1Node, g_redDiffuseMat); // a Red robot
constructRobot(g_robot2Node, g_blueDiffuseMat); // a Blue robot
g_mesh_cube.reset(new SgRbtNode(RigTForm(Cvec3(0, 0, -4))));
g_mesh_cube->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_cubeGeometryPN, g_specular, Cvec3(0, 0, 0))));
/* g_bunnyNode->addChild(shared_ptr<MyShapeNode>( */
/* new MyShapeNode(g_bunnyGeometry, g_bunnyMat))); */
for (int i = 0; i < g_numShells; ++i) {
g_bunnyNode->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_bunnyShellGeometries[i], g_bunnyShellMats[i])));
}
g_world->addChild(g_skyNode);
g_world->addChild(g_groundNode);
g_world->addChild(g_robot1Node);
g_world->addChild(g_robot2Node);
g_world->addChild(g_light1Node);
g_world->addChild(g_light2Node);
g_world->addChild(g_mesh_cube);
g_world->addChild(g_bunnyNode);
g_light1Node->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_sphere, g_lightMat, Cvec3(0,0,0))));
g_light2Node->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_sphere, g_lightMat, Cvec3(0,0,0))));
g_currentCameraNode = g_skyNode;
}
int main(int argc, char * argv[]) {
try {
initGlutState(argc,argv);
// on Mac, we shouldn't use GLEW.
#ifndef __MAC__
glewInit(); // load the OpenGL extensions
#endif
cout << (g_Gl2Compatible ? "Will use OpenGL 2.x / GLSL 1.0" : "Will use OpenGL 3.x / GLSL 1.5") << endl;
#ifndef __MAC__
if ((!g_Gl2Compatible) && !GLEW_VERSION_3_0)
throw runtime_error("Error: card/driver does not support OpenGL Shading Language v1.3");
else if (g_Gl2Compatible && !GLEW_VERSION_2_0)
throw runtime_error("Error: card/driver does not support OpenGL Shading Language v1.0");
#endif
initGLState();
initMaterials();
initGeometry();
initScene();
animateCube(0);
initSimulation();
glutMainLoop();
return 0;
}
catch (const runtime_error& e) {
cout << "Exception caught: " << e.what() << endl;
return -1;
}
}
added getn
////////////////////////////////////////////////////////////////////////
//
// Harvard University
// CS175 : Computer Graphics
// Professor Steven Gortler
//
////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <cstddef>
#include <vector>
#include <math.h>
#include <string>
#include <memory>
#include <stdexcept>
#include <list>
#if __GNUG__
# include <tr1/memory>
#endif
#ifdef __MAC__
# include <OpenGL/gl3.h>
# include <GLUT/glut.h>
#else
# include <GL/glew.h>
# include <GL/glut.h>
#endif
#include "ppm.h"
#include "cvec.h"
#include "matrix4.h"
#include "rigtform.h"
#include "glsupport.h"
#include "geometrymaker.h"
#include "arcball.h"
#include "scenegraph.h"
#include "asstcommon.h"
#include "drawer.h"
#include "picker.h"
#include "sgutils.h"
#include "geometry.h"
#include "mesh.h"
using namespace std;
using namespace tr1;
#define KF_UNDEF -1
// G L O B A L S ///////////////////////////////////////////////////
// --------- IMPORTANT --------------------------------------------------------
// Before you start working on this assignment, set the following variable
// properly to indicate whether you want to use OpenGL 2.x with GLSL 1.0 or
// OpenGL 3.x+ with GLSL 1.5.
//
// Set g_Gl2Compatible = true to use GLSL 1.0 and g_Gl2Compatible = false to
// use GLSL 1.5. Use GLSL 1.5 unless your system does not support it.
//
// If g_Gl2Compatible=true, shaders with -gl2 suffix will be loaded.
// If g_Gl2Compatible=false, shaders with -gl3 suffix will be loaded.
// To complete the assignment you only need to edit the shader files that get
// loaded
// ----------------------------------------------------------------------------
#ifdef __MAC__
const bool g_Gl2Compatible = false;
#else
const bool g_Gl2Compatible = true;
#endif
static const float g_frustMinFov = 60.0; // A minimal of 60 degree field of view
static float g_frustFovY = g_frustMinFov; // FOV in y direction (updated by updateFrustFovY)
static const float g_frustNear = -0.1; // near plane
static const float g_frustFar = -50.0; // far plane
static const float g_groundY = -2.0; // y coordinate of the ground
static const float g_groundSize = 10.0; // half the ground length
static const int g_divcap = 6;
enum SkyMode {WORLD_SKY=0, SKY_SKY=1};
static double g_horiz_scale = 4.0;
static int g_div_level = 0;
static int g_windowWidth = 512;
static int g_windowHeight = 512;
static bool g_mouseClickDown = false; // is the mouse button pressed
static bool g_mouseLClickButton, g_mouseRClickButton, g_mouseMClickButton;
static bool g_spaceDown = false; // space state, for middle mouse emulation
static bool g_flat = false; // smooth vs flat shading
static int g_mouseClickX, g_mouseClickY; // coordinates for mouse click event
static int g_activeShader = 0;
static Mesh cubeMesh;
static vector<double> vertex_speeds;
static vector<vector<int> > vertex_signs;
static bool meshLoaded = false;
static SkyMode g_activeCameraFrame = WORLD_SKY;
static bool g_displayArcball = true;
static double g_arcballScreenRadius = 100; // number of pixels
static double g_arcballScale = 1;
static bool g_pickingMode = false;
// -------- Shaders
static shared_ptr<Material> g_redDiffuseMat,
g_blueDiffuseMat,
g_bumpFloorMat,
g_arcballMat,
g_pickingMat,
g_lightMat,
g_specular,
g_bunnyMat;
shared_ptr<Material> g_overridingMaterial;
static vector<shared_ptr<Material> > g_bunnyShellMats; // for bunny shells
// New Geometry
static const int g_numShells = 24; // constants defining how many layers of shells
static double g_furHeight = 0.21;
static double g_hairyness = 0.7;
static shared_ptr<SimpleGeometryPN> g_bunnyGeometry;
static vector<shared_ptr<SimpleGeometryPNX> > g_bunnyShellGeometries;
static Mesh g_bunnyMesh;
// New Scene node
static shared_ptr<SgRbtNode> g_bunnyNode;
// linked list of frame vectors
static list<vector<RigTForm> > key_frames;
static int cur_frame = -1;
// --------- Geometry
typedef SgGeometryShapeNode MyShapeNode;
// Vertex buffer and index buffer associated with the ground and cube geometry
static shared_ptr<Geometry> g_ground, g_cube, g_sphere;
static shared_ptr<SimpleGeometryPN> g_cubeGeometryPN;
// --------- Scene
static const Cvec3 g_light1(2.0, 3.0, 14.0), g_light2(-2, 3.0, -14.0); // define two lights positions in world space
static shared_ptr<SgTransformNode> g_light1Node, g_light2Node;
static shared_ptr<SgRootNode> g_world;
static shared_ptr<SgRbtNode> g_skyNode, g_groundNode, g_mesh_cube, g_robot1Node, g_robot2Node;
static shared_ptr<SgRbtNode> g_currentCameraNode;
static shared_ptr<SgRbtNode> g_currentPickedRbtNode;
static int g_msBetweenKeyFrames = 2000;
static int g_animateFramesPerSecond = 60;
static bool animating = false;
static const Cvec3 g_gravity(0, -0.5, 0); // gavity vector
static double g_timeStep = 0.02;
static double g_numStepsPerFrame = 10;
static double g_damping = 0.96;
static double g_stiffness = 4;
static int g_simulationsPerSecond = 60;
static std::vector<Cvec3> g_tipPos, // should be hair tip pos in world-space coordinates
g_tipVelocity; // should be hair tip velocity in world-space coordinates
///////////////// END OF G L O B A L S //////////////////////////////////////////////////
static void updateShellGeometry() {
// TASK 1 and 3 TODO: finish this function as part of Task 1 and Task 3
}
static void hairsSimulationCallback(int dontCare) {
// TASK 2 TODO: wrte dynamics simulation code here as part of TASK2
// schedule this to get called again
glutTimerFunc(1000/g_simulationsPerSecond, hairsSimulationCallback, 0);
glutPostRedisplay(); // signal redisplaying
}
// New function that initialize the dynamics simulation
static void initSimulation() {
g_tipPos.resize(g_bunnyMesh.getNumVertices(), Cvec3(0));
g_tipVelocity = g_tipPos;
// TASK 1 TODO: initialize g_tipPos to "at-rest" hair tips in world coordinates
// Starts hair tip simulation
hairsSimulationCallback(0);
}
static void make_frame() {
vector<shared_ptr<SgRbtNode> > graph_vector;
dumpSgRbtNodes(g_world, graph_vector);
vector<RigTForm> new_frame;
for (int i = 0; i < graph_vector.size(); ++i) {
new_frame.push_back(graph_vector[i]->getRbt());
}
if (cur_frame == KF_UNDEF || cur_frame == key_frames.size() - 1) {
// undef is -1, so adding one sets the position to 0
key_frames.push_back(new_frame);
++cur_frame;
}
else {
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
key_frames.insert(it, new_frame);
++cur_frame;
}
return;
}
static void next_frame() {
if (cur_frame == KF_UNDEF || cur_frame == key_frames.size() - 1) {
cout << "can't advance frame" << endl;
return;
}
++cur_frame;
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
// this linked list of arrays is getting the previous vectors stacked on top of each other
fillSgRbtNodes(g_world, *it);
return;
}
static void prev_frame() {
if (cur_frame < 1) {
cout << "can't rewind frame "<< endl;
return;
}
--cur_frame;
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
fillSgRbtNodes(g_world, *it);
return;
}
static void delete_frame() {
if (cur_frame == KF_UNDEF) {
return;
}
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, cur_frame);
key_frames.erase(it);
if (key_frames.empty()) {
cur_frame = KF_UNDEF;
return;
}
else if (cur_frame != 0) {
--cur_frame;
}
fillSgRbtNodes(g_world, *it);
return;
}
static void write_frame() {
list<vector<RigTForm> >::iterator it = key_frames.begin();
FILE* output = fopen("animation.txt", "w");
int n = (*it).size();
fprintf(output, "%d %d\n", key_frames.size(), n);
while (it != key_frames.end()) {
vector<RigTForm> frame = *it;
for (int i = 0; i < frame.size(); ++i) {
RigTForm r = frame[i];
Cvec3 transFact = r.getTranslation();
Quat linFact = r.getRotation();
fprintf(output, "%.3f %.3f %.3f %.3f %.3f %.3f %.3f\n",
transFact[0], transFact[1], transFact[2],
linFact[0], linFact[1], linFact[2], linFact[3]
);
}
++it;
}
fclose(output);
}
static void read_frame() {
FILE* input = fopen("animation.txt", "r");
if (input == NULL) {
return;
}
int nFrames;
int nRbts;
fscanf(input, "%d %d\n", &nFrames, &nRbts);
key_frames.clear();
for (int i = 0; i < nFrames; ++i) {
vector<RigTForm> frame;
for (int j = 0; j < nRbts; ++j) {
Cvec3 transFact;
Quat linFact;
fscanf(input, "%lf %lf %lf %lf %lf %lf %lf\n",
&transFact[0], &transFact[1], &transFact[2],
&linFact[0], &linFact[1], &linFact[2], &linFact[3]
);
RigTForm r = RigTForm(transFact, linFact);
frame.push_back(r);
}
key_frames.push_back(frame);
}
cur_frame = 0;
fillSgRbtNodes(g_world, key_frames.front());
fclose(input);
}
static Quat slerp(Quat src, Quat dest, float alpha);
static Cvec3 lerp(Cvec3 src, Cvec3 dest, float alpha);
static Quat cond_neg(Quat q);
static Quat qpow(Quat q, float alpha);
Cvec3 getDTrans(Cvec3 c_i_1, Cvec3 c_i_neg_1, Cvec3 c_i) {
return (c_i_1 - c_i_neg_1)/6 + c_i;
}
Cvec3 getETrans(Cvec3 c_i_2, Cvec3 c_i_1, Cvec3 c_i) {
return (c_i_2 - c_i)/-6 + c_i_1;
}
Cvec3 bezierTrans(Cvec3 c_i_neg_1, Cvec3 c_i, Cvec3 c_i_1, Cvec3 c_i_2, int i, float t) {
Cvec3 d = getDTrans(c_i_1, c_i_neg_1, c_i);
Cvec3 e = getETrans(c_i_2, c_i_1, c_i);
Cvec3 f = c_i*(1 - t + i) + d*(t - i);
Cvec3 g = d*(1 - t + i) + e*(t - i);
Cvec3 h = e*(1 - t + i) + c_i_1*(t - i);
Cvec3 m = f*(1 - t + i) + g*(t - i);
Cvec3 n = g*(1 - t + i) + h*(t - i);
return m*(1 - t + i) + n*(t - i);
}
Quat getDRot(Quat c_i_1, Quat c_i_neg_1, Quat c_i) {
return qpow(cond_neg(c_i_1 * inv(c_i_neg_1)), 1.0/6.0) * c_i;
}
Quat getERot(Quat c_i_2, Quat c_i_1, Quat c_i) {
return qpow(cond_neg(c_i_2 * inv(c_i)), -1.0/6.0) * c_i_1;
}
Quat bezierRot(Quat c_i_neg_1, Quat c_i, Quat c_i_1, Quat c_i_2, int i, float t) {
Quat d = getDRot(c_i_1, c_i_neg_1, c_i);
Quat e = getERot(c_i_2, c_i_1, c_i);
Quat f = slerp(c_i, d, t -i);
Quat g = slerp(d, e, t - i);
Quat h = slerp(e, c_i_1, t - i);
Quat m = slerp(f, g, t - i);
Quat n = slerp(g, h, t - i);
return slerp(m, n, t - i);
}
bool interpolateAndDisplay(float t) {
list<vector<RigTForm> >::iterator it = key_frames.begin();
advance(it, (int) t);
++it;
vector<RigTForm> frame_1 = *it;
++it;
vector<RigTForm> frame_2 = *it;
++it;
if (it == key_frames.end()) {
return true;
}
vector<RigTForm> post_frame = *it;
// minus operator not overloaded for iterators. sad face.
--it; --it; --it;
vector<RigTForm> pre_frame = *it;
// d ci ci+1 e
float alpha = t - (int) t;
vector<RigTForm> frame;
int n = frame_1.size();
for (int i = 0; i < n; ++i) {
Cvec3 c_i_neg_1 = pre_frame[i].getTranslation();
Cvec3 c_i = frame_1[i].getTranslation();
Cvec3 c_i_1 = frame_2[i].getTranslation();
Cvec3 c_i_2 = post_frame[i].getTranslation();
Quat c_i_neg_1_r = pre_frame[i].getRotation();
Quat c_i_r = frame_1[i].getRotation();
Quat c_i_1_r = frame_2[i].getRotation();
Quat c_i_2_r = post_frame[i].getRotation();
Cvec3 trans = bezierTrans(c_i_neg_1, c_i, c_i_1, c_i_2, (int) t, t);
Quat rot = bezierRot(c_i_neg_1_r, c_i_r, c_i_1_r, c_i_2_r, (int) t, t);
frame.push_back(RigTForm(trans, rot));
}
fillSgRbtNodes(g_world, frame);
glutPostRedisplay();
return false;
}
static void animateTimerCallback(int ms) {
float t = (float) ms / (float) g_msBetweenKeyFrames;
bool endReached = interpolateAndDisplay(t);
if (!endReached) {
glutTimerFunc(1000/g_animateFramesPerSecond,
animateTimerCallback,
ms + 1000/g_animateFramesPerSecond);
}
else {
animating = false;
cur_frame = key_frames.size() - 2;
glutPostRedisplay();
}
}
static Cvec3 getFaceVertex(vector<Cvec3> & verts) {
// pass in the n vertices surrounding a face
float m_f = (float(1)/verts.size());
Cvec3 out = Cvec3 (0,0,0);
for (int i = 0; i < verts.size(); ++i) {
out += verts[i];
}
out *= m_f;
return out;
}
static Cvec3 getEdgeVertex(vector<Cvec3> & verts) {
// pass in two vertices on an edge, and the two face vertices of the
// faces they have in common
return getFaceVertex(verts);
}
static Cvec3 getVertexVertex(Cvec3 v, vector<Cvec3> & verts, vector<Cvec3> & faceverts) {
// pass in a vertex v, adjacent vertices verts, and
// the vertices of all adjacent faces faceverts.
Cvec3 out = Cvec3(0,0,0);
int n_v = verts.size();
out += v * (float(n_v - 2) / n_v);
Cvec3 out2 = Cvec3(0,0,0);
for (int i = 0; i < n_v; ++i) {
out2 += verts[i] + faceverts[i];
}
return out + (out2 * (float(1)/(n_v * n_v)));
}
Cvec3 get_N(Cvec3 p, Cvec3 n_hat, int m) {
Cvec3 s = p + (n_hat * g_furHeight);
return (s - p) * (float(1)/m);
}
static void simpleShadeCube(Mesh& mesh);
static void shadeCube(Mesh& mesh);
static void initBunnyMeshes() {
g_bunnyMesh.load("bunny.mesh");
// TODO: Init the per vertex normal of g_bunnyMesh, using codes from asst7
// ...
shadeCube(g_bunnyMesh);
// cout << "Finished shading bunny" << endl;
// TODO: Initialize g_bunnyGeometry from g_bunnyMesh, similar to
vector<VertexPN> verts;
for (int i = 0; i < g_bunnyMesh.getNumFaces(); ++i) {
const Mesh::Face f = g_bunnyMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
if (g_flat)
normal = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// add vertices to bunny geometry
int numVertices = verts.size();
VertexPN *vertices = (VertexPN *) malloc(numVertices * sizeof(VertexPN));
for (int i = 0; i < numVertices; ++i) {
Cvec3f pos = verts[i].p;
vertices[i] = verts[i];
}
g_bunnyGeometry.reset(new SimpleGeometryPN());
g_bunnyGeometry->upload(vertices, numVertices);
// Now allocate array of SimpleGeometryPNX to for shells, one per layer
g_bunnyShellGeometries.resize(g_numShells);
for (int i = 0; i < g_numShells; ++i) {
g_bunnyShellGeometries[i].reset(new SimpleGeometryPNX());
}
}
static void initGround() {
int ibLen, vbLen;
getPlaneVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makePlane(g_groundSize*2, vtx.begin(), idx.begin());
g_ground.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void simpleShadeCube(Mesh& mesh) {
Cvec3 normal = Cvec3(0, 1, 0);
for (int i = 0; i < mesh.getNumFaces(); ++i) {
const Mesh::Face f = mesh.getFace(i);
Cvec3 facenorm = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
v.setNormal(facenorm);
}
}
}
static void shadeCube(Mesh& mesh) {
Cvec3 normal = Cvec3(0, 0, 0);
for (int i = 0; i < mesh.getNumVertices(); ++i) {
mesh.getVertex(i).setNormal(normal);
}
for (int i = 0; i < mesh.getNumFaces(); ++i) {
const Mesh::Face f = mesh.getFace(i);
Cvec3 facenorm = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
v.setNormal(facenorm + v.getNormal());
}
}
for (int i = 0; i < mesh.getNumVertices(); ++i) {
const Mesh::Vertex v = mesh.getVertex(i);
v.setNormal(normalize(v.getNormal()));
}
}
void collectEdgeVertices(Mesh& m);
void collectFaceVertices(Mesh& m);
void collectVertexVertices(Mesh& m);
static void initCubeMesh() {
if (!meshLoaded) {
cubeMesh.load("./cube.mesh");
meshLoaded = true;
}
// set normals
shadeCube(cubeMesh);
// collect vertices from each face and map quads to triangles
vector<VertexPN> verts;
for (int i = 0; i < cubeMesh.getNumFaces(); ++i) {
const Mesh::Face f = cubeMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
if (g_flat)
normal = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// add vertices to cube geometry
int numVertices = verts.size();
VertexPN *vertices = (VertexPN *) malloc(numVertices * sizeof(VertexPN));
for (int i = 0; i < numVertices; ++i) {
Cvec3f pos = verts[i].p;
vertices[i] = verts[i];
}
if (!g_cubeGeometryPN) {
g_cubeGeometryPN.reset(new SimpleGeometryPN());
}
g_cubeGeometryPN->upload(vertices, numVertices);
}
static void initCubeAnimation() {
// set the speeds of each vertex
srand(time(NULL));
for (int i = 0; i < cubeMesh.getNumVertices(); ++i) {
// create random speed
vertex_speeds.push_back((double) rand() / RAND_MAX);
Cvec3 pos = cubeMesh.getVertex(i).getPosition();
// store sign
int xSign = (pos[0] < 0) ? -1 : 1;
int ySign = (pos[1] < 0) ? -1 : 1;
int zSign = (pos[2] < 0) ? -1 : 1;
vector<int> signs;
signs.push_back(xSign);
signs.push_back(ySign);
signs.push_back(zSign);
vertex_signs.push_back(signs);
}
}
static void initCubes() {
int ibLen, vbLen;
getCubeVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeCube(1, vtx.begin(), idx.begin());
g_cube.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void initSphere() {
int ibLen, vbLen;
getSphereVbIbLen(20, 10, vbLen, ibLen);
// Temporary storage for sphere Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeSphere(1, 20, 10, vtx.begin(), idx.begin());
g_sphere.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vtx.size(), idx.size()));
}
static void initRobots() {
// Init whatever geometry needed for the robots
}
// takes a projection matrix and send to the the shaders
inline void sendProjectionMatrix(Uniforms& uniforms, const Matrix4& projMatrix) {
uniforms.put("uProjMatrix", projMatrix);
}
// update g_frustFovY from g_frustMinFov, g_windowWidth, and g_windowHeight
static void updateFrustFovY() {
if (g_windowWidth >= g_windowHeight)
g_frustFovY = g_frustMinFov;
else {
const double RAD_PER_DEG = 0.5 * CS175_PI/180;
g_frustFovY = atan2(sin(g_frustMinFov * RAD_PER_DEG) * g_windowHeight / g_windowWidth, cos(g_frustMinFov * RAD_PER_DEG)) / RAD_PER_DEG;
}
}
static void animateCube(int ms) {
float t = (float) ms / (float) g_msBetweenKeyFrames;
// scale all vertices in cube
for (int i = 0; i < cubeMesh.getNumVertices(); ++i) {
const Mesh::Vertex v = cubeMesh.getVertex(i);
Cvec3 pos = v.getPosition();
double factor = (1 + (float(g_div_level)/10)) * ((-1 * sin((double) (g_horiz_scale * ms) / (1000 * (vertex_speeds[i] + .5))) + 1) / 2 + .5);
pos[0] = vertex_signs[i][0] * (factor / sqrt(3));
pos[1] = vertex_signs[i][1] * (factor / sqrt(3));
pos[2] = vertex_signs[i][2] * (factor / sqrt(3));
v.setPosition(pos);
}
// copy mesh to temporary mesh for rendering
Mesh renderMesh = cubeMesh;
// subdivision
for (int i = 0; i < g_div_level; ++i) {
collectFaceVertices(renderMesh);
collectEdgeVertices(renderMesh);
collectVertexVertices(renderMesh);
renderMesh.subdivide();
}
// set normals
shadeCube(renderMesh);
// collect vertices for each face
vector<VertexPN> verts;
int q = 0;
for (int i = 0; i < renderMesh.getNumFaces(); ++i) {
const Mesh::Face f = renderMesh.getFace(i);
Cvec3 pos;
Cvec3 normal;
for (int j = 0; j < f.getNumVertices(); ++j) {
const Mesh::Vertex v = f.getVertex(j);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
else
normal = f.getNormal();
verts.push_back(VertexPN(pos, normal));
if (j == 2) {
verts.push_back(VertexPN(pos, normal));
}
}
const Mesh::Vertex v = f.getVertex(0);
pos = v.getPosition();
if (!g_flat)
normal = v.getNormal();
else
normal = f.getNormal();
verts.push_back(VertexPN(pos, normal));
}
// dump into geometry
int numVertices = verts.size();
VertexPN *vertices = (VertexPN *) malloc(numVertices * sizeof(VertexPN));
for (int i = 0; i < numVertices; ++i) {
Cvec3f pos = verts[i].p;
vertices[i] = verts[i];
}
g_cubeGeometryPN->upload(vertices, numVertices);
glutPostRedisplay();
glutTimerFunc(1000/g_animateFramesPerSecond,
animateCube,
ms + 1000/g_animateFramesPerSecond);
}
void collectFaceVertices(Mesh& m) {
for (int i = 0; i < m.getNumFaces(); ++i) {
Mesh::Face f = m.getFace(i);
vector<Cvec3> vertices;
for (int j = 0; j < f.getNumVertices(); ++j) {
vertices.push_back(f.getVertex(j).getPosition());
}
m.setNewFaceVertex(f, getFaceVertex(vertices));
}
}
void collectEdgeVertices(Mesh& m) {
for (int i = 0; i < m.getNumEdges(); ++i) {
Mesh::Edge e = m.getEdge(i);
// get faces adjacent to edges
Cvec3 f0 = m.getNewFaceVertex(e.getFace(0));
Cvec3 f1 = m.getNewFaceVertex(e.getFace(1));
Cvec3 pos0 = e.getVertex(0).getPosition();
Cvec3 pos1 = e.getVertex(1).getPosition();
vector<Cvec3> vertices;
vertices.push_back(f0);
vertices.push_back(f1);
vertices.push_back(pos0);
vertices.push_back(pos1);
Cvec3 newEdge = getEdgeVertex(vertices);
m.setNewEdgeVertex(e, newEdge);
}
}
void collectVertexVertices(Mesh& m) {
vector<vector<Cvec3> > vertexVertices;
for (int i = 0; i < m.getNumVertices(); ++i) {
const Mesh::Vertex v = m.getVertex(i);
Mesh::VertexIterator it(v.getIterator()), it0(it);
vector<Cvec3> vertices;
vector<Cvec3> faces;
do {
vertices.push_back(it.getVertex().getPosition());
faces.push_back(m.getNewFaceVertex(it.getFace()));
}
while (++it != it0); // go around once the 1ring
Cvec3 vertex = getVertexVertex(v.getPosition(), vertices, faces);
m.setNewVertexVertex(v, vertex);
}
}
static Cvec3 lerp(Cvec3 src, Cvec3 dest, float alpha) {
assert(0 <= alpha && alpha <= 1.0);
float xout = ((1-alpha) * src[0]) + (alpha * dest[0]);
float yout = ((1-alpha) * src[1]) + (alpha * dest[1]);
float zout = ((1-alpha) * src[2]) + (alpha * dest[2]);
return Cvec3(xout, yout, zout);
}
static Quat cond_neg(Quat q) {
if (q[0] < 0) {
return Quat(-q[0], -q[1], -q[2], -q[3]);
}
return q;
}
static Quat qpow(Quat q, float alpha) {
Cvec3 axis = Cvec3(q[1], q[2], q[3]);
float theta = atan2(sqrt(norm2(axis)), q[0]);
if (norm2(axis) <= .001) {
return Quat();
}
axis = normalize(axis);
float q_outw = cos(alpha * theta);
float q_outx = axis[0] * sin(alpha * theta);
float q_outy = axis[1] * sin(alpha * theta);
float q_outz = axis[2] * sin(alpha * theta);
return normalize(Quat(q_outw, q_outx, q_outy, q_outz));
}
static Quat slerp(Quat src, Quat dest, float alpha) {
assert(0 <= alpha && alpha <= 1.0);
return normalize(qpow(cond_neg(dest * inv(src)), alpha) * src);
}
static Matrix4 makeProjectionMatrix() {
return Matrix4::makeProjection(
g_frustFovY, g_windowWidth / static_cast <double> (g_windowHeight),
g_frustNear, g_frustFar);
}
enum ManipMode {
ARCBALL_ON_PICKED,
ARCBALL_ON_SKY,
EGO_MOTION
};
static ManipMode getManipMode() {
// if nothing is picked or the picked transform is the transfrom we are viewing from
if (g_currentPickedRbtNode == NULL || g_currentPickedRbtNode == g_currentCameraNode) {
if (g_currentCameraNode == g_skyNode && g_activeCameraFrame == WORLD_SKY)
return ARCBALL_ON_SKY;
else
return EGO_MOTION;
}
else
return ARCBALL_ON_PICKED;
}
static bool shouldUseArcball() {
return getManipMode() != EGO_MOTION;
}
// The translation part of the aux frame either comes from the current
// active object, or is the identity matrix when
static RigTForm getArcballRbt() {
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
return getPathAccumRbt(g_world, g_currentPickedRbtNode);
case ARCBALL_ON_SKY:
return RigTForm();
case EGO_MOTION:
return getPathAccumRbt(g_world, g_currentCameraNode);
default:
throw runtime_error("Invalid ManipMode");
}
}
static void updateArcballScale() {
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
double depth = arcballEye.getTranslation()[2];
if (depth > -CS175_EPS)
g_arcballScale = 0.02;
else
g_arcballScale = getScreenToEyeScale(depth, g_frustFovY, g_windowHeight);
}
static void drawArcBall(Uniforms& uniforms) {
// switch to wire frame mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
Matrix4 MVM = rigTFormToMatrix(arcballEye) * Matrix4::makeScale(Cvec3(1, 1, 1) * g_arcballScale * g_arcballScreenRadius);
sendModelViewNormalMatrix(uniforms, MVM, normalMatrix(MVM));
uniforms.put("uColor", Cvec3 (0.27, 0.82, 0.35));
// switch back to solid mode
g_arcballMat->draw(*g_sphere, uniforms);
}
static void drawStuff(bool picking) {
Uniforms uniforms;
// if we are not translating, update arcball scale
if (!(g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton) || (g_mouseLClickButton && !g_mouseRClickButton && g_spaceDown)))
updateArcballScale();
// build & send proj. matrix to vshader
const Matrix4 projmat = makeProjectionMatrix();
sendProjectionMatrix(uniforms, projmat);
const RigTForm eyeRbt = getPathAccumRbt(g_world, g_currentCameraNode);
const RigTForm invEyeRbt = inv(eyeRbt);
// const Cvec3 eyeLight1 = Cvec3(invEyeRbt * Cvec4(g_light1, 1));
// const Cvec3 eyeLight2 = Cvec3(invEyeRbt * Cvec4(g_light2, 1));
const Cvec3 eyeLight1 = getPathAccumRbt(g_world, g_light1Node).getTranslation();
const Cvec3 eyeLight2 = getPathAccumRbt(g_world, g_light2Node).getTranslation();
uniforms.put("uLight", (Cvec3) (invEyeRbt * Cvec4(eyeLight1,1)));
uniforms.put("uLight2", (Cvec3) (invEyeRbt * Cvec4(eyeLight2,1)));
if (!picking) {
Drawer drawer(invEyeRbt, uniforms);
g_world->accept(drawer);
if (g_displayArcball && shouldUseArcball())
drawArcBall(uniforms);
}
else {
Picker picker(invEyeRbt, uniforms);
g_overridingMaterial = g_pickingMat;
g_world->accept(picker);
g_overridingMaterial.reset();
glFlush();
g_currentPickedRbtNode = picker.getRbtNodeAtXY(g_mouseClickX, g_mouseClickY);
if (g_currentPickedRbtNode == g_groundNode)
g_currentPickedRbtNode = shared_ptr<SgRbtNode>(); // set to NULL
cout << (g_currentPickedRbtNode ? "Part picked" : "No part picked") << endl;
}
}
static void display() {
// No more glUseProgram
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawStuff(false); // no more curSS
glutSwapBuffers();
checkGlErrors();
}
static void pick() {
// We need to set the clear color to black, for pick rendering.
// so let's save the clear color
GLdouble clearColor[4];
glGetDoublev(GL_COLOR_CLEAR_VALUE, clearColor);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// No more glUseProgram
drawStuff(true); // no more curSS
// Uncomment below and comment out the glutPostRedisplay in mouse(...) call back
// to see result of the pick rendering pass
// glutSwapBuffers();
//Now set back the clear color
glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
checkGlErrors();
}
static void reshape(const int w, const int h) {
g_windowWidth = w;
g_windowHeight = h;
glViewport(0, 0, w, h);
cerr << "Size of window is now " << w << "x" << h << endl;
g_arcballScreenRadius = max(1.0, min(h, w) * 0.25);
updateFrustFovY();
glutPostRedisplay();
}
static Cvec3 getArcballDirection(const Cvec2& p, const double r) {
double n2 = norm2(p);
if (n2 >= r*r)
return normalize(Cvec3(p, 0));
else
return normalize(Cvec3(p, sqrt(r*r - n2)));
}
static RigTForm moveArcball(const Cvec2& p0, const Cvec2& p1) {
const Matrix4 projMatrix = makeProjectionMatrix();
const RigTForm eyeInverse = inv(getPathAccumRbt(g_world, g_currentCameraNode));
const Cvec3 arcballCenter = getArcballRbt().getTranslation();
const Cvec3 arcballCenter_ec = Cvec3(eyeInverse * Cvec4(arcballCenter, 1));
if (arcballCenter_ec[2] > -CS175_EPS)
return RigTForm();
Cvec2 ballScreenCenter = getScreenSpaceCoord(arcballCenter_ec,
projMatrix, g_frustNear, g_frustFovY, g_windowWidth, g_windowHeight);
const Cvec3 v0 = getArcballDirection(p0 - ballScreenCenter, g_arcballScreenRadius);
const Cvec3 v1 = getArcballDirection(p1 - ballScreenCenter, g_arcballScreenRadius);
return RigTForm(Quat(0.0, v1[0], v1[1], v1[2]) * Quat(0.0, -v0[0], -v0[1], -v0[2]));
}
static RigTForm doMtoOwrtA(const RigTForm& M, const RigTForm& O, const RigTForm& A) {
return A * M * inv(A) * O;
}
static RigTForm getMRbt(const double dx, const double dy) {
RigTForm M;
if (g_mouseLClickButton && !g_mouseRClickButton && !g_spaceDown) {
if (shouldUseArcball())
M = moveArcball(Cvec2(g_mouseClickX, g_mouseClickY), Cvec2(g_mouseClickX + dx, g_mouseClickY + dy));
else
M = RigTForm(Quat::makeXRotation(-dy) * Quat::makeYRotation(dx));
}
else {
double movementScale = getManipMode() == EGO_MOTION ? 0.02 : g_arcballScale;
if (g_mouseRClickButton && !g_mouseLClickButton) {
M = RigTForm(Cvec3(dx, dy, 0) * movementScale);
}
else if (g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton) || (g_mouseLClickButton && g_spaceDown)) {
M = RigTForm(Cvec3(0, 0, -dy) * movementScale);
}
}
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
break;
case ARCBALL_ON_SKY:
M = inv(M);
break;
case EGO_MOTION:
if (g_mouseLClickButton && !g_mouseRClickButton && !g_spaceDown) // only invert rotation
M = inv(M);
break;
}
return M;
}
static RigTForm makeMixedFrame(const RigTForm& objRbt, const RigTForm& eyeRbt) {
return transFact(objRbt) * linFact(eyeRbt);
}
// l = w X Y Z
// o = l O
// a = w A = l (Z Y X)^1 A = l A'
// o = a (A')^-1 O
// => a M (A')^-1 O = l A' M (A')^-1 O
static void motion(const int x, const int y) {
if (!g_mouseClickDown)
return;
const double dx = x - g_mouseClickX;
const double dy = g_windowHeight - y - 1 - g_mouseClickY;
const RigTForm M = getMRbt(dx, dy); // the "action" matrix
// the matrix for the auxiliary frame (the w.r.t.)
RigTForm A = makeMixedFrame(getArcballRbt(), getPathAccumRbt(g_world, g_currentCameraNode));
shared_ptr<SgRbtNode> target;
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
target = g_currentPickedRbtNode;
break;
case ARCBALL_ON_SKY:
target = g_skyNode;
break;
case EGO_MOTION:
target = g_currentCameraNode;
break;
}
A = inv(getPathAccumRbt(g_world, target, 1)) * A;
target->setRbt(doMtoOwrtA(M, target->getRbt(), A));
g_mouseClickX += dx;
g_mouseClickY += dy;
glutPostRedisplay(); // we always redraw if we changed the scene
}
static void mouse(const int button, const int state, const int x, const int y) {
g_mouseClickX = x;
g_mouseClickY = g_windowHeight - y - 1; // conversion from GLUT window-coordinate-system to OpenGL window-coordinate-system
g_mouseLClickButton |= (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN);
g_mouseRClickButton |= (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN);
g_mouseMClickButton |= (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN);
g_mouseLClickButton &= !(button == GLUT_LEFT_BUTTON && state == GLUT_UP);
g_mouseRClickButton &= !(button == GLUT_RIGHT_BUTTON && state == GLUT_UP);
g_mouseMClickButton &= !(button == GLUT_MIDDLE_BUTTON && state == GLUT_UP);
g_mouseClickDown = g_mouseLClickButton || g_mouseRClickButton || g_mouseMClickButton;
if (g_pickingMode && button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
pick();
g_pickingMode = false;
cerr << "Picking mode is off" << endl;
glutPostRedisplay(); // request redisplay since the arcball will have moved
}
glutPostRedisplay();
}
static void keyboardUp(const unsigned char key, const int x, const int y) {
switch (key) {
case ' ':
g_spaceDown = false;
break;
}
glutPostRedisplay();
}
static void keyboard(const unsigned char key, const int x, const int y) {
if (animating) {
return;
}
switch (key) {
case ' ':
g_spaceDown = true;
break;
case 27:
exit(0); // ESC
case 'h':
cout << " ============== H E L P ==============\n\n"
<< "h\t\thelp menu\n"
<< "s\t\tsave screenshot\n"
<< "f\t\tToggle flat shading on/off.\n"
<< "p\t\tUse mouse to pick a part to edit\n"
<< "v\t\tCycle view\n"
<< "drag left mouse to rotate\n" << endl;
break;
case 's':
glFlush();
writePpmScreenshot(g_windowWidth, g_windowHeight, "out.ppm");
break;
case 'f':
if (g_flat = !g_flat) {
cout << "Flat shading mode." << endl;
goto f_breakout;
}
cout << "Smooth shading mode." << endl;
f_breakout:
initCubeMesh();
break;
case '7':
g_horiz_scale /= 2;
cout << "Deforming cube half as fast." << endl;
break;
case '8':
g_horiz_scale *= 2;
cout << "Deforming cube twice as fast." << endl;
break;
case '0':
if (g_div_level == g_divcap)
cout << "Cannot subdivide further." << endl;
else {
++g_div_level;
cout << "Increased subdivision level to " << g_div_level << "." << endl;
}
break;
case '9':
if (g_div_level == 0)
cout << "Cannot decrease subdivision further." << endl;
else {
--g_div_level;
cout << "Decreased subdivision level to " << g_div_level << "." << endl;
}
break;
case 'v':
{
shared_ptr<SgRbtNode> viewers[] = {g_skyNode, g_robot1Node, g_robot2Node};
for (int i = 0; i < 3; ++i) {
if (g_currentCameraNode == viewers[i]) {
g_currentCameraNode = viewers[(i+1)%3];
break;
}
}
}
break;
case 'p':
g_pickingMode = !g_pickingMode;
cerr << "Picking mode is " << (g_pickingMode ? "on" : "off") << endl;
break;
case 'm':
g_activeCameraFrame = SkyMode((g_activeCameraFrame+1) % 2);
cerr << "Editing sky eye w.r.t. " << (g_activeCameraFrame == WORLD_SKY ? "world-sky frame\n" : "sky-sky frame\n") << endl;
break;
case 'c':
cout << "clicked c" << endl;
break;
case 'u':
cout << "clicked u" << endl;
break;
case '>':
next_frame();
cout << "clicked >" << endl;
break;
case '<':
prev_frame();
cout << "clicked <" << endl;
break;
case 'n':
cout << "making snapshot of current scene graph" << endl;
make_frame();
break;
case 'd':
cout << "clicked d" << endl;
delete_frame();
break;
case 'i':
cout << "Reading animation from animation.txt" << endl;
read_frame();
break;
case 'w':
cout << "Writing animation to animation.txt" << endl;
write_frame();
break;
case 'y':
if (key_frames.size() < 4) {
cout << "Cannot play animation with fewer than 4 keyframes." << endl;
break;
}
animating = !animating;
animateTimerCallback(0);
break;
case '+':
g_msBetweenKeyFrames -= 100;
cout << g_msBetweenKeyFrames << " ms between keyframes." << endl;
break;
case '-':
g_msBetweenKeyFrames += 100;
cout << g_msBetweenKeyFrames << " ms between keyframes." << endl;
break;
}
glutPostRedisplay();
}
static void specialKeyboard(const int key, const int x, const int y) {
switch (key) {
case GLUT_KEY_RIGHT:
g_furHeight *= 1.05;
cerr << "fur height = " << g_furHeight << std::endl;
break;
case GLUT_KEY_LEFT:
g_furHeight /= 1.05;
std::cerr << "fur height = " << g_furHeight << std::endl;
break;
case GLUT_KEY_UP:
g_hairyness *= 1.05;
cerr << "hairyness = " << g_hairyness << std::endl;
break;
case GLUT_KEY_DOWN:
g_hairyness /= 1.05;
cerr << "hairyness = " << g_hairyness << std::endl;
break;
}
glutPostRedisplay();
}
static void initGlutState(int argc, char * argv[]) {
glutInit(&argc, argv); // initialize Glut based on cmd-line args
#ifdef __MAC__
glutInitDisplayMode(GLUT_3_2_CORE_PROFILE|GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); // core profile flag is required for GL 3.2 on Mac
#else
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); // RGBA pixel channels and double buffering
#endif
glutInitWindowSize(g_windowWidth, g_windowHeight); // create a window
glutCreateWindow("Assignment 7"); // title the window
glutIgnoreKeyRepeat(true); // avoids repeated keyboard calls when holding space to emulate middle mouse
glutDisplayFunc(display); // display rendering callback
glutReshapeFunc(reshape); // window reshape callback
glutMotionFunc(motion); // mouse movement callback
glutMouseFunc(mouse); // mouse click callback
glutKeyboardFunc(keyboard);
glutKeyboardUpFunc(keyboardUp);
glutSpecialFunc(specialKeyboard); // special keyboard callback
}
static void initGLState() {
glClearColor(128./255., 200./255., 255./255., 0.);
glClearDepth(0.);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_GREATER);
glReadBuffer(GL_BACK);
if (!g_Gl2Compatible)
glEnable(GL_FRAMEBUFFER_SRGB);
}
static void initMaterials() {
// Create some prototype materials
Material diffuse("./shaders/basic-gl3.vshader", "./shaders/diffuse-gl3.fshader");
Material solid("./shaders/basic-gl3.vshader", "./shaders/solid-gl3.fshader");
Material specular("./shaders/basic-gl3.vshader", "./shaders/specular-gl3.fshader");
// add specular material
g_specular.reset(new Material(specular));
// make it green yo
g_specular->getUniforms().put("uColor", Cvec3f(0,1,0));
// copy diffuse prototype and set red color
g_redDiffuseMat.reset(new Material(diffuse));
g_redDiffuseMat->getUniforms().put("uColor", Cvec3f(1, 0, 0));
// copy diffuse prototype and set blue color
g_blueDiffuseMat.reset(new Material(diffuse));
g_blueDiffuseMat->getUniforms().put("uColor", Cvec3f(0, 0, 1));
// normal mapping material
g_bumpFloorMat.reset(new Material("./shaders/normal-gl3.vshader", "./shaders/normal-gl3.fshader"));
g_bumpFloorMat->getUniforms().put("uTexColor", shared_ptr<ImageTexture>(new ImageTexture("Fieldstone.ppm", true)));
g_bumpFloorMat->getUniforms().put("uTexNormal", shared_ptr<ImageTexture>(new ImageTexture("FieldstoneNormal.ppm", false)));
// copy solid prototype, and set to wireframed rendering
g_arcballMat.reset(new Material(solid));
g_arcballMat->getUniforms().put("uColor", Cvec3f(0.27f, 0.82f, 0.35f));
g_arcballMat->getRenderStates().polygonMode(GL_FRONT_AND_BACK, GL_LINE);
// copy solid prototype, and set to color white
g_lightMat.reset(new Material(solid));
g_lightMat->getUniforms().put("uColor", Cvec3f(1, 1, 1));
// pick shader
g_pickingMat.reset(new Material("./shaders/basic-gl3.vshader", "./shaders/pick-gl3.fshader"));
// bunny material
g_bunnyMat.reset(new Material("./shaders/basic-gl3.vshader", "./shaders/bunny-gl3.fshader"));
g_bunnyMat->getUniforms()
.put("uColorAmbient", Cvec3f(0.45f, 0.3f, 0.3f))
.put("uColorDiffuse", Cvec3f(0.2f, 0.2f, 0.2f));
// bunny shell materials;
shared_ptr<ImageTexture> shellTexture(new ImageTexture("shell.ppm", false)); // common shell texture
// needs to enable repeating of texture coordinates
shellTexture->bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// eachy layer of the shell uses a different material, though the materials will share the
// same shader files and some common uniforms. hence we create a prototype here, and will
// copy from the prototype later
Material bunnyShellMatPrototype("./shaders/bunny-shell-gl3.vshader", "./shaders/bunny-shell-gl3.fshader");
bunnyShellMatPrototype.getUniforms().put("uTexShell", shellTexture);
bunnyShellMatPrototype.getRenderStates()
.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) // set blending mode
.enable(GL_BLEND) // enable blending
.disable(GL_CULL_FACE); // disable culling
// allocate array of materials
g_bunnyShellMats.resize(g_numShells);
for (int i = 0; i < g_numShells; ++i) {
g_bunnyShellMats[i].reset(new Material(bunnyShellMatPrototype)); // copy from the prototype
// but set a different exponent for blending transparency
g_bunnyShellMats[i]->getUniforms().put("uAlphaExponent", 2.f + 5.f * float(i + 1)/g_numShells);
}
};
static void initGeometry() {
initGround();
initCubes();
initSphere();
initRobots();
initCubeMesh();
initCubeAnimation();
initBunnyMeshes();
}
static void constructRobot(shared_ptr<SgTransformNode> base, shared_ptr<Material> material) {
const double ARM_LEN = 0.7,
ARM_THICK = 0.25,
LEG_LEN = 1,
LEG_THICK = 0.25,
TORSO_LEN = 1.5,
TORSO_THICK = 0.25,
TORSO_WIDTH = 1,
HEAD_SIZE = 0.7;
const int NUM_JOINTS = 10,
NUM_SHAPES = 10;
struct JointDesc {
int parent;
float x, y, z;
};
JointDesc jointDesc[NUM_JOINTS] = {
{-1}, // torso
{0, TORSO_WIDTH/2, TORSO_LEN/2, 0}, // upper right arm
{0, -TORSO_WIDTH/2, TORSO_LEN/2, 0}, // upper left arm
{1, ARM_LEN, 0, 0}, // lower right arm
{2, -ARM_LEN, 0, 0}, // lower left arm
{0, TORSO_WIDTH/2-LEG_THICK/2, -TORSO_LEN/2, 0}, // upper right leg
{0, -TORSO_WIDTH/2+LEG_THICK/2, -TORSO_LEN/2, 0}, // upper left leg
{5, 0, -LEG_LEN, 0}, // lower right leg
{6, 0, -LEG_LEN, 0}, // lower left
{0, 0, TORSO_LEN/2, 0} // head
};
struct ShapeDesc {
int parentJointId;
float x, y, z, sx, sy, sz;
shared_ptr<Geometry> geometry;
};
ShapeDesc shapeDesc[NUM_SHAPES] = {
{0, 0, 0, 0, TORSO_WIDTH, TORSO_LEN, TORSO_THICK, g_cube}, // torso
{1, ARM_LEN/2, 0, 0, ARM_LEN/2, ARM_THICK/2, ARM_THICK/2, g_sphere}, // upper right arm
{2, -ARM_LEN/2, 0, 0, ARM_LEN/2, ARM_THICK/2, ARM_THICK/2, g_sphere}, // upper left arm
{3, ARM_LEN/2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK, g_cube}, // lower right arm
{4, -ARM_LEN/2, 0, 0, ARM_LEN, ARM_THICK, ARM_THICK, g_cube}, // lower left arm
{5, 0, -LEG_LEN/2, 0, LEG_THICK/2, LEG_LEN/2, LEG_THICK/2, g_sphere}, // upper right leg
{6, 0, -LEG_LEN/2, 0, LEG_THICK/2, LEG_LEN/2, LEG_THICK/2, g_sphere}, // upper left leg
{7, 0, -LEG_LEN/2, 0, LEG_THICK, LEG_LEN, LEG_THICK, g_cube}, // lower right leg
{8, 0, -LEG_LEN/2, 0, LEG_THICK, LEG_LEN, LEG_THICK, g_cube}, // lower left leg
{9, 0, HEAD_SIZE/2 * 1.5, 0, HEAD_SIZE/2, HEAD_SIZE/2, HEAD_SIZE/2, g_sphere}, // head
};
shared_ptr<SgTransformNode> jointNodes[NUM_JOINTS];
for (int i = 0; i < NUM_JOINTS; ++i) {
if (jointDesc[i].parent == -1)
jointNodes[i] = base;
else {
jointNodes[i].reset(new SgRbtNode(RigTForm(Cvec3(jointDesc[i].x, jointDesc[i].y, jointDesc[i].z))));
jointNodes[jointDesc[i].parent]->addChild(jointNodes[i]);
}
}
for (int i = 0; i < NUM_SHAPES; ++i) {
shared_ptr<SgGeometryShapeNode> shape(
new MyShapeNode(shapeDesc[i].geometry,
material, // USE MATERIAL as opposed to color
Cvec3(shapeDesc[i].x, shapeDesc[i].y, shapeDesc[i].z),
Cvec3(0, 0, 0),
Cvec3(shapeDesc[i].sx, shapeDesc[i].sy, shapeDesc[i].sz)));
jointNodes[shapeDesc[i].parentJointId]->addChild(shape);
}
}
static void initScene() {
g_world.reset(new SgRootNode());
g_light1Node.reset(new SgRbtNode(RigTForm(g_light1)));
g_light2Node.reset(new SgRbtNode(RigTForm(g_light2)));
g_bunnyNode.reset(new SgRbtNode());
g_skyNode.reset(new SgRbtNode(RigTForm(Cvec3(0.0, 0.25, 4.0))));
g_groundNode.reset(new SgRbtNode());
g_groundNode->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_ground, g_bumpFloorMat, Cvec3(0, g_groundY, 0))));
g_robot1Node.reset(new SgRbtNode(RigTForm(Cvec3(-8, 1, 0))));
g_robot2Node.reset(new SgRbtNode(RigTForm(Cvec3(8, 1, 0))));
constructRobot(g_robot1Node, g_redDiffuseMat); // a Red robot
constructRobot(g_robot2Node, g_blueDiffuseMat); // a Blue robot
g_mesh_cube.reset(new SgRbtNode(RigTForm(Cvec3(0, 0, -4))));
g_mesh_cube->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_cubeGeometryPN, g_specular, Cvec3(0, 0, 0))));
/* g_bunnyNode->addChild(shared_ptr<MyShapeNode>( */
/* new MyShapeNode(g_bunnyGeometry, g_bunnyMat))); */
for (int i = 0; i < g_numShells; ++i) {
g_bunnyNode->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_bunnyShellGeometries[i], g_bunnyShellMats[i])));
}
g_world->addChild(g_skyNode);
g_world->addChild(g_groundNode);
g_world->addChild(g_robot1Node);
g_world->addChild(g_robot2Node);
g_world->addChild(g_light1Node);
g_world->addChild(g_light2Node);
g_world->addChild(g_mesh_cube);
g_world->addChild(g_bunnyNode);
g_light1Node->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_sphere, g_lightMat, Cvec3(0,0,0))));
g_light2Node->addChild(shared_ptr<MyShapeNode>(
new MyShapeNode(g_sphere, g_lightMat, Cvec3(0,0,0))));
g_currentCameraNode = g_skyNode;
}
int main(int argc, char * argv[]) {
try {
initGlutState(argc,argv);
// on Mac, we shouldn't use GLEW.
#ifndef __MAC__
glewInit(); // load the OpenGL extensions
#endif
cout << (g_Gl2Compatible ? "Will use OpenGL 2.x / GLSL 1.0" : "Will use OpenGL 3.x / GLSL 1.5") << endl;
#ifndef __MAC__
if ((!g_Gl2Compatible) && !GLEW_VERSION_3_0)
throw runtime_error("Error: card/driver does not support OpenGL Shading Language v1.3");
else if (g_Gl2Compatible && !GLEW_VERSION_2_0)
throw runtime_error("Error: card/driver does not support OpenGL Shading Language v1.0");
#endif
initGLState();
initMaterials();
initGeometry();
initScene();
animateCube(0);
initSimulation();
glutMainLoop();
return 0;
}
catch (const runtime_error& e) {
cout << "Exception caught: " << e.what() << endl;
return -1;
}
}
|
/* * This file is part of Maliit framework *
*
* Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Contact: maliit-discuss@lists.maliit.org
*
* 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
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
// Based on minputmethodstate.cpp from libmeegotouch
#include "inputmethod.h"
#include "inputmethod_p.h"
#if QT_VERSION >= 0x050000
#include <QGuiApplication>
#include <QInputMethod>
#else
#include <QApplication>
#include <QInputContext>
#endif
namespace Maliit {
InputMethodPrivate::InputMethodPrivate() :
area(),
widget(0),
orientationAngle(),
rotationInProgress(false)
{
}
InputMethodPrivate::~InputMethodPrivate()
{
}
InputMethod::InputMethod() :
QObject(),
d_ptr(new InputMethodPrivate)
{
}
InputMethod::~InputMethod()
{
}
InputMethod *InputMethod::instance()
{
static InputMethod singleton;
return &singleton;
}
void InputMethod::setWidget(QWidget *widget)
{
Q_D(InputMethod);
d->widget = widget;
}
QWidget *InputMethod::widget() const
{
Q_D(const InputMethod);
return d->widget;
}
QRect InputMethod::area() const
{
Q_D(const InputMethod);
return d->area;
}
void InputMethod::setArea(const QRect &newArea)
{
Q_D(InputMethod);
if (d->area != newArea) {
d->area = newArea;
Q_EMIT areaChanged(d->area);
}
}
void InputMethod::startOrientationAngleChange(OrientationAngle newOrientationAngle)
{
Q_D(InputMethod);
if (d->orientationAngle != newOrientationAngle) {
d->orientationAngle = newOrientationAngle;
d->rotationInProgress = true;
Q_EMIT orientationAngleAboutToChange(d->orientationAngle);
}
}
void InputMethod::setOrientationAngle(OrientationAngle newOrientationAngle)
{
Q_D(InputMethod);
if (d->orientationAngle != newOrientationAngle) {
d->orientationAngle = newOrientationAngle;
d->rotationInProgress = true;
}
if (d->rotationInProgress) {
d->rotationInProgress = false;
Q_EMIT orientationAngleChanged(d->orientationAngle);
}
}
OrientationAngle InputMethod::orientationAngle() const
{
Q_D(const InputMethod);
return d->orientationAngle;
}
void InputMethod::emitKeyPress(const QKeyEvent &event)
{
Q_EMIT keyPress(event);
}
void InputMethod::emitKeyRelease(const QKeyEvent &event)
{
Q_EMIT keyRelease(event);
}
void InputMethod::setLanguage(const QString &language)
{
Q_D(InputMethod);
if (d->language != language) {
d->language = language;
Q_EMIT languageChanged(language);
}
}
const QString &InputMethod::language() const
{
Q_D(const InputMethod);
return d->language;
}
void requestInputMethodPanel()
{
#if QT_VERSION >= 0x050000
qApp->inputMethod()->show();
#else
QInputContext *inputContext = qApp->inputContext();
if (!inputContext) {
return;
}
QEvent request(QEvent::RequestSoftwareInputPanel);
inputContext->filterEvent(&request);
#endif
}
void closeInputMethodPanel()
{
#if QT_VERSION >= 0x050000
qApp->inputMethod()->hide();
#else
QInputContext *inputContext = qApp->inputContext();
if (!inputContext) {
return;
}
QEvent close(QEvent::CloseSoftwareInputPanel);
inputContext->filterEvent(&close);
inputContext->reset();
#endif
}
} // namespace Maliit
Use QT_VERSION_CHECK instead of hex version number.
RevBy: Jan Arne Petersen
Full, original commit at 570cd91eda2eee9fe91c30e1dc5cdf66e9d2b02b in maliit-framework
/* * This file is part of Maliit framework *
*
* Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Contact: maliit-discuss@lists.maliit.org
*
* 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
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
// Based on minputmethodstate.cpp from libmeegotouch
#include "inputmethod.h"
#include "inputmethod_p.h"
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QGuiApplication>
#include <QInputMethod>
#else
#include <QApplication>
#include <QInputContext>
#endif
namespace Maliit {
InputMethodPrivate::InputMethodPrivate() :
area(),
widget(0),
orientationAngle(),
rotationInProgress(false)
{
}
InputMethodPrivate::~InputMethodPrivate()
{
}
InputMethod::InputMethod() :
QObject(),
d_ptr(new InputMethodPrivate)
{
}
InputMethod::~InputMethod()
{
}
InputMethod *InputMethod::instance()
{
static InputMethod singleton;
return &singleton;
}
void InputMethod::setWidget(QWidget *widget)
{
Q_D(InputMethod);
d->widget = widget;
}
QWidget *InputMethod::widget() const
{
Q_D(const InputMethod);
return d->widget;
}
QRect InputMethod::area() const
{
Q_D(const InputMethod);
return d->area;
}
void InputMethod::setArea(const QRect &newArea)
{
Q_D(InputMethod);
if (d->area != newArea) {
d->area = newArea;
Q_EMIT areaChanged(d->area);
}
}
void InputMethod::startOrientationAngleChange(OrientationAngle newOrientationAngle)
{
Q_D(InputMethod);
if (d->orientationAngle != newOrientationAngle) {
d->orientationAngle = newOrientationAngle;
d->rotationInProgress = true;
Q_EMIT orientationAngleAboutToChange(d->orientationAngle);
}
}
void InputMethod::setOrientationAngle(OrientationAngle newOrientationAngle)
{
Q_D(InputMethod);
if (d->orientationAngle != newOrientationAngle) {
d->orientationAngle = newOrientationAngle;
d->rotationInProgress = true;
}
if (d->rotationInProgress) {
d->rotationInProgress = false;
Q_EMIT orientationAngleChanged(d->orientationAngle);
}
}
OrientationAngle InputMethod::orientationAngle() const
{
Q_D(const InputMethod);
return d->orientationAngle;
}
void InputMethod::emitKeyPress(const QKeyEvent &event)
{
Q_EMIT keyPress(event);
}
void InputMethod::emitKeyRelease(const QKeyEvent &event)
{
Q_EMIT keyRelease(event);
}
void InputMethod::setLanguage(const QString &language)
{
Q_D(InputMethod);
if (d->language != language) {
d->language = language;
Q_EMIT languageChanged(language);
}
}
const QString &InputMethod::language() const
{
Q_D(const InputMethod);
return d->language;
}
void requestInputMethodPanel()
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
qApp->inputMethod()->show();
#else
QInputContext *inputContext = qApp->inputContext();
if (!inputContext) {
return;
}
QEvent request(QEvent::RequestSoftwareInputPanel);
inputContext->filterEvent(&request);
#endif
}
void closeInputMethodPanel()
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
qApp->inputMethod()->hide();
#else
QInputContext *inputContext = qApp->inputContext();
if (!inputContext) {
return;
}
QEvent close(QEvent::CloseSoftwareInputPanel);
inputContext->filterEvent(&close);
inputContext->reset();
#endif
}
} // namespace Maliit
|
/*! \file uclient.cc
****************************************************************************
*
* Implementation of the URBI interface class
*
* Copyright (C) 2004, 2006, 2007, 2008, 2009 Gostai S.A.S. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**********************************************************************/
#include <cstdlib>
#include <cerrno>
#include <locale.h>
#include <libport/windows.hh>
#include <libport/unistd.h>
#include <libport/sys/time.h>
#if !defined WIN32
# include <time.h>
# include <signal.h>
#endif
#include <libport/cstdio>
#include <libport/sys/select.h>
#include <libport/arpa/inet.h>
#include <libport/netdb.h>
#include <libport/errors.hh>
#include <libport/lockable.hh>
#include <libport/thread.hh>
#include <libport/utime.hh>
#include <urbi/uclient.hh>
#include <urbi/utag.hh>
namespace urbi
{
/*! Establish the connection with the server.
Spawn a new thread that will listen to the socket, parse the incoming URBI
messages, and notify the appropriate callbacks.
*/
UClient::UClient(const std::string& host, unsigned port,
size_t buflen, bool server,
int semListenInc)
: UAbstractClient(host, port, buflen, server)
, thread(0)
, pingInterval(0)
, semListenInc_ (semListenInc)
{
sd = -1;
int pos = 0;
setlocale(LC_NUMERIC, "C");
control_fd[0] = control_fd[1] = -1;
#ifndef WIN32
if (::pipe(control_fd) == -1)
{
rc = -1;
libport::perror("UClient::UClient failed to create pipe");
return;
}
//block sigpipe
signal(SIGPIPE, SIG_IGN);
#endif
// Address resolution stage.
struct sockaddr_in sa; // Internet address struct
memset(&sa, 0, sizeof sa);
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup(wVersionRequested, &wsaData);
#endif
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
// host-to-IP translation
struct hostent* hen = gethostbyname(host_.c_str());
if (!hen)
{
// maybe it is an IP address
sa.sin_addr.s_addr = inet_addr(host_.c_str());
if (sa.sin_addr.s_addr == INADDR_NONE)
{
std::cerr << "UClient::UClient cannot resolve host name." << std::endl;
rc = -1;
return;
}
}
else
memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length);
sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0)
{
rc = -1;
libport::perror("UClient::UClient socket");
return;
}
if (!server_)
{
// Connect on given host and port
rc = connect(sd, (struct sockaddr *) &sa, sizeof sa);
// If we attempt to connect too fast to aperios ipstack it will fail.
if (rc)
{
usleep(20000);
rc = connect(sd, (struct sockaddr *) &sa, sizeof sa);
}
// Check there was no error.
if (rc)
{
rc = -1;
libport::perror("UClient::UClient connect");
return;
}
// Check that it really worked.
while (!pos)
pos = ::recv(sd, recvBuffer, buflen, 0);
if (pos < 0)
{
rc = -1;
libport::perror("UClient::UClient recv");
return;
}
}
else
{
// Allow to rebind on the same port shortly after having used it.
{
int one = 1;
rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
if (rc)
{
rc = -1;
libport::perror("UClient::UClient cannot use setsockopt");
return;
}
}
// Bind socket
rc = bind (sd, (struct sockaddr *) &sa, sizeof sa);
if (rc)
{
rc = -1;
libport::perror("UClient::UClient cannot bind");
return;
}
// Activate listen/passive mode, do not allow queued connections
rc = listen (sd, 0);
if (rc)
{
rc = -1;
libport::perror("UClient::UClient cannot listen");
return;
}
// Create a thread waiting for incoming connection.
// This must not be blocking in case of a remote server.
// FIXME: block if normal remote ?
init_ = false;
thread = libport::startThread(this, &UClient::acceptThread);
}
recvBufferPosition = pos;
recvBuffer[recvBufferPosition] = 0;
// Do not create thread if one is already waiting for incoming connection
if (!thread)
{
thread = libport::startThread(this, &UClient::listenThread);
// Notify the base class that connection is established.
onConnection();
}
if (!defaultClient)
defaultClient = this;
listenSem_++;
acceptSem_++;
}
UClient::~UClient()
{
if (sd >= 0)
closeUClient ();
}
int
UClient::closeUClient ()
{
if (sd >= 0 && libport::closeSocket(sd) == -1)
libport::perror ("cannot close sd");
sd = -1;
if (control_fd[1] != -1
&& ::write(control_fd[1], "a", 1) == -1)
libport::perror ("cannot write to control_fd[1]");
// If the connection has failed while building the client, the
// thread is not created.
if (thread)
// Must wait for listen thread to terminate.
libport::joinThread(thread);
if (control_fd[1] != -1
&& close(control_fd[1]) == -1)
libport::perror ("cannot close controlfd[1]");
if (control_fd[0] != -1
&& close(control_fd[0]) == -1)
libport::perror ("cannot close controlfd[0]");
return 0;
}
bool
UClient::canSend(size_t)
{
return true;
}
int
UClient::effectiveSend(const void* buffer, size_t size)
{
#if DEBUG
char output[size+1];
memcpy (static_cast<void*> (output), buffer, size);
output[size]=0;
std::cerr << ">>>> SENT : [" << output << "]" << std::endl;
#endif
if (rc)
return -1;
size_t pos = 0;
while (pos != size)
{
int retval = ::send(sd, (char *) buffer + pos, size-pos, 0);
if (retval< 0)
{
rc = retval;
clientError("send error", rc);
return rc;
}
pos += retval;
}
return 0;
}
void
UClient::acceptThread()
{
// Wait for it...
acceptSem_--;
// Accept one connection
struct sockaddr_in saClient;
socklen_t addrlenClient;
int acceptFD = 0;
acceptFD = accept (sd, (struct sockaddr *) &saClient, &addrlenClient);
if (acceptFD < 0)
{
libport::perror("UClient::UClient cannot accept");
rc = -1;
return;
}
// Store client connection info
host_ = inet_ntoa(saClient.sin_addr);
port_ = saClient.sin_port;
// Do not listen anymore.
close(sd);
// Redirect send/receive on accepted connection.
sd = acceptFD;
// FIXME: leaking ?
thread = libport::startThread(this, &UClient::listenThread);
init_ = true;
onConnection();
// Stop this thread, the listen one is the real thing.
return;
}
void
UClient::listenThread()
{
// Wait for it...
for (int i = semListenInc_; i > 0; --i)
listenSem_--;
int maxfd = 1 + std::max(sd, control_fd[0]);
waitingPong = false;
// Declare ping channel for kernel that requires it.
send("if (isdef(Channel)) var lobby.%s = Channel.new(\"%s\");",
internalPongTag.c_str(), internalPongTag.c_str());
while (true)
{
if (sd == -1)
return;
fd_set rfds;
FD_ZERO(&rfds);
LIBPORT_FD_SET(sd, &rfds);
fd_set efds;
FD_ZERO(&efds);
LIBPORT_FD_SET(sd, &efds);
#ifndef WIN32
LIBPORT_FD_SET(control_fd[0], &rfds);
#endif
int selectReturn;
if (pingInterval)
{
const unsigned delay = waitingPong ? pongTimeout : pingInterval;
struct timeval timeout = { delay / 1000, (delay % 1000) * 1000};
selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout);
}
else
{
selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL);
}
if (sd < 0)
return;
// Treat error
if (selectReturn < 0 && errno != EINTR)
{
rc = -1;
clientError("Connection error : ", errno);
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(),
"!!! Connection error", std::list<BinaryData>() ));
return;
}
if (selectReturn < 0) // ::select catch a signal (errno == EINTR)
continue;
// timeout
else if (selectReturn == 0)
{
if (waitingPong) // Timeout while waiting PONG
{
rc = -1;
// FIXME: Choose between two differents way to alert user program
clientError("Lost connection with server");
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(),
"!!! Lost connection with server",
std::list<BinaryData>() ));
return;
}
else // Timeout : Ping_interval
{
send("%s << 1,", internalPongTag.c_str());
waitingPong = true;
}
}
else
{
// We receive data, at least the "1" value sent through the pong tag
// channel so we are no longer waiting for a pong.
waitingPong = false;
int count = ::recv(sd, &recvBuffer[recvBufferPosition],
buflen - recvBufferPosition - 1, 0);
if (count <= 0)
{
std::string errorMsg;
int errorCode = 0;
if (count < 0)
{
#ifdef WIN32
errorCode = WSAGetLastError();
#else
errorCode = errno;
#endif
errorMsg = "!!! Connection error";
}
else // count == 0 => Connection close
{
errorMsg = "!!! Connection closed";
}
rc = -1;
clientError(errorMsg.c_str(), errorCode);
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(),
errorMsg.c_str(), std::list<BinaryData>() ));
return;
}
recvBufferPosition += count;
recvBuffer[recvBufferPosition] = 0;
processRecvBuffer();
}
}
}
void
UClient::printf(const char * format, ...)
{
va_list arg;
va_start(arg, format);
vfprintf(stderr, format, arg);
va_end(arg);
}
unsigned int UClient::getCurrentTime() const
{
// FIXME: Put this into libport.
#ifdef WIN32
return GetTickCount();
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000+tv.tv_usec/1000;
#endif
}
void execute()
{
while (true)
sleep(100);
}
void exit(int code)
{
::exit(code);
}
UClient& connect(const std::string& host)
{
return *new UClient(host);
}
void disconnect(UClient &client)
{
delete &client;
}
void
UClient::setKeepAliveCheck(const unsigned pingInterval,
const unsigned pongTimeout)
{
this->pingInterval = pingInterval;
this->pongTimeout = pongTimeout;
}
} // namespace urbi
Get rid of spurious parse error.
* src/liburbi/uclient.cc (UClient::listenThread): Shush the
Channel creation.
/*! \file uclient.cc
****************************************************************************
*
* Implementation of the URBI interface class
*
* Copyright (C) 2004, 2006, 2007, 2008, 2009 Gostai S.A.S. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**********************************************************************/
#include <cstdlib>
#include <cerrno>
#include <locale.h>
#include <libport/windows.hh>
#include <libport/unistd.h>
#include <libport/sys/time.h>
#if !defined WIN32
# include <time.h>
# include <signal.h>
#endif
#include <libport/cstdio>
#include <libport/sys/select.h>
#include <libport/arpa/inet.h>
#include <libport/netdb.h>
#include <libport/errors.hh>
#include <libport/lockable.hh>
#include <libport/thread.hh>
#include <libport/utime.hh>
#include <urbi/uclient.hh>
#include <urbi/utag.hh>
namespace urbi
{
/*! Establish the connection with the server.
Spawn a new thread that will listen to the socket, parse the incoming URBI
messages, and notify the appropriate callbacks.
*/
UClient::UClient(const std::string& host, unsigned port,
size_t buflen, bool server,
int semListenInc)
: UAbstractClient(host, port, buflen, server)
, thread(0)
, pingInterval(0)
, semListenInc_ (semListenInc)
{
sd = -1;
int pos = 0;
setlocale(LC_NUMERIC, "C");
control_fd[0] = control_fd[1] = -1;
#ifndef WIN32
if (::pipe(control_fd) == -1)
{
rc = -1;
libport::perror("UClient::UClient failed to create pipe");
return;
}
//block sigpipe
signal(SIGPIPE, SIG_IGN);
#endif
// Address resolution stage.
struct sockaddr_in sa; // Internet address struct
memset(&sa, 0, sizeof sa);
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup(wVersionRequested, &wsaData);
#endif
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
// host-to-IP translation
struct hostent* hen = gethostbyname(host_.c_str());
if (!hen)
{
// maybe it is an IP address
sa.sin_addr.s_addr = inet_addr(host_.c_str());
if (sa.sin_addr.s_addr == INADDR_NONE)
{
std::cerr << "UClient::UClient cannot resolve host name." << std::endl;
rc = -1;
return;
}
}
else
memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length);
sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0)
{
rc = -1;
libport::perror("UClient::UClient socket");
return;
}
if (!server_)
{
// Connect on given host and port
rc = connect(sd, (struct sockaddr *) &sa, sizeof sa);
// If we attempt to connect too fast to aperios ipstack it will fail.
if (rc)
{
usleep(20000);
rc = connect(sd, (struct sockaddr *) &sa, sizeof sa);
}
// Check there was no error.
if (rc)
{
rc = -1;
libport::perror("UClient::UClient connect");
return;
}
// Check that it really worked.
while (!pos)
pos = ::recv(sd, recvBuffer, buflen, 0);
if (pos < 0)
{
rc = -1;
libport::perror("UClient::UClient recv");
return;
}
}
else
{
// Allow to rebind on the same port shortly after having used it.
{
int one = 1;
rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
if (rc)
{
rc = -1;
libport::perror("UClient::UClient cannot use setsockopt");
return;
}
}
// Bind socket
rc = bind (sd, (struct sockaddr *) &sa, sizeof sa);
if (rc)
{
rc = -1;
libport::perror("UClient::UClient cannot bind");
return;
}
// Activate listen/passive mode, do not allow queued connections
rc = listen (sd, 0);
if (rc)
{
rc = -1;
libport::perror("UClient::UClient cannot listen");
return;
}
// Create a thread waiting for incoming connection.
// This must not be blocking in case of a remote server.
// FIXME: block if normal remote ?
init_ = false;
thread = libport::startThread(this, &UClient::acceptThread);
}
recvBufferPosition = pos;
recvBuffer[recvBufferPosition] = 0;
// Do not create thread if one is already waiting for incoming connection
if (!thread)
{
thread = libport::startThread(this, &UClient::listenThread);
// Notify the base class that connection is established.
onConnection();
}
if (!defaultClient)
defaultClient = this;
listenSem_++;
acceptSem_++;
}
UClient::~UClient()
{
if (sd >= 0)
closeUClient ();
}
int
UClient::closeUClient ()
{
if (sd >= 0 && libport::closeSocket(sd) == -1)
libport::perror ("cannot close sd");
sd = -1;
if (control_fd[1] != -1
&& ::write(control_fd[1], "a", 1) == -1)
libport::perror ("cannot write to control_fd[1]");
// If the connection has failed while building the client, the
// thread is not created.
if (thread)
// Must wait for listen thread to terminate.
libport::joinThread(thread);
if (control_fd[1] != -1
&& close(control_fd[1]) == -1)
libport::perror ("cannot close controlfd[1]");
if (control_fd[0] != -1
&& close(control_fd[0]) == -1)
libport::perror ("cannot close controlfd[0]");
return 0;
}
bool
UClient::canSend(size_t)
{
return true;
}
int
UClient::effectiveSend(const void* buffer, size_t size)
{
#if DEBUG
char output[size+1];
memcpy (static_cast<void*> (output), buffer, size);
output[size]=0;
std::cerr << ">>>> SENT : [" << output << "]" << std::endl;
#endif
if (rc)
return -1;
size_t pos = 0;
while (pos != size)
{
int retval = ::send(sd, (char *) buffer + pos, size-pos, 0);
if (retval< 0)
{
rc = retval;
clientError("send error", rc);
return rc;
}
pos += retval;
}
return 0;
}
void
UClient::acceptThread()
{
// Wait for it...
acceptSem_--;
// Accept one connection
struct sockaddr_in saClient;
socklen_t addrlenClient;
int acceptFD = 0;
acceptFD = accept (sd, (struct sockaddr *) &saClient, &addrlenClient);
if (acceptFD < 0)
{
libport::perror("UClient::UClient cannot accept");
rc = -1;
return;
}
// Store client connection info
host_ = inet_ntoa(saClient.sin_addr);
port_ = saClient.sin_port;
// Do not listen anymore.
close(sd);
// Redirect send/receive on accepted connection.
sd = acceptFD;
// FIXME: leaking ?
thread = libport::startThread(this, &UClient::listenThread);
init_ = true;
onConnection();
// Stop this thread, the listen one is the real thing.
return;
}
void
UClient::listenThread()
{
// Wait for it...
for (int i = semListenInc_; i > 0; --i)
listenSem_--;
int maxfd = 1 + std::max(sd, control_fd[0]);
waitingPong = false;
// Declare ping channel for kernel that requires it.
send("if (isdef(Channel)) var lobby.%s = Channel.new(\"%s\") | {};",
internalPongTag.c_str(), internalPongTag.c_str());
while (true)
{
if (sd == -1)
return;
fd_set rfds;
FD_ZERO(&rfds);
LIBPORT_FD_SET(sd, &rfds);
fd_set efds;
FD_ZERO(&efds);
LIBPORT_FD_SET(sd, &efds);
#ifndef WIN32
LIBPORT_FD_SET(control_fd[0], &rfds);
#endif
int selectReturn;
if (pingInterval)
{
const unsigned delay = waitingPong ? pongTimeout : pingInterval;
struct timeval timeout = { delay / 1000, (delay % 1000) * 1000};
selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout);
}
else
{
selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL);
}
if (sd < 0)
return;
// Treat error
if (selectReturn < 0 && errno != EINTR)
{
rc = -1;
clientError("Connection error : ", errno);
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(),
"!!! Connection error", std::list<BinaryData>() ));
return;
}
if (selectReturn < 0) // ::select catch a signal (errno == EINTR)
continue;
// timeout
else if (selectReturn == 0)
{
if (waitingPong) // Timeout while waiting PONG
{
rc = -1;
// FIXME: Choose between two differents way to alert user program
clientError("Lost connection with server");
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(),
"!!! Lost connection with server",
std::list<BinaryData>() ));
return;
}
else // Timeout : Ping_interval
{
send("%s << 1,", internalPongTag.c_str());
waitingPong = true;
}
}
else
{
// We receive data, at least the "1" value sent through the pong tag
// channel so we are no longer waiting for a pong.
waitingPong = false;
int count = ::recv(sd, &recvBuffer[recvBufferPosition],
buflen - recvBufferPosition - 1, 0);
if (count <= 0)
{
std::string errorMsg;
int errorCode = 0;
if (count < 0)
{
#ifdef WIN32
errorCode = WSAGetLastError();
#else
errorCode = errno;
#endif
errorMsg = "!!! Connection error";
}
else // count == 0 => Connection close
{
errorMsg = "!!! Connection closed";
}
rc = -1;
clientError(errorMsg.c_str(), errorCode);
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(),
errorMsg.c_str(), std::list<BinaryData>() ));
return;
}
recvBufferPosition += count;
recvBuffer[recvBufferPosition] = 0;
processRecvBuffer();
}
}
}
void
UClient::printf(const char * format, ...)
{
va_list arg;
va_start(arg, format);
vfprintf(stderr, format, arg);
va_end(arg);
}
unsigned int UClient::getCurrentTime() const
{
// FIXME: Put this into libport.
#ifdef WIN32
return GetTickCount();
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000+tv.tv_usec/1000;
#endif
}
void execute()
{
while (true)
sleep(100);
}
void exit(int code)
{
::exit(code);
}
UClient& connect(const std::string& host)
{
return *new UClient(host);
}
void disconnect(UClient &client)
{
delete &client;
}
void
UClient::setKeepAliveCheck(const unsigned pingInterval,
const unsigned pongTimeout)
{
this->pingInterval = pingInterval;
this->pongTimeout = pongTimeout;
}
} // namespace urbi
|
/*
* Copyright (C) 2005-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file liburbi/uclient.cc
#if !defined WIN32
# include <libport/ctime>
# include <libport/csignal>
#endif
#include <boost/lambda/bind.hpp>
#include <libport/boost-error.hh>
#include <libport/format.hh>
#include <urbi/uclient.hh>
#include <urbi/utag.hh>
#include <liburbi/compatibility.hh>
GD_CATEGORY(Urbi.Client);
namespace urbi
{
/*-------------------.
| UClient::options. |
`-------------------*/
UClient::options::options(bool server)
: server_(server)
// Unless stated otherwise, auto start.
, start_(true)
, asynchronous_(false)
{
}
UCLIENT_OPTION_IMPL(UClient, bool, server)
UCLIENT_OPTION_IMPL(UClient, bool, start)
UCLIENT_OPTION_IMPL(UClient, bool, asynchronous)
/*----------.
| UClient. |
`----------*/
UClient::UClient(const std::string& host, unsigned port,
size_t buflen,
const options& opt)
: UAbstractClient(host, port, buflen, opt.server())
, ping_interval_(0)
, pong_timeout_(0)
, link_(new UClient*(this))
, ping_sent_(libport::utime())
, ping_sem_(0)
, asynchronous_(opt.asynchronous())
, synchronous_send_(false)
{
if (opt.start())
start();
}
UClient::error_type
UClient::start()
{
return rc = server_ ? listen_() : connect_();
}
UClient::error_type
UClient::connect_()
{
if (boost::system::error_code erc = connect(host_, port_, false, 0,
asynchronous_))
{
libport::boost_error(libport::format("UClient::UClient connect(%s, %s)",
host_, port_),
erc);
return -1;
}
else
return 0;
}
UClient::error_type
UClient::listen_()
{
if (boost::system::error_code erc =
listen(boost::bind(&UClient::mySocketFactory, this), host_, port_))
{
libport::boost_error(libport::format("UClient::UClient listen(%s, %s)",
host_, port_),
erc);
return -1;
}
else
return 0;
}
UClient::~UClient()
{
*link_ = 0;
closeUClient();
}
UClient::error_type
UClient::onClose()
{
if (closed_)
return 1;
UAbstractClient::onClose();
return 0;
}
UClient::error_type
UClient::closeUClient()
{
close();
onClose();
return 0;
}
UClient::error_type
UClient::effectiveSend(const void* buffer, size_t size)
{
if (rc)
return -1;
if (synchronous_send_)
libport::Socket::syncWrite(buffer, size);
else
libport::Socket::write(buffer, size);
return 0;
}
libport::Socket*
UClient::mySocketFactory()
{
return this;
}
void
UClient::onConnect()
{
init_ = true;
onConnection();
// Declare ping channel for kernel that requires it. Do not try
// to depend on kernelMajor, because it has not been computed yet.
// And computing kernelMajor requires this code to be run. So we
// need to write something that both k1 and k2 will like.
send(SYNCLINE_WRAP(
"if (isdef(Channel))\n"
" var lobby.%s = Channel.new(\"%s\")|;",
internalPongTag, internalPongTag));
// The folowwing calls may fail if we got disconnected.
try
{
host_ = getRemoteHost();
port_ = getRemotePort();
}
catch(const std::exception&)
{ // Ignore the error, next read attempt will trigger onError.
}
if (ping_interval_)
sendPing(link_);
}
void
UClient::onError(boost::system::error_code erc)
{
rc = -1;
resetAsyncCalls_();
clientError("!!! " + erc.message());
notifyCallbacks(UMessage(*this, 0, CLIENTERROR_TAG,
"!!! " + erc.message()));
return;
}
size_t
UClient::onRead(const void* data, size_t length)
{
size_t capacity = recvBufSize - recvBufferPosition - 1;
if (ping_interval_ && ping_sem_.uget(1))
{
pong_timeout_handler_->cancel();
send_ping_handler_ =
libport::asyncCall(boost::bind(&UClient::sendPing,
this, link_),
ping_interval_ - (libport::utime() - ping_sent_));
}
if (capacity < length)
{
size_t nsz = std::max(recvBufSize*2, recvBufferPosition + length+1);
char* nbuf = new char[nsz];
memcpy(nbuf, recvBuffer, recvBufferPosition);
delete[] recvBuffer;
recvBuffer = nbuf;
recvBufSize = nsz;
}
memcpy(&recvBuffer[recvBufferPosition], data, length);
recvBufferPosition += length;
recvBuffer[recvBufferPosition] = 0;
processRecvBuffer();
return length;
}
void
UClient::pongTimeout(link_type l)
{
if (*l)
{
const char* err = "!!! Lost connection with server: ping timeout";
// FIXME: Choose between two differents way to alert user program.
clientError(err);
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, err));
close();
}
}
void
UClient::sendPing(link_type l)
{
if (*l)
{
pong_timeout_handler_ =
libport::asyncCall(boost::bind(&UClient::pongTimeout, this, link_),
pong_timeout_);
send("%s << 1,", internalPongTag);
ping_sent_ = libport::utime();
ping_sem_++;
}
}
void
UClient::printf(const char * format, ...)
{
va_list arg;
va_start(arg, format);
vfprintf(stderr, format, arg);
va_end(arg);
}
unsigned int UClient::getCurrentTime() const
{
// FIXME: Put this into libport.
#ifdef WIN32
return GetTickCount();
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000+tv.tv_usec/1000;
#endif
}
void
UClient::setKeepAliveCheck(unsigned ping_interval,
unsigned pong_timeout)
{
// Always interrupt previous ping handler.
resetAsyncCalls_();
// From milliseconds to microseconds.
ping_interval_ = ping_interval * 1000;
pong_timeout_ = pong_timeout * 1000;
if (ping_interval_)
sendPing(link_);
}
void
UClient::resetAsyncCalls_()
{
if (pong_timeout_handler_)
{
pong_timeout_handler_->cancel();
pong_timeout_handler_.reset();
}
if (send_ping_handler_)
{
send_ping_handler_->cancel();
send_ping_handler_.reset();
}
}
void
UClient::waitForKernelVersion() const
{
// FIXME: use a condition.
while (kernelMajor_ < 0 && !error())
sleep(100000);
}
void
UClient::setSynchronousSend(bool enable)
{
synchronous_send_ = enable;
}
/*-----------------------.
| Standalone functions. |
`-----------------------*/
void execute()
{
while (true)
sleep(100);
}
void exit(int code)
{
::exit(code);
}
UClient&
connect(const std::string& host)
{
return *new UClient(host);
}
void disconnect(UClient &client)
{
// Asynchronous deletion to let our async handlers terminate.
client.destroy();
}
} // namespace urbi
uclient: style changes.
* sdk-remote/src/liburbi/uclient.cc: here.
And more logs.
/*
* Copyright (C) 2005-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file liburbi/uclient.cc
#if !defined WIN32
# include <libport/ctime>
# include <libport/csignal>
#endif
#include <boost/lambda/bind.hpp>
#include <libport/boost-error.hh>
#include <libport/format.hh>
#include <urbi/uclient.hh>
#include <urbi/utag.hh>
#include <liburbi/compatibility.hh>
GD_CATEGORY(Urbi.Client);
namespace urbi
{
/*-------------------.
| UClient::options. |
`-------------------*/
UClient::options::options(bool server)
: server_(server)
// Unless stated otherwise, auto start.
, start_(true)
, asynchronous_(false)
{
}
UCLIENT_OPTION_IMPL(UClient, bool, server)
UCLIENT_OPTION_IMPL(UClient, bool, start)
UCLIENT_OPTION_IMPL(UClient, bool, asynchronous)
/*----------.
| UClient. |
`----------*/
UClient::UClient(const std::string& host, unsigned port,
size_t buflen,
const options& opt)
: UAbstractClient(host, port, buflen, opt.server())
, ping_interval_(0)
, pong_timeout_(0)
, link_(new UClient*(this))
, ping_sent_(libport::utime())
, ping_sem_(0)
, asynchronous_(opt.asynchronous())
, synchronous_send_(false)
{
if (opt.start())
start();
}
UClient::error_type
UClient::start()
{
return rc = server_ ? listen_() : connect_();
}
UClient::error_type
UClient::connect_()
{
if (boost::system::error_code erc = connect(host_, port_, false, 0,
asynchronous_))
{
libport::boost_error(libport::format("UClient::UClient connect(%s, %s)",
host_, port_),
erc);
return -1;
}
else
return 0;
}
UClient::error_type
UClient::listen_()
{
if (boost::system::error_code erc =
listen(boost::bind(&UClient::mySocketFactory, this), host_, port_))
{
libport::boost_error(libport::format("UClient::UClient listen(%s, %s)",
host_, port_),
erc);
return -1;
}
else
return 0;
}
UClient::~UClient()
{
*link_ = 0;
closeUClient();
}
UClient::error_type
UClient::onClose()
{
if (!closed_)
UAbstractClient::onClose();
return !!closed_;
}
UClient::error_type
UClient::closeUClient()
{
close();
onClose();
return 0;
}
UClient::error_type
UClient::effectiveSend(const void* buffer, size_t size)
{
if (rc)
return -1;
if (synchronous_send_)
libport::Socket::syncWrite(buffer, size);
else
libport::Socket::write(buffer, size);
return 0;
}
libport::Socket*
UClient::mySocketFactory()
{
return this;
}
void
UClient::onConnect()
{
init_ = true;
onConnection();
// Declare ping channel for kernel that requires it. Do not try
// to depend on kernelMajor, because it has not been computed yet.
// And computing kernelMajor requires this code to be run. So we
// need to write something that both k1 and k2 will like.
send(SYNCLINE_WRAP(
"if (isdef(Channel))\n"
" var lobby.%s = Channel.new(\"%s\")|;",
internalPongTag, internalPongTag));
// The folowwing calls may fail if we got disconnected.
try
{
host_ = getRemoteHost();
port_ = getRemotePort();
}
catch (const std::exception& e)
{
// Ignore the error, next read attempt will trigger onError.
GD_FINFO_DUMP("ignore std::exception: %s", e.what());
}
if (ping_interval_)
sendPing(link_);
}
void
UClient::onError(boost::system::error_code erc)
{
rc = -1;
resetAsyncCalls_();
clientError("!!! " + erc.message());
notifyCallbacks(UMessage(*this, 0, CLIENTERROR_TAG,
"!!! " + erc.message()));
return;
}
size_t
UClient::onRead(const void* data, size_t length)
{
size_t capacity = recvBufSize - recvBufferPosition - 1;
if (ping_interval_ && ping_sem_.uget(1))
{
pong_timeout_handler_->cancel();
send_ping_handler_ =
libport::asyncCall(boost::bind(&UClient::sendPing,
this, link_),
ping_interval_ - (libport::utime() - ping_sent_));
}
if (capacity < length)
{
size_t nsz = std::max(recvBufSize*2, recvBufferPosition + length+1);
char* nbuf = new char[nsz];
memcpy(nbuf, recvBuffer, recvBufferPosition);
delete[] recvBuffer;
recvBuffer = nbuf;
recvBufSize = nsz;
}
memcpy(&recvBuffer[recvBufferPosition], data, length);
recvBufferPosition += length;
recvBuffer[recvBufferPosition] = 0;
processRecvBuffer();
return length;
}
void
UClient::pongTimeout(link_type l)
{
if (*l)
{
const char* err = "!!! Lost connection with server: ping timeout";
// FIXME: Choose between two differents way to alert user program.
clientError(err);
notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, err));
close();
}
}
void
UClient::sendPing(link_type l)
{
if (*l)
{
pong_timeout_handler_ =
libport::asyncCall(boost::bind(&UClient::pongTimeout, this, link_),
pong_timeout_);
send("%s << 1,", internalPongTag);
ping_sent_ = libport::utime();
ping_sem_++;
}
}
void
UClient::printf(const char * format, ...)
{
va_list arg;
va_start(arg, format);
vfprintf(stderr, format, arg);
va_end(arg);
}
unsigned int UClient::getCurrentTime() const
{
// FIXME: Put this into libport.
#ifdef WIN32
return GetTickCount();
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000+tv.tv_usec/1000;
#endif
}
void
UClient::setKeepAliveCheck(unsigned ping_interval,
unsigned pong_timeout)
{
// Always interrupt previous ping handler.
resetAsyncCalls_();
// From milliseconds to microseconds.
ping_interval_ = ping_interval * 1000;
pong_timeout_ = pong_timeout * 1000;
if (ping_interval_)
sendPing(link_);
}
void
UClient::resetAsyncCalls_()
{
if (pong_timeout_handler_)
{
pong_timeout_handler_->cancel();
pong_timeout_handler_.reset();
}
if (send_ping_handler_)
{
send_ping_handler_->cancel();
send_ping_handler_.reset();
}
}
void
UClient::waitForKernelVersion() const
{
// FIXME: use a condition.
while (kernelMajor_ < 0 && !error())
sleep(100000);
}
void
UClient::setSynchronousSend(bool enable)
{
synchronous_send_ = enable;
}
/*-----------------------.
| Standalone functions. |
`-----------------------*/
void execute()
{
while (true)
sleep(100);
}
void exit(int code)
{
::exit(code);
}
UClient&
connect(const std::string& host)
{
return *new UClient(host);
}
void disconnect(UClient &client)
{
// Asynchronous deletion to let our async handlers terminate.
client.destroy();
}
} // namespace urbi
|
#include <libmesh/distributed_mesh.h>
#include <libmesh/dof_map.h>
#include <libmesh/equation_systems.h>
#include <libmesh/linear_implicit_system.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_communication.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/numeric_vector.h>
#include <libmesh/replicated_mesh.h>
#include <libmesh/dyna_io.h>
#include <libmesh/exodusII_io.h>
#include <libmesh/nemesis_io.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
Number six_x_plus_sixty_y (const Point& p,
const Parameters&,
const std::string&,
const std::string&)
{
const Real & x = p(0);
const Real & y = p(1);
return 6*x + 60*y;
}
class MeshInputTest : public CppUnit::TestCase {
public:
CPPUNIT_TEST_SUITE( MeshInputTest );
#if LIBMESH_DIM > 1
#ifdef LIBMESH_HAVE_EXODUS_API
// Still not yet working?
// CPPUNIT_TEST( testExodusCopyNodalSolutionDistributed );
// CPPUNIT_TEST( testExodusCopyElementSolutionDistributed );
CPPUNIT_TEST( testExodusCopyNodalSolutionReplicated );
CPPUNIT_TEST( testExodusCopyElementSolutionReplicated );
CPPUNIT_TEST( testExodusReadHeader );
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
// Eventually this will support complex numbers.
CPPUNIT_TEST( testExodusWriteElementDataFromDiscontinuousNodalData );
#endif // LIBMESH_USE_COMPLEX_NUMBERS
#endif // LIBMESH_HAVE_EXODUS_API
#if defined(LIBMESH_HAVE_EXODUS_API) && defined(LIBMESH_HAVE_NEMESIS_API)
CPPUNIT_TEST( testNemesisReadReplicated );
CPPUNIT_TEST( testNemesisReadDistributed );
CPPUNIT_TEST( testNemesisCopyNodalSolutionDistributed );
CPPUNIT_TEST( testNemesisCopyNodalSolutionReplicated );
CPPUNIT_TEST( testNemesisCopyElementSolutionDistributed );
CPPUNIT_TEST( testNemesisCopyElementSolutionReplicated );
#endif
CPPUNIT_TEST( testDynaReadElem );
CPPUNIT_TEST( testDynaReadPatch );
CPPUNIT_TEST( testDynaFileMappingsFEMEx5);
CPPUNIT_TEST( testMeshMoveConstructor );
#endif // LIBMESH_DIM > 1
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp()
{}
void tearDown()
{}
#ifdef LIBMESH_HAVE_EXODUS_API
void testExodusReadHeader ()
{
// first scope: write file
{
ReplicatedMesh mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh, 3, 3, 0., 1., 0., 1.);
ExodusII_IO exii(mesh);
mesh.write("read_header_test.e");
}
// Make sure that the writing is done before the reading starts.
TestCommWorld->barrier();
// second scope: read header
// Note: The header information is read from file on processor 0
// and then broadcast to the other procs, so with this test we are
// checking both that the header information is read correctly and
// that it is correctly communicated to other procs.
{
ReplicatedMesh mesh(*TestCommWorld);
ExodusII_IO exii(mesh);
ExodusHeaderInfo header_info = exii.read_header("read_header_test.e");
// Make sure the header information is as expected.
CPPUNIT_ASSERT_EQUAL(std::string(header_info.title.data()), std::string("read_header_test.e"));
CPPUNIT_ASSERT_EQUAL(header_info.num_dim, 2);
CPPUNIT_ASSERT_EQUAL(header_info.num_elem, 9);
CPPUNIT_ASSERT_EQUAL(header_info.num_elem_blk, 1);
CPPUNIT_ASSERT_EQUAL(header_info.num_node_sets, 0);
CPPUNIT_ASSERT_EQUAL(header_info.num_side_sets, 4);
CPPUNIT_ASSERT_EQUAL(header_info.num_edge_blk, 0);
CPPUNIT_ASSERT_EQUAL(header_info.num_edge, 0);
}
}
template <typename MeshType, typename IOType>
void testCopyNodalSolutionImpl (const std::string & filename)
{
{
MeshType mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("n", FIRST, LAGRANGE);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
es.init();
sys.project_solution(six_x_plus_sixty_y, nullptr, es.parameters);
IOType meshoutput(mesh);
meshoutput.write_equation_systems(filename, es);
}
{
MeshType mesh(*TestCommWorld);
IOType meshinput(mesh);
// Avoid getting Nemesis solution values mixed up
if (meshinput.is_parallel_format())
{
mesh.allow_renumbering(false);
mesh.skip_noncritical_partitioning(true);
}
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("testn", FIRST, LAGRANGE);
if (mesh.processor_id() == 0 || meshinput.is_parallel_format())
meshinput.read(filename);
if (!meshinput.is_parallel_format())
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
// Read the solution e into variable teste.
//
// With complex numbers, we'll only bother reading the real
// part.
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
meshinput.copy_nodal_solution(sys, "testn", "r_n");
#else
meshinput.copy_nodal_solution(sys, "testn", "n");
#endif
// Exodus only handles double precision
Real exotol = std::max(TOLERANCE*TOLERANCE, Real(1e-12));
for (Real x = 0; x < 1 + TOLERANCE; x += Real(1.L/3.L))
for (Real y = 0; y < 1 + TOLERANCE; y += Real(1.L/3.L))
{
Point p(x,y);
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(sys.point_value(0,p)),
libmesh_real(6*x+60*y),
exotol);
}
}
}
void testExodusCopyNodalSolutionReplicated ()
{ testCopyNodalSolutionImpl<ReplicatedMesh,ExodusII_IO>("repl_with_nodal_soln.e"); }
void testExodusCopyNodalSolutionDistributed ()
{ testCopyNodalSolutionImpl<DistributedMesh,ExodusII_IO>("dist_with_nodal_soln.e"); }
#if defined(LIBMESH_HAVE_NEMESIS_API)
void testNemesisCopyNodalSolutionReplicated ()
{ testCopyNodalSolutionImpl<ReplicatedMesh,Nemesis_IO>("repl_with_nodal_soln.nem"); }
void testNemesisCopyNodalSolutionDistributed ()
{ testCopyNodalSolutionImpl<DistributedMesh,Nemesis_IO>("dist_with_nodal_soln.nem"); }
#endif
template <typename MeshType, typename IOType>
void testCopyElementSolutionImpl (const std::string & filename)
{
{
MeshType mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("e", CONSTANT, MONOMIAL);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
es.init();
sys.project_solution(six_x_plus_sixty_y, nullptr, es.parameters);
IOType meshinput(mesh);
// Don't try to write element data as nodal data
std::set<std::string> sys_list;
meshinput.write_equation_systems(filename, es, &sys_list);
// Just write it as element data
meshinput.write_element_data(es);
}
{
MeshType mesh(*TestCommWorld);
IOType meshinput(mesh);
// Avoid getting Nemesis solution values mixed up
if (meshinput.is_parallel_format())
{
mesh.allow_renumbering(false);
mesh.skip_noncritical_partitioning(true);
}
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("teste", CONSTANT, MONOMIAL);
if (mesh.processor_id() == 0 || meshinput.is_parallel_format())
meshinput.read(filename);
if (!meshinput.is_parallel_format())
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
// Read the solution e into variable teste.
//
// With complex numbers, we'll only bother reading the real
// part.
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
meshinput.copy_elemental_solution(sys, "teste", "r_e");
#else
meshinput.copy_elemental_solution(sys, "teste", "e");
#endif
// Exodus only handles double precision
Real exotol = std::max(TOLERANCE*TOLERANCE, Real(1e-12));
for (Real x = Real(1.L/6.L); x < 1; x += Real(1.L/3.L))
for (Real y = Real(1.L/6.L); y < 1; y += Real(1.L/3.L))
{
Point p(x,y);
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(sys.point_value(0,p)),
libmesh_real(6*x+60*y),
exotol);
}
}
}
void testExodusCopyElementSolutionReplicated ()
{ testCopyElementSolutionImpl<ReplicatedMesh,ExodusII_IO>("repl_with_elem_soln.e"); }
void testExodusCopyElementSolutionDistributed ()
{ testCopyElementSolutionImpl<DistributedMesh,ExodusII_IO>("dist_with_elem_soln.e"); }
#if defined(LIBMESH_HAVE_NEMESIS_API)
void testNemesisCopyElementSolutionReplicated ()
{ testCopyElementSolutionImpl<ReplicatedMesh,Nemesis_IO>("repl_with_elem_soln.nem"); }
void testNemesisCopyElementSolutionDistributed ()
{ testCopyElementSolutionImpl<DistributedMesh,Nemesis_IO>("dist_with_elem_soln.nem"); }
#endif
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
void testExodusWriteElementDataFromDiscontinuousNodalData()
{
// first scope: write file
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", FIRST, L2_LAGRANGE);
MeshTools::Generation::build_cube
(mesh, 2, 2, 2, 0., 1., 0., 1., 0., 1., HEX8);
es.init();
// Set solution u^e_i = i, for the ith vertex of a given element e.
const DofMap & dof_map = sys.get_dof_map();
std::vector<dof_id_type> dof_indices;
for (const auto & elem : mesh.element_ptr_range())
{
dof_map.dof_indices(elem, dof_indices, /*var_id=*/0);
for (unsigned int i=0; i<dof_indices.size(); ++i)
sys.solution->set(dof_indices[i], i);
}
sys.solution->close();
// Now write to file.
ExodusII_IO exii(mesh);
// Don't try to write element data as averaged nodal data.
std::set<std::string> sys_list;
exii.write_equation_systems("elemental_from_nodal.e", es, &sys_list);
// Write one elemental data field per vertex value.
sys_list = {"SimpleSystem"};
exii.write_element_data_from_discontinuous_nodal_data
(es, &sys_list, /*var_suffix=*/"_elem_corner_");
} // end first scope
// second scope: read values back in, verify they are correct.
{
std::vector<std::string> file_var_names =
{"u_elem_corner_0",
"u_elem_corner_1",
"u_elem_corner_2",
"u_elem_corner_3"};
std::vector<Real> expected_values = {0., 1., 2., 3.};
// copy_elemental_solution currently requires ReplicatedMesh
ReplicatedMesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
for (auto i : index_range(file_var_names))
sys.add_variable(file_var_names[i], CONSTANT, MONOMIAL);
ExodusII_IO exii(mesh);
if (mesh.processor_id() == 0)
exii.read("elemental_from_nodal.e");
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
for (auto i : index_range(file_var_names))
exii.copy_elemental_solution
(sys, sys.variable_name(i), file_var_names[i]);
// Check that the values we read back in are as expected.
for (const auto & elem : mesh.active_element_ptr_range())
for (auto i : index_range(file_var_names))
{
Real read_val = sys.point_value(i, elem->centroid());
LIBMESH_ASSERT_FP_EQUAL
(expected_values[i], read_val, TOLERANCE*TOLERANCE);
}
} // end second scope
} // end testExodusWriteElementDataFromDiscontinuousNodalData
#endif // !LIBMESH_USE_COMPLEX_NUMBERS
#endif // LIBMESH_HAVE_EXODUS_API
#if defined(LIBMESH_HAVE_EXODUS_API) && defined(LIBMESH_HAVE_NEMESIS_API)
template <typename MeshType>
void testNemesisReadImpl ()
{
// first scope: write file
{
MeshType mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh, 3, 3, 0., 1., 0., 1.);
mesh.write("test_nemesis_read.nem");
}
// Make sure that the writing is done before the reading starts.
TestCommWorld->barrier();
// second scope: read file
{
MeshType mesh(*TestCommWorld);
Nemesis_IO nem(mesh);
nem.read("test_nemesis_read.nem");
mesh.prepare_for_use();
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(9));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(16));
}
}
void testNemesisReadReplicated ()
{ testNemesisReadImpl<ReplicatedMesh>(); }
void testNemesisReadDistributed ()
{ testNemesisReadImpl<DistributedMesh>(); }
#endif
void testMasterCenters (const MeshBase & mesh)
{
auto locator = mesh.sub_point_locator();
const std::set<subdomain_id_type> manifold_subdomain { 0 };
const std::set<subdomain_id_type> nodeelem_subdomain { 1 };
for (auto & elem : mesh.element_ptr_range())
{
Point master_pt = {}; // center, for tensor product elements
FEMap fe_map;
Point physical_pt = fe_map.map(elem->dim(), elem, master_pt);
Point inverse_pt = fe_map.inverse_map(elem->dim(), elem,
physical_pt);
CPPUNIT_ASSERT(inverse_pt.norm() < TOLERANCE);
CPPUNIT_ASSERT(elem->contains_point(physical_pt));
const std::set<subdomain_id_type> * sbd_set =
(elem->type() == NODEELEM) ?
&nodeelem_subdomain : &manifold_subdomain;
const Elem * located_elem = (*locator)(physical_pt, sbd_set);
CPPUNIT_ASSERT(located_elem == elem);
}
}
void testDynaReadElem ()
{
Mesh mesh(*TestCommWorld);
DynaIO dyna(mesh);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
if (mesh.processor_id() == 0)
dyna.read("meshes/1_quad.bxt.gz");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 1 QUAD9 finite element, attached via a trivial map to 9
// spline Node+NodeElem objects
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(10));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(18));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
for (auto & elem : mesh.element_ptr_range())
{
if (elem->type() == NODEELEM)
continue;
CPPUNIT_ASSERT_EQUAL(elem->type(), QUAD9);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem->node_ref(n).get_extra_datum<Real>(weight_index),
Real(0.75));
CPPUNIT_ASSERT_EQUAL(elem->point(0)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(0)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(1)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem->point(1)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(2)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem->point(2)(1), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem->point(3)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(3)(1), Real(1.5));
CPPUNIT_ASSERT(elem->has_affine_map());
#if LIBMESH_DIM > 2
for (unsigned int v=0; v != 4; ++v)
CPPUNIT_ASSERT_EQUAL(elem->point(v)(2), Real(0));
#endif
}
testMasterCenters(mesh);
}
void testDynaReadPatch ()
{
Mesh mesh(*TestCommWorld);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
DynaIO dyna(mesh);
if (mesh.processor_id() == 0)
dyna.read("meshes/25_quad.bxt.gz");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 5^2 QUAD9 elements, with 11^2 nodes,
// tied to 49 Node/NodeElem spline nodes
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(25+49));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(121+49));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
for (const auto & elem : mesh.active_element_ptr_range())
{
if (elem->type() == NODEELEM)
continue;
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(0.04), elem->volume(), TOLERANCE);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem->node_ref(n).get_extra_datum<Real>(weight_index),
Real(1.0));
unsigned int n_neighbors = 0, n_neighbors_expected = 2;
for (unsigned int side=0; side != 4; ++side)
if (elem->neighbor_ptr(side))
n_neighbors++;
Point c = elem->centroid();
if (c(0) > 0.2 && c(0) < 0.8)
n_neighbors_expected++;
if (c(1) > 0.2 && c(1) < 0.8)
n_neighbors_expected++;
CPPUNIT_ASSERT_EQUAL(n_neighbors, n_neighbors_expected);
}
testMasterCenters(mesh);
#ifdef LIBMESH_HAVE_SOLVER
#ifdef LIBMESH_ENABLE_CONSTRAINTS
// Now test whether we can assign the desired constraint equations
EquationSystems es(mesh);
System & sys = es.add_system<LinearImplicitSystem>("test");
sys.add_variable("u", SECOND); // to match QUAD9
es.init();
dyna.add_spline_constraints(sys.get_dof_map(), 0, 0);
// We should have a constraint on every FE dof
CPPUNIT_ASSERT_EQUAL(sys.get_dof_map().n_constrained_dofs(), dof_id_type(121));
#endif // LIBMESH_ENABLE_CONSTRAINTS
#endif // LIBMESH_HAVE_SOLVER
}
void testDynaFileMappings (const std::string & filename)
{
Mesh mesh(*TestCommWorld);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
DynaIO dyna(mesh);
if (mesh.processor_id() == 0)
dyna.read(filename);
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
testMasterCenters(mesh);
}
void testDynaFileMappingsFEMEx5 ()
{
testDynaFileMappings("meshes/PressurizedCyl_Patch6_256Elem.bxt.gz");
}
void testMeshMoveConstructor ()
{
Mesh mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
// Construct mesh2, stealing the resources of the original.
Mesh mesh2(std::move(mesh));
// Make sure mesh2 now has the 9 elements.
CPPUNIT_ASSERT_EQUAL(mesh2.n_elem(),
static_cast<dof_id_type>(9));
// Verify that the moved-from mesh's Partitioner and BoundaryInfo
// objects were successfully stolen. Note: moved-from unique_ptrs
// are guaranteed to compare equal to nullptr, see e.g. Section
// 20.8.1/4 of the standard.
// https://stackoverflow.com/questions/24061767/is-unique-ptr-guaranteed-to-store-nullptr-after-move
CPPUNIT_ASSERT(!mesh.partitioner());
CPPUNIT_ASSERT(!mesh.boundary_info);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( MeshInputTest );
Test inverse_map on less trivial master points
I'm *still* not seeing warnings like in fem_system_ex5, though.
#include <libmesh/distributed_mesh.h>
#include <libmesh/dof_map.h>
#include <libmesh/equation_systems.h>
#include <libmesh/linear_implicit_system.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_communication.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/numeric_vector.h>
#include <libmesh/replicated_mesh.h>
#include <libmesh/dyna_io.h>
#include <libmesh/exodusII_io.h>
#include <libmesh/nemesis_io.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
Number six_x_plus_sixty_y (const Point& p,
const Parameters&,
const std::string&,
const std::string&)
{
const Real & x = p(0);
const Real & y = p(1);
return 6*x + 60*y;
}
class MeshInputTest : public CppUnit::TestCase {
public:
CPPUNIT_TEST_SUITE( MeshInputTest );
#if LIBMESH_DIM > 1
#ifdef LIBMESH_HAVE_EXODUS_API
// Still not yet working?
// CPPUNIT_TEST( testExodusCopyNodalSolutionDistributed );
// CPPUNIT_TEST( testExodusCopyElementSolutionDistributed );
CPPUNIT_TEST( testExodusCopyNodalSolutionReplicated );
CPPUNIT_TEST( testExodusCopyElementSolutionReplicated );
CPPUNIT_TEST( testExodusReadHeader );
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
// Eventually this will support complex numbers.
CPPUNIT_TEST( testExodusWriteElementDataFromDiscontinuousNodalData );
#endif // LIBMESH_USE_COMPLEX_NUMBERS
#endif // LIBMESH_HAVE_EXODUS_API
#if defined(LIBMESH_HAVE_EXODUS_API) && defined(LIBMESH_HAVE_NEMESIS_API)
CPPUNIT_TEST( testNemesisReadReplicated );
CPPUNIT_TEST( testNemesisReadDistributed );
CPPUNIT_TEST( testNemesisCopyNodalSolutionDistributed );
CPPUNIT_TEST( testNemesisCopyNodalSolutionReplicated );
CPPUNIT_TEST( testNemesisCopyElementSolutionDistributed );
CPPUNIT_TEST( testNemesisCopyElementSolutionReplicated );
#endif
CPPUNIT_TEST( testDynaReadElem );
CPPUNIT_TEST( testDynaReadPatch );
CPPUNIT_TEST( testDynaFileMappingsFEMEx5);
CPPUNIT_TEST( testMeshMoveConstructor );
#endif // LIBMESH_DIM > 1
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp()
{}
void tearDown()
{}
#ifdef LIBMESH_HAVE_EXODUS_API
void testExodusReadHeader ()
{
// first scope: write file
{
ReplicatedMesh mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh, 3, 3, 0., 1., 0., 1.);
ExodusII_IO exii(mesh);
mesh.write("read_header_test.e");
}
// Make sure that the writing is done before the reading starts.
TestCommWorld->barrier();
// second scope: read header
// Note: The header information is read from file on processor 0
// and then broadcast to the other procs, so with this test we are
// checking both that the header information is read correctly and
// that it is correctly communicated to other procs.
{
ReplicatedMesh mesh(*TestCommWorld);
ExodusII_IO exii(mesh);
ExodusHeaderInfo header_info = exii.read_header("read_header_test.e");
// Make sure the header information is as expected.
CPPUNIT_ASSERT_EQUAL(std::string(header_info.title.data()), std::string("read_header_test.e"));
CPPUNIT_ASSERT_EQUAL(header_info.num_dim, 2);
CPPUNIT_ASSERT_EQUAL(header_info.num_elem, 9);
CPPUNIT_ASSERT_EQUAL(header_info.num_elem_blk, 1);
CPPUNIT_ASSERT_EQUAL(header_info.num_node_sets, 0);
CPPUNIT_ASSERT_EQUAL(header_info.num_side_sets, 4);
CPPUNIT_ASSERT_EQUAL(header_info.num_edge_blk, 0);
CPPUNIT_ASSERT_EQUAL(header_info.num_edge, 0);
}
}
template <typename MeshType, typename IOType>
void testCopyNodalSolutionImpl (const std::string & filename)
{
{
MeshType mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("n", FIRST, LAGRANGE);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
es.init();
sys.project_solution(six_x_plus_sixty_y, nullptr, es.parameters);
IOType meshoutput(mesh);
meshoutput.write_equation_systems(filename, es);
}
{
MeshType mesh(*TestCommWorld);
IOType meshinput(mesh);
// Avoid getting Nemesis solution values mixed up
if (meshinput.is_parallel_format())
{
mesh.allow_renumbering(false);
mesh.skip_noncritical_partitioning(true);
}
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("testn", FIRST, LAGRANGE);
if (mesh.processor_id() == 0 || meshinput.is_parallel_format())
meshinput.read(filename);
if (!meshinput.is_parallel_format())
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
// Read the solution e into variable teste.
//
// With complex numbers, we'll only bother reading the real
// part.
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
meshinput.copy_nodal_solution(sys, "testn", "r_n");
#else
meshinput.copy_nodal_solution(sys, "testn", "n");
#endif
// Exodus only handles double precision
Real exotol = std::max(TOLERANCE*TOLERANCE, Real(1e-12));
for (Real x = 0; x < 1 + TOLERANCE; x += Real(1.L/3.L))
for (Real y = 0; y < 1 + TOLERANCE; y += Real(1.L/3.L))
{
Point p(x,y);
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(sys.point_value(0,p)),
libmesh_real(6*x+60*y),
exotol);
}
}
}
void testExodusCopyNodalSolutionReplicated ()
{ testCopyNodalSolutionImpl<ReplicatedMesh,ExodusII_IO>("repl_with_nodal_soln.e"); }
void testExodusCopyNodalSolutionDistributed ()
{ testCopyNodalSolutionImpl<DistributedMesh,ExodusII_IO>("dist_with_nodal_soln.e"); }
#if defined(LIBMESH_HAVE_NEMESIS_API)
void testNemesisCopyNodalSolutionReplicated ()
{ testCopyNodalSolutionImpl<ReplicatedMesh,Nemesis_IO>("repl_with_nodal_soln.nem"); }
void testNemesisCopyNodalSolutionDistributed ()
{ testCopyNodalSolutionImpl<DistributedMesh,Nemesis_IO>("dist_with_nodal_soln.nem"); }
#endif
template <typename MeshType, typename IOType>
void testCopyElementSolutionImpl (const std::string & filename)
{
{
MeshType mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("e", CONSTANT, MONOMIAL);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
es.init();
sys.project_solution(six_x_plus_sixty_y, nullptr, es.parameters);
IOType meshinput(mesh);
// Don't try to write element data as nodal data
std::set<std::string> sys_list;
meshinput.write_equation_systems(filename, es, &sys_list);
// Just write it as element data
meshinput.write_element_data(es);
}
{
MeshType mesh(*TestCommWorld);
IOType meshinput(mesh);
// Avoid getting Nemesis solution values mixed up
if (meshinput.is_parallel_format())
{
mesh.allow_renumbering(false);
mesh.skip_noncritical_partitioning(true);
}
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("teste", CONSTANT, MONOMIAL);
if (mesh.processor_id() == 0 || meshinput.is_parallel_format())
meshinput.read(filename);
if (!meshinput.is_parallel_format())
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
// Read the solution e into variable teste.
//
// With complex numbers, we'll only bother reading the real
// part.
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
meshinput.copy_elemental_solution(sys, "teste", "r_e");
#else
meshinput.copy_elemental_solution(sys, "teste", "e");
#endif
// Exodus only handles double precision
Real exotol = std::max(TOLERANCE*TOLERANCE, Real(1e-12));
for (Real x = Real(1.L/6.L); x < 1; x += Real(1.L/3.L))
for (Real y = Real(1.L/6.L); y < 1; y += Real(1.L/3.L))
{
Point p(x,y);
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(sys.point_value(0,p)),
libmesh_real(6*x+60*y),
exotol);
}
}
}
void testExodusCopyElementSolutionReplicated ()
{ testCopyElementSolutionImpl<ReplicatedMesh,ExodusII_IO>("repl_with_elem_soln.e"); }
void testExodusCopyElementSolutionDistributed ()
{ testCopyElementSolutionImpl<DistributedMesh,ExodusII_IO>("dist_with_elem_soln.e"); }
#if defined(LIBMESH_HAVE_NEMESIS_API)
void testNemesisCopyElementSolutionReplicated ()
{ testCopyElementSolutionImpl<ReplicatedMesh,Nemesis_IO>("repl_with_elem_soln.nem"); }
void testNemesisCopyElementSolutionDistributed ()
{ testCopyElementSolutionImpl<DistributedMesh,Nemesis_IO>("dist_with_elem_soln.nem"); }
#endif
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
void testExodusWriteElementDataFromDiscontinuousNodalData()
{
// first scope: write file
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", FIRST, L2_LAGRANGE);
MeshTools::Generation::build_cube
(mesh, 2, 2, 2, 0., 1., 0., 1., 0., 1., HEX8);
es.init();
// Set solution u^e_i = i, for the ith vertex of a given element e.
const DofMap & dof_map = sys.get_dof_map();
std::vector<dof_id_type> dof_indices;
for (const auto & elem : mesh.element_ptr_range())
{
dof_map.dof_indices(elem, dof_indices, /*var_id=*/0);
for (unsigned int i=0; i<dof_indices.size(); ++i)
sys.solution->set(dof_indices[i], i);
}
sys.solution->close();
// Now write to file.
ExodusII_IO exii(mesh);
// Don't try to write element data as averaged nodal data.
std::set<std::string> sys_list;
exii.write_equation_systems("elemental_from_nodal.e", es, &sys_list);
// Write one elemental data field per vertex value.
sys_list = {"SimpleSystem"};
exii.write_element_data_from_discontinuous_nodal_data
(es, &sys_list, /*var_suffix=*/"_elem_corner_");
} // end first scope
// second scope: read values back in, verify they are correct.
{
std::vector<std::string> file_var_names =
{"u_elem_corner_0",
"u_elem_corner_1",
"u_elem_corner_2",
"u_elem_corner_3"};
std::vector<Real> expected_values = {0., 1., 2., 3.};
// copy_elemental_solution currently requires ReplicatedMesh
ReplicatedMesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
for (auto i : index_range(file_var_names))
sys.add_variable(file_var_names[i], CONSTANT, MONOMIAL);
ExodusII_IO exii(mesh);
if (mesh.processor_id() == 0)
exii.read("elemental_from_nodal.e");
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
for (auto i : index_range(file_var_names))
exii.copy_elemental_solution
(sys, sys.variable_name(i), file_var_names[i]);
// Check that the values we read back in are as expected.
for (const auto & elem : mesh.active_element_ptr_range())
for (auto i : index_range(file_var_names))
{
Real read_val = sys.point_value(i, elem->centroid());
LIBMESH_ASSERT_FP_EQUAL
(expected_values[i], read_val, TOLERANCE*TOLERANCE);
}
} // end second scope
} // end testExodusWriteElementDataFromDiscontinuousNodalData
#endif // !LIBMESH_USE_COMPLEX_NUMBERS
#endif // LIBMESH_HAVE_EXODUS_API
#if defined(LIBMESH_HAVE_EXODUS_API) && defined(LIBMESH_HAVE_NEMESIS_API)
template <typename MeshType>
void testNemesisReadImpl ()
{
// first scope: write file
{
MeshType mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh, 3, 3, 0., 1., 0., 1.);
mesh.write("test_nemesis_read.nem");
}
// Make sure that the writing is done before the reading starts.
TestCommWorld->barrier();
// second scope: read file
{
MeshType mesh(*TestCommWorld);
Nemesis_IO nem(mesh);
nem.read("test_nemesis_read.nem");
mesh.prepare_for_use();
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(9));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(16));
}
}
void testNemesisReadReplicated ()
{ testNemesisReadImpl<ReplicatedMesh>(); }
void testNemesisReadDistributed ()
{ testNemesisReadImpl<DistributedMesh>(); }
#endif
void testMasterCenters (const MeshBase & mesh)
{
auto locator = mesh.sub_point_locator();
const std::set<subdomain_id_type> manifold_subdomain { 0 };
const std::set<subdomain_id_type> nodeelem_subdomain { 1 };
for (auto & elem : mesh.element_ptr_range())
{
Point master_pt = {}; // center, for tensor product elements
// But perturb it to try and trigger any mapping weirdness
if (elem->dim() > 0)
master_pt(0) = 0.25;
if (elem->dim() > 1)
master_pt(1) = -0.25;
if (elem->dim() > 2)
master_pt(2) = 0.75;
FEMap fe_map;
Point physical_pt = fe_map.map(elem->dim(), elem, master_pt);
Point inverse_pt = fe_map.inverse_map(elem->dim(), elem,
physical_pt);
CPPUNIT_ASSERT((inverse_pt-master_pt).norm() < TOLERANCE);
CPPUNIT_ASSERT(elem->contains_point(physical_pt));
const std::set<subdomain_id_type> * sbd_set =
(elem->type() == NODEELEM) ?
&nodeelem_subdomain : &manifold_subdomain;
const Elem * located_elem = (*locator)(physical_pt, sbd_set);
CPPUNIT_ASSERT(located_elem == elem);
}
}
void testDynaReadElem ()
{
Mesh mesh(*TestCommWorld);
DynaIO dyna(mesh);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
if (mesh.processor_id() == 0)
dyna.read("meshes/1_quad.bxt.gz");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 1 QUAD9 finite element, attached via a trivial map to 9
// spline Node+NodeElem objects
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(10));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(18));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
for (auto & elem : mesh.element_ptr_range())
{
if (elem->type() == NODEELEM)
continue;
CPPUNIT_ASSERT_EQUAL(elem->type(), QUAD9);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem->node_ref(n).get_extra_datum<Real>(weight_index),
Real(0.75));
CPPUNIT_ASSERT_EQUAL(elem->point(0)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(0)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(1)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem->point(1)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(2)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem->point(2)(1), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem->point(3)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem->point(3)(1), Real(1.5));
CPPUNIT_ASSERT(elem->has_affine_map());
#if LIBMESH_DIM > 2
for (unsigned int v=0; v != 4; ++v)
CPPUNIT_ASSERT_EQUAL(elem->point(v)(2), Real(0));
#endif
}
testMasterCenters(mesh);
}
void testDynaReadPatch ()
{
Mesh mesh(*TestCommWorld);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
DynaIO dyna(mesh);
if (mesh.processor_id() == 0)
dyna.read("meshes/25_quad.bxt.gz");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 5^2 QUAD9 elements, with 11^2 nodes,
// tied to 49 Node/NodeElem spline nodes
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(25+49));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(121+49));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
for (const auto & elem : mesh.active_element_ptr_range())
{
if (elem->type() == NODEELEM)
continue;
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(0.04), elem->volume(), TOLERANCE);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem->node_ref(n).get_extra_datum<Real>(weight_index),
Real(1.0));
unsigned int n_neighbors = 0, n_neighbors_expected = 2;
for (unsigned int side=0; side != 4; ++side)
if (elem->neighbor_ptr(side))
n_neighbors++;
Point c = elem->centroid();
if (c(0) > 0.2 && c(0) < 0.8)
n_neighbors_expected++;
if (c(1) > 0.2 && c(1) < 0.8)
n_neighbors_expected++;
CPPUNIT_ASSERT_EQUAL(n_neighbors, n_neighbors_expected);
}
testMasterCenters(mesh);
#ifdef LIBMESH_HAVE_SOLVER
#ifdef LIBMESH_ENABLE_CONSTRAINTS
// Now test whether we can assign the desired constraint equations
EquationSystems es(mesh);
System & sys = es.add_system<LinearImplicitSystem>("test");
sys.add_variable("u", SECOND); // to match QUAD9
es.init();
dyna.add_spline_constraints(sys.get_dof_map(), 0, 0);
// We should have a constraint on every FE dof
CPPUNIT_ASSERT_EQUAL(sys.get_dof_map().n_constrained_dofs(), dof_id_type(121));
#endif // LIBMESH_ENABLE_CONSTRAINTS
#endif // LIBMESH_HAVE_SOLVER
}
void testDynaFileMappings (const std::string & filename)
{
Mesh mesh(*TestCommWorld);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
DynaIO dyna(mesh);
if (mesh.processor_id() == 0)
dyna.read(filename);
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
testMasterCenters(mesh);
}
void testDynaFileMappingsFEMEx5 ()
{
testDynaFileMappings("meshes/PressurizedCyl_Patch6_256Elem.bxt.gz");
}
void testMeshMoveConstructor ()
{
Mesh mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
// Construct mesh2, stealing the resources of the original.
Mesh mesh2(std::move(mesh));
// Make sure mesh2 now has the 9 elements.
CPPUNIT_ASSERT_EQUAL(mesh2.n_elem(),
static_cast<dof_id_type>(9));
// Verify that the moved-from mesh's Partitioner and BoundaryInfo
// objects were successfully stolen. Note: moved-from unique_ptrs
// are guaranteed to compare equal to nullptr, see e.g. Section
// 20.8.1/4 of the standard.
// https://stackoverflow.com/questions/24061767/is-unique-ptr-guaranteed-to-store-nullptr-after-move
CPPUNIT_ASSERT(!mesh.partitioner());
CPPUNIT_ASSERT(!mesh.boundary_info);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( MeshInputTest );
|
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2022 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoUIInternal.hpp"
#include "travesty/base.h"
#include "travesty/edit_controller.h"
#include "travesty/host.h"
#include "travesty/view.h"
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI && defined(DISTRHO_OS_WINDOWS)
# include <winuser.h>
# define DPF_VST3_WIN32_TIMER_ID 1
#endif
/* TODO items:
* - mousewheel event
* - key down/up events
* - host-side resizing
* - file request?
*/
#if !(defined(DISTRHO_OS_MAC) || defined(DISTRHO_OS_WINDOWS))
# define DPF_VST3_USING_HOST_RUN_LOOP 1
#else
# define DPF_VST3_USING_HOST_RUN_LOOP 0
#endif
#ifndef DPF_VST3_TIMER_INTERVAL
# define DPF_VST3_TIMER_INTERVAL 16 /* ~60 fps */
#endif
START_NAMESPACE_DISTRHO
// --------------------------------------------------------------------------------------------------------------------
#if ! DISTRHO_PLUGIN_WANT_MIDI_INPUT
static constexpr const sendNoteFunc sendNoteCallback = nullptr;
#endif
#if ! DISTRHO_PLUGIN_WANT_STATE
static constexpr const setStateFunc setStateCallback = nullptr;
#endif
// --------------------------------------------------------------------------------------------------------------------
// Static data, see DistrhoPlugin.cpp
extern const char* d_nextBundlePath;
// --------------------------------------------------------------------------------------------------------------------
// Utility functions (defined on plugin side)
const char* tuid2str(const v3_tuid iid);
// --------------------------------------------------------------------------------------------------------------------
static void applyGeometryConstraints(const uint minimumWidth,
const uint minimumHeight,
const bool keepAspectRatio,
v3_view_rect* const rect)
{
d_stdout("applyGeometryConstraints %u %u %d {%d,%d,%d,%d} | BEFORE",
minimumWidth, minimumHeight, keepAspectRatio, rect->top, rect->left, rect->right, rect->bottom);
const int32_t minWidth = static_cast<int32_t>(minimumWidth);
const int32_t minHeight = static_cast<int32_t>(minimumHeight);
if (keepAspectRatio)
{
const double ratio = static_cast<double>(minWidth) / static_cast<double>(minHeight);
const double reqRatio = static_cast<double>(rect->right) / static_cast<double>(rect->bottom);
if (d_isNotEqual(ratio, reqRatio))
{
// fix width
if (reqRatio > ratio)
rect->right = static_cast<int32_t>(rect->bottom * ratio + 0.5);
// fix height
else
rect->bottom = static_cast<int32_t>(static_cast<double>(rect->right) / ratio + 0.5);
}
}
if (minWidth > rect->right)
rect->right = minWidth;
if (minHeight > rect->bottom)
rect->bottom = minHeight;
d_stdout("applyGeometryConstraints %u %u %d {%d,%d,%d,%d} | AFTER",
minimumWidth, minimumHeight, keepAspectRatio, rect->top, rect->left, rect->right, rect->bottom);
}
// --------------------------------------------------------------------------------------------------------------------
/**
* Helper class for getting a native idle timer, either through pugl or via native APIs.
*/
#if !DPF_VST3_USING_HOST_RUN_LOOP
class NativeIdleCallback : public IdleCallback
{
public:
NativeIdleCallback(UIExporter& ui)
: fUI(ui),
fCallbackRegistered(false)
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
#if defined(DISTRHO_OS_MAC)
, fTimerRef(nullptr)
#elif defined(DISTRHO_OS_WINDOWS)
, fTimerWindow(nullptr)
, fTimerWindowClassName()
#endif
#endif
{
}
void registerNativeIdleCallback()
{
DISTRHO_SAFE_ASSERT_RETURN(!fCallbackRegistered,);
fCallbackRegistered = true;
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
fUI.addIdleCallbackForVST3(this, DPF_VST3_TIMER_INTERVAL);
#elif defined(DISTRHO_OS_MAC)
constexpr const CFTimeInterval interval = DPF_VST3_TIMER_INTERVAL * 0.0001;
CFRunLoopTimerContext context = {};
context.info = this;
fTimerRef = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0,
platformIdleTimerCallback, &context);
DISTRHO_SAFE_ASSERT_RETURN(fTimerRef != nullptr,);
CFRunLoopAddTimer(CFRunLoopGetCurrent(), fTimerRef, kCFRunLoopCommonModes);
#elif defined(DISTRHO_OS_WINDOWS)
/* We cannot assume anything about the native parent window passed as a parameter (winId) to the
* UIVst3 constructor because we do not own it.
* These parent windows have class names like 'reaperPluginHostWrapProc' and 'JUCE_nnnnnn'.
*
* Create invisible window to handle a timer instead.
* There is no need for implementing a window proc because DefWindowProc already calls the
* callback function when processing WM_TIMER messages.
*/
fTimerWindowClassName = (
#ifdef DISTRHO_PLUGIN_BRAND
DISTRHO_PLUGIN_BRAND
#else
DISTRHO_MACRO_AS_STRING(DISTRHO_NAMESPACE)
#endif
"-" DISTRHO_PLUGIN_NAME "-"
);
char suffix[9];
std::snprintf(suffix, 8, "%08x", std::rand());
suffix[8] = '\0';
fTimerWindowClassName += suffix;
WNDCLASSEX cls;
ZeroMemory(&cls, sizeof(cls));
cls.cbSize = sizeof(WNDCLASSEX);
cls.cbWndExtra = sizeof(LONG_PTR);
cls.lpszClassName = fTimerWindowClassName.buffer();
cls.lpfnWndProc = DefWindowProc;
RegisterClassEx(&cls);
fTimerWindow = CreateWindowEx(0, cls.lpszClassName, "DPF Timer Helper",
0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
DISTRHO_SAFE_ASSERT_RETURN(fTimerWindow != nullptr,);
SetWindowLongPtr(fTimerWindow, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(static_cast<void*>(this)));
SetTimer(fTimerWindow, DPF_VST3_WIN32_TIMER_ID, DPF_VST3_TIMER_INTERVAL,
static_cast<TIMERPROC>(platformIdleTimerCallback));
#endif
}
~NativeIdleCallback()
{
if (!fCallbackRegistered)
return;
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
fUI.removeIdleCallbackForVST3(this);
#elif defined(DISTRHO_OS_MAC)
CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), fTimerRef, kCFRunLoopCommonModes);
CFRelease(fTimerRef);
#elif defined(DISTRHO_OS_WINDOWS)
DISTRHO_SAFE_ASSERT_RETURN(fTimerWindow != nullptr,);
KillTimer(fTimerWindow, DPF_VST3_WIN32_TIMER_ID);
DestroyWindow(fTimerWindow);
UnregisterClass(fTimerWindowClassName, nullptr);
#endif
}
private:
UIExporter& fUI;
bool fCallbackRegistered;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
#if defined(DISTRHO_OS_MAC)
CFRunLoopTimerRef fTimerRef;
static void platformIdleTimerCallback(CFRunLoopTimerRef, void* const info)
{
static_cast<NativeIdleCallback*>(info)->idleCallback();
}
#elif defined(DISTRHO_OS_WINDOWS)
HWND fTimerWindow;
String fTimerWindowClassName;
WINAPI static void platformIdleTimerCallback(const HWND hwnd, UINT, UINT_PTR, DWORD)
{
reinterpret_cast<NativeIdleCallback*>(GetWindowLongPtr(hwnd, GWLP_USERDATA))->idleCallback();
}
#endif
#endif
};
#endif
// --------------------------------------------------------------------------------------------------------------------
/**
* VST3 UI class.
*
* All the dynamic things from VST3 get implemented here, free of complex low-level VST3 pointer things.
* The UI is created during the "attach" view event, and destroyed during "removed".
*
* The low-level VST3 stuff comes after.
*/
class UIVst3
#if !DPF_VST3_USING_HOST_RUN_LOOP
: public NativeIdleCallback
#endif
{
public:
UIVst3(v3_plugin_view** const view,
v3_host_application** const host,
v3_connection_point** const connection,
v3_plugin_frame** const frame,
const intptr_t winId,
const float scaleFactor,
const double sampleRate,
void* const instancePointer,
const bool willResizeFromHost)
:
#if !DPF_VST3_USING_HOST_RUN_LOOP
NativeIdleCallback(fUI),
#endif
fView(view),
fHostApplication(host),
fConnection(connection),
fFrame(frame),
fReadyForPluginData(false),
fScaleFactor(scaleFactor),
fIsResizingFromPlugin(false),
fIsResizingFromHost(willResizeFromHost),
fUI(this, winId, sampleRate,
editParameterCallback,
setParameterCallback,
setStateCallback,
sendNoteCallback,
setSizeCallback,
nullptr, // TODO file request
d_nextBundlePath,
instancePointer,
scaleFactor)
{
}
~UIVst3()
{
if (fConnection != nullptr)
disconnect();
}
void postInit(uint32_t nextWidth, uint32_t nextHeight)
{
if (fIsResizingFromHost && nextWidth > 0 && nextHeight > 0)
{
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
nextWidth *= scaleFactor;
nextHeight *= scaleFactor;
#endif
if (fUI.getWidth() != nextWidth || fUI.getHeight() != nextHeight)
{
d_stdout("postInit sets new size as %u %u", nextWidth, nextHeight);
fUI.setWindowSizeForVST3(nextWidth, nextHeight);
}
}
if (fConnection != nullptr)
connect(fConnection);
#if !DPF_VST3_USING_HOST_RUN_LOOP
registerNativeIdleCallback();
#endif
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view interface calls
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
v3_result onWheel(float /*distance*/)
{
// TODO
return V3_NOT_IMPLEMENTED;
}
v3_result onKeyDown(const int16_t keychar, const int16_t keycode, const int16_t modifiers)
{
d_stdout("onKeyDown %i %i %x\n", keychar, keycode, modifiers);
DISTRHO_SAFE_ASSERT_INT_RETURN(keychar >= 0 && keychar < 0x7f, keychar, V3_FALSE);
using namespace DGL_NAMESPACE;
// TODO
uint dglcode = 0;
// TODO verify these
uint dglmods = 0;
if (modifiers & (1 << 0))
dglmods |= kModifierShift;
if (modifiers & (1 << 1))
dglmods |= kModifierAlt;
#ifdef DISTRHO_OS_MAC
if (modifiers & (1 << 2))
dglmods |= kModifierSuper;
if (modifiers & (1 << 3))
dglmods |= kModifierControl;
#else
if (modifiers & (1 << 2))
dglmods |= kModifierControl;
if (modifiers & (1 << 3))
dglmods |= kModifierSuper;
#endif
return fUI.handlePluginKeyboardVST3(true, static_cast<uint>(keychar), dglcode, dglmods) ? V3_TRUE : V3_FALSE;
}
v3_result onKeyUp(const int16_t keychar, const int16_t keycode, const int16_t modifiers)
{
d_stdout("onKeyDown %i %i %x\n", keychar, keycode, modifiers);
DISTRHO_SAFE_ASSERT_INT_RETURN(keychar >= 0 && keychar < 0x7f, keychar, V3_FALSE);
using namespace DGL_NAMESPACE;
// TODO
uint dglcode = 0;
// TODO verify these
uint dglmods = 0;
if (modifiers & (1 << 0))
dglmods |= kModifierShift;
if (modifiers & (1 << 1))
dglmods |= kModifierAlt;
#ifdef DISTRHO_OS_MAC
if (modifiers & (1 << 2))
dglmods |= kModifierSuper;
if (modifiers & (1 << 3))
dglmods |= kModifierControl;
#else
if (modifiers & (1 << 2))
dglmods |= kModifierControl;
if (modifiers & (1 << 3))
dglmods |= kModifierSuper;
#endif
return fUI.handlePluginKeyboardVST3(false, static_cast<uint>(keychar), dglcode, dglmods) ? V3_TRUE : V3_FALSE;
}
v3_result onFocus(const bool state)
{
if (state)
fUI.focus();
fUI.notifyFocusChanged(state);
return V3_OK;
}
#endif
v3_result getSize(v3_view_rect* const rect) const noexcept
{
rect->left = rect->top = 0;
rect->right = fUI.getWidth();
rect->bottom = fUI.getHeight();
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
rect->right /= scaleFactor;
rect->bottom /= scaleFactor;
#endif
d_stdout("getSize request returning %i %i", rect->right, rect->bottom);
return V3_OK;
}
v3_result onSize(v3_view_rect* const orect)
{
v3_view_rect rect = *orect;
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
rect.top *= scaleFactor;
rect.left *= scaleFactor;
rect.right *= scaleFactor;
rect.bottom *= scaleFactor;
#endif
if (fIsResizingFromPlugin)
{
d_stdout("host->plugin onSize request %i %i (IGNORED, plugin resize active)",
rect.right - rect.left, rect.bottom - rect.top);
return V3_OK;
}
d_stdout("host->plugin onSize request %i %i (OK)", rect.right - rect.left, rect.bottom - rect.top);
fIsResizingFromHost = true;
fUI.setWindowSizeForVST3(rect.right - rect.left, rect.bottom - rect.top);
return V3_OK;
}
v3_result setFrame(v3_plugin_frame** const frame) noexcept
{
fFrame = frame;
return V3_OK;
}
v3_result canResize() noexcept
{
return fUI.isResizable() ? V3_TRUE : V3_FALSE;
}
v3_result checkSizeConstraint(v3_view_rect* const rect)
{
uint minimumWidth, minimumHeight;
bool keepAspectRatio;
fUI.getGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio);
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
minimumWidth /= scaleFactor;
minimumHeight /= scaleFactor;
#endif
applyGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio, rect);
return V3_TRUE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_connection_point interface calls
void connect(v3_connection_point** const point) noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(point != nullptr,);
fConnection = point;
d_stdout("requesting current plugin state");
v3_message** const message = createMessage("init");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
void disconnect() noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
d_stdout("reporting UI closed");
fReadyForPluginData = false;
v3_message** const message = createMessage("close");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
fConnection = nullptr;
}
v3_result notify(v3_message** const message)
{
const char* const msgid = v3_cpp_obj(message)->get_message_id(message);
DISTRHO_SAFE_ASSERT_RETURN(msgid != nullptr, V3_INVALID_ARG);
v3_attribute_list** const attrs = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrs != nullptr, V3_INVALID_ARG);
if (std::strcmp(msgid, "ready") == 0)
{
DISTRHO_SAFE_ASSERT_RETURN(! fReadyForPluginData, V3_INTERNAL_ERR);
fReadyForPluginData = true;
return V3_OK;
}
if (std::strcmp(msgid, "parameter-set") == 0)
{
int64_t rindex;
double value;
v3_result res;
res = v3_cpp_obj(attrs)->get_int(attrs, "rindex", &rindex);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
res = v3_cpp_obj(attrs)->get_float(attrs, "value", &value);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
if (rindex < kVst3InternalParameterBaseCount)
{
switch (rindex)
{
#if DPF_VST3_USES_SEPARATE_CONTROLLER
case kVst3InternalParameterSampleRate:
DISTRHO_SAFE_ASSERT_RETURN(value >= 0.0, V3_INVALID_ARG);
fUI.setSampleRate(value, true);
break;
#endif
#if DISTRHO_PLUGIN_WANT_PROGRAMS
case kVst3InternalParameterProgram:
DISTRHO_SAFE_ASSERT_RETURN(value >= 0.0, V3_INVALID_ARG);
fUI.programLoaded(static_cast<uint32_t>(value + 0.5));
break;
#endif
}
return V3_OK;
}
const uint32_t index = static_cast<uint32_t>(rindex) - kVst3InternalParameterBaseCount;
fUI.parameterChanged(index, value);
return V3_OK;
}
#if DISTRHO_PLUGIN_WANT_STATE
if (std::strcmp(msgid, "state-set") == 0)
{
int64_t keyLength = -1;
int64_t valueLength = -1;
v3_result res;
res = v3_cpp_obj(attrs)->get_int(attrs, "key:length", &keyLength);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
DISTRHO_SAFE_ASSERT_INT_RETURN(keyLength >= 0, keyLength, V3_INTERNAL_ERR);
res = v3_cpp_obj(attrs)->get_int(attrs, "value:length", &valueLength);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
DISTRHO_SAFE_ASSERT_INT_RETURN(valueLength >= 0, valueLength, V3_INTERNAL_ERR);
int16_t* const key16 = (int16_t*)std::malloc(sizeof(int16_t)*(keyLength + 1));
DISTRHO_SAFE_ASSERT_RETURN(key16 != nullptr, V3_NOMEM);
int16_t* const value16 = (int16_t*)std::malloc(sizeof(int16_t)*(valueLength + 1));
DISTRHO_SAFE_ASSERT_RETURN(value16 != nullptr, V3_NOMEM);
res = v3_cpp_obj(attrs)->get_string(attrs, "key", key16, sizeof(int16_t)*keyLength);
DISTRHO_SAFE_ASSERT_INT2_RETURN(res == V3_OK, res, keyLength, res);
if (valueLength != 0)
{
res = v3_cpp_obj(attrs)->get_string(attrs, "value", value16, sizeof(int16_t)*valueLength);
DISTRHO_SAFE_ASSERT_INT2_RETURN(res == V3_OK, res, valueLength, res);
}
// do cheap inline conversion
char* const key = (char*)key16;
char* const value = (char*)value16;
for (int64_t i=0; i<keyLength; ++i)
key[i] = key16[i];
for (int64_t i=0; i<valueLength; ++i)
value[i] = value16[i];
key[keyLength] = '\0';
value[valueLength] = '\0';
fUI.stateChanged(key, value);
std::free(key16);
std::free(value16);
return V3_OK;
}
#endif
d_stdout("UIVst3 received unknown msg '%s'", msgid);
return V3_NOT_IMPLEMENTED;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view_content_scale_steinberg interface calls
v3_result setContentScaleFactor(const float factor)
{
if (d_isEqual(fScaleFactor, factor))
return V3_OK;
fScaleFactor = factor;
fUI.notifyScaleFactorChanged(factor);
return V3_OK;
}
#if DPF_VST3_USING_HOST_RUN_LOOP
// ----------------------------------------------------------------------------------------------------------------
// v3_timer_handler interface calls
void onTimer()
{
fUI.plugin_idle();
doIdleStuff();
}
#else
// ----------------------------------------------------------------------------------------------------------------
// special idle callback without v3_timer_handler
void idleCallback() override
{
fUI.idleForVST3();
doIdleStuff();
}
#endif
void doIdleStuff()
{
if (fReadyForPluginData)
{
fReadyForPluginData = false;
requestMorePluginData();
}
if (fIsResizingFromHost)
{
fIsResizingFromHost = false;
d_stdout("was resizing from host, now stopped");
}
if (fIsResizingFromPlugin)
{
fIsResizingFromPlugin = false;
d_stdout("was resizing from plugin, now stopped");
}
}
// ----------------------------------------------------------------------------------------------------------------
private:
// VST3 stuff
v3_plugin_view** const fView;
v3_host_application** const fHostApplication;
v3_connection_point** fConnection;
v3_plugin_frame** fFrame;
// Temporary data
bool fReadyForPluginData;
float fScaleFactor;
bool fIsResizingFromPlugin;
bool fIsResizingFromHost;
// Plugin UI (after VST3 stuff so the UI can call into us during its constructor)
UIExporter fUI;
// ----------------------------------------------------------------------------------------------------------------
// helper functions called during message passing
v3_message** createMessage(const char* const id) const
{
DISTRHO_SAFE_ASSERT_RETURN(fHostApplication != nullptr, nullptr);
v3_tuid iid;
std::memcpy(iid, v3_message_iid, sizeof(v3_tuid));
v3_message** msg = nullptr;
const v3_result res = v3_cpp_obj(fHostApplication)->create_instance(fHostApplication, iid, iid, (void**)&msg);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_TRUE, res, nullptr);
DISTRHO_SAFE_ASSERT_RETURN(msg != nullptr, nullptr);
v3_cpp_obj(msg)->set_message_id(msg, id);
return msg;
}
void requestMorePluginData() const
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("idle");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
// ----------------------------------------------------------------------------------------------------------------
// DPF callbacks
void editParameter(const uint32_t rindex, const bool started) const
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("parameter-edit");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_int(attrlist, "rindex", rindex);
v3_cpp_obj(attrlist)->set_int(attrlist, "started", started ? 1 : 0);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void editParameterCallback(void* ptr, uint32_t rindex, bool started)
{
((UIVst3*)ptr)->editParameter(rindex, started);
}
void setParameterValue(const uint32_t rindex, const float realValue)
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("parameter-set");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_int(attrlist, "rindex", rindex);
v3_cpp_obj(attrlist)->set_float(attrlist, "value", realValue);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
((UIVst3*)ptr)->setParameterValue(rindex, value);
}
void setSize(uint width, uint height)
{
DISTRHO_SAFE_ASSERT_RETURN(fView != nullptr,);
DISTRHO_SAFE_ASSERT_RETURN(fFrame != nullptr,);
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
width /= scaleFactor;
height /= scaleFactor;
#endif
if (fIsResizingFromHost)
{
d_stdout("plugin->host setSize %u %u (IGNORED, host resize active)", width, height);
return;
}
d_stdout("plugin->host setSize %u %u (OK)", width, height);
fIsResizingFromPlugin = true;
v3_view_rect rect;
rect.left = rect.top = 0;
rect.right = width;
rect.bottom = height;
v3_cpp_obj(fFrame)->resize_view(fFrame, fView, &rect);
}
static void setSizeCallback(void* ptr, uint width, uint height)
{
((UIVst3*)ptr)->setSize(width, height);
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity)
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("midi");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
uint8_t midiData[3];
midiData[0] = (velocity != 0 ? 0x90 : 0x80) | channel;
midiData[1] = note;
midiData[2] = velocity;
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_binary(attrlist, "data", midiData, sizeof(midiData));
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
((UIVst3*)ptr)->sendNote(channel, note, velocity);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void setState(const char* const key, const char* const value)
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("state-set");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_int(attrlist, "key:length", std::strlen(key));
v3_cpp_obj(attrlist)->set_int(attrlist, "value:length", std::strlen(value));
v3_cpp_obj(attrlist)->set_string(attrlist, "key", ScopedUTF16String(key));
v3_cpp_obj(attrlist)->set_string(attrlist, "value", ScopedUTF16String(value));
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void setStateCallback(void* ptr, const char* key, const char* value)
{
((UIVst3*)ptr)->setState(key, value);
}
#endif
};
// --------------------------------------------------------------------------------------------------------------------
/**
* VST3 low-level pointer thingies follow, proceed with care.
*/
// --------------------------------------------------------------------------------------------------------------------
// v3_funknown for classes with a single instance
template<class T>
static uint32_t V3_API dpf_single_instance_ref(void* const self)
{
return ++(*static_cast<T**>(self))->refcounter;
}
template<class T>
static uint32_t V3_API dpf_single_instance_unref(void* const self)
{
return --(*static_cast<T**>(self))->refcounter;
}
// --------------------------------------------------------------------------------------------------------------------
// dpf_ui_connection_point
struct dpf_ui_connection_point : v3_connection_point_cpp {
std::atomic_int refcounter;
ScopedPointer<UIVst3>& uivst3;
v3_connection_point** other;
dpf_ui_connection_point(ScopedPointer<UIVst3>& v)
: refcounter(1),
uivst3(v),
other(nullptr)
{
// v3_funknown, single instance
query_interface = query_interface_connection_point;
ref = dpf_single_instance_ref<dpf_ui_connection_point>;
unref = dpf_single_instance_unref<dpf_ui_connection_point>;
// v3_connection_point
point.connect = connect;
point.disconnect = disconnect;
point.notify = notify;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_connection_point(void* const self, const v3_tuid iid, void** const iface)
{
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_connection_point_iid))
{
d_stdout("UI|query_interface_connection_point => %p %s %p | OK", self, tuid2str(iid), iface);
++point->refcounter;
*iface = self;
return V3_OK;
}
d_stdout("DSP|query_interface_connection_point => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = NULL;
return V3_NO_INTERFACE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_connection_point
static v3_result V3_API connect(void* const self, v3_connection_point** const other)
{
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
d_stdout("UI|dpf_ui_connection_point::connect => %p %p", self, other);
DISTRHO_SAFE_ASSERT_RETURN(point->other == nullptr, V3_INVALID_ARG);
point->other = other;
if (UIVst3* const uivst3 = point->uivst3)
uivst3->connect(other);
return V3_OK;
};
static v3_result V3_API disconnect(void* const self, v3_connection_point** const other)
{
d_stdout("UI|dpf_ui_connection_point::disconnect => %p %p", self, other);
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
DISTRHO_SAFE_ASSERT_RETURN(point->other != nullptr, V3_INVALID_ARG);
point->other = nullptr;
if (UIVst3* const uivst3 = point->uivst3)
uivst3->disconnect();
return V3_OK;
};
static v3_result V3_API notify(void* const self, v3_message** const message)
{
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
UIVst3* const uivst3 = point->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->notify(message);
}
};
// --------------------------------------------------------------------------------------------------------------------
// dpf_plugin_view_content_scale
struct dpf_plugin_view_content_scale : v3_plugin_view_content_scale_cpp {
std::atomic_int refcounter;
ScopedPointer<UIVst3>& uivst3;
// cached values
float scaleFactor;
dpf_plugin_view_content_scale(ScopedPointer<UIVst3>& v)
: refcounter(1),
uivst3(v),
scaleFactor(0.0f)
{
// v3_funknown, single instance
query_interface = query_interface_view_content_scale;
ref = dpf_single_instance_ref<dpf_plugin_view_content_scale>;
unref = dpf_single_instance_unref<dpf_plugin_view_content_scale>;
// v3_plugin_view_content_scale
scale.set_content_scale_factor = set_content_scale_factor;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_view_content_scale(void* const self, const v3_tuid iid, void** const iface)
{
dpf_plugin_view_content_scale* const scale = *static_cast<dpf_plugin_view_content_scale**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_plugin_view_content_scale_iid))
{
d_stdout("query_interface_view_content_scale => %p %s %p | OK", self, tuid2str(iid), iface);
++scale->refcounter;
*iface = self;
return V3_OK;
}
d_stdout("query_interface_view_content_scale => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = NULL;
return V3_NO_INTERFACE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view_content_scale
static v3_result V3_API set_content_scale_factor(void* const self, const float factor)
{
dpf_plugin_view_content_scale* const scale = *static_cast<dpf_plugin_view_content_scale**>(self);
d_stdout("dpf_plugin_view::set_content_scale_factor => %p %f", self, factor);
scale->scaleFactor = factor;
if (UIVst3* const uivst3 = scale->uivst3)
return uivst3->setContentScaleFactor(factor);
return V3_NOT_INITIALIZED;
}
};
#if DPF_VST3_USING_HOST_RUN_LOOP
// --------------------------------------------------------------------------------------------------------------------
// dpf_timer_handler
struct dpf_timer_handler : v3_timer_handler_cpp {
std::atomic_int refcounter;
ScopedPointer<UIVst3>& uivst3;
bool valid;
dpf_timer_handler(ScopedPointer<UIVst3>& v)
: refcounter(1),
uivst3(v),
valid(true)
{
// v3_funknown, single instance
query_interface = query_interface_timer_handler;
ref = dpf_single_instance_ref<dpf_timer_handler>;
unref = dpf_single_instance_unref<dpf_timer_handler>;
// v3_timer_handler
timer.on_timer = on_timer;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_timer_handler(void* self, const v3_tuid iid, void** iface)
{
dpf_timer_handler* const timer = *static_cast<dpf_timer_handler**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_timer_handler_iid))
{
d_stdout("query_interface_timer_handler => %p %s %p | OK", self, tuid2str(iid), iface);
++timer->refcounter;
*iface = self;
return V3_OK;
}
d_stdout("query_interface_timer_handler => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = NULL;
return V3_NO_INTERFACE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_timer_handler
static void V3_API on_timer(void* self)
{
dpf_timer_handler* const timer = *static_cast<dpf_timer_handler**>(self);
DISTRHO_SAFE_ASSERT_RETURN(timer->valid,);
timer->uivst3->onTimer();
}
};
#endif
// --------------------------------------------------------------------------------------------------------------------
// dpf_plugin_view
static const char* const kSupportedPlatforms[] = {
#if defined(DISTRHO_OS_WINDOWS)
V3_VIEW_PLATFORM_TYPE_HWND,
#elif defined(DISTRHO_OS_MAC)
V3_VIEW_PLATFORM_TYPE_NSVIEW,
#else
V3_VIEW_PLATFORM_TYPE_X11,
#endif
};
struct dpf_plugin_view : v3_plugin_view_cpp {
std::atomic_int refcounter;
ScopedPointer<dpf_ui_connection_point> connection;
ScopedPointer<dpf_plugin_view_content_scale> scale;
#if DPF_VST3_USING_HOST_RUN_LOOP
ScopedPointer<dpf_timer_handler> timer;
#endif
ScopedPointer<UIVst3> uivst3;
// cached values
v3_host_application** const hostApplication;
void* const instancePointer;
double sampleRate;
v3_plugin_frame** frame;
v3_run_loop** runloop;
uint32_t nextWidth, nextHeight;
dpf_plugin_view(v3_host_application** const host, void* const instance, const double sr)
: refcounter(1),
hostApplication(host),
instancePointer(instance),
sampleRate(sr),
frame(nullptr),
runloop(nullptr),
nextWidth(0),
nextHeight(0)
{
d_stdout("dpf_plugin_view() with hostApplication %p", hostApplication);
// make sure host application is valid through out this view lifetime
if (hostApplication != nullptr)
v3_cpp_obj_ref(hostApplication);
// v3_funknown, everything custom
query_interface = query_interface_view;
ref = ref_view;
unref = unref_view;
// v3_plugin_view
view.is_platform_type_supported = is_platform_type_supported;
view.attached = attached;
view.removed = removed;
view.on_wheel = on_wheel;
view.on_key_down = on_key_down;
view.on_key_up = on_key_up;
view.get_size = get_size;
view.on_size = on_size;
view.on_focus = on_focus;
view.set_frame = set_frame;
view.can_resize = can_resize;
view.check_size_constraint = check_size_constraint;
}
~dpf_plugin_view()
{
d_stdout("~dpf_plugin_view()");
connection = nullptr;
scale = nullptr;
#if DPF_VST3_USING_HOST_RUN_LOOP
timer = nullptr;
#endif
uivst3 = nullptr;
if (hostApplication != nullptr)
v3_cpp_obj_unref(hostApplication);
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_view(void* self, const v3_tuid iid, void** iface)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_plugin_view_iid))
{
d_stdout("query_interface_view => %p %s %p | OK", self, tuid2str(iid), iface);
++view->refcounter;
*iface = self;
return V3_OK;
}
if (v3_tuid_match(v3_connection_point_iid, iid))
{
d_stdout("query_interface_view => %p %s %p | OK convert %p",
self, tuid2str(iid), iface, view->connection.get());
if (view->connection == nullptr)
view->connection = new dpf_ui_connection_point(view->uivst3);
else
++view->connection->refcounter;
*iface = &view->connection;
return V3_OK;
}
#ifndef DISTRHO_OS_MAC
if (v3_tuid_match(v3_plugin_view_content_scale_iid, iid))
{
d_stdout("query_interface_view => %p %s %p | OK convert %p",
self, tuid2str(iid), iface, view->scale.get());
if (view->scale == nullptr)
view->scale = new dpf_plugin_view_content_scale(view->uivst3);
else
++view->scale->refcounter;
*iface = &view->scale;
return V3_OK;
}
#endif
d_stdout("query_interface_view => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = nullptr;
return V3_NO_INTERFACE;
}
static uint32_t V3_API ref_view(void* self)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
const int refcount = ++view->refcounter;
d_stdout("dpf_plugin_view::ref => %p | refcount %i", self, refcount);
return refcount;
}
static uint32_t V3_API unref_view(void* self)
{
dpf_plugin_view** const viewptr = static_cast<dpf_plugin_view**>(self);
dpf_plugin_view* const view = *viewptr;
if (const int refcount = --view->refcounter)
{
d_stdout("dpf_plugin_view::unref => %p | refcount %i", self, refcount);
return refcount;
}
if (view->connection != nullptr && view->connection->other)
v3_cpp_obj(view->connection->other)->disconnect(view->connection->other,
(v3_connection_point**)&view->connection);
/**
* Some hosts will have unclean instances of a few of the view child classes at this point.
* We check for those here, going through the whole possible chain to see if it is safe to delete.
* TODO cleanup.
*/
bool unclean = false;
if (dpf_ui_connection_point* const conn = view->connection)
{
if (const int refcount = conn->refcounter)
{
unclean = true;
d_stderr("DPF warning: asked to delete view while connection point still active (refcount %d)", refcount);
}
}
#ifndef DISTRHO_OS_MAC
if (dpf_plugin_view_content_scale* const scale = view->scale)
{
if (const int refcount = scale->refcounter)
{
unclean = true;
d_stderr("DPF warning: asked to delete view while content scale still active (refcount %d)", refcount);
}
}
#endif
if (unclean)
return 0;
d_stdout("dpf_plugin_view::unref => %p | refcount is zero, deleting everything now!", self);
delete view;
delete viewptr;
return 0;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view
static v3_result V3_API is_platform_type_supported(void* const self, const char* const platform_type)
{
d_stdout("dpf_plugin_view::is_platform_type_supported => %p %s", self, platform_type);
for (size_t i=0; i<ARRAY_SIZE(kSupportedPlatforms); ++i)
{
if (std::strcmp(kSupportedPlatforms[i], platform_type) == 0)
return V3_OK;
}
return V3_NOT_IMPLEMENTED;
}
static v3_result V3_API attached(void* const self, void* const parent, const char* const platform_type)
{
d_stdout("dpf_plugin_view::attached => %p %p %s", self, parent, platform_type);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
DISTRHO_SAFE_ASSERT_RETURN(view->uivst3 == nullptr, V3_INVALID_ARG);
for (size_t i=0; i<ARRAY_SIZE(kSupportedPlatforms); ++i)
{
if (std::strcmp(kSupportedPlatforms[i], platform_type) == 0)
{
#if DPF_VST3_USING_HOST_RUN_LOOP
// find host run loop to plug ourselves into (required on some systems)
DISTRHO_SAFE_ASSERT_RETURN(view->frame != nullptr, V3_INVALID_ARG);
v3_run_loop** runloop = nullptr;
v3_cpp_obj_query_interface(view->frame, v3_run_loop_iid, &runloop);
DISTRHO_SAFE_ASSERT_RETURN(runloop != nullptr, V3_INVALID_ARG);
view->runloop = runloop;
#endif
const float lastScaleFactor = view->scale != nullptr ? view->scale->scaleFactor : 0.0f;
view->uivst3 = new UIVst3((v3_plugin_view**)self,
view->hostApplication,
view->connection != nullptr ? view->connection->other : nullptr,
view->frame,
(uintptr_t)parent,
lastScaleFactor,
view->sampleRate,
view->instancePointer,
view->nextWidth > 0 && view->nextHeight > 0);
view->uivst3->postInit(view->nextWidth, view->nextHeight);
view->nextWidth = 0;
view->nextHeight = 0;
#if DPF_VST3_USING_HOST_RUN_LOOP
// register a timer host run loop stuff
view->timer = new dpf_timer_handler(view->uivst3);
v3_cpp_obj(runloop)->register_timer(runloop,
(v3_timer_handler**)&view->timer,
DPF_VST3_TIMER_INTERVAL);
#endif
return V3_OK;
}
}
return V3_NOT_IMPLEMENTED;
}
static v3_result V3_API removed(void* const self)
{
d_stdout("dpf_plugin_view::removed => %p", self);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
DISTRHO_SAFE_ASSERT_RETURN(view->uivst3 != nullptr, V3_INVALID_ARG);
#if DPF_VST3_USING_HOST_RUN_LOOP
// unregister our timer as needed
if (v3_run_loop** const runloop = view->runloop)
{
if (view->timer != nullptr && view->timer->valid)
{
v3_cpp_obj(runloop)->unregister_timer(runloop, (v3_timer_handler**)&view->timer);
if (const int refcount = --view->timer->refcounter)
{
view->timer->valid = false;
d_stderr("VST3 warning: Host run loop did not give away timer (refcount %d)", refcount);
}
else
{
view->timer = nullptr;
}
}
v3_cpp_obj_unref(runloop);
view->runloop = nullptr;
}
#endif
view->uivst3 = nullptr;
return V3_OK;
}
static v3_result V3_API on_wheel(void* const self, const float distance)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_wheel => %p %f", self, distance);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onWheel(distance);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)distance;
#endif
}
static v3_result V3_API on_key_down(void* const self, const int16_t key_char, const int16_t key_code, const int16_t modifiers)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_key_down => %p %i %i %i", self, key_char, key_code, modifiers);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onKeyDown(key_char, key_code, modifiers);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)key_char; (void)key_code; (void)modifiers;
#endif
}
static v3_result V3_API on_key_up(void* const self, const int16_t key_char, const int16_t key_code, const int16_t modifiers)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_key_up => %p %i %i %i", self, key_char, key_code, modifiers);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onKeyUp(key_char, key_code, modifiers);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)key_char; (void)key_code; (void)modifiers;
#endif
}
static v3_result V3_API get_size(void* const self, v3_view_rect* const rect)
{
d_stdout("dpf_plugin_view::get_size => %p", self);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->getSize(rect);
// FIXME check if all this is really needed
const float lastScaleFactor = view->scale != nullptr ? view->scale->scaleFactor : 0.0f;
UIExporter tmpUI(nullptr, 0, view->sampleRate,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
view->instancePointer, lastScaleFactor);
rect->left = rect->top = 0;
view->nextWidth = tmpUI.getWidth();
view->nextHeight = tmpUI.getHeight();
#ifdef DISTRHO_OS_MAC
const double scaleFactor = tmpUI.getScaleFactor();
view->nextWidth /= scaleFactor;
view->nextHeight /= scaleFactor;
#endif
rect->right = view->nextWidth;
rect->bottom = view->nextHeight;
d_stdout("dpf_plugin_view::get_size => %p | next size %u %u with scale factor %f", self, view->nextWidth, view->nextHeight, lastScaleFactor);
return V3_OK;
}
static v3_result V3_API on_size(void* const self, v3_view_rect* const rect)
{
DISTRHO_SAFE_ASSERT_INT2_RETURN(rect->right > rect->left, rect->right, rect->left, V3_INVALID_ARG);
DISTRHO_SAFE_ASSERT_INT2_RETURN(rect->bottom > rect->top, rect->bottom, rect->top, V3_INVALID_ARG);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->onSize(rect);
view->nextWidth = static_cast<uint32_t>(rect->right - rect->left);
view->nextHeight = static_cast<uint32_t>(rect->bottom - rect->top);
return V3_OK;
}
static v3_result V3_API on_focus(void* const self, const v3_bool state)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_focus => %p %u", self, state);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onFocus(state);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)state;
#endif
}
static v3_result V3_API set_frame(void* const self, v3_plugin_frame** const frame)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
view->frame = frame;
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->setFrame(frame);
return V3_NOT_INITIALIZED;
}
static v3_result V3_API can_resize(void* const self)
{
#if DISTRHO_UI_USER_RESIZABLE
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->canResize();
return V3_TRUE;
#else
return V3_FALSE;
// unused
(void)self;
#endif
}
static v3_result V3_API check_size_constraint(void* const self, v3_view_rect* const rect)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->checkSizeConstraint(rect);
// FIXME check if all this is really needed
const float lastScaleFactor = view->scale != nullptr ? view->scale->scaleFactor : 0.0f;
UIExporter tmpUI(nullptr, 0, view->sampleRate,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
view->instancePointer, lastScaleFactor);
uint minimumWidth, minimumHeight;
bool keepAspectRatio;
tmpUI.getGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio);
#ifdef DISTRHO_OS_MAC
const double scaleFactor = tmpUI.getScaleFactor();
minimumWidth /= scaleFactor;
minimumHeight /= scaleFactor;
#endif
applyGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio, rect);
return V3_TRUE;
}
};
// --------------------------------------------------------------------------------------------------------------------
// dpf_plugin_view_create (called from plugin side)
v3_plugin_view** dpf_plugin_view_create(v3_host_application** host, void* instancePointer, double sampleRate);
v3_plugin_view** dpf_plugin_view_create(v3_host_application** const host,
void* const instancePointer,
const double sampleRate)
{
dpf_plugin_view** const viewptr = new dpf_plugin_view*;
*viewptr = new dpf_plugin_view(host, instancePointer, sampleRate);
return static_cast<v3_plugin_view**>(static_cast<void*>(viewptr));
}
// --------------------------------------------------------------------------------------------------------------------
END_NAMESPACE_DISTRHO
VST3: unregister native callback before destroying window
Signed-off-by: falkTX <d7e5958cbb080ba57e41fb602ade747e1a2da17c@falktx.com>
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2022 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoUIInternal.hpp"
#include "travesty/base.h"
#include "travesty/edit_controller.h"
#include "travesty/host.h"
#include "travesty/view.h"
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI && defined(DISTRHO_OS_WINDOWS)
# include <winuser.h>
# define DPF_VST3_WIN32_TIMER_ID 1
#endif
/* TODO items:
* - mousewheel event
* - key down/up events
* - host-side resizing
* - file request?
*/
#if !(defined(DISTRHO_OS_MAC) || defined(DISTRHO_OS_WINDOWS))
# define DPF_VST3_USING_HOST_RUN_LOOP 1
#else
# define DPF_VST3_USING_HOST_RUN_LOOP 0
#endif
#ifndef DPF_VST3_TIMER_INTERVAL
# define DPF_VST3_TIMER_INTERVAL 16 /* ~60 fps */
#endif
START_NAMESPACE_DISTRHO
// --------------------------------------------------------------------------------------------------------------------
#if ! DISTRHO_PLUGIN_WANT_MIDI_INPUT
static constexpr const sendNoteFunc sendNoteCallback = nullptr;
#endif
#if ! DISTRHO_PLUGIN_WANT_STATE
static constexpr const setStateFunc setStateCallback = nullptr;
#endif
// --------------------------------------------------------------------------------------------------------------------
// Static data, see DistrhoPlugin.cpp
extern const char* d_nextBundlePath;
// --------------------------------------------------------------------------------------------------------------------
// Utility functions (defined on plugin side)
const char* tuid2str(const v3_tuid iid);
// --------------------------------------------------------------------------------------------------------------------
static void applyGeometryConstraints(const uint minimumWidth,
const uint minimumHeight,
const bool keepAspectRatio,
v3_view_rect* const rect)
{
d_stdout("applyGeometryConstraints %u %u %d {%d,%d,%d,%d} | BEFORE",
minimumWidth, minimumHeight, keepAspectRatio, rect->top, rect->left, rect->right, rect->bottom);
const int32_t minWidth = static_cast<int32_t>(minimumWidth);
const int32_t minHeight = static_cast<int32_t>(minimumHeight);
if (keepAspectRatio)
{
const double ratio = static_cast<double>(minWidth) / static_cast<double>(minHeight);
const double reqRatio = static_cast<double>(rect->right) / static_cast<double>(rect->bottom);
if (d_isNotEqual(ratio, reqRatio))
{
// fix width
if (reqRatio > ratio)
rect->right = static_cast<int32_t>(rect->bottom * ratio + 0.5);
// fix height
else
rect->bottom = static_cast<int32_t>(static_cast<double>(rect->right) / ratio + 0.5);
}
}
if (minWidth > rect->right)
rect->right = minWidth;
if (minHeight > rect->bottom)
rect->bottom = minHeight;
d_stdout("applyGeometryConstraints %u %u %d {%d,%d,%d,%d} | AFTER",
minimumWidth, minimumHeight, keepAspectRatio, rect->top, rect->left, rect->right, rect->bottom);
}
// --------------------------------------------------------------------------------------------------------------------
/**
* Helper class for getting a native idle timer, either through pugl or via native APIs.
*/
#if !DPF_VST3_USING_HOST_RUN_LOOP
class NativeIdleCallback : public IdleCallback
{
public:
NativeIdleCallback(UIExporter& ui)
: fUI(ui),
fCallbackRegistered(false)
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
#if defined(DISTRHO_OS_MAC)
, fTimerRef(nullptr)
#elif defined(DISTRHO_OS_WINDOWS)
, fTimerWindow(nullptr)
, fTimerWindowClassName()
#endif
#endif
{
}
void registerNativeIdleCallback()
{
DISTRHO_SAFE_ASSERT_RETURN(!fCallbackRegistered,);
fCallbackRegistered = true;
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
fUI.addIdleCallbackForVST3(this, DPF_VST3_TIMER_INTERVAL);
#elif defined(DISTRHO_OS_MAC)
constexpr const CFTimeInterval interval = DPF_VST3_TIMER_INTERVAL * 0.0001;
CFRunLoopTimerContext context = {};
context.info = this;
fTimerRef = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0,
platformIdleTimerCallback, &context);
DISTRHO_SAFE_ASSERT_RETURN(fTimerRef != nullptr,);
CFRunLoopAddTimer(CFRunLoopGetCurrent(), fTimerRef, kCFRunLoopCommonModes);
#elif defined(DISTRHO_OS_WINDOWS)
/* We cannot assume anything about the native parent window passed as a parameter (winId) to the
* UIVst3 constructor because we do not own it.
* These parent windows have class names like 'reaperPluginHostWrapProc' and 'JUCE_nnnnnn'.
*
* Create invisible window to handle a timer instead.
* There is no need for implementing a window proc because DefWindowProc already calls the
* callback function when processing WM_TIMER messages.
*/
fTimerWindowClassName = (
#ifdef DISTRHO_PLUGIN_BRAND
DISTRHO_PLUGIN_BRAND
#else
DISTRHO_MACRO_AS_STRING(DISTRHO_NAMESPACE)
#endif
"-" DISTRHO_PLUGIN_NAME "-"
);
char suffix[9];
std::snprintf(suffix, 8, "%08x", std::rand());
suffix[8] = '\0';
fTimerWindowClassName += suffix;
WNDCLASSEX cls;
ZeroMemory(&cls, sizeof(cls));
cls.cbSize = sizeof(WNDCLASSEX);
cls.cbWndExtra = sizeof(LONG_PTR);
cls.lpszClassName = fTimerWindowClassName.buffer();
cls.lpfnWndProc = DefWindowProc;
RegisterClassEx(&cls);
fTimerWindow = CreateWindowEx(0, cls.lpszClassName, "DPF Timer Helper",
0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
DISTRHO_SAFE_ASSERT_RETURN(fTimerWindow != nullptr,);
SetWindowLongPtr(fTimerWindow, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(static_cast<void*>(this)));
SetTimer(fTimerWindow, DPF_VST3_WIN32_TIMER_ID, DPF_VST3_TIMER_INTERVAL,
static_cast<TIMERPROC>(platformIdleTimerCallback));
#endif
}
void unregisterNativeIdleCallback()
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
fUI.removeIdleCallbackForVST3(this);
#elif defined(DISTRHO_OS_MAC)
CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), fTimerRef, kCFRunLoopCommonModes);
CFRelease(fTimerRef);
#elif defined(DISTRHO_OS_WINDOWS)
DISTRHO_SAFE_ASSERT_RETURN(fTimerWindow != nullptr,);
KillTimer(fTimerWindow, DPF_VST3_WIN32_TIMER_ID);
DestroyWindow(fTimerWindow);
UnregisterClass(fTimerWindowClassName, nullptr);
#endif
}
private:
UIExporter& fUI;
bool fCallbackRegistered;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
#if defined(DISTRHO_OS_MAC)
CFRunLoopTimerRef fTimerRef;
static void platformIdleTimerCallback(CFRunLoopTimerRef, void* const info)
{
static_cast<NativeIdleCallback*>(info)->idleCallback();
}
#elif defined(DISTRHO_OS_WINDOWS)
HWND fTimerWindow;
String fTimerWindowClassName;
WINAPI static void platformIdleTimerCallback(const HWND hwnd, UINT, UINT_PTR, DWORD)
{
reinterpret_cast<NativeIdleCallback*>(GetWindowLongPtr(hwnd, GWLP_USERDATA))->idleCallback();
}
#endif
#endif
};
#endif
// --------------------------------------------------------------------------------------------------------------------
/**
* VST3 UI class.
*
* All the dynamic things from VST3 get implemented here, free of complex low-level VST3 pointer things.
* The UI is created during the "attach" view event, and destroyed during "removed".
*
* The low-level VST3 stuff comes after.
*/
class UIVst3
#if !DPF_VST3_USING_HOST_RUN_LOOP
: public NativeIdleCallback
#endif
{
public:
UIVst3(v3_plugin_view** const view,
v3_host_application** const host,
v3_connection_point** const connection,
v3_plugin_frame** const frame,
const intptr_t winId,
const float scaleFactor,
const double sampleRate,
void* const instancePointer,
const bool willResizeFromHost)
:
#if !DPF_VST3_USING_HOST_RUN_LOOP
NativeIdleCallback(fUI),
#endif
fView(view),
fHostApplication(host),
fConnection(connection),
fFrame(frame),
fReadyForPluginData(false),
fScaleFactor(scaleFactor),
fIsResizingFromPlugin(false),
fIsResizingFromHost(willResizeFromHost),
fUI(this, winId, sampleRate,
editParameterCallback,
setParameterCallback,
setStateCallback,
sendNoteCallback,
setSizeCallback,
nullptr, // TODO file request
d_nextBundlePath,
instancePointer,
scaleFactor)
{
}
~UIVst3()
{
#if !DPF_VST3_USING_HOST_RUN_LOOP
unregisterNativeIdleCallback();
#endif
if (fConnection != nullptr)
disconnect();
}
void postInit(uint32_t nextWidth, uint32_t nextHeight)
{
if (fIsResizingFromHost && nextWidth > 0 && nextHeight > 0)
{
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
nextWidth *= scaleFactor;
nextHeight *= scaleFactor;
#endif
if (fUI.getWidth() != nextWidth || fUI.getHeight() != nextHeight)
{
d_stdout("postInit sets new size as %u %u", nextWidth, nextHeight);
fUI.setWindowSizeForVST3(nextWidth, nextHeight);
}
}
if (fConnection != nullptr)
connect(fConnection);
#if !DPF_VST3_USING_HOST_RUN_LOOP
registerNativeIdleCallback();
#endif
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view interface calls
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
v3_result onWheel(float /*distance*/)
{
// TODO
return V3_NOT_IMPLEMENTED;
}
v3_result onKeyDown(const int16_t keychar, const int16_t keycode, const int16_t modifiers)
{
d_stdout("onKeyDown %i %i %x\n", keychar, keycode, modifiers);
DISTRHO_SAFE_ASSERT_INT_RETURN(keychar >= 0 && keychar < 0x7f, keychar, V3_FALSE);
using namespace DGL_NAMESPACE;
// TODO
uint dglcode = 0;
// TODO verify these
uint dglmods = 0;
if (modifiers & (1 << 0))
dglmods |= kModifierShift;
if (modifiers & (1 << 1))
dglmods |= kModifierAlt;
#ifdef DISTRHO_OS_MAC
if (modifiers & (1 << 2))
dglmods |= kModifierSuper;
if (modifiers & (1 << 3))
dglmods |= kModifierControl;
#else
if (modifiers & (1 << 2))
dglmods |= kModifierControl;
if (modifiers & (1 << 3))
dglmods |= kModifierSuper;
#endif
return fUI.handlePluginKeyboardVST3(true, static_cast<uint>(keychar), dglcode, dglmods) ? V3_TRUE : V3_FALSE;
}
v3_result onKeyUp(const int16_t keychar, const int16_t keycode, const int16_t modifiers)
{
d_stdout("onKeyDown %i %i %x\n", keychar, keycode, modifiers);
DISTRHO_SAFE_ASSERT_INT_RETURN(keychar >= 0 && keychar < 0x7f, keychar, V3_FALSE);
using namespace DGL_NAMESPACE;
// TODO
uint dglcode = 0;
// TODO verify these
uint dglmods = 0;
if (modifiers & (1 << 0))
dglmods |= kModifierShift;
if (modifiers & (1 << 1))
dglmods |= kModifierAlt;
#ifdef DISTRHO_OS_MAC
if (modifiers & (1 << 2))
dglmods |= kModifierSuper;
if (modifiers & (1 << 3))
dglmods |= kModifierControl;
#else
if (modifiers & (1 << 2))
dglmods |= kModifierControl;
if (modifiers & (1 << 3))
dglmods |= kModifierSuper;
#endif
return fUI.handlePluginKeyboardVST3(false, static_cast<uint>(keychar), dglcode, dglmods) ? V3_TRUE : V3_FALSE;
}
v3_result onFocus(const bool state)
{
if (state)
fUI.focus();
fUI.notifyFocusChanged(state);
return V3_OK;
}
#endif
v3_result getSize(v3_view_rect* const rect) const noexcept
{
rect->left = rect->top = 0;
rect->right = fUI.getWidth();
rect->bottom = fUI.getHeight();
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
rect->right /= scaleFactor;
rect->bottom /= scaleFactor;
#endif
d_stdout("getSize request returning %i %i", rect->right, rect->bottom);
return V3_OK;
}
v3_result onSize(v3_view_rect* const orect)
{
v3_view_rect rect = *orect;
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
rect.top *= scaleFactor;
rect.left *= scaleFactor;
rect.right *= scaleFactor;
rect.bottom *= scaleFactor;
#endif
if (fIsResizingFromPlugin)
{
d_stdout("host->plugin onSize request %i %i (IGNORED, plugin resize active)",
rect.right - rect.left, rect.bottom - rect.top);
return V3_OK;
}
d_stdout("host->plugin onSize request %i %i (OK)", rect.right - rect.left, rect.bottom - rect.top);
fIsResizingFromHost = true;
fUI.setWindowSizeForVST3(rect.right - rect.left, rect.bottom - rect.top);
return V3_OK;
}
v3_result setFrame(v3_plugin_frame** const frame) noexcept
{
fFrame = frame;
return V3_OK;
}
v3_result canResize() noexcept
{
return fUI.isResizable() ? V3_TRUE : V3_FALSE;
}
v3_result checkSizeConstraint(v3_view_rect* const rect)
{
uint minimumWidth, minimumHeight;
bool keepAspectRatio;
fUI.getGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio);
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
minimumWidth /= scaleFactor;
minimumHeight /= scaleFactor;
#endif
applyGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio, rect);
return V3_TRUE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_connection_point interface calls
void connect(v3_connection_point** const point) noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(point != nullptr,);
fConnection = point;
d_stdout("requesting current plugin state");
v3_message** const message = createMessage("init");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
void disconnect() noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
d_stdout("reporting UI closed");
fReadyForPluginData = false;
v3_message** const message = createMessage("close");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
fConnection = nullptr;
}
v3_result notify(v3_message** const message)
{
const char* const msgid = v3_cpp_obj(message)->get_message_id(message);
DISTRHO_SAFE_ASSERT_RETURN(msgid != nullptr, V3_INVALID_ARG);
v3_attribute_list** const attrs = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrs != nullptr, V3_INVALID_ARG);
if (std::strcmp(msgid, "ready") == 0)
{
DISTRHO_SAFE_ASSERT_RETURN(! fReadyForPluginData, V3_INTERNAL_ERR);
fReadyForPluginData = true;
return V3_OK;
}
if (std::strcmp(msgid, "parameter-set") == 0)
{
int64_t rindex;
double value;
v3_result res;
res = v3_cpp_obj(attrs)->get_int(attrs, "rindex", &rindex);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
res = v3_cpp_obj(attrs)->get_float(attrs, "value", &value);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
if (rindex < kVst3InternalParameterBaseCount)
{
switch (rindex)
{
#if DPF_VST3_USES_SEPARATE_CONTROLLER
case kVst3InternalParameterSampleRate:
DISTRHO_SAFE_ASSERT_RETURN(value >= 0.0, V3_INVALID_ARG);
fUI.setSampleRate(value, true);
break;
#endif
#if DISTRHO_PLUGIN_WANT_PROGRAMS
case kVst3InternalParameterProgram:
DISTRHO_SAFE_ASSERT_RETURN(value >= 0.0, V3_INVALID_ARG);
fUI.programLoaded(static_cast<uint32_t>(value + 0.5));
break;
#endif
}
return V3_OK;
}
const uint32_t index = static_cast<uint32_t>(rindex) - kVst3InternalParameterBaseCount;
fUI.parameterChanged(index, value);
return V3_OK;
}
#if DISTRHO_PLUGIN_WANT_STATE
if (std::strcmp(msgid, "state-set") == 0)
{
int64_t keyLength = -1;
int64_t valueLength = -1;
v3_result res;
res = v3_cpp_obj(attrs)->get_int(attrs, "key:length", &keyLength);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
DISTRHO_SAFE_ASSERT_INT_RETURN(keyLength >= 0, keyLength, V3_INTERNAL_ERR);
res = v3_cpp_obj(attrs)->get_int(attrs, "value:length", &valueLength);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_OK, res, res);
DISTRHO_SAFE_ASSERT_INT_RETURN(valueLength >= 0, valueLength, V3_INTERNAL_ERR);
int16_t* const key16 = (int16_t*)std::malloc(sizeof(int16_t)*(keyLength + 1));
DISTRHO_SAFE_ASSERT_RETURN(key16 != nullptr, V3_NOMEM);
int16_t* const value16 = (int16_t*)std::malloc(sizeof(int16_t)*(valueLength + 1));
DISTRHO_SAFE_ASSERT_RETURN(value16 != nullptr, V3_NOMEM);
res = v3_cpp_obj(attrs)->get_string(attrs, "key", key16, sizeof(int16_t)*keyLength);
DISTRHO_SAFE_ASSERT_INT2_RETURN(res == V3_OK, res, keyLength, res);
if (valueLength != 0)
{
res = v3_cpp_obj(attrs)->get_string(attrs, "value", value16, sizeof(int16_t)*valueLength);
DISTRHO_SAFE_ASSERT_INT2_RETURN(res == V3_OK, res, valueLength, res);
}
// do cheap inline conversion
char* const key = (char*)key16;
char* const value = (char*)value16;
for (int64_t i=0; i<keyLength; ++i)
key[i] = key16[i];
for (int64_t i=0; i<valueLength; ++i)
value[i] = value16[i];
key[keyLength] = '\0';
value[valueLength] = '\0';
fUI.stateChanged(key, value);
std::free(key16);
std::free(value16);
return V3_OK;
}
#endif
d_stdout("UIVst3 received unknown msg '%s'", msgid);
return V3_NOT_IMPLEMENTED;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view_content_scale_steinberg interface calls
v3_result setContentScaleFactor(const float factor)
{
if (d_isEqual(fScaleFactor, factor))
return V3_OK;
fScaleFactor = factor;
fUI.notifyScaleFactorChanged(factor);
return V3_OK;
}
#if DPF_VST3_USING_HOST_RUN_LOOP
// ----------------------------------------------------------------------------------------------------------------
// v3_timer_handler interface calls
void onTimer()
{
fUI.plugin_idle();
doIdleStuff();
}
#else
// ----------------------------------------------------------------------------------------------------------------
// special idle callback without v3_timer_handler
void idleCallback() override
{
fUI.idleForVST3();
doIdleStuff();
}
#endif
void doIdleStuff()
{
if (fReadyForPluginData)
{
fReadyForPluginData = false;
requestMorePluginData();
}
if (fIsResizingFromHost)
{
fIsResizingFromHost = false;
d_stdout("was resizing from host, now stopped");
}
if (fIsResizingFromPlugin)
{
fIsResizingFromPlugin = false;
d_stdout("was resizing from plugin, now stopped");
}
}
// ----------------------------------------------------------------------------------------------------------------
private:
// VST3 stuff
v3_plugin_view** const fView;
v3_host_application** const fHostApplication;
v3_connection_point** fConnection;
v3_plugin_frame** fFrame;
// Temporary data
bool fReadyForPluginData;
float fScaleFactor;
bool fIsResizingFromPlugin;
bool fIsResizingFromHost;
// Plugin UI (after VST3 stuff so the UI can call into us during its constructor)
UIExporter fUI;
// ----------------------------------------------------------------------------------------------------------------
// helper functions called during message passing
v3_message** createMessage(const char* const id) const
{
DISTRHO_SAFE_ASSERT_RETURN(fHostApplication != nullptr, nullptr);
v3_tuid iid;
std::memcpy(iid, v3_message_iid, sizeof(v3_tuid));
v3_message** msg = nullptr;
const v3_result res = v3_cpp_obj(fHostApplication)->create_instance(fHostApplication, iid, iid, (void**)&msg);
DISTRHO_SAFE_ASSERT_INT_RETURN(res == V3_TRUE, res, nullptr);
DISTRHO_SAFE_ASSERT_RETURN(msg != nullptr, nullptr);
v3_cpp_obj(msg)->set_message_id(msg, id);
return msg;
}
void requestMorePluginData() const
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("idle");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
// ----------------------------------------------------------------------------------------------------------------
// DPF callbacks
void editParameter(const uint32_t rindex, const bool started) const
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("parameter-edit");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_int(attrlist, "rindex", rindex);
v3_cpp_obj(attrlist)->set_int(attrlist, "started", started ? 1 : 0);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void editParameterCallback(void* ptr, uint32_t rindex, bool started)
{
((UIVst3*)ptr)->editParameter(rindex, started);
}
void setParameterValue(const uint32_t rindex, const float realValue)
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("parameter-set");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_int(attrlist, "rindex", rindex);
v3_cpp_obj(attrlist)->set_float(attrlist, "value", realValue);
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
((UIVst3*)ptr)->setParameterValue(rindex, value);
}
void setSize(uint width, uint height)
{
DISTRHO_SAFE_ASSERT_RETURN(fView != nullptr,);
DISTRHO_SAFE_ASSERT_RETURN(fFrame != nullptr,);
#ifdef DISTRHO_OS_MAC
const double scaleFactor = fUI.getScaleFactor();
width /= scaleFactor;
height /= scaleFactor;
#endif
if (fIsResizingFromHost)
{
d_stdout("plugin->host setSize %u %u (IGNORED, host resize active)", width, height);
return;
}
d_stdout("plugin->host setSize %u %u (OK)", width, height);
fIsResizingFromPlugin = true;
v3_view_rect rect;
rect.left = rect.top = 0;
rect.right = width;
rect.bottom = height;
v3_cpp_obj(fFrame)->resize_view(fFrame, fView, &rect);
}
static void setSizeCallback(void* ptr, uint width, uint height)
{
((UIVst3*)ptr)->setSize(width, height);
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity)
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("midi");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
uint8_t midiData[3];
midiData[0] = (velocity != 0 ? 0x90 : 0x80) | channel;
midiData[1] = note;
midiData[2] = velocity;
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_binary(attrlist, "data", midiData, sizeof(midiData));
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
((UIVst3*)ptr)->sendNote(channel, note, velocity);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void setState(const char* const key, const char* const value)
{
DISTRHO_SAFE_ASSERT_RETURN(fConnection != nullptr,);
v3_message** const message = createMessage("state-set");
DISTRHO_SAFE_ASSERT_RETURN(message != nullptr,);
v3_attribute_list** const attrlist = v3_cpp_obj(message)->get_attributes(message);
DISTRHO_SAFE_ASSERT_RETURN(attrlist != nullptr,);
v3_cpp_obj(attrlist)->set_int(attrlist, "__dpf_msg_target__", 1);
v3_cpp_obj(attrlist)->set_int(attrlist, "key:length", std::strlen(key));
v3_cpp_obj(attrlist)->set_int(attrlist, "value:length", std::strlen(value));
v3_cpp_obj(attrlist)->set_string(attrlist, "key", ScopedUTF16String(key));
v3_cpp_obj(attrlist)->set_string(attrlist, "value", ScopedUTF16String(value));
v3_cpp_obj(fConnection)->notify(fConnection, message);
v3_cpp_obj_unref(message);
}
static void setStateCallback(void* ptr, const char* key, const char* value)
{
((UIVst3*)ptr)->setState(key, value);
}
#endif
};
// --------------------------------------------------------------------------------------------------------------------
/**
* VST3 low-level pointer thingies follow, proceed with care.
*/
// --------------------------------------------------------------------------------------------------------------------
// v3_funknown for classes with a single instance
template<class T>
static uint32_t V3_API dpf_single_instance_ref(void* const self)
{
return ++(*static_cast<T**>(self))->refcounter;
}
template<class T>
static uint32_t V3_API dpf_single_instance_unref(void* const self)
{
return --(*static_cast<T**>(self))->refcounter;
}
// --------------------------------------------------------------------------------------------------------------------
// dpf_ui_connection_point
struct dpf_ui_connection_point : v3_connection_point_cpp {
std::atomic_int refcounter;
ScopedPointer<UIVst3>& uivst3;
v3_connection_point** other;
dpf_ui_connection_point(ScopedPointer<UIVst3>& v)
: refcounter(1),
uivst3(v),
other(nullptr)
{
// v3_funknown, single instance
query_interface = query_interface_connection_point;
ref = dpf_single_instance_ref<dpf_ui_connection_point>;
unref = dpf_single_instance_unref<dpf_ui_connection_point>;
// v3_connection_point
point.connect = connect;
point.disconnect = disconnect;
point.notify = notify;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_connection_point(void* const self, const v3_tuid iid, void** const iface)
{
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_connection_point_iid))
{
d_stdout("UI|query_interface_connection_point => %p %s %p | OK", self, tuid2str(iid), iface);
++point->refcounter;
*iface = self;
return V3_OK;
}
d_stdout("DSP|query_interface_connection_point => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = NULL;
return V3_NO_INTERFACE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_connection_point
static v3_result V3_API connect(void* const self, v3_connection_point** const other)
{
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
d_stdout("UI|dpf_ui_connection_point::connect => %p %p", self, other);
DISTRHO_SAFE_ASSERT_RETURN(point->other == nullptr, V3_INVALID_ARG);
point->other = other;
if (UIVst3* const uivst3 = point->uivst3)
uivst3->connect(other);
return V3_OK;
};
static v3_result V3_API disconnect(void* const self, v3_connection_point** const other)
{
d_stdout("UI|dpf_ui_connection_point::disconnect => %p %p", self, other);
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
DISTRHO_SAFE_ASSERT_RETURN(point->other != nullptr, V3_INVALID_ARG);
point->other = nullptr;
if (UIVst3* const uivst3 = point->uivst3)
uivst3->disconnect();
return V3_OK;
};
static v3_result V3_API notify(void* const self, v3_message** const message)
{
dpf_ui_connection_point* const point = *static_cast<dpf_ui_connection_point**>(self);
UIVst3* const uivst3 = point->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->notify(message);
}
};
// --------------------------------------------------------------------------------------------------------------------
// dpf_plugin_view_content_scale
struct dpf_plugin_view_content_scale : v3_plugin_view_content_scale_cpp {
std::atomic_int refcounter;
ScopedPointer<UIVst3>& uivst3;
// cached values
float scaleFactor;
dpf_plugin_view_content_scale(ScopedPointer<UIVst3>& v)
: refcounter(1),
uivst3(v),
scaleFactor(0.0f)
{
// v3_funknown, single instance
query_interface = query_interface_view_content_scale;
ref = dpf_single_instance_ref<dpf_plugin_view_content_scale>;
unref = dpf_single_instance_unref<dpf_plugin_view_content_scale>;
// v3_plugin_view_content_scale
scale.set_content_scale_factor = set_content_scale_factor;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_view_content_scale(void* const self, const v3_tuid iid, void** const iface)
{
dpf_plugin_view_content_scale* const scale = *static_cast<dpf_plugin_view_content_scale**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_plugin_view_content_scale_iid))
{
d_stdout("query_interface_view_content_scale => %p %s %p | OK", self, tuid2str(iid), iface);
++scale->refcounter;
*iface = self;
return V3_OK;
}
d_stdout("query_interface_view_content_scale => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = NULL;
return V3_NO_INTERFACE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view_content_scale
static v3_result V3_API set_content_scale_factor(void* const self, const float factor)
{
dpf_plugin_view_content_scale* const scale = *static_cast<dpf_plugin_view_content_scale**>(self);
d_stdout("dpf_plugin_view::set_content_scale_factor => %p %f", self, factor);
scale->scaleFactor = factor;
if (UIVst3* const uivst3 = scale->uivst3)
return uivst3->setContentScaleFactor(factor);
return V3_NOT_INITIALIZED;
}
};
#if DPF_VST3_USING_HOST_RUN_LOOP
// --------------------------------------------------------------------------------------------------------------------
// dpf_timer_handler
struct dpf_timer_handler : v3_timer_handler_cpp {
std::atomic_int refcounter;
ScopedPointer<UIVst3>& uivst3;
bool valid;
dpf_timer_handler(ScopedPointer<UIVst3>& v)
: refcounter(1),
uivst3(v),
valid(true)
{
// v3_funknown, single instance
query_interface = query_interface_timer_handler;
ref = dpf_single_instance_ref<dpf_timer_handler>;
unref = dpf_single_instance_unref<dpf_timer_handler>;
// v3_timer_handler
timer.on_timer = on_timer;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_timer_handler(void* self, const v3_tuid iid, void** iface)
{
dpf_timer_handler* const timer = *static_cast<dpf_timer_handler**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_timer_handler_iid))
{
d_stdout("query_interface_timer_handler => %p %s %p | OK", self, tuid2str(iid), iface);
++timer->refcounter;
*iface = self;
return V3_OK;
}
d_stdout("query_interface_timer_handler => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = NULL;
return V3_NO_INTERFACE;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_timer_handler
static void V3_API on_timer(void* self)
{
dpf_timer_handler* const timer = *static_cast<dpf_timer_handler**>(self);
DISTRHO_SAFE_ASSERT_RETURN(timer->valid,);
timer->uivst3->onTimer();
}
};
#endif
// --------------------------------------------------------------------------------------------------------------------
// dpf_plugin_view
static const char* const kSupportedPlatforms[] = {
#if defined(DISTRHO_OS_WINDOWS)
V3_VIEW_PLATFORM_TYPE_HWND,
#elif defined(DISTRHO_OS_MAC)
V3_VIEW_PLATFORM_TYPE_NSVIEW,
#else
V3_VIEW_PLATFORM_TYPE_X11,
#endif
};
struct dpf_plugin_view : v3_plugin_view_cpp {
std::atomic_int refcounter;
ScopedPointer<dpf_ui_connection_point> connection;
ScopedPointer<dpf_plugin_view_content_scale> scale;
#if DPF_VST3_USING_HOST_RUN_LOOP
ScopedPointer<dpf_timer_handler> timer;
#endif
ScopedPointer<UIVst3> uivst3;
// cached values
v3_host_application** const hostApplication;
void* const instancePointer;
double sampleRate;
v3_plugin_frame** frame;
v3_run_loop** runloop;
uint32_t nextWidth, nextHeight;
dpf_plugin_view(v3_host_application** const host, void* const instance, const double sr)
: refcounter(1),
hostApplication(host),
instancePointer(instance),
sampleRate(sr),
frame(nullptr),
runloop(nullptr),
nextWidth(0),
nextHeight(0)
{
d_stdout("dpf_plugin_view() with hostApplication %p", hostApplication);
// make sure host application is valid through out this view lifetime
if (hostApplication != nullptr)
v3_cpp_obj_ref(hostApplication);
// v3_funknown, everything custom
query_interface = query_interface_view;
ref = ref_view;
unref = unref_view;
// v3_plugin_view
view.is_platform_type_supported = is_platform_type_supported;
view.attached = attached;
view.removed = removed;
view.on_wheel = on_wheel;
view.on_key_down = on_key_down;
view.on_key_up = on_key_up;
view.get_size = get_size;
view.on_size = on_size;
view.on_focus = on_focus;
view.set_frame = set_frame;
view.can_resize = can_resize;
view.check_size_constraint = check_size_constraint;
}
~dpf_plugin_view()
{
d_stdout("~dpf_plugin_view()");
connection = nullptr;
scale = nullptr;
#if DPF_VST3_USING_HOST_RUN_LOOP
timer = nullptr;
#endif
uivst3 = nullptr;
if (hostApplication != nullptr)
v3_cpp_obj_unref(hostApplication);
}
// ----------------------------------------------------------------------------------------------------------------
// v3_funknown
static v3_result V3_API query_interface_view(void* self, const v3_tuid iid, void** iface)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (v3_tuid_match(iid, v3_funknown_iid) ||
v3_tuid_match(iid, v3_plugin_view_iid))
{
d_stdout("query_interface_view => %p %s %p | OK", self, tuid2str(iid), iface);
++view->refcounter;
*iface = self;
return V3_OK;
}
if (v3_tuid_match(v3_connection_point_iid, iid))
{
d_stdout("query_interface_view => %p %s %p | OK convert %p",
self, tuid2str(iid), iface, view->connection.get());
if (view->connection == nullptr)
view->connection = new dpf_ui_connection_point(view->uivst3);
else
++view->connection->refcounter;
*iface = &view->connection;
return V3_OK;
}
#ifndef DISTRHO_OS_MAC
if (v3_tuid_match(v3_plugin_view_content_scale_iid, iid))
{
d_stdout("query_interface_view => %p %s %p | OK convert %p",
self, tuid2str(iid), iface, view->scale.get());
if (view->scale == nullptr)
view->scale = new dpf_plugin_view_content_scale(view->uivst3);
else
++view->scale->refcounter;
*iface = &view->scale;
return V3_OK;
}
#endif
d_stdout("query_interface_view => %p %s %p | WARNING UNSUPPORTED", self, tuid2str(iid), iface);
*iface = nullptr;
return V3_NO_INTERFACE;
}
static uint32_t V3_API ref_view(void* self)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
const int refcount = ++view->refcounter;
d_stdout("dpf_plugin_view::ref => %p | refcount %i", self, refcount);
return refcount;
}
static uint32_t V3_API unref_view(void* self)
{
dpf_plugin_view** const viewptr = static_cast<dpf_plugin_view**>(self);
dpf_plugin_view* const view = *viewptr;
if (const int refcount = --view->refcounter)
{
d_stdout("dpf_plugin_view::unref => %p | refcount %i", self, refcount);
return refcount;
}
if (view->connection != nullptr && view->connection->other)
v3_cpp_obj(view->connection->other)->disconnect(view->connection->other,
(v3_connection_point**)&view->connection);
/**
* Some hosts will have unclean instances of a few of the view child classes at this point.
* We check for those here, going through the whole possible chain to see if it is safe to delete.
* TODO cleanup.
*/
bool unclean = false;
if (dpf_ui_connection_point* const conn = view->connection)
{
if (const int refcount = conn->refcounter)
{
unclean = true;
d_stderr("DPF warning: asked to delete view while connection point still active (refcount %d)", refcount);
}
}
#ifndef DISTRHO_OS_MAC
if (dpf_plugin_view_content_scale* const scale = view->scale)
{
if (const int refcount = scale->refcounter)
{
unclean = true;
d_stderr("DPF warning: asked to delete view while content scale still active (refcount %d)", refcount);
}
}
#endif
if (unclean)
return 0;
d_stdout("dpf_plugin_view::unref => %p | refcount is zero, deleting everything now!", self);
delete view;
delete viewptr;
return 0;
}
// ----------------------------------------------------------------------------------------------------------------
// v3_plugin_view
static v3_result V3_API is_platform_type_supported(void* const self, const char* const platform_type)
{
d_stdout("dpf_plugin_view::is_platform_type_supported => %p %s", self, platform_type);
for (size_t i=0; i<ARRAY_SIZE(kSupportedPlatforms); ++i)
{
if (std::strcmp(kSupportedPlatforms[i], platform_type) == 0)
return V3_OK;
}
return V3_NOT_IMPLEMENTED;
}
static v3_result V3_API attached(void* const self, void* const parent, const char* const platform_type)
{
d_stdout("dpf_plugin_view::attached => %p %p %s", self, parent, platform_type);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
DISTRHO_SAFE_ASSERT_RETURN(view->uivst3 == nullptr, V3_INVALID_ARG);
for (size_t i=0; i<ARRAY_SIZE(kSupportedPlatforms); ++i)
{
if (std::strcmp(kSupportedPlatforms[i], platform_type) == 0)
{
#if DPF_VST3_USING_HOST_RUN_LOOP
// find host run loop to plug ourselves into (required on some systems)
DISTRHO_SAFE_ASSERT_RETURN(view->frame != nullptr, V3_INVALID_ARG);
v3_run_loop** runloop = nullptr;
v3_cpp_obj_query_interface(view->frame, v3_run_loop_iid, &runloop);
DISTRHO_SAFE_ASSERT_RETURN(runloop != nullptr, V3_INVALID_ARG);
view->runloop = runloop;
#endif
const float lastScaleFactor = view->scale != nullptr ? view->scale->scaleFactor : 0.0f;
view->uivst3 = new UIVst3((v3_plugin_view**)self,
view->hostApplication,
view->connection != nullptr ? view->connection->other : nullptr,
view->frame,
(uintptr_t)parent,
lastScaleFactor,
view->sampleRate,
view->instancePointer,
view->nextWidth > 0 && view->nextHeight > 0);
view->uivst3->postInit(view->nextWidth, view->nextHeight);
view->nextWidth = 0;
view->nextHeight = 0;
#if DPF_VST3_USING_HOST_RUN_LOOP
// register a timer host run loop stuff
view->timer = new dpf_timer_handler(view->uivst3);
v3_cpp_obj(runloop)->register_timer(runloop,
(v3_timer_handler**)&view->timer,
DPF_VST3_TIMER_INTERVAL);
#endif
return V3_OK;
}
}
return V3_NOT_IMPLEMENTED;
}
static v3_result V3_API removed(void* const self)
{
d_stdout("dpf_plugin_view::removed => %p", self);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
DISTRHO_SAFE_ASSERT_RETURN(view->uivst3 != nullptr, V3_INVALID_ARG);
#if DPF_VST3_USING_HOST_RUN_LOOP
// unregister our timer as needed
if (v3_run_loop** const runloop = view->runloop)
{
if (view->timer != nullptr && view->timer->valid)
{
v3_cpp_obj(runloop)->unregister_timer(runloop, (v3_timer_handler**)&view->timer);
if (const int refcount = --view->timer->refcounter)
{
view->timer->valid = false;
d_stderr("VST3 warning: Host run loop did not give away timer (refcount %d)", refcount);
}
else
{
view->timer = nullptr;
}
}
v3_cpp_obj_unref(runloop);
view->runloop = nullptr;
}
#endif
view->uivst3 = nullptr;
return V3_OK;
}
static v3_result V3_API on_wheel(void* const self, const float distance)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_wheel => %p %f", self, distance);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onWheel(distance);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)distance;
#endif
}
static v3_result V3_API on_key_down(void* const self, const int16_t key_char, const int16_t key_code, const int16_t modifiers)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_key_down => %p %i %i %i", self, key_char, key_code, modifiers);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onKeyDown(key_char, key_code, modifiers);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)key_char; (void)key_code; (void)modifiers;
#endif
}
static v3_result V3_API on_key_up(void* const self, const int16_t key_char, const int16_t key_code, const int16_t modifiers)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_key_up => %p %i %i %i", self, key_char, key_code, modifiers);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onKeyUp(key_char, key_code, modifiers);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)key_char; (void)key_code; (void)modifiers;
#endif
}
static v3_result V3_API get_size(void* const self, v3_view_rect* const rect)
{
d_stdout("dpf_plugin_view::get_size => %p", self);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->getSize(rect);
// FIXME check if all this is really needed
const float lastScaleFactor = view->scale != nullptr ? view->scale->scaleFactor : 0.0f;
UIExporter tmpUI(nullptr, 0, view->sampleRate,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
view->instancePointer, lastScaleFactor);
rect->left = rect->top = 0;
view->nextWidth = tmpUI.getWidth();
view->nextHeight = tmpUI.getHeight();
#ifdef DISTRHO_OS_MAC
const double scaleFactor = tmpUI.getScaleFactor();
view->nextWidth /= scaleFactor;
view->nextHeight /= scaleFactor;
#endif
rect->right = view->nextWidth;
rect->bottom = view->nextHeight;
d_stdout("dpf_plugin_view::get_size => %p | next size %u %u with scale factor %f", self, view->nextWidth, view->nextHeight, lastScaleFactor);
return V3_OK;
}
static v3_result V3_API on_size(void* const self, v3_view_rect* const rect)
{
DISTRHO_SAFE_ASSERT_INT2_RETURN(rect->right > rect->left, rect->right, rect->left, V3_INVALID_ARG);
DISTRHO_SAFE_ASSERT_INT2_RETURN(rect->bottom > rect->top, rect->bottom, rect->top, V3_INVALID_ARG);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->onSize(rect);
view->nextWidth = static_cast<uint32_t>(rect->right - rect->left);
view->nextHeight = static_cast<uint32_t>(rect->bottom - rect->top);
return V3_OK;
}
static v3_result V3_API on_focus(void* const self, const v3_bool state)
{
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
d_stdout("dpf_plugin_view::on_focus => %p %u", self, state);
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
UIVst3* const uivst3 = view->uivst3;
DISTRHO_SAFE_ASSERT_RETURN(uivst3 != nullptr, V3_NOT_INITIALIZED);
return uivst3->onFocus(state);
#else
return V3_NOT_IMPLEMENTED;
// unused
(void)self; (void)state;
#endif
}
static v3_result V3_API set_frame(void* const self, v3_plugin_frame** const frame)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
view->frame = frame;
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->setFrame(frame);
return V3_NOT_INITIALIZED;
}
static v3_result V3_API can_resize(void* const self)
{
#if DISTRHO_UI_USER_RESIZABLE
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->canResize();
return V3_TRUE;
#else
return V3_FALSE;
// unused
(void)self;
#endif
}
static v3_result V3_API check_size_constraint(void* const self, v3_view_rect* const rect)
{
dpf_plugin_view* const view = *static_cast<dpf_plugin_view**>(self);
if (UIVst3* const uivst3 = view->uivst3)
return uivst3->checkSizeConstraint(rect);
// FIXME check if all this is really needed
const float lastScaleFactor = view->scale != nullptr ? view->scale->scaleFactor : 0.0f;
UIExporter tmpUI(nullptr, 0, view->sampleRate,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
view->instancePointer, lastScaleFactor);
uint minimumWidth, minimumHeight;
bool keepAspectRatio;
tmpUI.getGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio);
#ifdef DISTRHO_OS_MAC
const double scaleFactor = tmpUI.getScaleFactor();
minimumWidth /= scaleFactor;
minimumHeight /= scaleFactor;
#endif
applyGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio, rect);
return V3_TRUE;
}
};
// --------------------------------------------------------------------------------------------------------------------
// dpf_plugin_view_create (called from plugin side)
v3_plugin_view** dpf_plugin_view_create(v3_host_application** host, void* instancePointer, double sampleRate);
v3_plugin_view** dpf_plugin_view_create(v3_host_application** const host,
void* const instancePointer,
const double sampleRate)
{
dpf_plugin_view** const viewptr = new dpf_plugin_view*;
*viewptr = new dpf_plugin_view(host, instancePointer, sampleRate);
return static_cast<v3_plugin_view**>(static_cast<void*>(viewptr));
}
// --------------------------------------------------------------------------------------------------------------------
END_NAMESPACE_DISTRHO
|
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia 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.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "quicktest.h"
#include "quicktestresult_p.h"
#include <QtTest/qtestsystem.h>
#include "qtestoptions_p.h"
#include <QtQml/qqml.h>
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlcontext.h>
#include <QtQuick/qquickview.h>
#include <QtQml/qjsvalue.h>
#include <QtQml/qjsengine.h>
#include <QtGui/qopengl.h>
#include <QtCore/qurl.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qdir.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qfile.h>
#include <QtCore/qdebug.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qtextstream.h>
#include <QtGui/qtextdocument.h>
#include <stdio.h>
#include <QtGui/QGuiApplication>
#include <QtCore/QTranslator>
#include <QtTest/QSignalSpy>
QT_BEGIN_NAMESPACE
class QTestRootObject : public QObject
{
Q_OBJECT
Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged)
Q_PROPERTY(bool hasTestCase READ hasTestCase WRITE setHasTestCase NOTIFY hasTestCaseChanged)
public:
QTestRootObject(QObject *parent = 0)
: QObject(parent), hasQuit(false), m_windowShown(false), m_hasTestCase(false) {}
bool hasQuit:1;
bool hasTestCase() const { return m_hasTestCase; }
void setHasTestCase(bool value) { m_hasTestCase = value; emit hasTestCaseChanged(); }
bool windowShown() const { return m_windowShown; }
void setWindowShown(bool value) { m_windowShown = value; emit windowShownChanged(); }
Q_SIGNALS:
void windowShownChanged();
void hasTestCaseChanged();
private Q_SLOTS:
void quit() { hasQuit = true; }
private:
bool m_windowShown : 1;
bool m_hasTestCase :1;
};
static inline QString stripQuotes(const QString &s)
{
if (s.length() >= 2 && s.startsWith(QLatin1Char('"')) && s.endsWith(QLatin1Char('"')))
return s.mid(1, s.length() - 2);
else
return s;
}
void handleCompileErrors(const QFileInfo &fi, QQuickView *view)
{
// Error compiling the test - flag failure in the log and continue.
const QList<QQmlError> errors = view->errors();
QuickTestResult results;
results.setTestCaseName(fi.baseName());
results.startLogging();
results.setFunctionName(QLatin1String("compile"));
// Verbose warning output of all messages and relevant parameters
QString message;
QTextStream str(&message);
str << "\n " << QDir::toNativeSeparators(fi.absoluteFilePath()) << " produced "
<< errors.size() << " error(s):\n";
foreach (const QQmlError &e, errors) {
str << " ";
if (e.url().isLocalFile()) {
str << e.url().toLocalFile();
} else {
str << e.url().toString();
}
if (e.line() > 0)
str << ':' << e.line() << ',' << e.column();
str << ": " << e.description() << '\n';
}
str << " Working directory: " << QDir::toNativeSeparators(QDir::current().absolutePath()) << '\n';
if (QQmlEngine *engine = view->engine()) {
str << " View: " << view->metaObject()->className() << ", import paths:\n";
foreach (const QString &i, engine->importPathList())
str << " '" << QDir::toNativeSeparators(i) << "'\n";
const QStringList pluginPaths = engine->pluginPathList();
str << " Plugin paths:\n";
foreach (const QString &p, pluginPaths)
str << " '" << QDir::toNativeSeparators(p) << "'\n";
}
qWarning("%s", qPrintable(message));
// Fail with error 0.
results.fail(errors.at(0).description(),
errors.at(0).url(), errors.at(0).line());
results.finishTestData();
results.finishTestDataCleanup();
results.finishTestFunction();
results.setFunctionName(QString());
results.stopLogging();
}
bool qWaitForSignal(QObject *obj, const char* signal, int timeout = 5000)
{
QSignalSpy spy(obj, signal);
QElapsedTimer timer;
timer.start();
while (!spy.size()) {
int remaining = timeout - int(timer.elapsed());
if (remaining <= 0)
break;
QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
QTest::qSleep(10);
}
return spy.size();
}
int quick_test_main(int argc, char **argv, const char *name, const char *sourceDir)
{
QGuiApplication* app = 0;
if (!QCoreApplication::instance()) {
app = new QGuiApplication(argc, argv);
}
// Look for QML-specific command-line options.
// -import dir Specify an import directory.
// -input dir Specify the input directory for test cases.
// -translation file Specify the translation file.
QStringList imports;
QString testPath;
QString translationFile;
int outargc = 1;
int index = 1;
while (index < argc) {
if (strcmp(argv[index], "-import") == 0 && (index + 1) < argc) {
imports += stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
index += 2;
} else if (strcmp(argv[index], "-input") == 0 && (index + 1) < argc) {
testPath = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
index += 2;
} else if (strcmp(argv[index], "-opengl") == 0) {
++index;
} else if (strcmp(argv[index], "-translation") == 0 && (index + 1) < argc) {
translationFile = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
index += 2;
} else if (outargc != index) {
argv[outargc++] = argv[index++];
} else {
++outargc;
++index;
}
}
argv[outargc] = 0;
argc = outargc;
// Parse the command-line arguments.
// Setting currentAppname and currentTestObjectName (via setProgramName) are needed
// for the code coverage analysis. Must be done before parseArgs is called.
QuickTestResult::setCurrentAppname(argv[0]);
QuickTestResult::setProgramName(name);
QuickTestResult::parseArgs(argc, argv);
QTranslator translator;
if (!translationFile.isEmpty()) {
if (translator.load(translationFile)) {
app->installTranslator(&translator);
} else {
qWarning("Could not load the translation file '%s'.", qPrintable(translationFile));
}
}
// Determine where to look for the test data.
if (testPath.isEmpty() && sourceDir) {
const QString s = QString::fromLocal8Bit(sourceDir);
if (QFile::exists(s))
testPath = s;
}
if (testPath.isEmpty()) {
QDir current = QDir::current();
#ifdef Q_OS_WIN
// Skip release/debug subfolders
if (!current.dirName().compare(QLatin1String("Release"), Qt::CaseInsensitive)
|| !current.dirName().compare(QLatin1String("Debug"), Qt::CaseInsensitive))
current.cdUp();
#endif // Q_OS_WIN
testPath = current.absolutePath();
}
QStringList files;
const QFileInfo testPathInfo(testPath);
if (testPathInfo.isFile()) {
if (!testPath.endsWith(QStringLiteral(".qml"))) {
qWarning("'%s' does not have the suffix '.qml'.", qPrintable(testPath));
return 1;
}
files << testPath;
} else if (testPathInfo.isDir()) {
// Scan the test data directory recursively, looking for "tst_*.qml" files.
const QStringList filters(QStringLiteral("tst_*.qml"));
QDirIterator iter(testPathInfo.absoluteFilePath(), filters, QDir::Files,
QDirIterator::Subdirectories |
QDirIterator::FollowSymlinks);
while (iter.hasNext())
files += iter.next();
files.sort();
if (files.isEmpty()) {
qWarning("The directory '%s' does not contain any test files matching '%s'",
qPrintable(testPath), qPrintable(filters.front()));
return 1;
}
} else {
qWarning("'%s' does not exist under '%s'.",
qPrintable(testPath), qPrintable(QDir::currentPath()));
return 1;
}
// Scan through all of the "tst_*.qml" files and run each of them
// in turn with a QQuickView.
QQuickView *view = new QQuickView;
QTestRootObject rootobj;
QEventLoop eventLoop;
QObject::connect(view->engine(), SIGNAL(quit()),
&rootobj, SLOT(quit()));
QObject::connect(view->engine(), SIGNAL(quit()),
&eventLoop, SLOT(quit()));
view->rootContext()->setContextProperty
(QLatin1String("qtest"), &rootobj);
foreach (const QString &path, imports)
view->engine()->addImportPath(path);
foreach (QString file, files) {
QFileInfo fi(file);
if (!fi.exists())
continue;
rootobj.setHasTestCase(false);
rootobj.setWindowShown(false);
rootobj.hasQuit = false;
QString path = fi.absoluteFilePath();
if (path.startsWith(QLatin1String(":/")))
view->setSource(QUrl(QLatin1String("qrc:") + path.mid(2)));
else
view->setSource(QUrl::fromLocalFile(path));
if (QTest::printAvailableFunctions)
continue;
if (view->status() == QQuickView::Error) {
handleCompileErrors(fi, view);
continue;
}
if (!rootobj.hasQuit) {
// If the test already quit, then it was performed
// synchronously during setSource(). Otherwise it is
// an asynchronous test and we need to show the window
// and wait for the first frame to be rendered
// and then wait for quit indication.
view->show();
if (qWaitForSignal(view, SIGNAL(frameSwapped())))
rootobj.setWindowShown(true);
if (!rootobj.hasQuit && rootobj.hasTestCase())
eventLoop.exec();
}
}
// Flush the current logging stream.
QuickTestResult::setProgramName(0);
delete view;
delete app;
// Return the number of failures as the exit code.
return QuickTestResult::exitCode();
}
QT_END_NAMESPACE
#include "quicktest.moc"
Fix qmltest library.
- Avoid hangs (waiting for frameSwapped) and crashes
in window managers for empty windows by giving windows
a minimum size if they have 0x0 (observed on Mac, Windows).
- Polishing, set proper window flags, title, object name, output.
Change-Id: Iad5d66c3adbbfe085390132987e95f4c69272831
Reviewed-by: Christiaan Janssen <293f7292b4e4c70c138c7f8cfde88e640fae39b8@digia.com>
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia 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.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "quicktest.h"
#include "quicktestresult_p.h"
#include <QtTest/qtestsystem.h>
#include "qtestoptions_p.h"
#include <QtQml/qqml.h>
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlcontext.h>
#include <QtQuick/qquickview.h>
#include <QtQml/qjsvalue.h>
#include <QtQml/qjsengine.h>
#include <QtGui/qopengl.h>
#include <QtCore/qurl.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qdir.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qfile.h>
#include <QtCore/qdebug.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qtextstream.h>
#include <QtGui/qtextdocument.h>
#include <stdio.h>
#include <QtGui/QGuiApplication>
#include <QtCore/QTranslator>
#include <QtTest/QSignalSpy>
QT_BEGIN_NAMESPACE
class QTestRootObject : public QObject
{
Q_OBJECT
Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged)
Q_PROPERTY(bool hasTestCase READ hasTestCase WRITE setHasTestCase NOTIFY hasTestCaseChanged)
public:
QTestRootObject(QObject *parent = 0)
: QObject(parent), hasQuit(false), m_windowShown(false), m_hasTestCase(false) {}
bool hasQuit:1;
bool hasTestCase() const { return m_hasTestCase; }
void setHasTestCase(bool value) { m_hasTestCase = value; emit hasTestCaseChanged(); }
bool windowShown() const { return m_windowShown; }
void setWindowShown(bool value) { m_windowShown = value; emit windowShownChanged(); }
Q_SIGNALS:
void windowShownChanged();
void hasTestCaseChanged();
private Q_SLOTS:
void quit() { hasQuit = true; }
private:
bool m_windowShown : 1;
bool m_hasTestCase :1;
};
static inline QString stripQuotes(const QString &s)
{
if (s.length() >= 2 && s.startsWith(QLatin1Char('"')) && s.endsWith(QLatin1Char('"')))
return s.mid(1, s.length() - 2);
else
return s;
}
void handleCompileErrors(const QFileInfo &fi, QQuickView *view)
{
// Error compiling the test - flag failure in the log and continue.
const QList<QQmlError> errors = view->errors();
QuickTestResult results;
results.setTestCaseName(fi.baseName());
results.startLogging();
results.setFunctionName(QLatin1String("compile"));
// Verbose warning output of all messages and relevant parameters
QString message;
QTextStream str(&message);
str << "\n " << QDir::toNativeSeparators(fi.absoluteFilePath()) << " produced "
<< errors.size() << " error(s):\n";
foreach (const QQmlError &e, errors) {
str << " ";
if (e.url().isLocalFile()) {
str << QDir::toNativeSeparators(e.url().toLocalFile());
} else {
str << e.url().toString();
}
if (e.line() > 0)
str << ':' << e.line() << ',' << e.column();
str << ": " << e.description() << '\n';
}
str << " Working directory: " << QDir::toNativeSeparators(QDir::current().absolutePath()) << '\n';
if (QQmlEngine *engine = view->engine()) {
str << " View: " << view->metaObject()->className() << ", import paths:\n";
foreach (const QString &i, engine->importPathList())
str << " '" << QDir::toNativeSeparators(i) << "'\n";
const QStringList pluginPaths = engine->pluginPathList();
str << " Plugin paths:\n";
foreach (const QString &p, pluginPaths)
str << " '" << QDir::toNativeSeparators(p) << "'\n";
}
qWarning("%s", qPrintable(message));
// Fail with error 0.
results.fail(errors.at(0).description(),
errors.at(0).url(), errors.at(0).line());
results.finishTestData();
results.finishTestDataCleanup();
results.finishTestFunction();
results.setFunctionName(QString());
results.stopLogging();
}
bool qWaitForSignal(QObject *obj, const char* signal, int timeout = 5000)
{
QSignalSpy spy(obj, signal);
QElapsedTimer timer;
timer.start();
while (!spy.size()) {
int remaining = timeout - int(timer.elapsed());
if (remaining <= 0)
break;
QCoreApplication::processEvents(QEventLoop::AllEvents, remaining);
QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
QTest::qSleep(10);
}
return spy.size();
}
int quick_test_main(int argc, char **argv, const char *name, const char *sourceDir)
{
QGuiApplication* app = 0;
if (!QCoreApplication::instance()) {
app = new QGuiApplication(argc, argv);
}
// Look for QML-specific command-line options.
// -import dir Specify an import directory.
// -input dir Specify the input directory for test cases.
// -translation file Specify the translation file.
QStringList imports;
QString testPath;
QString translationFile;
int outargc = 1;
int index = 1;
while (index < argc) {
if (strcmp(argv[index], "-import") == 0 && (index + 1) < argc) {
imports += stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
index += 2;
} else if (strcmp(argv[index], "-input") == 0 && (index + 1) < argc) {
testPath = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
index += 2;
} else if (strcmp(argv[index], "-opengl") == 0) {
++index;
} else if (strcmp(argv[index], "-translation") == 0 && (index + 1) < argc) {
translationFile = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
index += 2;
} else if (outargc != index) {
argv[outargc++] = argv[index++];
} else {
++outargc;
++index;
}
}
argv[outargc] = 0;
argc = outargc;
// Parse the command-line arguments.
// Setting currentAppname and currentTestObjectName (via setProgramName) are needed
// for the code coverage analysis. Must be done before parseArgs is called.
QuickTestResult::setCurrentAppname(argv[0]);
QuickTestResult::setProgramName(name);
QuickTestResult::parseArgs(argc, argv);
QTranslator translator;
if (!translationFile.isEmpty()) {
if (translator.load(translationFile)) {
app->installTranslator(&translator);
} else {
qWarning("Could not load the translation file '%s'.", qPrintable(translationFile));
}
}
// Determine where to look for the test data.
if (testPath.isEmpty() && sourceDir) {
const QString s = QString::fromLocal8Bit(sourceDir);
if (QFile::exists(s))
testPath = s;
}
if (testPath.isEmpty()) {
QDir current = QDir::current();
#ifdef Q_OS_WIN
// Skip release/debug subfolders
if (!current.dirName().compare(QLatin1String("Release"), Qt::CaseInsensitive)
|| !current.dirName().compare(QLatin1String("Debug"), Qt::CaseInsensitive))
current.cdUp();
#endif // Q_OS_WIN
testPath = current.absolutePath();
}
QStringList files;
const QFileInfo testPathInfo(testPath);
if (testPathInfo.isFile()) {
if (!testPath.endsWith(QStringLiteral(".qml"))) {
qWarning("'%s' does not have the suffix '.qml'.", qPrintable(testPath));
return 1;
}
files << testPath;
} else if (testPathInfo.isDir()) {
// Scan the test data directory recursively, looking for "tst_*.qml" files.
const QStringList filters(QStringLiteral("tst_*.qml"));
QDirIterator iter(testPathInfo.absoluteFilePath(), filters, QDir::Files,
QDirIterator::Subdirectories |
QDirIterator::FollowSymlinks);
while (iter.hasNext())
files += iter.next();
files.sort();
if (files.isEmpty()) {
qWarning("The directory '%s' does not contain any test files matching '%s'",
qPrintable(testPath), qPrintable(filters.front()));
return 1;
}
} else {
qWarning("'%s' does not exist under '%s'.",
qPrintable(testPath), qPrintable(QDir::currentPath()));
return 1;
}
// Scan through all of the "tst_*.qml" files and run each of them
// in turn with a QQuickView.
QQuickView *view = new QQuickView;
view->setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint
| Qt::WindowCloseButtonHint);
QTestRootObject rootobj;
QEventLoop eventLoop;
QObject::connect(view->engine(), SIGNAL(quit()),
&rootobj, SLOT(quit()));
QObject::connect(view->engine(), SIGNAL(quit()),
&eventLoop, SLOT(quit()));
view->rootContext()->setContextProperty
(QLatin1String("qtest"), &rootobj);
foreach (const QString &path, imports)
view->engine()->addImportPath(path);
foreach (const QString &file, files) {
const QFileInfo fi(file);
if (!fi.exists())
continue;
view->setObjectName(fi.baseName());
view->setWindowTitle(view->objectName());
rootobj.setHasTestCase(false);
rootobj.setWindowShown(false);
rootobj.hasQuit = false;
QString path = fi.absoluteFilePath();
if (path.startsWith(QLatin1String(":/")))
view->setSource(QUrl(QLatin1String("qrc:") + path.mid(2)));
else
view->setSource(QUrl::fromLocalFile(path));
if (QTest::printAvailableFunctions)
continue;
if (view->status() == QQuickView::Error) {
handleCompileErrors(fi, view);
continue;
}
if (!rootobj.hasQuit) {
// If the test already quit, then it was performed
// synchronously during setSource(). Otherwise it is
// an asynchronous test and we need to show the window
// and wait for the first frame to be rendered
// and then wait for quit indication.
view->setFramePos(QPoint(50, 50));
if (view->size().isEmpty()) { // Avoid hangs with empty windows.
qWarning().nospace()
<< "Test '" << QDir::toNativeSeparators(path) << "' has invalid size "
<< view->size() << ", resizing.";
view->resize(200, 200);
}
view->show();
if (qWaitForSignal(view, SIGNAL(frameSwapped())))
rootobj.setWindowShown(true);
if (!rootobj.hasQuit && rootobj.hasTestCase())
eventLoop.exec();
view->hide();
}
}
// Flush the current logging stream.
QuickTestResult::setProgramName(0);
delete view;
delete app;
// Return the number of failures as the exit code.
return QuickTestResult::exitCode();
}
QT_END_NAMESPACE
#include "quicktest.moc"
|
/*
Copyright libCellML Contributors
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "gtest/gtest.h"
#include <algorithm>
#include <iostream>
#include <libcellml>
#include <string>
#include <vector>
TEST(Parser, invalidXMLElements) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<fellowship>"
"<Dwarf bearded>Gimli</ShortGuy>"
"<Hobbit>Frodo</EvenShorterGuy>"
"<Wizard>Gandalf</SomeGuyWithAStaff>"
"<Elf>"
"</fellows>";
std::vector<std::string> expectedErrors = {
"Specification mandate value for attribute bearded.",
"Specification mandates value for attribute bearded.",
"Opening and ending tag mismatch: Dwarf line 2 and ShortGuy.",
"Opening and ending tag mismatch: Hobbit line 2 and EvenShorterGuy.",
"Opening and ending tag mismatch: Wizard line 2 and SomeGuyWithAStaff.",
"Opening and ending tag mismatch: Elf line 2 and fellows.",
"Premature end of data in tag fellowship line 2.",
"Could not get a valid XML root node from the provided input."
};
libcellml::Parser p;
p.parseModel(input);
EXPECT_EQ(expectedErrors.size()-1, p.errorCount());
for (size_t i = 0; i < p.errorCount(); ++i) {
if (i == 0) {
EXPECT_TRUE( !p.getError(i)->getDescription().compare(expectedErrors.at(0))
|| !p.getError(i)->getDescription().compare(expectedErrors.at(1)));
} else {
EXPECT_EQ(expectedErrors.at(i+1), p.getError(i)->getDescription());
}
}
}
TEST(Parser, parse) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\"/>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseNamedModel) {
const std::string n = "name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"name\"/>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
EXPECT_EQ(n, model->getName());
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, moveParser) {
libcellml::Parser p, pm, pa;
pa = p;
pm = std::move(p);
libcellml::Parser pc(pm);
}
TEST(Parser, makeError) {
const std::string ex = "";
libcellml::ErrorPtr e = std::make_shared<libcellml::Error>();
EXPECT_EQ(ex, e->getDescription());
}
TEST(Parser, emptyModelString) {
const std::string ex = "";
const std::string expectedError = "Document is empty.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, nonXmlString) {
const std::string ex = "Not an xml string.";
std::vector<std::string> expectedErrors = {
"Start tag expected, '<' not found.",
"Could not get a valid XML root node from the provided input."
};
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(expectedErrors.size(), p.errorCount());
for (size_t i = 0; i < p.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), p.getError(i)->getDescription());
}
}
TEST(Parser, invalidRootNode) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<yodel xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"</yodel>";
const std::string expectedError1 = "Model root node is of invalid type 'yodel'. A valid CellML root node should be of type 'model'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, invalidModelAttribute) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" game=\"model_name\"/>";
const std::string expectedError1 = "Model '' has an invalid attribute 'game'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, invalidModelElement) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<uknits/>"
"</model>";
const std::string expectedError1 = "Model 'model_name' has an invalid child element 'uknits'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, modelWithInvalidElement) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"bilbo\">"
"<hobbit/>"
"</model>";
const std::string expectError1 = "Model 'bilbo' has an invalid child element 'hobbit'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<hobbit/>"
"</model>";
const std::string expectError2 = "Model '' has an invalid child element 'hobbit'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
}
TEST(Parser, parseModelWithInvalidAttributeAndGetError) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\" nonsense=\"oops\"/>";
const std::string expectedError = "Model 'modelName' has an invalid attribute 'nonsense'.";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(input);
EXPECT_EQ(1, parser.errorCount());
EXPECT_EQ(expectedError, parser.getError(0)->getDescription());
// Get ModelError and check.
EXPECT_EQ(model, parser.getError(0)->getModel());
// Get const modelError and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(parser).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::ModelPtr modelFromError = static_cast<const libcellml::Error*>(rawErr)->getModel();
EXPECT_EQ(model, modelFromError);
}
TEST(Parser, parseNamedModelWithNamedComponent) {
const std::string mName = "modelName";
const std::string cName = "componentName";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentName\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
EXPECT_EQ(mName, model->getName());
libcellml::ComponentPtr c = model->getComponent(cName);
EXPECT_EQ(cName, c->getName());
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseModelWithUnitsAndNamedComponent) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit multiplier=\"1.8\" units=\"celsius\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"<component name=\"component_name\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, unitsAttributeError) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"pH\" invalid_attribute=\"yes\"/>"
"</model>";
const std::string expectedError1 = "Units 'pH' has an invalid attribute 'invalid_attribute'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, unitsElementErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units>"
"<son name=\"stan\"/>"
"</units>"
"</model>";
const std::string expectError1 = "Units '' has an invalid child element 'son'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"randy\">"
"<son name=\"stan\"/>"
"</units>"
"</model>";
const std::string expectError2 = "Units 'randy' has an invalid child element 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
}
TEST(Parser, parseModelWithNamedComponentWithInvalidBaseUnitsAttributeAndGetError) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"unit_name\" base_unit=\"yes\"/>"
"<component name=\"component_name\">"
"</component>"
"</model>";
const std::string expectedError1 = "Units 'unit_name' has an invalid attribute 'base_unit'.";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(in);
EXPECT_EQ(1, parser.errorCount());
EXPECT_EQ(expectedError1, parser.getError(0)->getDescription());
libcellml::UnitsPtr unitsExpected = model->getUnits("unit_name");
// Get units from error and check.
EXPECT_EQ(unitsExpected, parser.getError(0)->getUnits());
// Get const units from error and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(parser).getError(0);
const libcellml::UnitsPtr unitsFromError = err->getUnits();
EXPECT_EQ(unitsExpected, unitsFromError);
}
TEST(Parser, parseModelWithInvalidComponentAttributeAndGetError) {
const std::string cName = "componentName";
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentName\" nonsense=\"oops\"/>"
"</model>";
const std::string expectedError = "Component 'componentName' has an invalid attribute 'nonsense'.";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(input);
libcellml::ComponentPtr component = model->getComponent(cName);
EXPECT_EQ(1, parser.errorCount());
EXPECT_EQ(expectedError, parser.getError(0)->getDescription());
// Get component from error and check.
EXPECT_EQ(component, parser.getError(0)->getComponent());
// Get const component from error and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(parser).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::ComponentPtr componentFromError = static_cast<const libcellml::Error*>(rawErr)->getComponent();
EXPECT_EQ(component, componentFromError);
// Get non-existent error
EXPECT_EQ(nullptr, parser.getError(1));
}
TEST(Parser, componentAttributeErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component lame=\"randy\"/>"
"</model>";
const std::string expectError1 = "Component '' has an invalid attribute 'lame'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\" son=\"stan\"/>"
"</model>";
const std::string expectError2 = "Component 'randy' has an invalid attribute 'son'.";
const std::string input3 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component son=\"stan\" name=\"randy\"/>"
"</model>";
const std::string expectError3 = "Component 'randy' has an invalid attribute 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input3);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError3, p.getError(0)->getDescription());
}
TEST(Parser, componentElementErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component>"
"<son name=\"stan\"/>"
"</component>"
"</model>";
const std::string expectError1 = "Component '' has an invalid child element 'son'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\">"
"<son name=\"stan\"/>"
"</component>"
"</model>";
const std::string expectError2 = "Component 'randy' has an invalid child element 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
}
TEST(Parser, parseModelWithTwoComponents) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"component1\"/>"
"<component name=\"component2\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseModelWithComponentHierarchyWaterfall) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"dave\"/>"
"<component name=\"bob\"/>"
"<component name=\"angus\"/>"
"<encapsulation>"
"<component_ref component=\"dave\">"
"<component_ref component=\"bob\">"
"<component_ref component=\"angus\"/>"
"</component_ref>"
"</component_ref>"
"</encapsulation>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseModelWithMultipleComponentHierarchyWaterfalls) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"ignatio\"/>"
"<component name=\"dave\"/>"
"<component name=\"bob\"/>"
"<component name=\"angus\"/>"
"<component name=\"jackie\"/>"
"<encapsulation>"
"<component_ref component=\"dave\">"
"<component_ref component=\"bob\">"
"<component_ref component=\"angus\"/>"
"<component_ref component=\"jackie\"/>"
"</component_ref>"
"</component_ref>"
"</encapsulation>"
"<component name=\"mildred\"/>"
"<component name=\"sue\"/>"
"<encapsulation>"
"<component_ref component=\"mildred\">"
"<component_ref component=\"sue\"/>"
"</component_ref>"
"</encapsulation>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, modelWithUnits) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit multiplier=\"1.8\" units=\"celsius\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"</model>";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit multiplier=\"1.8\" units=\"celsius\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(in);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, modelWithInvalidUnits) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\" temperature=\"451\">"
"<unit multiplier=\"Z\" exponent=\"35.0E+310\" units=\"celsius\" bill=\"murray\">"
"<degrees/>"
"</unit>"
"<bobshouse address=\"34 Rich Lane\"/>"
"<unit GUnit=\"50c\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"<units jerry=\"seinfeld\">"
"<unit units=\"friends\" neighbor=\"kramer\"/>"
"<unit george=\"friends\"/>"
"</units>"
"</model>";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit units=\"celsius\"/>"
"<unit units=\"\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"</model>";
std::vector<std::string> expectedErrors = {
"Units 'fahrenheitish' has an invalid attribute 'temperature'.",
"Unit referencing 'celsius' in units 'fahrenheitish' has an invalid child element 'degrees'.",
"Unit referencing 'celsius' in units 'fahrenheitish' has a multiplier with the value 'Z' that cannot be converted to a decimal number.",
"Unit referencing 'celsius' in units 'fahrenheitish' has an exponent with the value '35.0E+310' that cannot be converted to a decimal number.",
"Unit referencing 'celsius' in units 'fahrenheitish' has an invalid attribute 'bill'.",
"Units 'fahrenheitish' has an invalid child element 'bobshouse'.",
"Unit referencing '' in units 'fahrenheitish' has an invalid attribute 'GUnit'.",
"Units '' has an invalid attribute 'jerry'.",
"Unit referencing 'friends' in units '' has an invalid attribute 'neighbor'.",
"Unit referencing '' in units '' has an invalid attribute 'george'."
};
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(in);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, emptyEncapsulation) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation/>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' does not contain any child elements.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationWithNoComponentAttribute) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation>"
"<component_ref/>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' does not have a valid component attribute in a component_ref element.";
const std::string expectedError2 = "Encapsulation in model 'model_name' specifies an invalid parent component_ref that also does not have any children.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, encapsulationWithNoComponentRef) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation>"
"<component_free/>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' has an invalid child element 'component_free'.";
const std::string expectedError2 = "Encapsulation in model 'model_name' specifies an invalid parent component_ref that also does not have any children.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, encapsulationWithNoComponent) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_ref/>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' specifies 'bob' as a component in a component_ref but it does not exist in the model.";
const std::string expectedError2 = "Encapsulation in model 'model_name' does not have a valid component attribute in a component_ref that is a child of invalid parent component 'bob'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, encapsulationWithMissingComponent) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_ref component=\"dave\"/>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' specifies 'dave' as a component in a component_ref but it does not exist in the model.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationWithNoComponentChild) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<encapsulation>"
"<component_ref component=\"bob\"/>"
"</encapsulation>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' specifies 'bob' as a parent component_ref but it does not have any children.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationNoChildComponentRef) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_free/>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' has an invalid child element 'component_free'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationWithNoGrandchildComponentRef) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<component name=\"jim\"/>"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_ref component=\"jim\">"
"<component_free/>"
"</component_ref>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' has an invalid child element 'component_free'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, invalidEncapsulations) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"ringo\">"
"<component name=\"dave\"/>"
"<component name=\"bob\"/>"
"<encapsulation relationship=\"friends\">"
"<component_ref component=\"dave\" bogus=\"oops\">"
"<component_ref component=\"bob\" bogus=\"oops\"/>"
"<component_ref enemy=\"ignatio\"/>"
"</component_ref>"
"<component_ref component=\"ignatio\"/>"
"<component_ref>"
"<component_ref/>"
"</component_ref>"
"</encapsulation>"
"</model>";
std::vector<std::string> expectedErrors = {
"Encapsulation in model 'ringo' has an invalid attribute 'relationship'.",
"Encapsulation in model 'ringo' has an invalid component_ref attribute 'bogus'.",
"Encapsulation in model 'ringo' has an invalid component_ref attribute 'bogus'.",
"Encapsulation in model 'ringo' has an invalid component_ref attribute 'enemy'.",
"Encapsulation in model 'ringo' does not have a valid component attribute in a component_ref that is a child of 'dave'.",
"Encapsulation in model 'ringo' specifies 'ignatio' as a component in a component_ref but it does not exist in the model.",
"Encapsulation in model 'ringo' specifies an invalid parent component_ref that also does not have any children.",
"Encapsulation in model 'ringo' does not have a valid component attribute in a component_ref element.",
"Encapsulation in model 'ringo' does not have a valid component attribute in a component_ref that is a child of an invalid parent component."
};
libcellml::Parser parser;
parser.parseModel(e);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
TEST(Parser, invalidVariableAttributesAndGetVariableError) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"componentA\">"
"<variable name=\"quixote\" don=\"true\"/>"
"<variable windmill=\"tilted\"/>"
"</component>"
"</model>";
const std::string expectError1 = "Variable 'quixote' has an invalid attribute 'don'.";
const std::string expectError2 = "Variable '' has an invalid attribute 'windmill'.";
libcellml::Parser p;
libcellml::ModelPtr model = p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
EXPECT_EQ(expectError2, p.getError(1)->getDescription());
libcellml::VariablePtr variableExpected = model->getComponent("componentA")->getVariable("quixote");
// Get variable from error and check.
EXPECT_EQ(variableExpected, p.getError(0)->getVariable());
// Get const variable from error and check.
libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(p).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::VariablePtr variableFromError = static_cast<const libcellml::Error*>(rawErr)->getVariable();
EXPECT_EQ(variableExpected, variableFromError);
}
TEST(Parser, variableAttributeAndChildErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\">"
"<variable lame=\"randy\"/>"
"</component>"
"</model>";
const std::string expectError1 = "Variable '' has an invalid attribute 'lame'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\">"
"<variable name=\"randy\" son=\"stan\">"
"<daughter name=\"shelly\"/>"
"</variable>"
"</component>"
"</model>";
const std::string expectError2 = "Variable 'randy' has an invalid child element 'daughter'.";
const std::string expectError3 = "Variable 'randy' has an invalid attribute 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
EXPECT_EQ(expectError3, p.getError(1)->getDescription());
}
TEST(Parser, emptyConnections) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<connection/>"
"</model>";
const std::string expectedError1 = "Connection in model 'model_name' does not have a valid component_1 in a connection element.";
const std::string expectedError2 = "Connection in model 'model_name' does not have a valid component_2 in a connection element.";
const std::string expectedError3 = "Connection in model 'model_name' must contain one or more 'map_variables' elements.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(3, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
}
TEST(Parser, connectionErrorNoComponent2) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelA\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_1=\"component1\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model 'modelA' does not have a valid component_2 in a connection element.";
const std::string expectedError2 = "Connection in model 'modelA' specifies 'component1' as component_1 but it does not exist in the model.";
const std::string expectedError3 = "Connection in model 'modelA' specifies 'variable1' as variable_1 but the corresponding component_1 is invalid.";
const std::string expectedError4 = "Connection in model 'modelA' specifies 'variable2' as variable_2 but the corresponding component_2 is invalid.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(4, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
EXPECT_EQ(expectedError4, p.getError(3)->getDescription());
}
TEST(Parser, connectionErrorNoComponent2InModel) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_1=\"component1\" component_2=\"component2\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model 'modelName' specifies 'component2' as component_2 but it does not exist in the model.";
const std::string expectedError2 = "Connection in model 'modelName' specifies 'variable2' as variable_2 but the corresponding component_2 is invalid.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, connectionErrorNoComponent1) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_2=\"componentA\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model 'modelName' does not have a valid component_1 in a connection element.";
const std::string expectedError2 = "Connection in model 'modelName' specifies 'variable1' as variable_1 but the corresponding component_1 is invalid.";
const std::string expectedError3 = "Variable 'variable2' is specified as variable_2 in a connection but it does not exist in component_2 component 'componentA' of model 'modelName'.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(3, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
}
TEST(Parser, connectionErrorNoMapComponents) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection name=\"invalid\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\" variable_3=\"variable3\">"
"<map_units/>"
"</map_variables>"
"</connection>"
"</model>";
std::vector<std::string> expectedErrors = {
"Connection in model 'modelName' has an invalid connection attribute 'name'.",
"Connection in model 'modelName' does not have a valid component_1 in a connection element.",
"Connection in model 'modelName' does not have a valid component_2 in a connection element.",
"Connection in model 'modelName' has an invalid child element 'map_units' of element 'map_variables'.",
"Connection in model 'modelName' has an invalid map_variables attribute 'variable_3'.",
"Connection in model 'modelName' specifies 'variable1' as variable_1 but the corresponding component_1 is invalid.",
"Connection in model 'modelName' specifies 'variable2' as variable_2 but the corresponding component_2 is invalid."
};
libcellml::Parser parser;
parser.parseModel(in);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
TEST(Parser, connectionErrorNoMapVariables) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_2=\"componentA\" component_1=\"componentA\" component_3=\"componentA\"/>"
"<connection component_2=\"componentA\" component_1=\"componentA\"/>"
"</model>";
const std::string expectedError1 = "Connection in model '' has an invalid connection attribute 'component_3'.";
const std::string expectedError2 = "Connection in model '' must contain one or more 'map_variables' elements.";
const std::string expectedError3 = "Connection in model '' must contain one or more 'map_variables' elements.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(3, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
}
TEST(Parser, importedComponent2Connection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
"<component component_ref=\"component_in_that_model\" name=\"component_in_this_model\"/>"
"</import>"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<connection component_2=\"component_in_this_model\" component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_import\" variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
// Parse
libcellml::Parser parser;
parser.parseModel(e);
EXPECT_EQ(0, parser.errorCount());
}
TEST(Parser, validConnectionMapVariablesFirst) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"robert\">"
"<variable name=\"bob\"/>"
"</component>"
"<component name=\"james\">"
"<variable name=\"jimbo\"/>"
"</component>"
"<connection component_1=\"robert\" component_2=\"james\">"
"<map_variables variable_2=\"jimbo\" variable_1=\"bob\"/>"
"</connection>"
"</model>";
libcellml::Parser parser;
parser.parseModel(e);
EXPECT_EQ(0, parser.errorCount());
}
TEST(Parser, component2ConnectionVariableMissing) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_2=\"component_dave\" component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_angus\" variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
const std::string expectedError = "Variable 'variable_angus' is specified as variable_2 in a connection but it does not exist in component_2 component 'component_dave' of model ''.";
// Parse
libcellml::Parser p;
p.parseModel(e);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, component2InConnectionMissing) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_angus\" variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"</model>";
const std::string expectedError1 = "Connection in model '' does not have a valid component_2 in a connection element.";
const std::string expectedError2 = "Connection in model '' specifies 'variable_angus' as variable_2 but the corresponding component_2 is invalid.";
// Parse
libcellml::Parser p;
libcellml::ModelPtr m = p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, connectionVariable2Missing) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_2=\"component_dave\" component_1=\"component_bob\">"
"<map_variables variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model '' does not have a valid variable_2 in a map_variables element.";
// Parse
libcellml::Parser p;
p.parseModel(e);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, connectionVariable1Missing) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_2=\"component_dave\" component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_dave\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model '' does not have a valid variable_1 in a map_variables element.";
// Parse
libcellml::Parser p;
p.parseModel(e);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, connectionErrorNoMapVariablesType) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<component name=\"component2\">"
"<variable name=\"variable2\"/>"
"</component>"
"<connection component_1=\"component1\" component_2=\"component2\">"
"<map_variabels variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model '' has an invalid child element 'map_variabels'.";
const std::string expectedError2 = "Connection in model '' does not have a map_variables element.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, invalidImportsAndGetError) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" sauce=\"hollandaise\">"
"<units units_ref=\"a_units_in_that_model\" name=\"units_in_this_model\"/>"
"<component component_ref=\"a_component_in_that_model\" name=\"component_in_this_model\"/>"
"<invalid_nonsense/>"
"<units units_ruff=\"dog\" name=\"fido\"/>"
"<component component_meow=\"cat\" name=\"frank\"/>"
"</import>"
"</model>";
const std::string expectError1 = "Import from 'some-other-model.xml' has an invalid attribute 'sauce'.";
const std::string expectError2 = "Import from 'some-other-model.xml' has an invalid child element 'invalid_nonsense'.";
const std::string expectError3 = "Import of units 'fido' from 'some-other-model.xml' has an invalid attribute 'units_ruff'.";
const std::string expectError4 = "Import of component 'frank' from 'some-other-model.xml' has an invalid attribute 'component_meow'.";
const std::string output =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
"<component component_ref=\"a_component_in_that_model\" name=\"component_in_this_model\"/>"
"</import>"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
"<units units_ref=\"a_units_in_that_model\" name=\"units_in_this_model\"/>"
"</import>"
"</model>";
libcellml::Parser p;
libcellml::ModelPtr m = p.parseModel(input);
EXPECT_EQ(4, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
EXPECT_EQ(expectError2, p.getError(1)->getDescription());
EXPECT_EQ(expectError3, p.getError(2)->getDescription());
EXPECT_EQ(expectError4, p.getError(3)->getDescription());
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(output, a);
libcellml::ImportSourcePtr import = m->getUnits("units_in_this_model")->getImportSource();
// Get import from error and check.
EXPECT_EQ(import, p.getError(0)->getImportSource());
// Get const import from error and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(p).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::ImportSourcePtr importFromError = static_cast<const libcellml::Error*>(rawErr)->getImportSource();
EXPECT_EQ(import, importFromError);
}
TEST(Parser, invalidModelWithAllKindsOfErrors) {
// Check for all kinds of errors.
std::vector<bool> foundKind(9, false);
// Trigger CellML entity errors
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"starwars\" episode=\"four\">"
"<import princess=\"leia\"/>"
"<units jedi=\"luke\"/>"
"<component ship=\"falcon\">"
"<variable pilot=\"han\"/>"
"</component>"
"<connection wookie=\"chewie\"/>"
"<encapsulation yoda=\"green\"/>"
"</model>";
std::vector<std::string> expectedErrors = {
"Model 'starwars' has an invalid attribute 'episode'.",
"Import from '' has an invalid attribute 'princess'.",
"Units '' has an invalid attribute 'jedi'.",
"Component '' has an invalid attribute 'ship'.",
"Variable '' has an invalid attribute 'pilot'.",
"Connection in model 'starwars' has an invalid connection attribute 'wookie'.",
"Connection in model 'starwars' does not have a valid component_1 in a connection element.",
"Connection in model 'starwars' does not have a valid component_2 in a connection element.",
"Connection in model 'starwars' must contain one or more 'map_variables' elements.",
"Encapsulation in model 'starwars' has an invalid attribute 'yoda'.",
"Encapsulation in model 'starwars' does not contain any child elements."
};
// Parse and check for CellML errors.
libcellml::Parser parser;
parser.parseModel(input);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
switch (parser.getError(i)->getKind()) {
case (libcellml::Error::Kind::COMPONENT): {
foundKind.at(0) = true;
break;
}
case (libcellml::Error::Kind::CONNECTION): {
foundKind.at(1) = true;
break;
}
case (libcellml::Error::Kind::ENCAPSULATION): {
foundKind.at(2) = true;
break;
}
case (libcellml::Error::Kind::IMPORT): {
foundKind.at(3) = true;
break;
}
case (libcellml::Error::Kind::MODEL): {
foundKind.at(4) = true;
break;
}
case (libcellml::Error::Kind::UNITS): {
foundKind.at(5) = true;
break;
}
case (libcellml::Error::Kind::VARIABLE): {
foundKind.at(6) = true;
break;
}
default:{
}
}
}
// Trigger undefined error
libcellml::Parser parser2;
// Add an undefined error
libcellml::ErrorPtr undefinedError = std::make_shared<libcellml::Error>();
parser2.addError(undefinedError);
EXPECT_EQ(1, parser2.errorCount());
if (parser2.getError(0)->isKind(libcellml::Error::Kind::UNDEFINED)) {
foundKind.at(7) = true;
}
// Trigger an XML error
const std::string input3 = "jarjarbinks";
std::vector<std::string> expectedErrors3 = {
"Start tag expected, '<' not found.",
"Could not get a valid XML root node from the provided input."
};
libcellml::Parser parser3;
parser3.parseModel(input3);
EXPECT_EQ(expectedErrors3.size(), parser3.errorCount());
for (size_t i = 0; i < parser3.errorCount(); ++i) {
EXPECT_EQ(expectedErrors3.at(i), parser3.getError(i)->getDescription());
if (parser3.getError(i)->isKind(libcellml::Error::Kind::XML)) {
foundKind.at(8) = true;
}
}
// Check that we've found all the possible error types
bool foundAllKinds = false;
if (std::all_of(foundKind.begin(), foundKind.end(), [](bool i) {return i;})) {
foundAllKinds = true;
}
EXPECT_TRUE(foundAllKinds);
}
TEST(Parser, invalidModelWithTextInAllElements) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"starwars\">\n"
"episode7\n"
"<import xlink:href=\"sith.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">kylo</import>\n"
"<units name=\"robot\">"
"bb-8"
"<unit units=\"ball\">rolls</unit>"
"</units>\n"
"<component name=\"ship\">falcon\n"
" <variable name=\"jedi\">rey</variable>\n"
"</component>\n"
"<connection>"
"finn"
"<map_variables>"
"trooper"
"</map_variables>"
"</connection>\n"
"<encapsulation>"
"awakens"
"<component_ref component=\"ship\">"
"force"
"</component_ref>"
"</encapsulation>\n"
"</model>";
const std::vector<std::string> expectedErrors = {
"Model 'starwars' has an invalid non-whitespace child text element '\nepisode7\n'.",
"Import from 'sith.xml' has an invalid non-whitespace child text element 'kylo'.",
"Units 'robot' has an invalid non-whitespace child text element 'bb-8'.",
"Unit referencing 'ball' in units 'robot' has an invalid non-whitespace child text element 'rolls'.",
"Component 'ship' has an invalid non-whitespace child text element 'falcon\n '.",
"Variable 'jedi' has an invalid non-whitespace child text element 'rey'.",
"Connection in model 'starwars' does not have a valid component_1 in a connection element.",
"Connection in model 'starwars' does not have a valid component_2 in a connection element.",
"Connection in model 'starwars' has an invalid non-whitespace child text element 'finn'.",
"Connection in model 'starwars' has an invalid non-whitespace child text element 'trooper'.",
"Connection in model 'starwars' does not have a valid variable_1 in a map_variables element.",
"Connection in model 'starwars' does not have a valid variable_2 in a map_variables element.",
"Connection in model 'starwars' specifies '' as variable_1 but the corresponding component_1 is invalid.",
"Connection in model 'starwars' specifies '' as variable_2 but the corresponding component_2 is invalid.",
"Encapsulation in model 'starwars' has an invalid non-whitespace child text element 'awakens'.",
"Encapsulation in model 'starwars' specifies an invalid parent component_ref that also does not have any children.",
"Encapsulation in model 'starwars' has an invalid non-whitespace child text element 'force'."
};
// Parse and check for CellML errors.
libcellml::Parser parser;
parser.parseModel(input);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
TEST(Parser, parseIds) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" id=\"mid\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" id=\"i1id\">"
"<component component_ref=\"a_component_in_that_model\" name=\"component1\" id=\"c1id\"/>"
"</import>"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" id=\"i2id\">"
"<units units_ref=\"a_units_in_that_model\" name=\"units1\" id=\"u1id\"/>"
"</import>"
"<units name=\"units2\" id=\"u2id\"/>"
"<units name=\"units3\" id=\"u3id\"/>"
"<component name=\"component2\" id=\"c2id\">"
"<variable name=\"variable1\" id=\"vid\"/>"
"</component>"
"</model>";
libcellml::Parser p;
libcellml::ModelPtr model = p.parseModel(in);
EXPECT_EQ(0, p.errorCount());
EXPECT_EQ("mid", model->getId());
EXPECT_EQ("c1id", model->getComponent("component1")->getId());
EXPECT_EQ("i1id", model->getComponent("component1")->getImportSource()->getId());
EXPECT_EQ("u1id", model->getUnits("units1")->getId());
EXPECT_EQ("i2id", model->getUnits("units1")->getImportSource()->getId());
EXPECT_EQ("u2id", model->getUnits("units2")->getId());
EXPECT_EQ("c2id", model->getComponent("component2")->getId());
EXPECT_EQ("u3id", model->getUnits("units3")->getId());
EXPECT_EQ("vid", model->getComponent("component2")->getVariable("variable1")->getId());
}
TEST(Parser, parseResets) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" id=\"mid\">"
"<component name=\"component2\" id=\"c2id\">"
"<variable name=\"variable1\" id=\"vid\"/>"
"<reset order=\"1\" id=\"rid\">"
"<when order=\"5\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"<when order=\"3\" id=\"wid\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"</reset>"
"</component>"
"</model>";
libcellml::Parser p;
libcellml::ModelPtr model = p.parseModel(in);
libcellml::ComponentPtr c = model->getComponent(0);
EXPECT_EQ(1, c->resetCount());
libcellml::ResetPtr r = c->getReset(0);
EXPECT_EQ(1, r->getOrder());
EXPECT_EQ(2, r->whenCount());
libcellml::WhenPtr w = r->getWhen(1);
EXPECT_EQ(3, w->getOrder());
}
TEST(Parser, parseResetsWithNumerousErrors) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" id=\"mid\">"
"<component name=\"component2\" id=\"c2id\">"
"<variable name=\"variable1\" id=\"vid\"/>"
"<variable name=\"V_k\" id=\"vid\"/>"
"<reset order=\"1.3\" id=\"rid\">"
"<when order=\"-0\" change=\"$4.50\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"extra mathml node"
"</math>"
"</when>"
"<when order=\"3\" id=\"wid\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"<when order=\"3\" id=\"wid\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"</reset>"
"<reset variable=\"I_na\" order=\"2\" id=\"rid\">"
"<when order=\"5.9\" goods=\"socks\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"</when>"
"</reset>"
"<reset variable=\"I_na\" order=\"2\" id=\"rid\">"
"<when />"
"</reset>"
"<reset id=\"r3id\">"
"<when order=\"\"/>"
"<about>"
"Some description of importance."
"</about>"
"</reset>"
"<reset variable=\"V_k\" order=\"-\" start=\"now\"/>"
"<reset variable=\"variable1\" order=\"0\">"
"non empty whitespace."
"<when order=\"1\">"
"illegal content."
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"<variable/>"
"</when>"
"</reset>"
"</component>"
"</model>";
const std::vector<std::string> expectedErrors = {
"Reset in component 'component2' referencing variable '' has a non-integer order value '1.3'.",
"Reset in component 'component2' does not reference a variable in the component.",
"Reset in component 'component2' referencing variable '' does not have an order defined.",
"When in reset referencing variable '' with order '' has an invalid attribute 'change'.",
"When in reset referencing variable '' with order '' contains more than two MathML child elements.",
"Reset referencing variable 'I_na' is not a valid reference for a variable in component 'component2'.",
"Reset in component 'component2' does not reference a variable in the component.",
"When in reset referencing variable '' with order '2' has an invalid attribute 'goods'.",
"When in reset referencing variable '' with order '2' does not have an order defined.",
"When in reset referencing variable '' with order '2' contains only one MathML child element.",
"Reset referencing variable 'I_na' is not a valid reference for a variable in component 'component2'.",
"Reset in component 'component2' does not reference a variable in the component.",
"When in reset referencing variable '' with order '2' does not have an order defined.",
"When in reset referencing variable '' with order '2' contains zero MathML child elements.",
"Reset in component 'component2' does not reference a variable in the component.",
"Reset in component 'component2' referencing variable '' does not have an order defined.",
"When in reset referencing variable '' with order '' does not have an order defined.",
"When in reset referencing variable '' with order '' contains zero MathML child elements.",
"Reset in component 'component2' referencing variable '' has an invalid child element 'about'.",
"Reset in component 'component2' referencing variable 'V_k' has a non-integer order value '-'.",
"Reset in component 'component2' has an invalid attribute 'start'.",
"Reset in component 'component2' referencing variable 'V_k' does not have an order defined.",
"Reset in component 'component2' referencing variable 'variable1' has an invalid non-whitespace child text element 'non empty whitespace.'.",
"When in reset referencing variable 'variable1' with order '0' has an invalid non-whitespace child text element 'illegal content.'.",
"When in reset referencing variable 'variable1' with order '0' has an invalid child element 'variable'.",
};
libcellml::Parser parser;
parser.parseModel(in);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
Add test for checking the reset and when returned from parser error.
/*
Copyright libCellML Contributors
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "gtest/gtest.h"
#include <algorithm>
#include <iostream>
#include <libcellml>
#include <string>
#include <vector>
TEST(Parser, invalidXMLElements) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<fellowship>"
"<Dwarf bearded>Gimli</ShortGuy>"
"<Hobbit>Frodo</EvenShorterGuy>"
"<Wizard>Gandalf</SomeGuyWithAStaff>"
"<Elf>"
"</fellows>";
std::vector<std::string> expectedErrors = {
"Specification mandate value for attribute bearded.",
"Specification mandates value for attribute bearded.",
"Opening and ending tag mismatch: Dwarf line 2 and ShortGuy.",
"Opening and ending tag mismatch: Hobbit line 2 and EvenShorterGuy.",
"Opening and ending tag mismatch: Wizard line 2 and SomeGuyWithAStaff.",
"Opening and ending tag mismatch: Elf line 2 and fellows.",
"Premature end of data in tag fellowship line 2.",
"Could not get a valid XML root node from the provided input."
};
libcellml::Parser p;
p.parseModel(input);
EXPECT_EQ(expectedErrors.size()-1, p.errorCount());
for (size_t i = 0; i < p.errorCount(); ++i) {
if (i == 0) {
EXPECT_TRUE( !p.getError(i)->getDescription().compare(expectedErrors.at(0))
|| !p.getError(i)->getDescription().compare(expectedErrors.at(1)));
} else {
EXPECT_EQ(expectedErrors.at(i+1), p.getError(i)->getDescription());
}
}
}
TEST(Parser, parse) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\"/>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseNamedModel) {
const std::string n = "name";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"name\"/>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
EXPECT_EQ(n, model->getName());
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, moveParser) {
libcellml::Parser p, pm, pa;
pa = p;
pm = std::move(p);
libcellml::Parser pc(pm);
}
TEST(Parser, makeError) {
const std::string ex = "";
libcellml::ErrorPtr e = std::make_shared<libcellml::Error>();
EXPECT_EQ(ex, e->getDescription());
}
TEST(Parser, emptyModelString) {
const std::string ex = "";
const std::string expectedError = "Document is empty.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, nonXmlString) {
const std::string ex = "Not an xml string.";
std::vector<std::string> expectedErrors = {
"Start tag expected, '<' not found.",
"Could not get a valid XML root node from the provided input."
};
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(expectedErrors.size(), p.errorCount());
for (size_t i = 0; i < p.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), p.getError(i)->getDescription());
}
}
TEST(Parser, invalidRootNode) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<yodel xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"</yodel>";
const std::string expectedError1 = "Model root node is of invalid type 'yodel'. A valid CellML root node should be of type 'model'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, invalidModelAttribute) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" game=\"model_name\"/>";
const std::string expectedError1 = "Model '' has an invalid attribute 'game'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, invalidModelElement) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<uknits/>"
"</model>";
const std::string expectedError1 = "Model 'model_name' has an invalid child element 'uknits'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, modelWithInvalidElement) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"bilbo\">"
"<hobbit/>"
"</model>";
const std::string expectError1 = "Model 'bilbo' has an invalid child element 'hobbit'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<hobbit/>"
"</model>";
const std::string expectError2 = "Model '' has an invalid child element 'hobbit'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
}
TEST(Parser, parseModelWithInvalidAttributeAndGetError) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\" nonsense=\"oops\"/>";
const std::string expectedError = "Model 'modelName' has an invalid attribute 'nonsense'.";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(input);
EXPECT_EQ(1, parser.errorCount());
EXPECT_EQ(expectedError, parser.getError(0)->getDescription());
// Get ModelError and check.
EXPECT_EQ(model, parser.getError(0)->getModel());
// Get const modelError and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(parser).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::ModelPtr modelFromError = static_cast<const libcellml::Error*>(rawErr)->getModel();
EXPECT_EQ(model, modelFromError);
}
TEST(Parser, parseNamedModelWithNamedComponent) {
const std::string mName = "modelName";
const std::string cName = "componentName";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentName\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
EXPECT_EQ(mName, model->getName());
libcellml::ComponentPtr c = model->getComponent(cName);
EXPECT_EQ(cName, c->getName());
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseModelWithUnitsAndNamedComponent) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit multiplier=\"1.8\" units=\"celsius\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"<component name=\"component_name\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, unitsAttributeError) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"pH\" invalid_attribute=\"yes\"/>"
"</model>";
const std::string expectedError1 = "Units 'pH' has an invalid attribute 'invalid_attribute'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, unitsElementErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units>"
"<son name=\"stan\"/>"
"</units>"
"</model>";
const std::string expectError1 = "Units '' has an invalid child element 'son'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"randy\">"
"<son name=\"stan\"/>"
"</units>"
"</model>";
const std::string expectError2 = "Units 'randy' has an invalid child element 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
}
TEST(Parser, parseModelWithNamedComponentWithInvalidBaseUnitsAttributeAndGetError) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"unit_name\" base_unit=\"yes\"/>"
"<component name=\"component_name\">"
"</component>"
"</model>";
const std::string expectedError1 = "Units 'unit_name' has an invalid attribute 'base_unit'.";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(in);
EXPECT_EQ(1, parser.errorCount());
EXPECT_EQ(expectedError1, parser.getError(0)->getDescription());
libcellml::UnitsPtr unitsExpected = model->getUnits("unit_name");
// Get units from error and check.
EXPECT_EQ(unitsExpected, parser.getError(0)->getUnits());
// Get const units from error and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(parser).getError(0);
const libcellml::UnitsPtr unitsFromError = err->getUnits();
EXPECT_EQ(unitsExpected, unitsFromError);
}
TEST(Parser, parseModelWithInvalidComponentAttributeAndGetError) {
const std::string cName = "componentName";
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentName\" nonsense=\"oops\"/>"
"</model>";
const std::string expectedError = "Component 'componentName' has an invalid attribute 'nonsense'.";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(input);
libcellml::ComponentPtr component = model->getComponent(cName);
EXPECT_EQ(1, parser.errorCount());
EXPECT_EQ(expectedError, parser.getError(0)->getDescription());
// Get component from error and check.
EXPECT_EQ(component, parser.getError(0)->getComponent());
// Get const component from error and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(parser).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::ComponentPtr componentFromError = static_cast<const libcellml::Error*>(rawErr)->getComponent();
EXPECT_EQ(component, componentFromError);
// Get non-existent error
EXPECT_EQ(nullptr, parser.getError(1));
}
TEST(Parser, componentAttributeErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component lame=\"randy\"/>"
"</model>";
const std::string expectError1 = "Component '' has an invalid attribute 'lame'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\" son=\"stan\"/>"
"</model>";
const std::string expectError2 = "Component 'randy' has an invalid attribute 'son'.";
const std::string input3 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component son=\"stan\" name=\"randy\"/>"
"</model>";
const std::string expectError3 = "Component 'randy' has an invalid attribute 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input3);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError3, p.getError(0)->getDescription());
}
TEST(Parser, componentElementErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component>"
"<son name=\"stan\"/>"
"</component>"
"</model>";
const std::string expectError1 = "Component '' has an invalid child element 'son'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\">"
"<son name=\"stan\"/>"
"</component>"
"</model>";
const std::string expectError2 = "Component 'randy' has an invalid child element 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
}
TEST(Parser, parseModelWithTwoComponents) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"component1\"/>"
"<component name=\"component2\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseModelWithComponentHierarchyWaterfall) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"dave\"/>"
"<component name=\"bob\"/>"
"<component name=\"angus\"/>"
"<encapsulation>"
"<component_ref component=\"dave\">"
"<component_ref component=\"bob\">"
"<component_ref component=\"angus\"/>"
"</component_ref>"
"</component_ref>"
"</encapsulation>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, parseModelWithMultipleComponentHierarchyWaterfalls) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"ignatio\"/>"
"<component name=\"dave\"/>"
"<component name=\"bob\"/>"
"<component name=\"angus\"/>"
"<component name=\"jackie\"/>"
"<encapsulation>"
"<component_ref component=\"dave\">"
"<component_ref component=\"bob\">"
"<component_ref component=\"angus\"/>"
"<component_ref component=\"jackie\"/>"
"</component_ref>"
"</component_ref>"
"</encapsulation>"
"<component name=\"mildred\"/>"
"<component name=\"sue\"/>"
"<encapsulation>"
"<component_ref component=\"mildred\">"
"<component_ref component=\"sue\"/>"
"</component_ref>"
"</encapsulation>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(e);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, modelWithUnits) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit multiplier=\"1.8\" units=\"celsius\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"</model>";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit multiplier=\"1.8\" units=\"celsius\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(in);
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, modelWithInvalidUnits) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\" temperature=\"451\">"
"<unit multiplier=\"Z\" exponent=\"35.0E+310\" units=\"celsius\" bill=\"murray\">"
"<degrees/>"
"</unit>"
"<bobshouse address=\"34 Rich Lane\"/>"
"<unit GUnit=\"50c\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"<units jerry=\"seinfeld\">"
"<unit units=\"friends\" neighbor=\"kramer\"/>"
"<unit george=\"friends\"/>"
"</units>"
"</model>";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<units name=\"fahrenheitish\">"
"<unit units=\"celsius\"/>"
"<unit units=\"\"/>"
"</units>"
"<units name=\"dimensionless\"/>"
"</model>";
std::vector<std::string> expectedErrors = {
"Units 'fahrenheitish' has an invalid attribute 'temperature'.",
"Unit referencing 'celsius' in units 'fahrenheitish' has an invalid child element 'degrees'.",
"Unit referencing 'celsius' in units 'fahrenheitish' has a multiplier with the value 'Z' that cannot be converted to a decimal number.",
"Unit referencing 'celsius' in units 'fahrenheitish' has an exponent with the value '35.0E+310' that cannot be converted to a decimal number.",
"Unit referencing 'celsius' in units 'fahrenheitish' has an invalid attribute 'bill'.",
"Units 'fahrenheitish' has an invalid child element 'bobshouse'.",
"Unit referencing '' in units 'fahrenheitish' has an invalid attribute 'GUnit'.",
"Units '' has an invalid attribute 'jerry'.",
"Unit referencing 'friends' in units '' has an invalid attribute 'neighbor'.",
"Unit referencing '' in units '' has an invalid attribute 'george'."
};
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(in);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
libcellml::Printer printer;
const std::string a = printer.printModel(model);
EXPECT_EQ(e, a);
}
TEST(Parser, emptyEncapsulation) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation/>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' does not contain any child elements.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationWithNoComponentAttribute) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation>"
"<component_ref/>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' does not have a valid component attribute in a component_ref element.";
const std::string expectedError2 = "Encapsulation in model 'model_name' specifies an invalid parent component_ref that also does not have any children.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, encapsulationWithNoComponentRef) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation>"
"<component_free/>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' has an invalid child element 'component_free'.";
const std::string expectedError2 = "Encapsulation in model 'model_name' specifies an invalid parent component_ref that also does not have any children.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, encapsulationWithNoComponent) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_ref/>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' specifies 'bob' as a component in a component_ref but it does not exist in the model.";
const std::string expectedError2 = "Encapsulation in model 'model_name' does not have a valid component attribute in a component_ref that is a child of invalid parent component 'bob'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, encapsulationWithMissingComponent) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_ref component=\"dave\"/>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError1 = "Encapsulation in model 'model_name' specifies 'dave' as a component in a component_ref but it does not exist in the model.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationWithNoComponentChild) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<encapsulation>"
"<component_ref component=\"bob\"/>"
"</encapsulation>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' specifies 'bob' as a parent component_ref but it does not have any children.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationNoChildComponentRef) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_free/>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' has an invalid child element 'component_free'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, encapsulationWithNoGrandchildComponentRef) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"bob\"/>"
"<component name=\"jim\"/>"
"<encapsulation>"
"<component_ref component=\"bob\">"
"<component_ref component=\"jim\">"
"<component_free/>"
"</component_ref>"
"</component_ref>"
"</encapsulation>"
"</model>";
const std::string expectedError = "Encapsulation in model 'model_name' has an invalid child element 'component_free'.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, invalidEncapsulations) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"ringo\">"
"<component name=\"dave\"/>"
"<component name=\"bob\"/>"
"<encapsulation relationship=\"friends\">"
"<component_ref component=\"dave\" bogus=\"oops\">"
"<component_ref component=\"bob\" bogus=\"oops\"/>"
"<component_ref enemy=\"ignatio\"/>"
"</component_ref>"
"<component_ref component=\"ignatio\"/>"
"<component_ref>"
"<component_ref/>"
"</component_ref>"
"</encapsulation>"
"</model>";
std::vector<std::string> expectedErrors = {
"Encapsulation in model 'ringo' has an invalid attribute 'relationship'.",
"Encapsulation in model 'ringo' has an invalid component_ref attribute 'bogus'.",
"Encapsulation in model 'ringo' has an invalid component_ref attribute 'bogus'.",
"Encapsulation in model 'ringo' has an invalid component_ref attribute 'enemy'.",
"Encapsulation in model 'ringo' does not have a valid component attribute in a component_ref that is a child of 'dave'.",
"Encapsulation in model 'ringo' specifies 'ignatio' as a component in a component_ref but it does not exist in the model.",
"Encapsulation in model 'ringo' specifies an invalid parent component_ref that also does not have any children.",
"Encapsulation in model 'ringo' does not have a valid component attribute in a component_ref element.",
"Encapsulation in model 'ringo' does not have a valid component attribute in a component_ref that is a child of an invalid parent component."
};
libcellml::Parser parser;
parser.parseModel(e);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
TEST(Parser, invalidVariableAttributesAndGetVariableError) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"componentA\">"
"<variable name=\"quixote\" don=\"true\"/>"
"<variable windmill=\"tilted\"/>"
"</component>"
"</model>";
const std::string expectError1 = "Variable 'quixote' has an invalid attribute 'don'.";
const std::string expectError2 = "Variable '' has an invalid attribute 'windmill'.";
libcellml::Parser p;
libcellml::ModelPtr model = p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
EXPECT_EQ(expectError2, p.getError(1)->getDescription());
libcellml::VariablePtr variableExpected = model->getComponent("componentA")->getVariable("quixote");
// Get variable from error and check.
EXPECT_EQ(variableExpected, p.getError(0)->getVariable());
// Get const variable from error and check.
libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(p).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::VariablePtr variableFromError = static_cast<const libcellml::Error*>(rawErr)->getVariable();
EXPECT_EQ(variableExpected, variableFromError);
}
TEST(Parser, variableAttributeAndChildErrors) {
const std::string input1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\">"
"<variable lame=\"randy\"/>"
"</component>"
"</model>";
const std::string expectError1 = "Variable '' has an invalid attribute 'lame'.";
const std::string input2 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<component name=\"randy\">"
"<variable name=\"randy\" son=\"stan\">"
"<daughter name=\"shelly\"/>"
"</variable>"
"</component>"
"</model>";
const std::string expectError2 = "Variable 'randy' has an invalid child element 'daughter'.";
const std::string expectError3 = "Variable 'randy' has an invalid attribute 'son'.";
libcellml::Parser p;
p.parseModel(input1);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
p.clearErrors();
p.parseModel(input2);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectError2, p.getError(0)->getDescription());
EXPECT_EQ(expectError3, p.getError(1)->getDescription());
}
TEST(Parser, emptyConnections) {
const std::string ex =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model_name\">"
"<connection/>"
"</model>";
const std::string expectedError1 = "Connection in model 'model_name' does not have a valid component_1 in a connection element.";
const std::string expectedError2 = "Connection in model 'model_name' does not have a valid component_2 in a connection element.";
const std::string expectedError3 = "Connection in model 'model_name' must contain one or more 'map_variables' elements.";
libcellml::Parser p;
p.parseModel(ex);
EXPECT_EQ(3, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
}
TEST(Parser, connectionErrorNoComponent2) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelA\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_1=\"component1\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model 'modelA' does not have a valid component_2 in a connection element.";
const std::string expectedError2 = "Connection in model 'modelA' specifies 'component1' as component_1 but it does not exist in the model.";
const std::string expectedError3 = "Connection in model 'modelA' specifies 'variable1' as variable_1 but the corresponding component_1 is invalid.";
const std::string expectedError4 = "Connection in model 'modelA' specifies 'variable2' as variable_2 but the corresponding component_2 is invalid.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(4, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
EXPECT_EQ(expectedError4, p.getError(3)->getDescription());
}
TEST(Parser, connectionErrorNoComponent2InModel) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_1=\"component1\" component_2=\"component2\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model 'modelName' specifies 'component2' as component_2 but it does not exist in the model.";
const std::string expectedError2 = "Connection in model 'modelName' specifies 'variable2' as variable_2 but the corresponding component_2 is invalid.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, connectionErrorNoComponent1) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_2=\"componentA\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model 'modelName' does not have a valid component_1 in a connection element.";
const std::string expectedError2 = "Connection in model 'modelName' specifies 'variable1' as variable_1 but the corresponding component_1 is invalid.";
const std::string expectedError3 = "Variable 'variable2' is specified as variable_2 in a connection but it does not exist in component_2 component 'componentA' of model 'modelName'.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(3, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
}
TEST(Parser, connectionErrorNoMapComponents) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"modelName\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection name=\"invalid\">"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\" variable_3=\"variable3\">"
"<map_units/>"
"</map_variables>"
"</connection>"
"</model>";
std::vector<std::string> expectedErrors = {
"Connection in model 'modelName' has an invalid connection attribute 'name'.",
"Connection in model 'modelName' does not have a valid component_1 in a connection element.",
"Connection in model 'modelName' does not have a valid component_2 in a connection element.",
"Connection in model 'modelName' has an invalid child element 'map_units' of element 'map_variables'.",
"Connection in model 'modelName' has an invalid map_variables attribute 'variable_3'.",
"Connection in model 'modelName' specifies 'variable1' as variable_1 but the corresponding component_1 is invalid.",
"Connection in model 'modelName' specifies 'variable2' as variable_2 but the corresponding component_2 is invalid."
};
libcellml::Parser parser;
parser.parseModel(in);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
TEST(Parser, connectionErrorNoMapVariables) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"componentA\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection component_2=\"componentA\" component_1=\"componentA\" component_3=\"componentA\"/>"
"<connection component_2=\"componentA\" component_1=\"componentA\"/>"
"</model>";
const std::string expectedError1 = "Connection in model '' has an invalid connection attribute 'component_3'.";
const std::string expectedError2 = "Connection in model '' must contain one or more 'map_variables' elements.";
const std::string expectedError3 = "Connection in model '' must contain one or more 'map_variables' elements.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(3, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
EXPECT_EQ(expectedError3, p.getError(2)->getDescription());
}
TEST(Parser, importedComponent2Connection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
"<component component_ref=\"component_in_that_model\" name=\"component_in_this_model\"/>"
"</import>"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<connection component_2=\"component_in_this_model\" component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_import\" variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
// Parse
libcellml::Parser parser;
parser.parseModel(e);
EXPECT_EQ(0, parser.errorCount());
}
TEST(Parser, validConnectionMapVariablesFirst) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"robert\">"
"<variable name=\"bob\"/>"
"</component>"
"<component name=\"james\">"
"<variable name=\"jimbo\"/>"
"</component>"
"<connection component_1=\"robert\" component_2=\"james\">"
"<map_variables variable_2=\"jimbo\" variable_1=\"bob\"/>"
"</connection>"
"</model>";
libcellml::Parser parser;
parser.parseModel(e);
EXPECT_EQ(0, parser.errorCount());
}
TEST(Parser, component2ConnectionVariableMissing) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_2=\"component_dave\" component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_angus\" variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
const std::string expectedError = "Variable 'variable_angus' is specified as variable_2 in a connection but it does not exist in component_2 component 'component_dave' of model ''.";
// Parse
libcellml::Parser p;
p.parseModel(e);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError, p.getError(0)->getDescription());
}
TEST(Parser, component2InConnectionMissing) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_angus\" variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"</model>";
const std::string expectedError1 = "Connection in model '' does not have a valid component_2 in a connection element.";
const std::string expectedError2 = "Connection in model '' specifies 'variable_angus' as variable_2 but the corresponding component_2 is invalid.";
// Parse
libcellml::Parser p;
libcellml::ModelPtr m = p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(e, a);
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, connectionVariable2Missing) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_2=\"component_dave\" component_1=\"component_bob\">"
"<map_variables variable_1=\"variable_bob\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model '' does not have a valid variable_2 in a map_variables element.";
// Parse
libcellml::Parser p;
p.parseModel(e);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, connectionVariable1Missing) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component_bob\">"
"<variable name=\"variable_bob\"/>"
"</component>"
"<component name=\"component_dave\">"
"<variable name=\"variable_dave\"/>"
"</component>"
"<connection component_2=\"component_dave\" component_1=\"component_bob\">"
"<map_variables variable_2=\"variable_dave\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model '' does not have a valid variable_1 in a map_variables element.";
// Parse
libcellml::Parser p;
p.parseModel(e);
EXPECT_EQ(1, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
}
TEST(Parser, connectionErrorNoMapVariablesType) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<component name=\"component2\">"
"<variable name=\"variable2\"/>"
"</component>"
"<connection component_1=\"component1\" component_2=\"component2\">"
"<map_variabels variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
const std::string expectedError1 = "Connection in model '' has an invalid child element 'map_variabels'.";
const std::string expectedError2 = "Connection in model '' does not have a map_variables element.";
libcellml::Parser p;
p.parseModel(in);
EXPECT_EQ(2, p.errorCount());
EXPECT_EQ(expectedError1, p.getError(0)->getDescription());
EXPECT_EQ(expectedError2, p.getError(1)->getDescription());
}
TEST(Parser, invalidImportsAndGetError) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" sauce=\"hollandaise\">"
"<units units_ref=\"a_units_in_that_model\" name=\"units_in_this_model\"/>"
"<component component_ref=\"a_component_in_that_model\" name=\"component_in_this_model\"/>"
"<invalid_nonsense/>"
"<units units_ruff=\"dog\" name=\"fido\"/>"
"<component component_meow=\"cat\" name=\"frank\"/>"
"</import>"
"</model>";
const std::string expectError1 = "Import from 'some-other-model.xml' has an invalid attribute 'sauce'.";
const std::string expectError2 = "Import from 'some-other-model.xml' has an invalid child element 'invalid_nonsense'.";
const std::string expectError3 = "Import of units 'fido' from 'some-other-model.xml' has an invalid attribute 'units_ruff'.";
const std::string expectError4 = "Import of component 'frank' from 'some-other-model.xml' has an invalid attribute 'component_meow'.";
const std::string output =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
"<component component_ref=\"a_component_in_that_model\" name=\"component_in_this_model\"/>"
"</import>"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
"<units units_ref=\"a_units_in_that_model\" name=\"units_in_this_model\"/>"
"</import>"
"</model>";
libcellml::Parser p;
libcellml::ModelPtr m = p.parseModel(input);
EXPECT_EQ(4, p.errorCount());
EXPECT_EQ(expectError1, p.getError(0)->getDescription());
EXPECT_EQ(expectError2, p.getError(1)->getDescription());
EXPECT_EQ(expectError3, p.getError(2)->getDescription());
EXPECT_EQ(expectError4, p.getError(3)->getDescription());
libcellml::Printer printer;
const std::string a = printer.printModel(m);
EXPECT_EQ(output, a);
libcellml::ImportSourcePtr import = m->getUnits("units_in_this_model")->getImportSource();
// Get import from error and check.
EXPECT_EQ(import, p.getError(0)->getImportSource());
// Get const import from error and check.
const libcellml::ErrorPtr err = static_cast<const libcellml::Parser>(p).getError(0);
libcellml::Error *rawErr = err.get();
const libcellml::ImportSourcePtr importFromError = static_cast<const libcellml::Error*>(rawErr)->getImportSource();
EXPECT_EQ(import, importFromError);
}
TEST(Parser, invalidModelWithAllKindsOfErrors) {
// Check for all kinds of errors.
std::vector<bool> foundKind(9, false);
// Trigger CellML entity errors
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"starwars\" episode=\"four\">"
"<import princess=\"leia\"/>"
"<units jedi=\"luke\"/>"
"<component ship=\"falcon\">"
"<variable pilot=\"han\"/>"
"</component>"
"<connection wookie=\"chewie\"/>"
"<encapsulation yoda=\"green\"/>"
"</model>";
std::vector<std::string> expectedErrors = {
"Model 'starwars' has an invalid attribute 'episode'.",
"Import from '' has an invalid attribute 'princess'.",
"Units '' has an invalid attribute 'jedi'.",
"Component '' has an invalid attribute 'ship'.",
"Variable '' has an invalid attribute 'pilot'.",
"Connection in model 'starwars' has an invalid connection attribute 'wookie'.",
"Connection in model 'starwars' does not have a valid component_1 in a connection element.",
"Connection in model 'starwars' does not have a valid component_2 in a connection element.",
"Connection in model 'starwars' must contain one or more 'map_variables' elements.",
"Encapsulation in model 'starwars' has an invalid attribute 'yoda'.",
"Encapsulation in model 'starwars' does not contain any child elements."
};
// Parse and check for CellML errors.
libcellml::Parser parser;
parser.parseModel(input);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
switch (parser.getError(i)->getKind()) {
case (libcellml::Error::Kind::COMPONENT): {
foundKind.at(0) = true;
break;
}
case (libcellml::Error::Kind::CONNECTION): {
foundKind.at(1) = true;
break;
}
case (libcellml::Error::Kind::ENCAPSULATION): {
foundKind.at(2) = true;
break;
}
case (libcellml::Error::Kind::IMPORT): {
foundKind.at(3) = true;
break;
}
case (libcellml::Error::Kind::MODEL): {
foundKind.at(4) = true;
break;
}
case (libcellml::Error::Kind::UNITS): {
foundKind.at(5) = true;
break;
}
case (libcellml::Error::Kind::VARIABLE): {
foundKind.at(6) = true;
break;
}
default:{
}
}
}
// Trigger undefined error
libcellml::Parser parser2;
// Add an undefined error
libcellml::ErrorPtr undefinedError = std::make_shared<libcellml::Error>();
parser2.addError(undefinedError);
EXPECT_EQ(1, parser2.errorCount());
if (parser2.getError(0)->isKind(libcellml::Error::Kind::UNDEFINED)) {
foundKind.at(7) = true;
}
// Trigger an XML error
const std::string input3 = "jarjarbinks";
std::vector<std::string> expectedErrors3 = {
"Start tag expected, '<' not found.",
"Could not get a valid XML root node from the provided input."
};
libcellml::Parser parser3;
parser3.parseModel(input3);
EXPECT_EQ(expectedErrors3.size(), parser3.errorCount());
for (size_t i = 0; i < parser3.errorCount(); ++i) {
EXPECT_EQ(expectedErrors3.at(i), parser3.getError(i)->getDescription());
if (parser3.getError(i)->isKind(libcellml::Error::Kind::XML)) {
foundKind.at(8) = true;
}
}
// Check that we've found all the possible error types
bool foundAllKinds = false;
if (std::all_of(foundKind.begin(), foundKind.end(), [](bool i) {return i;})) {
foundAllKinds = true;
}
EXPECT_TRUE(foundAllKinds);
}
TEST(Parser, invalidModelWithTextInAllElements) {
const std::string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"starwars\">\n"
"episode7\n"
"<import xlink:href=\"sith.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">kylo</import>\n"
"<units name=\"robot\">"
"bb-8"
"<unit units=\"ball\">rolls</unit>"
"</units>\n"
"<component name=\"ship\">falcon\n"
" <variable name=\"jedi\">rey</variable>\n"
"</component>\n"
"<connection>"
"finn"
"<map_variables>"
"trooper"
"</map_variables>"
"</connection>\n"
"<encapsulation>"
"awakens"
"<component_ref component=\"ship\">"
"force"
"</component_ref>"
"</encapsulation>\n"
"</model>";
const std::vector<std::string> expectedErrors = {
"Model 'starwars' has an invalid non-whitespace child text element '\nepisode7\n'.",
"Import from 'sith.xml' has an invalid non-whitespace child text element 'kylo'.",
"Units 'robot' has an invalid non-whitespace child text element 'bb-8'.",
"Unit referencing 'ball' in units 'robot' has an invalid non-whitespace child text element 'rolls'.",
"Component 'ship' has an invalid non-whitespace child text element 'falcon\n '.",
"Variable 'jedi' has an invalid non-whitespace child text element 'rey'.",
"Connection in model 'starwars' does not have a valid component_1 in a connection element.",
"Connection in model 'starwars' does not have a valid component_2 in a connection element.",
"Connection in model 'starwars' has an invalid non-whitespace child text element 'finn'.",
"Connection in model 'starwars' has an invalid non-whitespace child text element 'trooper'.",
"Connection in model 'starwars' does not have a valid variable_1 in a map_variables element.",
"Connection in model 'starwars' does not have a valid variable_2 in a map_variables element.",
"Connection in model 'starwars' specifies '' as variable_1 but the corresponding component_1 is invalid.",
"Connection in model 'starwars' specifies '' as variable_2 but the corresponding component_2 is invalid.",
"Encapsulation in model 'starwars' has an invalid non-whitespace child text element 'awakens'.",
"Encapsulation in model 'starwars' specifies an invalid parent component_ref that also does not have any children.",
"Encapsulation in model 'starwars' has an invalid non-whitespace child text element 'force'."
};
// Parse and check for CellML errors.
libcellml::Parser parser;
parser.parseModel(input);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
TEST(Parser, parseIds) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" id=\"mid\">"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" id=\"i1id\">"
"<component component_ref=\"a_component_in_that_model\" name=\"component1\" id=\"c1id\"/>"
"</import>"
"<import xlink:href=\"some-other-model.xml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" id=\"i2id\">"
"<units units_ref=\"a_units_in_that_model\" name=\"units1\" id=\"u1id\"/>"
"</import>"
"<units name=\"units2\" id=\"u2id\"/>"
"<units name=\"units3\" id=\"u3id\"/>"
"<component name=\"component2\" id=\"c2id\">"
"<variable name=\"variable1\" id=\"vid\"/>"
"</component>"
"</model>";
libcellml::Parser p;
libcellml::ModelPtr model = p.parseModel(in);
EXPECT_EQ(0, p.errorCount());
EXPECT_EQ("mid", model->getId());
EXPECT_EQ("c1id", model->getComponent("component1")->getId());
EXPECT_EQ("i1id", model->getComponent("component1")->getImportSource()->getId());
EXPECT_EQ("u1id", model->getUnits("units1")->getId());
EXPECT_EQ("i2id", model->getUnits("units1")->getImportSource()->getId());
EXPECT_EQ("u2id", model->getUnits("units2")->getId());
EXPECT_EQ("c2id", model->getComponent("component2")->getId());
EXPECT_EQ("u3id", model->getUnits("units3")->getId());
EXPECT_EQ("vid", model->getComponent("component2")->getVariable("variable1")->getId());
}
TEST(Parser, parseResets) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" id=\"mid\">"
"<component name=\"component2\" id=\"c2id\">"
"<variable name=\"variable1\" id=\"vid\"/>"
"<reset order=\"1\" id=\"rid\">"
"<when order=\"5\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"<when order=\"3\" id=\"wid\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"</reset>"
"</component>"
"</model>";
libcellml::Parser p;
libcellml::ModelPtr model = p.parseModel(in);
libcellml::ComponentPtr c = model->getComponent(0);
EXPECT_EQ(1, c->resetCount());
libcellml::ResetPtr r = c->getReset(0);
EXPECT_EQ(1, r->getOrder());
EXPECT_EQ(2, r->whenCount());
libcellml::WhenPtr w = r->getWhen(1);
EXPECT_EQ(3, w->getOrder());
}
TEST(Parser, parseResetsWithNumerousErrors) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" id=\"mid\">"
"<component name=\"component2\" id=\"c2id\">"
"<variable name=\"variable1\" id=\"vid\"/>"
"<variable name=\"V_k\" id=\"vid\"/>"
"<reset order=\"1.3\" id=\"rid\">"
"<when order=\"-0\" change=\"$4.50\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"extra mathml node"
"</math>"
"</when>"
"<when order=\"3\" id=\"wid\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"<when order=\"3\" id=\"wid\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"</when>"
"</reset>"
"<reset variable=\"I_na\" order=\"2\" id=\"rid\">"
"<when order=\"5.9\" goods=\"socks\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"</when>"
"</reset>"
"<reset variable=\"I_na\" order=\"2\" id=\"rid\">"
"<when />"
"</reset>"
"<reset id=\"r3id\">"
"<when order=\"\"/>"
"<about>"
"Some description of importance."
"</about>"
"</reset>"
"<reset variable=\"V_k\" order=\"-\" start=\"now\"/>"
"<reset variable=\"variable1\" order=\"0\">"
"non empty whitespace."
"<when order=\"1\">"
"illegal content."
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some value in mathml"
"</math>"
"<variable/>"
"</when>"
"</reset>"
"</component>"
"</model>";
const std::vector<std::string> expectedErrors = {
"Reset in component 'component2' referencing variable '' has a non-integer order value '1.3'.",
"Reset in component 'component2' does not reference a variable in the component.",
"Reset in component 'component2' referencing variable '' does not have an order defined.",
"When in reset referencing variable '' with order '' has an invalid attribute 'change'.",
"When in reset referencing variable '' with order '' contains more than two MathML child elements.",
"Reset referencing variable 'I_na' is not a valid reference for a variable in component 'component2'.",
"Reset in component 'component2' does not reference a variable in the component.",
"When in reset referencing variable '' with order '2' has an invalid attribute 'goods'.",
"When in reset referencing variable '' with order '2' does not have an order defined.",
"When in reset referencing variable '' with order '2' contains only one MathML child element.",
"Reset referencing variable 'I_na' is not a valid reference for a variable in component 'component2'.",
"Reset in component 'component2' does not reference a variable in the component.",
"When in reset referencing variable '' with order '2' does not have an order defined.",
"When in reset referencing variable '' with order '2' contains zero MathML child elements.",
"Reset in component 'component2' does not reference a variable in the component.",
"Reset in component 'component2' referencing variable '' does not have an order defined.",
"When in reset referencing variable '' with order '' does not have an order defined.",
"When in reset referencing variable '' with order '' contains zero MathML child elements.",
"Reset in component 'component2' referencing variable '' has an invalid child element 'about'.",
"Reset in component 'component2' referencing variable 'V_k' has a non-integer order value '-'.",
"Reset in component 'component2' has an invalid attribute 'start'.",
"Reset in component 'component2' referencing variable 'V_k' does not have an order defined.",
"Reset in component 'component2' referencing variable 'variable1' has an invalid non-whitespace child text element 'non empty whitespace.'.",
"When in reset referencing variable 'variable1' with order '0' has an invalid non-whitespace child text element 'illegal content.'.",
"When in reset referencing variable 'variable1' with order '0' has an invalid child element 'variable'.",
};
libcellml::Parser parser;
parser.parseModel(in);
EXPECT_EQ(expectedErrors.size(), parser.errorCount());
for (size_t i = 0; i < parser.errorCount(); ++i) {
EXPECT_EQ(expectedErrors.at(i), parser.getError(i)->getDescription());
}
}
TEST(Parser, parseResetsCheckResetObjectCheckWhenObject) {
const std::string in =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/2.0#\" id=\"mid\">"
"<component name=\"component2\" id=\"c2id\">"
"<variable name=\"variable1\" id=\"vid\"/>"
"<variable name=\"V_k\" id=\"vid\"/>"
"<reset variable=\"V_k\" order=\"a\" id=\"rid\">"
"<when order=\"5.9\" goods=\"socks\">"
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\">"
"some condition in mathml"
"</math>"
"</when>"
"</reset>"
"</component>"
"</model>";
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(in);
libcellml::ResetPtr resetExpected = model->getComponent(0)->getReset(0);
libcellml::WhenPtr whenExpected = resetExpected->getWhen(0);
EXPECT_EQ(5, parser.errorCount());
EXPECT_EQ(resetExpected, parser.getError(1)->getReset());
EXPECT_EQ(whenExpected, parser.getError(2)->getWhen());
}
|
#include <stddef.h>
#include "MA_MIPSIV.h"
#include "MIPS.h"
#include "CodeGen.h"
#include "MemoryUtils.h"
#include "COP_SCU.h"
#include "offsetof_def.h"
#include "Integer64.h"
#include "placeholder_def.h"
using namespace std::tr1;
uint32 g_LWMaskRight[4] =
{
0x00FFFFFF,
0x0000FFFF,
0x000000FF,
0x00000000,
};
uint32 g_LWMaskLeft[4] =
{
0xFFFFFF00,
0xFFFF0000,
0xFF000000,
0x00000000,
};
uint64 g_LDMaskRight[8] =
{
0x00FFFFFFFFFFFFFFULL,
0x0000FFFFFFFFFFFFULL,
0x000000FFFFFFFFFFULL,
0x00000000FFFFFFFFULL,
0x0000000000FFFFFFULL,
0x000000000000FFFFULL,
0x00000000000000FFULL,
0x0000000000000000ULL,
};
uint64 g_LDMaskLeft[8] =
{
0xFFFFFFFFFFFFFF00ULL,
0xFFFFFFFFFFFF0000ULL,
0xFFFFFFFFFF000000ULL,
0xFFFFFFFF00000000ULL,
0xFFFFFF0000000000ULL,
0xFFFF000000000000ULL,
0xFF00000000000000ULL,
0x0000000000000000ULL,
};
void LWL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory <<= accessType * 8;
context->m_State.nGPR[rt].nV0 &= g_LWMaskRight[byteOffset];
context->m_State.nGPR[rt].nV0 |= memory;
context->m_State.nGPR[rt].nV1 = context->m_State.nGPR[rt].nV0 & 0x80000000 ? 0xFFFFFFFF : 0x00000000;
}
void LWR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory >>= byteOffset * 8;
context->m_State.nGPR[rt].nV0 &= g_LWMaskLeft[accessType];
context->m_State.nGPR[rt].nV0 |= memory;
context->m_State.nGPR[rt].nV1 = context->m_State.nGPR[rt].nV0 & 0x80000000 ? 0xFFFFFFFF : 0x00000000;
}
void LDL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q <<= accessType * 8;
context->m_State.nGPR[rt].nD0 &= g_LDMaskRight[byteOffset];
context->m_State.nGPR[rt].nD0 |= memory.q;
}
void LDR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q >>= byteOffset * 8;
context->m_State.nGPR[rt].nD0 &= g_LDMaskLeft[accessType];
context->m_State.nGPR[rt].nD0 |= memory.q;
}
void SWL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 reg = context->m_State.nGPR[rt].nV0;
reg >>= accessType * 8;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory &= g_LWMaskLeft[byteOffset];
memory |= reg;
CMemoryUtils::SetWordProxy(context, memory, alignedAddress);
}
void SWR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 reg = context->m_State.nGPR[rt].nV0;
reg <<= byteOffset * 8;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory &= g_LWMaskRight[accessType];
memory |= reg;
CMemoryUtils::SetWordProxy(context, memory, alignedAddress);
}
void SDL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
uint64 reg = context->m_State.nGPR[rt].nD0;
reg >>= accessType * 8;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q &= g_LDMaskLeft[byteOffset];
memory.q |= reg;
CMemoryUtils::SetWordProxy(context, memory.d0, alignedAddress + 0);
CMemoryUtils::SetWordProxy(context, memory.d1, alignedAddress + 4);
}
void SDR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
uint64 reg = context->m_State.nGPR[rt].nD0;
reg <<= byteOffset * 8;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q &= g_LDMaskRight[accessType];
memory.q |= reg;
CMemoryUtils::SetWordProxy(context, memory.d0, alignedAddress + 0);
CMemoryUtils::SetWordProxy(context, memory.d1, alignedAddress + 4);
}
CMA_MIPSIV::CMA_MIPSIV(MIPS_REGSIZE nRegSize) :
CMIPSArchitecture(nRegSize)
{
SetupInstructionTables();
SetupReflectionTables();
}
CMA_MIPSIV::~CMA_MIPSIV()
{
}
void CMA_MIPSIV::SetupInstructionTables()
{
for(unsigned int i = 0; i < MAX_GENERAL_OPS; i++)
{
m_pOpGeneral[i] = bind(m_cOpGeneral[i], this);
}
for(unsigned int i = 0; i < MAX_SPECIAL_OPS; i++)
{
m_pOpSpecial[i] = bind(m_cOpSpecial[i], this);
}
for(unsigned int i = 0; i < MAX_SPECIAL2_OPS; i++)
{
m_pOpSpecial2[i] = bind(&CMA_MIPSIV::Illegal, this);
}
for(unsigned int i = 0; i < MAX_REGIMM_OPS; i++)
{
m_pOpRegImm[i] = bind(m_cOpRegImm[i], this);
}
}
void CMA_MIPSIV::CompileInstruction(uint32 nAddress, CCodeGen* codeGen, CMIPS* pCtx)
{
SetupQuickVariables(nAddress, codeGen, pCtx);
m_nRS = (uint8)((m_nOpcode >> 21) & 0x1F);
m_nRT = (uint8)((m_nOpcode >> 16) & 0x1F);
m_nRD = (uint8)((m_nOpcode >> 11) & 0x1F);
m_nSA = (uint8)((m_nOpcode >> 6) & 0x1F);
m_nImmediate = (uint16)(m_nOpcode & 0xFFFF);
if(m_nOpcode)
{
m_pOpGeneral[(m_nOpcode >> 26)]();
}
}
void CMA_MIPSIV::SPECIAL()
{
m_pOpSpecial[m_nImmediate & 0x3F]();
}
void CMA_MIPSIV::SPECIAL2()
{
m_pOpSpecial2[m_nImmediate & 0x3F]();
}
void CMA_MIPSIV::REGIMM()
{
m_pOpRegImm[m_nRT]();
}
//////////////////////////////////////////////////
//General Opcodes
//////////////////////////////////////////////////
//02
void CMA_MIPSIV::J()
{
m_codeGen->PushCst((m_nAddress & 0xF0000000) | ((m_nOpcode & 0x03FFFFFF) << 2));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
}
//03
void CMA_MIPSIV::JAL()
{
//64-bit addresses?
//Save the address in RA
m_codeGen->PushCst(m_nAddress + 8);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[31].nV[0]));
//Update jump address
m_codeGen->PushCst((m_nAddress & 0xF0000000) | ((m_nOpcode & 0x03FFFFFF) << 2));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
}
//04
void CMA_MIPSIV::BEQ()
{
Template_BranchEq(true, false);
}
//05
void CMA_MIPSIV::BNE()
{
Template_BranchEq(false, false);
}
//06
void CMA_MIPSIV::BLEZ()
{
//Less/Equal & Not Likely
Template_BranchLez(true, false);
}
//07
void CMA_MIPSIV::BGTZ()
{
//Not Less/Equal & Not Likely
Template_BranchLez(false, false);
}
//08
void CMA_MIPSIV::ADDI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(static_cast<int16>(m_nImmediate));
m_codeGen->Add();
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
//09
void CMA_MIPSIV::ADDIU()
{
if(m_nRT == 0 && m_nRS == 0)
{
//Hack: PS2 IOP uses ADDIU R0, R0, $x for dynamic linking
m_codeGen->PushCst(m_nAddress);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[CCOP_SCU::EPC]));
m_codeGen->PushCst(1);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}
else
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(static_cast<int16>(m_nImmediate));
m_codeGen->Add();
if(m_regSize == MIPS_REGSIZE_64)
{
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
}
//0A
void CMA_MIPSIV::SLTI()
{
Template_SetLessThanImm(true);
}
//0B
void CMA_MIPSIV::SLTIU()
{
Template_SetLessThanImm(false);
}
//0C
void CMA_MIPSIV::ANDI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(m_nImmediate);
m_codeGen->And();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushCst(0);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
//0D
void CMA_MIPSIV::ORI()
{
//Lower 32-bits
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(m_nImmediate);
m_codeGen->Or();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
//Higher 32-bits (only if registers are different)
if(m_nRS != m_nRT)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
}
//0E
void CMA_MIPSIV::XORI()
{
//Lower 32-bits
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(m_nImmediate);
m_codeGen->Xor();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
//Higher 32-bits
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
//0F
void CMA_MIPSIV::LUI()
{
m_codeGen->PushCst(m_nImmediate << 16);
if(m_regSize == MIPS_REGSIZE_64)
{
m_codeGen->PushCst((m_nImmediate & 0x8000) ? 0xFFFFFFFF : 0x00000000);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
//10
void CMA_MIPSIV::COP0()
{
if(m_pCtx->m_pCOP[0] != NULL)
{
m_pCtx->m_pCOP[0]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//11
void CMA_MIPSIV::COP1()
{
if(m_pCtx->m_pCOP[1] != NULL)
{
m_pCtx->m_pCOP[1]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//12
void CMA_MIPSIV::COP2()
{
if(m_pCtx->m_pCOP[2] != NULL)
{
m_pCtx->m_pCOP[2]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//14
void CMA_MIPSIV::BEQL()
{
Template_BranchEq(true, true);
}
//15
void CMA_MIPSIV::BNEL()
{
Template_BranchEq(false, true);
}
//16
void CMA_MIPSIV::BLEZL()
{
//Less/Equal & Likely
Template_BranchLez(true, true);
}
//17
void CMA_MIPSIV::BGTZL()
{
//Not Less/Equal & Likely
Template_BranchLez(false, true);
}
//19
void CMA_MIPSIV::DADDIU()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushCst(static_cast<int16>(m_nImmediate));
m_codeGen->PushCst((m_nImmediate & 0x8000) == 0 ? 0x00000000 : 0xFFFFFFFF);
m_codeGen->Add64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
//1A
void CMA_MIPSIV::LDL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LDL_Proxy), 3, false);
}
//1B
void CMA_MIPSIV::LDR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LDR_Proxy), 3, false);
}
//20
void CMA_MIPSIV::LB()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetByteProxy), 2, true);
m_codeGen->SeX8();
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PullTop();
}
//21
void CMA_MIPSIV::LH()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetHalfProxy), 2, true);
m_codeGen->SeX16();
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PullTop();
}
//22
void CMA_MIPSIV::LWL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LWL_Proxy), 3, false);
}
//23
void CMA_MIPSIV::LW()
{
Template_LoadUnsigned32(reinterpret_cast<void*>(&CMemoryUtils::GetWordProxy));
}
//24
void CMA_MIPSIV::LBU()
{
Template_LoadUnsigned32(reinterpret_cast<void*>(&CMemoryUtils::GetByteProxy));
}
//25
void CMA_MIPSIV::LHU()
{
Template_LoadUnsigned32(reinterpret_cast<void*>(&CMemoryUtils::GetHalfProxy));
}
//26
void CMA_MIPSIV::LWR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LWR_Proxy), 3, false);
}
//27
void CMA_MIPSIV::LWU()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetWordProxy), 2, true);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushCst(0);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullTop();
}
//28
void CMA_MIPSIV::SB()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetByteProxy), 3, false);
m_codeGen->PullTop();
}
//29
void CMA_MIPSIV::SH()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetHalfProxy), 3, false);
m_codeGen->PullTop();
}
//2A
void CMA_MIPSIV::SWL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SWL_Proxy), 3, false);
}
//2B
void CMA_MIPSIV::SW()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetWordProxy), 3, false);
m_codeGen->PullTop();
}
//2C
void CMA_MIPSIV::SDL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SDL_Proxy), 3, false);
}
//2D
void CMA_MIPSIV::SDR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SDR_Proxy), 3, false);
}
//2E
void CMA_MIPSIV::SWR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SWR_Proxy), 3, false);
}
//2F
void CMA_MIPSIV::CACHE()
{
//No cache in our system. Nothing to do.
}
//31
void CMA_MIPSIV::LWC1()
{
if(m_pCtx->m_pCOP[1] != NULL)
{
m_pCtx->m_pCOP[1]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//36
void CMA_MIPSIV::LDC2()
{
if(m_pCtx->m_pCOP[2] != NULL)
{
m_pCtx->m_pCOP[2]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//37
void CMA_MIPSIV::LD()
{
ComputeMemAccessAddr();
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetWordProxy), 2, true);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
if(i != 1)
{
m_codeGen->PushCst(4);
m_codeGen->Add();
}
}
m_codeGen->PullTop();
}
//39
void CMA_MIPSIV::SWC1()
{
if(m_pCtx->m_pCOP[1] != NULL)
{
m_pCtx->m_pCOP[1]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//3E
void CMA_MIPSIV::SDC2()
{
if(m_pCtx->m_pCOP[2] != NULL)
{
m_pCtx->m_pCOP[2]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//3F
void CMA_MIPSIV::SD()
{
ComputeMemAccessAddr();
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetWordProxy), 3, false);
if(i != 1)
{
m_codeGen->PushCst(4);
m_codeGen->Add();
}
}
m_codeGen->PullTop();
}
//////////////////////////////////////////////////
//Special Opcodes
//////////////////////////////////////////////////
//00
void CMA_MIPSIV::SLL()
{
Template_ShiftCst32(bind(&CCodeGen::Shl, m_codeGen, PLACEHOLDER_1));
}
//02
void CMA_MIPSIV::SRL()
{
Template_ShiftCst32(bind(&CCodeGen::Srl, m_codeGen, PLACEHOLDER_1));
}
//03
void CMA_MIPSIV::SRA()
{
Template_ShiftCst32(bind(&CCodeGen::Sra, m_codeGen, PLACEHOLDER_1));
}
//04
void CMA_MIPSIV::SLLV()
{
Template_ShiftVar32(bind(&CCodeGen::Shl, m_codeGen));
}
//06
void CMA_MIPSIV::SRLV()
{
Template_ShiftVar32(bind(&CCodeGen::Srl, m_codeGen));
}
//07
void CMA_MIPSIV::SRAV()
{
Template_ShiftVar32(bind(&CCodeGen::Sra, m_codeGen));
}
//08
void CMA_MIPSIV::JR()
{
//TODO: 64-bits addresses
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
}
//09
void CMA_MIPSIV::JALR()
{
//TODO: 64-bits addresses
//Set the jump address
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
//Save address in register
m_codeGen->PushCst(m_nAddress + 8);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//0A
void CMA_MIPSIV::MOVZ()
{
Template_MovEqual(true);
}
//0B
void CMA_MIPSIV::MOVN()
{
Template_MovEqual(false);
}
//0C
void CMA_MIPSIV::SYSCALL()
{
//Save current EPC
m_codeGen->PushCst(m_nAddress);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[CCOP_SCU::EPC]));
m_codeGen->PushCst(1);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}
//0D
void CMA_MIPSIV::BREAK()
{
//NOP
}
//0F
void CMA_MIPSIV::SYNC()
{
//NOP
}
//10
void CMA_MIPSIV::MFHI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nHI[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nHI[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
}
//11
void CMA_MIPSIV::MTHI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHI[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHI[1]));
}
//12
void CMA_MIPSIV::MFLO()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nLO[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nLO[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
}
//13
void CMA_MIPSIV::MTLO()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nLO[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nLO[1]));
}
//14
void CMA_MIPSIV::DSLLV()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->Shl64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//16
void CMA_MIPSIV::DSRLV()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->Srl64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//18
void CMA_MIPSIV::MULT()
{
Template_Mult32(bind(&CCodeGen::MultS, m_codeGen), 0);
}
//19
void CMA_MIPSIV::MULTU()
{
Template_Mult32(bind(&CCodeGen::Mult, m_codeGen), 0);
}
//1A
void CMA_MIPSIV::DIV()
{
Template_Div32(bind(&CCodeGen::DivS, m_codeGen), 0);
}
//1B
void CMA_MIPSIV::DIVU()
{
Template_Div32(bind(&CCodeGen::Div, m_codeGen), 0);
}
//20
void CMA_MIPSIV::ADD()
{
Template_Add32(true);
}
//21
void CMA_MIPSIV::ADDU()
{
Template_Add32(false);
}
//22
void CMA_MIPSIV::SUB()
{
Template_Sub32(true);
}
//23
void CMA_MIPSIV::SUBU()
{
Template_Sub32(false);
}
//24
void CMA_MIPSIV::AND()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->And64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//25
void CMA_MIPSIV::OR()
{
//TODO: Use a 64-bits op
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[i]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->Or();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[i]));
}
}
//26
void CMA_MIPSIV::XOR()
{
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[i]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->Xor();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[i]));
}
}
//27
void CMA_MIPSIV::NOR()
{
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[i]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->Or();
m_codeGen->Not();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[i]));
}
}
//2A
void CMA_MIPSIV::SLT()
{
Template_SetLessThanReg(true);
}
//2B
void CMA_MIPSIV::SLTU()
{
Template_SetLessThanReg(false);
}
//2D
void CMA_MIPSIV::DADDU()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Add64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//2F
void CMA_MIPSIV::DSUBU()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Sub64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//38
void CMA_MIPSIV::DSLL()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Shl64(m_nSA);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3A
void CMA_MIPSIV::DSRL()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Srl64(m_nSA);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3B
void CMA_MIPSIV::DSRA()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Sra64(m_nSA);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3C
void CMA_MIPSIV::DSLL32()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Shl64(m_nSA + 0x20);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3E
void CMA_MIPSIV::DSRL32()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Srl64(m_nSA + 32);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3F
void CMA_MIPSIV::DSRA32()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Sra64(m_nSA + 32);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//////////////////////////////////////////////////
//Special2 Opcodes
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//RegImm Opcodes
//////////////////////////////////////////////////
//00
void CMA_MIPSIV::BLTZ()
{
//Not greater/equal & not likely
Template_BranchGez(false, false);
}
//01
void CMA_MIPSIV::BGEZ()
{
//Greater/equal & not likely
Template_BranchGez(true, false);
}
//02
void CMA_MIPSIV::BLTZL()
{
//Not greater/equal & likely
Template_BranchGez(false, true);
}
//03
void CMA_MIPSIV::BGEZL()
{
//Greater/equal & likely
Template_BranchGez(true, true);
}
//////////////////////////////////////////////////
//Opcode Tables
//////////////////////////////////////////////////
CMA_MIPSIV::InstructionFuncConstant CMA_MIPSIV::m_cOpGeneral[MAX_GENERAL_OPS] =
{
//0x00
&SPECIAL, ®IMM, &J, &JAL, &BEQ, &BNE, &BLEZ, &BGTZ,
//0x08
&ADDI, &ADDIU, &SLTI, &SLTIU, &ANDI, &ORI, &XORI, &LUI,
//0x10
&COP0, &COP1, &COP2, &Illegal, &BEQL, &BNEL, &BLEZL, &BGTZL,
//0x18
&Illegal, &DADDIU, &LDL, &LDR, &SPECIAL2, &Illegal, &Illegal, &Illegal,
//0x20
&LB, &LH, &LWL, &LW, &LBU, &LHU, &LWR, &LWU,
//0x28
&SB, &SH, &SWL, &SW, &SDL, &SDR, &SWR, &CACHE,
//0x30
&Illegal, &LWC1, &Illegal, &Illegal, &Illegal, &Illegal, &LDC2, &LD,
//0x38
&Illegal, &SWC1, &Illegal, &Illegal, &Illegal, &Illegal, &SDC2, &SD,
};
CMA_MIPSIV::InstructionFuncConstant CMA_MIPSIV::m_cOpSpecial[MAX_SPECIAL_OPS] =
{
//0x00
&SLL, &Illegal, &SRL, &SRA, &SLLV, &Illegal, &SRLV, &SRAV,
//0x08
&JR, &JALR, &MOVZ, &MOVN, &SYSCALL, &BREAK, &Illegal, &SYNC,
//0x10
&MFHI, &MTHI, &MFLO, &MTLO, &DSLLV, &Illegal, &DSRLV, &Illegal,
//0x18
&MULT, &MULTU, &DIV, &DIVU, &Illegal, &Illegal, &Illegal, &Illegal,
//0x20
&ADD, &ADDU, &SUB, &SUBU, &AND, &OR, &XOR, &NOR,
//0x28
&Illegal, &Illegal, &SLT, &SLTU, &Illegal, &DADDU, &Illegal, &DSUBU,
//0x30
&Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal,
//0x38
&DSLL, &Illegal, &DSRL, &DSRA, &DSLL32, &Illegal, &DSRL32, &DSRA32,
};
CMA_MIPSIV::InstructionFuncConstant CMA_MIPSIV::m_cOpRegImm[MAX_REGIMM_OPS] =
{
//0x00
&BLTZ, &BGEZ, &BLTZL, &BGEZL, &Illegal, &Illegal, &Illegal, &Illegal,
//0x08
&Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal,
//0x10
&Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal,
//0x18
&Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal, &Illegal,
};
- Small C++ conformance updates
- AND for MIPS32.
git-svn-id: 2ccb1f8d9e6dc8a19c79d6424fab741c5d5caced@494 b36208d7-6611-0410-8bec-b1987f11c4a2
#include <stddef.h>
#include "MA_MIPSIV.h"
#include "MIPS.h"
#include "CodeGen.h"
#include "MemoryUtils.h"
#include "COP_SCU.h"
#include "offsetof_def.h"
#include "Integer64.h"
#include "placeholder_def.h"
using namespace std::tr1;
uint32 g_LWMaskRight[4] =
{
0x00FFFFFF,
0x0000FFFF,
0x000000FF,
0x00000000,
};
uint32 g_LWMaskLeft[4] =
{
0xFFFFFF00,
0xFFFF0000,
0xFF000000,
0x00000000,
};
uint64 g_LDMaskRight[8] =
{
0x00FFFFFFFFFFFFFFULL,
0x0000FFFFFFFFFFFFULL,
0x000000FFFFFFFFFFULL,
0x00000000FFFFFFFFULL,
0x0000000000FFFFFFULL,
0x000000000000FFFFULL,
0x00000000000000FFULL,
0x0000000000000000ULL,
};
uint64 g_LDMaskLeft[8] =
{
0xFFFFFFFFFFFFFF00ULL,
0xFFFFFFFFFFFF0000ULL,
0xFFFFFFFFFF000000ULL,
0xFFFFFFFF00000000ULL,
0xFFFFFF0000000000ULL,
0xFFFF000000000000ULL,
0xFF00000000000000ULL,
0x0000000000000000ULL,
};
void LWL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory <<= accessType * 8;
context->m_State.nGPR[rt].nV0 &= g_LWMaskRight[byteOffset];
context->m_State.nGPR[rt].nV0 |= memory;
context->m_State.nGPR[rt].nV1 = context->m_State.nGPR[rt].nV0 & 0x80000000 ? 0xFFFFFFFF : 0x00000000;
}
void LWR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory >>= byteOffset * 8;
context->m_State.nGPR[rt].nV0 &= g_LWMaskLeft[accessType];
context->m_State.nGPR[rt].nV0 |= memory;
context->m_State.nGPR[rt].nV1 = context->m_State.nGPR[rt].nV0 & 0x80000000 ? 0xFFFFFFFF : 0x00000000;
}
void LDL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q <<= accessType * 8;
context->m_State.nGPR[rt].nD0 &= g_LDMaskRight[byteOffset];
context->m_State.nGPR[rt].nD0 |= memory.q;
}
void LDR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q >>= byteOffset * 8;
context->m_State.nGPR[rt].nD0 &= g_LDMaskLeft[accessType];
context->m_State.nGPR[rt].nD0 |= memory.q;
}
void SWL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 reg = context->m_State.nGPR[rt].nV0;
reg >>= accessType * 8;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory &= g_LWMaskLeft[byteOffset];
memory |= reg;
CMemoryUtils::SetWordProxy(context, memory, alignedAddress);
}
void SWR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x03;
uint32 byteOffset = address & 0x03;
uint32 accessType = 3 - byteOffset;
uint32 reg = context->m_State.nGPR[rt].nV0;
reg <<= byteOffset * 8;
uint32 memory = CMemoryUtils::GetWordProxy(context, alignedAddress);
memory &= g_LWMaskRight[accessType];
memory |= reg;
CMemoryUtils::SetWordProxy(context, memory, alignedAddress);
}
void SDL_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
uint64 reg = context->m_State.nGPR[rt].nD0;
reg >>= accessType * 8;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q &= g_LDMaskLeft[byteOffset];
memory.q |= reg;
CMemoryUtils::SetWordProxy(context, memory.d0, alignedAddress + 0);
CMemoryUtils::SetWordProxy(context, memory.d1, alignedAddress + 4);
}
void SDR_Proxy(uint32 address, uint32 rt, CMIPS* context)
{
uint32 alignedAddress = address & ~0x07;
uint32 byteOffset = address & 0x07;
uint32 accessType = 7 - byteOffset;
uint64 reg = context->m_State.nGPR[rt].nD0;
reg <<= byteOffset * 8;
INTEGER64 memory;
memory.d0 = CMemoryUtils::GetWordProxy(context, alignedAddress + 0);
memory.d1 = CMemoryUtils::GetWordProxy(context, alignedAddress + 4);
memory.q &= g_LDMaskRight[accessType];
memory.q |= reg;
CMemoryUtils::SetWordProxy(context, memory.d0, alignedAddress + 0);
CMemoryUtils::SetWordProxy(context, memory.d1, alignedAddress + 4);
}
CMA_MIPSIV::CMA_MIPSIV(MIPS_REGSIZE nRegSize) :
CMIPSArchitecture(nRegSize)
{
SetupInstructionTables();
SetupReflectionTables();
}
CMA_MIPSIV::~CMA_MIPSIV()
{
}
void CMA_MIPSIV::SetupInstructionTables()
{
for(unsigned int i = 0; i < MAX_GENERAL_OPS; i++)
{
m_pOpGeneral[i] = bind(m_cOpGeneral[i], this);
}
for(unsigned int i = 0; i < MAX_SPECIAL_OPS; i++)
{
m_pOpSpecial[i] = bind(m_cOpSpecial[i], this);
}
for(unsigned int i = 0; i < MAX_SPECIAL2_OPS; i++)
{
m_pOpSpecial2[i] = bind(&CMA_MIPSIV::Illegal, this);
}
for(unsigned int i = 0; i < MAX_REGIMM_OPS; i++)
{
m_pOpRegImm[i] = bind(m_cOpRegImm[i], this);
}
}
void CMA_MIPSIV::CompileInstruction(uint32 nAddress, CCodeGen* codeGen, CMIPS* pCtx)
{
SetupQuickVariables(nAddress, codeGen, pCtx);
m_nRS = (uint8)((m_nOpcode >> 21) & 0x1F);
m_nRT = (uint8)((m_nOpcode >> 16) & 0x1F);
m_nRD = (uint8)((m_nOpcode >> 11) & 0x1F);
m_nSA = (uint8)((m_nOpcode >> 6) & 0x1F);
m_nImmediate = (uint16)(m_nOpcode & 0xFFFF);
if(m_nOpcode)
{
m_pOpGeneral[(m_nOpcode >> 26)]();
}
}
void CMA_MIPSIV::SPECIAL()
{
m_pOpSpecial[m_nImmediate & 0x3F]();
}
void CMA_MIPSIV::SPECIAL2()
{
m_pOpSpecial2[m_nImmediate & 0x3F]();
}
void CMA_MIPSIV::REGIMM()
{
m_pOpRegImm[m_nRT]();
}
//////////////////////////////////////////////////
//General Opcodes
//////////////////////////////////////////////////
//02
void CMA_MIPSIV::J()
{
m_codeGen->PushCst((m_nAddress & 0xF0000000) | ((m_nOpcode & 0x03FFFFFF) << 2));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
}
//03
void CMA_MIPSIV::JAL()
{
//64-bit addresses?
//Save the address in RA
m_codeGen->PushCst(m_nAddress + 8);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[31].nV[0]));
//Update jump address
m_codeGen->PushCst((m_nAddress & 0xF0000000) | ((m_nOpcode & 0x03FFFFFF) << 2));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
}
//04
void CMA_MIPSIV::BEQ()
{
Template_BranchEq(true, false);
}
//05
void CMA_MIPSIV::BNE()
{
Template_BranchEq(false, false);
}
//06
void CMA_MIPSIV::BLEZ()
{
//Less/Equal & Not Likely
Template_BranchLez(true, false);
}
//07
void CMA_MIPSIV::BGTZ()
{
//Not Less/Equal & Not Likely
Template_BranchLez(false, false);
}
//08
void CMA_MIPSIV::ADDI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(static_cast<int16>(m_nImmediate));
m_codeGen->Add();
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
//09
void CMA_MIPSIV::ADDIU()
{
if(m_nRT == 0 && m_nRS == 0)
{
//Hack: PS2 IOP uses ADDIU R0, R0, $x for dynamic linking
m_codeGen->PushCst(m_nAddress);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[CCOP_SCU::EPC]));
m_codeGen->PushCst(1);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}
else
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(static_cast<int16>(m_nImmediate));
m_codeGen->Add();
if(m_regSize == MIPS_REGSIZE_64)
{
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
}
//0A
void CMA_MIPSIV::SLTI()
{
Template_SetLessThanImm(true);
}
//0B
void CMA_MIPSIV::SLTIU()
{
Template_SetLessThanImm(false);
}
//0C
void CMA_MIPSIV::ANDI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(m_nImmediate);
m_codeGen->And();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushCst(0);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
//0D
void CMA_MIPSIV::ORI()
{
//Lower 32-bits
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(m_nImmediate);
m_codeGen->Or();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
//Higher 32-bits (only if registers are different)
if(m_nRS != m_nRT)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
}
//0E
void CMA_MIPSIV::XORI()
{
//Lower 32-bits
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushCst(m_nImmediate);
m_codeGen->Xor();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
//Higher 32-bits
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
//0F
void CMA_MIPSIV::LUI()
{
m_codeGen->PushCst(m_nImmediate << 16);
if(m_regSize == MIPS_REGSIZE_64)
{
m_codeGen->PushCst((m_nImmediate & 0x8000) ? 0xFFFFFFFF : 0x00000000);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
}
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
//10
void CMA_MIPSIV::COP0()
{
if(m_pCtx->m_pCOP[0] != NULL)
{
m_pCtx->m_pCOP[0]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//11
void CMA_MIPSIV::COP1()
{
if(m_pCtx->m_pCOP[1] != NULL)
{
m_pCtx->m_pCOP[1]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//12
void CMA_MIPSIV::COP2()
{
if(m_pCtx->m_pCOP[2] != NULL)
{
m_pCtx->m_pCOP[2]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//14
void CMA_MIPSIV::BEQL()
{
Template_BranchEq(true, true);
}
//15
void CMA_MIPSIV::BNEL()
{
Template_BranchEq(false, true);
}
//16
void CMA_MIPSIV::BLEZL()
{
//Less/Equal & Likely
Template_BranchLez(true, true);
}
//17
void CMA_MIPSIV::BGTZL()
{
//Not Less/Equal & Likely
Template_BranchLez(false, true);
}
//19
void CMA_MIPSIV::DADDIU()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushCst(static_cast<int16>(m_nImmediate));
m_codeGen->PushCst((m_nImmediate & 0x8000) == 0 ? 0x00000000 : 0xFFFFFFFF);
m_codeGen->Add64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}
//1A
void CMA_MIPSIV::LDL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LDL_Proxy), 3, false);
}
//1B
void CMA_MIPSIV::LDR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LDR_Proxy), 3, false);
}
//20
void CMA_MIPSIV::LB()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetByteProxy), 2, true);
m_codeGen->SeX8();
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PullTop();
}
//21
void CMA_MIPSIV::LH()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetHalfProxy), 2, true);
m_codeGen->SeX16();
m_codeGen->SeX();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PullTop();
}
//22
void CMA_MIPSIV::LWL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LWL_Proxy), 3, false);
}
//23
void CMA_MIPSIV::LW()
{
Template_LoadUnsigned32(reinterpret_cast<void*>(&CMemoryUtils::GetWordProxy));
}
//24
void CMA_MIPSIV::LBU()
{
Template_LoadUnsigned32(reinterpret_cast<void*>(&CMemoryUtils::GetByteProxy));
}
//25
void CMA_MIPSIV::LHU()
{
Template_LoadUnsigned32(reinterpret_cast<void*>(&CMemoryUtils::GetHalfProxy));
}
//26
void CMA_MIPSIV::LWR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&LWR_Proxy), 3, false);
}
//27
void CMA_MIPSIV::LWU()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetWordProxy), 2, true);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushCst(0);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PullTop();
}
//28
void CMA_MIPSIV::SB()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetByteProxy), 3, false);
m_codeGen->PullTop();
}
//29
void CMA_MIPSIV::SH()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetHalfProxy), 3, false);
m_codeGen->PullTop();
}
//2A
void CMA_MIPSIV::SWL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SWL_Proxy), 3, false);
}
//2B
void CMA_MIPSIV::SW()
{
ComputeMemAccessAddr();
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetWordProxy), 3, false);
m_codeGen->PullTop();
}
//2C
void CMA_MIPSIV::SDL()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SDL_Proxy), 3, false);
}
//2D
void CMA_MIPSIV::SDR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SDR_Proxy), 3, false);
}
//2E
void CMA_MIPSIV::SWR()
{
ComputeMemAccessAddr();
m_codeGen->PushCst(m_nRT);
m_codeGen->PushRef(m_pCtx);
m_codeGen->Call(reinterpret_cast<void*>(&SWR_Proxy), 3, false);
}
//2F
void CMA_MIPSIV::CACHE()
{
//No cache in our system. Nothing to do.
}
//31
void CMA_MIPSIV::LWC1()
{
if(m_pCtx->m_pCOP[1] != NULL)
{
m_pCtx->m_pCOP[1]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//36
void CMA_MIPSIV::LDC2()
{
if(m_pCtx->m_pCOP[2] != NULL)
{
m_pCtx->m_pCOP[2]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//37
void CMA_MIPSIV::LD()
{
ComputeMemAccessAddr();
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::GetWordProxy), 2, true);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
if(i != 1)
{
m_codeGen->PushCst(4);
m_codeGen->Add();
}
}
m_codeGen->PullTop();
}
//39
void CMA_MIPSIV::SWC1()
{
if(m_pCtx->m_pCOP[1] != NULL)
{
m_pCtx->m_pCOP[1]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//3E
void CMA_MIPSIV::SDC2()
{
if(m_pCtx->m_pCOP[2] != NULL)
{
m_pCtx->m_pCOP[2]->CompileInstruction(m_nAddress, m_codeGen, m_pCtx);
}
else
{
Illegal();
}
}
//3F
void CMA_MIPSIV::SD()
{
ComputeMemAccessAddr();
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRef(m_pCtx);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&CMemoryUtils::SetWordProxy), 3, false);
if(i != 1)
{
m_codeGen->PushCst(4);
m_codeGen->Add();
}
}
m_codeGen->PullTop();
}
//////////////////////////////////////////////////
//Special Opcodes
//////////////////////////////////////////////////
//00
void CMA_MIPSIV::SLL()
{
Template_ShiftCst32(bind(&CCodeGen::Shl, m_codeGen, PLACEHOLDER_1));
}
//02
void CMA_MIPSIV::SRL()
{
Template_ShiftCst32(bind(&CCodeGen::Srl, m_codeGen, PLACEHOLDER_1));
}
//03
void CMA_MIPSIV::SRA()
{
Template_ShiftCst32(bind(&CCodeGen::Sra, m_codeGen, PLACEHOLDER_1));
}
//04
void CMA_MIPSIV::SLLV()
{
Template_ShiftVar32(bind(&CCodeGen::Shl, m_codeGen));
}
//06
void CMA_MIPSIV::SRLV()
{
Template_ShiftVar32(bind(&CCodeGen::Srl, m_codeGen));
}
//07
void CMA_MIPSIV::SRAV()
{
Template_ShiftVar32(bind(&CCodeGen::Sra, m_codeGen));
}
//08
void CMA_MIPSIV::JR()
{
//TODO: 64-bits addresses
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
}
//09
void CMA_MIPSIV::JALR()
{
//TODO: 64-bits addresses
//Set the jump address
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));
//Save address in register
m_codeGen->PushCst(m_nAddress + 8);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//0A
void CMA_MIPSIV::MOVZ()
{
Template_MovEqual(true);
}
//0B
void CMA_MIPSIV::MOVN()
{
Template_MovEqual(false);
}
//0C
void CMA_MIPSIV::SYSCALL()
{
//Save current EPC
m_codeGen->PushCst(m_nAddress);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[CCOP_SCU::EPC]));
m_codeGen->PushCst(1);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}
//0D
void CMA_MIPSIV::BREAK()
{
//NOP
}
//0F
void CMA_MIPSIV::SYNC()
{
//NOP
}
//10
void CMA_MIPSIV::MFHI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nHI[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nHI[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
}
//11
void CMA_MIPSIV::MTHI()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHI[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHI[1]));
}
//12
void CMA_MIPSIV::MFLO()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nLO[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nLO[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
}
//13
void CMA_MIPSIV::MTLO()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nLO[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nLO[1]));
}
//14
void CMA_MIPSIV::DSLLV()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->Shl64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//16
void CMA_MIPSIV::DSRLV()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->Srl64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//18
void CMA_MIPSIV::MULT()
{
Template_Mult32(bind(&CCodeGen::MultS, m_codeGen), 0);
}
//19
void CMA_MIPSIV::MULTU()
{
Template_Mult32(bind(&CCodeGen::Mult, m_codeGen), 0);
}
//1A
void CMA_MIPSIV::DIV()
{
Template_Div32(bind(&CCodeGen::DivS, m_codeGen), 0);
}
//1B
void CMA_MIPSIV::DIVU()
{
Template_Div32(bind(&CCodeGen::Div, m_codeGen), 0);
}
//20
void CMA_MIPSIV::ADD()
{
Template_Add32(true);
}
//21
void CMA_MIPSIV::ADDU()
{
Template_Add32(false);
}
//22
void CMA_MIPSIV::SUB()
{
Template_Sub32(true);
}
//23
void CMA_MIPSIV::SUBU()
{
Template_Sub32(false);
}
//24
void CMA_MIPSIV::AND()
{
if(m_regSize == MIPS_REGSIZE_32)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->And();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
else
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->And64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
}
//25
void CMA_MIPSIV::OR()
{
//TODO: Use a 64-bits op
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[i]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->Or();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[i]));
}
}
//26
void CMA_MIPSIV::XOR()
{
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[i]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->Xor();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[i]));
}
}
//27
void CMA_MIPSIV::NOR()
{
for(unsigned int i = 0; i < 2; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[i]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[i]));
m_codeGen->Or();
m_codeGen->Not();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[i]));
}
}
//2A
void CMA_MIPSIV::SLT()
{
Template_SetLessThanReg(true);
}
//2B
void CMA_MIPSIV::SLTU()
{
Template_SetLessThanReg(false);
}
//2D
void CMA_MIPSIV::DADDU()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Add64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//2F
void CMA_MIPSIV::DSUBU()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRS].nV[1]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Sub64();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//38
void CMA_MIPSIV::DSLL()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Shl64(m_nSA);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3A
void CMA_MIPSIV::DSRL()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Srl64(m_nSA);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3B
void CMA_MIPSIV::DSRA()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Sra64(m_nSA);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3C
void CMA_MIPSIV::DSLL32()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Shl64(m_nSA + 0x20);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3E
void CMA_MIPSIV::DSRL32()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Srl64(m_nSA + 32);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//3F
void CMA_MIPSIV::DSRA32()
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
m_codeGen->Sra64(m_nSA + 32);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRD].nV[0]));
}
//////////////////////////////////////////////////
//Special2 Opcodes
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//RegImm Opcodes
//////////////////////////////////////////////////
//00
void CMA_MIPSIV::BLTZ()
{
//Not greater/equal & not likely
Template_BranchGez(false, false);
}
//01
void CMA_MIPSIV::BGEZ()
{
//Greater/equal & not likely
Template_BranchGez(true, false);
}
//02
void CMA_MIPSIV::BLTZL()
{
//Not greater/equal & likely
Template_BranchGez(false, true);
}
//03
void CMA_MIPSIV::BGEZL()
{
//Greater/equal & likely
Template_BranchGez(true, true);
}
//////////////////////////////////////////////////
//Opcode Tables
//////////////////////////////////////////////////
CMA_MIPSIV::InstructionFuncConstant CMA_MIPSIV::m_cOpGeneral[MAX_GENERAL_OPS] =
{
//0x00
&CMA_MIPSIV::SPECIAL, &CMA_MIPSIV::REGIMM, &CMA_MIPSIV::J, &CMA_MIPSIV::JAL, &CMA_MIPSIV::BEQ, &CMA_MIPSIV::BNE, &CMA_MIPSIV::BLEZ, &CMA_MIPSIV::BGTZ,
//0x08
&CMA_MIPSIV::ADDI, &CMA_MIPSIV::ADDIU, &CMA_MIPSIV::SLTI, &CMA_MIPSIV::SLTIU, &CMA_MIPSIV::ANDI, &CMA_MIPSIV::ORI, &CMA_MIPSIV::XORI, &CMA_MIPSIV::LUI,
//0x10
&CMA_MIPSIV::COP0, &CMA_MIPSIV::COP1, &CMA_MIPSIV::COP2, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::BEQL, &CMA_MIPSIV::BNEL, &CMA_MIPSIV::BLEZL, &CMA_MIPSIV::BGTZL,
//0x18
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::DADDIU, &CMA_MIPSIV::LDL, &CMA_MIPSIV::LDR, &CMA_MIPSIV::SPECIAL2, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal,
//0x20
&CMA_MIPSIV::LB, &CMA_MIPSIV::LH, &CMA_MIPSIV::LWL, &CMA_MIPSIV::LW, &CMA_MIPSIV::LBU, &CMA_MIPSIV::LHU, &CMA_MIPSIV::LWR, &CMA_MIPSIV::LWU,
//0x28
&CMA_MIPSIV::SB, &CMA_MIPSIV::SH, &CMA_MIPSIV::SWL, &CMA_MIPSIV::SW, &CMA_MIPSIV::SDL, &CMA_MIPSIV::SDR, &CMA_MIPSIV::SWR, &CMA_MIPSIV::CACHE,
//0x30
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::LWC1, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::LDC2, &CMA_MIPSIV::LD,
//0x38
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::SWC1, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::SDC2, &CMA_MIPSIV::SD,
};
CMA_MIPSIV::InstructionFuncConstant CMA_MIPSIV::m_cOpSpecial[MAX_SPECIAL_OPS] =
{
//0x00
&CMA_MIPSIV::SLL, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::SRL, &CMA_MIPSIV::SRA, &CMA_MIPSIV::SLLV, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::SRLV, &CMA_MIPSIV::SRAV,
//0x08
&CMA_MIPSIV::JR, &CMA_MIPSIV::JALR, &CMA_MIPSIV::MOVZ, &CMA_MIPSIV::MOVN, &CMA_MIPSIV::SYSCALL, &CMA_MIPSIV::BREAK, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::SYNC,
//0x10
&CMA_MIPSIV::MFHI, &CMA_MIPSIV::MTHI, &CMA_MIPSIV::MFLO, &CMA_MIPSIV::MTLO, &CMA_MIPSIV::DSLLV, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::DSRLV, &CMA_MIPSIV::Illegal,
//0x18
&CMA_MIPSIV::MULT, &CMA_MIPSIV::MULTU, &CMA_MIPSIV::DIV, &CMA_MIPSIV::DIVU, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal,
//0x20
&CMA_MIPSIV::ADD, &CMA_MIPSIV::ADDU, &CMA_MIPSIV::SUB, &CMA_MIPSIV::SUBU, &CMA_MIPSIV::AND, &CMA_MIPSIV::OR, &CMA_MIPSIV::XOR, &CMA_MIPSIV::NOR,
//0x28
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::SLT, &CMA_MIPSIV::SLTU, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::DADDU, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::DSUBU,
//0x30
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal,
//0x38
&CMA_MIPSIV::DSLL, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::DSRL, &CMA_MIPSIV::DSRA, &CMA_MIPSIV::DSLL32, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::DSRL32, &CMA_MIPSIV::DSRA32,
};
CMA_MIPSIV::InstructionFuncConstant CMA_MIPSIV::m_cOpRegImm[MAX_REGIMM_OPS] =
{
//0x00
&CMA_MIPSIV::BLTZ, &CMA_MIPSIV::BGEZ, &CMA_MIPSIV::BLTZL, &CMA_MIPSIV::BGEZL, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal,
//0x08
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal,
//0x10
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal,
//0x18
&CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal, &CMA_MIPSIV::Illegal,
};
|
#include "MainPanel.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include <QScrollArea>
#include <QSettings>
QString g_getStylesheet(QString location)
{
QFile stylesheet(location);
if (stylesheet.open(QFile::ReadOnly))
{
QString styleSheet = stylesheet.readAll();
return styleSheet;
}
return "";
}
MainPanel::MainPanel(QWidget* parent)
: QWidget(parent)
{
setObjectName("mainPanel");
init();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
show();
}
void MainPanel::init()
{
if (!db.init())
{
QMessageBox error;
error.critical(0, "Error!", "An error occured while trying to load the database.");
exit(EXIT_FAILURE);
return;
}
QString style = g_getStylesheet(":/Styles/Content.css");
QSettings p("palette.ini", QSettings::IniFormat);
setObjectName("mainPanel");
setStyleSheet("background-color: " + p.value("Primary/DarkestBase").toString() + ";");
// Main panel layout
QGridLayout *mainGridLayout = new QGridLayout(this);
mainGridLayout->setSpacing(0);
mainGridLayout->setMargin(0);
setLayout(mainGridLayout);
// Main panel scroll area
QScrollArea *scrollArea = new QScrollArea(this);
scrollArea->setWidgetResizable(true);
scrollArea->setObjectName("mainPanelScrollArea");
scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
mainGridLayout->addWidget(scrollArea);
// Core widget
QWidget *coreWidget = new QWidget(this);
coreWidget->setObjectName("centralWidget");
coreWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setWidget(coreWidget);
// Vertical layout #1
QVBoxLayout *verticalLayout1 = new QVBoxLayout(this);
verticalLayout1->setSpacing(0);
verticalLayout1->setMargin(0);
verticalLayout1->setAlignment(Qt::AlignHCenter);
coreWidget->setLayout(verticalLayout1);
// Accent border
QLabel *accentBorder = new QLabel(this);
accentBorder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
accentBorder->setMaximumHeight(3);
accentBorder->setStyleSheet("background-color: " + p.value("Primary/DarkestBase").toString() +
";border-top: 2px solid " + p.value("Accent/MediumAccent").toString() +
";border-bottom: 1px solid" + p.value("Accent/DarkAccent").toString() + ";");
accentBorder->adjustSize();
verticalLayout1->addWidget(accentBorder);
// Horizontal layout #1
QHBoxLayout *horizontalLayout1 = new QHBoxLayout(this);
horizontalLayout1->setSpacing(0);
horizontalLayout1->setMargin(0);
horizontalLayout1->setAlignment(Qt::AlignVCenter);
verticalLayout1->addLayout(horizontalLayout1);
// Sidebar widget - locked width
QWidget *sidebar = new QWidget(this);
sidebar->setMinimumWidth(224);
sidebar->setMaximumWidth(224);
sidebar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
sidebar->setStyleSheet("background-image: url(:/Elements/Sidebar.png);");
horizontalLayout1->addWidget(sidebar);
// Vertical layout #3
QVBoxLayout *verticalLayout3 = new QVBoxLayout(this);
verticalLayout3->setSpacing(0);
verticalLayout3->setMargin(0);
verticalLayout3->setAlignment(Qt::AlignHCenter);
horizontalLayout1->addLayout(verticalLayout3);
// Horizontal layout #2 - window controls
QHBoxLayout *horizontalLayout2 = new QHBoxLayout(this);
horizontalLayout2->setSpacing(0);
horizontalLayout2->setMargin(8);
verticalLayout3->addLayout(horizontalLayout2);
// Window title
QLabel *windowTitle = new QLabel(this);
windowTitle->setText("Project Ascension");
windowTitle->setStyleSheet("font-size: 16px; color: #444444;");
windowTitle->setAttribute(Qt::WA_TransparentForMouseEvents);
horizontalLayout2->addWidget(windowTitle);
horizontalLayout2->addStretch();
// Window controls
// Minimize
QPushButton *pushButtonMinimize = new QPushButton("", this);
pushButtonMinimize->setObjectName("pushButtonMinimize");
horizontalLayout2->addWidget(pushButtonMinimize);
QObject::connect(pushButtonMinimize, SIGNAL(clicked()), this, SLOT(pushButtonMinimize()));
// Maximize
QPushButton *pushButtonMaximize = new QPushButton("", this);
pushButtonMaximize->setObjectName("pushButtonMaximize");
horizontalLayout2->addWidget(pushButtonMaximize);
QObject::connect(pushButtonMaximize, SIGNAL(clicked()), this, SLOT(pushButtonMaximize()));
// Close
QPushButton *pushButtonClose = new QPushButton("", this);
pushButtonClose->setObjectName("pushButtonClose");
horizontalLayout2->addWidget(pushButtonClose);
QObject::connect(pushButtonClose, SIGNAL(clicked()), this, SLOT(pushButtonClose()));
// Stacked content panel
QStackedWidget *stack = new QStackedWidget(this);
stack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
verticalLayout3->addWidget(stack);
// Show
show();
}
Remove erroneous window label
#include "MainPanel.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include <QScrollArea>
#include <QSettings>
QString g_getStylesheet(QString location)
{
QFile stylesheet(location);
if (stylesheet.open(QFile::ReadOnly))
{
QString styleSheet = stylesheet.readAll();
return styleSheet;
}
return "";
}
MainPanel::MainPanel(QWidget* parent)
: QWidget(parent)
{
setObjectName("mainPanel");
init();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
show();
}
void MainPanel::init()
{
if (!db.init())
{
QMessageBox error;
error.critical(0, "Error!", "An error occured while trying to load the database.");
exit(EXIT_FAILURE);
return;
}
QString style = g_getStylesheet(":/Styles/Content.css");
QSettings p("palette.ini", QSettings::IniFormat);
setObjectName("mainPanel");
setStyleSheet("background-color: " + p.value("Primary/DarkestBase").toString() + ";");
// Main panel layout
QGridLayout *mainGridLayout = new QGridLayout(this);
mainGridLayout->setSpacing(0);
mainGridLayout->setMargin(0);
setLayout(mainGridLayout);
// Main panel scroll area
QScrollArea *scrollArea = new QScrollArea(this);
scrollArea->setWidgetResizable(true);
scrollArea->setObjectName("mainPanelScrollArea");
scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
mainGridLayout->addWidget(scrollArea);
// Core widget
QWidget *coreWidget = new QWidget(this);
coreWidget->setObjectName("centralWidget");
coreWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setWidget(coreWidget);
// Vertical layout #1
QVBoxLayout *verticalLayout1 = new QVBoxLayout(this);
verticalLayout1->setSpacing(0);
verticalLayout1->setMargin(0);
verticalLayout1->setAlignment(Qt::AlignHCenter);
coreWidget->setLayout(verticalLayout1);
// Accent border
QLabel *accentBorder = new QLabel(this);
accentBorder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
accentBorder->setMaximumHeight(3);
accentBorder->setStyleSheet("background-color: " + p.value("Primary/DarkestBase").toString() +
";border-top: 2px solid " + p.value("Accent/MediumAccent").toString() +
";border-bottom: 1px solid" + p.value("Accent/DarkAccent").toString() + ";");
accentBorder->adjustSize();
verticalLayout1->addWidget(accentBorder);
// Horizontal layout #1
QHBoxLayout *horizontalLayout1 = new QHBoxLayout(this);
horizontalLayout1->setSpacing(0);
horizontalLayout1->setMargin(0);
horizontalLayout1->setAlignment(Qt::AlignVCenter);
verticalLayout1->addLayout(horizontalLayout1);
// Sidebar widget - locked width
QWidget *sidebar = new QWidget(this);
sidebar->setMinimumWidth(224);
sidebar->setMaximumWidth(224);
sidebar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
sidebar->setStyleSheet("background-image: url(:/Elements/Sidebar.png);");
horizontalLayout1->addWidget(sidebar);
// Vertical layout #3
QVBoxLayout *verticalLayout3 = new QVBoxLayout(this);
verticalLayout3->setSpacing(0);
verticalLayout3->setMargin(0);
verticalLayout3->setAlignment(Qt::AlignHCenter);
horizontalLayout1->addLayout(verticalLayout3);
// Horizontal layout #2 - window controls
QHBoxLayout *horizontalLayout2 = new QHBoxLayout(this);
horizontalLayout2->setSpacing(0);
horizontalLayout2->setMargin(8);
verticalLayout3->addLayout(horizontalLayout2);
horizontalLayout2->addStretch();
// Window controls
// Minimize
QPushButton *pushButtonMinimize = new QPushButton("", this);
pushButtonMinimize->setObjectName("pushButtonMinimize");
horizontalLayout2->addWidget(pushButtonMinimize);
QObject::connect(pushButtonMinimize, SIGNAL(clicked()), this, SLOT(pushButtonMinimize()));
// Maximize
QPushButton *pushButtonMaximize = new QPushButton("", this);
pushButtonMaximize->setObjectName("pushButtonMaximize");
horizontalLayout2->addWidget(pushButtonMaximize);
QObject::connect(pushButtonMaximize, SIGNAL(clicked()), this, SLOT(pushButtonMaximize()));
// Close
QPushButton *pushButtonClose = new QPushButton("", this);
pushButtonClose->setObjectName("pushButtonClose");
horizontalLayout2->addWidget(pushButtonClose);
QObject::connect(pushButtonClose, SIGNAL(clicked()), this, SLOT(pushButtonClose()));
// Stacked content panel
QStackedWidget *stack = new QStackedWidget(this);
stack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
verticalLayout3->addWidget(stack);
// Show
show();
}
|
// Copyright (c) 2011 The Chromium OS 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 "update_engine/download_action.h"
#include <errno.h>
#include <algorithm>
#include <string>
#include <vector>
#include <glib.h>
#include "update_engine/action_pipe.h"
#include "update_engine/subprocess.h"
using std::min;
using std::string;
using std::vector;
namespace chromeos_update_engine {
// Use a buffer to reduce the number of IOPS on SSD devices.
const size_t kFileWriterBufferSize = 128 * 1024; // 128 KiB
DownloadAction::DownloadAction(PrefsInterface* prefs,
HttpFetcher* http_fetcher)
: prefs_(prefs),
writer_(NULL),
http_fetcher_(http_fetcher),
code_(kActionCodeSuccess),
delegate_(NULL),
bytes_received_(0) {}
DownloadAction::~DownloadAction() {}
void DownloadAction::PerformAction() {
http_fetcher_->set_delegate(this);
// Get the InstallPlan and read it
CHECK(HasInputObject());
install_plan_ = GetInputObject();
bytes_received_ = 0;
install_plan_.Dump();
if (writer_) {
LOG(INFO) << "Using writer for test.";
} else {
delta_performer_.reset(new DeltaPerformer(prefs_));
delta_performer_->set_current_kernel_hash(install_plan_.kernel_hash);
delta_performer_->set_current_rootfs_hash(install_plan_.rootfs_hash);
writer_ = delta_performer_.get();
}
int rc = writer_->Open(install_plan_.install_path.c_str(),
O_TRUNC | O_WRONLY | O_CREAT | O_LARGEFILE,
0644);
if (rc < 0) {
LOG(ERROR) << "Unable to open output file " << install_plan_.install_path;
// report error to processor
processor_->ActionComplete(this, kActionCodeInstallDeviceOpenError);
return;
}
if (delta_performer_.get() &&
!delta_performer_->OpenKernel(
install_plan_.kernel_install_path.c_str())) {
LOG(ERROR) << "Unable to open kernel file "
<< install_plan_.kernel_install_path.c_str();
writer_->Close();
processor_->ActionComplete(this, kActionCodeKernelDeviceOpenError);
return;
}
if (delegate_) {
delegate_->SetDownloadStatus(true); // Set to active.
}
http_fetcher_->BeginTransfer(install_plan_.download_url);
}
void DownloadAction::TerminateProcessing() {
if (writer_) {
LOG_IF(WARNING, writer_->Close() != 0) << "Error closing the writer.";
writer_ = NULL;
}
if (delegate_) {
delegate_->SetDownloadStatus(false); // Set to inactive.
}
// Terminates the transfer. The action is terminated, if necessary, when the
// TransferTerminated callback is received.
http_fetcher_->TerminateTransfer();
}
void DownloadAction::SeekToOffset(off_t offset) {
bytes_received_ = offset;
}
void DownloadAction::ReceivedBytes(HttpFetcher *fetcher,
const char* bytes,
int length) {
bytes_received_ += length;
if (delegate_)
delegate_->BytesReceived(bytes_received_, install_plan_.size);
if (writer_ && !writer_->Write(bytes, length)) {
LOG(ERROR) << "Write error -- terminating processing.";
// Don't tell the action processor that the action is complete until we get
// the TransferTerminated callback. Otherwise, this and the HTTP fetcher
// objects may get destroyed before all callbacks are complete.
code_ = kActionCodeDownloadWriteError;
TerminateProcessing();
return;
}
}
namespace {
void FlushLinuxCaches() {
vector<string> command;
command.push_back("/bin/sync");
int rc;
LOG(INFO) << "FlushLinuxCaches-sync...";
Subprocess::SynchronousExec(command, &rc, NULL);
LOG(INFO) << "FlushLinuxCaches-drop_caches...";
const char* const drop_cmd = "3\n";
utils::WriteFile("/proc/sys/vm/drop_caches", drop_cmd, strlen(drop_cmd));
LOG(INFO) << "FlushLinuxCaches done.";
}
}
void DownloadAction::TransferComplete(HttpFetcher *fetcher, bool successful) {
if (writer_) {
LOG_IF(WARNING, writer_->Close() != 0) << "Error closing the writer.";
writer_ = NULL;
}
if (delegate_) {
delegate_->SetDownloadStatus(false); // Set to inactive.
}
ActionExitCode code =
successful ? kActionCodeSuccess : kActionCodeDownloadTransferError;
if (code == kActionCodeSuccess && delta_performer_.get()) {
code = delta_performer_->VerifyPayload("",
install_plan_.download_hash,
install_plan_.size);
if (code != kActionCodeSuccess) {
LOG(ERROR) << "Download of " << install_plan_.download_url
<< " failed due to payload verification error.";
} else if (!delta_performer_->GetNewPartitionInfo(
&install_plan_.kernel_size,
&install_plan_.kernel_hash,
&install_plan_.rootfs_size,
&install_plan_.rootfs_hash)) {
LOG(ERROR) << "Unable to get new partition hash info.";
code = kActionCodeDownloadNewPartitionInfoError;
}
}
FlushLinuxCaches();
// Write the path to the output pipe if we're successful.
if (code == kActionCodeSuccess && HasOutputPipe())
SetOutputObject(install_plan_);
processor_->ActionComplete(this, code);
}
void DownloadAction::TransferTerminated(HttpFetcher *fetcher) {
if (code_ != kActionCodeSuccess) {
processor_->ActionComplete(this, code_);
}
}
}; // namespace {}
Don't drop cache.
It's possible (probable?) that the sync and cache drop operations part way
through the update process are causing UI jank. However, these operations were
added to work around an apparent kernel bug early in our development. This
bug may or may not have been fixed.
The sync operation here will be re-added during the postinst immediately
before we active the new partition in firmware.
If the kernel bug re-appears, we'll re-add the operations needed to
work around it in postinst so that we have the maximum flexibility.
BUG=chromium-os:27957
TEST=image_to_live.sh.
Change-Id: I152e494c07d3dc9a8e87ea377911d740511c5a30
Reviewed-on: https://gerrit.chromium.org/gerrit/19632
Reviewed-by: Don Garrett <546ec366615570e68497e3c5df9092106a9808f4@chromium.org>
Tested-by: Don Garrett <546ec366615570e68497e3c5df9092106a9808f4@chromium.org>
Commit-Ready: Don Garrett <546ec366615570e68497e3c5df9092106a9808f4@chromium.org>
// Copyright (c) 2011 The Chromium OS 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 "update_engine/download_action.h"
#include <errno.h>
#include <algorithm>
#include <string>
#include <vector>
#include <glib.h>
#include "update_engine/action_pipe.h"
#include "update_engine/subprocess.h"
using std::min;
using std::string;
using std::vector;
namespace chromeos_update_engine {
// Use a buffer to reduce the number of IOPS on SSD devices.
const size_t kFileWriterBufferSize = 128 * 1024; // 128 KiB
DownloadAction::DownloadAction(PrefsInterface* prefs,
HttpFetcher* http_fetcher)
: prefs_(prefs),
writer_(NULL),
http_fetcher_(http_fetcher),
code_(kActionCodeSuccess),
delegate_(NULL),
bytes_received_(0) {}
DownloadAction::~DownloadAction() {}
void DownloadAction::PerformAction() {
http_fetcher_->set_delegate(this);
// Get the InstallPlan and read it
CHECK(HasInputObject());
install_plan_ = GetInputObject();
bytes_received_ = 0;
install_plan_.Dump();
if (writer_) {
LOG(INFO) << "Using writer for test.";
} else {
delta_performer_.reset(new DeltaPerformer(prefs_));
delta_performer_->set_current_kernel_hash(install_plan_.kernel_hash);
delta_performer_->set_current_rootfs_hash(install_plan_.rootfs_hash);
writer_ = delta_performer_.get();
}
int rc = writer_->Open(install_plan_.install_path.c_str(),
O_TRUNC | O_WRONLY | O_CREAT | O_LARGEFILE,
0644);
if (rc < 0) {
LOG(ERROR) << "Unable to open output file " << install_plan_.install_path;
// report error to processor
processor_->ActionComplete(this, kActionCodeInstallDeviceOpenError);
return;
}
if (delta_performer_.get() &&
!delta_performer_->OpenKernel(
install_plan_.kernel_install_path.c_str())) {
LOG(ERROR) << "Unable to open kernel file "
<< install_plan_.kernel_install_path.c_str();
writer_->Close();
processor_->ActionComplete(this, kActionCodeKernelDeviceOpenError);
return;
}
if (delegate_) {
delegate_->SetDownloadStatus(true); // Set to active.
}
http_fetcher_->BeginTransfer(install_plan_.download_url);
}
void DownloadAction::TerminateProcessing() {
if (writer_) {
LOG_IF(WARNING, writer_->Close() != 0) << "Error closing the writer.";
writer_ = NULL;
}
if (delegate_) {
delegate_->SetDownloadStatus(false); // Set to inactive.
}
// Terminates the transfer. The action is terminated, if necessary, when the
// TransferTerminated callback is received.
http_fetcher_->TerminateTransfer();
}
void DownloadAction::SeekToOffset(off_t offset) {
bytes_received_ = offset;
}
void DownloadAction::ReceivedBytes(HttpFetcher *fetcher,
const char* bytes,
int length) {
bytes_received_ += length;
if (delegate_)
delegate_->BytesReceived(bytes_received_, install_plan_.size);
if (writer_ && !writer_->Write(bytes, length)) {
LOG(ERROR) << "Write error -- terminating processing.";
// Don't tell the action processor that the action is complete until we get
// the TransferTerminated callback. Otherwise, this and the HTTP fetcher
// objects may get destroyed before all callbacks are complete.
code_ = kActionCodeDownloadWriteError;
TerminateProcessing();
return;
}
}
void DownloadAction::TransferComplete(HttpFetcher *fetcher, bool successful) {
if (writer_) {
LOG_IF(WARNING, writer_->Close() != 0) << "Error closing the writer.";
writer_ = NULL;
}
if (delegate_) {
delegate_->SetDownloadStatus(false); // Set to inactive.
}
ActionExitCode code =
successful ? kActionCodeSuccess : kActionCodeDownloadTransferError;
if (code == kActionCodeSuccess && delta_performer_.get()) {
code = delta_performer_->VerifyPayload("",
install_plan_.download_hash,
install_plan_.size);
if (code != kActionCodeSuccess) {
LOG(ERROR) << "Download of " << install_plan_.download_url
<< " failed due to payload verification error.";
} else if (!delta_performer_->GetNewPartitionInfo(
&install_plan_.kernel_size,
&install_plan_.kernel_hash,
&install_plan_.rootfs_size,
&install_plan_.rootfs_hash)) {
LOG(ERROR) << "Unable to get new partition hash info.";
code = kActionCodeDownloadNewPartitionInfoError;
}
}
// Write the path to the output pipe if we're successful.
if (code == kActionCodeSuccess && HasOutputPipe())
SetOutputObject(install_plan_);
processor_->ActionComplete(this, code);
}
void DownloadAction::TransferTerminated(HttpFetcher *fetcher) {
if (code_ != kActionCodeSuccess) {
processor_->ActionComplete(this, code_);
}
}
}; // namespace {}
|
/******************************************************************************\
* LuaValue.cpp *
* A class that somewhat mimics a Lua value. *
* *
* *
* Copyright (C) 2005-2011 by Leandro Motta Barros. *
* *
* 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 <cstring>
#include <Diluculum/LuaValue.hpp>
#include <Diluculum/LuaExceptions.hpp>
namespace Diluculum
{
// - LuaValue::LuaValue -----------------------------------------------------
LuaValue::LuaValue()
: dataType_(LUA_TNIL)
{ }
LuaValue::LuaValue (bool b)
: dataType_(LUA_TBOOLEAN)
{
memcpy (data_, &b, sizeof(bool));
}
LuaValue::LuaValue (float n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (double n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (long double n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (short n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (unsigned short n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (int n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (unsigned n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (long n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (unsigned long n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (const std::string& s)
: dataType_(LUA_TSTRING)
{
new(data_) std::string(s);
}
LuaValue::LuaValue (const char* s)
: dataType_(LUA_TSTRING)
{
new(data_) std::string(s);
}
LuaValue::LuaValue (const LuaValueMap& t)
: dataType_(LUA_TTABLE)
{
new(data_) LuaValueMap(t);
}
LuaValue::LuaValue (lua_CFunction f)
: dataType_(LUA_TFUNCTION)
{
new(data_) LuaFunction(f);
}
LuaValue::LuaValue (const LuaFunction& f)
: dataType_(LUA_TFUNCTION)
{
new(data_) LuaFunction(f);
}
LuaValue::LuaValue (const LuaUserData& ud)
: dataType_(LUA_TUSERDATA)
{
new(data_) LuaUserData(ud);
}
LuaValue::LuaValue (const LuaValueList& v)
// Avoids possible memory corruption during destroyObjectAtData
: dataType_(LUA_TNIL)
{
if (v.size() >= 1)
*this = v[0];
else
*this = Nil;
}
LuaValue::LuaValue (const LuaValue& other)
: dataType_ (other.dataType_)
{
switch (dataType_)
{
case LUA_TSTRING:
new(data_) std::string(other.asString());
break;
case LUA_TTABLE:
new(data_) LuaValueMap (other.asTable());
break;
case LUA_TUSERDATA:
new(data_) LuaUserData (other.asUserData());
break;
case LUA_TFUNCTION:
new(data_) LuaFunction (other.asFunction());
break;
default:
// no constructor needed.
memcpy (data_, other.data_, sizeof(PossibleTypes));
break;
}
}
// - LuaValue::operator= ----------------------------------------------------
LuaValue& LuaValue::operator= (const LuaValue& rhs)
{
destroyObjectAtData();
dataType_ = rhs.dataType_;
switch (dataType_)
{
case LUA_TSTRING:
new(data_) std::string (rhs.asString());
break;
case LUA_TTABLE:
new(data_) LuaValueMap (rhs.asTable());
break;
case LUA_TUSERDATA:
new(data_) LuaUserData (rhs.asUserData());
break;
case LUA_TFUNCTION:
new(data_) LuaFunction (rhs.asFunction());
break;
default:
// no constructor needed.
memcpy (data_, rhs.data_, sizeof(PossibleTypes));
break;
}
return *this;
}
const LuaValueList& LuaValue::operator= (const LuaValueList& rhs)
{
if (rhs.size() >= 1)
*this = rhs[0];
else
*this = Nil;
return rhs;
}
// - LuaValue::typeName -----------------------------------------------------
std::string LuaValue::typeName() const
{
switch (dataType_)
{
case LUA_TNIL:
return "nil";
case LUA_TBOOLEAN:
return "boolean";
case LUA_TNUMBER:
return "number";
case LUA_TSTRING:
return "string";
case LUA_TTABLE:
return "table";
case LUA_TFUNCTION:
return "function";
case LUA_TUSERDATA:
return "userdata";
default: // can't happen
assert (false
&& "Invalid type found in a call to 'LuaValue::typeName()'.");
return ""; // return something to make compilers happy.
}
}
// - LuaValue::asNumber() ---------------------------------------------------
lua_Number LuaValue::asNumber() const
{
if (dataType_ == LUA_TNUMBER)
{
const lua_Number* pn = reinterpret_cast<const lua_Number*>(&data_);
return *pn;
}
else
{
throw TypeMismatchError ("number", typeName());
}
}
// - LuaValue::asInteger() --------------------------------------------------
lua_Integer LuaValue::asInteger() const
{
if (dataType_ == LUA_TNUMBER)
{
lua_Number num = (*reinterpret_cast<const lua_Number*>(&data_));
lua_Integer res = static_cast<lua_Integer>(num);
return res;
}
else
{
throw TypeMismatchError ("number", typeName());
}
}
// - LuaValue::asString -----------------------------------------------------
const std::string& LuaValue::asString() const
{
if (dataType_ == LUA_TSTRING)
{
const std::string* ps = reinterpret_cast<const std::string*>(&data_);
return *ps;
}
else
{
throw TypeMismatchError ("string", typeName());
}
}
// - LuaValue::asBoolean ----------------------------------------------------
bool LuaValue::asBoolean() const
{
if (dataType_ == LUA_TBOOLEAN)
{
const bool* pb = reinterpret_cast<const bool*>(&data_);
return *pb;
}
else
{
throw TypeMismatchError ("boolean", typeName());
}
}
// - LuaValue::asTable ------------------------------------------------------
LuaValueMap LuaValue::asTable() const
{
if (dataType_ == LUA_TTABLE)
{
const LuaValueMap* pm = reinterpret_cast<const LuaValueMap*>(&data_);
return *pm;
}
else
{
throw TypeMismatchError ("table", typeName());
}
}
// - LuaValue::asFunction ---------------------------------------------------
const LuaFunction& LuaValue::asFunction() const
{
if (dataType_ == LUA_TFUNCTION)
{
const LuaFunction* pf = reinterpret_cast<const LuaFunction*>(&data_);
return *pf;
}
else
{
throw TypeMismatchError ("function", typeName());
}
}
// - LuaValue::asUserData ---------------------------------------------------
const LuaUserData& LuaValue::asUserData() const
{
if (dataType_ == LUA_TUSERDATA)
{
const LuaUserData* pd = reinterpret_cast<const LuaUserData*>(&data_);
return *pd;
}
else
{
throw TypeMismatchError ("userdata", typeName());
}
}
LuaUserData& LuaValue::asUserData()
{
if (dataType_ == LUA_TUSERDATA)
{
LuaUserData* pd = reinterpret_cast<LuaUserData*>(&data_);
return *pd;
}
else
{
throw TypeMismatchError ("userdata", typeName());
}
}
// - LuaValue::operator< ----------------------------------------------------
bool LuaValue::operator< (const LuaValue& rhs) const
{
std::string lhsTypeName = typeName();
std::string rhsTypeName = rhs.typeName();
if (lhsTypeName < rhsTypeName)
return true;
else if (lhsTypeName > rhsTypeName)
return false;
else // lhsTypeName == rhsTypeName
{
if (lhsTypeName == "nil")
return false;
else if (lhsTypeName == "boolean")
return asBoolean() < rhs.asBoolean();
else if (lhsTypeName == "number")
return asNumber() < rhs.asNumber();
else if (lhsTypeName == "string")
return asString() < rhs.asString();
else if (lhsTypeName == "function")
return asFunction() < rhs.asFunction();
else if (lhsTypeName == "userdata")
return asUserData() < rhs.asUserData();
else if (lhsTypeName == "table")
{
const LuaValueMap lhsMap = asTable();
const LuaValueMap rhsMap = rhs.asTable();
if (lhsMap.size() < rhsMap.size())
return true;
else if (lhsMap.size() > rhsMap.size())
return false;
else // lhsMap.size() == rhsMap.size()
{
typedef LuaValueMap::const_iterator iter_t;
iter_t pLHS = lhsMap.begin();
iter_t pRHS = rhsMap.begin();
const iter_t end = lhsMap.end();
while (pLHS != end)
{
// check the key first
if (pLHS->first < pRHS->first)
return true;
else if (pLHS->first > pRHS->first)
return false;
// then check the value
if (pLHS->second < pRHS->second)
return true;
else if (pLHS->second > pRHS->second)
return false;
// make the iterators iterate
++pRHS;
++pLHS;
}
return false;
}
}
else
{
assert (false && "Unsupported type found at a call "
"to 'LuaValue::operator<()'");
return false; // make the compiler happy.
}
}
}
// - LuaValue::operator> ----------------------------------------------------
bool LuaValue::operator> (const LuaValue& rhs) const
{
std::string lhsTypeName = typeName();
std::string rhsTypeName = rhs.typeName();
if (lhsTypeName > rhsTypeName)
return true;
else if (lhsTypeName < rhsTypeName)
return false;
else // lhsTypeName == rhsTypeName
{
if (lhsTypeName == "nil")
return false;
else if (lhsTypeName == "boolean")
return asBoolean() > rhs.asBoolean();
else if (lhsTypeName == "number")
return asNumber() > rhs.asNumber();
else if (lhsTypeName == "string")
return asString() > rhs.asString();
else if (lhsTypeName == "function")
return asFunction() > rhs.asFunction();
else if (lhsTypeName == "userdata")
return asUserData() > rhs.asUserData();
else if (lhsTypeName == "table")
{
const LuaValueMap lhsMap = asTable();
const LuaValueMap rhsMap = rhs.asTable();
if (lhsMap.size() > rhsMap.size())
return true;
else if (lhsMap.size() < rhsMap.size())
return false;
else // lhsMap.size() == rhsMap.size()
{
typedef LuaValueMap::const_iterator iter_t;
iter_t pLHS = lhsMap.begin();
iter_t pRHS = rhsMap.begin();
const iter_t end = lhsMap.end();
while (pLHS != end)
{
// check the key first
if (pLHS->first > pRHS->first)
return true;
else if (pLHS->first < pRHS->first)
return false;
// then check the value
if (pLHS->second > pRHS->second)
return true;
else if (pLHS->second < pRHS->second)
return false;
// make the iterators iterate
++pRHS;
++pLHS;
}
return false;
}
}
else
{
assert (false && "Unsupported type found at a call "
"to 'LuaValue::operator>()'");
return false; // make the compiler happy.
}
}
}
// - LuaValue::operator== ---------------------------------------------------
bool LuaValue::operator== (const LuaValue& rhs) const
{
std::string lhsTypeName = typeName();
std::string rhsTypeName = rhs.typeName();
if (typeName() != rhs.typeName())
return false;
else switch (type())
{
case LUA_TNIL:
return true;
case LUA_TBOOLEAN:
return asBoolean() == rhs.asBoolean();
case LUA_TNUMBER:
return asNumber() == rhs.asNumber();
case LUA_TSTRING:
return asString() == rhs.asString();
case LUA_TTABLE:
return asTable() == rhs.asTable();
case LUA_TFUNCTION:
return asFunction() == rhs.asFunction();
case LUA_TUSERDATA:
return asUserData() == rhs.asUserData();
default:
{
assert(
false
&& "Invalid type found in a call to 'LuaValue::operator==()'.");
return 0; // make compilers happy
}
}
}
// - LuaValue::operator[] ---------------------------------------------------
LuaValue& LuaValue::operator[] (const LuaValue& key)
{
if (type() != LUA_TTABLE)
throw TypeMismatchError ("table", typeName());
LuaValueMap* pTable = reinterpret_cast<LuaValueMap*>(data_);
return (*pTable)[key];
}
const LuaValue& LuaValue::operator[] (const LuaValue& key) const
{
if (type() != LUA_TTABLE)
throw TypeMismatchError ("table", typeName());
const LuaValueMap* pTable = reinterpret_cast<const LuaValueMap*>(data_);
LuaValueMap::const_iterator it = (*pTable).find(key);
if (it == (*pTable).end())
return Nil;
return it->second;
}
// - LuaValue::destroyObjectAtData ------------------------------------------
void LuaValue::destroyObjectAtData()
{
switch (dataType_)
{
case LUA_TSTRING:
{
std::string* ps = reinterpret_cast<std::string*>(data_);
ps->~basic_string();
break;
}
case LUA_TTABLE:
{
LuaValueMap* pm = reinterpret_cast<LuaValueMap*>(data_);
pm->~LuaValueMap();
break;
}
case LUA_TUSERDATA:
{
LuaUserData* pd = reinterpret_cast<LuaUserData*>(data_);
pd->~LuaUserData();
break;
}
case LUA_TFUNCTION:
{
LuaFunction* pf = reinterpret_cast<LuaFunction*>(data_);
pf->~LuaFunction();
break;
}
default:
// no destructor needed.
break;
}
}
} // namespace Diluculum
Getting rid of warning.
/******************************************************************************\
* LuaValue.cpp *
* A class that somewhat mimics a Lua value. *
* *
* *
* Copyright (C) 2005-2011 by Leandro Motta Barros. *
* *
* 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 <cstring>
#include <Diluculum/LuaValue.hpp>
#include <Diluculum/LuaExceptions.hpp>
namespace Diluculum
{
// - LuaValue::LuaValue -----------------------------------------------------
LuaValue::LuaValue()
: dataType_(LUA_TNIL)
{ }
LuaValue::LuaValue (bool b)
: dataType_(LUA_TBOOLEAN)
{
memcpy (data_, &b, sizeof(bool));
}
LuaValue::LuaValue (float n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (double n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (long double n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (short n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (unsigned short n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (int n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (unsigned n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (long n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (unsigned long n)
: dataType_(LUA_TNUMBER)
{
lua_Number num = static_cast<lua_Number>(n);
memcpy (data_, &num, sizeof(lua_Number));
}
LuaValue::LuaValue (const std::string& s)
: dataType_(LUA_TSTRING)
{
new(data_) std::string(s);
}
LuaValue::LuaValue (const char* s)
: dataType_(LUA_TSTRING)
{
new(data_) std::string(s);
}
LuaValue::LuaValue (const LuaValueMap& t)
: dataType_(LUA_TTABLE)
{
new(data_) LuaValueMap(t);
}
LuaValue::LuaValue (lua_CFunction f)
: dataType_(LUA_TFUNCTION)
{
new(data_) LuaFunction(f);
}
LuaValue::LuaValue (const LuaFunction& f)
: dataType_(LUA_TFUNCTION)
{
new(data_) LuaFunction(f);
}
LuaValue::LuaValue (const LuaUserData& ud)
: dataType_(LUA_TUSERDATA)
{
new(data_) LuaUserData(ud);
}
LuaValue::LuaValue (const LuaValueList& v)
// Avoids possible memory corruption during destroyObjectAtData
: dataType_(LUA_TNIL)
{
if (v.size() >= 1)
*this = v[0];
else
*this = Nil;
}
LuaValue::LuaValue (const LuaValue& other)
: dataType_ (other.dataType_)
{
switch (dataType_)
{
case LUA_TSTRING:
new(data_) std::string(other.asString());
break;
case LUA_TTABLE:
new(data_) LuaValueMap (other.asTable());
break;
case LUA_TUSERDATA:
new(data_) LuaUserData (other.asUserData());
break;
case LUA_TFUNCTION:
new(data_) LuaFunction (other.asFunction());
break;
default:
// no constructor needed.
memcpy (data_, other.data_, sizeof(PossibleTypes));
break;
}
}
// - LuaValue::operator= ----------------------------------------------------
LuaValue& LuaValue::operator= (const LuaValue& rhs)
{
destroyObjectAtData();
dataType_ = rhs.dataType_;
switch (dataType_)
{
case LUA_TSTRING:
new(data_) std::string (rhs.asString());
break;
case LUA_TTABLE:
new(data_) LuaValueMap (rhs.asTable());
break;
case LUA_TUSERDATA:
new(data_) LuaUserData (rhs.asUserData());
break;
case LUA_TFUNCTION:
new(data_) LuaFunction (rhs.asFunction());
break;
default:
// no constructor needed.
memcpy (data_, rhs.data_, sizeof(PossibleTypes));
break;
}
return *this;
}
const LuaValueList& LuaValue::operator= (const LuaValueList& rhs)
{
if (rhs.size() >= 1)
*this = rhs[0];
else
*this = Nil;
return rhs;
}
// - LuaValue::typeName -----------------------------------------------------
std::string LuaValue::typeName() const
{
switch (dataType_)
{
case LUA_TNIL:
return "nil";
case LUA_TBOOLEAN:
return "boolean";
case LUA_TNUMBER:
return "number";
case LUA_TSTRING:
return "string";
case LUA_TTABLE:
return "table";
case LUA_TFUNCTION:
return "function";
case LUA_TUSERDATA:
return "userdata";
default: // can't happen
assert (false
&& "Invalid type found in a call to 'LuaValue::typeName()'.");
return ""; // return something to make compilers happy.
}
}
// - LuaValue::asNumber() ---------------------------------------------------
lua_Number LuaValue::asNumber() const
{
if (dataType_ == LUA_TNUMBER)
{
const lua_Number* pn = reinterpret_cast<const lua_Number*>(&data_);
return *pn;
}
else
{
throw TypeMismatchError ("number", typeName());
}
}
// - LuaValue::asInteger() --------------------------------------------------
lua_Integer LuaValue::asInteger() const
{
if (dataType_ == LUA_TNUMBER)
{
const lua_Number* num = reinterpret_cast<const lua_Number*>(&data_);
lua_Integer res = static_cast<lua_Integer>(*num);
return res;
}
else
{
throw TypeMismatchError ("number", typeName());
}
}
// - LuaValue::asString -----------------------------------------------------
const std::string& LuaValue::asString() const
{
if (dataType_ == LUA_TSTRING)
{
const std::string* ps = reinterpret_cast<const std::string*>(&data_);
return *ps;
}
else
{
throw TypeMismatchError ("string", typeName());
}
}
// - LuaValue::asBoolean ----------------------------------------------------
bool LuaValue::asBoolean() const
{
if (dataType_ == LUA_TBOOLEAN)
{
const bool* pb = reinterpret_cast<const bool*>(&data_);
return *pb;
}
else
{
throw TypeMismatchError ("boolean", typeName());
}
}
// - LuaValue::asTable ------------------------------------------------------
LuaValueMap LuaValue::asTable() const
{
if (dataType_ == LUA_TTABLE)
{
const LuaValueMap* pm = reinterpret_cast<const LuaValueMap*>(&data_);
return *pm;
}
else
{
throw TypeMismatchError ("table", typeName());
}
}
// - LuaValue::asFunction ---------------------------------------------------
const LuaFunction& LuaValue::asFunction() const
{
if (dataType_ == LUA_TFUNCTION)
{
const LuaFunction* pf = reinterpret_cast<const LuaFunction*>(&data_);
return *pf;
}
else
{
throw TypeMismatchError ("function", typeName());
}
}
// - LuaValue::asUserData ---------------------------------------------------
const LuaUserData& LuaValue::asUserData() const
{
if (dataType_ == LUA_TUSERDATA)
{
const LuaUserData* pd = reinterpret_cast<const LuaUserData*>(&data_);
return *pd;
}
else
{
throw TypeMismatchError ("userdata", typeName());
}
}
LuaUserData& LuaValue::asUserData()
{
if (dataType_ == LUA_TUSERDATA)
{
LuaUserData* pd = reinterpret_cast<LuaUserData*>(&data_);
return *pd;
}
else
{
throw TypeMismatchError ("userdata", typeName());
}
}
// - LuaValue::operator< ----------------------------------------------------
bool LuaValue::operator< (const LuaValue& rhs) const
{
std::string lhsTypeName = typeName();
std::string rhsTypeName = rhs.typeName();
if (lhsTypeName < rhsTypeName)
return true;
else if (lhsTypeName > rhsTypeName)
return false;
else // lhsTypeName == rhsTypeName
{
if (lhsTypeName == "nil")
return false;
else if (lhsTypeName == "boolean")
return asBoolean() < rhs.asBoolean();
else if (lhsTypeName == "number")
return asNumber() < rhs.asNumber();
else if (lhsTypeName == "string")
return asString() < rhs.asString();
else if (lhsTypeName == "function")
return asFunction() < rhs.asFunction();
else if (lhsTypeName == "userdata")
return asUserData() < rhs.asUserData();
else if (lhsTypeName == "table")
{
const LuaValueMap lhsMap = asTable();
const LuaValueMap rhsMap = rhs.asTable();
if (lhsMap.size() < rhsMap.size())
return true;
else if (lhsMap.size() > rhsMap.size())
return false;
else // lhsMap.size() == rhsMap.size()
{
typedef LuaValueMap::const_iterator iter_t;
iter_t pLHS = lhsMap.begin();
iter_t pRHS = rhsMap.begin();
const iter_t end = lhsMap.end();
while (pLHS != end)
{
// check the key first
if (pLHS->first < pRHS->first)
return true;
else if (pLHS->first > pRHS->first)
return false;
// then check the value
if (pLHS->second < pRHS->second)
return true;
else if (pLHS->second > pRHS->second)
return false;
// make the iterators iterate
++pRHS;
++pLHS;
}
return false;
}
}
else
{
assert (false && "Unsupported type found at a call "
"to 'LuaValue::operator<()'");
return false; // make the compiler happy.
}
}
}
// - LuaValue::operator> ----------------------------------------------------
bool LuaValue::operator> (const LuaValue& rhs) const
{
std::string lhsTypeName = typeName();
std::string rhsTypeName = rhs.typeName();
if (lhsTypeName > rhsTypeName)
return true;
else if (lhsTypeName < rhsTypeName)
return false;
else // lhsTypeName == rhsTypeName
{
if (lhsTypeName == "nil")
return false;
else if (lhsTypeName == "boolean")
return asBoolean() > rhs.asBoolean();
else if (lhsTypeName == "number")
return asNumber() > rhs.asNumber();
else if (lhsTypeName == "string")
return asString() > rhs.asString();
else if (lhsTypeName == "function")
return asFunction() > rhs.asFunction();
else if (lhsTypeName == "userdata")
return asUserData() > rhs.asUserData();
else if (lhsTypeName == "table")
{
const LuaValueMap lhsMap = asTable();
const LuaValueMap rhsMap = rhs.asTable();
if (lhsMap.size() > rhsMap.size())
return true;
else if (lhsMap.size() < rhsMap.size())
return false;
else // lhsMap.size() == rhsMap.size()
{
typedef LuaValueMap::const_iterator iter_t;
iter_t pLHS = lhsMap.begin();
iter_t pRHS = rhsMap.begin();
const iter_t end = lhsMap.end();
while (pLHS != end)
{
// check the key first
if (pLHS->first > pRHS->first)
return true;
else if (pLHS->first < pRHS->first)
return false;
// then check the value
if (pLHS->second > pRHS->second)
return true;
else if (pLHS->second < pRHS->second)
return false;
// make the iterators iterate
++pRHS;
++pLHS;
}
return false;
}
}
else
{
assert (false && "Unsupported type found at a call "
"to 'LuaValue::operator>()'");
return false; // make the compiler happy.
}
}
}
// - LuaValue::operator== ---------------------------------------------------
bool LuaValue::operator== (const LuaValue& rhs) const
{
std::string lhsTypeName = typeName();
std::string rhsTypeName = rhs.typeName();
if (typeName() != rhs.typeName())
return false;
else switch (type())
{
case LUA_TNIL:
return true;
case LUA_TBOOLEAN:
return asBoolean() == rhs.asBoolean();
case LUA_TNUMBER:
return asNumber() == rhs.asNumber();
case LUA_TSTRING:
return asString() == rhs.asString();
case LUA_TTABLE:
return asTable() == rhs.asTable();
case LUA_TFUNCTION:
return asFunction() == rhs.asFunction();
case LUA_TUSERDATA:
return asUserData() == rhs.asUserData();
default:
{
assert(
false
&& "Invalid type found in a call to 'LuaValue::operator==()'.");
return 0; // make compilers happy
}
}
}
// - LuaValue::operator[] ---------------------------------------------------
LuaValue& LuaValue::operator[] (const LuaValue& key)
{
if (type() != LUA_TTABLE)
throw TypeMismatchError ("table", typeName());
LuaValueMap* pTable = reinterpret_cast<LuaValueMap*>(data_);
return (*pTable)[key];
}
const LuaValue& LuaValue::operator[] (const LuaValue& key) const
{
if (type() != LUA_TTABLE)
throw TypeMismatchError ("table", typeName());
const LuaValueMap* pTable = reinterpret_cast<const LuaValueMap*>(data_);
LuaValueMap::const_iterator it = (*pTable).find(key);
if (it == (*pTable).end())
return Nil;
return it->second;
}
// - LuaValue::destroyObjectAtData ------------------------------------------
void LuaValue::destroyObjectAtData()
{
switch (dataType_)
{
case LUA_TSTRING:
{
std::string* ps = reinterpret_cast<std::string*>(data_);
ps->~basic_string();
break;
}
case LUA_TTABLE:
{
LuaValueMap* pm = reinterpret_cast<LuaValueMap*>(data_);
pm->~LuaValueMap();
break;
}
case LUA_TUSERDATA:
{
LuaUserData* pd = reinterpret_cast<LuaUserData*>(data_);
pd->~LuaUserData();
break;
}
case LUA_TFUNCTION:
{
LuaFunction* pf = reinterpret_cast<LuaFunction*>(data_);
pf->~LuaFunction();
break;
}
default:
// no destructor needed.
break;
}
}
} // namespace Diluculum
|
#include <Siv3D.hpp>
#include "Main.h"
#include "Loader.hpp"
#ifdef DEPLOY
String currentDocument(L"./doc/");
String configFile(L"./speedreader.ini");
String sampleDocument(L"./sample/");
#else
String currentDocument(L"../Speedreader/speedreader/doc/");
String configFile(L"../Speedreader/speedreader.ini");
String sampleDocument(L"../Speedreader/speedreader/sample/");
#endif
std::wstring displayOrder(L"LTR"); // Right to left(RTL): 0 LTR: 1
double joystickPointerSpeed = 1.0;
int drawingXOffset = 100;
double viewingPage = 0;
int displayMode = 1;
int autoplaySpeed = 0;
int debugTexureLoadingBenchmark;
int numPages;
void loadPDFConfig() {
String filename = Format(currentDocument, L"config.ini");
INIReader ini(filename);
if (!ini)
{
INIWriter default_ini(filename);
default_ini.write(L"displayOrder", L"LTR");
ini = INIReader(filename);
}
displayOrder = ini.getOr<std::wstring>(L"displayOrder", L"LTR");
}
void updateConfig(INIReader config) {
config.reload();
joystickPointerSpeed = config.getOr<double>(L"Controller.PointerSpeed", 1.0);
drawingXOffset = config.getOr<int>(L"Drawing.XOffset", 100);
debugTexureLoadingBenchmark = config.getOr<int>(L"Debug.TextureLoadingBenchmark", 0);
}
void loadNewDocument(String path) {
currentDocument = path;
Profiler::EnableWarning(false); // 再読み込み時のテクスチャ破棄で警告されるので読み終わるまでdisable
loadPDFConfig();
viewingPage = 0;
displayMode = 1;
loader::loadPDF(currentDocument);
numPages = loader::numPages;
}
void convertToDDS() {
// TODO: make menu to call this
for (auto i : step(100)) {
Image(
Format(L"C:/Users/nishio/Desktop/images/pages_{:04d}.png"_fmt, i + 1)
).save(
Format(L"C:/Users/nishio/Desktop/images/pages_{:04d}.dds"_fmt, i + 1)
);
}
}
void Main()
{
INIReader config(configFile);
updateConfig(config);
const Font font(30);
const Font font10(10);
loadPDFConfig();
Window::SetTitle(L"Speedreader");
Window::Resize(1300, 700);
Window::ToUpperLeft();
Window::SetStyle(WindowStyle::Sizeable);
Cursor::SetPos(0, 0);
Vec2 pos = Mouse::Pos();
Stopwatch stopwatch(true);
loader::loadPDF(currentDocument);
numPages = loader::numPages;
while (System::Update())
{
double invFPS = stopwatch.ms();
stopwatch.restart();
if (config.hasChanged()) updateConfig(config);
if (Dragdrop::HasItems())
{
const Array<FilePath> items = Dragdrop::GetFilePaths();
loadNewDocument(items[0]);
}
// まだ読み終わってなければ順次ロード
loader::keepLoading();
auto controller = XInput(0);
controller.setLeftTriggerDeadZone();
controller.setRightTriggerDeadZone();
controller.setLeftThumbDeadZone();
controller.setRightThumbDeadZone();
pos += Vec2(
controller.leftThumbX * joystickPointerSpeed * invFPS,
-controller.leftThumbY * joystickPointerSpeed * invFPS);
//pos += Mouse::Delta(); // マウスも併用する場合はジョイスティックでの移動差分をマウスの入力と勘違いするので用修正
if (pos.x < 0) pos.x = 0;
if (pos.y < 0) pos.y = 0;
if (pos.x > Window::Width()) pos.x = Window::Width();
if (pos.y > Window::Height()) pos.y = Window::Height();
viewingPage -= pow(controller.leftTrigger, 2);
viewingPage += pow(controller.rightTrigger, 2);
viewingPage += controller.rightThumbY / 5; // slow
// キーでのパラパラめくり// 早送り巻き戻しメタファー
if (Input::KeyRight.clicked) {
if (autoplaySpeed > 0) {
autoplaySpeed *= 2;
}
else if (autoplaySpeed == 0) {
autoplaySpeed = 1;
}
else {
autoplaySpeed = 0;
}
}
if (Input::KeyLeft.clicked) {
if (autoplaySpeed < 0) {
autoplaySpeed *= 2;
}
else if (autoplaySpeed == 0) {
autoplaySpeed = -1;
}
else {
autoplaySpeed = 0;
}
}
if (autoplaySpeed) {
viewingPage += autoplaySpeed * invFPS / 1000;
font10(L"自動再生: ", autoplaySpeed).draw(0, 0);
}
if (viewingPage < 0) viewingPage = 0;
if (viewingPage > numPages - 1) viewingPage = numPages - 1;
if (displayMode == 0) {
if (controller.buttonA.clicked || Input::KeyDown.clicked) viewingPage += 0.5;
if (controller.buttonB.clicked || Input::KeyUp.clicked) viewingPage -= 0.5;
}
else {
if (controller.buttonA.clicked || Input::KeyDown.clicked) {
viewingPage++;
autoplaySpeed = 0;
}
if (controller.buttonB.clicked || Input::KeyUp.clicked) {
viewingPage--;
autoplaySpeed = 0;
}
}
// 最初・最後のページで前後に移動した時に反対側に飛ぶべきかどうか、今disabled
//if (page < 0) page += numPages;
//if (page > numPages - 1) page = 0;
if (viewingPage < 0) viewingPage = 0;
if (viewingPage > numPages - 1) viewingPage = numPages - 1;
int ipage = static_cast<int>(viewingPage) % numPages;
if (controller.buttonLB.clicked || Input::KeyZ.clicked) {
displayMode = (displayMode - 1);
if (displayMode < 0) displayMode = 0;
}
if (controller.buttonRB.clicked || Input::KeyC.clicked) {
displayMode = (displayMode + 1);
}
Texture t = loader::getPage(ipage);
double h = static_cast<double>(t.height);
double w = static_cast<double>(t.width);
const int screenHeight = 640;
double pageHeight = screenHeight, pageWidth = w / h * pageHeight;
int horizontalMultiplier = 2; // 見開きにするなら2、しないなら1
if (h < w) horizontalMultiplier = 1;
// draw progress bar
int progressBarWidth = static_cast<int>(pageWidth * horizontalMultiplier);
Rect(drawingXOffset, screenHeight + 10,
progressBarWidth, 20).draw(Color(200));
Rect(drawingXOffset, screenHeight + 12,
progressBarWidth * (ipage + 1) / numPages, 16).draw(Color(100));
font10(ipage + 1).draw(drawingXOffset, screenHeight + 12);
const int32 w2 = font10(numPages).region().w;
font10(numPages).draw(drawingXOffset + progressBarWidth - w2, screenHeight + 12);
if (displayMode == 0) {
// Zoom-in mode
int scale = 2;
if (static_cast<int>(viewingPage * 2) % 2 == 0) {
t.resize(pageWidth * scale, pageHeight * scale).draw(drawingXOffset, 0);
}
else {
t(0, h / 2, w, h / 2).resize(pageWidth * scale, pageHeight).draw(drawingXOffset, 0);
}
}
else if(displayMode > 0) {
int numPageHorizontal = displayMode * horizontalMultiplier;
int numPageVertical = displayMode;
// Tile mode
if (displayOrder == L"LTR") {
pageHeight /= numPageVertical;
pageWidth /= numPageVertical;
for (int y = 0; y < numPageVertical; y++) {
for (int x = 0; x < numPageHorizontal; x++) {
int i = ipage + y * numPageHorizontal + x;
loader::getPage(i)
.resize(pageWidth, pageHeight)
.draw(drawingXOffset + pageWidth * x, pageHeight * y);
}
}
}
else {
pageHeight /= numPageVertical;
pageWidth /= numPageVertical;
for (int y = 0; y < numPageVertical; y++) {
for (int x = 0; x < numPageHorizontal; x++) {
int i = ipage + y * numPageHorizontal + x;
loader::getPage(i)
.resize(pageWidth, pageHeight)
.draw(drawingXOffset + pageWidth * (numPageHorizontal - x - 1), pageHeight * y);
}
}
}
// Xボタンでそのページを通常表示
if (controller.buttonX.clicked || Input::MouseL.clicked) {
if (Input::MouseL.clicked) {
pos = Mouse::Pos();
}
int x = static_cast<int>((pos.x - drawingXOffset) / pageWidth);
if (displayOrder != L"LTR") {
x = numPageHorizontal - x - 1;
}
int y = static_cast<int>(pos.y / pageHeight);
viewingPage = ipage + x + y * numPageHorizontal;
displayMode = 1;
Cursor::SetPos(0, 0);
pos = { 0, 0 };
}
}
// デモ用
if (controller.buttonY.clicked || Input::KeyY.clicked) {
loadNewDocument(sampleDocument);
}
// カーソル表示
Circle(pos, 10).draw({ 255, 255, 0, 127 });
}
}
ignore ESC
#include <Siv3D.hpp>
#include "Main.h"
#include "Loader.hpp"
#ifdef DEPLOY
String currentDocument(L"./doc/");
String configFile(L"./speedreader.ini");
String sampleDocument(L"./sample/");
#else
String currentDocument(L"../Speedreader/speedreader/doc/");
String configFile(L"../Speedreader/speedreader.ini");
String sampleDocument(L"../Speedreader/speedreader/sample/");
#endif
std::wstring displayOrder(L"LTR"); // Right to left(RTL): 0 LTR: 1
double joystickPointerSpeed = 1.0;
int drawingXOffset = 100;
double viewingPage = 0;
int displayMode = 1;
int autoplaySpeed = 0;
int debugTexureLoadingBenchmark;
int numPages;
void loadPDFConfig() {
String filename = Format(currentDocument, L"config.ini");
INIReader ini(filename);
if (!ini)
{
INIWriter default_ini(filename);
default_ini.write(L"displayOrder", L"LTR");
ini = INIReader(filename);
}
displayOrder = ini.getOr<std::wstring>(L"displayOrder", L"LTR");
}
void updateConfig(INIReader config) {
config.reload();
joystickPointerSpeed = config.getOr<double>(L"Controller.PointerSpeed", 1.0);
drawingXOffset = config.getOr<int>(L"Drawing.XOffset", 100);
debugTexureLoadingBenchmark = config.getOr<int>(L"Debug.TextureLoadingBenchmark", 0);
}
void loadNewDocument(String path) {
currentDocument = path;
Profiler::EnableWarning(false); // 再読み込み時のテクスチャ破棄で警告されるので読み終わるまでdisable
loadPDFConfig();
viewingPage = 0;
displayMode = 1;
loader::loadPDF(currentDocument);
numPages = loader::numPages;
}
void convertToDDS() {
// TODO: make menu to call this
for (auto i : step(100)) {
Image(
Format(L"C:/Users/nishio/Desktop/images/pages_{:04d}.png"_fmt, i + 1)
).save(
Format(L"C:/Users/nishio/Desktop/images/pages_{:04d}.dds"_fmt, i + 1)
);
}
}
void Main()
{
INIReader config(configFile);
updateConfig(config);
const Font font(30);
const Font font10(10);
loadPDFConfig();
Window::SetTitle(L"Speedreader");
Window::Resize(1300, 700);
Window::ToUpperLeft();
Window::SetStyle(WindowStyle::Sizeable);
Cursor::SetPos(0, 0);
Vec2 pos = Mouse::Pos();
Stopwatch stopwatch(true);
loader::loadPDF(currentDocument);
numPages = loader::numPages;
// ESCでWindowを閉じない
System::SetExitEvent(WindowEvent::CloseButton);
while (System::Update())
{
double invFPS = stopwatch.ms();
stopwatch.restart();
if (config.hasChanged()) updateConfig(config);
if (Dragdrop::HasItems())
{
const Array<FilePath> items = Dragdrop::GetFilePaths();
loadNewDocument(items[0]);
}
// まだ読み終わってなければ順次ロード
loader::keepLoading();
auto controller = XInput(0);
controller.setLeftTriggerDeadZone();
controller.setRightTriggerDeadZone();
controller.setLeftThumbDeadZone();
controller.setRightThumbDeadZone();
pos += Vec2(
controller.leftThumbX * joystickPointerSpeed * invFPS,
-controller.leftThumbY * joystickPointerSpeed * invFPS);
//pos += Mouse::Delta(); // マウスも併用する場合はジョイスティックでの移動差分をマウスの入力と勘違いするので用修正
if (pos.x < 0) pos.x = 0;
if (pos.y < 0) pos.y = 0;
if (pos.x > Window::Width()) pos.x = Window::Width();
if (pos.y > Window::Height()) pos.y = Window::Height();
viewingPage -= pow(controller.leftTrigger, 2);
viewingPage += pow(controller.rightTrigger, 2);
viewingPage += controller.rightThumbY / 5; // slow
// キーでのパラパラめくり// 早送り巻き戻しメタファー
if (Input::KeyRight.clicked) {
if (autoplaySpeed > 0) {
autoplaySpeed *= 2;
}
else if (autoplaySpeed == 0) {
autoplaySpeed = 1;
}
else {
autoplaySpeed = 0;
}
}
if (Input::KeyLeft.clicked) {
if (autoplaySpeed < 0) {
autoplaySpeed *= 2;
}
else if (autoplaySpeed == 0) {
autoplaySpeed = -1;
}
else {
autoplaySpeed = 0;
}
}
if (autoplaySpeed) {
viewingPage += autoplaySpeed * invFPS / 1000;
font10(L"自動再生: ", autoplaySpeed).draw(0, 0);
}
if (viewingPage < 0) viewingPage = 0;
if (viewingPage > numPages - 1) viewingPage = numPages - 1;
if (displayMode == 0) {
if (controller.buttonA.clicked || Input::KeyDown.clicked) viewingPage += 0.5;
if (controller.buttonB.clicked || Input::KeyUp.clicked) viewingPage -= 0.5;
}
else {
if (controller.buttonA.clicked || Input::KeyDown.clicked) {
viewingPage++;
autoplaySpeed = 0;
}
if (controller.buttonB.clicked || Input::KeyUp.clicked) {
viewingPage--;
autoplaySpeed = 0;
}
}
// 最初・最後のページで前後に移動した時に反対側に飛ぶべきかどうか、今disabled
//if (page < 0) page += numPages;
//if (page > numPages - 1) page = 0;
if (viewingPage < 0) viewingPage = 0;
if (viewingPage > numPages - 1) viewingPage = numPages - 1;
int ipage = static_cast<int>(viewingPage) % numPages;
if (controller.buttonLB.clicked || Input::KeyZ.clicked) {
displayMode = (displayMode - 1);
if (displayMode < 0) displayMode = 0;
}
if (controller.buttonRB.clicked || Input::KeyC.clicked) {
displayMode = (displayMode + 1);
}
Texture t = loader::getPage(ipage);
double h = static_cast<double>(t.height);
double w = static_cast<double>(t.width);
const int screenHeight = 640;
double pageHeight = screenHeight, pageWidth = w / h * pageHeight;
int horizontalMultiplier = 2; // 見開きにするなら2、しないなら1
if (h < w) horizontalMultiplier = 1;
// draw progress bar
int progressBarWidth = static_cast<int>(pageWidth * horizontalMultiplier);
Rect(drawingXOffset, screenHeight + 10,
progressBarWidth, 20).draw(Color(200));
Rect(drawingXOffset, screenHeight + 12,
progressBarWidth * (ipage + 1) / numPages, 16).draw(Color(100));
font10(ipage + 1).draw(drawingXOffset, screenHeight + 12);
const int32 w2 = font10(numPages).region().w;
font10(numPages).draw(drawingXOffset + progressBarWidth - w2, screenHeight + 12);
if (displayMode == 0) {
// Zoom-in mode
int scale = 2;
if (static_cast<int>(viewingPage * 2) % 2 == 0) {
t.resize(pageWidth * scale, pageHeight * scale).draw(drawingXOffset, 0);
}
else {
t(0, h / 2, w, h / 2).resize(pageWidth * scale, pageHeight).draw(drawingXOffset, 0);
}
}
else if(displayMode > 0) {
int numPageHorizontal = displayMode * horizontalMultiplier;
int numPageVertical = displayMode;
// Tile mode
if (displayOrder == L"LTR") {
pageHeight /= numPageVertical;
pageWidth /= numPageVertical;
for (int y = 0; y < numPageVertical; y++) {
for (int x = 0; x < numPageHorizontal; x++) {
int i = ipage + y * numPageHorizontal + x;
loader::getPage(i)
.resize(pageWidth, pageHeight)
.draw(drawingXOffset + pageWidth * x, pageHeight * y);
}
}
}
else {
pageHeight /= numPageVertical;
pageWidth /= numPageVertical;
for (int y = 0; y < numPageVertical; y++) {
for (int x = 0; x < numPageHorizontal; x++) {
int i = ipage + y * numPageHorizontal + x;
loader::getPage(i)
.resize(pageWidth, pageHeight)
.draw(drawingXOffset + pageWidth * (numPageHorizontal - x - 1), pageHeight * y);
}
}
}
// Xボタンでそのページを通常表示
if (controller.buttonX.clicked || Input::MouseL.clicked) {
if (Input::MouseL.clicked) {
pos = Mouse::Pos();
}
int x = static_cast<int>((pos.x - drawingXOffset) / pageWidth);
if (displayOrder != L"LTR") {
x = numPageHorizontal - x - 1;
}
int y = static_cast<int>(pos.y / pageHeight);
viewingPage = ipage + x + y * numPageHorizontal;
displayMode = 1;
Cursor::SetPos(0, 0);
pos = { 0, 0 };
}
}
// デモ用
if (controller.buttonY.clicked || Input::KeyY.clicked) {
loadNewDocument(sampleDocument);
}
// カーソル表示
Circle(pos, 10).draw({ 255, 255, 0, 127 });
}
}
|
// main.cc
#include "lib.h"
#include "log.h"
#include "CommandInput.h"
#include "CommandOutput.h"
#include "Command.h"
#include "Time.h"
#include "Connection.h"
#include "Sensor.h"
#include "TrafficModel.h"
#include "KernelTcp.h"
#include "DirectInput.h"
#include "TrivialCommandOutput.h"
#include <iostream>
using namespace std;
namespace global
{
int connectionModelArg = 0;
unsigned short peerServerPort = 0;
unsigned short monitorServerPort = 0;
bool doDaemonize = false;
int replayArg = NO_REPLAY;
int replayfd = -1;
list<int> replaySensors;
int peerAccept = -1;
string interface;
auto_ptr<ConnectionModel> connectionModelExemplar;
list< pair<int, string> > peers;
map<Order, Connection> connections;
// A connection is in this map only if it is currently connected.
map<Order, Connection *> planetMap;
fd_set readers;
int maxReader = -1;
std::auto_ptr<CommandInput> input;
std::auto_ptr<CommandOutput> output;
}
void usageMessage(char *progname);
void processArgs(int argc, char * argv[]);
void init(void);
void mainLoop(void);
void replayLoop(void);
void writeToConnections(multimap<Time, Connection *> & schedule);
void addNewPeer(fd_set * readable);
void readFromPeers(fd_set * readable);
void packetCapture(fd_set * readable);
void exitHandler(int signal);
int main(int argc, char * argv[])
{
umask(0);
processArgs(argc, argv);
init();
if (global::doDaemonize)
{
// Run with no change in directory, and no closing of standard files.
int error = daemon(1, 1);
if (error == -1)
{
logWrite(ERROR, "Daemonization failed: %s", strerror(errno));
}
}
if (global::replayArg == REPLAY_LOAD)
{
replayLoop();
}
else
{
mainLoop();
}
return 0;
}
void usageMessage(char *progname)
{
cerr << "Usage: " << progname << " [options]" << endl;
cerr << " --connectionmodel=<null|kerneltcp> " << endl;
cerr << " --peerserverport=<int> " << endl;
cerr << " --monitorserverport=<int> " << endl;
cerr << " --interface=<iface> " << endl;
cerr << " --daemonize " << endl;
cerr << " --replay-save=<filename> " << endl;
cerr << " --replay-load=<filename> " << endl;
cerr << " --replay-sensor=<null|state|packet|delay|min-delay|max-delay|throughput|ewma-throughput>" << endl;
logWrite(ERROR, "Bad command line argument", global::connectionModelArg);
}
void processArgs(int argc, char * argv[])
{
// Defaults, in case the user does not pass us explicit values
global::connectionModelArg = CONNECTION_MODEL_KERNEL;
global::peerServerPort = 3491;
global::monitorServerPort = 4200;
global::interface = "vnet";
global::doDaemonize = false;
global::replayArg = NO_REPLAY;
global::replayfd = -1;
static struct option longOptions[] = {
// If you modify this, make sure to modify the shortOptions string below
// too.
{"connectionmodel", required_argument, NULL, 'c'},
{"peerserverport", required_argument, NULL, 'p'},
{"monitorserverport", required_argument, NULL, 'm'},
{"interface", required_argument, NULL, 'i'},
{"daemonize", no_argument , NULL, 'd'},
{"replay-save", required_argument, NULL, 's'},
{"replay-load", required_argument, NULL, 'l'},
{"replay-sensor", required_argument, NULL, 'n'},
// Required so that getopt_long can find the end of the list
{NULL, 0, NULL, 0}
};
string shortOptions = "c:p:m:i:ds:l:";
// Not used
int longIndex;
// Loop until all options have been handled
while (true)
{
int ch =
getopt_long(argc, argv, shortOptions.c_str(), longOptions, &longIndex);
// Detect end of options
if (ch == -1)
{
break;
}
int argIntVal;
// Make a copy of optarg that's more c++-y.
string optArg;
if (optarg != NULL)
{
optArg = optarg;
}
switch ((char) ch)
{
case 'c':
if (optArg == "null") {
global::connectionModelArg = CONNECTION_MODEL_NULL;
}
else if (optArg == "kerneltcp")
{
global::connectionModelArg = CONNECTION_MODEL_KERNEL;
}
else
{
usageMessage(argv[0]);
exit(1);
}
break;
case 'p':
if (sscanf(optarg,"%i",&argIntVal))
{
usageMessage(argv[0]);
exit(1);
}
else
{
global::peerServerPort = argIntVal;
}
break;
case 'm':
if (sscanf(optarg,"%i",&argIntVal))
{
usageMessage(argv[0]);
exit(1);
}
else
{
global::monitorServerPort = argIntVal;
}
break;
case 'i':
global::interface = optArg;
break;
case 'd':
global::doDaemonize = true;
break;
case 's':
if (global::replayArg == NO_REPLAY)
{
global::replayfd = open(optarg, O_WRONLY | O_CREAT | O_TRUNC,
S_IRWXU | S_IRWXG | S_IRWXO);
if (global::replayfd != -1)
{
global::replayArg = REPLAY_SAVE;
}
else
{
fprintf(stderr,"Error opening replay-save file: %s: %s\n", optarg,
strerror(errno));
exit(1);
}
}
else
{
fprintf(stderr, "replay-save option was invoked when replay "
"was already set\n");
exit(1);
}
break;
case 'l':
if (global::replayArg == NO_REPLAY)
{
global::replayfd = open(optarg, O_RDONLY);
if (global::replayfd != -1)
{
global::replayArg = REPLAY_LOAD;
}
else
{
fprintf(stderr, "Error opening replay-load file: %s: %s\n", optarg,
strerror(errno));
exit(1);
}
}
else
{
fprintf(stderr, "replay-load option was invoked when replay "
"was already set\n");
exit(1);
}
break;
case 'n':
if (optArg == "null")
{
global::replaySensors.push_back(NULL_SENSOR);
}
else if (optArg == "state")
{
global::replaySensors.push_back(STATE_SENSOR);
}
else if (optArg == "packet")
{
global::replaySensors.push_back(PACKET_SENSOR);
}
else if (optArg == "delay")
{
global::replaySensors.push_back(DELAY_SENSOR);
}
else if (optArg == "min-delay")
{
global::replaySensors.push_back(MIN_DELAY_SENSOR);
}
else if (optArg == "max-delay")
{
global::replaySensors.push_back(MAX_DELAY_SENSOR);
}
else if (optArg == "throughput")
{
global::replaySensors.push_back(THROUGHPUT_SENSOR);
}
else if (optArg == "ewma-throughput")
{
global::replaySensors.push_back(EWMA_THROUGHPUT_SENSOR);
}
else
{
usageMessage(argv[0]);
exit(1);
}
break;
case '?':
default:
usageMessage(argv[0]);
exit(1);
}
}
}
void init(void)
{
FD_ZERO(&global::readers);
global::maxReader = -1;
logInit(stderr, LOG_EVERYTHING, true);
/*
* Install a signal handler so that we can catch control-C's, etc.
*/;
struct sigaction action;
action.sa_handler = exitHandler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGTERM,&action,NULL);
sigaction(SIGINT,&action,NULL);
/*
* Make sure we leave a core dump if we crash
*/
struct rlimit limit;
limit.rlim_cur = RLIM_INFINITY;
limit.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE,&limit)) {
logWrite(ERROR,"Unable to set core dump size!");
}
srandom(getpid());
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::init();
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::init();
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt at initialization (%d)."
"Terminating program.", global::connectionModelArg);
}
if (global::replayArg == REPLAY_LOAD)
{
global::input.reset(new NullCommandInput());
global::output.reset(new NullCommandOutput());
}
else
{
global::input.reset(new DirectInput());
global::output.reset(new TrivialCommandOutput());
}
}
void mainLoop(void)
{
multimap<Time, Connection *> schedule;
fd_set readable;
FD_ZERO(&readable);
// Select on file descriptors
while (true)
{
// struct timeval debugTimeout;
// debugTimeout.tv_sec = 0;
// debugTimeout.tv_usec = 100000;
readable = global::readers;
Time timeUntilWrite;
struct timeval * waitPeriod;
Time now = getCurrentTime();
multimap<Time, Connection *>::iterator nextWrite = schedule.begin();
if (nextWrite != schedule.end() && now < nextWrite->first)
{
timeUntilWrite = nextWrite->first - now;
waitPeriod = timeUntilWrite.getTimeval();
}
else
{
// otherwise we want to wait forever.
timeUntilWrite = Time();
waitPeriod = NULL;
}
int error = select(global::maxReader + 1, &readable, NULL, NULL,
// &debugTimeout);
waitPeriod);
if (error == -1)
{
switch (errno)
{
case EBADF:
case EINVAL:
logWrite(ERROR, "Select failed due to improper inputs. "
"Unable to continue: %s", strerror(errno));
exit(1);
break;
case EINTR:
case ENOMEM:
default:
logWrite(EXCEPTION, "Select failed. We may not be able to continue. "
"Retrying: %s", strerror(errno));
continue;
break;
}
}
global::input->nextCommand(&readable);
Command * current = global::input->getCommand();
if (current != NULL)
{
current->run(schedule);
// global::input->nextCommand(&readable);
// current = global::input->getCommand();
}
writeToConnections(schedule);
addNewPeer(&readable);
readFromPeers(&readable);
packetCapture(&readable);
}
}
// Returns true on success
bool replayWrite(char * source, int size)
{
bool result = true;
if (size == 0) {
return true;
}
int error = write(global::replayfd, source, size);
if (error <= 0)
{
if (error == 0)
{
logWrite(EXCEPTION, "replayfd was closed unexpectedly");
}
else if (error == -1)
{
logWrite(EXCEPTION, "Error writing replay output: %s", strerror(errno));
}
result = false;
}
return result;
}
void replayWriteCommand(char * head, char * body, unsigned short bodySize)
{
bool success = true;
success = replayWrite(head, Header::headerSize);
if (success)
{
replayWrite(body, bodySize);
}
}
void replayWritePacket(PacketInfo * packet)
{
Header head;
head.type = packet->packetType;
head.size = packet->census();
head.key = packet->elab;
char headBuffer[Header::headerSize];
saveHeader(headBuffer, head);
bool success = replayWrite(headBuffer, Header::headerSize);
if (success)
{
char *packetBuffer;
packetBuffer = static_cast<char*>(malloc(head.size));
//logWrite(REPLAY,"Making a packet buffer of size %d",head.size);
char* endptr = savePacket(& packetBuffer[0], *packet);
// find out how many bytes were written
int writtensize = (endptr - packetBuffer);
if (writtensize != head.size) {
logWrite(ERROR,"replayWritePacket(): Made packet save buffer of size "
"%d, but wrote %d", head.size, writtensize);
}
replayWrite(& packetBuffer[0], head.size);
free(packetBuffer);
}
}
// Returns true on success
bool replayRead(char * dest, int size)
{
bool result = true;
int error = read(global::replayfd, dest, size);
if (error <= 0)
{
if (error == 0)
{
logWrite(EXCEPTION, "End of replay input");
}
else if (error == -1)
{
logWrite(EXCEPTION, "Error reading replay input: %s", strerror(errno));
}
result = false;
}
return result;
}
void replayLoop(void)
{
bool done = false;
char headerBuffer[Header::headerSize];
Header head;
vector<char> packetBuffer;
struct tcp_info kernel;
struct ip ip;
list<Option> ipOptions;
struct tcphdr tcp;
list<Option> tcpOptions;
PacketInfo packet;
map<Order, SensorList> streams;
done = ! replayRead(headerBuffer, Header::headerSize);
while (!done)
{
loadHeader(headerBuffer, &head);
packetBuffer.resize(head.size);
switch(head.type)
{
case NEW_CONNECTION_COMMAND:
{
map<Order, SensorList>::iterator current =
streams.insert(make_pair(head.key, SensorList())).first;
list<int>::iterator pos = global::replaySensors.begin();
list<int>::iterator limit = global::replaySensors.end();
SensorCommand tempSensor;
for (; pos != limit; ++pos)
{
tempSensor.type = *pos;
current->second.addSensor(tempSensor);
}
}
break;
case DELETE_CONNECTION_COMMAND:
streams.erase(head.key);
break;
case SENSOR_COMMAND:
done = ! replayRead(& packetBuffer[0], sizeof(int));
if (!done)
{
if (global::replaySensors.empty())
{
unsigned int sensorType = 0;
loadInt(& packetBuffer[0], & sensorType);
SensorCommand sensor;
sensor.type = sensorType;
streams[head.key].addSensor(sensor);
}
}
break;
case PACKET_INFO_SEND_COMMAND:
case PACKET_INFO_ACK_COMMAND:
logWrite(EXCEPTION,"Got a packet: %d",head.type);
done = ! replayRead(& packetBuffer[0], head.size);
if (!done)
{
loadPacket(& packetBuffer[0], &packet, kernel, ip, tcp, ipOptions,
tcpOptions);
Sensor * sensorHead = streams[head.key].getHead();
if (sensorHead != NULL)
{
sensorHead->capturePacket(&packet);
}
}
break;
default:
logWrite(ERROR, "Invalid command type in replay input: %d", head.type);
done = true;
break;
}
if (!done)
{
done = ! replayRead(headerBuffer, Header::headerSize);
}
}
}
void writeToConnections(multimap<Time, Connection *> & schedule)
{
Time now = getCurrentTime();
// bool done = false;
// Notify any connection which is due, then erase that entry from
// the schedule and insert another entry at the new time specified
// by the connection.
// while (! schedule.empty() && !done)
if (! schedule.empty())
{
multimap<Time, Connection *>::iterator pos = schedule.begin();
if (pos->first < now)
{
Connection * current = pos->second;
Time nextTime = current->writeToConnection(pos->first);
schedule.erase(pos);
if (nextTime != Time())
{
schedule.insert(make_pair(nextTime, current));
}
}
// else
// {
// done = true;
// }
}
}
void addNewPeer(fd_set * readable)
{
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::addNewPeer(readable);
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::addNewPeer(readable);
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt (%d). "
"No further peers will be accepted.", global::connectionModelArg);
break;
}
}
void readFromPeers(fd_set * readable)
{
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::readFromPeers(readable);
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::readFromPeers(readable);
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt (%d). "
"I can no longer read from current peers.",
global::connectionModelArg);
break;
}
}
void packetCapture(fd_set * readable)
{
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::packetCapture(readable);
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::packetCapture(readable);
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt (%d). "
"I can no longer capture packets sent to peers.",
global::connectionModelArg);
break;
}
}
void setDescriptor(int fd)
{
if (fd > -1 && fd < FD_SETSIZE)
{
FD_SET(fd, &(global::readers));
if (fd > global::maxReader)
{
global::maxReader = fd;
}
}
else
{
logWrite(ERROR, "Invalid descriptor sent to setDescriptor: "
"%d (FDSET_SIZE=%d)", fd, FD_SETSIZE);
}
}
void clearDescriptor(int fd)
{
if (fd > -1 && fd < FD_SETSIZE)
{
FD_CLR(fd, &(global::readers));
if (fd > global::maxReader)
{
global::maxReader = fd;
}
}
else
{
logWrite(ERROR, "Invalid descriptor sent to clearDescriptor: "
"%d (FDSET_SIZE=%d)", fd, FD_SETSIZE);
}
}
string ipToString(unsigned int ip)
{
struct in_addr address;
address.s_addr = ip;
return string(inet_ntoa(address));
}
int createServer(int port, string const & debugString)
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
logWrite(ERROR, "socket(): %s: %s", debugString.c_str(), strerror(errno));
return -1;
}
int doesReuse = 1;
int error = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &doesReuse,
sizeof(doesReuse));
if (error == -1)
{
logWrite(ERROR, "setsockopt(SO_REUSEADDR): %s: %s", debugString.c_str(),
strerror(errno));
close(fd);
return -1;
}
int forcedSize = 262144;
error = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &forcedSize,
sizeof(forcedSize));
if (error == -1)
{
logWrite(ERROR, "Failed to set receive buffer size: %s",
strerror(errno));
close(fd);
return -1;
}
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = htonl(INADDR_ANY);
error = bind(fd, reinterpret_cast<struct sockaddr *>(&address),
sizeof(address));
if (error == -1)
{
logWrite(ERROR, "bind(): %s: %s", debugString.c_str(), strerror(errno));
close(fd);
return -1;
}
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
{
logWrite(ERROR, "fcntl(F_GETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(fd);
return -1;
}
error = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (error == -1)
{
logWrite(ERROR, "fcntl(F_SETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(fd);
return -1;
}
error = listen(fd, 4);
if (error == -1)
{
logWrite(ERROR, "listen(): %s: %s", debugString.c_str(), strerror(errno));
close(fd);
return -1;
}
setDescriptor(fd);
return fd;
}
int acceptServer(int acceptfd, struct sockaddr_in * remoteAddress,
string const & debugString)
{
struct sockaddr_in stackAddress;
struct sockaddr_in * address;
socklen_t addressSize = sizeof(struct sockaddr_in);
if (remoteAddress == NULL)
{
address = &stackAddress;
}
else
{
address = remoteAddress;
}
int resultfd = accept(acceptfd,
reinterpret_cast<struct sockaddr *>(address),
&addressSize);
if (resultfd == -1)
{
if (errno != EINTR && errno != EWOULDBLOCK && errno != ECONNABORTED
&& errno != EPROTO)
{
logWrite(EXCEPTION, "accept(): %s: %s", debugString.c_str(),
strerror(errno));
}
return -1;
}
int flags = fcntl(resultfd, F_GETFL, 0);
if (flags == -1)
{
logWrite(EXCEPTION, "fcntl(F_GETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(resultfd);
return -1;
}
int error = fcntl(resultfd, F_SETFL, flags | O_NONBLOCK);
if (error == -1)
{
logWrite(EXCEPTION, "fcntl(F_SETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(resultfd);
return -1;
}
setDescriptor(resultfd);
return resultfd;
}
void exitHandler(int signal) {
logWrite(EXCEPTION,"Killed with signal %i, cleaning up",signal);
exit(0);
}
size_t PacketInfo::census(void) const
{
/* TODO: Remove this old code. It is too easy to get wrong.
// packetTime + packetLength
size_t result = sizeof(int)*(2+1) +
sizeof(struct tcp_info) +
sizeof(struct ip) + sizeof(struct tcphdr)
+ sizeof(unsigned char) // bufferFull
+ sizeof(unsigned char) // packetType
+ sizeof(unsigned char) + sizeof(int) + 2*sizeof(short); // elab
// Size for ipOptions and tcpOptions.
result += sizeof(unsigned int)*2;
std::list<Option>::iterator pos = ipOptions->begin();
std::list<Option>::iterator limit = ipOptions->end();
for (; pos != limit; ++pos)
{
result += 2 + pos->length;
}
pos = tcpOptions->begin();
limit = tcpOptions->end();
for (; pos != limit; ++pos)
{
result += 2 + pos->length;
}
return result;
*/
savePacket(NULL, *this);
return static_cast<size_t>(getLastSaveloadSize());
}
Add the ability to run the least-squares throughput sensor from the
command-line.
// main.cc
#include "lib.h"
#include "log.h"
#include "CommandInput.h"
#include "CommandOutput.h"
#include "Command.h"
#include "Time.h"
#include "Connection.h"
#include "Sensor.h"
#include "TrafficModel.h"
#include "KernelTcp.h"
#include "DirectInput.h"
#include "TrivialCommandOutput.h"
#include <iostream>
using namespace std;
namespace global
{
int connectionModelArg = 0;
unsigned short peerServerPort = 0;
unsigned short monitorServerPort = 0;
bool doDaemonize = false;
int replayArg = NO_REPLAY;
int replayfd = -1;
list<int> replaySensors;
int peerAccept = -1;
string interface;
auto_ptr<ConnectionModel> connectionModelExemplar;
list< pair<int, string> > peers;
map<Order, Connection> connections;
// A connection is in this map only if it is currently connected.
map<Order, Connection *> planetMap;
fd_set readers;
int maxReader = -1;
std::auto_ptr<CommandInput> input;
std::auto_ptr<CommandOutput> output;
}
void usageMessage(char *progname);
void processArgs(int argc, char * argv[]);
void init(void);
void mainLoop(void);
void replayLoop(void);
void writeToConnections(multimap<Time, Connection *> & schedule);
void addNewPeer(fd_set * readable);
void readFromPeers(fd_set * readable);
void packetCapture(fd_set * readable);
void exitHandler(int signal);
int main(int argc, char * argv[])
{
umask(0);
processArgs(argc, argv);
init();
if (global::doDaemonize)
{
// Run with no change in directory, and no closing of standard files.
int error = daemon(1, 1);
if (error == -1)
{
logWrite(ERROR, "Daemonization failed: %s", strerror(errno));
}
}
if (global::replayArg == REPLAY_LOAD)
{
replayLoop();
}
else
{
mainLoop();
}
return 0;
}
void usageMessage(char *progname)
{
cerr << "Usage: " << progname << " [options]" << endl;
cerr << " --connectionmodel=<null|kerneltcp> " << endl;
cerr << " --peerserverport=<int> " << endl;
cerr << " --monitorserverport=<int> " << endl;
cerr << " --interface=<iface> " << endl;
cerr << " --daemonize " << endl;
cerr << " --replay-save=<filename> " << endl;
cerr << " --replay-load=<filename> " << endl;
cerr << " --replay-sensor=<null|state|packet|delay|min-delay|max-delay|throughput|ewma-throughput|leastsquares-throughput>" << endl;
logWrite(ERROR, "Bad command line argument", global::connectionModelArg);
}
void processArgs(int argc, char * argv[])
{
// Defaults, in case the user does not pass us explicit values
global::connectionModelArg = CONNECTION_MODEL_KERNEL;
global::peerServerPort = 3491;
global::monitorServerPort = 4200;
global::interface = "vnet";
global::doDaemonize = false;
global::replayArg = NO_REPLAY;
global::replayfd = -1;
static struct option longOptions[] = {
// If you modify this, make sure to modify the shortOptions string below
// too.
{"connectionmodel", required_argument, NULL, 'c'},
{"peerserverport", required_argument, NULL, 'p'},
{"monitorserverport", required_argument, NULL, 'm'},
{"interface", required_argument, NULL, 'i'},
{"daemonize", no_argument , NULL, 'd'},
{"replay-save", required_argument, NULL, 's'},
{"replay-load", required_argument, NULL, 'l'},
{"replay-sensor", required_argument, NULL, 'n'},
// Required so that getopt_long can find the end of the list
{NULL, 0, NULL, 0}
};
string shortOptions = "c:p:m:i:ds:l:";
// Not used
int longIndex;
// Loop until all options have been handled
while (true)
{
int ch =
getopt_long(argc, argv, shortOptions.c_str(), longOptions, &longIndex);
// Detect end of options
if (ch == -1)
{
break;
}
int argIntVal;
// Make a copy of optarg that's more c++-y.
string optArg;
if (optarg != NULL)
{
optArg = optarg;
}
switch ((char) ch)
{
case 'c':
if (optArg == "null") {
global::connectionModelArg = CONNECTION_MODEL_NULL;
}
else if (optArg == "kerneltcp")
{
global::connectionModelArg = CONNECTION_MODEL_KERNEL;
}
else
{
usageMessage(argv[0]);
exit(1);
}
break;
case 'p':
if (sscanf(optarg,"%i",&argIntVal))
{
usageMessage(argv[0]);
exit(1);
}
else
{
global::peerServerPort = argIntVal;
}
break;
case 'm':
if (sscanf(optarg,"%i",&argIntVal))
{
usageMessage(argv[0]);
exit(1);
}
else
{
global::monitorServerPort = argIntVal;
}
break;
case 'i':
global::interface = optArg;
break;
case 'd':
global::doDaemonize = true;
break;
case 's':
if (global::replayArg == NO_REPLAY)
{
global::replayfd = open(optarg, O_WRONLY | O_CREAT | O_TRUNC,
S_IRWXU | S_IRWXG | S_IRWXO);
if (global::replayfd != -1)
{
global::replayArg = REPLAY_SAVE;
}
else
{
fprintf(stderr,"Error opening replay-save file: %s: %s\n", optarg,
strerror(errno));
exit(1);
}
}
else
{
fprintf(stderr, "replay-save option was invoked when replay "
"was already set\n");
exit(1);
}
break;
case 'l':
if (global::replayArg == NO_REPLAY)
{
global::replayfd = open(optarg, O_RDONLY);
if (global::replayfd != -1)
{
global::replayArg = REPLAY_LOAD;
}
else
{
fprintf(stderr, "Error opening replay-load file: %s: %s\n", optarg,
strerror(errno));
exit(1);
}
}
else
{
fprintf(stderr, "replay-load option was invoked when replay "
"was already set\n");
exit(1);
}
break;
case 'n':
if (optArg == "null")
{
global::replaySensors.push_back(NULL_SENSOR);
}
else if (optArg == "state")
{
global::replaySensors.push_back(STATE_SENSOR);
}
else if (optArg == "packet")
{
global::replaySensors.push_back(PACKET_SENSOR);
}
else if (optArg == "delay")
{
global::replaySensors.push_back(DELAY_SENSOR);
}
else if (optArg == "min-delay")
{
global::replaySensors.push_back(MIN_DELAY_SENSOR);
}
else if (optArg == "max-delay")
{
global::replaySensors.push_back(MAX_DELAY_SENSOR);
}
else if (optArg == "throughput")
{
global::replaySensors.push_back(THROUGHPUT_SENSOR);
}
else if (optArg == "ewma-throughput")
{
global::replaySensors.push_back(EWMA_THROUGHPUT_SENSOR);
}
else if (optArg == "leastsquares-throughput")
{
global::replaySensors.push_back(LEAST_SQUARES_THROUGHPUT);
}
else
{
usageMessage(argv[0]);
exit(1);
}
break;
case '?':
default:
usageMessage(argv[0]);
exit(1);
}
}
}
void init(void)
{
FD_ZERO(&global::readers);
global::maxReader = -1;
logInit(stderr, LOG_EVERYTHING, true);
/*
* Install a signal handler so that we can catch control-C's, etc.
*/;
struct sigaction action;
action.sa_handler = exitHandler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGTERM,&action,NULL);
sigaction(SIGINT,&action,NULL);
/*
* Make sure we leave a core dump if we crash
*/
struct rlimit limit;
limit.rlim_cur = RLIM_INFINITY;
limit.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE,&limit)) {
logWrite(ERROR,"Unable to set core dump size!");
}
srandom(getpid());
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::init();
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::init();
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt at initialization (%d)."
"Terminating program.", global::connectionModelArg);
}
if (global::replayArg == REPLAY_LOAD)
{
global::input.reset(new NullCommandInput());
global::output.reset(new NullCommandOutput());
}
else
{
global::input.reset(new DirectInput());
global::output.reset(new TrivialCommandOutput());
}
}
void mainLoop(void)
{
multimap<Time, Connection *> schedule;
fd_set readable;
FD_ZERO(&readable);
// Select on file descriptors
while (true)
{
// struct timeval debugTimeout;
// debugTimeout.tv_sec = 0;
// debugTimeout.tv_usec = 100000;
readable = global::readers;
Time timeUntilWrite;
struct timeval * waitPeriod;
Time now = getCurrentTime();
multimap<Time, Connection *>::iterator nextWrite = schedule.begin();
if (nextWrite != schedule.end() && now < nextWrite->first)
{
timeUntilWrite = nextWrite->first - now;
waitPeriod = timeUntilWrite.getTimeval();
}
else
{
// otherwise we want to wait forever.
timeUntilWrite = Time();
waitPeriod = NULL;
}
int error = select(global::maxReader + 1, &readable, NULL, NULL,
// &debugTimeout);
waitPeriod);
if (error == -1)
{
switch (errno)
{
case EBADF:
case EINVAL:
logWrite(ERROR, "Select failed due to improper inputs. "
"Unable to continue: %s", strerror(errno));
exit(1);
break;
case EINTR:
case ENOMEM:
default:
logWrite(EXCEPTION, "Select failed. We may not be able to continue. "
"Retrying: %s", strerror(errno));
continue;
break;
}
}
global::input->nextCommand(&readable);
Command * current = global::input->getCommand();
if (current != NULL)
{
current->run(schedule);
// global::input->nextCommand(&readable);
// current = global::input->getCommand();
}
writeToConnections(schedule);
addNewPeer(&readable);
readFromPeers(&readable);
packetCapture(&readable);
}
}
// Returns true on success
bool replayWrite(char * source, int size)
{
bool result = true;
if (size == 0) {
return true;
}
int error = write(global::replayfd, source, size);
if (error <= 0)
{
if (error == 0)
{
logWrite(EXCEPTION, "replayfd was closed unexpectedly");
}
else if (error == -1)
{
logWrite(EXCEPTION, "Error writing replay output: %s", strerror(errno));
}
result = false;
}
return result;
}
void replayWriteCommand(char * head, char * body, unsigned short bodySize)
{
bool success = true;
success = replayWrite(head, Header::headerSize);
if (success)
{
replayWrite(body, bodySize);
}
}
void replayWritePacket(PacketInfo * packet)
{
Header head;
head.type = packet->packetType;
head.size = packet->census();
head.key = packet->elab;
char headBuffer[Header::headerSize];
saveHeader(headBuffer, head);
bool success = replayWrite(headBuffer, Header::headerSize);
if (success)
{
char *packetBuffer;
packetBuffer = static_cast<char*>(malloc(head.size));
//logWrite(REPLAY,"Making a packet buffer of size %d",head.size);
char* endptr = savePacket(& packetBuffer[0], *packet);
// find out how many bytes were written
int writtensize = (endptr - packetBuffer);
if (writtensize != head.size) {
logWrite(ERROR,"replayWritePacket(): Made packet save buffer of size "
"%d, but wrote %d", head.size, writtensize);
}
replayWrite(& packetBuffer[0], head.size);
free(packetBuffer);
}
}
// Returns true on success
bool replayRead(char * dest, int size)
{
bool result = true;
int error = read(global::replayfd, dest, size);
if (error <= 0)
{
if (error == 0)
{
logWrite(EXCEPTION, "End of replay input");
}
else if (error == -1)
{
logWrite(EXCEPTION, "Error reading replay input: %s", strerror(errno));
}
result = false;
}
return result;
}
void replayLoop(void)
{
bool done = false;
char headerBuffer[Header::headerSize];
Header head;
vector<char> packetBuffer;
struct tcp_info kernel;
struct ip ip;
list<Option> ipOptions;
struct tcphdr tcp;
list<Option> tcpOptions;
PacketInfo packet;
map<Order, SensorList> streams;
done = ! replayRead(headerBuffer, Header::headerSize);
while (!done)
{
loadHeader(headerBuffer, &head);
packetBuffer.resize(head.size);
switch(head.type)
{
case NEW_CONNECTION_COMMAND:
{
map<Order, SensorList>::iterator current =
streams.insert(make_pair(head.key, SensorList())).first;
list<int>::iterator pos = global::replaySensors.begin();
list<int>::iterator limit = global::replaySensors.end();
SensorCommand tempSensor;
for (; pos != limit; ++pos)
{
tempSensor.type = *pos;
current->second.addSensor(tempSensor);
}
}
break;
case DELETE_CONNECTION_COMMAND:
streams.erase(head.key);
break;
case SENSOR_COMMAND:
done = ! replayRead(& packetBuffer[0], sizeof(int));
if (!done)
{
if (global::replaySensors.empty())
{
unsigned int sensorType = 0;
loadInt(& packetBuffer[0], & sensorType);
SensorCommand sensor;
sensor.type = sensorType;
streams[head.key].addSensor(sensor);
}
}
break;
case PACKET_INFO_SEND_COMMAND:
case PACKET_INFO_ACK_COMMAND:
logWrite(EXCEPTION,"Got a packet: %d",head.type);
done = ! replayRead(& packetBuffer[0], head.size);
if (!done)
{
loadPacket(& packetBuffer[0], &packet, kernel, ip, tcp, ipOptions,
tcpOptions);
Sensor * sensorHead = streams[head.key].getHead();
if (sensorHead != NULL)
{
sensorHead->capturePacket(&packet);
}
}
break;
default:
logWrite(ERROR, "Invalid command type in replay input: %d", head.type);
done = true;
break;
}
if (!done)
{
done = ! replayRead(headerBuffer, Header::headerSize);
}
}
}
void writeToConnections(multimap<Time, Connection *> & schedule)
{
Time now = getCurrentTime();
// bool done = false;
// Notify any connection which is due, then erase that entry from
// the schedule and insert another entry at the new time specified
// by the connection.
// while (! schedule.empty() && !done)
if (! schedule.empty())
{
multimap<Time, Connection *>::iterator pos = schedule.begin();
if (pos->first < now)
{
Connection * current = pos->second;
Time nextTime = current->writeToConnection(pos->first);
schedule.erase(pos);
if (nextTime != Time())
{
schedule.insert(make_pair(nextTime, current));
}
}
// else
// {
// done = true;
// }
}
}
void addNewPeer(fd_set * readable)
{
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::addNewPeer(readable);
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::addNewPeer(readable);
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt (%d). "
"No further peers will be accepted.", global::connectionModelArg);
break;
}
}
void readFromPeers(fd_set * readable)
{
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::readFromPeers(readable);
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::readFromPeers(readable);
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt (%d). "
"I can no longer read from current peers.",
global::connectionModelArg);
break;
}
}
void packetCapture(fd_set * readable)
{
switch (global::connectionModelArg)
{
case CONNECTION_MODEL_NULL:
ConnectionModelNull::packetCapture(readable);
break;
case CONNECTION_MODEL_KERNEL:
KernelTcp::packetCapture(readable);
break;
default:
logWrite(ERROR, "connectionModelArg is corrupt (%d). "
"I can no longer capture packets sent to peers.",
global::connectionModelArg);
break;
}
}
void setDescriptor(int fd)
{
if (fd > -1 && fd < FD_SETSIZE)
{
FD_SET(fd, &(global::readers));
if (fd > global::maxReader)
{
global::maxReader = fd;
}
}
else
{
logWrite(ERROR, "Invalid descriptor sent to setDescriptor: "
"%d (FDSET_SIZE=%d)", fd, FD_SETSIZE);
}
}
void clearDescriptor(int fd)
{
if (fd > -1 && fd < FD_SETSIZE)
{
FD_CLR(fd, &(global::readers));
if (fd > global::maxReader)
{
global::maxReader = fd;
}
}
else
{
logWrite(ERROR, "Invalid descriptor sent to clearDescriptor: "
"%d (FDSET_SIZE=%d)", fd, FD_SETSIZE);
}
}
string ipToString(unsigned int ip)
{
struct in_addr address;
address.s_addr = ip;
return string(inet_ntoa(address));
}
int createServer(int port, string const & debugString)
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
logWrite(ERROR, "socket(): %s: %s", debugString.c_str(), strerror(errno));
return -1;
}
int doesReuse = 1;
int error = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &doesReuse,
sizeof(doesReuse));
if (error == -1)
{
logWrite(ERROR, "setsockopt(SO_REUSEADDR): %s: %s", debugString.c_str(),
strerror(errno));
close(fd);
return -1;
}
int forcedSize = 262144;
error = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &forcedSize,
sizeof(forcedSize));
if (error == -1)
{
logWrite(ERROR, "Failed to set receive buffer size: %s",
strerror(errno));
close(fd);
return -1;
}
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = htonl(INADDR_ANY);
error = bind(fd, reinterpret_cast<struct sockaddr *>(&address),
sizeof(address));
if (error == -1)
{
logWrite(ERROR, "bind(): %s: %s", debugString.c_str(), strerror(errno));
close(fd);
return -1;
}
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
{
logWrite(ERROR, "fcntl(F_GETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(fd);
return -1;
}
error = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (error == -1)
{
logWrite(ERROR, "fcntl(F_SETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(fd);
return -1;
}
error = listen(fd, 4);
if (error == -1)
{
logWrite(ERROR, "listen(): %s: %s", debugString.c_str(), strerror(errno));
close(fd);
return -1;
}
setDescriptor(fd);
return fd;
}
int acceptServer(int acceptfd, struct sockaddr_in * remoteAddress,
string const & debugString)
{
struct sockaddr_in stackAddress;
struct sockaddr_in * address;
socklen_t addressSize = sizeof(struct sockaddr_in);
if (remoteAddress == NULL)
{
address = &stackAddress;
}
else
{
address = remoteAddress;
}
int resultfd = accept(acceptfd,
reinterpret_cast<struct sockaddr *>(address),
&addressSize);
if (resultfd == -1)
{
if (errno != EINTR && errno != EWOULDBLOCK && errno != ECONNABORTED
&& errno != EPROTO)
{
logWrite(EXCEPTION, "accept(): %s: %s", debugString.c_str(),
strerror(errno));
}
return -1;
}
int flags = fcntl(resultfd, F_GETFL, 0);
if (flags == -1)
{
logWrite(EXCEPTION, "fcntl(F_GETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(resultfd);
return -1;
}
int error = fcntl(resultfd, F_SETFL, flags | O_NONBLOCK);
if (error == -1)
{
logWrite(EXCEPTION, "fcntl(F_SETFL): %s: %s", debugString.c_str(),
strerror(errno));
close(resultfd);
return -1;
}
setDescriptor(resultfd);
return resultfd;
}
void exitHandler(int signal) {
logWrite(EXCEPTION,"Killed with signal %i, cleaning up",signal);
exit(0);
}
size_t PacketInfo::census(void) const
{
/* TODO: Remove this old code. It is too easy to get wrong.
// packetTime + packetLength
size_t result = sizeof(int)*(2+1) +
sizeof(struct tcp_info) +
sizeof(struct ip) + sizeof(struct tcphdr)
+ sizeof(unsigned char) // bufferFull
+ sizeof(unsigned char) // packetType
+ sizeof(unsigned char) + sizeof(int) + 2*sizeof(short); // elab
// Size for ipOptions and tcpOptions.
result += sizeof(unsigned int)*2;
std::list<Option>::iterator pos = ipOptions->begin();
std::list<Option>::iterator limit = ipOptions->end();
for (; pos != limit; ++pos)
{
result += 2 + pos->length;
}
pos = tcpOptions->begin();
limit = tcpOptions->end();
for (; pos != limit; ++pos)
{
result += 2 + pos->length;
}
return result;
*/
savePacket(NULL, *this);
return static_cast<size_t>(getLastSaveloadSize());
}
|
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include <seastar/core/sleep.hh>
#include "tests/test-utils.hh"
#include "tests/mutation_assertions.hh"
#include "tests/mutation_reader_assertions.hh"
#include "tests/mutation_source_test.hh"
#include "schema_builder.hh"
#include "simple_schema.hh"
#include "row_cache.hh"
#include "core/thread.hh"
#include "memtable.hh"
#include "partition_slice_builder.hh"
#include "tests/memtable_snapshot_source.hh"
#include "disk-error-handler.hh"
thread_local disk_error_signal_type commit_error;
thread_local disk_error_signal_type general_disk_error;
using namespace std::chrono_literals;
static schema_ptr make_schema() {
return schema_builder("ks", "cf")
.with_column("pk", bytes_type, column_kind::partition_key)
.with_column("v", bytes_type, column_kind::regular_column)
.build();
}
static thread_local api::timestamp_type next_timestamp = 1;
static
mutation make_new_mutation(schema_ptr s, partition_key key) {
mutation m(key, s);
static thread_local int next_value = 1;
m.set_clustered_cell(clustering_key::make_empty(), "v", data_value(to_bytes(sprint("v%d", next_value++))), next_timestamp++);
return m;
}
static inline
mutation make_new_large_mutation(schema_ptr s, partition_key key) {
mutation m(key, s);
static thread_local int next_value = 1;
static constexpr size_t blob_size = 64 * 1024;
std::vector<int> data;
data.reserve(blob_size);
for (unsigned i = 0; i < blob_size; i++) {
data.push_back(next_value);
}
next_value++;
bytes b(reinterpret_cast<int8_t*>(data.data()), data.size() * sizeof(int));
m.set_clustered_cell(clustering_key::make_empty(), "v", data_value(std::move(b)), next_timestamp++);
return m;
}
static
partition_key new_key(schema_ptr s) {
static thread_local int next = 0;
return partition_key::from_single_value(*s, to_bytes(sprint("key%d", next++)));
}
static
mutation make_new_mutation(schema_ptr s) {
return make_new_mutation(s, new_key(s));
}
static inline
mutation make_new_large_mutation(schema_ptr s, int key) {
return make_new_large_mutation(s, partition_key::from_single_value(*s, to_bytes(sprint("key%d", key))));
}
static inline
mutation make_new_mutation(schema_ptr s, int key) {
return make_new_mutation(s, partition_key::from_single_value(*s, to_bytes(sprint("key%d", key))));
}
snapshot_source make_decorated_snapshot_source(snapshot_source src, std::function<mutation_source(mutation_source)> decorator) {
return snapshot_source([src = std::move(src), decorator = std::move(decorator)] () mutable {
return decorator(src());
});
}
mutation_source make_source_with(mutation m) {
return mutation_source([m] (schema_ptr s, const dht::partition_range&, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
assert(m.schema() == s);
return make_reader_returning(m, std::move(fwd));
});
}
// It is assumed that src won't change.
snapshot_source snapshot_source_from_snapshot(mutation_source src) {
return snapshot_source([src = std::move(src)] {
return src;
});
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(make_source_with(m)), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(m)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_cache_works_after_clearing) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(make_source_with(m)), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(m)
.produces_end_of_stream();
tracker.clear();
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(m)
.produces_end_of_stream();
});
}
class partition_counting_reader final : public mutation_reader::impl {
mutation_reader _reader;
int& _counter;
public:
partition_counting_reader(mutation_reader mr, int& counter)
: _reader(std::move(mr)), _counter(counter) { }
virtual future<streamed_mutation_opt> operator()() override {
_counter++;
return _reader();
}
virtual future<> fast_forward_to(const dht::partition_range& pr) override {
return _reader.fast_forward_to(pr);
}
};
mutation_reader make_counting_reader(mutation_reader mr, int& counter) {
return make_mutation_reader<partition_counting_reader>(std::move(mr), counter);
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_empty_full_range) {
return seastar::async([] {
auto s = make_schema();
int secondary_calls_count = 0;
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mutation_source([&secondary_calls_count] (schema_ptr s, const dht::partition_range& range, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
return make_counting_reader(make_empty_reader(), secondary_calls_count);
})), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
});
}
SEASTAR_TEST_CASE(test_cache_uses_continuity_info_for_single_partition_query) {
return seastar::async([] {
auto s = make_schema();
int secondary_calls_count = 0;
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mutation_source([&secondary_calls_count] (schema_ptr s, const dht::partition_range& range, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
return make_counting_reader(make_empty_reader(), secondary_calls_count);
})), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
auto pk = partition_key::from_exploded(*s, { int32_type->decompose(100) });
auto dk = dht::global_partitioner().decorate_key(*s, pk);
auto range = dht::partition_range::make_singular(dk);
assert_that(cache.make_reader(s, range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
});
}
void test_cache_delegates_to_underlying_only_once_with_single_partition(schema_ptr s,
const mutation& m,
const dht::partition_range& range,
int calls_to_secondary) {
int secondary_calls_count = 0;
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mutation_source([m, &secondary_calls_count] (schema_ptr s, const dht::partition_range& range, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
assert(m.schema() == s);
if (range.contains(dht::ring_position(m.decorated_key()), dht::ring_position_comparator(*s))) {
return make_counting_reader(make_reader_returning(m, std::move(fwd)), secondary_calls_count);
} else {
return make_counting_reader(make_empty_reader(), secondary_calls_count);
}
})), tracker);
assert_that(cache.make_reader(s, range))
.produces(m)
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, calls_to_secondary);
assert_that(cache.make_reader(s, range))
.produces(m)
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, calls_to_secondary);
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_single_key_range) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
test_cache_delegates_to_underlying_only_once_with_single_partition(s, m,
dht::partition_range::make_singular(query::ring_position(m.decorated_key())), 1);
});
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_full_range) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
test_cache_delegates_to_underlying_only_once_with_single_partition(s, m, query::full_partition_range, 2);
});
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_range_open) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
dht::partition_range::bound end = {dht::ring_position(m.decorated_key()), true};
dht::partition_range range = dht::partition_range::make_ending_with(end);
test_cache_delegates_to_underlying_only_once_with_single_partition(s, m, range, 2);
});
}
// partitions must be sorted by decorated key
static void require_no_token_duplicates(const std::vector<mutation>& partitions) {
std::experimental::optional<dht::token> last_token;
for (auto&& p : partitions) {
const dht::decorated_key& key = p.decorated_key();
if (last_token && key.token() == *last_token) {
BOOST_FAIL("token duplicate detected");
}
last_token = key.token();
}
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_multiple_mutations) {
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("key", bytes_type, column_kind::partition_key)
.with_column("v", bytes_type)
.build();
auto make_partition_mutation = [s] (bytes key) -> mutation {
mutation m(partition_key::from_single_value(*s, key), s);
m.set_clustered_cell(clustering_key::make_empty(), "v", data_value(bytes("v1")), 1);
return m;
};
int partition_count = 5;
std::vector<mutation> partitions;
for (int i = 0; i < partition_count; ++i) {
partitions.emplace_back(
make_partition_mutation(to_bytes(sprint("key_%d", i))));
}
std::sort(partitions.begin(), partitions.end(), mutation_decorated_key_less_comparator());
require_no_token_duplicates(partitions);
dht::decorated_key key_before_all = partitions.front().decorated_key();
partitions.erase(partitions.begin());
dht::decorated_key key_after_all = partitions.back().decorated_key();
partitions.pop_back();
cache_tracker tracker;
auto mt = make_lw_shared<memtable>(s);
for (auto&& m : partitions) {
mt->apply(m);
}
auto make_cache = [&tracker, &mt](schema_ptr s, int& secondary_calls_count) -> lw_shared_ptr<row_cache> {
auto secondary = mutation_source([&mt, &secondary_calls_count] (schema_ptr s, const dht::partition_range& range,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return make_counting_reader(mt->as_data_source()(s, range, slice, pc, std::move(trace), std::move(fwd)), secondary_calls_count);
});
return make_lw_shared<row_cache>(s, snapshot_source_from_snapshot(secondary), tracker);
};
auto make_ds = [&make_cache](schema_ptr s, int& secondary_calls_count) -> mutation_source {
auto cache = make_cache(s, secondary_calls_count);
return mutation_source([cache] (schema_ptr s, const dht::partition_range& range,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return cache->make_reader(s, range, slice, pc, std::move(trace), std::move(fwd));
});
};
auto do_test = [&s, &partitions] (const mutation_source& ds, const dht::partition_range& range,
int& secondary_calls_count, int expected_calls) {
assert_that(ds(s, range))
.produces(slice(partitions, range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(expected_calls, secondary_calls_count);
};
{
int secondary_calls_count = 0;
auto test = [&] (const mutation_source& ds, const dht::partition_range& range, int expected_count) {
do_test(ds, range, secondary_calls_count, expected_count);
};
auto ds = make_ds(s, secondary_calls_count);
auto expected = partitions.size() + 1;
test(ds, query::full_partition_range, expected);
test(ds, query::full_partition_range, expected);
test(ds, dht::partition_range::make_ending_with({partitions[0].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_ending_with({partitions[0].decorated_key(), true}), expected);
test(ds, dht::partition_range::make_starting_with({partitions.back().decorated_key(), false}), expected);
test(ds, dht::partition_range::make_starting_with({partitions.back().decorated_key(), true}), expected);
test(ds, dht::partition_range::make_ending_with({partitions[1].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_ending_with({partitions[1].decorated_key(), true}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[1].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[1].decorated_key(), true}), expected);
test(ds, dht::partition_range::make_ending_with({partitions.back().decorated_key(), false}), expected);
test(ds, dht::partition_range::make_ending_with({partitions.back().decorated_key(), true}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[0].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[0].decorated_key(), true}), expected);
test(ds, dht::partition_range::make(
{dht::ring_position::starting_at(key_before_all.token())},
{dht::ring_position::ending_at(key_after_all.token())}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[1].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[1].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), true},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), false},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), true},
{partitions[2].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), false},
{partitions[2].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[2].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[2].decorated_key(), false}),
expected);
}
{
int secondary_calls_count = 0;
auto ds = make_ds(s, secondary_calls_count);
auto range = dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), true});
assert_that(ds(s, range))
.produces(slice(partitions, range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(3, secondary_calls_count);
assert_that(ds(s, range))
.produces(slice(partitions, range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(3, secondary_calls_count);
auto range2 = dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), false});
assert_that(ds(s, range2))
.produces(slice(partitions, range2))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(3, secondary_calls_count);
auto range3 = dht::partition_range::make(
{dht::ring_position::starting_at(key_before_all.token())},
{partitions[2].decorated_key(), false});
assert_that(ds(s, range3))
.produces(slice(partitions, range3))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(5, secondary_calls_count);
}
{
int secondary_calls_count = 0;
auto test = [&] (const mutation_source& ds, const dht::partition_range& range, int expected_count) {
do_test(ds, range, secondary_calls_count, expected_count);
};
auto cache = make_cache(s, secondary_calls_count);
auto ds = mutation_source([cache] (schema_ptr s, const dht::partition_range& range,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return cache->make_reader(s, range, slice, pc, std::move(trace), std::move(fwd));
});
test(ds, query::full_partition_range, partitions.size() + 1);
test(ds, query::full_partition_range, partitions.size() + 1);
cache->invalidate([] {}, key_after_all);
assert_that(ds(s, query::full_partition_range))
.produces(slice(partitions, query::full_partition_range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(partitions.size() + 2, secondary_calls_count);
}
});
}
static std::vector<mutation> make_ring(schema_ptr s, int n_mutations) {
std::vector<mutation> mutations;
for (int i = 0; i < n_mutations; ++i) {
mutations.push_back(make_new_mutation(s));
}
std::sort(mutations.begin(), mutations.end(), mutation_decorated_key_less_comparator());
return mutations;
}
SEASTAR_TEST_CASE(test_query_of_incomplete_range_goes_to_underlying) {
return seastar::async([] {
auto s = make_schema();
std::vector<mutation> mutations = make_ring(s, 3);
auto mt = make_lw_shared<memtable>(s);
for (auto&& m : mutations) {
mt->apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
auto get_partition_range = [] (const mutation& m) {
return dht::partition_range::make_singular(query::ring_position(m.decorated_key()));
};
auto key0_range = get_partition_range(mutations[0]);
auto key2_range = get_partition_range(mutations[2]);
// Populate cache for first key
assert_that(cache.make_reader(s, key0_range))
.produces(mutations[0])
.produces_end_of_stream();
// Populate cache for last key
assert_that(cache.make_reader(s, key2_range))
.produces(mutations[2])
.produces_end_of_stream();
// Test single-key queries
assert_that(cache.make_reader(s, key0_range))
.produces(mutations[0])
.produces_end_of_stream();
assert_that(cache.make_reader(s, key2_range))
.produces(mutations[2])
.produces_end_of_stream();
// Test range query
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(mutations[0])
.produces(mutations[1])
.produces(mutations[2])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_single_key_queries_after_population_in_reverse_order) {
return seastar::async([] {
auto s = make_schema();
auto mt = make_lw_shared<memtable>(s);
std::vector<mutation> mutations = make_ring(s, 3);
for (auto&& m : mutations) {
mt->apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
auto get_partition_range = [] (const mutation& m) {
return dht::partition_range::make_singular(query::ring_position(m.decorated_key()));
};
auto key0_range = get_partition_range(mutations[0]);
auto key1_range = get_partition_range(mutations[1]);
auto key2_range = get_partition_range(mutations[2]);
for (int i = 0; i < 2; ++i) {
assert_that(cache.make_reader(s, key2_range))
.produces(mutations[2])
.produces_end_of_stream();
assert_that(cache.make_reader(s, key1_range))
.produces(mutations[1])
.produces_end_of_stream();
assert_that(cache.make_reader(s, key0_range))
.produces(mutations[0])
.produces_end_of_stream();
}
});
}
SEASTAR_TEST_CASE(test_row_cache_conforms_to_mutation_source) {
return seastar::async([] {
cache_tracker tracker;
run_mutation_source_tests([&tracker](schema_ptr s, const std::vector<mutation>& mutations) -> mutation_source {
auto mt = make_lw_shared<memtable>(s);
for (auto&& m : mutations) {
mt->apply(m);
}
auto cache = make_lw_shared<row_cache>(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
return mutation_source([cache] (schema_ptr s,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
streamed_mutation::forwarding fwd,
mutation_reader::forwarding fwd_mr) {
return cache->make_reader(s, range, slice, pc, std::move(trace_state), fwd, fwd_mr);
});
});
});
}
static
mutation make_fully_continuous(const mutation& m) {
mutation res = m;
res.partition().make_fully_continuous();
return res;
}
SEASTAR_TEST_CASE(test_reading_from_random_partial_partition) {
return seastar::async([] {
cache_tracker tracker;
random_mutation_generator gen(random_mutation_generator::generate_counters::no);
// The test primes the cache with m1, which has random continuity,
// and then applies m2 on top of it. This should result in some of m2's
// write information to be dropped. The test then verifies that we still get the
// proper m1 + m2.
auto m1 = gen();
auto m2 = make_fully_continuous(gen());
memtable_snapshot_source underlying(gen.schema());
underlying.apply(make_fully_continuous(m1));
row_cache cache(gen.schema(), snapshot_source([&] { return underlying(); }), tracker);
cache.populate(m1); // m1 is supposed to have random continuity and populate() should preserve it
auto rd1 = cache.make_reader(gen.schema());
auto sm1 = rd1().get0();
// Merge m2 into cache
auto mt = make_lw_shared<memtable>(gen.schema());
mt->apply(m2);
cache.update([&] { underlying.apply(m2); }, *mt).get();
auto rd2 = cache.make_reader(gen.schema());
auto sm2 = rd2().get0();
assert_that(std::move(sm1)).has_mutation().is_equal_to(m1);
assert_that(std::move(sm2)).has_mutation().is_equal_to(m1 + m2);
});
}
SEASTAR_TEST_CASE(test_random_partition_population) {
return seastar::async([] {
cache_tracker tracker;
random_mutation_generator gen(random_mutation_generator::generate_counters::no);
auto m1 = make_fully_continuous(gen());
auto m2 = make_fully_continuous(gen());
memtable_snapshot_source underlying(gen.schema());
underlying.apply(m1);
row_cache cache(gen.schema(), snapshot_source([&] { return underlying(); }), tracker);
assert_that(cache.make_reader(gen.schema()))
.produces(m1)
.produces_end_of_stream();
cache.invalidate([&] {
underlying.apply(m2);
}).get();
auto pr = dht::partition_range::make_singular(m2.decorated_key());
assert_that(cache.make_reader(gen.schema(), pr))
.produces(m1 + m2)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_eviction) {
return seastar::async([] {
auto s = make_schema();
auto mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
std::vector<dht::decorated_key> keys;
for (int i = 0; i < 100000; i++) {
auto m = make_new_mutation(s);
keys.emplace_back(m.decorated_key());
cache.populate(m);
}
std::random_device random;
std::shuffle(keys.begin(), keys.end(), std::default_random_engine(random()));
for (auto&& key : keys) {
cache.make_reader(s, dht::partition_range::make_singular(key));
}
while (tracker.partitions() > 0) {
logalloc::shard_tracker().reclaim(100);
}
});
}
bool has_key(row_cache& cache, const dht::decorated_key& key) {
auto range = dht::partition_range::make_singular(key);
auto reader = cache.make_reader(cache.schema(), range);
auto mo = reader().get0();
return bool(mo);
}
void verify_has(row_cache& cache, const dht::decorated_key& key) {
BOOST_REQUIRE(has_key(cache, key));
}
void verify_does_not_have(row_cache& cache, const dht::decorated_key& key) {
BOOST_REQUIRE(!has_key(cache, key));
}
void verify_has(row_cache& cache, const mutation& m) {
auto range = dht::partition_range::make_singular(m.decorated_key());
auto reader = cache.make_reader(cache.schema(), range);
assert_that(reader().get0()).has_mutation().is_equal_to(m);
}
void test_sliced_read_row_presence(mutation_reader reader, schema_ptr s, std::deque<int> expected)
{
clustering_key::equality ck_eq(*s);
auto smopt = reader().get0();
BOOST_REQUIRE(smopt);
auto mfopt = (*smopt)().get0();
while (mfopt) {
if (mfopt->is_clustering_row()) {
BOOST_REQUIRE(!expected.empty());
auto expected_ck = expected.front();
auto ck = clustering_key_prefix::from_single_value(*s, int32_type->decompose(expected_ck));
expected.pop_front();
auto& cr = mfopt->as_clustering_row();
if (!ck_eq(cr.key(), ck)) {
BOOST_FAIL(sprint("Expected %s, but got %s", ck, cr.key()));
}
}
mfopt = (*smopt)().get0();
}
BOOST_REQUIRE(expected.empty());
BOOST_REQUIRE(!reader().get0());
}
SEASTAR_TEST_CASE(test_single_partition_update) {
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("pk", int32_type, column_kind::partition_key)
.with_column("ck", int32_type, column_kind::clustering_key)
.with_column("v", int32_type)
.build();
auto pk = partition_key::from_exploded(*s, { int32_type->decompose(100) });
auto dk = dht::global_partitioner().decorate_key(*s, pk);
auto range = dht::partition_range::make_singular(dk);
auto make_ck = [&s] (int v) {
return clustering_key_prefix::from_single_value(*s, int32_type->decompose(v));
};
auto ck1 = make_ck(1);
auto ck2 = make_ck(2);
auto ck3 = make_ck(3);
auto ck4 = make_ck(4);
auto ck7 = make_ck(7);
memtable_snapshot_source cache_mt(s);
{
mutation m(pk, s);
m.set_clustered_cell(ck1, "v", data_value(101), 1);
m.set_clustered_cell(ck2, "v", data_value(101), 1);
m.set_clustered_cell(ck4, "v", data_value(101), 1);
m.set_clustered_cell(ck7, "v", data_value(101), 1);
cache_mt.apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source([&] { return cache_mt(); }), tracker);
{
auto slice = partition_slice_builder(*s)
.with_range(query::clustering_range::make_ending_with(ck1))
.with_range(query::clustering_range::make_starting_with(ck4))
.build();
auto reader = cache.make_reader(s, range, slice);
test_sliced_read_row_presence(std::move(reader), s, {1, 4, 7});
}
auto mt = make_lw_shared<memtable>(s);
cache.update([&] {
mutation m(pk, s);
m.set_clustered_cell(ck3, "v", data_value(101), 1);
mt->apply(m);
cache_mt.apply(m);
}, *mt).get();
{
auto reader = cache.make_reader(s, range);
test_sliced_read_row_presence(std::move(reader), s, {1, 2, 3, 4, 7});
}
});
}
SEASTAR_TEST_CASE(test_update) {
return seastar::async([] {
auto s = make_schema();
auto cache_mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker, is_continuous::yes);
BOOST_TEST_MESSAGE("Check cache miss with populate");
int partition_count = 1000;
// populate cache with some partitions
std::vector<dht::decorated_key> keys_in_cache;
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_in_cache.push_back(m.decorated_key());
cache.populate(m);
}
// populate memtable with partitions not in cache
auto mt = make_lw_shared<memtable>(s);
std::vector<dht::decorated_key> keys_not_in_cache;
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_not_in_cache.push_back(m.decorated_key());
mt->apply(m);
}
cache.update([] {}, *mt).get();
for (auto&& key : keys_not_in_cache) {
verify_has(cache, key);
}
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
std::copy(keys_not_in_cache.begin(), keys_not_in_cache.end(), std::back_inserter(keys_in_cache));
keys_not_in_cache.clear();
BOOST_TEST_MESSAGE("Check cache miss with drop");
auto mt2 = make_lw_shared<memtable>(s);
// populate memtable with partitions not in cache
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_not_in_cache.push_back(m.decorated_key());
mt2->apply(m);
cache.invalidate([] {}, m.decorated_key()).get();
}
cache.update([] {}, *mt2).get();
for (auto&& key : keys_not_in_cache) {
verify_does_not_have(cache, key);
}
BOOST_TEST_MESSAGE("Check cache hit with merge");
auto mt3 = make_lw_shared<memtable>(s);
std::vector<mutation> new_mutations;
for (auto&& key : keys_in_cache) {
auto m = make_new_mutation(s, key.key());
new_mutations.push_back(m);
mt3->apply(m);
}
cache.update([] {}, *mt3).get();
for (auto&& m : new_mutations) {
verify_has(cache, m);
}
});
}
#ifndef DEFAULT_ALLOCATOR
SEASTAR_TEST_CASE(test_update_failure) {
return seastar::async([] {
auto s = make_schema();
auto cache_mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker, is_continuous::yes);
int partition_count = 1000;
// populate cache with some partitions
using partitions_type = std::map<partition_key, mutation_partition, partition_key::less_compare>;
auto original_partitions = partitions_type(partition_key::less_compare(*s));
for (int i = 0; i < partition_count / 2; i++) {
auto m = make_new_mutation(s, i + partition_count / 2);
original_partitions.emplace(m.key(), m.partition());
cache.populate(m);
}
// populate memtable with more updated partitions
auto mt = make_lw_shared<memtable>(s);
auto updated_partitions = partitions_type(partition_key::less_compare(*s));
for (int i = 0; i < partition_count; i++) {
auto m = make_new_large_mutation(s, i);
updated_partitions.emplace(m.key(), m.partition());
mt->apply(m);
}
// fill all transient memory
std::vector<bytes> memory_hog;
{
logalloc::reclaim_lock _(tracker.region());
try {
while (true) {
memory_hog.emplace_back(bytes(bytes::initialized_later(), 4 * 1024));
}
} catch (const std::bad_alloc&) {
// expected
}
}
auto ev = tracker.region().evictor();
int evicitons_left = 10;
tracker.region().make_evictable([&] () mutable {
if (evicitons_left == 0) {
return memory::reclaiming_result::reclaimed_nothing;
}
--evicitons_left;
return ev();
});
bool failed = false;
try {
cache.update([] { }, *mt).get();
} catch (const std::bad_alloc&) {
failed = true;
}
BOOST_REQUIRE(!evicitons_left); // should have happened
memory_hog.clear();
auto has_only = [&] (const partitions_type& partitions) {
auto reader = cache.make_reader(s, query::full_partition_range);
for (int i = 0; i < partition_count; i++) {
auto mopt = mutation_from_streamed_mutation(reader().get0()).get0();
if (!mopt) {
break;
}
auto it = partitions.find(mopt->key());
BOOST_REQUIRE(it != partitions.end());
BOOST_REQUIRE(it->second.equal(*s, mopt->partition()));
}
BOOST_REQUIRE(!reader().get0());
};
if (failed) {
has_only(original_partitions);
} else {
has_only(updated_partitions);
}
});
}
#endif
class throttle {
unsigned _block_counter = 0;
promise<> _p; // valid when _block_counter != 0, resolves when goes down to 0
public:
future<> enter() {
if (_block_counter) {
promise<> p1;
promise<> p2;
auto f1 = p1.get_future();
p2.get_future().then([p1 = std::move(p1), p3 = std::move(_p)] () mutable {
p1.set_value();
p3.set_value();
});
_p = std::move(p2);
return f1;
} else {
return make_ready_future<>();
}
}
void block() {
++_block_counter;
_p = promise<>();
}
void unblock() {
assert(_block_counter);
if (--_block_counter == 0) {
_p.set_value();
}
}
};
class throttled_mutation_source {
private:
class impl : public enable_lw_shared_from_this<impl> {
mutation_source _underlying;
::throttle& _throttle;
private:
class reader : public mutation_reader::impl {
throttle& _throttle;
mutation_reader _reader;
public:
reader(throttle& t, mutation_reader r)
: _throttle(t)
, _reader(std::move(r))
{}
virtual future<streamed_mutation_opt> operator()() override {
return _reader().finally([this] () {
return _throttle.enter();
});
}
virtual future<> fast_forward_to(const dht::partition_range& pr) override {
return _reader.fast_forward_to(pr);
}
};
public:
impl(::throttle& t, mutation_source underlying)
: _underlying(std::move(underlying))
, _throttle(t)
{ }
mutation_reader make_reader(schema_ptr s, const dht::partition_range& pr,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return make_mutation_reader<reader>(_throttle, _underlying(s, pr, slice, pc, std::move(trace), std::move(fwd)));
}
};
lw_shared_ptr<impl> _impl;
public:
throttled_mutation_source(throttle& t, mutation_source underlying)
: _impl(make_lw_shared<impl>(t, std::move(underlying)))
{ }
operator mutation_source() const {
return mutation_source([impl = _impl] (schema_ptr s, const dht::partition_range& pr,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return impl->make_reader(std::move(s), pr, slice, pc, std::move(trace), std::move(fwd));
});
}
};
static std::vector<mutation> updated_ring(std::vector<mutation>& mutations) {
std::vector<mutation> result;
for (auto&& m : mutations) {
result.push_back(make_new_mutation(m.schema(), m.key()));
}
return result;
}
SEASTAR_TEST_CASE(test_continuity_flag_and_invalidate_race) {
return seastar::async([] {
auto s = make_schema();
lw_shared_ptr<memtable> mt = make_lw_shared<memtable>(s);
auto ring = make_ring(s, 4);
for (auto&& m : ring) {
mt->apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
// Bring ring[2]and ring[3] to cache.
auto range = dht::partition_range::make_starting_with({ ring[2].ring_position(), true });
assert_that(cache.make_reader(s, range))
.produces(ring[2])
.produces(ring[3])
.produces_end_of_stream();
// Start reader with full range.
auto rd = assert_that(cache.make_reader(s, query::full_partition_range));
rd.produces(ring[0]);
// Invalidate ring[2] and ring[3]
cache.invalidate([] {}, dht::partition_range::make_starting_with({ ring[2].ring_position(), true })).get();
// Continue previous reader.
rd.produces(ring[1])
.produces(ring[2])
.produces(ring[3])
.produces_end_of_stream();
// Start another reader with full range.
rd = assert_that(cache.make_reader(s, query::full_partition_range));
rd.produces(ring[0])
.produces(ring[1])
.produces(ring[2]);
// Invalidate whole cache.
cache.invalidate([] {}).get();
rd.produces(ring[3])
.produces_end_of_stream();
// Start yet another reader with full range.
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(ring[0])
.produces(ring[1])
.produces(ring[2])
.produces(ring[3])
.produces_end_of_stream();;
});
}
SEASTAR_TEST_CASE(test_cache_population_and_update_race) {
return seastar::async([] {
auto s = make_schema();
memtable_snapshot_source memtables(s);
throttle thr;
auto cache_source = make_decorated_snapshot_source(snapshot_source([&] { return memtables(); }), [&] (mutation_source src) {
return throttled_mutation_source(thr, std::move(src));
});
cache_tracker tracker;
auto mt1 = make_lw_shared<memtable>(s);
auto ring = make_ring(s, 3);
for (auto&& m : ring) {
mt1->apply(m);
}
memtables.apply(*mt1);
row_cache cache(s, cache_source, tracker);
auto mt2 = make_lw_shared<memtable>(s);
auto ring2 = updated_ring(ring);
for (auto&& m : ring2) {
mt2->apply(m);
}
thr.block();
auto m0_range = dht::partition_range::make_singular(ring[0].ring_position());
auto rd1 = cache.make_reader(s, m0_range);
auto rd1_result = rd1();
auto rd2 = cache.make_reader(s);
auto rd2_result = rd2();
sleep(10ms).get();
// This update should miss on all partitions
auto mt2_copy = make_lw_shared<memtable>(s);
mt2_copy->apply(*mt2).get();
auto update_future = cache.update([&] { memtables.apply(mt2_copy); }, *mt2);
auto rd3 = cache.make_reader(s);
// rd2, which is in progress, should not prevent forward progress of update()
thr.unblock();
update_future.get();
// Reads started before memtable flush should return previous value, otherwise this test
// doesn't trigger the conditions it is supposed to protect against.
assert_that(rd1_result.get0()).has_mutation().is_equal_to(ring[0]);
assert_that(rd2_result.get0()).has_mutation().is_equal_to(ring[0]);
assert_that(rd2().get0()).has_mutation().is_equal_to(ring2[1]);
assert_that(rd2().get0()).has_mutation().is_equal_to(ring2[2]);
assert_that(rd2().get0()).has_no_mutation();
// Reads started after update was started but before previous populations completed
// should already see the new data
assert_that(std::move(rd3))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
// Reads started after flush should see new data
assert_that(cache.make_reader(s))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_invalidate) {
return seastar::async([] {
auto s = make_schema();
auto mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
int partition_count = 1000;
// populate cache with some partitions
std::vector<dht::decorated_key> keys_in_cache;
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_in_cache.push_back(m.decorated_key());
cache.populate(m);
}
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
// remove a single element from cache
auto some_element = keys_in_cache.begin() + 547;
std::vector<dht::decorated_key> keys_not_in_cache;
keys_not_in_cache.push_back(*some_element);
cache.invalidate([] {}, *some_element).get();
keys_in_cache.erase(some_element);
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
for (auto&& key : keys_not_in_cache) {
verify_does_not_have(cache, key);
}
// remove a range of elements
std::sort(keys_in_cache.begin(), keys_in_cache.end(), [s] (auto& dk1, auto& dk2) {
return dk1.less_compare(*s, dk2);
});
auto some_range_begin = keys_in_cache.begin() + 123;
auto some_range_end = keys_in_cache.begin() + 423;
auto range = dht::partition_range::make(
{ *some_range_begin, true }, { *some_range_end, false }
);
keys_not_in_cache.insert(keys_not_in_cache.end(), some_range_begin, some_range_end);
cache.invalidate([] {}, range).get();
keys_in_cache.erase(some_range_begin, some_range_end);
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
for (auto&& key : keys_not_in_cache) {
verify_does_not_have(cache, key);
}
});
}
SEASTAR_TEST_CASE(test_cache_population_and_clear_race) {
return seastar::async([] {
auto s = make_schema();
memtable_snapshot_source memtables(s);
throttle thr;
auto cache_source = make_decorated_snapshot_source(snapshot_source([&] { return memtables(); }), [&] (mutation_source src) {
return throttled_mutation_source(thr, std::move(src));
});
cache_tracker tracker;
auto mt1 = make_lw_shared<memtable>(s);
auto ring = make_ring(s, 3);
for (auto&& m : ring) {
mt1->apply(m);
}
memtables.apply(*mt1);
row_cache cache(s, std::move(cache_source), tracker);
auto mt2 = make_lw_shared<memtable>(s);
auto ring2 = updated_ring(ring);
for (auto&& m : ring2) {
mt2->apply(m);
}
thr.block();
auto rd1 = cache.make_reader(s);
auto rd1_result = rd1();
sleep(10ms).get();
// This update should miss on all partitions
auto cache_cleared = cache.invalidate([&] {
memtables.apply(mt2);
});
auto rd2 = cache.make_reader(s);
// rd1, which is in progress, should not prevent forward progress of clear()
thr.unblock();
cache_cleared.get();
// Reads started before memtable flush should return previous value, otherwise this test
// doesn't trigger the conditions it is supposed to protect against.
assert_that(rd1_result.get0()).has_mutation().is_equal_to(ring[0]);
assert_that(rd1().get0()).has_mutation().is_equal_to(ring2[1]);
assert_that(rd1().get0()).has_mutation().is_equal_to(ring2[2]);
assert_that(rd1().get0()).has_no_mutation();
// Reads started after clear but before previous populations completed
// should already see the new data
assert_that(std::move(rd2))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
// Reads started after clear should see new data
assert_that(cache.make_reader(s))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_mvcc) {
return seastar::async([] {
auto test = [&] (const mutation& m1, const mutation& m2, bool with_active_memtable_reader) {
auto s = m1.schema();
memtable_snapshot_source underlying(s);
partition_key::equality eq(*s);
underlying.apply(m1);
cache_tracker tracker;
row_cache cache(s, snapshot_source([&] { return underlying(); }), tracker);
auto pk = m1.key();
cache.populate(m1);
auto sm1 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm1);
BOOST_REQUIRE(eq(sm1->key(), pk));
auto sm2 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm2);
BOOST_REQUIRE(eq(sm2->key(), pk));
auto mt1 = make_lw_shared<memtable>(s);
mt1->apply(m2);
auto m12 = m1 + m2;
stdx::optional<mutation_reader> mt1_reader_opt;
stdx::optional<streamed_mutation_opt> mt1_reader_sm_opt;
if (with_active_memtable_reader) {
mt1_reader_opt = mt1->make_reader(s);
mt1_reader_sm_opt = (*mt1_reader_opt)().get0();
BOOST_REQUIRE(*mt1_reader_sm_opt);
}
auto mt1_copy = make_lw_shared<memtable>(s);
mt1_copy->apply(*mt1).get();
cache.update([&] { underlying.apply(mt1_copy); }, *mt1).get();
auto sm3 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm3);
BOOST_REQUIRE(eq(sm3->key(), pk));
auto sm4 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm4);
BOOST_REQUIRE(eq(sm4->key(), pk));
auto sm5 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm5);
BOOST_REQUIRE(eq(sm5->key(), pk));
assert_that_stream(std::move(*sm3)).has_monotonic_positions();
if (with_active_memtable_reader) {
assert(mt1_reader_sm_opt);
auto mt1_reader_mutation = mutation_from_streamed_mutation(std::move(*mt1_reader_sm_opt)).get0();
BOOST_REQUIRE(mt1_reader_mutation);
assert_that(*mt1_reader_mutation).is_equal_to(m2);
}
auto m_4 = mutation_from_streamed_mutation(std::move(sm4)).get0();
assert_that(*m_4).is_equal_to(m12);
auto m_1 = mutation_from_streamed_mutation(std::move(sm1)).get0();
assert_that(*m_1).is_equal_to(m1);
cache.invalidate([] {}).get0();
auto m_2 = mutation_from_streamed_mutation(std::move(sm2)).get0();
assert_that(*m_2).is_equal_to(m1);
auto m_5 = mutation_from_streamed_mutation(std::move(sm5)).get0();
assert_that(*m_5).is_equal_to(m12);
};
for_each_mutation_pair([&] (const mutation& m1_, const mutation& m2_, are_equal) {
if (m1_.schema() != m2_.schema()) {
return;
}
if (m1_.partition().empty() || m2_.partition().empty()) {
return;
}
auto s = m1_.schema();
auto m1 = m1_;
m1.partition().make_fully_continuous();
auto m2 = mutation(m1.decorated_key(), m1.schema());
m2.partition().apply(*s, m2_.partition(), *s);
m2.partition().make_fully_continuous();
test(m1, m2, false);
test(m1, m2, true);
});
});
}
SEASTAR_TEST_CASE(test_slicing_mutation_reader) {
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("pk", int32_type, column_kind::partition_key)
.with_column("ck", int32_type, column_kind::clustering_key)
.with_column("v", int32_type)
.build();
auto pk = partition_key::from_exploded(*s, { int32_type->decompose(0) });
mutation m(pk, s);
constexpr auto row_count = 8;
for (auto i = 0; i < row_count; i++) {
m.set_clustered_cell(clustering_key_prefix::from_single_value(*s, int32_type->decompose(i)),
to_bytes("v"), data_value(i), api::new_timestamp());
}
auto mt = make_lw_shared<memtable>(s);
mt->apply(m);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
auto run_tests = [&] (auto& ps, std::deque<int> expected) {
cache.invalidate([] {}).get0();
auto reader = cache.make_reader(s, query::full_partition_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
reader = cache.make_reader(s, query::full_partition_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
auto dk = dht::global_partitioner().decorate_key(*s, pk);
auto singular_range = dht::partition_range::make_singular(dk);
reader = cache.make_reader(s, singular_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
cache.invalidate([] {}).get0();
reader = cache.make_reader(s, singular_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
};
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range {
{ },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(2)), false },
}).with_range(clustering_key_prefix::from_single_value(*s, int32_type->decompose(5)))
.with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(7)) },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(10)) },
}).build();
run_tests(ps, { 0, 1, 5, 7 });
}
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(1)) },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(2)) },
}).with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(4)), false },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(6)) },
}).with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(7)), false },
{ },
}).build();
run_tests(ps, { 1, 2, 5, 6 });
}
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range {
{ },
{ },
}).build();
run_tests(ps, { 0, 1, 2, 3, 4, 5, 6, 7 });
}
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range::make_singular(clustering_key_prefix::from_single_value(*s, int32_type->decompose(4))))
.build();
run_tests(ps, { 4 });
}
});
}
SEASTAR_TEST_CASE(test_lru) {
return seastar::async([] {
auto s = make_schema();
auto cache_mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker);
int partition_count = 10;
std::vector<mutation> partitions = make_ring(s, partition_count);
for (auto&& m : partitions) {
cache.populate(m);
}
auto pr = dht::partition_range::make_ending_with(dht::ring_position(partitions[2].decorated_key()));
auto rd = cache.make_reader(s, pr);
assert_that(std::move(rd))
.produces(partitions[0])
.produces(partitions[1])
.produces(partitions[2])
.produces_end_of_stream();
auto ret = tracker.region().evict_some();
BOOST_REQUIRE(ret == memory::reclaiming_result::reclaimed_something);
pr = dht::partition_range::make_ending_with(dht::ring_position(partitions[4].decorated_key()));
rd = cache.make_reader(s, pr);
assert_that(std::move(rd))
.produces(partitions[0])
.produces(partitions[1])
.produces(partitions[2])
.produces(partitions[4])
.produces_end_of_stream();
pr = dht::partition_range::make_singular(dht::ring_position(partitions[5].decorated_key()));
rd = cache.make_reader(s, pr);
assert_that(std::move(rd))
.produces(partitions[5])
.produces_end_of_stream();
ret = tracker.region().evict_some();
BOOST_REQUIRE(ret == memory::reclaiming_result::reclaimed_something);
rd = cache.make_reader(s);
assert_that(std::move(rd))
.produces(partitions[0])
.produces(partitions[1])
.produces(partitions[2])
.produces(partitions[4])
.produces(partitions[5])
.produces(partitions[7])
.produces(partitions[8])
.produces(partitions[9])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_update_invalidating) {
return seastar::async([] {
simple_schema s;
cache_tracker tracker;
memtable_snapshot_source underlying(s.schema());
auto mutation_for_key = [&] (dht::decorated_key key) {
mutation m(key, s.schema());
s.add_row(m, s.make_ckey(0), "val");
return m;
};
auto keys = s.make_pkeys(4);
auto m1 = mutation_for_key(keys[1]);
underlying.apply(m1);
auto m2 = mutation_for_key(keys[3]);
underlying.apply(m2);
row_cache cache(s.schema(), snapshot_source([&] { return underlying(); }), tracker);
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces_end_of_stream();
auto mt = make_lw_shared<memtable>(s.schema());
auto m3 = mutation_for_key(m1.decorated_key());
m3.partition().apply(s.new_tombstone());
auto m4 = mutation_for_key(keys[2]);
auto m5 = mutation_for_key(keys[0]);
mt->apply(m3);
mt->apply(m4);
mt->apply(m5);
auto mt_copy = make_lw_shared<memtable>(s.schema());
mt_copy->apply(*mt).get();
cache.update_invalidating([&] { underlying.apply(mt_copy); }, *mt).get();
assert_that(cache.make_reader(s.schema()))
.produces(m5)
.produces(m1 + m3)
.produces(m4)
.produces(m2)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_scan_with_partial_partitions) {
return seastar::async([] {
simple_schema s;
auto cache_mt = make_lw_shared<memtable>(s.schema());
auto pkeys = s.make_pkeys(3);
mutation m1(pkeys[0], s.schema());
s.add_row(m1, s.make_ckey(0), "v1");
s.add_row(m1, s.make_ckey(1), "v2");
s.add_row(m1, s.make_ckey(2), "v3");
s.add_row(m1, s.make_ckey(3), "v4");
cache_mt->apply(m1);
mutation m2(pkeys[1], s.schema());
s.add_row(m2, s.make_ckey(0), "v5");
s.add_row(m2, s.make_ckey(1), "v6");
s.add_row(m2, s.make_ckey(2), "v7");
cache_mt->apply(m2);
mutation m3(pkeys[2], s.schema());
s.add_row(m3, s.make_ckey(0), "v8");
s.add_row(m3, s.make_ckey(1), "v9");
s.add_row(m3, s.make_ckey(2), "v10");
cache_mt->apply(m3);
cache_tracker tracker;
row_cache cache(s.schema(), snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker);
// partially populate all up to middle of m1
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_ending_with(s.make_ckey(1)))
.build();
auto prange = dht::partition_range::make_ending_with(dht::ring_position(m1.decorated_key()));
assert_that(cache.make_reader(s.schema(), prange, slice))
.produces(m1, slice.row_ranges(*s.schema(), m1.key()))
.produces_end_of_stream();
}
// partially populate m3
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_ending_with(s.make_ckey(1)))
.build();
auto prange = dht::partition_range::make_singular(m3.decorated_key());
assert_that(cache.make_reader(s.schema(), prange, slice))
.produces(m3, slice.row_ranges(*s.schema(), m3.key()))
.produces_end_of_stream();
}
// full scan
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces(m3)
.produces_end_of_stream();
// full scan after full scan
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces(m3)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_cache_populates_partition_tombstone) {
return seastar::async([] {
simple_schema s;
auto cache_mt = make_lw_shared<memtable>(s.schema());
auto pkeys = s.make_pkeys(2);
mutation m1(pkeys[0], s.schema());
s.add_static_row(m1, "val");
m1.partition().apply(tombstone(s.new_timestamp(), gc_clock::now()));
cache_mt->apply(m1);
mutation m2(pkeys[1], s.schema());
s.add_static_row(m2, "val");
m2.partition().apply(tombstone(s.new_timestamp(), gc_clock::now()));
cache_mt->apply(m2);
cache_tracker tracker;
row_cache cache(s.schema(), snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker);
// singular range case
{
auto prange = dht::partition_range::make_singular(dht::ring_position(m1.decorated_key()));
assert_that(cache.make_reader(s.schema(), prange))
.produces(m1)
.produces_end_of_stream();
assert_that(cache.make_reader(s.schema(), prange)) // over populated
.produces(m1)
.produces_end_of_stream();
}
// range scan case
{
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces_end_of_stream();
assert_that(cache.make_reader(s.schema())) // over populated
.produces(m1)
.produces(m2)
.produces_end_of_stream();
}
});
}
// Tests the case of cache reader having to reconcile a range tombstone
// from the underlying mutation source which overlaps with previously emitted
// tombstones.
SEASTAR_TEST_CASE(test_tombstone_merging_in_partial_partition) {
return seastar::async([] {
simple_schema s;
cache_tracker tracker;
memtable_snapshot_source underlying(s.schema());
auto pk = s.make_pkey(0);
auto pr = dht::partition_range::make_singular(pk);
tombstone t0{s.new_timestamp(), gc_clock::now()};
tombstone t1{s.new_timestamp(), gc_clock::now()};
mutation m1(pk, s.schema());
m1.partition().apply_delete(*s.schema(),
s.make_range_tombstone(query::clustering_range::make(s.make_ckey(0), s.make_ckey(10)), t0));
underlying.apply(m1);
mutation m2(pk, s.schema());
m2.partition().apply_delete(*s.schema(),
s.make_range_tombstone(query::clustering_range::make(s.make_ckey(3), s.make_ckey(6)), t1));
m2.partition().apply_delete(*s.schema(),
s.make_range_tombstone(query::clustering_range::make(s.make_ckey(7), s.make_ckey(12)), t1));
s.add_row(m2, s.make_ckey(4), "val");
s.add_row(m2, s.make_ckey(8), "val");
underlying.apply(m2);
row_cache cache(s.schema(), snapshot_source([&] { return underlying(); }), tracker);
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_singular(s.make_ckey(4)))
.build();
assert_that(cache.make_reader(s.schema(), pr, slice))
.produces(m1 + m2, slice.row_ranges(*s.schema(), pk.key()))
.produces_end_of_stream();
}
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_starting_with(s.make_ckey(4)))
.build();
assert_that(cache.make_reader(s.schema(), pr, slice))
.produces(m1 + m2, slice.row_ranges(*s.schema(), pk.key()))
.produces_end_of_stream();
auto rd = cache.make_reader(s.schema(), pr, slice);
auto smo = rd().get0();
BOOST_REQUIRE(smo);
assert_that_stream(std::move(*smo)).has_monotonic_positions();
}
});
}
static void consume_all(mutation_reader& rd) {
while (streamed_mutation_opt smo = rd().get0()) {
auto&& sm = *smo;
while (sm().get0()) ;
}
}
static void populate_range(row_cache& cache,
const dht::partition_range& pr = query::full_partition_range,
const query::clustering_range& r = query::full_clustering_range)
{
auto slice = partition_slice_builder(*cache.schema()).with_range(r).build();
auto rd = cache.make_reader(cache.schema(), pr, slice);
consume_all(rd);
}
SEASTAR_TEST_CASE(test_readers_get_all_data_after_eviction) {
return seastar::async([] {
simple_schema table;
schema_ptr s = table.schema();
memtable_snapshot_source underlying(s);
auto m1 = table.new_mutation("pk");
table.add_row(m1, table.make_ckey(3), "v3");
auto m2 = table.new_mutation("pk");
table.add_row(m2, table.make_ckey(1), "v1");
table.add_row(m2, table.make_ckey(2), "v2");
underlying.apply(m1);
cache_tracker tracker;
row_cache cache(s, snapshot_source([&] { return underlying(); }), tracker);
cache.populate(m1);
auto apply = [&] (mutation m) {
auto mt = make_lw_shared<memtable>(m.schema());
mt->apply(m);
cache.update([&] { underlying.apply(m); }, *mt).get();
};
auto make_sm = [&] (const query::partition_slice& slice = query::full_slice) {
auto rd = cache.make_reader(s, query::full_partition_range, slice);
auto smo = rd().get0();
BOOST_REQUIRE(smo);
streamed_mutation& sm = *smo;
sm.set_max_buffer_size(1);
return assert_that_stream(std::move(sm));
};
auto sm1 = make_sm();
apply(m2);
auto sm2 = make_sm();
auto slice_with_key2 = partition_slice_builder(*s)
.with_range(query::clustering_range::make_singular(table.make_ckey(2)))
.build();
auto sm3 = make_sm(slice_with_key2);
cache.evict();
sm3.produces_row_with_key(table.make_ckey(2))
.produces_end_of_stream();
sm1.produces(m1);
sm2.produces(m1 + m2);
});
}
//
// Tests the following case of eviction and re-population:
//
// (Before) <ROW key=0> <RT1> <RT2> <RT3> <ROW key=8, cont=1>
// ^--- lower bound ^---- next row
//
// (After) <ROW key=0> <ROW key=8, cont=0> <ROW key=8, cont=1>
// ^--- lower bound ^---- next row
SEASTAR_TEST_CASE(test_tombstones_are_not_missed_when_range_is_invalidated) {
return seastar::async([] {
simple_schema s;
cache_tracker tracker;
memtable_snapshot_source underlying(s.schema());
auto pk = s.make_pkey(0);
auto pr = dht::partition_range::make_singular(pk);
mutation m1(pk, s.schema());
s.add_row(m1, s.make_ckey(0), "v0");
auto rt1 = s.make_range_tombstone(query::clustering_range::make(s.make_ckey(1), s.make_ckey(2)),
s.new_tombstone());
auto rt2 = s.make_range_tombstone(query::clustering_range::make(s.make_ckey(3), s.make_ckey(4)),
s.new_tombstone());
auto rt3 = s.make_range_tombstone(query::clustering_range::make(s.make_ckey(5), s.make_ckey(6)),
s.new_tombstone());
m1.partition().apply_delete(*s.schema(), rt1);
m1.partition().apply_delete(*s.schema(), rt2);
m1.partition().apply_delete(*s.schema(), rt3);
s.add_row(m1, s.make_ckey(8), "v8");
underlying.apply(m1);
row_cache cache(s.schema(), snapshot_source([&] { return underlying(); }), tracker);
auto make_sm = [&] (const query::partition_slice& slice = query::full_slice) {
auto rd = cache.make_reader(s.schema(), pr, slice);
auto smo = rd().get0();
BOOST_REQUIRE(smo);
streamed_mutation& sm = *smo;
sm.set_max_buffer_size(1);
return assert_that_stream(std::move(sm));
};
// populate using reader in same snapshot
{
populate_range(cache);
auto slice_after_7 = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_starting_with(s.make_ckey(7)))
.build();
auto sma2 = make_sm(slice_after_7);
auto sma = make_sm();
sma.produces_row_with_key(s.make_ckey(0));
sma.produces_range_tombstone(rt1);
cache.evict();
sma2.produces_row_with_key(s.make_ckey(8));
sma2.produces_end_of_stream();
sma.produces_range_tombstone(rt2);
sma.produces_range_tombstone(rt3);
sma.produces_row_with_key(s.make_ckey(8));
sma.produces_end_of_stream();
}
// populate using reader created after invalidation
{
populate_range(cache);
auto sma = make_sm();
sma.produces_row_with_key(s.make_ckey(0));
sma.produces_range_tombstone(rt1);
mutation m2(pk, s.schema());
s.add_row(m2, s.make_ckey(7), "v7");
cache.invalidate([&] {
underlying.apply(m2);
}).get();
populate_range(cache, pr, query::clustering_range::make_starting_with(s.make_ckey(5)));
sma.produces_range_tombstone(rt2);
sma.produces_range_tombstone(rt3);
sma.produces_row_with_key(s.make_ckey(8));
sma.produces_end_of_stream();
}
});
}
tests: row_cache: Add test for concurrent population
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include <seastar/core/sleep.hh>
#include "tests/test-utils.hh"
#include "tests/mutation_assertions.hh"
#include "tests/mutation_reader_assertions.hh"
#include "tests/mutation_source_test.hh"
#include "schema_builder.hh"
#include "simple_schema.hh"
#include "row_cache.hh"
#include "core/thread.hh"
#include "memtable.hh"
#include "partition_slice_builder.hh"
#include "tests/memtable_snapshot_source.hh"
#include "disk-error-handler.hh"
thread_local disk_error_signal_type commit_error;
thread_local disk_error_signal_type general_disk_error;
using namespace std::chrono_literals;
static schema_ptr make_schema() {
return schema_builder("ks", "cf")
.with_column("pk", bytes_type, column_kind::partition_key)
.with_column("v", bytes_type, column_kind::regular_column)
.build();
}
static thread_local api::timestamp_type next_timestamp = 1;
static
mutation make_new_mutation(schema_ptr s, partition_key key) {
mutation m(key, s);
static thread_local int next_value = 1;
m.set_clustered_cell(clustering_key::make_empty(), "v", data_value(to_bytes(sprint("v%d", next_value++))), next_timestamp++);
return m;
}
static inline
mutation make_new_large_mutation(schema_ptr s, partition_key key) {
mutation m(key, s);
static thread_local int next_value = 1;
static constexpr size_t blob_size = 64 * 1024;
std::vector<int> data;
data.reserve(blob_size);
for (unsigned i = 0; i < blob_size; i++) {
data.push_back(next_value);
}
next_value++;
bytes b(reinterpret_cast<int8_t*>(data.data()), data.size() * sizeof(int));
m.set_clustered_cell(clustering_key::make_empty(), "v", data_value(std::move(b)), next_timestamp++);
return m;
}
static
partition_key new_key(schema_ptr s) {
static thread_local int next = 0;
return partition_key::from_single_value(*s, to_bytes(sprint("key%d", next++)));
}
static
mutation make_new_mutation(schema_ptr s) {
return make_new_mutation(s, new_key(s));
}
static inline
mutation make_new_large_mutation(schema_ptr s, int key) {
return make_new_large_mutation(s, partition_key::from_single_value(*s, to_bytes(sprint("key%d", key))));
}
static inline
mutation make_new_mutation(schema_ptr s, int key) {
return make_new_mutation(s, partition_key::from_single_value(*s, to_bytes(sprint("key%d", key))));
}
snapshot_source make_decorated_snapshot_source(snapshot_source src, std::function<mutation_source(mutation_source)> decorator) {
return snapshot_source([src = std::move(src), decorator = std::move(decorator)] () mutable {
return decorator(src());
});
}
mutation_source make_source_with(mutation m) {
return mutation_source([m] (schema_ptr s, const dht::partition_range&, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
assert(m.schema() == s);
return make_reader_returning(m, std::move(fwd));
});
}
// It is assumed that src won't change.
snapshot_source snapshot_source_from_snapshot(mutation_source src) {
return snapshot_source([src = std::move(src)] {
return src;
});
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(make_source_with(m)), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(m)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_cache_works_after_clearing) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(make_source_with(m)), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(m)
.produces_end_of_stream();
tracker.clear();
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(m)
.produces_end_of_stream();
});
}
class partition_counting_reader final : public mutation_reader::impl {
mutation_reader _reader;
int& _counter;
public:
partition_counting_reader(mutation_reader mr, int& counter)
: _reader(std::move(mr)), _counter(counter) { }
virtual future<streamed_mutation_opt> operator()() override {
_counter++;
return _reader();
}
virtual future<> fast_forward_to(const dht::partition_range& pr) override {
return _reader.fast_forward_to(pr);
}
};
mutation_reader make_counting_reader(mutation_reader mr, int& counter) {
return make_mutation_reader<partition_counting_reader>(std::move(mr), counter);
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_empty_full_range) {
return seastar::async([] {
auto s = make_schema();
int secondary_calls_count = 0;
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mutation_source([&secondary_calls_count] (schema_ptr s, const dht::partition_range& range, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
return make_counting_reader(make_empty_reader(), secondary_calls_count);
})), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
});
}
SEASTAR_TEST_CASE(test_cache_uses_continuity_info_for_single_partition_query) {
return seastar::async([] {
auto s = make_schema();
int secondary_calls_count = 0;
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mutation_source([&secondary_calls_count] (schema_ptr s, const dht::partition_range& range, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
return make_counting_reader(make_empty_reader(), secondary_calls_count);
})), tracker);
assert_that(cache.make_reader(s, query::full_partition_range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
auto pk = partition_key::from_exploded(*s, { int32_type->decompose(100) });
auto dk = dht::global_partitioner().decorate_key(*s, pk);
auto range = dht::partition_range::make_singular(dk);
assert_that(cache.make_reader(s, range))
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, 1);
});
}
void test_cache_delegates_to_underlying_only_once_with_single_partition(schema_ptr s,
const mutation& m,
const dht::partition_range& range,
int calls_to_secondary) {
int secondary_calls_count = 0;
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mutation_source([m, &secondary_calls_count] (schema_ptr s, const dht::partition_range& range, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, streamed_mutation::forwarding fwd) {
assert(m.schema() == s);
if (range.contains(dht::ring_position(m.decorated_key()), dht::ring_position_comparator(*s))) {
return make_counting_reader(make_reader_returning(m, std::move(fwd)), secondary_calls_count);
} else {
return make_counting_reader(make_empty_reader(), secondary_calls_count);
}
})), tracker);
assert_that(cache.make_reader(s, range))
.produces(m)
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, calls_to_secondary);
assert_that(cache.make_reader(s, range))
.produces(m)
.produces_end_of_stream();
BOOST_REQUIRE_EQUAL(secondary_calls_count, calls_to_secondary);
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_single_key_range) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
test_cache_delegates_to_underlying_only_once_with_single_partition(s, m,
dht::partition_range::make_singular(query::ring_position(m.decorated_key())), 1);
});
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_full_range) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
test_cache_delegates_to_underlying_only_once_with_single_partition(s, m, query::full_partition_range, 2);
});
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_range_open) {
return seastar::async([] {
auto s = make_schema();
auto m = make_new_mutation(s);
dht::partition_range::bound end = {dht::ring_position(m.decorated_key()), true};
dht::partition_range range = dht::partition_range::make_ending_with(end);
test_cache_delegates_to_underlying_only_once_with_single_partition(s, m, range, 2);
});
}
// partitions must be sorted by decorated key
static void require_no_token_duplicates(const std::vector<mutation>& partitions) {
std::experimental::optional<dht::token> last_token;
for (auto&& p : partitions) {
const dht::decorated_key& key = p.decorated_key();
if (last_token && key.token() == *last_token) {
BOOST_FAIL("token duplicate detected");
}
last_token = key.token();
}
}
SEASTAR_TEST_CASE(test_cache_delegates_to_underlying_only_once_multiple_mutations) {
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("key", bytes_type, column_kind::partition_key)
.with_column("v", bytes_type)
.build();
auto make_partition_mutation = [s] (bytes key) -> mutation {
mutation m(partition_key::from_single_value(*s, key), s);
m.set_clustered_cell(clustering_key::make_empty(), "v", data_value(bytes("v1")), 1);
return m;
};
int partition_count = 5;
std::vector<mutation> partitions;
for (int i = 0; i < partition_count; ++i) {
partitions.emplace_back(
make_partition_mutation(to_bytes(sprint("key_%d", i))));
}
std::sort(partitions.begin(), partitions.end(), mutation_decorated_key_less_comparator());
require_no_token_duplicates(partitions);
dht::decorated_key key_before_all = partitions.front().decorated_key();
partitions.erase(partitions.begin());
dht::decorated_key key_after_all = partitions.back().decorated_key();
partitions.pop_back();
cache_tracker tracker;
auto mt = make_lw_shared<memtable>(s);
for (auto&& m : partitions) {
mt->apply(m);
}
auto make_cache = [&tracker, &mt](schema_ptr s, int& secondary_calls_count) -> lw_shared_ptr<row_cache> {
auto secondary = mutation_source([&mt, &secondary_calls_count] (schema_ptr s, const dht::partition_range& range,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return make_counting_reader(mt->as_data_source()(s, range, slice, pc, std::move(trace), std::move(fwd)), secondary_calls_count);
});
return make_lw_shared<row_cache>(s, snapshot_source_from_snapshot(secondary), tracker);
};
auto make_ds = [&make_cache](schema_ptr s, int& secondary_calls_count) -> mutation_source {
auto cache = make_cache(s, secondary_calls_count);
return mutation_source([cache] (schema_ptr s, const dht::partition_range& range,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return cache->make_reader(s, range, slice, pc, std::move(trace), std::move(fwd));
});
};
auto do_test = [&s, &partitions] (const mutation_source& ds, const dht::partition_range& range,
int& secondary_calls_count, int expected_calls) {
assert_that(ds(s, range))
.produces(slice(partitions, range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(expected_calls, secondary_calls_count);
};
{
int secondary_calls_count = 0;
auto test = [&] (const mutation_source& ds, const dht::partition_range& range, int expected_count) {
do_test(ds, range, secondary_calls_count, expected_count);
};
auto ds = make_ds(s, secondary_calls_count);
auto expected = partitions.size() + 1;
test(ds, query::full_partition_range, expected);
test(ds, query::full_partition_range, expected);
test(ds, dht::partition_range::make_ending_with({partitions[0].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_ending_with({partitions[0].decorated_key(), true}), expected);
test(ds, dht::partition_range::make_starting_with({partitions.back().decorated_key(), false}), expected);
test(ds, dht::partition_range::make_starting_with({partitions.back().decorated_key(), true}), expected);
test(ds, dht::partition_range::make_ending_with({partitions[1].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_ending_with({partitions[1].decorated_key(), true}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[1].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[1].decorated_key(), true}), expected);
test(ds, dht::partition_range::make_ending_with({partitions.back().decorated_key(), false}), expected);
test(ds, dht::partition_range::make_ending_with({partitions.back().decorated_key(), true}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[0].decorated_key(), false}), expected);
test(ds, dht::partition_range::make_starting_with({partitions[0].decorated_key(), true}), expected);
test(ds, dht::partition_range::make(
{dht::ring_position::starting_at(key_before_all.token())},
{dht::ring_position::ending_at(key_after_all.token())}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[1].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[1].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), true},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), false},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), true},
{partitions[2].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[1].decorated_key(), false},
{partitions[2].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[2].decorated_key(), true}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[2].decorated_key(), false}),
expected);
test(ds, dht::partition_range::make(
{partitions[0].decorated_key(), false},
{partitions[2].decorated_key(), false}),
expected);
}
{
int secondary_calls_count = 0;
auto ds = make_ds(s, secondary_calls_count);
auto range = dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), true});
assert_that(ds(s, range))
.produces(slice(partitions, range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(3, secondary_calls_count);
assert_that(ds(s, range))
.produces(slice(partitions, range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(3, secondary_calls_count);
auto range2 = dht::partition_range::make(
{partitions[0].decorated_key(), true},
{partitions[1].decorated_key(), false});
assert_that(ds(s, range2))
.produces(slice(partitions, range2))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(3, secondary_calls_count);
auto range3 = dht::partition_range::make(
{dht::ring_position::starting_at(key_before_all.token())},
{partitions[2].decorated_key(), false});
assert_that(ds(s, range3))
.produces(slice(partitions, range3))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(5, secondary_calls_count);
}
{
int secondary_calls_count = 0;
auto test = [&] (const mutation_source& ds, const dht::partition_range& range, int expected_count) {
do_test(ds, range, secondary_calls_count, expected_count);
};
auto cache = make_cache(s, secondary_calls_count);
auto ds = mutation_source([cache] (schema_ptr s, const dht::partition_range& range,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return cache->make_reader(s, range, slice, pc, std::move(trace), std::move(fwd));
});
test(ds, query::full_partition_range, partitions.size() + 1);
test(ds, query::full_partition_range, partitions.size() + 1);
cache->invalidate([] {}, key_after_all);
assert_that(ds(s, query::full_partition_range))
.produces(slice(partitions, query::full_partition_range))
.produces_end_of_stream();
BOOST_CHECK_EQUAL(partitions.size() + 2, secondary_calls_count);
}
});
}
static std::vector<mutation> make_ring(schema_ptr s, int n_mutations) {
std::vector<mutation> mutations;
for (int i = 0; i < n_mutations; ++i) {
mutations.push_back(make_new_mutation(s));
}
std::sort(mutations.begin(), mutations.end(), mutation_decorated_key_less_comparator());
return mutations;
}
SEASTAR_TEST_CASE(test_query_of_incomplete_range_goes_to_underlying) {
return seastar::async([] {
auto s = make_schema();
std::vector<mutation> mutations = make_ring(s, 3);
auto mt = make_lw_shared<memtable>(s);
for (auto&& m : mutations) {
mt->apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
auto get_partition_range = [] (const mutation& m) {
return dht::partition_range::make_singular(query::ring_position(m.decorated_key()));
};
auto key0_range = get_partition_range(mutations[0]);
auto key2_range = get_partition_range(mutations[2]);
// Populate cache for first key
assert_that(cache.make_reader(s, key0_range))
.produces(mutations[0])
.produces_end_of_stream();
// Populate cache for last key
assert_that(cache.make_reader(s, key2_range))
.produces(mutations[2])
.produces_end_of_stream();
// Test single-key queries
assert_that(cache.make_reader(s, key0_range))
.produces(mutations[0])
.produces_end_of_stream();
assert_that(cache.make_reader(s, key2_range))
.produces(mutations[2])
.produces_end_of_stream();
// Test range query
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(mutations[0])
.produces(mutations[1])
.produces(mutations[2])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_single_key_queries_after_population_in_reverse_order) {
return seastar::async([] {
auto s = make_schema();
auto mt = make_lw_shared<memtable>(s);
std::vector<mutation> mutations = make_ring(s, 3);
for (auto&& m : mutations) {
mt->apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
auto get_partition_range = [] (const mutation& m) {
return dht::partition_range::make_singular(query::ring_position(m.decorated_key()));
};
auto key0_range = get_partition_range(mutations[0]);
auto key1_range = get_partition_range(mutations[1]);
auto key2_range = get_partition_range(mutations[2]);
for (int i = 0; i < 2; ++i) {
assert_that(cache.make_reader(s, key2_range))
.produces(mutations[2])
.produces_end_of_stream();
assert_that(cache.make_reader(s, key1_range))
.produces(mutations[1])
.produces_end_of_stream();
assert_that(cache.make_reader(s, key0_range))
.produces(mutations[0])
.produces_end_of_stream();
}
});
}
SEASTAR_TEST_CASE(test_row_cache_conforms_to_mutation_source) {
return seastar::async([] {
cache_tracker tracker;
run_mutation_source_tests([&tracker](schema_ptr s, const std::vector<mutation>& mutations) -> mutation_source {
auto mt = make_lw_shared<memtable>(s);
for (auto&& m : mutations) {
mt->apply(m);
}
auto cache = make_lw_shared<row_cache>(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
return mutation_source([cache] (schema_ptr s,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
streamed_mutation::forwarding fwd,
mutation_reader::forwarding fwd_mr) {
return cache->make_reader(s, range, slice, pc, std::move(trace_state), fwd, fwd_mr);
});
});
});
}
static
mutation make_fully_continuous(const mutation& m) {
mutation res = m;
res.partition().make_fully_continuous();
return res;
}
SEASTAR_TEST_CASE(test_reading_from_random_partial_partition) {
return seastar::async([] {
cache_tracker tracker;
random_mutation_generator gen(random_mutation_generator::generate_counters::no);
// The test primes the cache with m1, which has random continuity,
// and then applies m2 on top of it. This should result in some of m2's
// write information to be dropped. The test then verifies that we still get the
// proper m1 + m2.
auto m1 = gen();
auto m2 = make_fully_continuous(gen());
memtable_snapshot_source underlying(gen.schema());
underlying.apply(make_fully_continuous(m1));
row_cache cache(gen.schema(), snapshot_source([&] { return underlying(); }), tracker);
cache.populate(m1); // m1 is supposed to have random continuity and populate() should preserve it
auto rd1 = cache.make_reader(gen.schema());
auto sm1 = rd1().get0();
// Merge m2 into cache
auto mt = make_lw_shared<memtable>(gen.schema());
mt->apply(m2);
cache.update([&] { underlying.apply(m2); }, *mt).get();
auto rd2 = cache.make_reader(gen.schema());
auto sm2 = rd2().get0();
assert_that(std::move(sm1)).has_mutation().is_equal_to(m1);
assert_that(std::move(sm2)).has_mutation().is_equal_to(m1 + m2);
});
}
SEASTAR_TEST_CASE(test_random_partition_population) {
return seastar::async([] {
cache_tracker tracker;
random_mutation_generator gen(random_mutation_generator::generate_counters::no);
auto m1 = make_fully_continuous(gen());
auto m2 = make_fully_continuous(gen());
memtable_snapshot_source underlying(gen.schema());
underlying.apply(m1);
row_cache cache(gen.schema(), snapshot_source([&] { return underlying(); }), tracker);
assert_that(cache.make_reader(gen.schema()))
.produces(m1)
.produces_end_of_stream();
cache.invalidate([&] {
underlying.apply(m2);
}).get();
auto pr = dht::partition_range::make_singular(m2.decorated_key());
assert_that(cache.make_reader(gen.schema(), pr))
.produces(m1 + m2)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_eviction) {
return seastar::async([] {
auto s = make_schema();
auto mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
std::vector<dht::decorated_key> keys;
for (int i = 0; i < 100000; i++) {
auto m = make_new_mutation(s);
keys.emplace_back(m.decorated_key());
cache.populate(m);
}
std::random_device random;
std::shuffle(keys.begin(), keys.end(), std::default_random_engine(random()));
for (auto&& key : keys) {
cache.make_reader(s, dht::partition_range::make_singular(key));
}
while (tracker.partitions() > 0) {
logalloc::shard_tracker().reclaim(100);
}
});
}
bool has_key(row_cache& cache, const dht::decorated_key& key) {
auto range = dht::partition_range::make_singular(key);
auto reader = cache.make_reader(cache.schema(), range);
auto mo = reader().get0();
return bool(mo);
}
void verify_has(row_cache& cache, const dht::decorated_key& key) {
BOOST_REQUIRE(has_key(cache, key));
}
void verify_does_not_have(row_cache& cache, const dht::decorated_key& key) {
BOOST_REQUIRE(!has_key(cache, key));
}
void verify_has(row_cache& cache, const mutation& m) {
auto range = dht::partition_range::make_singular(m.decorated_key());
auto reader = cache.make_reader(cache.schema(), range);
assert_that(reader().get0()).has_mutation().is_equal_to(m);
}
void test_sliced_read_row_presence(mutation_reader reader, schema_ptr s, std::deque<int> expected)
{
clustering_key::equality ck_eq(*s);
auto smopt = reader().get0();
BOOST_REQUIRE(smopt);
auto mfopt = (*smopt)().get0();
while (mfopt) {
if (mfopt->is_clustering_row()) {
BOOST_REQUIRE(!expected.empty());
auto expected_ck = expected.front();
auto ck = clustering_key_prefix::from_single_value(*s, int32_type->decompose(expected_ck));
expected.pop_front();
auto& cr = mfopt->as_clustering_row();
if (!ck_eq(cr.key(), ck)) {
BOOST_FAIL(sprint("Expected %s, but got %s", ck, cr.key()));
}
}
mfopt = (*smopt)().get0();
}
BOOST_REQUIRE(expected.empty());
BOOST_REQUIRE(!reader().get0());
}
SEASTAR_TEST_CASE(test_single_partition_update) {
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("pk", int32_type, column_kind::partition_key)
.with_column("ck", int32_type, column_kind::clustering_key)
.with_column("v", int32_type)
.build();
auto pk = partition_key::from_exploded(*s, { int32_type->decompose(100) });
auto dk = dht::global_partitioner().decorate_key(*s, pk);
auto range = dht::partition_range::make_singular(dk);
auto make_ck = [&s] (int v) {
return clustering_key_prefix::from_single_value(*s, int32_type->decompose(v));
};
auto ck1 = make_ck(1);
auto ck2 = make_ck(2);
auto ck3 = make_ck(3);
auto ck4 = make_ck(4);
auto ck7 = make_ck(7);
memtable_snapshot_source cache_mt(s);
{
mutation m(pk, s);
m.set_clustered_cell(ck1, "v", data_value(101), 1);
m.set_clustered_cell(ck2, "v", data_value(101), 1);
m.set_clustered_cell(ck4, "v", data_value(101), 1);
m.set_clustered_cell(ck7, "v", data_value(101), 1);
cache_mt.apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source([&] { return cache_mt(); }), tracker);
{
auto slice = partition_slice_builder(*s)
.with_range(query::clustering_range::make_ending_with(ck1))
.with_range(query::clustering_range::make_starting_with(ck4))
.build();
auto reader = cache.make_reader(s, range, slice);
test_sliced_read_row_presence(std::move(reader), s, {1, 4, 7});
}
auto mt = make_lw_shared<memtable>(s);
cache.update([&] {
mutation m(pk, s);
m.set_clustered_cell(ck3, "v", data_value(101), 1);
mt->apply(m);
cache_mt.apply(m);
}, *mt).get();
{
auto reader = cache.make_reader(s, range);
test_sliced_read_row_presence(std::move(reader), s, {1, 2, 3, 4, 7});
}
});
}
SEASTAR_TEST_CASE(test_update) {
return seastar::async([] {
auto s = make_schema();
auto cache_mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker, is_continuous::yes);
BOOST_TEST_MESSAGE("Check cache miss with populate");
int partition_count = 1000;
// populate cache with some partitions
std::vector<dht::decorated_key> keys_in_cache;
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_in_cache.push_back(m.decorated_key());
cache.populate(m);
}
// populate memtable with partitions not in cache
auto mt = make_lw_shared<memtable>(s);
std::vector<dht::decorated_key> keys_not_in_cache;
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_not_in_cache.push_back(m.decorated_key());
mt->apply(m);
}
cache.update([] {}, *mt).get();
for (auto&& key : keys_not_in_cache) {
verify_has(cache, key);
}
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
std::copy(keys_not_in_cache.begin(), keys_not_in_cache.end(), std::back_inserter(keys_in_cache));
keys_not_in_cache.clear();
BOOST_TEST_MESSAGE("Check cache miss with drop");
auto mt2 = make_lw_shared<memtable>(s);
// populate memtable with partitions not in cache
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_not_in_cache.push_back(m.decorated_key());
mt2->apply(m);
cache.invalidate([] {}, m.decorated_key()).get();
}
cache.update([] {}, *mt2).get();
for (auto&& key : keys_not_in_cache) {
verify_does_not_have(cache, key);
}
BOOST_TEST_MESSAGE("Check cache hit with merge");
auto mt3 = make_lw_shared<memtable>(s);
std::vector<mutation> new_mutations;
for (auto&& key : keys_in_cache) {
auto m = make_new_mutation(s, key.key());
new_mutations.push_back(m);
mt3->apply(m);
}
cache.update([] {}, *mt3).get();
for (auto&& m : new_mutations) {
verify_has(cache, m);
}
});
}
#ifndef DEFAULT_ALLOCATOR
SEASTAR_TEST_CASE(test_update_failure) {
return seastar::async([] {
auto s = make_schema();
auto cache_mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker, is_continuous::yes);
int partition_count = 1000;
// populate cache with some partitions
using partitions_type = std::map<partition_key, mutation_partition, partition_key::less_compare>;
auto original_partitions = partitions_type(partition_key::less_compare(*s));
for (int i = 0; i < partition_count / 2; i++) {
auto m = make_new_mutation(s, i + partition_count / 2);
original_partitions.emplace(m.key(), m.partition());
cache.populate(m);
}
// populate memtable with more updated partitions
auto mt = make_lw_shared<memtable>(s);
auto updated_partitions = partitions_type(partition_key::less_compare(*s));
for (int i = 0; i < partition_count; i++) {
auto m = make_new_large_mutation(s, i);
updated_partitions.emplace(m.key(), m.partition());
mt->apply(m);
}
// fill all transient memory
std::vector<bytes> memory_hog;
{
logalloc::reclaim_lock _(tracker.region());
try {
while (true) {
memory_hog.emplace_back(bytes(bytes::initialized_later(), 4 * 1024));
}
} catch (const std::bad_alloc&) {
// expected
}
}
auto ev = tracker.region().evictor();
int evicitons_left = 10;
tracker.region().make_evictable([&] () mutable {
if (evicitons_left == 0) {
return memory::reclaiming_result::reclaimed_nothing;
}
--evicitons_left;
return ev();
});
bool failed = false;
try {
cache.update([] { }, *mt).get();
} catch (const std::bad_alloc&) {
failed = true;
}
BOOST_REQUIRE(!evicitons_left); // should have happened
memory_hog.clear();
auto has_only = [&] (const partitions_type& partitions) {
auto reader = cache.make_reader(s, query::full_partition_range);
for (int i = 0; i < partition_count; i++) {
auto mopt = mutation_from_streamed_mutation(reader().get0()).get0();
if (!mopt) {
break;
}
auto it = partitions.find(mopt->key());
BOOST_REQUIRE(it != partitions.end());
BOOST_REQUIRE(it->second.equal(*s, mopt->partition()));
}
BOOST_REQUIRE(!reader().get0());
};
if (failed) {
has_only(original_partitions);
} else {
has_only(updated_partitions);
}
});
}
#endif
class throttle {
unsigned _block_counter = 0;
promise<> _p; // valid when _block_counter != 0, resolves when goes down to 0
public:
future<> enter() {
if (_block_counter) {
promise<> p1;
promise<> p2;
auto f1 = p1.get_future();
p2.get_future().then([p1 = std::move(p1), p3 = std::move(_p)] () mutable {
p1.set_value();
p3.set_value();
});
_p = std::move(p2);
return f1;
} else {
return make_ready_future<>();
}
}
void block() {
++_block_counter;
_p = promise<>();
}
void unblock() {
assert(_block_counter);
if (--_block_counter == 0) {
_p.set_value();
}
}
};
class throttled_mutation_source {
private:
class impl : public enable_lw_shared_from_this<impl> {
mutation_source _underlying;
::throttle& _throttle;
private:
class reader : public mutation_reader::impl {
throttle& _throttle;
mutation_reader _reader;
public:
reader(throttle& t, mutation_reader r)
: _throttle(t)
, _reader(std::move(r))
{}
virtual future<streamed_mutation_opt> operator()() override {
return _reader().finally([this] () {
return _throttle.enter();
});
}
virtual future<> fast_forward_to(const dht::partition_range& pr) override {
return _reader.fast_forward_to(pr);
}
};
public:
impl(::throttle& t, mutation_source underlying)
: _underlying(std::move(underlying))
, _throttle(t)
{ }
mutation_reader make_reader(schema_ptr s, const dht::partition_range& pr,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return make_mutation_reader<reader>(_throttle, _underlying(s, pr, slice, pc, std::move(trace), std::move(fwd)));
}
};
lw_shared_ptr<impl> _impl;
public:
throttled_mutation_source(throttle& t, mutation_source underlying)
: _impl(make_lw_shared<impl>(t, std::move(underlying)))
{ }
operator mutation_source() const {
return mutation_source([impl = _impl] (schema_ptr s, const dht::partition_range& pr,
const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace, streamed_mutation::forwarding fwd) {
return impl->make_reader(std::move(s), pr, slice, pc, std::move(trace), std::move(fwd));
});
}
};
static std::vector<mutation> updated_ring(std::vector<mutation>& mutations) {
std::vector<mutation> result;
for (auto&& m : mutations) {
result.push_back(make_new_mutation(m.schema(), m.key()));
}
return result;
}
SEASTAR_TEST_CASE(test_continuity_flag_and_invalidate_race) {
return seastar::async([] {
auto s = make_schema();
lw_shared_ptr<memtable> mt = make_lw_shared<memtable>(s);
auto ring = make_ring(s, 4);
for (auto&& m : ring) {
mt->apply(m);
}
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
// Bring ring[2]and ring[3] to cache.
auto range = dht::partition_range::make_starting_with({ ring[2].ring_position(), true });
assert_that(cache.make_reader(s, range))
.produces(ring[2])
.produces(ring[3])
.produces_end_of_stream();
// Start reader with full range.
auto rd = assert_that(cache.make_reader(s, query::full_partition_range));
rd.produces(ring[0]);
// Invalidate ring[2] and ring[3]
cache.invalidate([] {}, dht::partition_range::make_starting_with({ ring[2].ring_position(), true })).get();
// Continue previous reader.
rd.produces(ring[1])
.produces(ring[2])
.produces(ring[3])
.produces_end_of_stream();
// Start another reader with full range.
rd = assert_that(cache.make_reader(s, query::full_partition_range));
rd.produces(ring[0])
.produces(ring[1])
.produces(ring[2]);
// Invalidate whole cache.
cache.invalidate([] {}).get();
rd.produces(ring[3])
.produces_end_of_stream();
// Start yet another reader with full range.
assert_that(cache.make_reader(s, query::full_partition_range))
.produces(ring[0])
.produces(ring[1])
.produces(ring[2])
.produces(ring[3])
.produces_end_of_stream();;
});
}
SEASTAR_TEST_CASE(test_cache_population_and_update_race) {
return seastar::async([] {
auto s = make_schema();
memtable_snapshot_source memtables(s);
throttle thr;
auto cache_source = make_decorated_snapshot_source(snapshot_source([&] { return memtables(); }), [&] (mutation_source src) {
return throttled_mutation_source(thr, std::move(src));
});
cache_tracker tracker;
auto mt1 = make_lw_shared<memtable>(s);
auto ring = make_ring(s, 3);
for (auto&& m : ring) {
mt1->apply(m);
}
memtables.apply(*mt1);
row_cache cache(s, cache_source, tracker);
auto mt2 = make_lw_shared<memtable>(s);
auto ring2 = updated_ring(ring);
for (auto&& m : ring2) {
mt2->apply(m);
}
thr.block();
auto m0_range = dht::partition_range::make_singular(ring[0].ring_position());
auto rd1 = cache.make_reader(s, m0_range);
auto rd1_result = rd1();
auto rd2 = cache.make_reader(s);
auto rd2_result = rd2();
sleep(10ms).get();
// This update should miss on all partitions
auto mt2_copy = make_lw_shared<memtable>(s);
mt2_copy->apply(*mt2).get();
auto update_future = cache.update([&] { memtables.apply(mt2_copy); }, *mt2);
auto rd3 = cache.make_reader(s);
// rd2, which is in progress, should not prevent forward progress of update()
thr.unblock();
update_future.get();
// Reads started before memtable flush should return previous value, otherwise this test
// doesn't trigger the conditions it is supposed to protect against.
assert_that(rd1_result.get0()).has_mutation().is_equal_to(ring[0]);
assert_that(rd2_result.get0()).has_mutation().is_equal_to(ring[0]);
assert_that(rd2().get0()).has_mutation().is_equal_to(ring2[1]);
assert_that(rd2().get0()).has_mutation().is_equal_to(ring2[2]);
assert_that(rd2().get0()).has_no_mutation();
// Reads started after update was started but before previous populations completed
// should already see the new data
assert_that(std::move(rd3))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
// Reads started after flush should see new data
assert_that(cache.make_reader(s))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_invalidate) {
return seastar::async([] {
auto s = make_schema();
auto mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
int partition_count = 1000;
// populate cache with some partitions
std::vector<dht::decorated_key> keys_in_cache;
for (int i = 0; i < partition_count; i++) {
auto m = make_new_mutation(s);
keys_in_cache.push_back(m.decorated_key());
cache.populate(m);
}
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
// remove a single element from cache
auto some_element = keys_in_cache.begin() + 547;
std::vector<dht::decorated_key> keys_not_in_cache;
keys_not_in_cache.push_back(*some_element);
cache.invalidate([] {}, *some_element).get();
keys_in_cache.erase(some_element);
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
for (auto&& key : keys_not_in_cache) {
verify_does_not_have(cache, key);
}
// remove a range of elements
std::sort(keys_in_cache.begin(), keys_in_cache.end(), [s] (auto& dk1, auto& dk2) {
return dk1.less_compare(*s, dk2);
});
auto some_range_begin = keys_in_cache.begin() + 123;
auto some_range_end = keys_in_cache.begin() + 423;
auto range = dht::partition_range::make(
{ *some_range_begin, true }, { *some_range_end, false }
);
keys_not_in_cache.insert(keys_not_in_cache.end(), some_range_begin, some_range_end);
cache.invalidate([] {}, range).get();
keys_in_cache.erase(some_range_begin, some_range_end);
for (auto&& key : keys_in_cache) {
verify_has(cache, key);
}
for (auto&& key : keys_not_in_cache) {
verify_does_not_have(cache, key);
}
});
}
SEASTAR_TEST_CASE(test_cache_population_and_clear_race) {
return seastar::async([] {
auto s = make_schema();
memtable_snapshot_source memtables(s);
throttle thr;
auto cache_source = make_decorated_snapshot_source(snapshot_source([&] { return memtables(); }), [&] (mutation_source src) {
return throttled_mutation_source(thr, std::move(src));
});
cache_tracker tracker;
auto mt1 = make_lw_shared<memtable>(s);
auto ring = make_ring(s, 3);
for (auto&& m : ring) {
mt1->apply(m);
}
memtables.apply(*mt1);
row_cache cache(s, std::move(cache_source), tracker);
auto mt2 = make_lw_shared<memtable>(s);
auto ring2 = updated_ring(ring);
for (auto&& m : ring2) {
mt2->apply(m);
}
thr.block();
auto rd1 = cache.make_reader(s);
auto rd1_result = rd1();
sleep(10ms).get();
// This update should miss on all partitions
auto cache_cleared = cache.invalidate([&] {
memtables.apply(mt2);
});
auto rd2 = cache.make_reader(s);
// rd1, which is in progress, should not prevent forward progress of clear()
thr.unblock();
cache_cleared.get();
// Reads started before memtable flush should return previous value, otherwise this test
// doesn't trigger the conditions it is supposed to protect against.
assert_that(rd1_result.get0()).has_mutation().is_equal_to(ring[0]);
assert_that(rd1().get0()).has_mutation().is_equal_to(ring2[1]);
assert_that(rd1().get0()).has_mutation().is_equal_to(ring2[2]);
assert_that(rd1().get0()).has_no_mutation();
// Reads started after clear but before previous populations completed
// should already see the new data
assert_that(std::move(rd2))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
// Reads started after clear should see new data
assert_that(cache.make_reader(s))
.produces(ring2[0])
.produces(ring2[1])
.produces(ring2[2])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_mvcc) {
return seastar::async([] {
auto test = [&] (const mutation& m1, const mutation& m2, bool with_active_memtable_reader) {
auto s = m1.schema();
memtable_snapshot_source underlying(s);
partition_key::equality eq(*s);
underlying.apply(m1);
cache_tracker tracker;
row_cache cache(s, snapshot_source([&] { return underlying(); }), tracker);
auto pk = m1.key();
cache.populate(m1);
auto sm1 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm1);
BOOST_REQUIRE(eq(sm1->key(), pk));
auto sm2 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm2);
BOOST_REQUIRE(eq(sm2->key(), pk));
auto mt1 = make_lw_shared<memtable>(s);
mt1->apply(m2);
auto m12 = m1 + m2;
stdx::optional<mutation_reader> mt1_reader_opt;
stdx::optional<streamed_mutation_opt> mt1_reader_sm_opt;
if (with_active_memtable_reader) {
mt1_reader_opt = mt1->make_reader(s);
mt1_reader_sm_opt = (*mt1_reader_opt)().get0();
BOOST_REQUIRE(*mt1_reader_sm_opt);
}
auto mt1_copy = make_lw_shared<memtable>(s);
mt1_copy->apply(*mt1).get();
cache.update([&] { underlying.apply(mt1_copy); }, *mt1).get();
auto sm3 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm3);
BOOST_REQUIRE(eq(sm3->key(), pk));
auto sm4 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm4);
BOOST_REQUIRE(eq(sm4->key(), pk));
auto sm5 = cache.make_reader(s)().get0();
BOOST_REQUIRE(sm5);
BOOST_REQUIRE(eq(sm5->key(), pk));
assert_that_stream(std::move(*sm3)).has_monotonic_positions();
if (with_active_memtable_reader) {
assert(mt1_reader_sm_opt);
auto mt1_reader_mutation = mutation_from_streamed_mutation(std::move(*mt1_reader_sm_opt)).get0();
BOOST_REQUIRE(mt1_reader_mutation);
assert_that(*mt1_reader_mutation).is_equal_to(m2);
}
auto m_4 = mutation_from_streamed_mutation(std::move(sm4)).get0();
assert_that(*m_4).is_equal_to(m12);
auto m_1 = mutation_from_streamed_mutation(std::move(sm1)).get0();
assert_that(*m_1).is_equal_to(m1);
cache.invalidate([] {}).get0();
auto m_2 = mutation_from_streamed_mutation(std::move(sm2)).get0();
assert_that(*m_2).is_equal_to(m1);
auto m_5 = mutation_from_streamed_mutation(std::move(sm5)).get0();
assert_that(*m_5).is_equal_to(m12);
};
for_each_mutation_pair([&] (const mutation& m1_, const mutation& m2_, are_equal) {
if (m1_.schema() != m2_.schema()) {
return;
}
if (m1_.partition().empty() || m2_.partition().empty()) {
return;
}
auto s = m1_.schema();
auto m1 = m1_;
m1.partition().make_fully_continuous();
auto m2 = mutation(m1.decorated_key(), m1.schema());
m2.partition().apply(*s, m2_.partition(), *s);
m2.partition().make_fully_continuous();
test(m1, m2, false);
test(m1, m2, true);
});
});
}
SEASTAR_TEST_CASE(test_slicing_mutation_reader) {
return seastar::async([] {
auto s = schema_builder("ks", "cf")
.with_column("pk", int32_type, column_kind::partition_key)
.with_column("ck", int32_type, column_kind::clustering_key)
.with_column("v", int32_type)
.build();
auto pk = partition_key::from_exploded(*s, { int32_type->decompose(0) });
mutation m(pk, s);
constexpr auto row_count = 8;
for (auto i = 0; i < row_count; i++) {
m.set_clustered_cell(clustering_key_prefix::from_single_value(*s, int32_type->decompose(i)),
to_bytes("v"), data_value(i), api::new_timestamp());
}
auto mt = make_lw_shared<memtable>(s);
mt->apply(m);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(mt->as_data_source()), tracker);
auto run_tests = [&] (auto& ps, std::deque<int> expected) {
cache.invalidate([] {}).get0();
auto reader = cache.make_reader(s, query::full_partition_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
reader = cache.make_reader(s, query::full_partition_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
auto dk = dht::global_partitioner().decorate_key(*s, pk);
auto singular_range = dht::partition_range::make_singular(dk);
reader = cache.make_reader(s, singular_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
cache.invalidate([] {}).get0();
reader = cache.make_reader(s, singular_range, ps);
test_sliced_read_row_presence(std::move(reader), s, expected);
};
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range {
{ },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(2)), false },
}).with_range(clustering_key_prefix::from_single_value(*s, int32_type->decompose(5)))
.with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(7)) },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(10)) },
}).build();
run_tests(ps, { 0, 1, 5, 7 });
}
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(1)) },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(2)) },
}).with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(4)), false },
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(6)) },
}).with_range(query::clustering_range {
query::clustering_range::bound { clustering_key_prefix::from_single_value(*s, int32_type->decompose(7)), false },
{ },
}).build();
run_tests(ps, { 1, 2, 5, 6 });
}
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range {
{ },
{ },
}).build();
run_tests(ps, { 0, 1, 2, 3, 4, 5, 6, 7 });
}
{
auto ps = partition_slice_builder(*s)
.with_range(query::clustering_range::make_singular(clustering_key_prefix::from_single_value(*s, int32_type->decompose(4))))
.build();
run_tests(ps, { 4 });
}
});
}
SEASTAR_TEST_CASE(test_lru) {
return seastar::async([] {
auto s = make_schema();
auto cache_mt = make_lw_shared<memtable>(s);
cache_tracker tracker;
row_cache cache(s, snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker);
int partition_count = 10;
std::vector<mutation> partitions = make_ring(s, partition_count);
for (auto&& m : partitions) {
cache.populate(m);
}
auto pr = dht::partition_range::make_ending_with(dht::ring_position(partitions[2].decorated_key()));
auto rd = cache.make_reader(s, pr);
assert_that(std::move(rd))
.produces(partitions[0])
.produces(partitions[1])
.produces(partitions[2])
.produces_end_of_stream();
auto ret = tracker.region().evict_some();
BOOST_REQUIRE(ret == memory::reclaiming_result::reclaimed_something);
pr = dht::partition_range::make_ending_with(dht::ring_position(partitions[4].decorated_key()));
rd = cache.make_reader(s, pr);
assert_that(std::move(rd))
.produces(partitions[0])
.produces(partitions[1])
.produces(partitions[2])
.produces(partitions[4])
.produces_end_of_stream();
pr = dht::partition_range::make_singular(dht::ring_position(partitions[5].decorated_key()));
rd = cache.make_reader(s, pr);
assert_that(std::move(rd))
.produces(partitions[5])
.produces_end_of_stream();
ret = tracker.region().evict_some();
BOOST_REQUIRE(ret == memory::reclaiming_result::reclaimed_something);
rd = cache.make_reader(s);
assert_that(std::move(rd))
.produces(partitions[0])
.produces(partitions[1])
.produces(partitions[2])
.produces(partitions[4])
.produces(partitions[5])
.produces(partitions[7])
.produces(partitions[8])
.produces(partitions[9])
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_update_invalidating) {
return seastar::async([] {
simple_schema s;
cache_tracker tracker;
memtable_snapshot_source underlying(s.schema());
auto mutation_for_key = [&] (dht::decorated_key key) {
mutation m(key, s.schema());
s.add_row(m, s.make_ckey(0), "val");
return m;
};
auto keys = s.make_pkeys(4);
auto m1 = mutation_for_key(keys[1]);
underlying.apply(m1);
auto m2 = mutation_for_key(keys[3]);
underlying.apply(m2);
row_cache cache(s.schema(), snapshot_source([&] { return underlying(); }), tracker);
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces_end_of_stream();
auto mt = make_lw_shared<memtable>(s.schema());
auto m3 = mutation_for_key(m1.decorated_key());
m3.partition().apply(s.new_tombstone());
auto m4 = mutation_for_key(keys[2]);
auto m5 = mutation_for_key(keys[0]);
mt->apply(m3);
mt->apply(m4);
mt->apply(m5);
auto mt_copy = make_lw_shared<memtable>(s.schema());
mt_copy->apply(*mt).get();
cache.update_invalidating([&] { underlying.apply(mt_copy); }, *mt).get();
assert_that(cache.make_reader(s.schema()))
.produces(m5)
.produces(m1 + m3)
.produces(m4)
.produces(m2)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_scan_with_partial_partitions) {
return seastar::async([] {
simple_schema s;
auto cache_mt = make_lw_shared<memtable>(s.schema());
auto pkeys = s.make_pkeys(3);
mutation m1(pkeys[0], s.schema());
s.add_row(m1, s.make_ckey(0), "v1");
s.add_row(m1, s.make_ckey(1), "v2");
s.add_row(m1, s.make_ckey(2), "v3");
s.add_row(m1, s.make_ckey(3), "v4");
cache_mt->apply(m1);
mutation m2(pkeys[1], s.schema());
s.add_row(m2, s.make_ckey(0), "v5");
s.add_row(m2, s.make_ckey(1), "v6");
s.add_row(m2, s.make_ckey(2), "v7");
cache_mt->apply(m2);
mutation m3(pkeys[2], s.schema());
s.add_row(m3, s.make_ckey(0), "v8");
s.add_row(m3, s.make_ckey(1), "v9");
s.add_row(m3, s.make_ckey(2), "v10");
cache_mt->apply(m3);
cache_tracker tracker;
row_cache cache(s.schema(), snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker);
// partially populate all up to middle of m1
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_ending_with(s.make_ckey(1)))
.build();
auto prange = dht::partition_range::make_ending_with(dht::ring_position(m1.decorated_key()));
assert_that(cache.make_reader(s.schema(), prange, slice))
.produces(m1, slice.row_ranges(*s.schema(), m1.key()))
.produces_end_of_stream();
}
// partially populate m3
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_ending_with(s.make_ckey(1)))
.build();
auto prange = dht::partition_range::make_singular(m3.decorated_key());
assert_that(cache.make_reader(s.schema(), prange, slice))
.produces(m3, slice.row_ranges(*s.schema(), m3.key()))
.produces_end_of_stream();
}
// full scan
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces(m3)
.produces_end_of_stream();
// full scan after full scan
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces(m3)
.produces_end_of_stream();
});
}
SEASTAR_TEST_CASE(test_cache_populates_partition_tombstone) {
return seastar::async([] {
simple_schema s;
auto cache_mt = make_lw_shared<memtable>(s.schema());
auto pkeys = s.make_pkeys(2);
mutation m1(pkeys[0], s.schema());
s.add_static_row(m1, "val");
m1.partition().apply(tombstone(s.new_timestamp(), gc_clock::now()));
cache_mt->apply(m1);
mutation m2(pkeys[1], s.schema());
s.add_static_row(m2, "val");
m2.partition().apply(tombstone(s.new_timestamp(), gc_clock::now()));
cache_mt->apply(m2);
cache_tracker tracker;
row_cache cache(s.schema(), snapshot_source_from_snapshot(cache_mt->as_data_source()), tracker);
// singular range case
{
auto prange = dht::partition_range::make_singular(dht::ring_position(m1.decorated_key()));
assert_that(cache.make_reader(s.schema(), prange))
.produces(m1)
.produces_end_of_stream();
assert_that(cache.make_reader(s.schema(), prange)) // over populated
.produces(m1)
.produces_end_of_stream();
}
// range scan case
{
assert_that(cache.make_reader(s.schema()))
.produces(m1)
.produces(m2)
.produces_end_of_stream();
assert_that(cache.make_reader(s.schema())) // over populated
.produces(m1)
.produces(m2)
.produces_end_of_stream();
}
});
}
// Tests the case of cache reader having to reconcile a range tombstone
// from the underlying mutation source which overlaps with previously emitted
// tombstones.
SEASTAR_TEST_CASE(test_tombstone_merging_in_partial_partition) {
return seastar::async([] {
simple_schema s;
cache_tracker tracker;
memtable_snapshot_source underlying(s.schema());
auto pk = s.make_pkey(0);
auto pr = dht::partition_range::make_singular(pk);
tombstone t0{s.new_timestamp(), gc_clock::now()};
tombstone t1{s.new_timestamp(), gc_clock::now()};
mutation m1(pk, s.schema());
m1.partition().apply_delete(*s.schema(),
s.make_range_tombstone(query::clustering_range::make(s.make_ckey(0), s.make_ckey(10)), t0));
underlying.apply(m1);
mutation m2(pk, s.schema());
m2.partition().apply_delete(*s.schema(),
s.make_range_tombstone(query::clustering_range::make(s.make_ckey(3), s.make_ckey(6)), t1));
m2.partition().apply_delete(*s.schema(),
s.make_range_tombstone(query::clustering_range::make(s.make_ckey(7), s.make_ckey(12)), t1));
s.add_row(m2, s.make_ckey(4), "val");
s.add_row(m2, s.make_ckey(8), "val");
underlying.apply(m2);
row_cache cache(s.schema(), snapshot_source([&] { return underlying(); }), tracker);
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_singular(s.make_ckey(4)))
.build();
assert_that(cache.make_reader(s.schema(), pr, slice))
.produces(m1 + m2, slice.row_ranges(*s.schema(), pk.key()))
.produces_end_of_stream();
}
{
auto slice = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_starting_with(s.make_ckey(4)))
.build();
assert_that(cache.make_reader(s.schema(), pr, slice))
.produces(m1 + m2, slice.row_ranges(*s.schema(), pk.key()))
.produces_end_of_stream();
auto rd = cache.make_reader(s.schema(), pr, slice);
auto smo = rd().get0();
BOOST_REQUIRE(smo);
assert_that_stream(std::move(*smo)).has_monotonic_positions();
}
});
}
static void consume_all(mutation_reader& rd) {
while (streamed_mutation_opt smo = rd().get0()) {
auto&& sm = *smo;
while (sm().get0()) ;
}
}
static void populate_range(row_cache& cache,
const dht::partition_range& pr = query::full_partition_range,
const query::clustering_range& r = query::full_clustering_range)
{
auto slice = partition_slice_builder(*cache.schema()).with_range(r).build();
auto rd = cache.make_reader(cache.schema(), pr, slice);
consume_all(rd);
}
static void apply(row_cache& cache, memtable_snapshot_source& underlying, const mutation& m) {
auto mt = make_lw_shared<memtable>(m.schema());
mt->apply(m);
cache.update([&] { underlying.apply(m); }, *mt).get();
}
SEASTAR_TEST_CASE(test_readers_get_all_data_after_eviction) {
return seastar::async([] {
simple_schema table;
schema_ptr s = table.schema();
memtable_snapshot_source underlying(s);
auto m1 = table.new_mutation("pk");
table.add_row(m1, table.make_ckey(3), "v3");
auto m2 = table.new_mutation("pk");
table.add_row(m2, table.make_ckey(1), "v1");
table.add_row(m2, table.make_ckey(2), "v2");
underlying.apply(m1);
cache_tracker tracker;
row_cache cache(s, snapshot_source([&] { return underlying(); }), tracker);
cache.populate(m1);
auto apply = [&] (mutation m) {
::apply(cache, underlying, m);
};
auto make_sm = [&] (const query::partition_slice& slice = query::full_slice) {
auto rd = cache.make_reader(s, query::full_partition_range, slice);
auto smo = rd().get0();
BOOST_REQUIRE(smo);
streamed_mutation& sm = *smo;
sm.set_max_buffer_size(1);
return assert_that_stream(std::move(sm));
};
auto sm1 = make_sm();
apply(m2);
auto sm2 = make_sm();
auto slice_with_key2 = partition_slice_builder(*s)
.with_range(query::clustering_range::make_singular(table.make_ckey(2)))
.build();
auto sm3 = make_sm(slice_with_key2);
cache.evict();
sm3.produces_row_with_key(table.make_ckey(2))
.produces_end_of_stream();
sm1.produces(m1);
sm2.produces(m1 + m2);
});
}
//
// Tests the following case of eviction and re-population:
//
// (Before) <ROW key=0> <RT1> <RT2> <RT3> <ROW key=8, cont=1>
// ^--- lower bound ^---- next row
//
// (After) <ROW key=0> <ROW key=8, cont=0> <ROW key=8, cont=1>
// ^--- lower bound ^---- next row
SEASTAR_TEST_CASE(test_tombstones_are_not_missed_when_range_is_invalidated) {
return seastar::async([] {
simple_schema s;
cache_tracker tracker;
memtable_snapshot_source underlying(s.schema());
auto pk = s.make_pkey(0);
auto pr = dht::partition_range::make_singular(pk);
mutation m1(pk, s.schema());
s.add_row(m1, s.make_ckey(0), "v0");
auto rt1 = s.make_range_tombstone(query::clustering_range::make(s.make_ckey(1), s.make_ckey(2)),
s.new_tombstone());
auto rt2 = s.make_range_tombstone(query::clustering_range::make(s.make_ckey(3), s.make_ckey(4)),
s.new_tombstone());
auto rt3 = s.make_range_tombstone(query::clustering_range::make(s.make_ckey(5), s.make_ckey(6)),
s.new_tombstone());
m1.partition().apply_delete(*s.schema(), rt1);
m1.partition().apply_delete(*s.schema(), rt2);
m1.partition().apply_delete(*s.schema(), rt3);
s.add_row(m1, s.make_ckey(8), "v8");
underlying.apply(m1);
row_cache cache(s.schema(), snapshot_source([&] { return underlying(); }), tracker);
auto make_sm = [&] (const query::partition_slice& slice = query::full_slice) {
auto rd = cache.make_reader(s.schema(), pr, slice);
auto smo = rd().get0();
BOOST_REQUIRE(smo);
streamed_mutation& sm = *smo;
sm.set_max_buffer_size(1);
return assert_that_stream(std::move(sm));
};
// populate using reader in same snapshot
{
populate_range(cache);
auto slice_after_7 = partition_slice_builder(*s.schema())
.with_range(query::clustering_range::make_starting_with(s.make_ckey(7)))
.build();
auto sma2 = make_sm(slice_after_7);
auto sma = make_sm();
sma.produces_row_with_key(s.make_ckey(0));
sma.produces_range_tombstone(rt1);
cache.evict();
sma2.produces_row_with_key(s.make_ckey(8));
sma2.produces_end_of_stream();
sma.produces_range_tombstone(rt2);
sma.produces_range_tombstone(rt3);
sma.produces_row_with_key(s.make_ckey(8));
sma.produces_end_of_stream();
}
// populate using reader created after invalidation
{
populate_range(cache);
auto sma = make_sm();
sma.produces_row_with_key(s.make_ckey(0));
sma.produces_range_tombstone(rt1);
mutation m2(pk, s.schema());
s.add_row(m2, s.make_ckey(7), "v7");
cache.invalidate([&] {
underlying.apply(m2);
}).get();
populate_range(cache, pr, query::clustering_range::make_starting_with(s.make_ckey(5)));
sma.produces_range_tombstone(rt2);
sma.produces_range_tombstone(rt3);
sma.produces_row_with_key(s.make_ckey(8));
sma.produces_end_of_stream();
}
});
}
SEASTAR_TEST_CASE(test_concurrent_population_before_latest_version_iterator) {
return seastar::async([] {
simple_schema s;
cache_tracker tracker;
memtable_snapshot_source underlying(s.schema());
auto pk = s.make_pkey(0);
auto pr = dht::partition_range::make_singular(pk);
mutation m1(pk, s.schema());
s.add_row(m1, s.make_ckey(0), "v");
s.add_row(m1, s.make_ckey(1), "v");
underlying.apply(m1);
row_cache cache(s.schema(), snapshot_source([&] { return underlying(); }), tracker);
auto make_sm = [&] (const query::partition_slice& slice = query::full_slice) {
auto rd = cache.make_reader(s.schema(), pr, slice);
auto smo = rd().get0();
BOOST_REQUIRE(smo);
streamed_mutation& sm = *smo;
sm.set_max_buffer_size(1);
return assert_that_stream(std::move(sm));
};
{
populate_range(cache, pr, s.make_ckey_range(0, 1));
auto rd = make_sm(); // to keep current version alive
mutation m2(pk, s.schema());
s.add_row(m2, s.make_ckey(2), "v");
s.add_row(m2, s.make_ckey(3), "v");
s.add_row(m2, s.make_ckey(4), "v");
apply(cache, underlying, m2);
auto slice1 = partition_slice_builder(*s.schema())
.with_range(s.make_ckey_range(0, 5))
.build();
auto sma1 = make_sm(slice1);
sma1.produces_row_with_key(s.make_ckey(0));
populate_range(cache, pr, s.make_ckey_range(3, 3));
auto sma2 = make_sm(slice1);
sma2.produces_row_with_key(s.make_ckey(0));
populate_range(cache, pr, s.make_ckey_range(2, 3));
sma2.produces_row_with_key(s.make_ckey(1));
sma2.produces_row_with_key(s.make_ckey(2));
sma2.produces_row_with_key(s.make_ckey(3));
sma2.produces_row_with_key(s.make_ckey(4));
sma2.produces_end_of_stream();
sma1.produces_row_with_key(s.make_ckey(1));
sma1.produces_row_with_key(s.make_ckey(2));
sma1.produces_row_with_key(s.make_ckey(3));
sma1.produces_row_with_key(s.make_ckey(4));
sma1.produces_end_of_stream();
}
{
cache.evict();
populate_range(cache, pr, s.make_ckey_range(4, 4));
auto slice1 = partition_slice_builder(*s.schema())
.with_range(s.make_ckey_range(0, 1))
.with_range(s.make_ckey_range(3, 3))
.build();
auto sma1 = make_sm(slice1);
sma1.produces_row_with_key(s.make_ckey(0));
populate_range(cache, pr, s.make_ckey_range(2, 4));
sma1.produces_row_with_key(s.make_ckey(1));
sma1.produces_row_with_key(s.make_ckey(3));
sma1.produces_end_of_stream();
}
});
}
|
/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include "resolution.h"
#include "astutil.h"
#include "stlUtil.h"
#include "build.h"
#include "caches.h"
#include "callInfo.h"
#include "CForLoop.h"
#include "expr.h"
#include "ForLoop.h"
#include "iterator.h"
#include "ParamForLoop.h"
#include "passes.h"
#include "resolveIntents.h"
#include "scopeResolve.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "WhileStmt.h"
#include "../ifa/prim_data.h"
#include "view.h"
#include <inttypes.h>
#include <map>
#include <sstream>
#include <vector>
// Allow disambiguation tracing to be controlled by the command-line option
// --explain-verbose.
#define ENABLE_TRACING_OF_DISAMBIGUATION 1
#ifdef ENABLE_TRACING_OF_DISAMBIGUATION
#define TRACE_DISAMBIGUATE_BY_MATCH(...) \
if (developer && DC.explain) fprintf(stderr, __VA_ARGS__)
#else
#define TRACE_DISAMBIGUATE_BY_MATCH(...)
#endif
/** Contextual info used by the disambiguation process.
*
* This class wraps information that is used by multiple functions during the
* function disambiguation process.
*/
class DisambiguationContext {
public:
/// The actual arguments from the call site.
Vec<Symbol*>* actuals;
/// The scope in which the call is made.
Expr* scope;
/// Whether or not to print out tracing information.
bool explain;
/// Indexes used when printing out tracing information.
int i, j;
/** A simple constructor that initializes all of the values except i and j.
*
* \param actuals The actual arguments from the call site.
* \param scope A block representing the scope the call was made in.
* \param explain Whether or not a trace of this disambiguation process should
* be printed for the developer.
*/
DisambiguationContext(Vec<Symbol*>* actuals, Expr* scope, bool explain) :
actuals(actuals), scope(scope), explain(explain), i(-1), j(-1) {}
/** A helper function used to set the i and j members.
*
* \param i The index of the left-hand side of the comparison.
* \param j The index of the right-hand side of the comparison.
*
* \return A constant reference to this disambiguation context.
*/
const DisambiguationContext& forPair(int newI, int newJ) {
this->i = newI;
this->j = newJ;
return *this;
}
};
/** A wrapper for candidates for function call resolution.
*
* If a best candidate was found than the function member will point to it.
*/
class ResolutionCandidate {
public:
/// A pointer to the best candidate function.
FnSymbol* fn;
/** The actual arguments for the candidate, aligned so that they have the same
* index as their corresponding formal argument in alignedFormals.
*/
Vec<Symbol*> alignedActuals;
/** The formal arguments for the candidate, aligned so that they have the same
* index as their corresponding actual argument in alignedActuals.
*/
Vec<ArgSymbol*> alignedFormals;
/// A symbol map for substitutions that were made during the copying process.
SymbolMap substitutions;
/** The main constructor.
*
* \param fn A function that is a candidate for the resolution process.
*/
ResolutionCandidate(FnSymbol* function) : fn(function) {}
/** Compute the alignment of actual and formal arguments for the wrapped
* function and the current call site.
*
* \param info The CallInfo object corresponding to the call site.
*
* \return If a valid alignment was found.
*/
bool computeAlignment(CallInfo& info);
/// Compute substitutions for wrapped function that is generic.
void computeSubstitutions();
};
/// State information used during the disambiguation process.
class DisambiguationState {
public:
/// Is fn1 more specific than fn2?
bool fn1MoreSpecific;
/// Is fn2 more specific than fn1?
bool fn2MoreSpecific;
/// Does fn1 require promotion?
bool fn1Promotes;
/// Does fn2 require promotion?
bool fn2Promotes;
/// 1 == fn1, 2 == fn2, -1 == conflicting signals
int paramPrefers;
/// Initialize the state to the starting values.
DisambiguationState()
: fn1MoreSpecific(false), fn2MoreSpecific(false),
fn1Promotes(false), fn2Promotes(false), paramPrefers(0) {}
/** Prints out information for tracing of the disambiguation process.
*
* \param DBMLoc A string representing the location in the DBM process the
* message is coming from.
* \param DC The disambiguation context.
*/
void printSummary(const char* DBMLoc, const DisambiguationContext& DC) {
if (this->fn1MoreSpecific) {
TRACE_DISAMBIGUATE_BY_MATCH("\n%s: Fn %d is more specific than Fn %d\n", DBMLoc, DC.i, DC.j);
} else {
TRACE_DISAMBIGUATE_BY_MATCH("\n%s: Fn %d is NOT more specific than Fn %d\n", DBMLoc, DC.i, DC.j);
}
if (this->fn2MoreSpecific) {
TRACE_DISAMBIGUATE_BY_MATCH("%s: Fn %d is more specific than Fn %d\n", DBMLoc, DC.j, DC.i);
} else {
TRACE_DISAMBIGUATE_BY_MATCH("%s: Fn %d is NOT more specific than Fn %d\n", DBMLoc, DC.j, DC.i);
}
}
};
//#
//# Global Variables
//#
bool resolved = false;
bool inDynamicDispatchResolution = false;
SymbolMap paramMap;
//#
//# Static Variables
//#
static int explainCallLine;
static ModuleSymbol* explainCallModule;
static Vec<CallExpr*> inits;
static Vec<FnSymbol*> resolvedFormals;
Vec<CallExpr*> callStack;
static Vec<CondStmt*> tryStack;
static bool tryFailure = false;
static Map<Type*,Type*> runtimeTypeMap; // map static types to runtime types
// e.g. array and domain runtime types
static Map<Type*,FnSymbol*> valueToRuntimeTypeMap; // convertValueToRuntimeType
static Map<Type*,FnSymbol*> runtimeTypeToValueMap; // convertRuntimeTypeToValue
static std::map<std::string, std::pair<AggregateType*, FnSymbol*> > functionTypeMap; // lookup table/cache for function types and their representative parents
static std::map<FnSymbol*, FnSymbol*> functionCaptureMap; //loopup table/cache for function captures
// map of compiler warnings that may need to be reissued for repeated
// calls; the inner compiler warning map is from the compilerWarning
// function; the outer compiler warning map is from the function
// containing the compilerWarning function
// to do: this needs to be a map from functions to multiple strings in
// order to support multiple compiler warnings are allowed to
// be in a single function
static Map<FnSymbol*,const char*> innerCompilerWarningMap;
static Map<FnSymbol*,const char*> outerCompilerWarningMap;
Map<Type*,FnSymbol*> autoCopyMap; // type to chpl__autoCopy function
Map<Type*,FnSymbol*> autoDestroyMap; // type to chpl__autoDestroy function
Map<FnSymbol*,FnSymbol*> iteratorLeaderMap; // iterator->leader map for promotion
Map<FnSymbol*,FnSymbol*> iteratorFollowerMap; // iterator->leader map for promotion
//#
//# Static Function Declarations
//#
static bool hasRefField(Type *type);
static bool typeHasRefField(Type *type);
static FnSymbol* resolveUninsertedCall(Type* type, CallExpr* call);
static void makeRefType(Type* type);
static void resolveAutoCopy(Type* type);
static void resolveAutoDestroy(Type* type);
static void resolveOther();
static FnSymbol*
protoIteratorMethod(IteratorInfo* ii, const char* name, Type* retType);
static void protoIteratorClass(FnSymbol* fn);
static bool isInstantiatedField(Symbol* field);
static Symbol* determineQueriedField(CallExpr* call);
static void resolveSpecifiedReturnType(FnSymbol* fn);
static bool fits_in_int(int width, Immediate* imm);
static bool fits_in_uint(int width, Immediate* imm);
static bool canInstantiate(Type* actualType, Type* formalType);
static bool canParamCoerce(Type* actualType, Symbol* actualSym, Type* formalType);
static bool
moreSpecific(FnSymbol* fn, Type* actualType, Type* formalType);
static bool
computeActualFormalAlignment(FnSymbol* fn,
Vec<Symbol*>& alignedActuals,
Vec<ArgSymbol*>& alignedFormals,
CallInfo& info);
static Type*
getInstantiationType(Type* actualType, Type* formalType);
static void
computeGenericSubs(SymbolMap &subs,
FnSymbol* fn,
Vec<Symbol*>& alignedActuals);
static FnSymbol*
expandVarArgs(FnSymbol* origFn, int numActuals);
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info);
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates,
FnSymbol* fn,
CallInfo& info);
static BlockStmt* getParentBlock(Expr* expr);
static bool
isMoreVisibleInternal(BlockStmt* block, FnSymbol* fn1, FnSymbol* fn2,
Vec<BlockStmt*>& visited);
static bool
isMoreVisible(Expr* expr, FnSymbol* fn1, FnSymbol* fn2);
static bool explainCallMatch(CallExpr* call);
static CallExpr* userCall(CallExpr* call);
static void
printResolutionErrorAmbiguous(
Vec<FnSymbol*>& candidateFns,
CallInfo* info);
static void
printResolutionErrorUnresolved(
Vec<FnSymbol*>& visibleFns,
CallInfo* info);
static void issueCompilerError(CallExpr* call);
static void reissueCompilerWarning(const char* str, int offset);
BlockStmt* getVisibilityBlock(Expr* expr);
static void buildVisibleFunctionMap();
static BlockStmt*
getVisibleFunctions(BlockStmt* block,
const char* name,
Vec<FnSymbol*>& visibleFns,
Vec<BlockStmt*>& visited);
static Expr* resolve_type_expr(Expr* expr);
static void makeNoop(CallExpr* call);
static void resolveDefaultGenericType(CallExpr* call);
static void
gatherCandidates(Vec<ResolutionCandidate*>& candidates,
Vec<FnSymbol*>& visibleFns,
CallInfo& info);
static void resolveNormalCall(CallExpr* call);
static void lvalueCheck(CallExpr* call);
static void resolveTupleAndExpand(CallExpr* call);
static void resolveTupleExpand(CallExpr* call);
static void resolveSetMember(CallExpr* call);
static void resolveMove(CallExpr* call);
static void resolveNew(CallExpr* call);
static bool formalRequiresTemp(ArgSymbol* formal);
static void insertFormalTemps(FnSymbol* fn);
static void addLocalCopiesAndWritebacks(FnSymbol* fn, SymbolMap& formals2vars);
static Expr* dropUnnecessaryCast(CallExpr* call);
static AggregateType* createAndInsertFunParentClass(CallExpr *call, const char *name);
static FnSymbol* createAndInsertFunParentMethod(CallExpr *call, AggregateType *parent, AList &arg_list, bool isFormal, Type *retType);
static std::string buildParentName(AList &arg_list, bool isFormal, Type *retType);
static AggregateType* createOrFindFunTypeFromAnnotation(AList &arg_list, CallExpr *call);
static Expr* createFunctionAsValue(CallExpr *call);
static bool
isOuterVar(Symbol* sym, FnSymbol* fn, Symbol* parent = NULL);
static bool
usesOuterVars(FnSymbol* fn, Vec<FnSymbol*> &seen);
static Expr* preFold(Expr* expr);
static void foldEnumOp(int op, EnumSymbol *e1, EnumSymbol *e2, Immediate *imm);
static bool isSubType(Type* sub, Type* super);
static void insertValueTemp(Expr* insertPoint, Expr* actual);
FnSymbol* requiresImplicitDestroy(CallExpr* call);
static Expr* postFold(Expr* expr);
static Expr* resolveExpr(Expr* expr);
static void
computeReturnTypeParamVectors(BaseAST* ast,
Symbol* retSymbol,
Vec<Type*>& retTypes,
Vec<Symbol*>& retParams);
static void
replaceSetterArgWithTrue(BaseAST* ast, FnSymbol* fn);
static void
replaceSetterArgWithFalse(BaseAST* ast, FnSymbol* fn, Symbol* ret);
static void
insertCasts(BaseAST* ast, FnSymbol* fn, Vec<CallExpr*>& casts);
static void buildValueFunction(FnSymbol* fn);
static bool
possible_signature_match(FnSymbol* fn, FnSymbol* gn);
static bool signature_match(FnSymbol* fn, FnSymbol* gn);
static void
collectInstantiatedAggregateTypes(Vec<Type*>& icts, Type* ct);
static bool isVirtualChild(FnSymbol* child, FnSymbol* parent);
static void addToVirtualMaps(FnSymbol* pfn, AggregateType* ct);
static void addAllToVirtualMaps(FnSymbol* fn, AggregateType* ct);
static void buildVirtualMaps();
static void
addVirtualMethodTableEntry(Type* type, FnSymbol* fn, bool exclusive = false);
static void resolveTypedefedArgTypes(FnSymbol* fn);
static void computeStandardModuleSet();
static void unmarkDefaultedGenerics();
static void resolveUses(ModuleSymbol* mod);
static void resolveExports();
static void resolveEnumTypes();
static void resolveDynamicDispatches();
static void insertRuntimeTypeTemps();
static void resolveAutoCopies();
static void resolveRecordInitializers();
static void insertDynamicDispatchCalls();
static Type* buildRuntimeTypeInfo(FnSymbol* fn);
static void insertReturnTemps();
static void initializeClass(Expr* stmt, Symbol* sym);
static void handleRuntimeTypes();
static void pruneResolvedTree();
static void removeCompilerWarnings();
static void removeUnusedFunctions();
static void removeUnusedTypes();
static void buildRuntimeTypeInitFns();
static void buildRuntimeTypeInitFn(FnSymbol* fn, Type* runtimeType);
static void removeUnusedGlobals();
static void removeParamArgs();
static void removeRandomPrimitives();
static void removeActualNames();
static void removeTypeBlocks();
static void removeFormalTypeAndInitBlocks();
static void replaceTypeArgsWithFormalTypeTemps();
static void replaceValuesWithRuntimeTypes();
static void removeWhereClauses();
static void replaceReturnedValuesWithRuntimeTypes();
static Expr* resolvePrimInit(CallExpr* call);
static void insertRuntimeInitTemps();
static void removeInitFields();
static void removeMootFields();
static void expandInitFieldPrims();
static void fixTypeNames(AggregateType* ct);
static void setScalarPromotionType(AggregateType* ct);
bool ResolutionCandidate::computeAlignment(CallInfo& info) {
if (alignedActuals.n != 0) alignedActuals.clear();
if (alignedFormals.n != 0) alignedFormals.clear();
return computeActualFormalAlignment(fn, alignedActuals, alignedFormals, info);
}
void ResolutionCandidate::computeSubstitutions() {
if (substitutions.n != 0) substitutions.clear();
computeGenericSubs(substitutions, fn, alignedActuals);
}
static bool hasRefField(Type *type) {
if (isPrimitiveType(type)) return false;
if (type->symbol->hasFlag(FLAG_OBJECT_CLASS)) return false;
if (!isClass(type)) { // record or union
if (AggregateType *ct = toAggregateType(type)) {
for_fields(field, ct) {
if (hasRefField(field->type)) return true;
}
}
return false;
}
return true;
}
static bool typeHasRefField(Type *type) {
if (AggregateType *ct = toAggregateType(type)) {
for_fields(field, ct) {
if (hasRefField(field->typeInfo())) return true;
}
}
return false;
}
//
// build reference type
//
static FnSymbol*
resolveUninsertedCall(Type* type, CallExpr* call) {
if (type->defaultInitializer) {
if (type->defaultInitializer->instantiationPoint)
type->defaultInitializer->instantiationPoint->insertAtHead(call);
else
type->symbol->defPoint->insertBefore(call);
} else {
chpl_gen_main->insertAtHead(call);
}
resolveCall(call);
call->remove();
return call->isResolved();
}
// Fills in the refType field of a type
// with the type's corresponding reference type.
static void makeRefType(Type* type) {
if (!type)
// Should this be an assert?
return;
if (type->refType) {
// Already done.
return;
}
if (type == dtMethodToken ||
type == dtUnknown ||
type->symbol->hasFlag(FLAG_REF) ||
type->symbol->hasFlag(FLAG_GENERIC)) {
return;
}
CallExpr* call = new CallExpr("_type_construct__ref", type->symbol);
FnSymbol* fn = resolveUninsertedCall(type, call);
type->refType = toAggregateType(fn->retType);
type->refType->getField(1)->type = type;
if (type->symbol->hasFlag(FLAG_ATOMIC_TYPE))
type->refType->symbol->addFlag(FLAG_ATOMIC_TYPE);
}
static void
resolveAutoCopy(Type* type) {
SET_LINENO(type->symbol);
Symbol* tmp = newTemp(type);
chpl_gen_main->insertAtHead(new DefExpr(tmp));
CallExpr* call = new CallExpr("chpl__autoCopy", tmp);
FnSymbol* fn = resolveUninsertedCall(type, call);
resolveFns(fn);
autoCopyMap.put(type, fn);
tmp->defPoint->remove();
}
static void
resolveAutoDestroy(Type* type) {
SET_LINENO(type->symbol);
Symbol* tmp = newTemp(type);
chpl_gen_main->insertAtHead(new DefExpr(tmp));
CallExpr* call = new CallExpr("chpl__autoDestroy", tmp);
FnSymbol* fn = resolveUninsertedCall(type, call);
resolveFns(fn);
autoDestroyMap.put(type, fn);
tmp->defPoint->remove();
}
FnSymbol* getAutoCopy(Type *t) {
return autoCopyMap.get(t);
}
FnSymbol* getAutoDestroy(Type* t) {
return autoDestroyMap.get(t);
}
const char* toString(Type* type) {
return type->getValType()->symbol->name;
}
const char* toString(CallInfo* info) {
bool method = false;
bool _this = false;
const char *str = "";
if (info->actuals.n > 1)
if (info->actuals.head()->type == dtMethodToken)
method = true;
if (!strcmp("this", info->name)) {
_this = true;
method = false;
}
if (method) {
if (info->actuals.v[1] && info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE))
str = astr(str, "type ", toString(info->actuals.v[1]->type), ".");
else
str = astr(str, toString(info->actuals.v[1]->type), ".");
}
if (!developer && !strncmp("_type_construct_", info->name, 16)) {
str = astr(str, info->name+16);
} else if (!developer && !strncmp("_construct_", info->name, 11)) {
str = astr(str, info->name+11);
} else if (!_this) {
str = astr(str, info->name);
}
if (!info->call->methodTag) {
if (info->call->square)
str = astr(str, "[");
else
str = astr(str, "(");
}
bool first = false;
int start = 0;
if (method)
start = 2;
if (_this)
start = 2;
for (int i = start; i < info->actuals.n; i++) {
if (!first)
first = true;
else
str = astr(str, ", ");
if (info->actualNames.v[i])
str = astr(str, info->actualNames.v[i], "=");
VarSymbol* var = toVarSymbol(info->actuals.v[i]);
if (info->actuals.v[i]->type->symbol->hasFlag(FLAG_ITERATOR_RECORD) &&
info->actuals.v[i]->type->defaultInitializer->hasFlag(FLAG_PROMOTION_WRAPPER))
str = astr(str, "promoted expression");
else if (info->actuals.v[i] && info->actuals.v[i]->hasFlag(FLAG_TYPE_VARIABLE))
str = astr(str, "type ", toString(info->actuals.v[i]->type));
else if (var && var->immediate) {
if (var->immediate->const_kind == CONST_KIND_STRING) {
str = astr(str, "\"", var->immediate->v_string, "\"");
} else {
const size_t bufSize = 512;
char buff[bufSize];
snprint_imm(buff, bufSize, *var->immediate);
str = astr(str, buff);
}
} else
str = astr(str, toString(info->actuals.v[i]->type));
}
if (!info->call->methodTag) {
if (info->call->square)
str = astr(str, "]");
else
str = astr(str, ")");
}
return str;
}
const char* toString(FnSymbol* fn) {
if (fn->userString) {
if (developer)
return astr(fn->userString, " [", istr(fn->id), "]");
else
return fn->userString;
}
const char* str;
int start = 0;
if (developer) {
// report the name as-is and include all args
str = fn->name;
} else {
if (fn->instantiatedFrom)
fn = fn->instantiatedFrom;
if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
// if not, make sure 'str' is built as desired
INT_ASSERT(!strncmp("_type_construct_", fn->name, 16));
str = astr(fn->name+16);
} else if (fn->hasFlag(FLAG_CONSTRUCTOR)) {
INT_ASSERT(!strncmp("_construct_", fn->name, 11));
str = astr(fn->name+11);
} else if (fn->isPrimaryMethod()) {
if (!strcmp(fn->name, "this")) {
INT_ASSERT(fn->hasFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION));
str = astr(toString(fn->getFormal(2)->type));
start = 1;
} else {
INT_ASSERT(! fn->hasFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION));
str = astr(toString(fn->getFormal(2)->type), ".", fn->name);
start = 2;
}
} else if (fn->hasFlag(FLAG_MODULE_INIT)) {
INT_ASSERT(!strncmp("chpl__init_", fn->name, 11)); //if not, fix next line
str = astr("top-level module statements for ", fn->name+11);
} else
str = astr(fn->name);
} // if !developer
bool skipParens =
fn->hasFlag(FLAG_NO_PARENS) ||
(fn->hasFlag(FLAG_TYPE_CONSTRUCTOR) && fn->numFormals() == 0) ||
(fn->hasFlag(FLAG_MODULE_INIT) && !developer);
if (!skipParens)
str = astr(str, "(");
bool first = false;
for (int i = start; i < fn->numFormals(); i++) {
ArgSymbol* arg = fn->getFormal(i+1);
if (arg->hasFlag(FLAG_IS_MEME))
continue;
if (!first) {
first = true;
if (skipParens)
str = astr(str, " ");
} else
str = astr(str, ", ");
if (arg->intent == INTENT_PARAM || arg->hasFlag(FLAG_INSTANTIATED_PARAM))
str = astr(str, "param ");
if (arg->hasFlag(FLAG_TYPE_VARIABLE))
str = astr(str, "type ", arg->name);
else if (arg->type == dtUnknown) {
SymExpr* sym = NULL;
if (arg->typeExpr)
sym = toSymExpr(arg->typeExpr->body.tail);
if (sym)
str = astr(str, arg->name, ": ", sym->var->name);
else
str = astr(str, arg->name);
} else if (arg->type == dtAny) {
str = astr(str, arg->name);
} else
str = astr(str, arg->name, ": ", toString(arg->type));
if (arg->variableExpr)
str = astr(str, " ...");
}
if (!skipParens)
str = astr(str, ")");
if (developer)
str = astr(str, " [", istr(fn->id), "]");
return str;
}
static FnSymbol*
protoIteratorMethod(IteratorInfo* ii, const char* name, Type* retType) {
FnSymbol* fn = new FnSymbol(name);
fn->addFlag(FLAG_AUTO_II);
if (strcmp(name, "advance"))
fn->addFlag(FLAG_INLINE);
fn->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
fn->addFlag(FLAG_METHOD);
fn->_this = new ArgSymbol(INTENT_BLANK, "this", ii->iclass);
fn->_this->addFlag(FLAG_ARG_THIS);
fn->retType = retType;
fn->insertFormalAtTail(fn->_this);
ii->iterator->defPoint->insertBefore(new DefExpr(fn));
normalize(fn);
// Pretend that this function is already resolved.
// Its body will be filled in during the lowerIterators pass.
fn->addFlag(FLAG_RESOLVED);
return fn;
}
static void
protoIteratorClass(FnSymbol* fn) {
INT_ASSERT(!fn->iteratorInfo);
SET_LINENO(fn);
IteratorInfo* ii = new IteratorInfo();
fn->iteratorInfo = ii;
fn->iteratorInfo->iterator = fn;
const char* className = astr(fn->name);
if (fn->_this)
className = astr(className, "_", fn->_this->type->symbol->cname);
ii->iclass = new AggregateType(AGGREGATE_CLASS);
TypeSymbol* cts = new TypeSymbol(astr("_ic_", className), ii->iclass);
cts->addFlag(FLAG_ITERATOR_CLASS);
add_root_type(ii->iclass); // Add super : dtObject.
fn->defPoint->insertBefore(new DefExpr(cts));
ii->irecord = new AggregateType(AGGREGATE_RECORD);
TypeSymbol* rts = new TypeSymbol(astr("_ir_", className), ii->irecord);
rts->addFlag(FLAG_ITERATOR_RECORD);
if (fn->retTag == RET_REF)
rts->addFlag(FLAG_REF_ITERATOR_CLASS);
fn->defPoint->insertBefore(new DefExpr(rts));
ii->tag = it_iterator;
ii->advance = protoIteratorMethod(ii, "advance", dtVoid);
ii->zip1 = protoIteratorMethod(ii, "zip1", dtVoid);
ii->zip2 = protoIteratorMethod(ii, "zip2", dtVoid);
ii->zip3 = protoIteratorMethod(ii, "zip3", dtVoid);
ii->zip4 = protoIteratorMethod(ii, "zip4", dtVoid);
ii->hasMore = protoIteratorMethod(ii, "hasMore", dtInt[INT_SIZE_DEFAULT]);
ii->getValue = protoIteratorMethod(ii, "getValue", fn->retType);
ii->init = protoIteratorMethod(ii, "init", dtVoid);
ii->incr = protoIteratorMethod(ii, "incr", dtVoid);
// The original iterator function is stashed in the defaultInitializer field
// of the iterator record type. Since we are only creating shell functions
// here, we still need a way to obtain the original iterator function, so we
// can fill in the bodies of the above 9 methods in the lowerIterators pass.
ii->irecord->defaultInitializer = fn;
ii->irecord->scalarPromotionType = fn->retType;
fn->retType = ii->irecord;
fn->retTag = RET_VALUE;
makeRefType(fn->retType);
ii->getIterator = new FnSymbol("_getIterator");
ii->getIterator->addFlag(FLAG_AUTO_II);
ii->getIterator->addFlag(FLAG_INLINE);
ii->getIterator->retType = ii->iclass;
ii->getIterator->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "ir", ii->irecord));
VarSymbol* ret = newTemp("_ic_", ii->iclass);
ii->getIterator->insertAtTail(new DefExpr(ret));
CallExpr* icAllocCall = callChplHereAlloc(ret->typeInfo()->symbol);
ii->getIterator->insertAtTail(new CallExpr(PRIM_MOVE, ret, icAllocCall));
ii->getIterator->insertAtTail(new CallExpr(PRIM_SETCID, ret));
ii->getIterator->insertAtTail(new CallExpr(PRIM_RETURN, ret));
fn->defPoint->insertBefore(new DefExpr(ii->getIterator));
// The _getIterator function is stashed in the defaultInitializer field of
// the iterator class type. This makes it easy to obtain the iterator given
// just a symbol of the iterator class type. This may include _getIterator
// and _getIteratorZip functions in the module code.
ii->iclass->defaultInitializer = ii->getIterator;
normalize(ii->getIterator);
resolveFns(ii->getIterator); // No shortcuts.
}
//
// returns true if the field was instantiated
//
static bool
isInstantiatedField(Symbol* field) {
TypeSymbol* ts = toTypeSymbol(field->defPoint->parentSymbol);
INT_ASSERT(ts);
AggregateType* ct = toAggregateType(ts->type);
INT_ASSERT(ct);
for_formals(formal, ct->defaultTypeConstructor) {
if (!strcmp(field->name, formal->name))
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
return true;
}
return false;
}
//
// determine field associated with query expression
//
static Symbol*
determineQueriedField(CallExpr* call) {
AggregateType* ct = toAggregateType(call->get(1)->getValType());
INT_ASSERT(ct);
SymExpr* last = toSymExpr(call->get(call->numActuals()));
INT_ASSERT(last);
VarSymbol* var = toVarSymbol(last->var);
INT_ASSERT(var && var->immediate);
if (var->immediate->const_kind == CONST_KIND_STRING) {
// field queried by name
return ct->getField(var->immediate->v_string, false);
} else {
// field queried by position
int position = var->immediate->int_value();
Vec<ArgSymbol*> args;
for_formals(arg, ct->defaultTypeConstructor) {
args.add(arg);
}
for (int i = 2; i < call->numActuals(); i++) {
SymExpr* actual = toSymExpr(call->get(i));
INT_ASSERT(actual);
VarSymbol* var = toVarSymbol(actual->var);
INT_ASSERT(var && var->immediate && var->immediate->const_kind == CONST_KIND_STRING);
for (int j = 0; j < args.n; j++) {
if (args.v[j] && !strcmp(args.v[j]->name, var->immediate->v_string))
args.v[j] = NULL;
}
}
forv_Vec(ArgSymbol, arg, args) {
if (arg) {
if (position == 1)
return ct->getField(arg->name, false);
position--;
}
}
}
return NULL;
}
//
// For some types, e.g. _domain/_array records, implementing
// Chapel's ref/out/... intents can be done simply by passing the
// value itself, rather than address-of. This function flags such cases
// by returning false, meaning "not OK to convert".
//
static bool
okToConvertFormalToRefType(Type* type) {
if (isRecordWrappedType(type))
// no, don't
return false;
// otherwise, proceed with the original plan
return true;
}
static void
resolveSpecifiedReturnType(FnSymbol* fn) {
resolveBlockStmt(fn->retExprType);
fn->retType = fn->retExprType->body.tail->typeInfo();
if (fn->retType != dtUnknown) {
if (fn->retTag == RET_REF) {
makeRefType(fn->retType);
fn->retType = fn->retType->refType;
}
fn->retExprType->remove();
if (fn->isIterator() && !fn->iteratorInfo) {
protoIteratorClass(fn);
}
}
}
//
// Generally, atomics must also be passed by reference when
// passed by blank intent. The following expression checks for
// these cases by looking for atomics passed by blank intent and
// changing their type to a ref type. Interestingly, this
// conversion does not seem to be required for single-locale
// compilation, but it is for multi-locale. Otherwise, updates
// to atomics are lost (as demonstrated by
// test/functions/bradc/intents/test_pass_atomic.chpl).
//
// I say "generally" because there are a few cases where passing
// atomics by reference breaks things -- primarily in
// constructors, assignment operators, and tuple construction.
// So we have some unfortunate special checks that dance around
// these cases.
//
// While I can't explain precisely why these special cases are
// required yet, here are the tests that tend to have problems
// without these special conditions:
//
// test/release/examples/benchmarks/hpcc/ra-atomics.chpl
// test/types/atomic/sungeun/no_atomic_assign.chpl
// test/functions/bradc/intents/test_construct_atomic_intent.chpl
// test/users/vass/barrierWF.test-1.chpl
// test/studies/shootout/spectral-norm/spectralnorm.chpl
// test/release/examples/benchmarks/ssca2/SSCA2_main.chpl
// test/parallel/taskPar/sungeun/barrier/*.chpl
//
static bool convertAtomicFormalTypeToRef(ArgSymbol* formal, FnSymbol* fn) {
return (formal->intent == INTENT_BLANK &&
!formal->hasFlag(FLAG_TYPE_VARIABLE) &&
isAtomicType(formal->type))
&& !fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR)
&& !fn->hasFlag(FLAG_CONSTRUCTOR)
&& strcmp(fn->name,"=") != 0
&& !fn->hasFlag(FLAG_BUILD_TUPLE);
}
void
resolveFormals(FnSymbol* fn) {
static Vec<FnSymbol*> done;
if (!fn->hasFlag(FLAG_GENERIC)) {
if (done.set_in(fn))
return;
done.set_add(fn);
for_formals(formal, fn) {
if (formal->type == dtUnknown) {
if (!formal->typeExpr) {
formal->type = dtObject;
} else {
resolveBlockStmt(formal->typeExpr);
formal->type = formal->typeExpr->body.tail->getValType();
}
}
//
// Fix up value types that need to be ref types.
//
if (formal->type->symbol->hasFlag(FLAG_REF))
// Already a ref type, so done.
continue;
if (formal->intent == INTENT_INOUT ||
formal->intent == INTENT_OUT ||
formal->intent == INTENT_REF ||
formal->intent == INTENT_CONST_REF ||
convertAtomicFormalTypeToRef(formal, fn) ||
formal->hasFlag(FLAG_WRAP_WRITTEN_FORMAL) ||
(formal == fn->_this &&
(isUnion(formal->type) ||
isRecord(formal->type)))) {
if (okToConvertFormalToRefType(formal->type)) {
makeRefType(formal->type);
formal->type = formal->type->refType;
// The type of the formal is its own ref type!
}
}
}
if (fn->retExprType)
resolveSpecifiedReturnType(fn);
resolvedFormals.set_add(fn);
}
}
static bool fits_in_int_helper(int width, int64_t val) {
switch (width) {
default: INT_FATAL("bad width in fits_in_int_helper");
case 1:
return (val == 0 || val == 1);
case 8:
return (val >= INT8_MIN && val <= INT8_MAX);
case 16:
return (val >= INT16_MIN && val <= INT16_MAX);
case 32:
return (val >= INT32_MIN && val <= INT32_MAX);
case 64:
// As an int64_t will always fit within a 64 bit int.
return true;
}
}
static bool fits_in_int(int width, Immediate* imm) {
if (imm->const_kind == NUM_KIND_INT && imm->num_index == INT_SIZE_DEFAULT) {
int64_t i = imm->int_value();
return fits_in_int_helper(width, i);
}
/* BLC: There is some question in my mind about whether this
function should include the following code as well -- that is,
whether default-sized uint params should get the same special
treatment in cases like this. I didn't enable it for now because
nothing seemed to rely on it and I didn't come up with a case
that would. But it's worth keeping around for future
consideration.
Similarly, we may want to consider enabling such param casts for
int sizes other then default-width.
else if (imm->const_kind == NUM_KIND_UINT &&
imm->num_index == INT_SIZE_DEFAULT) {
uint64_t u = imm->uint_value();
int64_t i = (int64_t)u;
if (i < 0)
return false;
return fits_in_int_helper(width, i);
}*/
return false;
}
static bool fits_in_uint_helper(int width, uint64_t val) {
switch (width) {
default: INT_FATAL("bad width in fits_in_uint_helper");
case 8:
return (val <= UINT8_MAX);
case 16:
return (val <= UINT16_MAX);
case 32:
return (val <= UINT32_MAX);
case 64:
// As a uint64_t will always fit inside a 64 bit uint.
return true;
}
}
static bool fits_in_uint(int width, Immediate* imm) {
if (imm->const_kind == NUM_KIND_INT && imm->num_index == INT_SIZE_DEFAULT) {
int64_t i = imm->int_value();
if (i < 0)
return false;
return fits_in_uint_helper(width, (uint64_t)i);
}
/* BLC: See comment just above in fits_in_int()...
else if (imm->const_kind == NUM_KIND_UINT && imm->num_index == INT_SIZE_64) {
uint64_t u = imm->uint_value();
return fits_in_uint_helper(width, u);
}*/
return false;
}
static void ensureEnumTypeResolved(EnumType* etype) {
INT_ASSERT( etype != NULL );
if( ! etype->integerType ) {
// Make sure to resolve all enum types.
for_enums(def, etype) {
if (def->init) {
Expr* enumTypeExpr =
resolve_type_expr(def->init);
Type* enumtype = enumTypeExpr->typeInfo();
if (enumtype == dtUnknown)
INT_FATAL(def->init, "Unable to resolve enumerator type expression");
// printf("Type of %s.%s is %s\n", etype->symbol->name, def->sym->name,
// enumtype->symbol->name);
}
}
// Now try computing the enum size...
etype->sizeAndNormalize();
}
INT_ASSERT(etype->integerType != NULL);
}
// Is this a legal actual argument where an l-value is required?
// I.e. for an out/inout/ref formal.
static bool
isLegalLvalueActualArg(ArgSymbol* formal, Expr* actual) {
if (SymExpr* se = toSymExpr(actual))
if (se->var->hasFlag(FLAG_EXPR_TEMP) ||
((se->var->hasFlag(FLAG_REF_TO_CONST) ||
se->var->isConstant()) && !formal->hasFlag(FLAG_ARG_THIS)) ||
se->var->isParameter())
if (okToConvertFormalToRefType(formal->type) ||
// If the user says 'const', it means 'const'.
// Honor FLAG_CONST if it is a coerce temp, too.
(se->var->hasFlag(FLAG_CONST) &&
(!se->var->hasFlag(FLAG_TEMP) || se->var->hasFlag(FLAG_COERCE_TEMP))
))
return false;
// Perhaps more checks are needed.
return true;
}
// Is this a legal actual argument for a 'const ref' formal?
// At present, params cannot be passed to 'const ref'.
static bool
isLegalConstRefActualArg(ArgSymbol* formal, Expr* actual) {
if (SymExpr* se = toSymExpr(actual))
if (se->var->isParameter())
if (okToConvertFormalToRefType(formal->type))
return false;
// Perhaps more checks are needed.
return true;
}
// Returns true iff dispatching the actualType to the formalType
// results in an instantiation.
static bool
canInstantiate(Type* actualType, Type* formalType) {
if (actualType == dtMethodToken)
return false;
if (formalType == dtAny)
return true;
if (formalType == dtIntegral && (is_int_type(actualType) || is_uint_type(actualType)))
return true;
if (formalType == dtAnyEnumerated && (is_enum_type(actualType)))
return true;
if (formalType == dtNumeric &&
(is_int_type(actualType) || is_uint_type(actualType) || is_imag_type(actualType) ||
is_real_type(actualType) || is_complex_type(actualType)))
return true;
if (formalType == dtString && actualType==dtStringC)
return true;
if (formalType == dtStringC && actualType==dtStringCopy)
return true;
if (formalType == dtIteratorRecord && actualType->symbol->hasFlag(FLAG_ITERATOR_RECORD))
return true;
if (formalType == dtIteratorClass && actualType->symbol->hasFlag(FLAG_ITERATOR_CLASS))
return true;
if (actualType == formalType)
return true;
if (actualType->instantiatedFrom && canInstantiate(actualType->instantiatedFrom, formalType))
return true;
return false;
}
//
// returns true if dispatching from actualType to formalType results
// in a compile-time coercion; this is a subset of canCoerce below as,
// for example, real(32) cannot be coerced to real(64) at compile-time
//
static bool canParamCoerce(Type* actualType, Symbol* actualSym, Type* formalType) {
if (is_bool_type(formalType) && is_bool_type(actualType))
return true;
if (is_int_type(formalType)) {
if (is_bool_type(actualType))
return true;
if (is_int_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
if (is_uint_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
//
// If the actual is an enum, check to see if *all* its values
// are small enough that they fit into this integer width
//
if (EnumType* etype = toEnumType(actualType)) {
ensureEnumTypeResolved(etype);
if (get_width(etype->getIntegerType()) <= get_width(formalType))
return true;
}
//
// For smaller integer types, if the argument is a param, does it
// store a value that's small enough that it could dispatch to
// this argument?
//
if (get_width(formalType) < 64) {
if (VarSymbol* var = toVarSymbol(actualSym))
if (var->immediate)
if (fits_in_int(get_width(formalType), var->immediate))
return true;
if (EnumType* etype = toEnumType(actualType)) {
ensureEnumTypeResolved(etype);
if (EnumSymbol* enumsym = toEnumSymbol(actualSym)) {
if (Immediate* enumval = enumsym->getImmediate()) {
if (fits_in_int(get_width(formalType), enumval)) {
return true;
}
}
}
}
}
}
if (is_uint_type(formalType)) {
if (is_bool_type(actualType))
return true;
if (is_uint_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
if (VarSymbol* var = toVarSymbol(actualSym))
if (var->immediate)
if (fits_in_uint(get_width(formalType), var->immediate))
return true;
}
return false;
}
//
// returns true iff dispatching the actualType to the formalType
// results in a coercion.
//
bool
canCoerce(Type* actualType, Symbol* actualSym, Type* formalType, FnSymbol* fn, bool* promotes) {
if (canParamCoerce(actualType, actualSym, formalType))
return true;
if (is_real_type(formalType)) {
if ((is_int_type(actualType) || is_uint_type(actualType))
&& get_width(formalType) >= 64)
return true;
if (is_real_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
}
if (is_complex_type(formalType)) {
if ((is_int_type(actualType) || is_uint_type(actualType))
&& get_width(formalType) >= 128)
return true;
if (is_real_type(actualType) &&
(get_width(actualType) <= get_width(formalType)/2))
return true;
if (is_imag_type(actualType) &&
(get_width(actualType) <= get_width(formalType)/2))
return true;
if (is_complex_type(actualType) &&
(get_width(actualType) < get_width(formalType)))
return true;
}
if (isSyncType(actualType)) {
Type* baseType = actualType->getField("base_type")->type;
return canDispatch(baseType, NULL, formalType, fn, promotes);
}
if (actualType->symbol->hasFlag(FLAG_REF))
return canDispatch(actualType->getValType(), NULL, formalType, fn, promotes);
if (// isLcnSymbol(actualSym) && // What does this exclude?
actualType == dtStringC && formalType == dtString)
return true;
if (formalType == dtStringC && actualType == dtStringCopy)
return true;
if (formalType == dtString && actualType == dtStringCopy)
return true;
return false;
}
// Returns true iff the actualType can dispatch to the formalType.
// The function symbol is used to avoid scalar promotion on =.
// param is set if the actual is a parameter (compile-time constant).
bool
canDispatch(Type* actualType, Symbol* actualSym, Type* formalType, FnSymbol* fn, bool* promotes, bool paramCoerce) {
if (promotes)
*promotes = false;
if (actualType == formalType)
return true;
//
// The following check against FLAG_REF ensures that 'nil' can't be
// passed to a by-ref argument (for example, an atomic type). I
// found that without this, calls like autocopy(nil) became
// ambiguous when given the choice between the completely generic
// autocopy(x) and the autocopy(x: atomic int) (represented as
// autocopy(x: ref(atomic int)) internally).
//
if (actualType == dtNil && isClass(formalType) &&
!formalType->symbol->hasFlag(FLAG_REF))
return true;
if (actualType->refType == formalType)
return true;
if (!paramCoerce && canCoerce(actualType, actualSym, formalType, fn, promotes))
return true;
if (paramCoerce && canParamCoerce(actualType, actualSym, formalType))
return true;
forv_Vec(Type, parent, actualType->dispatchParents) {
if (parent == formalType || canDispatch(parent, NULL, formalType, fn, promotes)) {
return true;
}
}
if (fn &&
strcmp(fn->name, "=") &&
actualType->scalarPromotionType &&
(canDispatch(actualType->scalarPromotionType, NULL, formalType, fn))) {
if (promotes)
*promotes = true;
return true;
}
return false;
}
bool
isDispatchParent(Type* t, Type* pt) {
forv_Vec(Type, p, t->dispatchParents)
if (p == pt || isDispatchParent(p, pt))
return true;
return false;
}
static bool
moreSpecific(FnSymbol* fn, Type* actualType, Type* formalType) {
if (canDispatch(actualType, NULL, formalType, fn))
return true;
if (canInstantiate(actualType, formalType)) {
return true;
}
return false;
}
static bool
computeActualFormalAlignment(FnSymbol* fn,
Vec<Symbol*>& alignedActuals,
Vec<ArgSymbol*>& alignedFormals,
CallInfo& info) {
alignedActuals.fill(fn->numFormals());
alignedFormals.fill(info.actuals.n);
// Match named actuals against formal names in the function signature.
// Record successful matches.
for (int i = 0; i < alignedFormals.n; i++) {
if (info.actualNames.v[i]) {
bool match = false;
int j = 0;
for_formals(formal, fn) {
if (!strcmp(info.actualNames.v[i], formal->name)) {
match = true;
alignedFormals.v[i] = formal;
alignedActuals.v[j] = info.actuals.v[i];
break;
}
j++;
}
// Fail if no matching formal is found.
if (!match)
return false;
}
}
// Fill in unmatched formals in sequence with the remaining actuals.
// Record successful substitutions.
int j = 0;
ArgSymbol* formal = (fn->numFormals()) ? fn->getFormal(1) : NULL;
for (int i = 0; i < alignedFormals.n; i++) {
if (!info.actualNames.v[i]) {
bool match = false;
while (formal) {
if (formal->variableExpr)
return (fn->hasFlag(FLAG_GENERIC)) ? true : false;
if (!alignedActuals.v[j]) {
match = true;
alignedFormals.v[i] = formal;
alignedActuals.v[j] = info.actuals.v[i];
break;
}
formal = next_formal(formal);
j++;
}
// Fail if there are too many unnamed actuals.
if (!match && !(fn->hasFlag(FLAG_GENERIC) && fn->hasFlag(FLAG_TUPLE)))
return false;
}
}
// Make sure that any remaining formals are matched by name
// or have a default value.
while (formal) {
if (!alignedActuals.v[j] && !formal->defaultExpr)
// Fail if not.
return false;
formal = next_formal(formal);
j++;
}
return true;
}
//
// returns the type that a formal type should be instantiated to when
// instantiated by a given actual type
//
static Type*
getInstantiationType(Type* actualType, Type* formalType) {
if (canInstantiate(actualType, formalType)) {
return actualType;
}
if (Type* st = actualType->scalarPromotionType) {
if (canInstantiate(st, formalType))
return st;
}
if (Type* vt = actualType->getValType()) {
if (canInstantiate(vt, formalType))
return vt;
else if (Type* st = vt->scalarPromotionType)
if (canInstantiate(st, formalType))
return st;
}
return NULL;
}
static void
computeGenericSubs(SymbolMap &subs,
FnSymbol* fn,
Vec<Symbol*>& alignedActuals) {
int i = 0;
for_formals(formal, fn) {
if (formal->intent == INTENT_PARAM) {
if (alignedActuals.v[i] && alignedActuals.v[i]->isParameter()) {
if (!formal->type->symbol->hasFlag(FLAG_GENERIC) ||
canInstantiate(alignedActuals.v[i]->type, formal->type))
subs.put(formal, alignedActuals.v[i]);
} else if (!alignedActuals.v[i] && formal->defaultExpr) {
// break because default expression may reference generic
// arguments earlier in formal list; make those substitutions
// first (test/classes/bradc/paramInClass/weirdParamInit4)
if (subs.n)
break;
resolveBlockStmt(formal->defaultExpr);
SymExpr* se = toSymExpr(formal->defaultExpr->body.tail);
if (se && se->var->isParameter() &&
(!formal->type->symbol->hasFlag(FLAG_GENERIC) || canInstantiate(se->var->type, formal->type)))
subs.put(formal, se->var);
else
INT_FATAL(fn, "unable to handle default parameter");
}
} else if (formal->type->symbol->hasFlag(FLAG_GENERIC)) {
//
// check for field with specified generic type
//
if (!formal->hasFlag(FLAG_TYPE_VARIABLE) && formal->type != dtAny &&
strcmp(formal->name, "outer") && strcmp(formal->name, "meme") &&
(fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)))
USR_FATAL(formal, "invalid generic type specification on class field");
if (alignedActuals.v[i]) {
if (Type* type = getInstantiationType(alignedActuals.v[i]->type, formal->type)) {
// String literal actuals aligned with non-param generic
// formals of type dtAny will result in an instantiation of
// a dtString formal. This is in line with variable
// declarations with non-typed initializing expressions and
// non-param formals with string literal default expressions
// (see fix_def_expr() and hack_resolve_types() in
// normalize.cpp). This conversion is not performed for extern
// functions.
if ((!fn->hasFlag(FLAG_EXTERN)) && (formal->type == dtAny) &&
(!formal->hasFlag(FLAG_PARAM)) && (type == dtStringC) &&
(alignedActuals.v[i]->type == dtStringC) &&
(alignedActuals.v[i]->isImmediate()))
subs.put(formal, dtString->symbol);
else
subs.put(formal, type->symbol);
}
} else if (formal->defaultExpr) {
// break because default expression may reference generic
// arguments earlier in formal list; make those substitutions
// first (test/classes/bradc/genericTypes)
if (subs.n)
break;
resolveBlockStmt(formal->defaultExpr);
Type* defaultType = formal->defaultExpr->body.tail->typeInfo();
if (defaultType == dtTypeDefaultToken)
subs.put(formal, dtTypeDefaultToken->symbol);
else if (Type* type = getInstantiationType(defaultType, formal->type))
subs.put(formal, type->symbol);
}
}
i++;
}
}
/** Common code for multiple paths through expandVarArgs.
*
* This code handles the case where the number of varargs are known at compile
* time. It inserts the necessary code to copy the values into and out of the
* varargs tuple.
*/
static void
handleSymExprInExpandVarArgs(FnSymbol* workingFn, ArgSymbol* formal, SymExpr* sym) {
workingFn->addFlag(FLAG_EXPANDED_VARARGS);
// Handle specified number of variable arguments.
if (VarSymbol* n_var = toVarSymbol(sym->var)) {
if (n_var->type == dtInt[INT_SIZE_DEFAULT] && n_var->immediate) {
int n = n_var->immediate->int_value();
CallExpr* tupleCall = new CallExpr((formal->hasFlag(FLAG_TYPE_VARIABLE)) ?
"_type_construct__tuple" : "_construct__tuple");
for (int i = 0; i < n; i++) {
DefExpr* new_arg_def = formal->defPoint->copy();
ArgSymbol* new_formal = toArgSymbol(new_arg_def->sym);
new_formal->variableExpr = NULL;
tupleCall->insertAtTail(new SymExpr(new_formal));
new_formal->name = astr("_e", istr(i), "_", formal->name);
new_formal->cname = astr("_e", istr(i), "_", formal->cname);
formal->defPoint->insertBefore(new_arg_def);
}
VarSymbol* var = new VarSymbol(formal->name);
// Replace mappings to the old formal with mappings to the new variable.
if (workingFn->hasFlag(FLAG_PARTIAL_COPY)) {
for (int index = workingFn->partialCopyMap.n; --index >= 0;) {
SymbolMapElem& mapElem = workingFn->partialCopyMap.v[index];
if (mapElem.value == formal) {
mapElem.value = var;
break;
}
}
}
if (formal->hasFlag(FLAG_TYPE_VARIABLE)) {
var->addFlag(FLAG_TYPE_VARIABLE);
}
if (formal->intent == INTENT_OUT || formal->intent == INTENT_INOUT) {
int i = 1;
for_actuals(actual, tupleCall) {
VarSymbol* tmp = newTemp("_varargs_tmp_");
workingFn->insertBeforeReturnAfterLabel(new DefExpr(tmp));
workingFn->insertBeforeReturnAfterLabel(new CallExpr(PRIM_MOVE, tmp, new CallExpr(var, new_IntSymbol(i))));
workingFn->insertBeforeReturnAfterLabel(new CallExpr("=", actual->copy(), tmp));
i++;
}
}
tupleCall->insertAtHead(new_IntSymbol(n));
workingFn->insertAtHead(new CallExpr(PRIM_MOVE, var, tupleCall));
workingFn->insertAtHead(new DefExpr(var));
formal->defPoint->remove();
if (workingFn->hasFlag(FLAG_PARTIAL_COPY)) {
// If this is a partial copy, store the mapping for substitution later.
workingFn->partialCopyMap.put(formal, var);
} else {
// Otherwise, do the substitution now.
subSymbol(workingFn->body, formal, var);
}
if (workingFn->where) {
VarSymbol* var = new VarSymbol(formal->name);
if (formal->hasFlag(FLAG_TYPE_VARIABLE)) {
var->addFlag(FLAG_TYPE_VARIABLE);
}
workingFn->where->insertAtHead(new CallExpr(PRIM_MOVE, var, tupleCall->copy()));
workingFn->where->insertAtHead(new DefExpr(var));
subSymbol(workingFn->where, formal, var);
}
}
}
}
static FnSymbol*
expandVarArgs(FnSymbol* origFn, int numActuals) {
bool genericArgSeen = false;
FnSymbol* workingFn = origFn;
SymbolMap substitutions;
static Map<FnSymbol*,Vec<FnSymbol*>*> cache;
// check for cached stamped out function
if (Vec<FnSymbol*>* cfns = cache.get(origFn)) {
forv_Vec(FnSymbol, cfn, *cfns) {
if (cfn->numFormals() == numActuals) return cfn;
}
}
for_formals(formal, origFn) {
if (workingFn != origFn) {
formal = toArgSymbol(substitutions.get(formal));
}
if (!genericArgSeen && formal->variableExpr && !isDefExpr(formal->variableExpr->body.tail)) {
resolveBlockStmt(formal->variableExpr);
}
/*
* Set genericArgSeen to true if a generic argument appears before the
* argument with the variable expression.
*/
// INT_ASSERT(arg->type);
// Adding 'ref' intent to the "ret" arg of
// inline proc =(ref ret:syserr, x:syserr) { __primitive("=", ret, x); }
// in SysBasic.chpl:150 causes a segfault.
// The addition of the arg->type test in the folloiwng conditional is a
// workaround.
// A better approach would be to add a check that each formal of a function
// has a type (if that can be expected) and then fix the fault where it occurs.
if (formal->type && formal->type->symbol->hasFlag(FLAG_GENERIC)) {
genericArgSeen = true;
}
if (!formal->variableExpr) {
continue;
}
// Handle unspecified variable number of arguments.
if (DefExpr* def = toDefExpr(formal->variableExpr->body.tail)) {
int numCopies = numActuals - workingFn->numFormals() + 1;
if (numCopies <= 0) {
if (workingFn != origFn) delete workingFn;
return NULL;
}
if (workingFn == origFn) {
workingFn = origFn->copy(&substitutions);
INT_ASSERT(! workingFn->hasFlag(FLAG_RESOLVED));
workingFn->addFlag(FLAG_INVISIBLE_FN);
origFn->defPoint->insertBefore(new DefExpr(workingFn));
formal = static_cast<ArgSymbol*>(substitutions.get(formal));
}
Symbol* newSym = substitutions.get(def->sym);
SymExpr* newSymExpr = new SymExpr(new_IntSymbol(numCopies));
newSym->defPoint->replace(newSymExpr);
subSymbol(workingFn, newSym, new_IntSymbol(numCopies));
handleSymExprInExpandVarArgs(workingFn, formal, newSymExpr);
genericArgSeen = false;
} else if (SymExpr* sym = toSymExpr(formal->variableExpr->body.tail)) {
handleSymExprInExpandVarArgs(workingFn, formal, sym);
} else if (!workingFn->hasFlag(FLAG_GENERIC)) {
INT_FATAL("bad variableExpr");
}
}
Vec<FnSymbol*>* cfns = cache.get(origFn);
if (cfns == NULL) {
cfns = new Vec<FnSymbol*>();
}
cfns->add(workingFn);
cache.put(origFn, cfns);
return workingFn;
}
static void
resolve_type_constructor(FnSymbol* fn, CallInfo& info) {
SET_LINENO(fn);
CallExpr* typeConstructorCall = new CallExpr(astr("_type", fn->name));
for_formals(formal, fn) {
if (strcmp(formal->name, "meme")) {
if (fn->_this->type->symbol->hasFlag(FLAG_TUPLE)) {
if (formal->instantiatedFrom) {
typeConstructorCall->insertAtTail(formal->type->symbol);
} else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) {
typeConstructorCall->insertAtTail(paramMap.get(formal));
}
} else {
if (!strcmp(formal->name, "outer") || formal->type == dtMethodToken) {
typeConstructorCall->insertAtTail(formal);
} else if (formal->instantiatedFrom) {
typeConstructorCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal->type->symbol)));
} else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) {
typeConstructorCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(paramMap.get(formal))));
}
}
}
}
info.call->insertBefore(typeConstructorCall);
resolveCall(typeConstructorCall);
INT_ASSERT(typeConstructorCall->isResolved());
resolveFns(typeConstructorCall->isResolved());
fn->_this->type = typeConstructorCall->isResolved()->retType;
typeConstructorCall->remove();
}
/** Candidate filtering logic specific to concrete functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterConcreteCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
currCandidate->fn = expandVarArgs(currCandidate->fn, info.actuals.n);
if (!currCandidate->fn) return;
resolveTypedefedArgTypes(currCandidate->fn);
if (!currCandidate->computeAlignment(info)) {
return;
}
/*
* Make sure that type constructor is resolved before other constructors.
*/
if (currCandidate->fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR)) {
resolve_type_constructor(currCandidate->fn, info);
}
/*
* A derived generic type will use the type of its parent, and expects this to
* be instantiated before it is.
*/
resolveFormals(currCandidate->fn);
int coindex = -1;
for_formals(formal, currCandidate->fn) {
if (Symbol* actual = currCandidate->alignedActuals.v[++coindex]) {
if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) {
return;
}
if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formal->hasFlag(FLAG_INSTANTIATED_PARAM))) {
return;
}
}
}
candidates.add(currCandidate);
}
/** Candidate filtering logic specific to generic functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterGenericCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
currCandidate->fn = expandVarArgs(currCandidate->fn, info.actuals.n);
if (!currCandidate->fn) return;
if (!currCandidate->computeAlignment(info)) {
return;
}
/*
* Early rejection of generic functions.
*/
int coindex = 0;
for_formals(formal, currCandidate->fn) {
if (formal->type != dtUnknown) {
if (Symbol* actual = currCandidate->alignedActuals.v[coindex]) {
if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) {
return;
}
if (formal->type->symbol->hasFlag(FLAG_GENERIC)) {
Type* vt = actual->getValType();
Type* st = actual->type->scalarPromotionType;
Type* svt = (vt) ? vt->scalarPromotionType : NULL;
if (!canInstantiate(actual->type, formal->type) &&
(!vt || !canInstantiate(vt, formal->type)) &&
(!st || !canInstantiate(st, formal->type)) &&
(!svt || !canInstantiate(svt, formal->type))) {
return;
}
} else {
if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formal->hasFlag(FLAG_INSTANTIATED_PARAM))) {
return;
}
}
}
}
++coindex;
}
// Compute the param/type substitutions for generic arguments.
currCandidate->computeSubstitutions();
/*
* If no substitutions were made we can't instantiate this generic, and must
* reject it.
*/
if (currCandidate->substitutions.n > 0) {
/*
* Instantiate just enough of the generic to get through the rest of the
* filtering and disambiguation processes.
*/
currCandidate->fn = instantiateSignature(currCandidate->fn, currCandidate->substitutions, info.call);
if (currCandidate->fn != NULL) {
filterCandidate(candidates, currCandidate, info);
}
}
}
/** Tests to see if a function is a candidate for resolving a specific call. If
* it is a candidate, we add it to the candidate lists.
*
* This version of filterCandidate is called by other versions of
* filterCandidate, and shouldn't be called outside this family of functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
if (currCandidate->fn->hasFlag(FLAG_GENERIC)) {
filterGenericCandidate(candidates, currCandidate, info);
} else {
filterConcreteCandidate(candidates, currCandidate, info);
}
}
/** Tests to see if a function is a candidate for resolving a specific call. If
* it is a candidate, we add it to the candidate lists.
*
* This version of filterCandidate is called by code outside the filterCandidate
* family of functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates, FnSymbol* fn, CallInfo& info) {
ResolutionCandidate* currCandidate = new ResolutionCandidate(fn);
filterCandidate(candidates, currCandidate, info);
if (candidates.tail() != currCandidate) {
// The candidate was not accepted. Time to clean it up.
delete currCandidate;
}
}
static BlockStmt*
getParentBlock(Expr* expr) {
for (Expr* tmp = expr->parentExpr; tmp; tmp = tmp->parentExpr) {
if (BlockStmt* block = toBlockStmt(tmp))
return block;
}
if (expr->parentSymbol) {
FnSymbol* parentFn = toFnSymbol(expr->parentSymbol);
if (parentFn && parentFn->instantiationPoint)
return parentFn->instantiationPoint;
else if (expr->parentSymbol->defPoint)
return getParentBlock(expr->parentSymbol->defPoint);
}
return NULL;
}
//
// helper routine for isMoreVisible (below);
//
static bool
isMoreVisibleInternal(BlockStmt* block, FnSymbol* fn1, FnSymbol* fn2,
Vec<BlockStmt*>& visited) {
//
// fn1 is more visible
//
if (fn1->defPoint->parentExpr == block)
return true;
//
// fn2 is more visible
//
if (fn2->defPoint->parentExpr == block)
return false;
visited.set_add(block);
//
// default to true if neither are visible
//
bool moreVisible = true;
//
// ensure f2 is not more visible via parent block, and recurse
//
if (BlockStmt* parentBlock = getParentBlock(block))
if (!visited.set_in(parentBlock))
moreVisible &= isMoreVisibleInternal(parentBlock, fn1, fn2, visited);
//
// ensure f2 is not more visible via module uses, and recurse
//
if (block && block->modUses) {
for_actuals(expr, block->modUses) {
SymExpr* se = toSymExpr(expr);
INT_ASSERT(se);
ModuleSymbol* mod = toModuleSymbol(se->var);
INT_ASSERT(mod);
if (!visited.set_in(mod->block))
moreVisible &= isMoreVisibleInternal(mod->block, fn1, fn2, visited);
}
}
return moreVisible;
}
//
// return true if fn1 is more visible than fn2 from expr
//
// assumption: fn1 and fn2 are visible from expr; if this assumption
// is violated, this function will return true
//
static bool
isMoreVisible(Expr* expr, FnSymbol* fn1, FnSymbol* fn2) {
//
// common-case check to see if functions have equal visibility
//
if (fn1->defPoint->parentExpr == fn2->defPoint->parentExpr) {
// Special check which makes cg-initializers inferior to user-defined constructors
// with the same args.
if (fn2->hasFlag(FLAG_DEFAULT_CONSTRUCTOR))
return true;
return false;
}
//
// call helper function with visited set to avoid infinite recursion
//
Vec<BlockStmt*> visited;
BlockStmt* block = toBlockStmt(expr);
if (!block)
block = getParentBlock(expr);
return isMoreVisibleInternal(block, fn1, fn2, visited);
}
static bool paramWorks(Symbol* actual, Type* formalType) {
Immediate* imm = NULL;
if (VarSymbol* var = toVarSymbol(actual)) {
imm = var->immediate;
}
if (EnumSymbol* enumsym = toEnumSymbol(actual)) {
ensureEnumTypeResolved(toEnumType(enumsym->type));
imm = enumsym->getImmediate();
}
if (imm) {
if (is_int_type(formalType)) {
return fits_in_int(get_width(formalType), imm);
}
if (is_uint_type(formalType)) {
return fits_in_uint(get_width(formalType), imm);
}
}
return false;
}
//
// This is a utility function that essentially tracks which function,
// if any, the param arguments prefer.
//
static inline void registerParamPreference(int& paramPrefers, int preference,
const char* argstr,
DisambiguationContext DC) {
if (paramPrefers == 0 || paramPrefers == preference) {
/* if the param currently has no preference or it matches the new
preference, preserve the current preference */
paramPrefers = preference;
TRACE_DISAMBIGUATE_BY_MATCH("param prefers %s\n", argstr);
} else {
/* otherwise its preference contradicts the previous arguments, so
mark it as not preferring either */
paramPrefers = -1;
TRACE_DISAMBIGUATE_BY_MATCH("param prefers differing things\n");
}
}
static bool considerParamMatches(Type* actualtype,
Type* arg1type, Type* arg2type) {
/* BLC: Seems weird to have to add this; could just add it in the enum
case if enums have to be special-cased here. Otherwise, how are the
int cases handled later...? */
if (actualtype->symbol->hasFlag(FLAG_REF)) {
actualtype = actualtype->getValType();
}
if (actualtype == arg1type && actualtype != arg2type) {
return true;
}
// If we don't have an exact match in the previous line, let's see if
// we have a bool(w1) passed to bool(w2) or non-bool case; This is
// based on the enum case developed in r20208
if (is_bool_type(actualtype) && is_bool_type(arg1type) && !is_bool_type(arg2type)) {
return true;
}
// Otherwise, have bool cast to default-sized integer over a smaller size
if (is_bool_type(actualtype) && actualtype != arg1type && actualtype != arg2type) {
return considerParamMatches(dtInt[INT_SIZE_DEFAULT], arg1type, arg2type);
}
if (is_enum_type(actualtype) && actualtype != arg1type && actualtype != arg2type) {
return considerParamMatches(dtInt[INT_SIZE_DEFAULT], arg1type, arg2type);
}
if (isSyncType(actualtype) && actualtype != arg1type && actualtype != arg2type) {
return considerParamMatches(actualtype->getField("base_type")->type,
arg1type, arg2type);
}
return false;
}
/** Compare two argument mappings, given a set of actual arguments, and set the
* disambiguation state appropriately.
*
* This function implements the argument mapping comparison component of the
* disambiguation procedure as detailed in section 13.14.3 of the Chapel
* language specification (page 107).
*
* \param fn1 The first function to be compared.
* \param formal1 The formal argument that correspond to the actual argument
* for the first function.
* \param fn2 The second function to be compared.
* \param formal2 The formal argument that correspond to the actual argument
* for the second function.
* \param actual The actual argument from the call site.
* \param DC The disambiguation context.
* \param DS The disambiguation state.
*/
static void testArgMapping(FnSymbol* fn1, ArgSymbol* formal1,
FnSymbol* fn2, ArgSymbol* formal2,
Symbol* actual,
const DisambiguationContext& DC,
DisambiguationState& DS) {
// We only want to deal with the value types here, avoiding odd overloads
// working (or not) due to _ref.
Type *f1Type = formal1->type->getValType();
Type *f2Type = formal2->type->getValType();
Type *actualType = actual->type->getValType();
TRACE_DISAMBIGUATE_BY_MATCH("Actual's type: %s\n", toString(actualType));
bool formal1Promotes = false;
canDispatch(actualType, actual, f1Type, fn1, &formal1Promotes);
DS.fn1Promotes |= formal1Promotes;
TRACE_DISAMBIGUATE_BY_MATCH("Formal 1's type: %s\n", toString(f1Type));
if (formal1Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("Actual requires promotion to match formal 1\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Actual DOES NOT require promotion to match formal 1\n");
}
if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 1 is an instantiated param.\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 1 is NOT an instantiated param.\n");
}
bool formal2Promotes = false;
canDispatch(actualType, actual, f2Type, fn1, &formal2Promotes);
DS.fn2Promotes |= formal2Promotes;
TRACE_DISAMBIGUATE_BY_MATCH("Formal 2's type: %s\n", toString(f2Type));
if (formal2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("Actual requires promotion to match formal 2\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Actual DOES NOT require promotion to match formal 2\n");
}
if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 2 is an instantiated param.\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 2 is NOT an instantiated param.\n");
}
if (f1Type == f2Type && formal1->hasFlag(FLAG_INSTANTIATED_PARAM) && !formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("A: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (f1Type == f2Type && !formal1->hasFlag(FLAG_INSTANTIATED_PARAM) && formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("B: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (!formal1Promotes && formal2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("C: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (formal1Promotes && !formal2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("D: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (f1Type == f2Type && !formal1->instantiatedFrom && formal2->instantiatedFrom) {
TRACE_DISAMBIGUATE_BY_MATCH("E: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (f1Type == f2Type && formal1->instantiatedFrom && !formal2->instantiatedFrom) {
TRACE_DISAMBIGUATE_BY_MATCH("F: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (formal1->instantiatedFrom != dtAny && formal2->instantiatedFrom == dtAny) {
TRACE_DISAMBIGUATE_BY_MATCH("G: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (formal1->instantiatedFrom == dtAny && formal2->instantiatedFrom != dtAny) {
TRACE_DISAMBIGUATE_BY_MATCH("H: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (considerParamMatches(actualType, f1Type, f2Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("In first param case\n");
// The actual matches formal1's type, but not formal2's
if (paramWorks(actual, f2Type)) {
// but the actual is a param and works for formal2
if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) {
// the param works equally well for both, but
// matches the first slightly better if we had to
// decide
registerParamPreference(DS.paramPrefers, 1, "formal1", DC);
} else if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
registerParamPreference(DS.paramPrefers, 2, "formal2", DC);
} else {
// neither is a param, but formal1 is an exact type
// match, so prefer that one
registerParamPreference(DS.paramPrefers, 1, "formal1", DC);
}
} else {
TRACE_DISAMBIGUATE_BY_MATCH("I: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
}
} else if (considerParamMatches(actualType, f2Type, f1Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("In second param case\n");
// The actual matches formal2's type, but not formal1's
if (paramWorks(actual, f1Type)) {
// but the actual is a param and works for formal1
if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
// the param works equally well for both, but
// matches the second slightly better if we had to
// decide
registerParamPreference(DS.paramPrefers, 2, "formal2", DC);
} else if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) {
registerParamPreference(DS.paramPrefers, 1, "formal1", DC);
} else {
// neither is a param, but formal1 is an exact type
// match, so prefer that one
registerParamPreference(DS.paramPrefers, 2, "formal2", DC);
}
} else {
TRACE_DISAMBIGUATE_BY_MATCH("J: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
}
} else if (moreSpecific(fn1, f1Type, f2Type) && f2Type != f1Type) {
TRACE_DISAMBIGUATE_BY_MATCH("K: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (moreSpecific(fn1, f2Type, f1Type) && f2Type != f1Type) {
TRACE_DISAMBIGUATE_BY_MATCH("L: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (is_int_type(f1Type) && is_uint_type(f2Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("M: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (is_int_type(f2Type) && is_uint_type(f1Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("N: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else {
TRACE_DISAMBIGUATE_BY_MATCH("O: no information gained from argument\n");
}
}
/** Determines if fn1 is a better match than fn2.
*
* This function implements the function comparison component of the
* disambiguation procedure as detailed in section 13.14.3 of the Chapel
* language specification (page 106).
*
* \param candidate1 The function on the left-hand side of the comparison.
* \param candidate2 The function on the right-hand side of the comparison.
* \param DC The disambiguation context.
*
* \return True if fn1 is a more specific function than f2, false otherwise.
*/
static bool isBetterMatch(ResolutionCandidate* candidate1,
ResolutionCandidate* candidate2,
const DisambiguationContext& DC) {
DisambiguationState DS;
for (int k = 0; k < candidate1->alignedFormals.n; ++k) {
Symbol* actual = DC.actuals->v[k];
ArgSymbol* formal1 = candidate1->alignedFormals.v[k];
ArgSymbol* formal2 = candidate2->alignedFormals.v[k];
TRACE_DISAMBIGUATE_BY_MATCH("\nLooking at argument %d\n", k);
testArgMapping(candidate1->fn, formal1, candidate2->fn, formal2, actual, DC, DS);
}
if (!DS.fn1Promotes && DS.fn2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("\nP: Fn %d does not require argument promotion; Fn %d does\n", DC.i, DC.j);
DS.printSummary("P", DC);
return true;
}
if (!(DS.fn1MoreSpecific || DS.fn2MoreSpecific)) {
// If the decision hasn't been made based on the argument mappings...
if (isMoreVisible(DC.scope, candidate1->fn, candidate2->fn)) {
TRACE_DISAMBIGUATE_BY_MATCH("\nQ: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (isMoreVisible(DC.scope, candidate2->fn, candidate1->fn)) {
TRACE_DISAMBIGUATE_BY_MATCH("\nR: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (DS.paramPrefers == 1) {
TRACE_DISAMBIGUATE_BY_MATCH("\nS: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (DS.paramPrefers == 2) {
TRACE_DISAMBIGUATE_BY_MATCH("\nT: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (candidate1->fn->where && !candidate2->fn->where) {
TRACE_DISAMBIGUATE_BY_MATCH("\nU: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (!candidate1->fn->where && candidate2->fn->where) {
TRACE_DISAMBIGUATE_BY_MATCH("\nV: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
}
}
DS.printSummary("W", DC);
return DS.fn1MoreSpecific && !DS.fn2MoreSpecific;
}
/** Find the best candidate from a list of candidates.
*
* This function finds the best Chapel function from a set of candidates, given
* a call site. This is an implementation of 13.14.3 of the Chapel language
* specification (page 106).
*
* \param candidates A list of the candidate functions, from which the best
* match is selected.
* \param DC The disambiguation context.
*
* \return The result of the disambiguation process.
*/
static ResolutionCandidate*
disambiguateByMatch(Vec<ResolutionCandidate*>& candidates, DisambiguationContext DC) {
// If index i is set then we can skip testing function F_i because we already
// know it can not be the best match.
std::vector<bool> notBest(candidates.n, false);
for (int i = 0; i < candidates.n; ++i) {
TRACE_DISAMBIGUATE_BY_MATCH("##########################\n");
TRACE_DISAMBIGUATE_BY_MATCH("# Considering function %d #\n", i);
TRACE_DISAMBIGUATE_BY_MATCH("##########################\n\n");
ResolutionCandidate* candidate1 = candidates.v[i];
bool best = true; // is fn1 the best candidate?
TRACE_DISAMBIGUATE_BY_MATCH("%s\n\n", toString(candidate1->fn));
if (notBest[i]) {
TRACE_DISAMBIGUATE_BY_MATCH("Already known to not be best match. Skipping.\n\n");
continue;
}
for (int j = 0; j < candidates.n; ++j) {
if (i == j) continue;
TRACE_DISAMBIGUATE_BY_MATCH("Comparing to function %d\n", j);
TRACE_DISAMBIGUATE_BY_MATCH("-----------------------\n");
ResolutionCandidate* candidate2 = candidates.v[j];
TRACE_DISAMBIGUATE_BY_MATCH("%s\n", toString(candidate2->fn));
if (isBetterMatch(candidate1, candidate2, DC.forPair(i, j))) {
TRACE_DISAMBIGUATE_BY_MATCH("X: Fn %d is a better match than Fn %d\n\n\n", i, j);
notBest[j] = true;
} else {
TRACE_DISAMBIGUATE_BY_MATCH("X: Fn %d is NOT a better match than Fn %d\n\n\n", i, j);
best = false;
break;
}
}
if (best) {
TRACE_DISAMBIGUATE_BY_MATCH("Y: Fn %d is the best match.\n\n\n", i);
return candidate1;
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Y: Fn %d is NOT the best match.\n\n\n", i);
}
}
TRACE_DISAMBIGUATE_BY_MATCH("Z: No non-ambiguous best match.\n\n");
return NULL;
}
static bool
explainCallMatch(CallExpr* call) {
if (!call->isNamed(fExplainCall))
return false;
if (explainCallModule && explainCallModule != call->getModule())
return false;
if (explainCallLine != -1 && explainCallLine != call->linenum())
return false;
return true;
}
static CallExpr*
userCall(CallExpr* call) {
if (developer)
return call;
// If the called function is compiler-generated or is in one of the internal
// modules, back up the stack until a call is encountered whose target
// function is neither.
// TODO: This function should be rewritten so each test appears only once.
if (call->getFunction()->hasFlag(FLAG_COMPILER_GENERATED) ||
call->getModule()->modTag == MOD_INTERNAL) {
for (int i = callStack.n-1; i >= 0; i--) {
if (!callStack.v[i]->getFunction()->hasFlag(FLAG_COMPILER_GENERATED) &&
callStack.v[i]->getModule()->modTag != MOD_INTERNAL)
return callStack.v[i];
}
}
return call;
}
static void
printResolutionErrorAmbiguous(
Vec<FnSymbol*>& candidates,
CallInfo* info) {
CallExpr* call = userCall(info->call);
if (!strcmp("this", info->name)) {
USR_FATAL(call, "ambiguous access of '%s' by '%s'",
toString(info->actuals.v[1]->type),
toString(info));
} else {
const char* entity = "call";
if (!strncmp("_type_construct_", info->name, 16))
entity = "type specifier";
const char* str = toString(info);
if (info->scope) {
ModuleSymbol* mod = toModuleSymbol(info->scope->parentSymbol);
INT_ASSERT(mod);
str = astr(mod->name, ".", str);
}
USR_FATAL_CONT(call, "ambiguous %s '%s'", entity, str);
if (developer) {
for (int i = callStack.n-1; i>=0; i--) {
CallExpr* cs = callStack.v[i];
FnSymbol* f = cs->getFunction();
if (f->instantiatedFrom)
USR_PRINT(callStack.v[i], " instantiated from %s", f->name);
else
break;
}
}
bool printed_one = false;
forv_Vec(FnSymbol, fn, candidates) {
USR_PRINT(fn, "%s %s",
printed_one ? " " : "candidates are:",
toString(fn));
printed_one = true;
}
USR_STOP();
}
}
static void
printResolutionErrorUnresolved(
Vec<FnSymbol*>& visibleFns,
CallInfo* info) {
CallExpr* call = userCall(info->call);
if (!strcmp("_cast", info->name)) {
if (!info->actuals.head()->hasFlag(FLAG_TYPE_VARIABLE)) {
USR_FATAL(call, "illegal cast to non-type",
toString(info->actuals.v[1]->type),
toString(info->actuals.v[0]->type));
} else {
USR_FATAL(call, "illegal cast from %s to %s",
toString(info->actuals.v[1]->type),
toString(info->actuals.v[0]->type));
}
} else if (!strcmp("free", info->name)) {
if (info->actuals.n > 0 &&
isRecord(info->actuals.v[2]->type))
USR_FATAL(call, "delete not allowed on records");
} else if (!strcmp("these", info->name)) {
if (info->actuals.n == 2 &&
info->actuals.v[0]->type == dtMethodToken)
USR_FATAL(call, "cannot iterate over values of type %s",
toString(info->actuals.v[1]->type));
} else if (!strcmp("_type_construct__tuple", info->name)) {
if (info->call->argList.length == 0)
USR_FATAL(call, "tuple size must be specified");
SymExpr* sym = toSymExpr(info->call->get(1));
if (!sym || !sym->var->isParameter()) {
USR_FATAL(call, "tuple size must be static");
} else {
USR_FATAL(call, "invalid tuple");
}
} else if (!strcmp("=", info->name)) {
if (info->actuals.v[0] && !info->actuals.v[0]->hasFlag(FLAG_TYPE_VARIABLE) &&
info->actuals.v[1] && info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE)) {
USR_FATAL(call, "illegal assignment of type to value");
} else if (info->actuals.v[0] && info->actuals.v[0]->hasFlag(FLAG_TYPE_VARIABLE) &&
info->actuals.v[1] && !info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE)) {
USR_FATAL(call, "illegal assignment of value to type");
} else if (info->actuals.v[1]->type == dtNil) {
USR_FATAL(call, "type mismatch in assignment from nil to %s",
toString(info->actuals.v[0]->type));
} else {
USR_FATAL(call, "type mismatch in assignment from %s to %s",
toString(info->actuals.v[1]->type),
toString(info->actuals.v[0]->type));
}
} else if (!strcmp("this", info->name)) {
Type* type = info->actuals.v[1]->getValType();
if (type->symbol->hasFlag(FLAG_ITERATOR_RECORD)) {
USR_FATAL(call, "illegal access of iterator or promoted expression");
} else if (type->symbol->hasFlag(FLAG_FUNCTION_CLASS)) {
USR_FATAL(call, "illegal access of first class function");
} else {
USR_FATAL(call, "unresolved access of '%s' by '%s'",
toString(info->actuals.v[1]->type),
toString(info));
}
} else {
const char* entity = "call";
if (!strncmp("_type_construct_", info->name, 16))
entity = "type specifier";
const char* str = toString(info);
if (info->scope) {
ModuleSymbol* mod = toModuleSymbol(info->scope->parentSymbol);
INT_ASSERT(mod);
str = astr(mod->name, ".", str);
}
USR_FATAL_CONT(call, "unresolved %s '%s'", entity, str);
if (visibleFns.n > 0) {
if (developer) {
for (int i = callStack.n-1; i>=0; i--) {
CallExpr* cs = callStack.v[i];
FnSymbol* f = cs->getFunction();
if (f->instantiatedFrom)
USR_PRINT(callStack.v[i], " instantiated from %s", f->name);
else
break;
}
}
bool printed_one = false;
forv_Vec(FnSymbol, fn, visibleFns) {
// Consider "visible functions are"
USR_PRINT(fn, "%s %s",
printed_one ? " " : "candidates are:",
toString(fn));
printed_one = true;
}
}
if (visibleFns.n == 1 &&
visibleFns.v[0]->numFormals() == 0
&& !strncmp("_type_construct_", info->name, 16))
USR_PRINT(call, "did you forget the 'new' keyword?");
USR_STOP();
}
}
static void issueCompilerError(CallExpr* call) {
//
// Disable compiler warnings in internal modules that are triggered
// within a dynamic dispatch context because of potential user
// confusion. Removed the following code and See the following
// tests:
//
// test/arrays/bradc/workarounds/arrayOfSpsArray.chpl
// test/arrays/deitz/part4/test_array_of_associative_arrays.chpl
// test/classes/bradc/arrayInClass/genericArrayInClass-otharrs.chpl
//
if (call->isPrimitive(PRIM_WARNING))
if (inDynamicDispatchResolution)
if (call->getModule()->modTag == MOD_INTERNAL &&
callStack.head()->getModule()->modTag == MOD_INTERNAL)
return;
//
// If an errorDepth was specified, report a diagnostic about the call
// that deep into the callStack. The default depth is 1.
//
FnSymbol* fn = toFnSymbol(call->parentSymbol);
VarSymbol* depthParam = toVarSymbol(paramMap.get(toDefExpr(fn->formals.tail)->sym));
int64_t depth;
bool foundDepthVal;
if (depthParam && depthParam->immediate &&
depthParam->immediate->const_kind == NUM_KIND_INT) {
depth = depthParam->immediate->int_value();
foundDepthVal = true;
} else {
depth = 1;
foundDepthVal = false;
}
if (depth > callStack.n - 1) {
if (foundDepthVal)
USR_WARN(call, "compiler diagnostic depth value exceeds call stack depth");
depth = callStack.n - 1;
}
if (depth < 0) {
USR_WARN(call, "compiler diagnostic depth value can not be negative");
depth = 0;
}
CallExpr* from = NULL;
for (int i = callStack.n-1 - depth; i >= 0; i--) {
from = callStack.v[i];
// We report calls whose target function is not compiler-generated and is
// not defined in one of the internal modules.
if (from->linenum() > 0 &&
from->getModule()->modTag != MOD_INTERNAL &&
!from->getFunction()->hasFlag(FLAG_COMPILER_GENERATED))
break;
}
const char* str = "";
for_formals(arg, fn) {
if (foundDepthVal && arg->defPoint == fn->formals.tail)
continue;
VarSymbol* var = toVarSymbol(paramMap.get(arg));
INT_ASSERT(var && var->immediate && var->immediate->const_kind == CONST_KIND_STRING);
str = astr(str, var->immediate->v_string);
}
if (call->isPrimitive(PRIM_ERROR)) {
USR_FATAL(from, "%s", str);
} else {
USR_WARN(from, "%s", str);
}
if (FnSymbol* fn = toFnSymbol(callStack.tail()->isResolved()))
innerCompilerWarningMap.put(fn, str);
if (FnSymbol* fn = toFnSymbol(callStack.v[callStack.n-1 - depth]->isResolved()))
outerCompilerWarningMap.put(fn, str);
}
static void reissueCompilerWarning(const char* str, int offset) {
//
// Disable compiler warnings in internal modules that are triggered
// within a dynamic dispatch context because of potential user
// confusion. See note in 'issueCompileError' above.
//
if (inDynamicDispatchResolution)
if (callStack.tail()->getModule()->modTag == MOD_INTERNAL &&
callStack.head()->getModule()->modTag == MOD_INTERNAL)
return;
CallExpr* from = NULL;
for (int i = callStack.n-offset; i >= 0; i--) {
from = callStack.v[i];
// We report calls whose target function is not compiler-generated and is
// not defined in one of the internal modules.
if (from->linenum() > 0 &&
from->getModule()->modTag != MOD_INTERNAL &&
!from->getFunction()->hasFlag(FLAG_COMPILER_GENERATED))
break;
}
USR_WARN(from, "%s", str);
}
class VisibleFunctionBlock {
public:
Map<const char*,Vec<FnSymbol*>*> visibleFunctions;
VisibleFunctionBlock() { }
};
static Map<BlockStmt*,VisibleFunctionBlock*> visibleFunctionMap;
static int nVisibleFunctions = 0; // for incremental build
static Map<BlockStmt*,BlockStmt*> visibilityBlockCache;
static Vec<BlockStmt*> standardModuleSet;
//
// return true if expr is a CondStmt with chpl__tryToken as its condition
//
static bool isTryTokenCond(Expr* expr) {
CondStmt* cond = toCondStmt(expr);
if (!cond) return false;
SymExpr* sym = toSymExpr(cond->condExpr);
if (!sym) return false;
return sym->var == gTryToken;
}
//
// return the innermost block for searching for visible functions
//
BlockStmt*
getVisibilityBlock(Expr* expr) {
if (BlockStmt* block = toBlockStmt(expr->parentExpr)) {
if (block->blockTag == BLOCK_SCOPELESS)
return getVisibilityBlock(block);
else if (block->parentExpr && isTryTokenCond(block->parentExpr)) {
// Make the visibility block of the then and else blocks of a
// conditional using chpl__tryToken be the block containing the
// conditional statement. Without this, there were some cases where
// a function gets instantiated into one side of the conditional but
// used in both sides, then the side with the instantiation gets
// folded out leaving expressions with no visibility block.
// test/functions/iterators/angeles/dynamic.chpl is an example that
// currently fails without this.
return getVisibilityBlock(block->parentExpr);
} else
return block;
} else if (expr->parentExpr) {
return getVisibilityBlock(expr->parentExpr);
} else if (Symbol* s = expr->parentSymbol) {
FnSymbol* fn = toFnSymbol(s);
if (fn && fn->instantiationPoint)
return fn->instantiationPoint;
else
return getVisibilityBlock(s->defPoint);
} else {
INT_FATAL(expr, "Expresion has no visibility block.");
return NULL;
}
}
static void buildVisibleFunctionMap() {
for (int i = nVisibleFunctions; i < gFnSymbols.n; i++) {
FnSymbol* fn = gFnSymbols.v[i];
if (!fn->hasFlag(FLAG_INVISIBLE_FN) && fn->defPoint->parentSymbol && !isArgSymbol(fn->defPoint->parentSymbol)) {
BlockStmt* block = NULL;
if (fn->hasFlag(FLAG_AUTO_II)) {
block = theProgram->block;
} else {
block = getVisibilityBlock(fn->defPoint);
//
// add all functions in standard modules to theProgram
//
if (standardModuleSet.set_in(block))
block = theProgram->block;
}
VisibleFunctionBlock* vfb = visibleFunctionMap.get(block);
if (!vfb) {
vfb = new VisibleFunctionBlock();
visibleFunctionMap.put(block, vfb);
}
Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(fn->name);
if (!fns) {
fns = new Vec<FnSymbol*>();
vfb->visibleFunctions.put(fn->name, fns);
}
fns->add(fn);
}
}
nVisibleFunctions = gFnSymbols.n;
}
static BlockStmt*
getVisibleFunctions(BlockStmt* block,
const char* name,
Vec<FnSymbol*>& visibleFns,
Vec<BlockStmt*>& visited) {
//
// all functions in standard modules are stored in a single block
//
if (standardModuleSet.set_in(block))
block = theProgram->block;
//
// avoid infinite recursion due to modules with mutual uses
//
if (visited.set_in(block))
return NULL;
if (isModuleSymbol(block->parentSymbol))
visited.set_add(block);
bool canSkipThisBlock = true;
VisibleFunctionBlock* vfb = visibleFunctionMap.get(block);
if (vfb) {
canSkipThisBlock = false; // cannot skip if this block defines functions
Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(name);
if (fns) {
visibleFns.append(*fns);
}
}
if (block->modUses) {
for_actuals(expr, block->modUses) {
SymExpr* se = toSymExpr(expr);
INT_ASSERT(se);
ModuleSymbol* mod = toModuleSymbol(se->var);
INT_ASSERT(mod);
canSkipThisBlock = false; // cannot skip if this block uses modules
getVisibleFunctions(mod->block, name, visibleFns, visited);
}
}
//
// visibilityBlockCache contains blocks that can be skipped
//
if (BlockStmt* next = visibilityBlockCache.get(block)) {
getVisibleFunctions(next, name, visibleFns, visited);
return (canSkipThisBlock) ? next : block;
}
if (block != rootModule->block) {
BlockStmt* next = getVisibilityBlock(block);
BlockStmt* cache = getVisibleFunctions(next, name, visibleFns, visited);
if (cache)
visibilityBlockCache.put(block, cache);
return (canSkipThisBlock) ? cache : block;
}
return NULL;
}
// Ensure 'parent' is the block before which we want to do the capturing.
static void verifyTaskFnCall(BlockStmt* parent, CallExpr* call) {
if (call->isNamed("coforall_fn") || call->isNamed("on_fn")) {
INT_ASSERT(parent->isForLoop());
} else if (call->isNamed("cobegin_fn")) {
DefExpr* first = toDefExpr(parent->getFirstExpr());
// just documenting the current state
INT_ASSERT(first && !strcmp(first->sym->name, "_cobeginCount"));
} else {
INT_ASSERT(call->isNamed("begin_fn"));
}
}
//
// Allow invoking isConstValWillNotChange() even on formals
// with blank and 'const' intents.
//
static bool isConstValWillNotChange(Symbol* sym) {
if (ArgSymbol* arg = toArgSymbol(sym)) {
IntentTag cInt = concreteIntent(arg->intent, arg->type->getValType());
return cInt == INTENT_CONST_IN;
}
return sym->isConstValWillNotChange();
}
//
// Returns the expression that we want to capture before.
//
// Why not just 'parent'? In users/shetag/fock/fock-dyn-prog-cntr.chpl,
// we cannot do parent->insertBefore() because parent->list is null.
// That's because we have: if ... then cobegin ..., so 'parent' is
// immediately under CondStmt. This motivated me for cobegins to capture
// inside of the 'parent' block, at the beginning of it.
//
static Expr* parentToMarker(BlockStmt* parent, CallExpr* call) {
if (call->isNamed("cobegin_fn")) {
// I want to be cute and keep _cobeginCount def and move
// as the first two statements in the block.
DefExpr* def = toDefExpr(parent->body.head);
INT_ASSERT(def);
// Just so we know what we are doing.
INT_ASSERT(!strcmp((def->sym->name), "_cobeginCount"));
CallExpr* move = toCallExpr(def->next);
INT_ASSERT(move);
SymExpr* arg1 = toSymExpr(move->get(1));
INT_ASSERT(arg1->var == def->sym);
// And this is where we want to insert:
return move->next;
}
// Otherwise insert before 'parent'
return parent;
}
// map: (block id) -> (map: sym -> sym)
typedef std::map<int, SymbolMap*> CapturedValueMap;
static CapturedValueMap capturedValues;
static void freeCache(CapturedValueMap& c) {
for (std::map<int, SymbolMap*>::iterator it = c.begin(); it != c.end(); ++it)
delete it->second;
}
//
// Generate code to store away the value of 'varActual' before
// the cobegin or the coforall loop starts. Use this value
// instead of 'varActual' as the actual to the task function,
// meaning (later in compilation) in the argument bundle.
//
// This is to ensure that all task functions use the same value
// for their respective formal when that has an 'in'-like intent,
// even if 'varActual' is modified between creations of
// the multiple task functions.
//
static void captureTaskIntentValues(int argNum, ArgSymbol* formal,
Expr* actual, Symbol* varActual,
CallInfo& info, CallExpr* call,
FnSymbol* taskFn)
{
BlockStmt* parent = toBlockStmt(call->parentExpr);
INT_ASSERT(parent);
if (taskFn->hasFlag(FLAG_ON) && !parent->isForLoop()) {
// coforall ... { on ... { .... }} ==> there is an intermediate BlockStmt
parent = toBlockStmt(parent->parentExpr);
INT_ASSERT(parent);
}
if (fVerify && (argNum == 0 || (argNum == 1 && taskFn->hasFlag(FLAG_ON))))
verifyTaskFnCall(parent, call); //assertions only
Expr* marker = parentToMarker(parent, call);
if (varActual->defPoint->parentExpr == parent) {
// Index variable of the coforall loop? Do not capture it!
if (fVerify) {
// This is what currently happens.
CallExpr* move = toCallExpr(varActual->defPoint->next);
INT_ASSERT(move);
INT_ASSERT(move->isPrimitive(PRIM_MOVE));
SymExpr* src = toSymExpr(move->get(2));
INT_ASSERT(src);
INT_ASSERT(!strcmp(src->var->name, "_indexOfInterest"));
}
// do nothing
return;
}
SymbolMap*& symap = capturedValues[parent->id];
Symbol* captemp = NULL;
if (symap)
captemp = symap->get(varActual);
else
symap = new SymbolMap();
if (!captemp) {
captemp = newTemp(astr(formal->name, "_captemp"), formal->type);
marker->insertBefore(new DefExpr(captemp));
// todo: once AMM is in effect, drop chpl__autoCopy - do straight move
FnSymbol* autoCopy = getAutoCopy(formal->type);
if (autoCopy)
marker->insertBefore("'move'(%S,%S(%S))", captemp, autoCopy, varActual);
else if (isReferenceType(varActual->type) &&
!isReferenceType(captemp->type))
marker->insertBefore("'move'(%S,'deref'(%S))", captemp, varActual);
else
marker->insertBefore("'move'(%S,%S)", captemp, varActual);
symap->put(varActual, captemp);
}
actual->replace(new SymExpr(captemp));
Symbol*& iact = info.actuals.v[argNum];
INT_ASSERT(iact == varActual);
iact = captemp;
}
//
// Copy the type of the actual into the type of the corresponding formal
// of a task function. (I think resolution wouldn't make this happen
// automatically and correctly in all cases.)
// Also do captureTaskIntentValues() when needed.
//
static void handleTaskIntentArgs(CallExpr* call, FnSymbol* taskFn,
CallInfo& info)
{
INT_ASSERT(taskFn);
if (!needsCapture(taskFn)) {
// A task function should have args only if it needsCapture.
if (taskFn->hasFlag(FLAG_ON)) {
// Documenting the current state: fn_on gets a chpl_localeID_t arg.
INT_ASSERT(call->numActuals() == 1);
} else {
INT_ASSERT(!isTaskFun(taskFn) || call->numActuals() == 0);
}
return;
}
int argNum = -1;
for_formals_actuals(formal, actual, call) {
argNum++;
SymExpr* symexpActual = toSymExpr(actual);
if (!symexpActual) {
// We add NamedExpr args in propagateExtraLeaderArgs().
NamedExpr* namedexpActual = toNamedExpr(actual);
INT_ASSERT(namedexpActual);
symexpActual = toSymExpr(namedexpActual->actual);
}
INT_ASSERT(symexpActual); // because of how we invoke a task function
Symbol* varActual = symexpActual->var;
// If 'call' is in a generic function, it is supposed to have been
// instantiated by now. Otherwise our task function has to remain generic.
INT_ASSERT(!varActual->type->symbol->hasFlag(FLAG_GENERIC));
// Need to copy varActual->type even for type variables.
// BTW some formals' types may have been set in createTaskFunctions().
formal->type = varActual->type;
// If the actual is a ref, still need to capture it => remove ref.
if (isReferenceType(varActual->type)) {
Type* deref = varActual->type->getValType();
// todo: replace needsCapture() with always resolveArgIntent(formal)
// then checking (formal->intent & INTENT_FLAG_IN)
if (needsCapture(deref)) {
formal->type = deref;
// If the formal has a ref intent, DO need a ref type => restore it.
resolveArgIntent(formal);
if (formal->intent & INTENT_FLAG_REF) {
formal->type = varActual->type;
}
}
}
if (varActual->hasFlag(FLAG_TYPE_VARIABLE))
formal->addFlag(FLAG_TYPE_VARIABLE);
// This does not capture records/strings that are passed
// by blank or const intent. As of this writing (6'2015)
// records and strings are (incorrectly) captured at the point
// when the task function/arg bundle is created.
if (taskFn->hasFlag(FLAG_COBEGIN_OR_COFORALL) &&
!isConstValWillNotChange(varActual) &&
(concreteIntent(formal->intent, formal->type->getValType())
& INTENT_FLAG_IN))
// skip dummy_locale_arg: chpl_localeID_t
if (argNum != 0 || !taskFn->hasFlag(FLAG_ON))
captureTaskIntentValues(argNum, formal, actual, varActual, info, call,
taskFn);
}
// Even if some formals are (now) types, if 'taskFn' remained generic,
// gatherCandidates() would not instantiate it, for some reason.
taskFn->removeFlag(FLAG_GENERIC);
}
static Expr*
resolve_type_expr(Expr* expr) {
Expr* result = NULL;
for_exprs_postorder(e, expr) {
result = preFold(e);
if (CallExpr* call = toCallExpr(result)) {
if (call->parentSymbol) {
callStack.add(call);
resolveCall(call);
FnSymbol* fn = call->isResolved();
if (fn && call->parentSymbol) {
resolveFormals(fn);
if (fn->retTag == RET_PARAM || fn->retTag == RET_TYPE ||
fn->retType == dtUnknown)
resolveFns(fn);
}
callStack.pop();
}
}
result = postFold(result);
}
return result;
}
static void
makeNoop(CallExpr* call) {
if (call->baseExpr)
call->baseExpr->remove();
while (call->numActuals())
call->get(1)->remove();
call->primitive = primitives[PRIM_NOOP];
}
//
// The following several functions support const-ness checking.
// Which is tailored to how our existing Chapel code is written
// and to the current constructor story. In particular:
//
// * Const-ness of fields is not honored within constructors
// and initialize() functions
//
// * A function invoked directly from a constructor or initialize()
// are treated as if were a constructor.
//
// The implementation also tends to the case where such an invocation
// occurs inside a task function within the constructor or initialize().
//
// THESE RULES ARE INTERIM.
// They will change - and the Chapel code will need to be updated -
// for the upcoming new constructor story.
//
// Implementation note: we need to propagate the constness property
// through temp assignments, dereferences, and calls to methods with
// FLAG_REF_TO_CONST_WHEN_CONST_THIS.
//
static void findNonTaskFnParent(CallExpr* call,
FnSymbol*& parent, int& stackIdx) {
// We assume that 'call' is at the top of the call stack.
INT_ASSERT(callStack.n >= 1);
INT_ASSERT(callStack.v[callStack.n-1] == call ||
callStack.v[callStack.n-1] == call->parentExpr);
int ix;
for (ix = callStack.n-1; ix >= 0; ix--) {
CallExpr* curr = callStack.v[ix];
Symbol* parentSym = curr->parentSymbol;
FnSymbol* parentFn = toFnSymbol(parentSym);
if (!parentFn)
break;
if (!isTaskFun(parentFn)) {
stackIdx = ix;
parent = parentFn;
return;
}
}
// backup plan
parent = toFnSymbol(call->parentSymbol);
stackIdx = -1;
}
static bool isConstructorLikeFunction(FnSymbol* fn) {
return fn->hasFlag(FLAG_CONSTRUCTOR) || !strcmp(fn->name, "initialize");
}
// Is 'call' in a constructor or in initialize()?
// This includes being in a task function invoked from the above.
static bool isInConstructorLikeFunction(CallExpr* call) {
FnSymbol* parent;
int stackIdx;
findNonTaskFnParent(call, parent, stackIdx); // sets the args
return parent && isConstructorLikeFunction(parent);
}
// Is the function of interest invoked from a constructor
// or initialize(), with the constructor's or intialize's 'this'
// as the receiver actual.
static bool isInvokedFromConstructorLikeFunction(int stackIdx) {
if (stackIdx > 0) {
CallExpr* call2 = callStack.v[stackIdx - 1];
if (FnSymbol* parent2 = toFnSymbol(call2->parentSymbol))
if (isConstructorLikeFunction(parent2))
if (call2->numActuals() >= 2)
if (SymExpr* thisArg2 = toSymExpr(call2->get(2)))
if (thisArg2->var->hasFlag(FLAG_ARG_THIS))
return true;
}
return false;
}
// Check whether the actual comes from accessing a const field of 'this'
// and the call is in a function invoked directly from this's constructor.
// In such case, fields of 'this' are not considered 'const',
// so we remove the const-ness flag.
static bool checkAndUpdateIfLegalFieldOfThis(CallExpr* call, Expr* actual,
FnSymbol*& nonTaskFnParent) {
int stackIdx;
findNonTaskFnParent(call, nonTaskFnParent, stackIdx); // sets the args
if (SymExpr* se = toSymExpr(actual))
if (se->var->hasFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS))
if (isInvokedFromConstructorLikeFunction(stackIdx)) {
// Yes, this is the case we are looking for.
se->var->removeFlag(FLAG_REF_TO_CONST);
return true;
}
return false;
}
// little helper
static Symbol* getBaseSymForConstCheck(CallExpr* call) {
// ensure this is a method call
INT_ASSERT(call->get(1)->typeInfo() == dtMethodToken);
SymExpr* baseExpr = toSymExpr(call->get(2));
INT_ASSERT(baseExpr); // otherwise, cannot do the checking
return baseExpr->var;
}
// If 'call' is an access to a const thing, for example a const field
// or a field of a const record, set const flag(s) on the symbol
// that stores the result of 'call'.
static void setFlagsAndCheckForConstAccess(Symbol* dest,
CallExpr* call, FnSymbol* resolvedFn)
{
// Is the outcome of 'call' a reference to a const?
bool refConst = resolvedFn->hasFlag(FLAG_REF_TO_CONST);
// Another flag that's relevant.
const bool constWCT = resolvedFn->hasFlag(FLAG_REF_TO_CONST_WHEN_CONST_THIS);
// The second flag does not make sense when the first flag is set.
INT_ASSERT(!(refConst && constWCT));
// The symbol whose field is accessed, if applicable:
Symbol* baseSym = NULL;
if (refConst) {
if (resolvedFn->hasFlag(FLAG_FIELD_ACCESSOR) &&
// promotion wrappers are not handled currently
!resolvedFn->hasFlag(FLAG_PROMOTION_WRAPPER)
)
baseSym = getBaseSymForConstCheck(call);
} else if (constWCT) {
baseSym = getBaseSymForConstCheck(call);
if (baseSym->isConstant() ||
baseSym->hasFlag(FLAG_REF_TO_CONST) ||
baseSym->hasFlag(FLAG_CONST)
)
refConst = true;
else
// The result is not constant.
baseSym = NULL;
} else if (dest->hasFlag(FLAG_ARRAY_ALIAS) &&
resolvedFn->hasFlag(FLAG_AUTO_COPY_FN) &&
!dest->hasFlag(FLAG_CONST))
{
// We are creating a var alias - ensure aliasee is not const either.
SymExpr* aliaseeSE = toSymExpr(call->get(1));
INT_ASSERT(aliaseeSE);
if (aliaseeSE->var->isConstant() ||
aliaseeSE->var->hasFlag(FLAG_CONST))
USR_FATAL_CONT(call, "creating a non-const alias '%s' of a const array or domain", dest->name);
}
// Do not consider it const if it is an access to 'this'
// in a constructor. Todo: will need to reconcile with UMM.
// btw (baseSym != NULL) ==> (refConst == true).
if (baseSym) {
// Aside: at this point 'baseSym' can have reference or value type,
// seemingly without a particular rule.
if (baseSym->hasFlag(FLAG_ARG_THIS) &&
isInConstructorLikeFunction(call)
)
refConst = false;
}
if (refConst) {
if (isReferenceType(dest->type))
dest->addFlag(FLAG_REF_TO_CONST);
else
dest->addFlag(FLAG_CONST);
if (baseSym && baseSym->hasFlag(FLAG_ARG_THIS))
// 'call' can be a field accessor or an array element accessor or ?
dest->addFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS);
// Propagate this flag. btw (recConst && constWCT) ==> (baseSym != NULL)
if (constWCT && baseSym->hasFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS))
dest->addFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS);
}
}
// Report an error when storing a sync or single variable into a tuple.
// This is because currently we deallocate memory excessively in this case.
static void checkForStoringIntoTuple(CallExpr* call, FnSymbol* resolvedFn)
{
// Do not perform the checks if:
// not building a tuple
if (!resolvedFn->hasFlag(FLAG_BUILD_TUPLE) ||
// sync/single tuples are used in chpl__autoCopy(x: _tuple), allow them
resolvedFn->hasFlag(FLAG_ALLOW_REF) ||
// sync/single tuple *types* and params seem OK
resolvedFn->retTag != RET_VALUE)
return;
for_formals_actuals(formal, actual, call)
if (isSyncType(formal->type)) {
const char* name = "";
if (SymExpr* aSE = toSymExpr(actual))
if (!aSE->var->hasFlag(FLAG_TEMP))
name = aSE->var->name;
USR_FATAL_CONT(actual, "storing a sync or single variable %s in a tuple is not currently implemented - apply readFE() or readFF()", name);
}
}
// If 'fn' is the default assignment for a record type, return
// the name of that record type; otherwise return NULL.
static const char* defaultRecordAssignmentTo(FnSymbol* fn) {
if (!strcmp("=", fn->name)) {
if (fn->hasFlag(FLAG_COMPILER_GENERATED)) {
Type* desttype = fn->getFormal(1)->type->getValType();
INT_ASSERT(desttype != dtUnknown); // otherwise this test is unreliable
if (isRecord(desttype) || isUnion(desttype))
return desttype->symbol->name;
}
}
return NULL;
}
//
// special case cast of class w/ type variables that is not generic
// i.e. type variables are type definitions (have default types)
//
static void
resolveDefaultGenericType(CallExpr* call) {
SET_LINENO(call);
for_actuals(actual, call) {
if (NamedExpr* ne = toNamedExpr(actual))
actual = ne->actual;
if (SymExpr* te = toSymExpr(actual)) {
if (TypeSymbol* ts = toTypeSymbol(te->var)) {
if (AggregateType* ct = toAggregateType(ts->type)) {
if (ct->symbol->hasFlag(FLAG_GENERIC)) {
CallExpr* cc = new CallExpr(ct->defaultTypeConstructor->name);
te->replace(cc);
resolveCall(cc);
cc->replace(new SymExpr(cc->typeInfo()->symbol));
}
}
}
if (VarSymbol* vs = toVarSymbol(te->var)) {
// Fix for complicated extern vars like
// extern var x: c_ptr(c_int);
if( vs->hasFlag(FLAG_EXTERN) && vs->hasFlag(FLAG_TYPE_VARIABLE) &&
vs->defPoint && vs->defPoint->init ) {
if( CallExpr* def = toCallExpr(vs->defPoint->init) ) {
vs->defPoint->init = resolveExpr(def);
te->replace(new SymExpr(vs->defPoint->init->typeInfo()->symbol));
}
}
}
}
}
}
static void
gatherCandidates(Vec<ResolutionCandidate*>& candidates,
Vec<FnSymbol*>& visibleFns,
CallInfo& info) {
// Search user-defined (i.e. non-compiler-generated) functions first.
forv_Vec(FnSymbol, visibleFn, visibleFns) {
if (visibleFn->hasFlag(FLAG_COMPILER_GENERATED)) {
continue;
}
if (info.call->methodTag &&
! (visibleFn->hasFlag(FLAG_NO_PARENS) ||
visibleFn->hasFlag(FLAG_TYPE_CONSTRUCTOR))) {
continue;
}
if (fExplainVerbose &&
((explainCallLine && explainCallMatch(info.call)) ||
info.call->id == explainCallID))
{
USR_PRINT(visibleFn, "Considering function: %s", toString(visibleFn));
}
filterCandidate(candidates, visibleFn, info);
}
// Return if we got a successful match with user-defined functions.
if (candidates.n) {
return;
}
// No. So search compiler-defined functions.
forv_Vec(FnSymbol, visibleFn, visibleFns) {
if (!visibleFn->hasFlag(FLAG_COMPILER_GENERATED)) {
continue;
}
if (info.call->methodTag &&
! (visibleFn->hasFlag(FLAG_NO_PARENS) ||
visibleFn->hasFlag(FLAG_TYPE_CONSTRUCTOR))) {
continue;
}
if (fExplainVerbose &&
((explainCallLine && explainCallMatch(info.call)) ||
info.call->id == explainCallID))
{
USR_PRINT(visibleFn, "Considering function: %s", toString(visibleFn));
}
filterCandidate(candidates, visibleFn, info);
}
}
void
resolveCall(CallExpr* call)
{
if (call->primitive)
{
switch (call->primitive->tag)
{
default: /* do nothing */ break;
case PRIM_TUPLE_AND_EXPAND: resolveTupleAndExpand(call); break;
case PRIM_TUPLE_EXPAND: resolveTupleExpand(call); break;
case PRIM_SET_MEMBER: resolveSetMember(call); break;
case PRIM_MOVE: resolveMove(call); break;
case PRIM_TYPE_INIT:
case PRIM_INIT: resolveDefaultGenericType(call); break;
case PRIM_NO_INIT: resolveDefaultGenericType(call); break;
case PRIM_NEW: resolveNew(call); break;
}
}
else
{
resolveNormalCall(call);
}
}
void resolveNormalCall(CallExpr* call) {
resolveDefaultGenericType(call);
CallInfo info(call);
Vec<FnSymbol*> visibleFns; // visible functions
//
// update visible function map as necessary
//
if (gFnSymbols.n != nVisibleFunctions) {
buildVisibleFunctionMap();
}
if (!call->isResolved()) {
if (!info.scope) {
Vec<BlockStmt*> visited;
getVisibleFunctions(getVisibilityBlock(call), info.name, visibleFns, visited);
} else {
if (VisibleFunctionBlock* vfb = visibleFunctionMap.get(info.scope)) {
if (Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(info.name)) {
visibleFns.append(*fns);
}
}
}
} else {
visibleFns.add(call->isResolved());
handleTaskIntentArgs(call, call->isResolved(), info);
}
if ((explainCallLine && explainCallMatch(call)) ||
call->id == explainCallID)
{
USR_PRINT(call, "call: %s", toString(&info));
if (visibleFns.n == 0)
USR_PRINT(call, "no visible functions found");
bool first = true;
forv_Vec(FnSymbol, visibleFn, visibleFns) {
USR_PRINT(visibleFn, "%s %s",
first ? "visible functions are:" : " ",
toString(visibleFn));
first = false;
}
}
Vec<ResolutionCandidate*> candidates;
gatherCandidates(candidates, visibleFns, info);
if ((explainCallLine && explainCallMatch(info.call)) ||
call->id == explainCallID)
{
if (candidates.n == 0) {
USR_PRINT(info.call, "no candidates found");
} else {
bool first = true;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
USR_PRINT(candidate->fn, "%s %s",
first ? "candidates are:" : " ",
toString(candidate->fn));
first = false;
}
}
}
Expr* scope = (info.scope) ? info.scope : getVisibilityBlock(call);
bool explain = fExplainVerbose &&
((explainCallLine && explainCallMatch(call)) ||
info.call->id == explainCallID);
DisambiguationContext DC(&info.actuals, scope, explain);
ResolutionCandidate* best = disambiguateByMatch(candidates, DC);
if (best && best->fn) {
/*
* Finish instantiating the body. This is a noop if the function wasn't
* partially instantiated.
*/
instantiateBody(best->fn);
if (explainCallLine && explainCallMatch(call)) {
USR_PRINT(best->fn, "best candidate is: %s", toString(best->fn));
}
}
// Future work note: the repeated check to best and best->fn means that we
// could probably restructure this function to a better form.
if (call->partialTag && (!best || !best->fn ||
!best->fn->hasFlag(FLAG_NO_PARENS))) {
if (best != NULL) {
delete best;
best = NULL;
}
} else if (!best) {
if (tryStack.n) {
tryFailure = true;
return;
} else {
if (candidates.n > 0) {
Vec<FnSymbol*> candidateFns;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
candidateFns.add(candidate->fn);
}
printResolutionErrorAmbiguous(candidateFns, &info);
} else {
printResolutionErrorUnresolved(visibleFns, &info);
}
}
} else {
best->fn = defaultWrap(best->fn, &best->alignedFormals, &info);
reorderActuals(best->fn, &best->alignedFormals, &info);
coerceActuals(best->fn, &info);
best->fn = promotionWrap(best->fn, &info);
}
FnSymbol* resolvedFn = best != NULL ? best->fn : NULL;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
delete candidate;
}
if (call->partialTag) {
if (!resolvedFn) {
return;
}
call->partialTag = false;
}
if (resolvedFn &&
!strcmp("=", resolvedFn->name) &&
isRecord(resolvedFn->getFormal(1)->type) &&
resolvedFn->getFormal(2)->type == dtNil) {
USR_FATAL(userCall(call), "type mismatch in assignment from nil to %s",
toString(resolvedFn->getFormal(1)->type));
}
if (!resolvedFn) {
INT_FATAL(call, "unable to resolve call");
}
if (call->parentSymbol) {
SET_LINENO(call);
call->baseExpr->replace(new SymExpr(resolvedFn));
}
if (resolvedFn->hasFlag(FLAG_MODIFIES_CONST_FIELDS))
// Not allowed if it is not called directly from a constructor.
if (!isInConstructorLikeFunction(call) ||
!getBaseSymForConstCheck(call)->hasFlag(FLAG_ARG_THIS)
)
USR_FATAL_CONT(call, "illegal call to %s() - it modifies 'const' fields of 'this', therefore it can be invoked only directly from a constructor on the object being constructed", resolvedFn->name);
lvalueCheck(call);
checkForStoringIntoTuple(call, resolvedFn);
if (const char* str = innerCompilerWarningMap.get(resolvedFn)) {
reissueCompilerWarning(str, 2);
if (callStack.n >= 2)
if (FnSymbol* fn = toFnSymbol(callStack.v[callStack.n-2]->isResolved()))
outerCompilerWarningMap.put(fn, str);
}
if (const char* str = outerCompilerWarningMap.get(resolvedFn)) {
reissueCompilerWarning(str, 1);
}
}
static void lvalueCheck(CallExpr* call)
{
// Check to ensure the actual supplied to an OUT, INOUT or REF argument
// is an lvalue.
for_formals_actuals(formal, actual, call) {
bool errorMsg = false;
switch (formal->intent) {
case INTENT_BLANK:
case INTENT_IN:
case INTENT_CONST:
case INTENT_CONST_IN:
case INTENT_PARAM:
case INTENT_TYPE:
// not checking them here
break;
case INTENT_INOUT:
case INTENT_OUT:
case INTENT_REF:
if (!isLegalLvalueActualArg(formal, actual))
errorMsg = true;
break;
case INTENT_CONST_REF:
if (!isLegalConstRefActualArg(formal, actual))
errorMsg = true;
break;
default:
// all intents should be covered above
INT_ASSERT(false);
break;
}
FnSymbol* nonTaskFnParent = NULL;
if (errorMsg &&
// sets nonTaskFnParent
checkAndUpdateIfLegalFieldOfThis(call, actual, nonTaskFnParent)
) {
errorMsg = false;
nonTaskFnParent->addFlag(FLAG_MODIFIES_CONST_FIELDS);
}
if (errorMsg) {
if (nonTaskFnParent->hasFlag(FLAG_SUPPRESS_LVALUE_ERRORS))
// we are asked to ignore errors here
return;
FnSymbol* calleeFn = call->isResolved();
INT_ASSERT(calleeFn == formal->defPoint->parentSymbol); // sanity
if (calleeFn->hasFlag(FLAG_ASSIGNOP)) {
// This assert is FYI. Perhaps can remove it if it fails.
INT_ASSERT(callStack.n > 0 && callStack.v[callStack.n-1] == call);
const char* recordName =
defaultRecordAssignmentTo(toFnSymbol(call->parentSymbol));
if (recordName && callStack.n >= 2)
// blame on the caller of the caller, if available
USR_FATAL_CONT(callStack.v[callStack.n-2],
"cannot assign to a record of the type %s"
" using the default assignment operator"
" because it has 'const' field(s)", recordName);
else
USR_FATAL_CONT(actual, "illegal lvalue in assignment");
}
else
{
ModuleSymbol* mod = calleeFn->getModule();
char cn1 = calleeFn->name[0];
const char* calleeParens = (isalpha(cn1) || cn1 == '_') ? "()" : "";
// Should this be the same condition as in insertLineNumber() ?
if (developer || mod->modTag == MOD_USER) {
USR_FATAL_CONT(actual, "non-lvalue actual is passed to %s formal '%s'"
" of %s%s", formal->intentDescrString(), formal->name,
calleeFn->name, calleeParens);
} else {
USR_FATAL_CONT(actual, "non-lvalue actual is passed to a %s formal of"
" %s%s", formal->intentDescrString(),
calleeFn->name, calleeParens);
}
}
}
}
}
// We do some const-related work upon PRIM_MOVE
static void setConstFlagsAndCheckUponMove(Symbol* lhs, Expr* rhs) {
// If this assigns into a loop index variable from a non-var iterator,
// mark the variable constant.
if (SymExpr* rhsSE = toSymExpr(rhs)) {
// If RHS is this special variable...
if (rhsSE->var->hasFlag(FLAG_INDEX_OF_INTEREST)) {
INT_ASSERT(lhs->hasFlag(FLAG_INDEX_VAR));
// ... and not of a reference type
// todo: differentiate based on ref-ness, not _ref type
// todo: not all const if it is zippered and one of iterators is var
if (!isReferenceType(rhsSE->var->type))
// ... and not an array (arrays are always yielded by reference)
if (!rhsSE->var->type->symbol->hasFlag(FLAG_ARRAY))
// ... then mark LHS constant.
lhs->addFlag(FLAG_CONST);
}
} else if (CallExpr* rhsCall = toCallExpr(rhs)) {
if (rhsCall->isPrimitive(PRIM_GET_MEMBER)) {
if (SymExpr* rhsBase = toSymExpr(rhsCall->get(1))) {
if (rhsBase->var->hasFlag(FLAG_CONST) ||
rhsBase->var->hasFlag(FLAG_REF_TO_CONST)
)
lhs->addFlag(FLAG_REF_TO_CONST);
} else {
INT_ASSERT(false); // PRIM_GET_MEMBER of a non-SymExpr??
}
} else if (FnSymbol* resolvedFn = rhsCall->isResolved()) {
setFlagsAndCheckForConstAccess(lhs, rhsCall, resolvedFn);
}
}
}
static void resolveTupleAndExpand(CallExpr* call) {
SymExpr* se = toSymExpr(call->get(1));
int size = 0;
for (int i = 0; i < se->var->type->substitutions.n; i++) {
if (se->var->type->substitutions.v[i].key) {
if (!strcmp("size", se->var->type->substitutions.v[i].key->name)) {
size = toVarSymbol(se->var->type->substitutions.v[i].value)->immediate->int_value();
break;
}
}
}
INT_ASSERT(size);
CallExpr* noop = new CallExpr(PRIM_NOOP);
call->getStmtExpr()->insertBefore(noop);
VarSymbol* tmp = gTrue;
for (int i = 1; i <= size; i++) {
VarSymbol* tmp1 = newTemp("_tuple_and_expand_tmp_");
tmp1->addFlag(FLAG_MAYBE_PARAM);
tmp1->addFlag(FLAG_MAYBE_TYPE);
VarSymbol* tmp2 = newTemp("_tuple_and_expand_tmp_");
tmp2->addFlag(FLAG_MAYBE_PARAM);
tmp2->addFlag(FLAG_MAYBE_TYPE);
VarSymbol* tmp3 = newTemp("_tuple_and_expand_tmp_");
tmp3->addFlag(FLAG_MAYBE_PARAM);
tmp3->addFlag(FLAG_MAYBE_TYPE);
VarSymbol* tmp4 = newTemp("_tuple_and_expand_tmp_");
tmp4->addFlag(FLAG_MAYBE_PARAM);
tmp4->addFlag(FLAG_MAYBE_TYPE);
call->getStmtExpr()->insertBefore(new DefExpr(tmp1));
call->getStmtExpr()->insertBefore(new DefExpr(tmp2));
call->getStmtExpr()->insertBefore(new DefExpr(tmp3));
call->getStmtExpr()->insertBefore(new DefExpr(tmp4));
call->getStmtExpr()->insertBefore(
new CallExpr(PRIM_MOVE, tmp1,
new CallExpr(se->copy(), new_IntSymbol(i))));
CallExpr* query = new CallExpr(PRIM_QUERY, tmp1);
for (int i = 2; i < call->numActuals(); i++)
query->insertAtTail(call->get(i)->copy());
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp2, query));
call->getStmtExpr()->insertBefore(
new CallExpr(PRIM_MOVE, tmp3,
new CallExpr("==", tmp2, call->get(3)->copy())));
call->getStmtExpr()->insertBefore(
new CallExpr(PRIM_MOVE, tmp4,
new CallExpr("&", tmp3, tmp)));
tmp = tmp4;
}
call->replace(new SymExpr(tmp));
noop->replace(call); // put call back in ast for function resolution
makeNoop(call);
}
static void resolveTupleExpand(CallExpr* call) {
SymExpr* sym = toSymExpr(call->get(1));
Type* type = sym->var->getValType();
if (!type->symbol->hasFlag(FLAG_TUPLE))
USR_FATAL(call, "invalid tuple expand primitive");
int size = 0;
for (int i = 0; i < type->substitutions.n; i++) {
if (type->substitutions.v[i].key) {
if (!strcmp("size", type->substitutions.v[i].key->name)) {
size = toVarSymbol(type->substitutions.v[i].value)->immediate->int_value();
break;
}
}
}
if (size == 0)
INT_FATAL(call, "Invalid tuple expand primitive");
CallExpr* parent = toCallExpr(call->parentExpr);
CallExpr* noop = new CallExpr(PRIM_NOOP);
call->getStmtExpr()->insertBefore(noop);
for (int i = 1; i <= size; i++) {
VarSymbol* tmp = newTemp("_tuple_expand_tmp_");
tmp->addFlag(FLAG_MAYBE_TYPE);
DefExpr* def = new DefExpr(tmp);
call->getStmtExpr()->insertBefore(def);
CallExpr* e = NULL;
if (!call->parentSymbol->hasFlag(FLAG_EXPAND_TUPLES_WITH_VALUES)) {
e = new CallExpr(sym->copy(), new_IntSymbol(i));
} else {
e = new CallExpr(PRIM_GET_MEMBER_VALUE, sym->copy(),
new_StringSymbol(astr("x", istr(i))));
}
CallExpr* move = new CallExpr(PRIM_MOVE, tmp, e);
call->getStmtExpr()->insertBefore(move);
call->insertBefore(new SymExpr(tmp));
}
call->remove();
noop->replace(call); // put call back in ast for function resolution
makeNoop(call);
// increase tuple rank
if (parent && parent->isNamed("_type_construct__tuple")) {
parent->get(1)->replace(new SymExpr(new_IntSymbol(parent->numActuals()-1)));
}
}
static void resolveSetMember(CallExpr* call) {
// Get the field name.
SymExpr* sym = toSymExpr(call->get(2));
if (!sym)
INT_FATAL(call, "bad set member primitive");
VarSymbol* var = toVarSymbol(sym->var);
if (!var || !var->immediate)
INT_FATAL(call, "bad set member primitive");
const char* name = var->immediate->v_string;
// Special case: An integer field name is actually a tuple member index.
{
int64_t i;
if (get_int(sym, &i)) {
name = astr("x", istr(i));
call->get(2)->replace(new SymExpr(new_StringSymbol(name)));
}
}
AggregateType* ct = toAggregateType(call->get(1)->typeInfo());
if (!ct)
INT_FATAL(call, "bad set member primitive");
Symbol* fs = NULL;
for_fields(field, ct) {
if (!strcmp(field->name, name)) {
fs = field; break;
}
}
if (!fs)
INT_FATAL(call, "bad set member primitive");
Type* t = call->get(3)->typeInfo();
// I think this never happens, so can be turned into an assert. <hilde>
if (t == dtUnknown)
INT_FATAL(call, "Unable to resolve field type");
if (t == dtNil && fs->type == dtUnknown)
USR_FATAL(call->parentSymbol, "unable to determine type of field from nil");
if (fs->type == dtUnknown)
fs->type = t;
if (t != fs->type && t != dtNil && t != dtObject) {
USR_FATAL(userCall(call),
"cannot assign expression of type %s to field of type %s",
toString(t), toString(fs->type));
}
}
static void resolveMove(CallExpr* call) {
Expr* rhs = call->get(2);
Symbol* lhs = NULL;
if (SymExpr* se = toSymExpr(call->get(1)))
lhs = se->var;
INT_ASSERT(lhs);
FnSymbol* fn = toFnSymbol(call->parentSymbol);
bool isReturn = fn ? lhs == fn->getReturnSymbol() : false;
if (lhs->hasFlag(FLAG_TYPE_VARIABLE) && !isTypeExpr(rhs)) {
if (isReturn) {
if (!call->parentSymbol->hasFlag(FLAG_RUNTIME_TYPE_INIT_FN))
USR_FATAL(call, "illegal return of value where type is expected");
} else {
USR_FATAL(call, "illegal assignment of value to type");
}
}
if (!lhs->hasFlag(FLAG_TYPE_VARIABLE) && !lhs->hasFlag(FLAG_MAYBE_TYPE) && isTypeExpr(rhs)) {
if (isReturn) {
USR_FATAL(call, "illegal return of type where value is expected");
} else {
USR_FATAL(call, "illegal assignment of type to value");
}
}
// do not resolve function return type yet
// except for constructors
if (fn && call->parentExpr != fn->where && call->parentExpr != fn->retExprType &&
isReturn && fn->_this != lhs) {
if (fn->retType == dtUnknown) {
return;
}
}
Type* rhsType = rhs->typeInfo();
if (rhsType == dtVoid) {
if (isReturn && (lhs->type == dtVoid || lhs->type == dtUnknown))
{
// It is OK to assign void to the return value variable as long as its
// type is void or is not yet established.
}
else
{
if (CallExpr* rhsFn = toCallExpr(rhs)) {
if (FnSymbol* rhsFnSym = rhsFn->isResolved()) {
USR_FATAL(userCall(call),
"illegal use of function that does not return a value: '%s'",
rhsFnSym->name);
}
}
USR_FATAL(userCall(call),
"illegal use of function that does not return a value");
}
}
if (lhs->type == dtUnknown || lhs->type == dtNil)
lhs->type = rhsType;
Type* lhsType = lhs->type;
setConstFlagsAndCheckUponMove(lhs, rhs);
if (CallExpr* call = toCallExpr(rhs)) {
if (FnSymbol* fn = call->isResolved()) {
if (rhsType == dtUnknown) {
USR_FATAL_CONT(fn, "unable to resolve return type of function '%s'", fn->name);
USR_FATAL(rhs, "called recursively at this point");
}
}
}
if (rhsType == dtUnknown)
USR_FATAL(call, "unable to resolve type");
if (rhsType == dtNil && lhsType != dtNil && !isClass(lhsType))
USR_FATAL(userCall(call), "type mismatch in assignment from nil to %s",
toString(lhsType));
Type* lhsBaseType = lhsType->getValType();
Type* rhsBaseType = rhsType->getValType();
bool isChplHereAlloc = false;
// Fix up calls inserted by callChplHereAlloc()
if (CallExpr* rhsCall = toCallExpr(rhs)) {
// Here we are going to fix up calls inserted by
// callChplHereAlloc() and callChplHereFree()
//
// Currently this code assumes that such primitives are only
// inserted by the compiler. TODO: Add a check to make sure
// these are the ones added by the above functions.
//
if (rhsCall->isPrimitive(PRIM_SIZEOF)) {
// Fix up arg to sizeof(), as we may not have known the
// type earlier
SymExpr* sizeSym = toSymExpr(rhsCall->get(1));
INT_ASSERT(sizeSym);
rhs->replace(new CallExpr(PRIM_SIZEOF, sizeSym->var->typeInfo()->symbol));
return;
} else if (rhsCall->isPrimitive(PRIM_CAST_TO_VOID_STAR)) {
if (isReferenceType(rhsCall->get(1)->typeInfo())) {
// Add a dereference as needed, as we did not have complete
// type information earlier
SymExpr* castVar = toSymExpr(rhsCall->get(1));
INT_ASSERT(castVar);
VarSymbol* derefTmp = newTemp("castDeref", castVar->typeInfo()->getValType());
call->insertBefore(new DefExpr(derefTmp));
call->insertBefore(new CallExpr(PRIM_MOVE, derefTmp,
new CallExpr(PRIM_DEREF,
new SymExpr(castVar->var))));
rhsCall->replace(new CallExpr(PRIM_CAST_TO_VOID_STAR,
new SymExpr(derefTmp)));
}
} else if (rhsCall->isResolved() == gChplHereAlloc) {
// Insert cast below for calls to chpl_here_*alloc()
isChplHereAlloc = true;
}
}
if (!isChplHereAlloc && rhsType != dtNil &&
rhsBaseType != lhsBaseType &&
!isDispatchParent(rhsBaseType, lhsBaseType))
USR_FATAL(userCall(call), "type mismatch in assignment from %s to %s",
toString(rhsType), toString(lhsType));
if (isChplHereAlloc ||
(rhsType != lhsType && isDispatchParent(rhsBaseType, lhsBaseType))) {
Symbol* tmp = newTemp("cast_tmp", rhsType);
call->insertBefore(new DefExpr(tmp));
call->insertBefore(new CallExpr(PRIM_MOVE, tmp, rhs->remove()));
call->insertAtTail(new CallExpr(PRIM_CAST,
isChplHereAlloc ? lhs->type->symbol :
lhsBaseType->symbol, tmp));
}
}
// Some new expressions are converted in normalize(). For example, a call to a
// type function is resolved at this point.
// The syntax supports calling the result of a type function as a constructor,
// but this is not fully implemented.
static void
resolveNew(CallExpr* call)
{
// This is a 'new' primitive, so we expect the argument to be a constructor
// call.
CallExpr* ctor = toCallExpr(call->get(1));
// May need to resolve ctor here.
if (FnSymbol* fn = ctor->isResolved())
{
// If the function is a constructor, just bridge out the 'new' primitive
// and call the constructor. Done.
if (fn->hasFlag(FLAG_CONSTRUCTOR))
{
call->replace(ctor);
return;
}
// Not a constructor, so issue an error.
USR_FATAL(call, "invalid use of 'new' on %s", fn->name);
return;
}
if (UnresolvedSymExpr* urse = toUnresolvedSymExpr(ctor->baseExpr))
{
USR_FATAL(call, "invalid use of 'new' on %s", urse->unresolved);
return;
}
USR_FATAL(call, "invalid use of 'new'");
}
//
// This tells us whether we can rely on the compiler's back end (e.g.,
// C) to provide the copy for us for 'in' or 'const in' intents when
// passing an argument of type 't'.
//
static bool backendRequiresCopyForIn(Type* t) {
return (isRecord(t) ||
t->symbol->hasFlag(FLAG_ARRAY) ||
t->symbol->hasFlag(FLAG_DOMAIN));
}
// Returns true if the formal needs an internal temporary, false otherwise.
static bool
formalRequiresTemp(ArgSymbol* formal) {
//
// get the formal's function
//
FnSymbol* fn = toFnSymbol(formal->defPoint->parentSymbol);
INT_ASSERT(fn);
return
//
// 'out' and 'inout' intents are passed by ref at the C level, so we
// need to make an explicit copy in the codegen'd function */
//
(formal->intent == INTENT_OUT ||
formal->intent == INTENT_INOUT ||
//
// 'in' and 'const in' also require a copy, but for simple types
// (like ints or class references), we can rely on C's copy when
// passing the argument, as long as the routine is not
// inlined.
//
((formal->intent == INTENT_IN || formal->intent == INTENT_CONST_IN) &&
(backendRequiresCopyForIn(formal->type) || !fn->hasFlag(FLAG_INLINE)))
//
// The following case reduces memory leaks for zippered forall
// leader/follower pairs where the communicated intermediate
// result is a tuple of ranges, but I can't explain why it'd be
// needed. Tom has said that iterators haven't really been
// bolted down in terms of memory leaks, so future work would be
// to remove this hack and close the leak properly.
//
|| strcmp(formal->name, "followThis") == 0
);
}
static void
insertFormalTemps(FnSymbol* fn) {
SymbolMap formals2vars;
for_formals(formal, fn) {
if (formalRequiresTemp(formal)) {
SET_LINENO(formal);
VarSymbol* tmp = newTemp(astr("_formal_tmp_", formal->name));
formals2vars.put(formal, tmp);
}
}
if (formals2vars.n > 0) {
// The names of formals in the body of this function are replaced with the
// names of their corresponding local temporaries.
update_symbols(fn->body, &formals2vars);
// Add calls to chpl__initCopy to create local copies as necessary.
// Add writeback code for out and inout intents.
addLocalCopiesAndWritebacks(fn, formals2vars);
}
}
// Given the map from formals to local "_formal_tmp_" variables, this function
// adds code as necessary
// - to copy the formal into the temporary at the start of the function
// - and copy it back when done.
// The copy in is needed for "inout", "in" and "const in" intents.
// The copy out is needed for "inout" and "out" intents.
// Blank intent is treated like "const", and normally copies the formal through
// chpl__autoCopy.
// Note that autoCopy is called in this case, but not for "inout", "in" and "const in".
// Either record-wrapped types are always passed by ref, or some unexpected
// behavior will result by applying "in" intents to them.
static void addLocalCopiesAndWritebacks(FnSymbol* fn, SymbolMap& formals2vars)
{
// Enumerate the formals that have local temps.
form_Map(SymbolMapElem, e, formals2vars) {
ArgSymbol* formal = toArgSymbol(e->key); // Get the formal.
Symbol* tmp = e->value; // Get the temp.
SET_LINENO(formal);
// TODO: Move this closer to the location (in code) where we determine
// whether tmp owns its value or not. That is, push setting these flags
// (or not) into the cases below, as appropriate.
Type* formalType = formal->type->getValType();
if ((formal->intent == INTENT_BLANK ||
formal->intent == INTENT_CONST ||
formal->intent == INTENT_CONST_IN) &&
!isSyncType(formalType) &&
!isRefCountedType(formalType))
{
tmp->addFlag(FLAG_CONST);
tmp->addFlag(FLAG_INSERT_AUTO_DESTROY);
}
// This switch adds the extra code inside the current function necessary
// to implement the ref-to-value semantics, where needed.
switch (formal->intent)
{
// Make sure we handle every case.
default:
INT_FATAL("Unhandled INTENT case.");
break;
// These cases are weeded out by formalRequiresTemp() above.
case INTENT_PARAM:
case INTENT_TYPE:
case INTENT_REF:
case INTENT_CONST_REF:
INT_FATAL("Unexpected INTENT case.");
break;
case INTENT_OUT:
if (formal->defaultExpr && formal->defaultExpr->body.tail->typeInfo() != dtTypeDefaultToken) {
BlockStmt* defaultExpr = formal->defaultExpr->copy();
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, defaultExpr->body.tail->remove()));
fn->insertAtHead(defaultExpr);
} else {
VarSymbol* refTmp = newTemp("_formal_ref_tmp_");
VarSymbol* typeTmp = newTemp("_formal_type_tmp_");
typeTmp->addFlag(FLAG_MAYBE_TYPE);
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_INIT, typeTmp)));
fn->insertAtHead(new CallExpr(PRIM_MOVE, typeTmp, new CallExpr(PRIM_TYPEOF, refTmp)));
fn->insertAtHead(new CallExpr(PRIM_MOVE, refTmp, new CallExpr(PRIM_DEREF, formal)));
fn->insertAtHead(new DefExpr(refTmp));
fn->insertAtHead(new DefExpr(typeTmp));
}
break;
case INTENT_INOUT:
case INTENT_IN:
case INTENT_CONST_IN:
// TODO: Adding a formal temp for INTENT_CONST_IN is conservative.
// If the compiler verifies in a separate pass that it is never written,
// we don't have to copy it.
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr("chpl__initCopy", formal)));
tmp->addFlag(FLAG_INSERT_AUTO_DESTROY);
break;
case INTENT_BLANK:
case INTENT_CONST:
{
TypeSymbol* ts = formal->type->symbol;
if (!getRecordWrappedFlags(ts).any() &&
!ts->hasFlag(FLAG_ITERATOR_CLASS) &&
!ts->hasFlag(FLAG_ITERATOR_RECORD) &&
!getSyncFlags(ts).any()) {
if (fn->hasFlag(FLAG_BEGIN)) {
// autoCopy/autoDestroy will be added later, in parallel pass
// by insertAutoCopyDestroyForTaskArg()
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, formal));
tmp->removeFlag(FLAG_INSERT_AUTO_DESTROY);
} else {
// Note that because we reject the case of record-wrapped types above,
// the only way we can get a formal whose call to chpl__autoCopy does
// anything different from calling chpl__initCopy is if the formal is a
// tuple containing a record-wrapped type. This is probably not
// intentional: It gives tuple-wrapped record-wrapped types different
// behavior from bare record-wrapped types.
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr("chpl__autoCopy", formal)));
// WORKAROUND:
// This is a temporary bug fix that results in leaked memory.
//
// Here we avoid calling the destructor for any formals that
// are records or have records because the call may result
// in repeatedly freeing memory if the user defined
// destructor calls delete on any fields. I think we
// probably need a similar change in the INOUT/IN case
// above. See test/types/records/sungeun/destructor3.chpl
// and test/users/recordbug3.chpl.
//
// For records, this problem should go away if/when we
// implement 'const ref' intents and make them the default
// for records.
//
// Another solution (and the one that would fix records in
// classes) is to call the user record's default
// constructor if it takes no arguments. This is not the
// currently described behavior in the spec. This would
// require the user to implement a default constructor if
// explicit memory allocation is required.
//
if (!isAggregateType(formal->type) ||
(isRecord(formal->type) &&
((formal->type->getModule()->modTag==MOD_INTERNAL) ||
(formal->type->getModule()->modTag==MOD_STANDARD))) ||
!typeHasRefField(formal->type))
tmp->addFlag(FLAG_INSERT_AUTO_DESTROY);
}
} else
{
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, formal));
// If this is a simple move, then we did not call chpl__autoCopy to
// create tmp, so then it is a bad idea to insert a call to
// chpl__autodestroy later.
tmp->removeFlag(FLAG_INSERT_AUTO_DESTROY);
}
break;
}
}
fn->insertAtHead(new DefExpr(tmp));
// For inout or out intent, this assigns the modified value back to the
// formal at the end of the function body.
if (formal->intent == INTENT_INOUT || formal->intent == INTENT_OUT) {
fn->insertBeforeReturnAfterLabel(new CallExpr("=", formal, tmp));
}
}
}
//
//
//
static Expr* dropUnnecessaryCast(CallExpr* call) {
// Check for and remove casts to the original type and size
Expr* result = call;
if (!call->isNamed("_cast"))
INT_FATAL("dropUnnecessaryCasts called on non _cast call");
if (SymExpr* sym = toSymExpr(call->get(2))) {
if (VarSymbol* var = toVarSymbol(sym->var)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
Type* oldType = var->type;
Type* newType = sym->var->type;
if (newType == oldType) {
result = new SymExpr(var);
call->replace(result);
}
}
} else if (EnumSymbol* e = toEnumSymbol(sym->var)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
EnumType* oldType = toEnumType(e->type);
EnumType* newType = toEnumType(sym->var->type);
if (newType && oldType == newType) {
result = new SymExpr(e);
call->replace(result);
}
}
}
}
return result;
}
/*
Creates the parent class which will represent the function's type. Children of the parent class will capture different functions which
happen to share the same function type. By using the parent class we can assign new values onto variable that match the function type
but may currently be pointing at a different function.
*/
static AggregateType* createAndInsertFunParentClass(CallExpr *call, const char *name) {
AggregateType *parent = new AggregateType(AGGREGATE_CLASS);
TypeSymbol *parent_ts = new TypeSymbol(name, parent);
parent_ts->addFlag(FLAG_FUNCTION_CLASS);
// Because this function type needs to be globally visible (because we don't know the modules it will be passed to), we put
// it at the highest scope
theProgram->block->body.insertAtTail(new DefExpr(parent_ts));
parent->dispatchParents.add(dtObject);
dtObject->dispatchChildren.add(parent);
VarSymbol* parent_super = new VarSymbol("super", dtObject);
parent_super->addFlag(FLAG_SUPER_CLASS);
parent->fields.insertAtHead(new DefExpr(parent_super));
build_constructors(parent);
buildDefaultDestructor(parent);
return parent;
}
/*
To mimic a function call, we create a .this method for the parent class. This will allow the object to look and feel like a
first-class function, by both being an object and being invoked using parentheses syntax. Children of the parent class will
override this method and wrap the function that is being used as a first-class value.
To focus on just the types of the arguments and not their names or default values, we use the parent method's names and types
as the basis for all children which override it.
The function is put at the highest scope so that all functions of a given type will share the same parent class.
*/
static FnSymbol* createAndInsertFunParentMethod(CallExpr *call, AggregateType *parent, AList &arg_list, bool isFormal, Type *retType) {
FnSymbol* parent_method = new FnSymbol("this");
parent_method->addFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION);
parent_method->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
parent_method->addFlag(FLAG_METHOD);
ArgSymbol* thisParentSymbol = new ArgSymbol(INTENT_BLANK, "this", parent);
thisParentSymbol->addFlag(FLAG_ARG_THIS);
parent_method->insertFormalAtTail(thisParentSymbol);
parent_method->_this = thisParentSymbol;
int i = 0, alength = arg_list.length;
//We handle the arg list differently depending on if it's a list of formal args or actual args
if (isFormal) {
for_alist(formalExpr, arg_list) {
DefExpr* dExp = toDefExpr(formalExpr);
ArgSymbol* fArg = toArgSymbol(dExp->sym);
if (fArg->type != dtVoid) {
ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, fArg->name, fArg->type);
if (fArg->typeExpr)
newFormal->typeExpr = fArg->typeExpr->copy();
parent_method->insertFormalAtTail(newFormal);
}
}
}
else {
char name_buffer[100];
int name_index = 0;
for_alist(actualExpr, arg_list) {
sprintf(name_buffer, "name%i", name_index++);
if (i != (alength-1)) {
SymExpr* sExpr = toSymExpr(actualExpr);
if (sExpr->var->type != dtVoid) {
ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, name_buffer, sExpr->var->type);
parent_method->insertFormalAtTail(newFormal);
}
}
++i;
}
}
if (retType != dtVoid) {
VarSymbol *tmp = newTemp("_return_tmp_", retType);
parent_method->insertAtTail(new DefExpr(tmp));
parent_method->insertAtTail(new CallExpr(PRIM_RETURN, tmp));
}
// Because this function type needs to be globally visible (because we don't know the modules it will be passed to), we put
// it at the highest scope
theProgram->block->body.insertAtTail(new DefExpr(parent_method));
normalize(parent_method);
parent->methods.add(parent_method);
return parent_method;
}
/*
Builds up the name of the parent for lookup by looking through the types of the arguments, either formal or actual
*/
static std::string buildParentName(AList &arg_list, bool isFormal, Type *retType) {
std::ostringstream oss;
oss << "chpl__fcf_type_";
bool isFirst = true;
if (isFormal) {
if (arg_list.length == 0) {
oss << "void";
}
else {
for_alist(formalExpr, arg_list) {
DefExpr* dExp = toDefExpr(formalExpr);
ArgSymbol* fArg = toArgSymbol(dExp->sym);
if (!isFirst)
oss << "_";
oss << fArg->type->symbol->cname;
isFirst = false;
}
}
oss << "_";
oss << retType->symbol->cname;
}
else {
int i = 0, alength = arg_list.length;
if (alength == 1) {
oss << "void_";
}
for_alist(actualExpr, arg_list) {
if (!isFirst)
oss << "_";
SymExpr* sExpr = toSymExpr(actualExpr);
++i;
oss << sExpr->var->type->symbol->cname;
isFirst = false;
}
}
return oss.str();
}
/*
Helper function for creating or finding the parent class for a given function type specified
by the type signature. The last type given in the signature is the return type, the remainder
represent arguments to the function.
*/
static AggregateType* createOrFindFunTypeFromAnnotation(AList &arg_list, CallExpr *call) {
AggregateType *parent;
SymExpr *retTail = toSymExpr(arg_list.tail);
Type *retType = retTail->var->type;
std::string parent_name = buildParentName(arg_list, false, retType);
if (functionTypeMap.find(parent_name) != functionTypeMap.end()) {
parent = functionTypeMap[parent_name].first;
} else {
parent = createAndInsertFunParentClass(call, parent_name.c_str());
FnSymbol* parent_method = createAndInsertFunParentMethod(call, parent, arg_list, false, retType);
functionTypeMap[parent_name] = std::pair<AggregateType*, FnSymbol*>(parent, parent_method);
}
return parent;
}
/*
Captures a function as a first-class value by creating an object that will represent the function. The class is
created at the same scope as the function being referenced. Each class is unique and shared among all
uses of that function as a value. Once built, the class will override the .this method of the parent and wrap
the call to the function being captured as a value. Then, an instance of the class is instantiated and returned.
*/
static Expr*
createFunctionAsValue(CallExpr *call) {
static int unique_fcf_id = 0;
UnresolvedSymExpr* use = toUnresolvedSymExpr(call->get(1));
INT_ASSERT(use);
const char *flname = use->unresolved;
Vec<FnSymbol*> visibleFns;
Vec<BlockStmt*> visited;
getVisibleFunctions(getVisibilityBlock(call), flname, visibleFns, visited);
if (visibleFns.n > 1) {
USR_FATAL(call, "%s: can not capture overloaded functions as values",
visibleFns.v[0]->name);
}
INT_ASSERT(visibleFns.n == 1);
FnSymbol* captured_fn = visibleFns.head();
//Check to see if we've already cached the capture somewhere
if (functionCaptureMap.find(captured_fn) != functionCaptureMap.end()) {
return new CallExpr(functionCaptureMap[captured_fn]);
}
resolveFormals(captured_fn);
resolveFns(captured_fn);
AggregateType *parent;
FnSymbol *thisParentMethod;
std::string parent_name = buildParentName(captured_fn->formals, true, captured_fn->retType);
if (functionTypeMap.find(parent_name) != functionTypeMap.end()) {
std::pair<AggregateType*, FnSymbol*> ctfs = functionTypeMap[parent_name];
parent = ctfs.first;
thisParentMethod = ctfs.second;
}
else {
parent = createAndInsertFunParentClass(call, parent_name.c_str());
thisParentMethod = createAndInsertFunParentMethod(call, parent, captured_fn->formals, true, captured_fn->retType);
functionTypeMap[parent_name] = std::pair<AggregateType*, FnSymbol*>(parent, thisParentMethod);
}
AggregateType *ct = new AggregateType(AGGREGATE_CLASS);
std::ostringstream fcf_name;
fcf_name << "_chpl_fcf_" << unique_fcf_id++ << "_" << flname;
TypeSymbol *ts = new TypeSymbol(astr(fcf_name.str().c_str()), ct);
call->parentExpr->insertBefore(new DefExpr(ts));
ct->dispatchParents.add(parent);
bool inserted = parent->dispatchChildren.add_exclusive(ct);
INT_ASSERT(inserted);
VarSymbol* super = new VarSymbol("super", parent);
super->addFlag(FLAG_SUPER_CLASS);
ct->fields.insertAtHead(new DefExpr(super));
build_constructors(ct);
buildDefaultDestructor(ct);
FnSymbol *thisMethod = new FnSymbol("this");
thisMethod->addFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION);
thisMethod->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
thisMethod->addFlag(FLAG_METHOD);
ArgSymbol *thisSymbol = new ArgSymbol(INTENT_BLANK, "this", ct);
thisSymbol->addFlag(FLAG_ARG_THIS);
thisMethod->insertFormalAtTail(thisSymbol);
thisMethod->_this = thisSymbol;
CallExpr *innerCall = new CallExpr(captured_fn);
int skip = 2;
for_alist(formalExpr, thisParentMethod->formals) {
//Skip the first two arguments from the parent, which are _mt and this
if (skip) {
--skip;
continue;
}
DefExpr* dExp = toDefExpr(formalExpr);
ArgSymbol* fArg = toArgSymbol(dExp->sym);
ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, fArg->name, fArg->type);
if (fArg->typeExpr)
newFormal->typeExpr = fArg->typeExpr->copy();
SymExpr* argSym = new SymExpr(newFormal);
innerCall->insertAtTail(argSym);
thisMethod->insertFormalAtTail(newFormal);
}
std::vector<CallExpr*> calls;
collectCallExprs(captured_fn, calls);
for_vector(CallExpr, cl, calls) {
if (cl->isPrimitive(PRIM_YIELD)) {
USR_FATAL_CONT(cl, "Iterators not allowed in first class functions");
}
}
if (captured_fn->retType == dtVoid) {
thisMethod->insertAtTail(innerCall);
}
else {
VarSymbol *tmp = newTemp("_return_tmp_");
thisMethod->insertAtTail(new DefExpr(tmp));
thisMethod->insertAtTail(new CallExpr(PRIM_MOVE, tmp, innerCall));
thisMethod->insertAtTail(new CallExpr(PRIM_RETURN, tmp));
}
call->parentExpr->insertBefore(new DefExpr(thisMethod));
normalize(thisMethod);
ct->methods.add(thisMethod);
FnSymbol *wrapper = new FnSymbol("wrapper");
wrapper->addFlag(FLAG_INLINE);
wrapper->insertAtTail(new CallExpr(PRIM_RETURN, new CallExpr(PRIM_CAST, parent->symbol, new CallExpr(ct->defaultInitializer))));
call->getStmtExpr()->insertBefore(new DefExpr(wrapper));
normalize(wrapper);
CallExpr *call_wrapper = new CallExpr(wrapper);
functionCaptureMap[captured_fn] = wrapper;
return call_wrapper;
}
//
// returns true if the symbol is defined in an outer function to fn
// third argument not used at call site
//
static bool
isOuterVar(Symbol* sym, FnSymbol* fn, Symbol* parent /* = NULL*/) {
if (!parent)
parent = fn->defPoint->parentSymbol;
if (!isFnSymbol(parent))
return false;
else if (sym->defPoint->parentSymbol == parent)
return true;
else
return isOuterVar(sym, fn, parent->defPoint->parentSymbol);
}
//
// finds outer vars directly used in a function
//
static bool
usesOuterVars(FnSymbol* fn, Vec<FnSymbol*> &seen) {
std::vector<BaseAST*> asts;
collect_asts(fn, asts);
for_vector(BaseAST, ast, asts) {
if (toCallExpr(ast)) {
CallExpr *call = toCallExpr(ast);
//dive into calls
Vec<FnSymbol*> visibleFns;
Vec<BlockStmt*> visited;
getVisibleFunctions(getVisibilityBlock(call), call->parentSymbol->name, visibleFns, visited);
forv_Vec(FnSymbol, called_fn, visibleFns) {
bool seen_this_fn = false;
forv_Vec(FnSymbol, seen_fn, seen) {
if (called_fn == seen_fn) {
seen_this_fn = true;
break;
}
}
if (!seen_this_fn) {
seen.add(called_fn);
if (usesOuterVars(called_fn, seen)) {
return true;
}
}
}
}
if (SymExpr* symExpr = toSymExpr(ast)) {
Symbol* sym = symExpr->var;
if (isLcnSymbol(sym)) {
if (isOuterVar(sym, fn))
return true;
}
}
}
return false;
}
static bool
isNormalField(Symbol* field)
{
if( field->hasFlag(FLAG_IMPLICIT_ALIAS_FIELD) ) return false;
if( field->hasFlag(FLAG_TYPE_VARIABLE) ) return false;
if( field->hasFlag(FLAG_SUPER_CLASS) ) return false;
// TODO -- this will break user fields named outer!
if( 0 == strcmp("outer", field->name)) return false;
return true;
}
static CallExpr* toPrimToLeaderCall(Expr* expr) {
if (CallExpr* call = toCallExpr(expr))
if (call->isPrimitive(PRIM_TO_LEADER) ||
call->isPrimitive(PRIM_TO_STANDALONE))
return call;
return NULL;
}
// Recursively resolve typedefs
static Type* resolveTypeAlias(SymExpr* se)
{
if (! se)
return NULL;
// Quick exit if the type is already known.
Type* result = se->getValType();
if (result != dtUnknown)
return result;
VarSymbol* var = toVarSymbol(se->var);
if (! var)
return NULL;
DefExpr* def = var->defPoint;
SET_LINENO(def);
Expr* typeExpr = resolve_type_expr(def->init);
SymExpr* tse = toSymExpr(typeExpr);
return resolveTypeAlias(tse);
}
// Returns NULL if no substitution was made. Otherwise, returns the expression
// that replaced 'call'.
static Expr* resolveTupleIndexing(CallExpr* call, Symbol* baseVar)
{
if (call->numActuals() != 3)
USR_FATAL(call, "illegal tuple indexing expression");
Type* indexType = call->get(3)->getValType();
if (!is_int_type(indexType) && !is_uint_type(indexType))
USR_FATAL(call, "tuple indexing expression is not of integral type");
AggregateType* baseType = toAggregateType(baseVar->getValType());
int64_t index;
uint64_t uindex;
char field[8];
if (get_int(call->get(3), &index)) {
sprintf(field, "x%" PRId64, index);
if (index <= 0 || index >= baseType->fields.length)
USR_FATAL(call, "tuple index out-of-bounds error (%ld)", index);
} else if (get_uint(call->get(3), &uindex)) {
sprintf(field, "x%" PRIu64, uindex);
if (uindex <= 0 || uindex >= (unsigned long)baseType->fields.length)
USR_FATAL(call, "tuple index out-of-bounds error (%lu)", uindex);
} else {
return NULL; // not a tuple indexing expression
}
Type* fieldType = baseType->getField(field)->type;
// Decomposing into a loop index variable from a non-var iterator?
// In some cases, extract the value and mark constant.
// See e.g. test/statements/vass/index-variable-const-errors.chpl
bool intoIndexVarByVal = false;
// If decomposing this special variable
// or another tuple that we just decomposed.
if (baseVar->hasFlag(FLAG_INDEX_OF_INTEREST)) {
// Find the destination.
CallExpr* move = toCallExpr(call->parentExpr);
INT_ASSERT(move && move->isPrimitive(PRIM_MOVE));
SymExpr* destSE = toSymExpr(move->get(1));
INT_ASSERT(destSE);
if (!isReferenceType(baseVar->type) &&
!isReferenceType(fieldType)) {
if (destSE->var->hasFlag(FLAG_INDEX_VAR)) {
// The destination is constant only if both the tuple
// and the current component are non-references.
// And it's not an array (arrays are always yielded by reference)
// - see boundaries() in release/examples/benchmarks/miniMD/miniMD.
if (!fieldType->symbol->hasFlag(FLAG_ARRAY)) {
destSE->var->addFlag(FLAG_CONST);
}
} else {
INT_ASSERT(destSE->var->hasFlag(FLAG_TEMP));
// We are detupling into another tuple,
// which will be detupled later.
destSE->var->addFlag(FLAG_INDEX_OF_INTEREST);
}
}
if (!isReferenceType(baseVar->type))
// If either a non-var iterator or zippered,
// extract with PRIM_GET_MEMBER_VALUE.
intoIndexVarByVal = true;
}
Expr* result;
if (isReferenceType(fieldType) || intoIndexVarByVal)
result = new CallExpr(PRIM_GET_MEMBER_VALUE, baseVar, new_StringSymbol(field));
else
result = new CallExpr(PRIM_GET_MEMBER, baseVar, new_StringSymbol(field));
call->replace(result);
return result;
}
// Returns NULL if no substitution was made. Otherwise, returns the expression
// that replaced the PRIM_INIT (or PRIM_NO_INIT) expression.
// Here, "replaced" means that the PRIM_INIT (or PRIM_NO_INIT) primitive is no
// longer in the tree.
static Expr* resolvePrimInit(CallExpr* call)
{
Expr* result = NULL;
// ('init' foo) --> A default value or the result of an initializer call.
// ('no_init' foo) --> Ditto, only in some cases a simpler default value.
// The argument is expected to be a type variable.
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (!se->var->hasFlag(FLAG_TYPE_VARIABLE))
USR_FATAL(call, "invalid type specification");
Type* type = resolveTypeAlias(se);
// Do not resolve PRIM_INIT on extern types.
// These are removed later.
// It is useful to leave them in the tree, because PRIM_INIT behaves like an
// expression and has a type.
if (type->symbol->hasFlag(FLAG_EXTERN))
{
CallExpr* stmt = toCallExpr(call->parentExpr);
INT_ASSERT(stmt->isPrimitive(PRIM_MOVE));
// makeNoop(stmt);
// result = stmt;
return result;
}
// Do not resolve runtime type values yet.
// Let these flow through to replaceInitPrims().
if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
return result;
SET_LINENO(call);
if (type->defaultValue ||
type->symbol->hasFlag(FLAG_TUPLE)) {
// Very special case for the method token.
// Unfortunately, dtAny cannot (currently) bind to dtMethodToken, so
// inline proc _defaultOf(type t) where t==_MT cannot be written in module
// code.
// Maybe it would be better to indicate which calls are method calls
// through the use of a flag. Until then, we just fake in the needed
// result and short-circuit the resolution of _defaultOf(type _MT).
if (type == dtMethodToken)
{
result = new SymExpr(gMethodToken);
call->replace(result);
return result;
}
}
if (type->defaultInitializer)
{
if (type->symbol->hasFlag(FLAG_ITERATOR_RECORD))
// defaultInitializers for iterator record types cannot be called as
// default constructors. So give up now!
return result;
}
CallExpr* defOfCall = new CallExpr("_defaultOf", type->symbol);
call->replace(defOfCall);
resolveCall(defOfCall);
resolveFns(defOfCall->isResolved());
result = postFold(defOfCall);
return result;
}
static Expr*
preFold(Expr* expr) {
Expr* result = expr;
if (CallExpr* call = toCallExpr(expr)) {
// Match calls that look like: (<type-symbol> <immediate-integer>)
// and replace them with: <new-type-symbol>
// <type-symbol> is in {dtBools, dtInt, dtUint, dtReal, dtImag, dtComplex}.
// This replaces, e.g. ( dtInt[INT_SIZE_DEFAULT] 32) with dtInt[INT_SIZE_32].
if (SymExpr* sym = toSymExpr(call->baseExpr)) {
if (TypeSymbol* type = toTypeSymbol(sym->var)) {
if (call->numActuals() == 1) {
if (SymExpr* arg = toSymExpr(call->get(1))) {
if (VarSymbol* var = toVarSymbol(arg->var)) {
if (var->immediate) {
if (NUM_KIND_INT == var->immediate->const_kind ||
NUM_KIND_UINT == var->immediate->const_kind) {
int size;
if (NUM_KIND_INT == var->immediate->const_kind) {
size = var->immediate->int_value();
} else {
size = (int)var->immediate->uint_value();
}
TypeSymbol* tsize = NULL;
if (type == dtBools[BOOL_SIZE_SYS]->symbol) {
switch (size) {
case 8: tsize = dtBools[BOOL_SIZE_8]->symbol; break;
case 16: tsize = dtBools[BOOL_SIZE_16]->symbol; break;
case 32: tsize = dtBools[BOOL_SIZE_32]->symbol; break;
case 64: tsize = dtBools[BOOL_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for bool", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtInt[INT_SIZE_DEFAULT]->symbol) {
switch (size) {
case 8: tsize = dtInt[INT_SIZE_8]->symbol; break;
case 16: tsize = dtInt[INT_SIZE_16]->symbol; break;
case 32: tsize = dtInt[INT_SIZE_32]->symbol; break;
case 64: tsize = dtInt[INT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for int", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtUInt[INT_SIZE_DEFAULT]->symbol) {
switch (size) {
case 8: tsize = dtUInt[INT_SIZE_8]->symbol; break;
case 16: tsize = dtUInt[INT_SIZE_16]->symbol; break;
case 32: tsize = dtUInt[INT_SIZE_32]->symbol; break;
case 64: tsize = dtUInt[INT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for uint", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtReal[FLOAT_SIZE_64]->symbol) {
switch (size) {
case 32: tsize = dtReal[FLOAT_SIZE_32]->symbol; break;
case 64: tsize = dtReal[FLOAT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for real", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtImag[FLOAT_SIZE_64]->symbol) {
switch (size) {
case 32: tsize = dtImag[FLOAT_SIZE_32]->symbol; break;
case 64: tsize = dtImag[FLOAT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for imag", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtComplex[COMPLEX_SIZE_128]->symbol) {
switch (size) {
case 64: tsize = dtComplex[COMPLEX_SIZE_64]->symbol; break;
case 128: tsize = dtComplex[COMPLEX_SIZE_128]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for complex", size);
}
result = new SymExpr(tsize);
call->replace(result);
}
}
}
}
}
}
}
}
if (SymExpr* sym = toSymExpr(call->baseExpr)) {
if (isLcnSymbol(sym->var)) {
Expr* base = call->baseExpr;
base->replace(new UnresolvedSymExpr("this"));
call->insertAtHead(base);
call->insertAtHead(gMethodToken);
}
}
if (CallExpr* base = toCallExpr(call->baseExpr)) {
if (base->partialTag) {
for_actuals_backward(actual, base) {
actual->remove();
call->insertAtHead(actual);
}
base->replace(base->baseExpr->remove());
} else {
VarSymbol* this_temp = newTemp("_this_tmp_");
this_temp->addFlag(FLAG_EXPR_TEMP);
base->replace(new UnresolvedSymExpr("this"));
CallExpr* move = new CallExpr(PRIM_MOVE, this_temp, base);
call->insertAtHead(new SymExpr(this_temp));
call->insertAtHead(gMethodToken);
call->getStmtExpr()->insertBefore(new DefExpr(this_temp));
call->getStmtExpr()->insertBefore(move);
result = move;
return result;
}
}
if (call->isNamed("this")) {
SymExpr* base = toSymExpr(call->get(2));
INT_ASSERT(base);
if (isVarSymbol(base->var) && base->var->hasFlag(FLAG_TYPE_VARIABLE)) {
if (call->numActuals() == 2)
USR_FATAL(call, "illegal call of type");
int64_t index;
if (!get_int(call->get(3), &index))
USR_FATAL(call, "illegal type index expression");
char field[8];
sprintf(field, "x%" PRId64, index);
result = new SymExpr(base->var->type->getField(field)->type->symbol);
call->replace(result);
} else if (base && isLcnSymbol(base->var)) {
//
// resolve tuple indexing by an integral parameter
//
Type* t = base->var->getValType();
if (t->symbol->hasFlag(FLAG_TUPLE))
if (Expr* expr = resolveTupleIndexing(call, base->var))
result = expr; // call was replaced by expr
}
}
else if (call->isPrimitive(PRIM_INIT))
{
if (Expr* expr = resolvePrimInit(call))
{
// call was replaced by expr.
result = expr;
}
// No default value yet, so defer resolution of this init
// primitive until record initializer resolution.
} else if (call->isPrimitive(PRIM_NO_INIT)) {
// Lydia note: fUseNoinit does not control this section. This was
// necessary because with the definition of type defaults in the module
// code, return temporary variables would cause an infinite loop by
// trying to default initialize within the default initialization
// definition. (It is safe for these temporaries to skip default
// initialization, as they will always be assigned a value before they
// are returned.) Thus noinit must remain attached to these temporaries,
// even if --no-use-noinit is thrown. This is an implementation detail
// that the user does not need to care about.
// fUseNoinit controls the insertion of PRIM_NO_INIT statements in the
// normalize pass.
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (!se->var->hasFlag(FLAG_TYPE_VARIABLE))
USR_FATAL(call, "invalid type specification");
Type* type = call->get(1)->getValType();
if (isAggregateType(type)) {
if (type->symbol->hasFlag(FLAG_IGNORE_NOINIT)) {
// These types deal with their uninitialized fields differently than
// normal records/classes. They may require special case
// implementations, but were capable of being isolated from the new
// cases that do work.
bool nowarn = false;
// In the case of temporary variables that use noinit (at this point
// only return variables), it is not useful to warn the user we are
// still default initializing the values as they weren't the ones to
// tell us to use noinit in the first place. So squash the warning
// in this case.
if (call->parentExpr) {
CallExpr* parent = toCallExpr(call->parentExpr);
if (parent && parent->isPrimitive(PRIM_MOVE)) {
// Should always be true, but just in case...
if (SymExpr* holdsDest = toSymExpr(parent->get(1))) {
Symbol* dest = holdsDest->var;
if (dest->hasFlag(FLAG_TEMP) && !strcmp(dest->name, "ret")) {
nowarn = true;
}
}
}
}
if (!nowarn)
USR_WARN("type %s does not currently support noinit, using default initialization", type->symbol->name);
result = new CallExpr(PRIM_INIT, call->get(1)->remove());
call->replace(result);
inits.add((CallExpr *)result);
} else {
result = call;
inits.add(call);
}
}
} else if (call->isPrimitive(PRIM_TYPEOF)) {
Type* type = call->get(1)->getValType();
if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
result = new CallExpr("chpl__convertValueToRuntimeType", call->get(1)->remove());
call->replace(result);
// If this call is inside a BLOCK_TYPE_ONLY, it will be removed and the
// runtime type will not be initialized. Unset this bit to fix.
//
// Assumption: The block we need to modify is either the parent or
// grandparent expression of the call.
BlockStmt* blk = NULL;
if ((blk = toBlockStmt(result->parentExpr))) {
// If the call's parent expression is a block, we assume it to
// be a scopeless type_only block.
INT_ASSERT(blk->blockTag & BLOCK_TYPE);
} else {
// The grandparent block doesn't necessarily have the BLOCK_TYPE_ONLY
// flag.
blk = toBlockStmt(result->parentExpr->parentExpr);
}
if (blk) {
(unsigned&)(blk->blockTag) &= ~(unsigned)BLOCK_TYPE_ONLY;
}
}
} else if (call->isPrimitive(PRIM_QUERY)) {
Symbol* field = determineQueriedField(call);
if (field && (field->hasFlag(FLAG_PARAM) || field->hasFlag(FLAG_TYPE_VARIABLE))) {
result = new CallExpr(field->name, gMethodToken, call->get(1)->remove());
call->replace(result);
} else if (isInstantiatedField(field)) {
VarSymbol* tmp = newTemp("_instantiated_field_tmp_");
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_TUPLE) && field->name[0] == 'x')
result = new CallExpr(PRIM_GET_MEMBER_VALUE, call->get(1)->remove(), new_StringSymbol(field->name));
else
result = new CallExpr(field->name, gMethodToken, call->get(1)->remove());
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, result));
call->replace(new CallExpr(PRIM_TYPEOF, tmp));
} else
USR_FATAL(call, "invalid query -- queried field must be a type or parameter");
} else if (call->isPrimitive(PRIM_CAPTURE_FN)) {
result = createFunctionAsValue(call);
call->replace(result);
} else if (call->isPrimitive(PRIM_CREATE_FN_TYPE)) {
AggregateType *parent = createOrFindFunTypeFromAnnotation(call->argList, call);
result = new SymExpr(parent->symbol);
call->replace(result);
} else if (call->isNamed("chpl__initCopy") ||
call->isNamed("chpl__autoCopy")) {
if (call->numActuals() == 1) {
if (SymExpr* symExpr = toSymExpr(call->get(1))) {
if (VarSymbol* var = toVarSymbol(symExpr->var)) {
if (var->immediate) {
result = new SymExpr(var);
call->replace(result);
}
} else {
if (EnumSymbol* var = toEnumSymbol(symExpr->var)) {
// Treat enum values as immediates
result = new SymExpr(var);
call->replace(result);
}
}
}
}
} else if (call->isNamed("_cast")) {
result = dropUnnecessaryCast(call);
if (result == call) {
// The cast was not dropped. Remove integer casts on immediate values.
if (SymExpr* sym = toSymExpr(call->get(2))) {
if (VarSymbol* var = toVarSymbol(sym->var)) {
if (var->immediate) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
Type* oldType = var->type;
Type* newType = sym->var->type;
if ((is_int_type(oldType) || is_uint_type(oldType) ||
is_bool_type(oldType)) &&
(is_int_type(newType) || is_uint_type(newType) ||
is_bool_type(newType) || is_enum_type(newType) ||
(newType == dtStringC))) {
VarSymbol* typevar = toVarSymbol(newType->defaultValue);
EnumType* typeenum = toEnumType(newType);
if (typevar) {
if (!typevar->immediate)
INT_FATAL("unexpected case in cast_fold");
Immediate coerce = *typevar->immediate;
coerce_immediate(var->immediate, &coerce);
result = new SymExpr(new_ImmediateSymbol(&coerce));
call->replace(result);
} else if (typeenum) {
int64_t value, count = 0;
bool replaced = false;
if (!get_int(call->get(2), &value)) {
INT_FATAL("unexpected case in cast_fold");
}
for_enums(constant, typeenum) {
if (!get_int(constant->init, &count)) {
count++;
}
if (count == value) {
result = new SymExpr(constant->sym);
call->replace(result);
replaced = true;
break;
}
}
if (!replaced) {
USR_FATAL(call->get(2), "enum cast out of bounds");
}
} else {
INT_FATAL("unexpected case in cast_fold");
}
}
}
}
} else if (EnumSymbol* enumSym = toEnumSymbol(sym->var)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
Type* newType = sym->var->type;
if (newType == dtStringC) {
result = new SymExpr(new_StringSymbol(enumSym->name));
call->replace(result);
}
}
}
}
}
} else if (call->isNamed("==")) {
if (isTypeExpr(call->get(1)) && isTypeExpr(call->get(2))) {
Type* lt = call->get(1)->getValType();
Type* rt = call->get(2)->getValType();
if (lt != dtUnknown && rt != dtUnknown &&
!lt->symbol->hasFlag(FLAG_GENERIC) &&
!rt->symbol->hasFlag(FLAG_GENERIC)) {
result = (lt == rt) ? new SymExpr(gTrue) : new SymExpr(gFalse);
call->replace(result);
}
}
} else if (call->isNamed("!=")) {
if (isTypeExpr(call->get(1)) && isTypeExpr(call->get(2))) {
Type* lt = call->get(1)->getValType();
Type* rt = call->get(2)->getValType();
if (lt != dtUnknown && rt != dtUnknown &&
!lt->symbol->hasFlag(FLAG_GENERIC) &&
!rt->symbol->hasFlag(FLAG_GENERIC)) {
result = (lt != rt) ? new SymExpr(gTrue) : new SymExpr(gFalse);
call->replace(result);
}
}
} else if (call->isNamed("_type_construct__tuple") && !call->isResolved()) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
if (VarSymbol* var = toVarSymbol(sym->var)) {
if (var->immediate) {
int rank = var->immediate->int_value();
if (rank != call->numActuals() - 1) {
if (call->numActuals() != 2)
INT_FATAL(call, "bad homogeneous tuple");
Expr* actual = call->get(2);
for (int i = 1; i < rank; i++) {
call->insertAtTail(actual->copy());
}
}
}
}
}
} else if (call->isPrimitive(PRIM_BLOCK_PARAM_LOOP)) {
ParamForLoop* paramLoop = toParamForLoop(call->parentExpr);
result = paramLoop->foldForResolve();
} else if (call->isPrimitive(PRIM_LOGICAL_FOLDER)) {
bool removed = false;
SymExpr* sym1 = toSymExpr(call->get(1));
if (VarSymbol* sym = toVarSymbol(sym1->var)) {
if (sym->immediate || paramMap.get(sym)) {
CallExpr* mvCall = toCallExpr(call->parentExpr);
SymExpr* sym = toSymExpr(mvCall->get(1));
VarSymbol* var = toVarSymbol(sym->var);
removed = true;
var->addFlag(FLAG_MAYBE_PARAM);
result = call->get(2)->remove();
call->replace(result);
}
}
if (!removed) {
result = call->get(2)->remove();
call->replace(result);
}
} else if (call->isPrimitive(PRIM_ADDR_OF)) {
// remove set ref if already a reference
if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) {
result = call->get(1)->remove();
call->replace(result);
} else {
// This test is turned off if we are in a wrapper function.
FnSymbol* fn = call->getFunction();
if (!fn->hasFlag(FLAG_WRAPPER)) {
SymExpr* lhs = NULL;
// check legal var function return
if (CallExpr* move = toCallExpr(call->parentExpr)) {
if (move->isPrimitive(PRIM_MOVE)) {
lhs = toSymExpr(move->get(1));
if (lhs && lhs->var == fn->getReturnSymbol()) {
SymExpr* ret = toSymExpr(call->get(1));
INT_ASSERT(ret);
if (ret->var->defPoint->getFunction() == move->getFunction() &&
!ret->var->type->symbol->hasFlag(FLAG_ITERATOR_RECORD) &&
!ret->var->type->symbol->hasFlag(FLAG_ARRAY))
// Should this conditional include domains, distributions, sync and/or single?
USR_FATAL(ret, "illegal expression to return by ref");
if (ret->var->isConstant() || ret->var->isParameter())
USR_FATAL(ret, "function cannot return constant by ref");
}
}
}
//
// check that the operand of 'addr of' is a legal lvalue.
if (SymExpr* rhs = toSymExpr(call->get(1))) {
if (!(lhs && lhs->var->hasFlag(FLAG_REF_VAR) && lhs->var->hasFlag(FLAG_CONST))) {
if (rhs->var->hasFlag(FLAG_EXPR_TEMP) || rhs->var->isConstant() || rhs->var->isParameter()) {
if (lhs && lhs->var->hasFlag(FLAG_REF_VAR)) {
if (rhs->var->isImmediate()) {
USR_FATAL_CONT(call, "Cannot set a non-const reference to a literal value.");
} else {
// We should not fall into this case... should be handled in normalize
INT_FATAL(call, "Cannot set a non-const reference to a const variable.");
}
} else {
// This probably indicates that an invalid 'addr of' primitive
// was inserted, which would be the compiler's fault, not the
// user's.
// At least, we might perform the check at or before the 'addr
// of' primitive is inserted.
INT_FATAL(call, "A non-lvalue appears where an lvalue is expected.");
}
}
}
}
}
}
} else if (call->isPrimitive(PRIM_DEREF)) {
// remove deref if arg is already a value
if (!call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) {
result = call->get(1)->remove();
call->replace(result);
}
} else if (call->isPrimitive(PRIM_TYPE_TO_STRING)) {
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se && se->var->hasFlag(FLAG_TYPE_VARIABLE));
result = new SymExpr(new_StringSymbol(se->var->type->symbol->name));
call->replace(result);
} else if (call->isPrimitive(PRIM_WIDE_GET_LOCALE) ||
call->isPrimitive(PRIM_WIDE_GET_NODE)) {
Type* type = call->get(1)->getValType();
//
// ensure .locale (and on) are applied to lvalues or classes
// (locale type is a class)
//
SymExpr* se = toSymExpr(call->get(1));
if (se->var->hasFlag(FLAG_EXPR_TEMP) && !isClass(type))
USR_WARN(se, "accessing the locale of a local expression");
//
// if .locale is applied to an expression of array, domain, or distribution
// wrapper type, apply .locale to the _value field of the
// wrapper
//
if (isRecordWrappedType(type)) {
VarSymbol* tmp = newTemp("_locale_tmp_");
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
result = new CallExpr("_value", gMethodToken, call->get(1)->remove());
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, result));
call->insertAtTail(tmp);
}
} else if (call->isPrimitive(PRIM_TO_STANDALONE)) {
FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer;
CallExpr* standaloneCall = new CallExpr(iterator->name);
for_formals(formal, iterator) {
standaloneCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal)));
}
// "tag" should be placed at the end of the formals in the source code as
// well, to avoid insertion of an order wrapper.
standaloneCall->insertAtTail(new NamedExpr("tag", new SymExpr(gStandaloneTag)));
call->replace(standaloneCall);
result = standaloneCall;
} else if (call->isPrimitive(PRIM_TO_LEADER)) {
FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer;
CallExpr* leaderCall;
if (FnSymbol* leader = iteratorLeaderMap.get(iterator))
leaderCall = new CallExpr(leader);
else
leaderCall = new CallExpr(iterator->name);
for_formals(formal, iterator) {
leaderCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal)));
}
// "tag" should be placed at the end of the formals in the source code as
// well, to avoid insertion of an order wrapper.
leaderCall->insertAtTail(new NamedExpr("tag", new SymExpr(gLeaderTag)));
call->replace(leaderCall);
result = leaderCall;
} else if (call->isPrimitive(PRIM_TO_FOLLOWER)) {
FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer;
CallExpr* followerCall;
if (FnSymbol* follower = iteratorFollowerMap.get(iterator))
followerCall = new CallExpr(follower);
else
followerCall = new CallExpr(iterator->name);
for_formals(formal, iterator) {
followerCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal)));
}
// "tag", "followThis" and optionally "fast" should be placed at the end
// of the formals in the source code as well, to avoid insertion of an
// order wrapper.
followerCall->insertAtTail(new NamedExpr("tag", new SymExpr(gFollowerTag)));
followerCall->insertAtTail(new NamedExpr(iterFollowthisArgname, call->get(2)->remove()));
if (call->numActuals() > 1) {
followerCall->insertAtTail(new NamedExpr("fast", call->get(2)->remove()));
}
call->replace(followerCall);
result = followerCall;
} else if (call->isPrimitive(PRIM_NUM_FIELDS)) {
AggregateType* classtype = toAggregateType(toSymExpr(call->get(1))->var->type);
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
}
result = new SymExpr(new_IntSymbol(fieldcount));
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_NUM_TO_NAME)) {
AggregateType* classtype = toAggregateType(toSymExpr(call->get(1))->var->type);
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
int fieldnum = var->immediate->int_value();
int fieldcount = 0;
const char* name = NULL;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if (fieldcount == fieldnum) {
name = field->name;
}
}
if (!name) {
// In this case, we ran out of fields without finding the number
// specified. This is the user's error.
USR_FATAL(call, "'%d' is not a valid field number", fieldnum);
}
result = new SymExpr(new_StringSymbol(name));
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_VALUE_BY_NUM)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
int fieldnum = var->immediate->int_value();
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if (fieldcount == fieldnum) {
result = new CallExpr(PRIM_GET_MEMBER, call->get(1)->copy(),
new_StringSymbol(field->name));
break;
}
}
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_ID_BY_NUM)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
int fieldnum = var->immediate->int_value();
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if (fieldcount == fieldnum) {
result = new SymExpr(new_IntSymbol(field->id));
break;
}
}
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_VALUE_BY_NAME)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
Immediate* imm = var->immediate;
INT_ASSERT( classtype != NULL );
// fail horribly if immediate is not a string .
INT_ASSERT(imm->const_kind == CONST_KIND_STRING);
const char* fieldname = imm->v_string;
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if ( 0 == strcmp(field->name, fieldname) ) {
result = new CallExpr(PRIM_GET_MEMBER, call->get(1)->copy(),
new_StringSymbol(field->name));
break;
}
}
call->replace(result);
} else if (call->isPrimitive(PRIM_ENUM_MIN_BITS) || call->isPrimitive(PRIM_ENUM_IS_SIGNED)) {
EnumType* et = toEnumType(toSymExpr(call->get(1))->var->type);
ensureEnumTypeResolved(et);
result = NULL;
if( call->isPrimitive(PRIM_ENUM_MIN_BITS) ) {
result = new SymExpr(new_IntSymbol(get_width(et->integerType)));
} else if( call->isPrimitive(PRIM_ENUM_IS_SIGNED) ) {
if( is_int_type(et->integerType) )
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
}
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_UNION_TYPE)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
if( isUnion(classtype) )
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_ATOMIC_TYPE)) {
if (isAtomicType(call->get(1)->typeInfo()))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_SYNC_TYPE)) {
Type* syncType = call->get(1)->typeInfo();
if (syncType->symbol->hasFlag(FLAG_SYNC))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_SINGLE_TYPE)) {
Type* singleType = call->get(1)->typeInfo();
if (singleType->symbol->hasFlag(FLAG_SINGLE))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_TUPLE_TYPE)) {
Type* tupleType = call->get(1)->typeInfo();
if (tupleType->symbol->hasFlag(FLAG_TUPLE))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_STAR_TUPLE_TYPE)) {
Type* tupleType = call->get(1)->typeInfo();
INT_ASSERT(tupleType->symbol->hasFlag(FLAG_TUPLE));
if (tupleType->symbol->hasFlag(FLAG_STAR_TUPLE))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
}
}
//
// ensure result of pre-folding is in the AST
//
INT_ASSERT(result->parentSymbol);
return result;
}
static void foldEnumOp(int op, EnumSymbol *e1, EnumSymbol *e2, Immediate *imm) {
int64_t val1 = -1, val2 = -1, count = 0;
// ^^^ This is an assumption that "long" on the compiler host is at
// least as big as "int" on the target. This is not guaranteed to be true.
EnumType *type1, *type2;
type1 = toEnumType(e1->type);
type2 = toEnumType(e2->type);
INT_ASSERT(type1 && type2);
// Loop over the enum values to find the int value of e1
for_enums(constant, type1) {
if (!get_int(constant->init, &count)) {
count++;
}
if (constant->sym == e1) {
val1 = count;
break;
}
}
// Loop over the enum values to find the int value of e2
count = 0;
for_enums(constant, type2) {
if (!get_int(constant->init, &count)) {
count++;
}
if (constant->sym == e2) {
val2 = count;
break;
}
}
// All operators on enum types result in a bool
imm->const_kind = NUM_KIND_BOOL;
imm->num_index = BOOL_SIZE_SYS;
switch (op) {
default: INT_FATAL("fold constant op not supported"); break;
case P_prim_equal:
imm->v_bool = val1 == val2;
break;
case P_prim_notequal:
imm->v_bool = val1 != val2;
break;
case P_prim_less:
imm->v_bool = val1 < val2;
break;
case P_prim_lessorequal:
imm->v_bool = val1 <= val2;
break;
case P_prim_greater:
imm->v_bool = val1 > val2;
break;
case P_prim_greaterorequal:
imm->v_bool = val1 >= val2;
break;
}
}
#define FOLD_CALL1(prim) \
if (SymExpr* sym = toSymExpr(call->get(1))) { \
if (VarSymbol* lhs = toVarSymbol(sym->var)) { \
if (lhs->immediate) { \
Immediate i3; \
fold_constant(prim, lhs->immediate, NULL, &i3); \
result = new SymExpr(new_ImmediateSymbol(&i3)); \
call->replace(result); \
} \
} \
}
#define FOLD_CALL2(prim) \
if (SymExpr* sym = toSymExpr(call->get(1))) { \
if (VarSymbol* lhs = toVarSymbol(sym->var)) { \
if (lhs->immediate) { \
if (SymExpr* sym = toSymExpr(call->get(2))) { \
if (VarSymbol* rhs = toVarSymbol(sym->var)) { \
if (rhs->immediate) { \
Immediate i3; \
fold_constant(prim, lhs->immediate, rhs->immediate, &i3); \
result = new SymExpr(new_ImmediateSymbol(&i3)); \
call->replace(result); \
} \
} \
} \
} \
} else if (EnumSymbol* lhs = toEnumSymbol(sym->var)) { \
if (SymExpr* sym = toSymExpr(call->get(2))) { \
if (EnumSymbol* rhs = toEnumSymbol(sym->var)) { \
Immediate imm; \
foldEnumOp(prim, lhs, rhs, &imm); \
result = new SymExpr(new_ImmediateSymbol(&imm)); \
call->replace(result); \
} \
} \
} \
}
static bool
isSubType(Type* sub, Type* super) {
if (sub == super)
return true;
forv_Vec(Type, parent, sub->dispatchParents) {
if (isSubType(parent, super))
return true;
}
return false;
}
static void
insertValueTemp(Expr* insertPoint, Expr* actual) {
if (SymExpr* se = toSymExpr(actual)) {
if (!se->var->type->refType) {
VarSymbol* tmp = newTemp("_value_tmp_", se->var->getValType());
insertPoint->insertBefore(new DefExpr(tmp));
insertPoint->insertBefore(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_DEREF, se->var)));
se->var = tmp;
}
}
}
//
// returns resolved function if the function requires an implicit
// destroy of its returned value (i.e. reference count)
//
// Currently, FLAG_DONOR_FN is only relevant when placed on
// chpl__autoCopy().
//
FnSymbol*
requiresImplicitDestroy(CallExpr* call) {
if (FnSymbol* fn = call->isResolved()) {
FnSymbol* parent = call->getFunction();
INT_ASSERT(parent);
if (!parent->hasFlag(FLAG_DONOR_FN) &&
// No autocopy/destroy calls in a donor function (this might
// need to change when this flag is used more generally)).
// Currently, this assumes we have thoughtfully written
// chpl__autoCopy functions.
// Return type is a record (which includes array, record, and
// dist) or a ref counted type that is passed by reference
(isRecord(fn->retType) ||
(fn->retType->symbol->hasFlag(FLAG_REF) &&
isRefCountedType(fn->retType->getValType()))) &&
// These are special functions where we don't want to destroy
// the result
!fn->hasFlag(FLAG_NO_IMPLICIT_COPY) &&
!fn->isIterator() &&
!fn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE) &&
!fn->hasFlag(FLAG_DONOR_FN) &&
!fn->hasFlag(FLAG_INIT_COPY_FN) &&
strcmp(fn->name, "=") &&
strcmp(fn->name, "_defaultOf") &&
!fn->hasFlag(FLAG_AUTO_II) &&
!fn->hasFlag(FLAG_CONSTRUCTOR) &&
!fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
return fn;
}
}
return NULL;
}
static Expr*
postFold(Expr* expr) {
Expr* result = expr;
if (!expr->parentSymbol)
return result;
SET_LINENO(expr);
if (CallExpr* call = toCallExpr(expr)) {
if (FnSymbol* fn = call->isResolved()) {
if (fn->retTag == RET_PARAM || fn->hasFlag(FLAG_MAYBE_PARAM)) {
VarSymbol* ret = toVarSymbol(fn->getReturnSymbol());
if (ret && ret->immediate) {
result = new SymExpr(ret);
expr->replace(result);
} else if (EnumSymbol* es = toEnumSymbol(fn->getReturnSymbol())) {
result = new SymExpr(es);
expr->replace(result);
} else if (fn->retTag == RET_PARAM) {
USR_FATAL(call, "param function does not resolve to a param symbol");
}
}
if (fn->hasFlag(FLAG_MAYBE_TYPE) && fn->getReturnSymbol()->hasFlag(FLAG_TYPE_VARIABLE))
fn->retTag = RET_TYPE;
if (fn->retTag == RET_TYPE) {
Symbol* ret = fn->getReturnSymbol();
if (!ret->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
result = new SymExpr(ret->type->symbol);
expr->replace(result);
}
}
} else if (call->isPrimitive(PRIM_QUERY_TYPE_FIELD) ||
call->isPrimitive(PRIM_QUERY_PARAM_FIELD)) {
SymExpr* classWrap = toSymExpr(call->get(1));
// Really should be a symExpr
INT_ASSERT(classWrap);
AggregateType* ct = toAggregateType(classWrap->var->type);
if (!ct) {
USR_FATAL(call, "Attempted to obtain field of a type that was not a record or class");
}
const char* memberName = get_string(call->get(2));
// Finds the field matching the specified name.
Vec<Symbol *> keys;
ct->substitutions.get_keys(keys);
forv_Vec(Symbol, key, keys) {
if (!strcmp(memberName, key->name)) {
// If there is a substitution for it, replace this call with that
// substitution
if (Symbol* value = ct->substitutions.get(key)) {
result = new SymExpr(value);
expr->replace(result);
}
}
}
}
// param initialization should not involve PRIM_ASSIGN or "=".
else if (call->isPrimitive(PRIM_MOVE)) {
bool set = false;
if (SymExpr* lhs = toSymExpr(call->get(1))) {
if (lhs->var->hasFlag(FLAG_MAYBE_PARAM) || lhs->var->isParameter()) {
if (paramMap.get(lhs->var))
INT_FATAL(call, "parameter set multiple times");
VarSymbol* lhsVar = toVarSymbol(lhs->var);
// We are expecting the LHS to be a var (what else could it be?
if (lhsVar->immediate) {
// The value of the LHS of this move has already been
// established, most likely through a construct like
// if (cond) return x;
// return y;
// In this case, the first 'true' conditional that hits a return
// can fast-forward to the end of the routine, and some
// resolution time can be saved.
// Re-enable the fatal error to catch this case; the correct
// solution is to ensure that the containing expression is never
// resolved, using the abbreviated resolution suggested above.
// INT_ASSERT(!lhsVar->immediate);
set = true; // That is, set previously.
} else {
if (SymExpr* rhs = toSymExpr(call->get(2))) {
if (VarSymbol* rhsVar = toVarSymbol(rhs->var)) {
if (rhsVar->immediate) {
paramMap.put(lhs->var, rhsVar);
lhs->var->defPoint->remove();
makeNoop(call);
set = true;
}
}
if (EnumSymbol* rhsv = toEnumSymbol(rhs->var)) {
paramMap.put(lhs->var, rhsv);
lhs->var->defPoint->remove();
makeNoop(call);
set = true;
}
}
}
if (!set && lhs->var->isParameter())
USR_FATAL(call, "Initializing parameter '%s' to value not known at compile time", lhs->var->name);
}
if (!set) {
if (lhs->var->hasFlag(FLAG_MAYBE_TYPE)) {
// Add FLAG_TYPE_VARIABLE when relevant
if (SymExpr* rhs = toSymExpr(call->get(2))) {
if (rhs->var->hasFlag(FLAG_TYPE_VARIABLE))
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
} else if (CallExpr* rhs = toCallExpr(call->get(2))) {
if (FnSymbol* fn = rhs->isResolved()) {
if (fn->retTag == RET_TYPE)
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
} else if (rhs->isPrimitive(PRIM_DEREF)) {
if (isTypeExpr(rhs->get(1)))
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
}
}
}
if (CallExpr* rhs = toCallExpr(call->get(2))) {
if (rhs->isPrimitive(PRIM_TYPEOF)) {
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
}
if (FnSymbol* fn = rhs->isResolved()) {
if (!strcmp(fn->name, "=") && fn->retType == dtVoid) {
call->replace(rhs->remove());
result = rhs;
set = true;
}
}
}
}
if (!set) {
if (lhs->var->hasFlag(FLAG_EXPR_TEMP) &&
!lhs->var->hasFlag(FLAG_TYPE_VARIABLE)) {
if (CallExpr* rhsCall = toCallExpr(call->get(2))) {
if (requiresImplicitDestroy(rhsCall)) {
lhs->var->addFlag(FLAG_INSERT_AUTO_COPY);
lhs->var->addFlag(FLAG_INSERT_AUTO_DESTROY);
}
}
}
if (isReferenceType(lhs->var->type) ||
lhs->var->type->symbol->hasFlag(FLAG_REF_ITERATOR_CLASS) ||
lhs->var->type->symbol->hasFlag(FLAG_ARRAY))
// Should this conditional include domains, distributions, sync and/or single?
lhs->var->removeFlag(FLAG_EXPR_TEMP);
}
if (!set) {
if (CallExpr* rhs = toCallExpr(call->get(2))) {
if (rhs->isPrimitive(PRIM_NO_INIT)) {
// If the lhs is a primitive, then we can safely just remove this
// value. Otherwise the type needs to be resolved a little
// further and so this statement can't be removed until
// resolveRecordInitializers
if (!isAggregateType(rhs->get(1)->getValType())) {
makeNoop(call);
}
}
}
}
}
} else if (call->isPrimitive(PRIM_GET_MEMBER)) {
Type* baseType = call->get(1)->getValType();
const char* memberName = get_string(call->get(2));
Symbol* sym = baseType->getField(memberName);
SymExpr* left = toSymExpr(call->get(1));
if (left && left->var->hasFlag(FLAG_TYPE_VARIABLE)) {
result = new SymExpr(sym->type->symbol);
call->replace(result);
} else if (sym->isParameter()) {
Vec<Symbol*> keys;
baseType->substitutions.get_keys(keys);
forv_Vec(Symbol, key, keys) {
if (!strcmp(sym->name, key->name)) {
if (Symbol* value = baseType->substitutions.get(key)) {
result = new SymExpr(value);
call->replace(result);
}
}
}
}
} else if (call->isPrimitive(PRIM_IS_SUBTYPE)) {
if (isTypeExpr(call->get(1)) || isTypeExpr(call->get(2))) {
Type* lt = call->get(2)->getValType(); // a:t cast is cast(t,a)
Type* rt = call->get(1)->getValType();
if (lt != dtUnknown && rt != dtUnknown && lt != dtAny &&
rt != dtAny && !lt->symbol->hasFlag(FLAG_GENERIC)) {
bool is_true = false;
if (lt->instantiatedFrom == rt)
is_true = true;
if (isSubType(lt, rt))
is_true = true;
result = (is_true) ? new SymExpr(gTrue) : new SymExpr(gFalse);
call->replace(result);
}
}
} else if (call->isPrimitive(PRIM_CAST)) {
Type* t= call->get(1)->typeInfo();
if (t == dtUnknown)
INT_FATAL(call, "Unable to resolve type");
call->get(1)->replace(new SymExpr(t->symbol));
} else if (call->isPrimitive("string_compare")) {
SymExpr* lhs = toSymExpr(call->get(1));
SymExpr* rhs = toSymExpr(call->get(2));
INT_ASSERT(lhs && rhs);
if (lhs->var->isParameter() && rhs->var->isParameter()) {
const char* lstr = get_string(lhs);
const char* rstr = get_string(rhs);
int comparison = strcmp(lstr, rstr);
result = new SymExpr(new_IntSymbol(comparison));
call->replace(result);
}
} else if (call->isPrimitive("string_concat")) {
SymExpr* lhs = toSymExpr(call->get(1));
SymExpr* rhs = toSymExpr(call->get(2));
INT_ASSERT(lhs && rhs);
if (lhs->var->isParameter() && rhs->var->isParameter()) {
const char* lstr = get_string(lhs);
const char* rstr = get_string(rhs);
result = new SymExpr(new_StringSymbol(astr(lstr, rstr)));
call->replace(result);
}
} else if (call->isPrimitive("string_length")) {
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (se->var->isParameter()) {
const char* str = get_string(se);
result = new SymExpr(new_IntSymbol(strlen(str), INT_SIZE_DEFAULT));
call->replace(result);
}
} else if (call->isPrimitive("ascii")) {
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (se->var->isParameter()) {
const char* str = get_string(se);
result = new SymExpr(new_IntSymbol((int)str[0], INT_SIZE_DEFAULT));
call->replace(result);
}
} else if (call->isPrimitive("string_contains")) {
SymExpr* lhs = toSymExpr(call->get(1));
SymExpr* rhs = toSymExpr(call->get(2));
INT_ASSERT(lhs && rhs);
if (lhs->var->isParameter() && rhs->var->isParameter()) {
const char* lstr = get_string(lhs);
const char* rstr = get_string(rhs);
result = new SymExpr(strstr(lstr, rstr) ? gTrue : gFalse);
call->replace(result);
}
} else if (call->isPrimitive(PRIM_UNARY_MINUS)) {
FOLD_CALL1(P_prim_minus);
} else if (call->isPrimitive(PRIM_UNARY_PLUS)) {
FOLD_CALL1(P_prim_plus);
} else if (call->isPrimitive(PRIM_UNARY_NOT)) {
FOLD_CALL1(P_prim_not);
} else if (call->isPrimitive(PRIM_UNARY_LNOT)) {
FOLD_CALL1(P_prim_lnot);
} else if (call->isPrimitive(PRIM_ADD)) {
FOLD_CALL2(P_prim_add);
} else if (call->isPrimitive(PRIM_SUBTRACT)) {
FOLD_CALL2(P_prim_subtract);
} else if (call->isPrimitive(PRIM_MULT)) {
FOLD_CALL2(P_prim_mult);
} else if (call->isPrimitive(PRIM_DIV)) {
FOLD_CALL2(P_prim_div);
} else if (call->isPrimitive(PRIM_MOD)) {
FOLD_CALL2(P_prim_mod);
} else if (call->isPrimitive(PRIM_EQUAL)) {
FOLD_CALL2(P_prim_equal);
} else if (call->isPrimitive(PRIM_NOTEQUAL)) {
FOLD_CALL2(P_prim_notequal);
} else if (call->isPrimitive(PRIM_LESSOREQUAL)) {
FOLD_CALL2(P_prim_lessorequal);
} else if (call->isPrimitive(PRIM_GREATEROREQUAL)) {
FOLD_CALL2(P_prim_greaterorequal);
} else if (call->isPrimitive(PRIM_LESS)) {
FOLD_CALL2(P_prim_less);
} else if (call->isPrimitive(PRIM_GREATER)) {
FOLD_CALL2(P_prim_greater);
} else if (call->isPrimitive(PRIM_AND)) {
FOLD_CALL2(P_prim_and);
} else if (call->isPrimitive(PRIM_OR)) {
FOLD_CALL2(P_prim_or);
} else if (call->isPrimitive(PRIM_XOR)) {
FOLD_CALL2(P_prim_xor);
} else if (call->isPrimitive(PRIM_POW)) {
FOLD_CALL2(P_prim_pow);
} else if (call->isPrimitive(PRIM_LSH)) {
FOLD_CALL2(P_prim_lsh);
} else if (call->isPrimitive(PRIM_RSH)) {
FOLD_CALL2(P_prim_rsh);
} else if (call->isPrimitive(PRIM_ARRAY_ALLOC) ||
call->isPrimitive(PRIM_SYNC_INIT) ||
call->isPrimitive(PRIM_SYNC_LOCK) ||
call->isPrimitive(PRIM_SYNC_UNLOCK) ||
call->isPrimitive(PRIM_SYNC_WAIT_FULL) ||
call->isPrimitive(PRIM_SYNC_WAIT_EMPTY) ||
call->isPrimitive(PRIM_SYNC_SIGNAL_FULL) ||
call->isPrimitive(PRIM_SYNC_SIGNAL_EMPTY) ||
call->isPrimitive(PRIM_SINGLE_INIT) ||
call->isPrimitive(PRIM_SINGLE_LOCK) ||
call->isPrimitive(PRIM_SINGLE_UNLOCK) ||
call->isPrimitive(PRIM_SINGLE_WAIT_FULL) ||
call->isPrimitive(PRIM_SINGLE_SIGNAL_FULL) ||
call->isPrimitive(PRIM_WRITEEF) ||
call->isPrimitive(PRIM_WRITEFF) ||
call->isPrimitive(PRIM_WRITEXF) ||
call->isPrimitive(PRIM_READFF) ||
call->isPrimitive(PRIM_READFE) ||
call->isPrimitive(PRIM_READXX) ||
call->isPrimitive(PRIM_SYNC_IS_FULL) ||
call->isPrimitive(PRIM_SINGLE_WRITEEF) ||
call->isPrimitive(PRIM_SINGLE_READFF) ||
call->isPrimitive(PRIM_SINGLE_READXX) ||
call->isPrimitive(PRIM_SINGLE_IS_FULL) ||
call->isPrimitive(PRIM_EXECUTE_TASKS_IN_LIST) ||
call->isPrimitive(PRIM_FREE_TASK_LIST) ||
(call->primitive &&
(!strncmp("_fscan", call->primitive->name, 6) ||
!strcmp("_readToEndOfLine", call->primitive->name) ||
!strcmp("_now_timer", call->primitive->name)))) {
//
// these primitives require temps to dereference actuals
// why not do this to all primitives?
//
for_actuals(actual, call) {
insertValueTemp(call->getStmtExpr(), actual);
}
}
} else if (SymExpr* sym = toSymExpr(expr)) {
if (Symbol* val = paramMap.get(sym->var)) {
CallExpr* call = toCallExpr(sym->parentExpr);
if (call && call->get(1) == sym) {
// This is a place where param substitution has already determined the
// value of a move or assignment, so we can just ignore the update.
if (call->isPrimitive(PRIM_MOVE)) {
makeNoop(call);
return result;
}
// The substitution usually happens before resolution, so for
// assignment, we key off of the name :-(
if (call->isNamed("="))
{
makeNoop(call);
return result;
}
}
if (sym->var->type != dtUnknown && sym->var->type != val->type) {
CallExpr* cast = new CallExpr("_cast", sym->var, val);
sym->replace(cast);
result = preFold(cast);
} else {
sym->var = val;
}
}
}
if (CondStmt* cond = toCondStmt(result->parentExpr)) {
if (cond->condExpr == result) {
if (Expr* expr = cond->foldConstantCondition()) {
result = expr;
} else {
//
// push try block
//
if (SymExpr* se = toSymExpr(result))
if (se->var == gTryToken)
tryStack.add(cond);
}
}
}
//
// pop try block and delete else
//
if (tryStack.n) {
if (BlockStmt* block = toBlockStmt(result)) {
if (tryStack.tail()->thenStmt == block) {
tryStack.tail()->replace(block->remove());
tryStack.pop();
}
}
}
return result;
}
static bool is_param_resolved(FnSymbol* fn, Expr* expr) {
if (BlockStmt* block = toBlockStmt(expr)) {
if (block->isWhileStmt() == true) {
USR_FATAL(expr, "param function cannot contain a non-param while loop");
} else if (block->isForLoop() == true) {
USR_FATAL(expr, "param function cannot contain a non-param for loop");
} else if (block->isLoopStmt() == true) {
USR_FATAL(expr, "param function cannot contain a non-param loop");
}
}
if (BlockStmt* block = toBlockStmt(expr->parentExpr)) {
if (isCondStmt(block->parentExpr)) {
USR_FATAL(block->parentExpr,
"param function cannot contain a non-param conditional");
}
}
if (paramMap.get(fn->getReturnSymbol())) {
CallExpr* call = toCallExpr(fn->body->body.tail);
INT_ASSERT(call);
INT_ASSERT(call->isPrimitive(PRIM_RETURN));
call->get(1)->replace(new SymExpr(paramMap.get(fn->getReturnSymbol())));
return true; // param function is resolved
}
return false;
}
// Resolves an expression and manages the callStack and tryStack.
// On success, returns the call that was passed in.
// On a try failure, returns either the expression preceding the elseStmt,
// substituted for the body of the param condition (if that substitution could
// be made), or NULL.
// If null, then resolution of the current block should be aborted. tryFailure
// is true in this case, so the search for a matching elseStmt continue in the
// surrounding block or call.
static Expr*
resolveExpr(Expr* expr) {
Expr* const origExpr = expr;
FnSymbol* fn = toFnSymbol(expr->parentSymbol);
SET_LINENO(expr);
if (SymExpr* se = toSymExpr(expr)) {
if (se->var) {
makeRefType(se->var->type);
}
}
expr = preFold(expr);
if (fn && fn->retTag == RET_PARAM) {
if (is_param_resolved(fn, expr)) {
return expr;
}
}
if (DefExpr* def = toDefExpr(expr)) {
if (def->init) {
Expr* init = preFold(def->init);
init = resolveExpr(init);
// expr is unchanged, so is treated as "resolved".
}
if (def->sym->hasFlag(FLAG_CHPL__ITER)) {
implementForallIntents1(def);
}
}
if (CallExpr* call = toCallExpr(expr)) {
if (call->isPrimitive(PRIM_ERROR) ||
call->isPrimitive(PRIM_WARNING)) {
issueCompilerError(call);
}
// Resolve expressions of the form: <type> ( args )
// These will be constructor calls (or type constructor calls) that slipped
// past normalization due to the use of typedefs.
if (SymExpr* se = toSymExpr(call->baseExpr)) {
if (TypeSymbol* ts = toTypeSymbol(se->var)) {
if (call->numActuals() == 0 ||
(call->numActuals() == 2 && isSymExpr(call->get(1)) &&
toSymExpr(call->get(1))->var == gMethodToken)) {
// This looks like a typedef, so ignore it.
} else {
// More needed here ... .
INT_FATAL(ts, "not yet implemented.");
}
}
}
callStack.add(call);
resolveCall(call);
if (!tryFailure && call->isResolved()) {
if (CallExpr* origToLeaderCall = toPrimToLeaderCall(origExpr))
// ForallLeaderArgs: process the leader that 'call' invokes.
implementForallIntents2(call, origToLeaderCall);
resolveFns(call->isResolved());
}
if (tryFailure) {
if (tryStack.tail()->parentSymbol == fn) {
// The code in the 'true' branch of a tryToken conditional has failed
// to resolve fully. Roll the callStack back to the function where
// the nearest tryToken conditional is and replace the entire
// conditional with the 'false' branch then continue resolution on
// it. If the 'true' branch did fully resolve, we would replace the
// conditional with the 'true' branch instead.
while (callStack.n > 0 &&
callStack.tail()->isResolved() !=
tryStack.tail()->elseStmt->parentSymbol) {
callStack.pop();
}
BlockStmt* block = tryStack.tail()->elseStmt;
tryStack.tail()->replace(block->remove());
tryStack.pop();
if (!block->prev)
block->insertBefore(new CallExpr(PRIM_NOOP));
return block->prev;
} else {
return NULL;
}
}
callStack.pop();
}
if (SymExpr* sym = toSymExpr(expr)) {
// Avoid record constructors via cast
// should be fixed by out-of-order resolution
CallExpr* parent = toCallExpr(sym->parentExpr);
if (!parent ||
!parent->isPrimitive(PRIM_IS_SUBTYPE) ||
!sym->var->hasFlag(FLAG_TYPE_VARIABLE)) {
if (AggregateType* ct = toAggregateType(sym->typeInfo())) {
if (!ct->symbol->hasFlag(FLAG_GENERIC) &&
!ct->symbol->hasFlag(FLAG_ITERATOR_CLASS) &&
!ct->symbol->hasFlag(FLAG_ITERATOR_RECORD)) {
resolveFormals(ct->defaultTypeConstructor);
if (resolvedFormals.set_in(ct->defaultTypeConstructor)) {
if (ct->defaultTypeConstructor->hasFlag(FLAG_PARTIAL_COPY))
instantiateBody(ct->defaultTypeConstructor);
resolveFns(ct->defaultTypeConstructor);
}
}
}
}
}
return postFold(expr);
}
void
resolveBlockStmt(BlockStmt* blockStmt) {
for_exprs_postorder(expr, blockStmt) {
expr = resolveExpr(expr);
if (tryFailure) {
if (expr == NULL)
return;
tryFailure = false;
}
}
}
static void
computeReturnTypeParamVectors(BaseAST* ast,
Symbol* retSymbol,
Vec<Type*>& retTypes,
Vec<Symbol*>& retParams) {
if (CallExpr* call = toCallExpr(ast)) {
if (call->isPrimitive(PRIM_MOVE)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
if (sym->var == retSymbol) {
if (SymExpr* sym = toSymExpr(call->get(2)))
retParams.add(sym->var);
else
retParams.add(NULL);
retTypes.add(call->get(2)->typeInfo());
}
}
}
}
AST_CHILDREN_CALL(ast, computeReturnTypeParamVectors, retSymbol, retTypes, retParams);
}
static void
replaceSetterArgWithTrue(BaseAST* ast, FnSymbol* fn) {
if (SymExpr* se = toSymExpr(ast)) {
if (se->var == fn->setter->sym) {
se->var = gTrue;
if (fn->isIterator())
USR_WARN(fn, "setter argument is not supported in iterators");
}
}
AST_CHILDREN_CALL(ast, replaceSetterArgWithTrue, fn);
}
static void
replaceSetterArgWithFalse(BaseAST* ast, FnSymbol* fn, Symbol* ret) {
if (SymExpr* se = toSymExpr(ast)) {
if (se->var == fn->setter->sym)
se->var = gFalse;
else if (se->var == ret) {
if (CallExpr* move = toCallExpr(se->parentExpr))
if (move->isPrimitive(PRIM_MOVE))
if (CallExpr* call = toCallExpr(move->get(2)))
if (call->isPrimitive(PRIM_ADDR_OF))
call->primitive = primitives[PRIM_DEREF];
}
}
AST_CHILDREN_CALL(ast, replaceSetterArgWithFalse, fn, ret);
}
static void
insertCasts(BaseAST* ast, FnSymbol* fn, Vec<CallExpr*>& casts) {
if (CallExpr* call = toCallExpr(ast)) {
if (call->parentSymbol == fn) {
if (call->isPrimitive(PRIM_MOVE)) {
if (SymExpr* lhs = toSymExpr(call->get(1))) {
Type* lhsType = lhs->var->type;
if (lhsType != dtUnknown) {
Expr* rhs = call->get(2);
Type* rhsType = rhs->typeInfo();
if (rhsType != lhsType &&
rhsType->refType != lhsType &&
rhsType != lhsType->refType) {
SET_LINENO(rhs);
rhs->remove();
Symbol* tmp = NULL;
if (SymExpr* se = toSymExpr(rhs)) {
tmp = se->var;
} else {
tmp = newTemp("_cast_tmp_", rhs->typeInfo());
call->insertBefore(new DefExpr(tmp));
call->insertBefore(new CallExpr(PRIM_MOVE, tmp, rhs));
}
CallExpr* cast = new CallExpr("_cast", lhsType->symbol, tmp);
call->insertAtTail(cast);
casts.add(cast);
}
}
}
}
}
}
AST_CHILDREN_CALL(ast, insertCasts, fn, casts);
}
static void instantiate_default_constructor(FnSymbol* fn) {
//
// instantiate initializer
//
if (fn->instantiatedFrom) {
INT_ASSERT(!fn->retType->defaultInitializer);
FnSymbol* instantiatedFrom = fn->instantiatedFrom;
while (instantiatedFrom->instantiatedFrom)
instantiatedFrom = instantiatedFrom->instantiatedFrom;
CallExpr* call = new CallExpr(instantiatedFrom->retType->defaultInitializer);
for_formals(formal, fn) {
if (formal->type == dtMethodToken || formal == fn->_this) {
call->insertAtTail(formal);
} else if (paramMap.get(formal)) {
call->insertAtTail(new NamedExpr(formal->name, new SymExpr(paramMap.get(formal))));
} else {
Symbol* field = fn->retType->getField(formal->name);
if (instantiatedFrom->hasFlag(FLAG_TUPLE)) {
call->insertAtTail(field);
} else {
call->insertAtTail(new NamedExpr(formal->name, new SymExpr(field)));
}
}
}
fn->insertBeforeReturn(call);
resolveCall(call);
fn->retType->defaultInitializer = call->isResolved();
INT_ASSERT(fn->retType->defaultInitializer);
// resolveFns(fn->retType->defaultInitializer);
call->remove();
}
}
static void buildValueFunction(FnSymbol* fn) {
if (!fn->isIterator()) {
FnSymbol* copy;
bool valueFunctionExists = fn->valueFunction;
if (!valueFunctionExists) {
// Build the value function when it does not already exist.
copy = fn->copy();
copy->removeFlag(FLAG_RESOLVED);
copy->addFlag(FLAG_INVISIBLE_FN);
if (fn->hasFlag(FLAG_NO_IMPLICIT_COPY))
copy->addFlag(FLAG_NO_IMPLICIT_COPY);
copy->retTag = RET_VALUE; // Change ret flag to value (not ref).
fn->defPoint->insertBefore(new DefExpr(copy));
fn->valueFunction = copy;
Symbol* ret = copy->getReturnSymbol();
replaceSetterArgWithFalse(copy, copy, ret);
replaceSetterArgWithTrue(fn, fn);
} else {
copy = fn->valueFunction;
}
resolveFns(copy);
} else {
replaceSetterArgWithTrue(fn, fn);
}
}
static void resolveReturnType(FnSymbol* fn)
{
// Resolve return type.
Symbol* ret = fn->getReturnSymbol();
Type* retType = ret->type;
if (retType == dtUnknown) {
Vec<Type*> retTypes;
Vec<Symbol*> retParams;
computeReturnTypeParamVectors(fn, ret, retTypes, retParams);
if (retTypes.n == 1)
retType = retTypes.head();
else if (retTypes.n > 1) {
for (int i = 0; i < retTypes.n; i++) {
bool best = true;
for (int j = 0; j < retTypes.n; j++) {
if (retTypes.v[i] != retTypes.v[j]) {
bool requireScalarPromotion = false;
if (!canDispatch(retTypes.v[j], retParams.v[j], retTypes.v[i], fn, &requireScalarPromotion))
best = false;
if (requireScalarPromotion)
best = false;
}
}
if (best) {
retType = retTypes.v[i];
break;
}
}
}
if (!fn->iteratorInfo) {
if (retTypes.n == 0)
retType = dtVoid;
}
}
ret->type = retType;
if (!fn->iteratorInfo) {
if (retType == dtUnknown)
USR_FATAL(fn, "unable to resolve return type");
fn->retType = retType;
}
}
// Simple wrappers to check if a function is a specific type of iterator
static bool isIteratorOfType(FnSymbol* fn, Symbol* iterTag) {
if (fn->isIterator()) {
for_formals(formal, fn) {
if (formal->type == iterTag->type && paramMap.get(formal) == iterTag) {
return true;
}
}
}
return false;
}
static bool isLeaderIterator(FnSymbol* fn) {
return isIteratorOfType(fn, gLeaderTag);
}
static bool isFollowerIterator(FnSymbol* fn) {
return isIteratorOfType(fn, gFollowerTag);
}
static bool isStandaloneIterator(FnSymbol* fn) {
return isIteratorOfType(fn, gStandaloneTag);
}
void
resolveFns(FnSymbol* fn) {
if (fn->isResolved())
return;
fn->addFlag(FLAG_RESOLVED);
if (fn->hasFlag(FLAG_EXTERN)) {
resolveBlockStmt(fn->body);
resolveReturnType(fn);
return;
}
if (fn->hasFlag(FLAG_FUNCTION_PROTOTYPE))
return;
//
// Mark serial loops that yield inside of follower and standalone iterators
// as order independent. By using a forall loop, a user is asserting that
// their loop is order independent. Here we just mark the serial loops inside
// of the "follower" with this information. Note that only loops that yield
// are marked since other loops are not necessarily order independent. Only
// the inner most loop of a loop nest will be marked.
//
if (isFollowerIterator(fn) || isStandaloneIterator(fn)) {
std::vector<CallExpr*> callExprs;
collectCallExprs(fn->body, callExprs);
for_vector(CallExpr, call, callExprs) {
if (call->isPrimitive(PRIM_YIELD)) {
if (LoopStmt* loop = LoopStmt::findEnclosingLoop(call)) {
if (loop->isCoforallLoop() == false) {
loop->orderIndependentSet(true);
}
}
}
}
}
//
// Mark leader and standalone parallel iterators for inlining. Also stash a
// pristine copy of the iterator (required by forall intents)
//
if (isLeaderIterator(fn) || isStandaloneIterator(fn)) {
fn->addFlag(FLAG_INLINE_ITERATOR);
stashPristineCopyOfLeaderIter(fn, /*ignore_isResolved:*/ true);
}
if (fn->retTag == RET_REF) {
buildValueFunction(fn);
}
insertFormalTemps(fn);
resolveBlockStmt(fn->body);
if (tryFailure) {
fn->removeFlag(FLAG_RESOLVED);
return;
}
if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
AggregateType* ct = toAggregateType(fn->retType);
if (!ct)
INT_FATAL(fn, "Constructor has no class type");
setScalarPromotionType(ct);
fixTypeNames(ct);
}
resolveReturnType(fn);
//
// insert casts as necessary
//
if (fn->retTag != RET_PARAM) {
Vec<CallExpr*> casts;
insertCasts(fn->body, fn, casts);
forv_Vec(CallExpr, cast, casts) {
resolveCall(cast);
if (cast->isResolved()) {
resolveFns(cast->isResolved());
}
}
}
if (fn->isIterator() && !fn->iteratorInfo) {
protoIteratorClass(fn);
}
// Resolve base class type constructors as well.
if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
forv_Vec(Type, parent, fn->retType->dispatchParents) {
if (toAggregateType(parent) && parent != dtValue && parent != dtObject && parent->defaultTypeConstructor) {
resolveFormals(parent->defaultTypeConstructor);
if (resolvedFormals.set_in(parent->defaultTypeConstructor)) {
resolveFns(parent->defaultTypeConstructor);
}
}
}
if (AggregateType* ct = toAggregateType(fn->retType)) {
for_fields(field, ct) {
if (AggregateType* fct = toAggregateType(field->type)) {
if (fct->defaultTypeConstructor) {
resolveFormals(fct->defaultTypeConstructor);
if (resolvedFormals.set_in(fct->defaultTypeConstructor)) {
resolveFns(fct->defaultTypeConstructor);
}
}
}
}
}
// This instantiates the default constructor for the corresponding type constructor.
instantiate_default_constructor(fn);
//
// resolve destructor
//
if (AggregateType* ct = toAggregateType(fn->retType)) {
if (!ct->destructor &&
!ct->symbol->hasFlag(FLAG_REF)) {
VarSymbol* tmp = newTemp(ct);
CallExpr* call = new CallExpr("~chpl_destroy", gMethodToken, tmp);
// In case resolveCall drops other stuff into the tree ahead of the
// call, we wrap everything in a block for safe removal.
BlockStmt* block = new BlockStmt();
block->insertAtHead(call);
fn->insertAtHead(block);
fn->insertAtHead(new DefExpr(tmp));
resolveCall(call);
resolveFns(call->isResolved());
ct->destructor = call->isResolved();
block->remove();
tmp->defPoint->remove();
}
}
}
//
// mark privatized classes
//
if (fn->hasFlag(FLAG_PRIVATIZED_CLASS)) {
if (fn->getReturnSymbol() == gTrue) {
fn->getFormal(1)->type->symbol->addFlag(FLAG_PRIVATIZED_CLASS);
}
}
}
static bool
possible_signature_match(FnSymbol* fn, FnSymbol* gn) {
if (fn->name != gn->name)
return false;
if (fn->numFormals() != gn->numFormals())
return false;
for (int i = 3; i <= fn->numFormals(); i++) {
ArgSymbol* fa = fn->getFormal(i);
ArgSymbol* ga = gn->getFormal(i);
if (strcmp(fa->name, ga->name))
return false;
}
return true;
}
static bool
signature_match(FnSymbol* fn, FnSymbol* gn) {
if (fn->name != gn->name)
return false;
if (fn->numFormals() != gn->numFormals())
return false;
for (int i = 3; i <= fn->numFormals(); i++) {
ArgSymbol* fa = fn->getFormal(i);
ArgSymbol* ga = gn->getFormal(i);
if (strcmp(fa->name, ga->name))
return false;
if (fa->type != ga->type)
return false;
}
return true;
}
//
// add to vector icts all types instantiated from ct
//
static void
collectInstantiatedAggregateTypes(Vec<Type*>& icts, Type* ct) {
forv_Vec(TypeSymbol, ts, gTypeSymbols) {
if (ts->type->defaultTypeConstructor)
if (!ts->hasFlag(FLAG_GENERIC) &&
ts->type->defaultTypeConstructor->instantiatedFrom ==
ct->defaultTypeConstructor)
icts.add(ts->type);
}
}
//
// return true if child overrides parent in dispatch table
//
static bool
isVirtualChild(FnSymbol* child, FnSymbol* parent) {
if (Vec<FnSymbol*>* children = virtualChildrenMap.get(parent)) {
forv_Vec(FnSymbol*, candidateChild, *children) {
if (candidateChild == child)
return true;
}
}
return false;
}
static void
addToVirtualMaps(FnSymbol* pfn, AggregateType* ct) {
forv_Vec(FnSymbol, cfn, ct->methods) {
if (cfn && !cfn->instantiatedFrom && possible_signature_match(pfn, cfn)) {
Vec<Type*> types;
if (ct->symbol->hasFlag(FLAG_GENERIC))
collectInstantiatedAggregateTypes(types, ct);
else
types.add(ct);
forv_Vec(Type, type, types) {
SymbolMap subs;
if (ct->symbol->hasFlag(FLAG_GENERIC))
subs.put(cfn->getFormal(2), type->symbol);
for (int i = 3; i <= cfn->numFormals(); i++) {
ArgSymbol* arg = cfn->getFormal(i);
if (arg->intent == INTENT_PARAM) {
subs.put(arg, paramMap.get(pfn->getFormal(i)));
} else if (arg->type->symbol->hasFlag(FLAG_GENERIC)) {
subs.put(arg, pfn->getFormal(i)->type->symbol);
}
}
FnSymbol* fn = cfn;
if (subs.n) {
fn = instantiate(fn, subs, NULL);
if (fn) {
if (type->defaultTypeConstructor->instantiationPoint)
fn->instantiationPoint = type->defaultTypeConstructor->instantiationPoint;
else
fn->instantiationPoint = toBlockStmt(type->defaultTypeConstructor->defPoint->parentExpr);
INT_ASSERT(fn->instantiationPoint);
}
}
if (fn) {
resolveFormals(fn);
if (signature_match(pfn, fn)) {
resolveFns(fn);
if (fn->retType->symbol->hasFlag(FLAG_ITERATOR_RECORD) &&
pfn->retType->symbol->hasFlag(FLAG_ITERATOR_RECORD)) {
if (!isSubType(fn->retType->defaultInitializer->iteratorInfo->getValue->retType,
pfn->retType->defaultInitializer->iteratorInfo->getValue->retType)) {
USR_FATAL_CONT(pfn, "conflicting return type specified for '%s: %s'", toString(pfn),
pfn->retType->defaultInitializer->iteratorInfo->getValue->retType->symbol->name);
USR_FATAL_CONT(fn, " overridden by '%s: %s'", toString(fn),
fn->retType->defaultInitializer->iteratorInfo->getValue->retType->symbol->name);
USR_STOP();
} else {
pfn->retType->dispatchChildren.add_exclusive(fn->retType);
fn->retType->dispatchParents.add_exclusive(pfn->retType);
Type* pic = pfn->retType->defaultInitializer->iteratorInfo->iclass;
Type* ic = fn->retType->defaultInitializer->iteratorInfo->iclass;
INT_ASSERT(ic->symbol->hasFlag(FLAG_ITERATOR_CLASS));
// Iterator classes are created as normal top-level classes (inheriting
// from dtObject). Here, we want to re-parent ic with pic, so
// we need to remove and replace the object base class.
INT_ASSERT(ic->dispatchParents.n == 1);
Type* parent = ic->dispatchParents.only();
if (parent == dtObject)
{
int item = parent->dispatchChildren.index(ic);
parent->dispatchChildren.remove(item);
ic->dispatchParents.remove(0);
}
pic->dispatchChildren.add_exclusive(ic);
ic->dispatchParents.add_exclusive(pic);
continue; // do not add to virtualChildrenMap; handle in _getIterator
}
} else if (!isSubType(fn->retType, pfn->retType)) {
USR_FATAL_CONT(pfn, "conflicting return type specified for '%s: %s'", toString(pfn), pfn->retType->symbol->name);
USR_FATAL_CONT(fn, " overridden by '%s: %s'", toString(fn), fn->retType->symbol->name);
USR_STOP();
}
{
Vec<FnSymbol*>* fns = virtualChildrenMap.get(pfn);
if (!fns) fns = new Vec<FnSymbol*>();
fns->add(fn);
virtualChildrenMap.put(pfn, fns);
fn->addFlag(FLAG_VIRTUAL);
pfn->addFlag(FLAG_VIRTUAL);
}
{
Vec<FnSymbol*>* fns = virtualRootsMap.get(fn);
if (!fns) fns = new Vec<FnSymbol*>();
bool added = false;
//
// check if parent or child already exists in vector
//
for (int i = 0; i < fns->n; i++) {
//
// if parent already exists, do not add child to vector
//
if (isVirtualChild(pfn, fns->v[i])) {
added = true;
break;
}
//
// if child already exists, replace with parent
//
if (isVirtualChild(fns->v[i], pfn)) {
fns->v[i] = pfn;
added = true;
break;
}
}
if (!added)
fns->add(pfn);
virtualRootsMap.put(fn, fns);
}
}
}
}
}
}
}
static void
addAllToVirtualMaps(FnSymbol* fn, AggregateType* ct) {
forv_Vec(Type, t, ct->dispatchChildren) {
AggregateType* ct = toAggregateType(t);
if (ct->defaultTypeConstructor &&
(ct->defaultTypeConstructor->hasFlag(FLAG_GENERIC) ||
ct->defaultTypeConstructor->isResolved()))
addToVirtualMaps(fn, ct);
if (!ct->instantiatedFrom)
addAllToVirtualMaps(fn, ct);
}
}
static void
buildVirtualMaps() {
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->hasFlag(FLAG_WRAPPER))
// Only "true" functions are used to populate virtual maps.
continue;
if (! fn->isResolved())
// Only functions that are actually used go into the virtual map.
continue;
if (fn->hasFlag(FLAG_NO_PARENS))
// Parenthesesless functions are statically bound; that is, they are not
// dispatched through the virtual table.
continue;
if (fn->retTag == RET_PARAM || fn->retTag == RET_TYPE)
// Only run-time functions populate the virtual map.
continue;
if (fn->numFormals() > 1 && fn->getFormal(1)->type == dtMethodToken) {
// Only methods go in the virtual function table.
if (AggregateType* pt = toAggregateType(fn->getFormal(2)->type)) {
if (isClass(pt) && !pt->symbol->hasFlag(FLAG_GENERIC)) {
addAllToVirtualMaps(fn, pt);
}
}
}
}
}
static void
addVirtualMethodTableEntry(Type* type, FnSymbol* fn, bool exclusive /*= false*/) {
Vec<FnSymbol*>* fns = virtualMethodTable.get(type);
if (!fns) fns = new Vec<FnSymbol*>();
if (exclusive) {
forv_Vec(FnSymbol, f, *fns) {
if (f == fn)
return;
}
}
fns->add(fn);
virtualMethodTable.put(type, fns);
}
void
parseExplainFlag(char* flag, int* line, ModuleSymbol** module) {
*line = 0;
if (strcmp(flag, "")) {
char *token, *str1 = NULL, *str2 = NULL;
token = strstr(flag, ":");
if (token) {
*token = '\0';
str1 = token+1;
token = strstr(str1, ":");
if (token) {
*token = '\0';
str2 = token + 1;
}
}
if (str1) {
if (str2 || !atoi(str1)) {
forv_Vec(ModuleSymbol, mod, allModules) {
if (!strcmp(mod->name, str1)) {
*module = mod;
break;
}
}
if (!*module)
USR_FATAL("invalid module name '%s' passed to --explain-call flag", str1);
} else
*line = atoi(str1);
if (str2)
*line = atoi(str2);
}
if (*line == 0)
*line = -1;
}
}
static void resolveExternVarSymbols()
{
forv_Vec(VarSymbol, vs, gVarSymbols)
{
if (! vs->hasFlag(FLAG_EXTERN))
continue;
DefExpr* def = vs->defPoint;
Expr* init = def->next;
// We expect the expression following the DefExpr for an extern to be a
// type block that initializes the variable.
BlockStmt* block = toBlockStmt(init);
if (block)
resolveBlockStmt(block);
}
}
static void resolveTypedefedArgTypes(FnSymbol* fn)
{
for_formals(formal, fn)
{
INT_ASSERT(formal->type); // Should be *something*.
if (formal->type != dtUnknown)
continue;
if (BlockStmt* block = formal->typeExpr)
{
if (SymExpr* se = toSymExpr(block->body.first()))
{
if (se->var->hasFlag(FLAG_TYPE_VARIABLE))
{
Type* type = resolveTypeAlias(toSymExpr(se));
INT_ASSERT(type);
formal->type = type;
}
}
}
}
}
static void
computeStandardModuleSet() {
standardModuleSet.set_add(rootModule->block);
standardModuleSet.set_add(theProgram->block);
Vec<ModuleSymbol*> stack;
stack.add(standardModule);
while (ModuleSymbol* mod = stack.pop()) {
if (mod->block->modUses) {
for_actuals(expr, mod->block->modUses) {
SymExpr* se = toSymExpr(expr);
INT_ASSERT(se);
ModuleSymbol* use = toModuleSymbol(se->var);
INT_ASSERT(use);
if (!standardModuleSet.set_in(use->block)) {
stack.add(use);
standardModuleSet.set_add(use->block);
}
}
}
}
}
void
resolve() {
parseExplainFlag(fExplainCall, &explainCallLine, &explainCallModule);
computeStandardModuleSet();
// call _nilType nil so as to not confuse the user
dtNil->symbol->name = gNil->name;
bool changed = true;
while (changed) {
changed = false;
forv_Vec(FnSymbol, fn, gFnSymbols) {
changed = fn->tag_generic() || changed;
}
}
unmarkDefaultedGenerics();
resolveExternVarSymbols();
// --ipe does not build a mainModule
if (mainModule)
resolveUses(mainModule);
// --ipe does not build printModuleInitModule
if (printModuleInitModule)
resolveUses(printModuleInitModule);
// --ipe does not build chpl_gen_main
if (chpl_gen_main)
resolveFns(chpl_gen_main);
USR_STOP();
resolveExports();
resolveEnumTypes();
resolveDynamicDispatches();
insertRuntimeTypeTemps();
resolveAutoCopies();
resolveRecordInitializers();
resolveOther();
insertDynamicDispatchCalls();
insertReturnTemps();
handleRuntimeTypes();
pruneResolvedTree();
freeCache(ordersCache);
freeCache(defaultsCache);
freeCache(genericsCache);
freeCache(coercionsCache);
freeCache(promotionsCache);
freeCache(capturedValues);
Vec<VisibleFunctionBlock*> vfbs;
visibleFunctionMap.get_values(vfbs);
forv_Vec(VisibleFunctionBlock, vfb, vfbs) {
Vec<Vec<FnSymbol*>*> vfns;
vfb->visibleFunctions.get_values(vfns);
forv_Vec(Vec<FnSymbol*>, vfn, vfns) {
delete vfn;
}
delete vfb;
}
visibleFunctionMap.clear();
visibilityBlockCache.clear();
forv_Vec(BlockStmt, stmt, gBlockStmts) {
stmt->moduleUseClear();
}
resolved = true;
}
static void unmarkDefaultedGenerics() {
//
// make it so that arguments with types that have default values for
// all generic arguments used those defaults
//
// FLAG_MARKED_GENERIC is used to identify places where the user inserted
// '?' (queries) to mark such a type as generic.
//
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (!fn->inTree())
continue;
bool unmark = fn->hasFlag(FLAG_GENERIC);
for_formals(formal, fn) {
if (formal->type->hasGenericDefaults) {
if (!formal->hasFlag(FLAG_MARKED_GENERIC) &&
formal != fn->_this &&
!formal->hasFlag(FLAG_IS_MEME)) {
SET_LINENO(formal);
formal->typeExpr = new BlockStmt(new CallExpr(formal->type->defaultTypeConstructor));
insert_help(formal->typeExpr, NULL, formal);
formal->type = dtUnknown;
} else {
unmark = false;
}
} else if (formal->type->symbol->hasFlag(FLAG_GENERIC) || formal->intent == INTENT_PARAM) {
unmark = false;
}
}
if (unmark) {
fn->removeFlag(FLAG_GENERIC);
INT_ASSERT(false);
}
}
}
// Resolve uses in postorder (removing back-links).
// We have to resolve modules in dependency order,
// so that the types of globals are ready when we need them.
static void resolveUses(ModuleSymbol* mod)
{
static Vec<ModuleSymbol*> initMods;
static int module_resolution_depth = 0;
// Test and set to break loops and prevent infinite recursion.
if (initMods.set_in(mod))
return;
initMods.set_add(mod);
++module_resolution_depth;
// I use my parent implicitly.
if (ModuleSymbol* parent = mod->defPoint->getModule())
if (parent != theProgram && parent != rootModule)
resolveUses(parent);
// Now, traverse my use statements, and call the initializer for each
// module I use.
forv_Vec(ModuleSymbol, usedMod, mod->modUseList)
resolveUses(usedMod);
// Finally, myself.
if (fPrintModuleResolution)
fprintf(stderr, "%2d Resolving module %s ...", module_resolution_depth, mod->name);
FnSymbol* fn = mod->initFn;
resolveFormals(fn);
resolveFns(fn);
if (fPrintModuleResolution)
putc('\n', stderr);
--module_resolution_depth;
}
static void resolveExports() {
// We need to resolve any additional functions that will be exported.
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->hasFlag(FLAG_EXPORT)) {
SET_LINENO(fn);
resolveFormals(fn);
resolveFns(fn);
}
}
}
static void resolveEnumTypes() {
// need to handle enumerated types better
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (EnumType* et = toEnumType(type->type)) {
ensureEnumTypeResolved(et);
}
}
}
static void resolveDynamicDispatches() {
inDynamicDispatchResolution = true;
int num_types;
do {
num_types = gTypeSymbols.n;
{
Vec<Vec<FnSymbol*>*> values;
virtualChildrenMap.get_values(values);
forv_Vec(Vec<FnSymbol*>, value, values) {
delete value;
}
}
virtualChildrenMap.clear();
{
Vec<Vec<FnSymbol*>*> values;
virtualRootsMap.get_values(values);
forv_Vec(Vec<FnSymbol*>, value, values) {
delete value;
}
}
virtualRootsMap.clear();
buildVirtualMaps();
} while (num_types != gTypeSymbols.n);
for (int i = 0; i < virtualRootsMap.n; i++) {
if (virtualRootsMap.v[i].key) {
for (int j = 0; j < virtualRootsMap.v[i].value->n; j++) {
FnSymbol* root = virtualRootsMap.v[i].value->v[j];
addVirtualMethodTableEntry(root->_this->type, root, true);
}
}
}
Vec<Type*> ctq;
ctq.add(dtObject);
forv_Vec(Type, ct, ctq) {
if (Vec<FnSymbol*>* parentFns = virtualMethodTable.get(ct)) {
forv_Vec(FnSymbol, pfn, *parentFns) {
Vec<Type*> childSet;
if (Vec<FnSymbol*>* childFns = virtualChildrenMap.get(pfn)) {
forv_Vec(FnSymbol, cfn, *childFns) {
forv_Vec(Type, pt, cfn->_this->type->dispatchParents) {
if (pt == ct) {
if (!childSet.set_in(cfn->_this->type)) {
addVirtualMethodTableEntry(cfn->_this->type, cfn);
childSet.set_add(cfn->_this->type);
}
break;
}
}
}
}
forv_Vec(Type, childType, ct->dispatchChildren) {
if (!childSet.set_in(childType)) {
addVirtualMethodTableEntry(childType, pfn);
}
}
}
}
forv_Vec(Type, child, ct->dispatchChildren) {
ctq.add(child);
}
}
for (int i = 0; i < virtualMethodTable.n; i++) {
if (virtualMethodTable.v[i].key) {
virtualMethodTable.v[i].value->reverse();
for (int j = 0; j < virtualMethodTable.v[i].value->n; j++) {
virtualMethodMap.put(virtualMethodTable.v[i].value->v[j], j);
}
}
}
inDynamicDispatchResolution = false;
if (fPrintDispatch) {
printf("Dynamic dispatch table:\n");
for (int i = 0; i < virtualMethodTable.n; i++) {
if (Type* t = virtualMethodTable.v[i].key) {
printf(" %s\n", toString(t));
for (int j = 0; j < virtualMethodTable.v[i].value->n; j++) {
printf(" %s\n", toString(virtualMethodTable.v[i].value->v[j]));
}
}
}
}
}
static void insertRuntimeTypeTemps() {
forv_Vec(TypeSymbol, ts, gTypeSymbols) {
if (ts->defPoint &&
ts->defPoint->parentSymbol &&
ts->hasFlag(FLAG_HAS_RUNTIME_TYPE) &&
!ts->hasFlag(FLAG_GENERIC)) {
SET_LINENO(ts);
VarSymbol* tmp = newTemp("_runtime_type_tmp_", ts->type);
ts->type->defaultInitializer->insertBeforeReturn(new DefExpr(tmp));
CallExpr* call = new CallExpr("chpl__convertValueToRuntimeType", tmp);
ts->type->defaultInitializer->insertBeforeReturn(call);
resolveCall(call);
resolveFns(call->isResolved());
valueToRuntimeTypeMap.put(ts->type, call->isResolved());
call->remove();
tmp->defPoint->remove();
}
}
}
static void resolveAutoCopies() {
forv_Vec(TypeSymbol, ts, gTypeSymbols) {
if (!ts->defPoint->parentSymbol)
continue; // Type is not in tree
if (ts->hasFlag(FLAG_GENERIC))
continue; // Consider only concrete types.
if (ts->hasFlag(FLAG_SYNTACTIC_DISTRIBUTION))
continue; // Skip the "dmapped" pseudo-type.
if (isRecord(ts->type) || getSyncFlags(ts).any())
{
resolveAutoCopy(ts->type);
resolveAutoDestroy(ts->type);
}
}
}
static void resolveRecordInitializers() {
//
// resolve PRIM_INITs for records
//
forv_Vec(CallExpr, init, inits)
{
// Ignore if dead.
if (!init->parentSymbol)
continue;
Type* type = init->get(1)->typeInfo();
// Don't resolve initializers for runtime types.
// These have to be resolved after runtime types are replaced by values in
// insertRuntimeInitTemps().
if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
continue;
// Extract the value type.
if (type->symbol->hasFlag(FLAG_REF))
type = type->getValType();
// Resolve the AggregateType that has noinit used on it.
if (init->isPrimitive(PRIM_NO_INIT)) {
// Replaces noinit with a call to the defaultTypeConstructor,
// providing the param and type arguments necessary to allocate
// space for the instantiation of this (potentially) generic type.
// defaultTypeConstructor calls are already cleaned up at the end of
// function resolution, so the noinit cleanup would be redundant.
SET_LINENO(init);
CallExpr* res = new CallExpr(type->defaultTypeConstructor);
for_formals(formal, type->defaultTypeConstructor) {
Vec<Symbol *> keys;
// Finds each named argument in the type constructor and inserts
// the substitution provided.
type->substitutions.get_keys(keys);
// I don't think we can guarantee that the substitutions will be
// in the same order as the arguments for the defaultTypeConstructor.
// That would make this O(n) instead of potentially O(n*n)
forv_Vec(Symbol, key, keys) {
if (!strcmp(formal->name, key->name)) {
Symbol* formalVal = type->substitutions.get(key);
res->insertAtTail(new NamedExpr(formal->name,
new SymExpr(formalVal)));
}
}
}
init->get(1)->replace(res);
resolveCall(res);
makeNoop((CallExpr *)init->parentExpr);
// Now that we've resolved the type constructor and thus resolved the
// generic type of the variable we were assigning to, the outer move
// is no longer needed, so remove it and continue to the next init.
continue;
}
// This could be an assert...
if (type->defaultValue)
INT_FATAL(init, "PRIM_INIT should have been replaced already");
SET_LINENO(init);
if (type->symbol->hasFlag(FLAG_DISTRIBUTION)) {
// This initialization cannot be replaced by a _defaultOf function
// earlier in the compiler, there is not enough information to build a
// default function for it. When we have the ability to call a
// constructor from a type alias, it can be moved directly into module
// code
Symbol* tmp = newTemp("_distribution_tmp_");
init->getStmtExpr()->insertBefore(new DefExpr(tmp));
CallExpr* classCall = new CallExpr(type->getField("_valueType")->type->defaultInitializer);
CallExpr* move = new CallExpr(PRIM_MOVE, tmp, classCall);
init->getStmtExpr()->insertBefore(move);
resolveCall(classCall);
resolveFns(classCall->isResolved());
resolveCall(move);
CallExpr* distCall = new CallExpr("chpl__buildDistValue", tmp);
init->replace(distCall);
resolveCall(distCall);
resolveFns(distCall->isResolved());
} else {
CallExpr* call = new CallExpr("_defaultOf", type->symbol);
init->replace(call);
resolveNormalCall(call);
// At this point in the compiler, we can resolve the _defaultOf function
// for the type, so do so.
if (call->isResolved())
resolveFns(call->isResolved());
}
}
}
//
// Resolve other things we might want later
//
static void resolveOther() {
//
// When compiling with --minimal-modules, gPrintModuleInitFn is not
// defined.
//
if (gPrintModuleInitFn) {
// Resolve the function that will print module init order
resolveFns(gPrintModuleInitFn);
}
}
static void insertDynamicDispatchCalls() {
// Select resolved calls whose function appears in the virtualChildrenMap.
// These are the dynamically-dispatched calls.
forv_Vec(CallExpr, call, gCallExprs) {
if (!call->parentSymbol) continue;
if (!call->getStmtExpr()) continue;
FnSymbol* key = call->isResolved();
if (!key) continue;
Vec<FnSymbol*>* fns = virtualChildrenMap.get(key);
if (!fns) continue;
SET_LINENO(call);
//Check to see if any of the overridden methods reference outer variables. If they do, then when we later change the
//signature in flattenFunctions, the vtable style will break (function signatures will no longer match). To avoid this
//we switch to the if-block style in the case where outer variables are discovered.
//Note: This is conservative, as we haven't finished resolving functions and calls yet, we check all possibilities.
bool referencesOuterVars = false;
Vec<FnSymbol*> seen;
referencesOuterVars = usesOuterVars(key, seen);
if (!referencesOuterVars) {
for (int i = 0; i < fns->n; ++i) {
seen.clear();
if ( (referencesOuterVars = usesOuterVars(key, seen)) ) {
break;
}
}
}
if ((fns->n + 1 > fConditionalDynamicDispatchLimit) && (!referencesOuterVars)) {
//
// change call of root method into virtual method call;
// Insert function SymExpr and virtual method temp at head of argument
// list.
//
// N.B.: The following variable must have the same size as the type of
// chpl__class_id / chpl_cid_* -- otherwise communication will cause
// problems when it tries to read the cid of a remote class. See
// test/classes/sungeun/remoteDynamicDispatch.chpl (on certain
// machines and configurations).
VarSymbol* cid = newTemp("_virtual_method_tmp_", dtInt[INT_SIZE_32]);
call->getStmtExpr()->insertBefore(new DefExpr(cid));
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, cid, new CallExpr(PRIM_GETCID, call->get(2)->copy())));
call->get(1)->insertBefore(new SymExpr(cid));
// "remove" here means VMT calls are not really "resolved".
// That is, calls to isResolved() return NULL.
call->get(1)->insertBefore(call->baseExpr->remove());
call->primitive = primitives[PRIM_VIRTUAL_METHOD_CALL];
// This clause leads to necessary reference temporaries not being inserted,
// while the clause below works correctly. <hilde>
// Increase --conditional-dynamic-dispatch-limit to see this.
} else {
forv_Vec(FnSymbol, fn, *fns) {
Type* type = fn->getFormal(2)->type;
CallExpr* subcall = call->copy();
SymExpr* tmp = new SymExpr(gNil);
// Build the IF block.
BlockStmt* ifBlock = new BlockStmt();
VarSymbol* cid = newTemp("_dynamic_dispatch_tmp_", dtBool);
ifBlock->insertAtTail(new DefExpr(cid));
ifBlock->insertAtTail(new CallExpr(PRIM_MOVE, cid,
new CallExpr(PRIM_TESTCID,
call->get(2)->copy(),
type->symbol)));
VarSymbol* _ret = NULL;
if (key->retType != dtVoid) {
_ret = newTemp("_return_tmp_", key->retType);
ifBlock->insertAtTail(new DefExpr(_ret));
}
// Build the TRUE block.
BlockStmt* trueBlock = new BlockStmt();
if (fn->retType == key->retType) {
if (_ret)
trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, _ret, subcall));
else
trueBlock->insertAtTail(subcall);
} else if (isSubType(fn->retType, key->retType)) {
// Insert a cast to the overridden method's return type
VarSymbol* castTemp = newTemp("_cast_tmp_", fn->retType);
trueBlock->insertAtTail(new DefExpr(castTemp));
trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, castTemp,
subcall));
INT_ASSERT(_ret);
trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, _ret,
new CallExpr(PRIM_CAST,
key->retType->symbol,
castTemp)));
} else
INT_FATAL(key, "unexpected case");
// Build the FALSE block.
BlockStmt* falseBlock = NULL;
if (_ret)
falseBlock = new BlockStmt(new CallExpr(PRIM_MOVE, _ret, tmp));
else
falseBlock = new BlockStmt(tmp);
ifBlock->insertAtTail(new CondStmt(
new SymExpr(cid),
trueBlock,
falseBlock));
if (key->retType == dtUnknown)
INT_FATAL(call, "bad parent virtual function return type");
call->getStmtExpr()->insertBefore(ifBlock);
if (_ret)
call->replace(new SymExpr(_ret));
else
call->remove();
tmp->replace(call);
subcall->baseExpr->replace(new SymExpr(fn));
if (SymExpr* se = toSymExpr(subcall->get(2))) {
VarSymbol* tmp = newTemp("_cast_tmp_", type);
se->getStmtExpr()->insertBefore(new DefExpr(tmp));
se->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_CAST, type->symbol, se->var)));
se->replace(new SymExpr(tmp));
} else if (CallExpr* ce = toCallExpr(subcall->get(2)))
if (ce->isPrimitive(PRIM_CAST))
ce->get(1)->replace(new SymExpr(type->symbol));
else
INT_FATAL(subcall, "unexpected");
else
INT_FATAL(subcall, "unexpected");
}
}
}
}
static Type*
buildRuntimeTypeInfo(FnSymbol* fn) {
SET_LINENO(fn);
AggregateType* ct = new AggregateType(AGGREGATE_RECORD);
TypeSymbol* ts = new TypeSymbol(astr("_RuntimeTypeInfo"), ct);
for_formals(formal, fn) {
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM))
continue;
VarSymbol* field = new VarSymbol(formal->name, formal->type);
ct->fields.insertAtTail(new DefExpr(field));
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
field->addFlag(FLAG_TYPE_VARIABLE);
}
theProgram->block->insertAtTail(new DefExpr(ts));
ct->symbol->addFlag(FLAG_RUNTIME_TYPE_VALUE);
makeRefType(ts->type); // make sure the new type has a ref type.
return ct;
}
static void insertReturnTemps() {
//
// Insert return temps for functions that return values if no
// variable captures the result. If the value is a sync/single var or a
// reference to a sync/single var, pass it through the _statementLevelSymbol
// function to get the semantics of reading a sync/single var. If the value
// is an iterator pass it through another overload of
// _statementLevelSymbol to iterate through it for side effects.
// Note that we do not do this for --minimal-modules compilation
// because we do not support sync/singles for minimal modules.
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->parentSymbol) {
if (FnSymbol* fn = call->isResolved()) {
if (fn->retType != dtVoid) {
CallExpr* parent = toCallExpr(call->parentExpr);
if (!parent && !isDefExpr(call->parentExpr)) { // no use
SET_LINENO(call); // TODO: reset_ast_loc() below?
VarSymbol* tmp = newTemp("_return_tmp_", fn->retType);
DefExpr* def = new DefExpr(tmp);
call->insertBefore(def);
if (!fMinimalModules &&
((fn->retType->getValType() &&
isSyncType(fn->retType->getValType())) ||
isSyncType(fn->retType) ||
fn->isIterator())) {
CallExpr* sls = new CallExpr("_statementLevelSymbol", tmp);
call->insertBefore(sls);
reset_ast_loc(sls, call);
resolveCall(sls);
INT_ASSERT(sls->isResolved());
resolveFns(sls->isResolved());
}
def->insertAfter(new CallExpr(PRIM_MOVE, tmp, call->remove()));
}
}
}
}
}
}
//
// insert code to initialize a class or record
//
static void
initializeClass(Expr* stmt, Symbol* sym) {
AggregateType* ct = toAggregateType(sym->type);
INT_ASSERT(ct);
for_fields(field, ct) {
if (!field->hasFlag(FLAG_SUPER_CLASS)) {
SET_LINENO(field);
if (field->type->defaultValue) {
stmt->insertBefore(new CallExpr(PRIM_SET_MEMBER, sym, field, field->type->defaultValue));
} else if (isRecord(field->type)) {
VarSymbol* tmp = newTemp("_init_class_tmp_", field->type);
stmt->insertBefore(new DefExpr(tmp));
initializeClass(stmt, tmp);
stmt->insertBefore(new CallExpr(PRIM_SET_MEMBER, sym, field, tmp));
}
}
}
}
static void handleRuntimeTypes()
{
// insertRuntimeTypeTemps is also called earlier in resolve(). That call
// can insert variables that need autoCopies and inserting autoCopies can
// insert things that need runtime type temps. These need to be fixed up
// by insertRuntimeTypeTemps before buildRuntimeTypeInitFns is called to
// update the type -> runtimeType mapping. Without this, there is an
// actual/formal type mismatch (with --verify) for the code:
// record R { var A: [1..1][1..1] real; }
insertRuntimeTypeTemps();
buildRuntimeTypeInitFns();
replaceValuesWithRuntimeTypes();
replaceReturnedValuesWithRuntimeTypes();
insertRuntimeInitTemps();
}
//
// pruneResolvedTree -- prunes and cleans the AST after all of the
// function calls and types have been resolved
//
static void
pruneResolvedTree() {
removeUnusedFunctions();
if (fRemoveUnreachableBlocks)
deadBlockElimination();
removeRandomPrimitives();
replaceTypeArgsWithFormalTypeTemps();
removeParamArgs();
removeUnusedGlobals();
removeUnusedTypes();
removeActualNames();
removeFormalTypeAndInitBlocks();
removeTypeBlocks();
removeInitFields();
removeWhereClauses();
removeMootFields();
expandInitFieldPrims();
removeCompilerWarnings();
}
static void clearDefaultInitFns(FnSymbol* unusedFn) {
// Before removing an unused function, check if it is a defaultInitializer.
// If unusedFn is a defaultInitializer, its retType's defaultInitializer
// field will be unusedFn. Set the defaultInitializer field to NULL so the
// removed function doesn't leave behind a garbage pointer.
if (unusedFn->retType->defaultInitializer == unusedFn) {
unusedFn->retType->defaultInitializer = NULL;
}
}
static void removeUnusedFunctions() {
// Remove unused functions
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->hasFlag(FLAG_PRINT_MODULE_INIT_FN)) continue;
if (fn->defPoint && fn->defPoint->parentSymbol) {
if (! fn->isResolved() || fn->retTag == RET_PARAM) {
clearDefaultInitFns(fn);
fn->defPoint->remove();
}
}
}
}
static void removeCompilerWarnings() {
// Warnings have now been issued, no need to keep the function around.
// Remove calls to compilerWarning and let dead code elimination handle
// the rest.
typedef MapElem<FnSymbol*, const char*> FnSymbolElem;
form_Map(FnSymbolElem, el, innerCompilerWarningMap) {
forv_Vec(CallExpr, call, *(el->key->calledBy)) {
call->remove();
}
}
}
static bool
isUnusedClass(AggregateType *ct) {
// Special case for global types.
if (ct->symbol->hasFlag(FLAG_GLOBAL_TYPE_SYMBOL))
return false;
// Runtime types are assumed to be always used.
if (ct->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE))
return false;
// Uses of iterator records get inserted in lowerIterators
if (ct->symbol->hasFlag(FLAG_ITERATOR_RECORD))
return false;
// FALSE if initializers are used
if (ct->defaultInitializer && ct->defaultInitializer->isResolved())
return false;
// FALSE if the type constructor is used.
if (ct->defaultTypeConstructor && ct->defaultTypeConstructor->isResolved())
return false;
bool allChildrenUnused = true;
forv_Vec(Type, child, ct->dispatchChildren) {
AggregateType* childClass = toAggregateType(child);
INT_ASSERT(childClass);
if (!isUnusedClass(childClass)) {
allChildrenUnused = false;
break;
}
}
return allChildrenUnused;
}
// Remove unused types
static void removeUnusedTypes() {
// Remove unused aggregate types.
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (type->defPoint && type->defPoint->parentSymbol)
{
// Skip ref and runtime value types:
// ref types are handled below;
// runtime value types are assumed to be always used.
if (type->hasFlag(FLAG_REF))
continue;
if (type->hasFlag(FLAG_RUNTIME_TYPE_VALUE))
continue;
if (AggregateType* ct = toAggregateType(type->type))
if (isUnusedClass(ct))
ct->symbol->defPoint->remove();
}
}
// Remove unused ref types.
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (type->defPoint && type->defPoint->parentSymbol) {
if (type->hasFlag(FLAG_REF)) {
// Get the value type of the ref type.
if (AggregateType* ct = toAggregateType(type->getValType())) {
if (isUnusedClass(ct)) {
// If the value type is unused, its ref type can also be removed.
type->defPoint->remove();
}
}
// If the default type constructor for this ref type is in the tree, it
// can be removed.
if (type->type->defaultTypeConstructor->defPoint->parentSymbol)
type->type->defaultTypeConstructor->defPoint->remove();
}
}
}
}
static void removeUnusedGlobals()
{
forv_Vec(DefExpr, def, gDefExprs)
{
// Remove unused global variables
if (toVarSymbol(def->sym))
if (toModuleSymbol(def->parentSymbol))
if (def->sym->type == dtUnknown)
def->remove();
}
}
static void removeRandomPrimitive(CallExpr* call)
{
if (! call->primitive)
// TODO: This is weird.
// Calls which trigger this case appear as the init clause of a type
// variable.
// The parent module or function may be resolved, but apparently the type
// variable is resolved only if it is used.
// Generally speaking, we resolve a declaration only if it is used.
// But right now, we only apply this test to functions.
// The test should be extended to variable declarations as well. That is,
// variables need only be resolved if they are actually used.
return;
// A primitive.
switch (call->primitive->tag)
{
default: /* do nothing */ break;
case PRIM_NOOP:
call->remove();
break;
case PRIM_TYPEOF:
{
// Remove move(x, PRIM_TYPEOF(y)) calls -- useless after this
CallExpr* parentCall = toCallExpr(call->parentExpr);
if (parentCall && parentCall->isPrimitive(PRIM_MOVE) &&
parentCall->get(2) == call) {
parentCall->remove();
} else {
// Replace PRIM_TYPEOF with argument
call->replace(call->get(1)->remove());
}
}
break;
case PRIM_CAST:
// Remove trivial casts.
if (call->get(1)->typeInfo() == call->get(2)->typeInfo())
call->replace(call->get(2)->remove());
break;
case PRIM_SET_MEMBER:
case PRIM_GET_MEMBER:
case PRIM_GET_MEMBER_VALUE:
{
// Remove member accesses of types
// Replace string literals with field symbols in member primitives
Type* baseType = call->get(1)->typeInfo();
if (baseType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE))
break;
if (!call->parentSymbol->hasFlag(FLAG_REF) &&
baseType->symbol->hasFlag(FLAG_REF))
baseType = baseType->getValType();
const char* memberName = get_string(call->get(2));
Symbol* sym = baseType->getField(memberName);
if (sym->hasFlag(FLAG_TYPE_VARIABLE) ||
!strcmp(sym->name, "_promotionType") ||
sym->isParameter())
call->getStmtExpr()->remove();
else {
SET_LINENO(call->get(2));
call->get(2)->replace(new SymExpr(sym));
}
}
break;
// Maybe this can be pushed into the following case, where a PRIM_MOVE gets
// removed if its rhs is a type symbol. That is, resolution of a
// PRIM_TYPE_INIT replaces the primitive with symexpr that contains a type symbol.
case PRIM_TYPE_INIT:
{
// A "type init" call that is in the tree should always have a callExpr
// parent, as guaranteed by CallExpr::verify().
CallExpr* parent = toCallExpr(call->parentExpr);
// We expect all PRIM_TYPE_INIT primitives to have a PRIM_MOVE
// parent, following the insertion of call temps.
if (parent->isPrimitive(PRIM_MOVE))
parent->remove();
else
INT_FATAL(parent, "expected parent of PRIM_TYPE_EXPR to be a PRIM_MOVE");
}
break;
case PRIM_MOVE:
{
// Remove types to enable --baseline
SymExpr* sym = toSymExpr(call->get(2));
if (sym && isTypeSymbol(sym->var))
call->remove();
}
break;
}
}
// Remove the method token, parameter and type arguments from
// function signatures and corresponding calls.
static void removeParamArgs()
{
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols)
{
if (! fn->isResolved())
// Don't bother with unresolved functions.
// They will be removed from the tree.
continue;
for_formals(formal, fn)
{
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM) ||
formal->type == dtMethodToken)
{
// Remove the argument from the call site.
forv_Vec(CallExpr, call, *fn->calledBy)
{
// Don't bother with calls that are not in the tree.
if (! call->parentSymbol)
continue;
// Performance note: AList::get(int) also performs a linear search.
for_formals_actuals(cf, ca, call)
{
if (cf == formal)
{
ca->remove();
break;
}
}
}
formal->defPoint->remove();
}
}
}
}
static void removeRandomPrimitives()
{
forv_Vec(CallExpr, call, gCallExprs)
{
// Don't bother with calls that are not in the tree.
if (! call->parentSymbol)
continue;
// Ignore calls to actual functions.
if (call->isResolved())
continue;
// Only primitives remain.
removeRandomPrimitive(call);
}
}
static void removeActualNames()
{
forv_Vec(NamedExpr, named, gNamedExprs)
{
if (! named->parentSymbol)
continue;
// Remove names of named actuals
Expr* actual = named->actual;
actual->remove();
named->replace(actual);
}
}
static void removeTypeBlocks()
{
forv_Vec(BlockStmt, block, gBlockStmts)
{
if (! block->parentSymbol)
continue;
// Remove type blocks--code that exists only to determine types
if (block->blockTag & BLOCK_TYPE_ONLY)
{
block->remove();
}
}
}
//
// buildRuntimeTypeInitFns: Build a 'chpl__convertRuntimeTypeToValue'
// (value) function for all functions tagged as runtime type
// initialization functions. Also, build a function to return the
// runtime type for all runtime type initialization functions.
//
// Functions flagged with the "runtime type init fn" pragma
// (FLAG_RUNTIME_TYPE_INIT_FN during compilation) are designed to
// specify to the compiler how to create a new value of a given type
// from the arguments to the function. These arguments effectively
// supply whatever static and/or runtime information is required to
// build such a value (and therefore effectively represent the
// "type"). Any non-static arguments are bundled into a runtime type
// (record) by the compiler and passed around to represent the type at
// execution time.
//
// The actual type specified is fully-resolved during function resolution. So
// the "runtime type" mechanism is a way to create a parameterized type, but up
// to a point handle it uniformly in the compiler.
// Perhaps a more complete implementation of generic types with inheritance
// would get rid of the need for this specialized machinery.
//
// In practice, we currently use these to create
// runtime types for domains and arrays (via procedures named
// 'chpl__buildDomainRuntimeType' and 'chpl__buildArrayRuntimeType',
// respectively).
//
// For each such flagged function:
//
// - Clone the function, naming it 'chpl__convertRuntimeTypeToValue'
// and change it to a value function
//
// - Replace the body of the original function with a new function
// that returns the dynamic runtime type info
//
// Subsequently, the functions as written in the modules are now
// called 'chpl__convertRuntimeTypeToValue' and used to initialize
// variables with runtime types later in insertRuntimeInitTemps().
//
// Notice also that the original functions had been marked as type
// functions during parsing even though they were not written as such
// (see addPragmaFlags() in build.cpp for more info). Now they are
// actually type functions.
//
static void buildRuntimeTypeInitFns() {
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
// Look only at functions flagged as "runtime type init fn".
if (fn->hasFlag(FLAG_RUNTIME_TYPE_INIT_FN)) {
// Look only at resolved instances.
if (! fn->isResolved())
continue;
INT_ASSERT(fn->retType->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE));
SET_LINENO(fn);
// Build a new runtime type for this function
Type* runtimeType = buildRuntimeTypeInfo(fn);
runtimeTypeMap.put(fn->retType, runtimeType);
// Build chpl__convertRuntimeTypeToValue() instance.
buildRuntimeTypeInitFn(fn, runtimeType);
}
}
}
}
// Build a function to return the runtime type by modifying
// the original function.
static void buildRuntimeTypeInitFn(FnSymbol* fn, Type* runtimeType)
{
// Clone the original function and call the clone chpl__convertRuntimeTypeToValue.
FnSymbol* runtimeTypeToValueFn = fn->copy();
INT_ASSERT(runtimeTypeToValueFn->hasFlag(FLAG_RESOLVED));
runtimeTypeToValueFn->name = astr("chpl__convertRuntimeTypeToValue");
runtimeTypeToValueFn->cname = runtimeTypeToValueFn->name;
// Remove this flag from the clone.
runtimeTypeToValueFn->removeFlag(FLAG_RUNTIME_TYPE_INIT_FN);
// Make the clone a value function.
runtimeTypeToValueFn->getReturnSymbol()->removeFlag(FLAG_TYPE_VARIABLE);
runtimeTypeToValueFn->retTag = RET_VALUE;
fn->defPoint->insertBefore(new DefExpr(runtimeTypeToValueFn));
// Remove static arguments from the RTTV function.
for_formals(formal, runtimeTypeToValueFn)
{
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM))
formal->defPoint->remove();
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
{
Symbol* field = runtimeType->getField(formal->name);
if (! field->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
formal->defPoint->remove();
}
}
// Insert the clone (convertRuntimeTypeToValue) into the runtimeTypeToValueMap.
runtimeTypeToValueMap.put(runtimeType, runtimeTypeToValueFn);
// Change the return type of the original function.
fn->retType = runtimeType;
fn->getReturnSymbol()->type = runtimeType;
// Build a new body for the original function.
BlockStmt* block = new BlockStmt();
VarSymbol* var = newTemp("_return_tmp_", fn->retType);
block->insertAtTail(new DefExpr(var));
// Bundle all non-static arguments into the runtime type record.
// Remove static arguments from this specialized buildRuntimeType function.
for_formals(formal, fn)
{
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM))
continue;
Symbol* field = runtimeType->getField(formal->name);
if (formal->hasFlag(FLAG_TYPE_VARIABLE) &&
! field->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
continue;
block->insertAtTail(new CallExpr(PRIM_SET_MEMBER, var, field, formal));
}
block->insertAtTail(new CallExpr(PRIM_RETURN, var));
// Replace the body of the orignal chpl__buildRuntime...Type() function.
fn->body->replace(block);
}
static void removeFormalTypeAndInitBlocks()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
for_formals(formal, fn) {
// Remove formal default values
if (formal->defaultExpr)
formal->defaultExpr->remove();
// Remove formal type expressions
if (formal->typeExpr)
formal->typeExpr->remove();
}
}
}
}
static void replaceTypeArgsWithFormalTypeTemps()
{
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (! fn->isResolved())
// Don't bother with unresolved functions.
// They will be removed from the tree.
continue;
// Skip this function if it is not in the tree.
if (! fn->defPoint)
continue;
if (! fn->defPoint->parentSymbol)
continue;
// We do not remove type args from extern functions
// TODO: Find out if we really support type args in extern functions.
if (fn->hasFlag(FLAG_EXTERN))
continue;
for_formals(formal, fn)
{
// We are only interested in type formals
if (! formal->hasFlag(FLAG_TYPE_VARIABLE))
continue;
// Replace the formal with a _formal_type_tmp_.
SET_LINENO(formal);
VarSymbol* tmp = newTemp("_formal_type_tmp_", formal->type);
fn->insertAtHead(new DefExpr(tmp));
subSymbol(fn, formal, tmp);
// Remove the corresponding actual from all call sites.
forv_Vec(CallExpr, call, *fn->calledBy)
{
for_formals_actuals(cf, ca, call)
{
if (cf == formal)
{
ca->remove();
break;
}
}
}
formal->defPoint->remove();
//
// If we're removing the formal representing 'this' (if it's a
// type, say), we need to nullify the 'this' pointer in the
// function as well to avoid assumptions that it's legal later.
//
if (formal == fn->_this) {
fn->_this = NULL;
}
}
}
}
static void replaceValuesWithRuntimeTypes()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
for_formals(formal, fn) {
if (formal->hasFlag(FLAG_TYPE_VARIABLE) &&
formal->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
if (FnSymbol* fn = valueToRuntimeTypeMap.get(formal->type)) {
Type* rt = (fn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) ?
fn->retType : runtimeTypeMap.get(fn->retType);
INT_ASSERT(rt);
formal->type = rt;
formal->removeFlag(FLAG_TYPE_VARIABLE);
}
}
}
}
}
}
static void removeWhereClauses()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
if (fn->where)
fn->where->remove();
}
}
}
static void replaceReturnedValuesWithRuntimeTypes()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
if (fn->retTag == RET_TYPE) {
VarSymbol* ret = toVarSymbol(fn->getReturnSymbol());
if (ret && ret->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
if (FnSymbol* rtfn = valueToRuntimeTypeMap.get(ret->type)) {
Type* rt = (rtfn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) ?
rtfn->retType : runtimeTypeMap.get(rtfn->retType);
INT_ASSERT(rt);
ret->type = rt;
fn->retType = ret->type;
fn->retTag = RET_VALUE;
}
}
}
}
}
}
static void replaceInitPrims(std::vector<BaseAST*>& asts)
{
for_vector(BaseAST, ast, asts) {
if (CallExpr* call = toCallExpr(ast)) {
// We are only interested in INIT primitives.
if (call->isPrimitive(PRIM_INIT)) {
FnSymbol* parent = toFnSymbol(call->parentSymbol);
// Call must be in the tree and lie in a resolved function.
if (! parent || ! parent->isResolved())
continue;
SymExpr* se = toSymExpr(call->get(1));
Type* rt = se->var->type;
if (rt->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) {
// ('init' foo), where typeof(foo) has flag "runtime type value"
//
// ==>
//
// (var _runtime_type_tmp_1)
// ('move' _runtime_type_tmp_1 ('.v' foo "field1"))
// (var _runtime_type_tmp_2)
// ('move' _runtime_type_tmp_2 ('.v' foo "field2"))
// (chpl__convertRuntimeTypeToValue _runtime_type_tmp_1 _rtt_2 ... )
SET_LINENO(call);
FnSymbol* runtimeTypeToValueFn = runtimeTypeToValueMap.get(rt);
INT_ASSERT(runtimeTypeToValueFn);
CallExpr* runtimeTypeToValueCall = new CallExpr(runtimeTypeToValueFn);
for_formals(formal, runtimeTypeToValueFn) {
Symbol* field = rt->getField(formal->name);
INT_ASSERT(field);
VarSymbol* tmp = newTemp("_runtime_type_tmp_", field->type);
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp,
new CallExpr(PRIM_GET_MEMBER_VALUE, se->var, field)));
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
tmp->addFlag(FLAG_TYPE_VARIABLE);
runtimeTypeToValueCall->insertAtTail(tmp);
}
VarSymbol* tmp = newTemp("_runtime_type_tmp_", runtimeTypeToValueFn->retType);
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, runtimeTypeToValueCall));
INT_ASSERT(autoCopyMap.get(tmp->type));
call->replace(new CallExpr(autoCopyMap.get(tmp->type), tmp));
} else if (rt->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
//
// This is probably related to a comment that used to handle
// this case elsewhere:
//
// special handling of tuple constructor to avoid
// initialization of array based on an array type symbol
// rather than a runtime array type
//
// this code added during the introduction of the new
// keyword; it should be removed when possible
//
call->getStmtExpr()->remove();
}
else
{
Expr* expr = resolvePrimInit(call);
if (! expr)
{
// This PRIM_INIT could not be resolved.
// But that's OK if it's an extern type.
// (We don't expect extern types to have initializers.)
// Also, we don't generate initializers for iterator records.
// Maybe we can avoid adding PRIM_INIT for these cases in the first
// place....
if (rt->symbol->hasFlag(FLAG_EXTERN) ||
rt->symbol->hasFlag(FLAG_ITERATOR_RECORD))
{
INT_ASSERT(toCallExpr(call->parentExpr)->isPrimitive(PRIM_MOVE));
makeNoop(toCallExpr(call->parentExpr));
continue;
}
INT_FATAL(call, "PRIM_INIT should have already been handled");
}
}
}
}
}
}
static void insertRuntimeInitTemps() {
std::vector<BaseAST*> asts;
collect_asts_postorder(rootModule, asts);
// Collect asts which are definitions of VarSymbols that are type variables
// and are flagged as runtime types.
for_vector(BaseAST, ast, asts) {
if (DefExpr* def = toDefExpr(ast)) {
if (isVarSymbol(def->sym) &&
def->sym->hasFlag(FLAG_TYPE_VARIABLE) &&
def->sym->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
// Collapse these through the runtimeTypeMap ...
Type* rt = runtimeTypeMap.get(def->sym->type);
INT_ASSERT(rt);
def->sym->type = rt;
// ... and remove the type variable flag
// (Make these declarations look like normal vars.)
def->sym->removeFlag(FLAG_TYPE_VARIABLE);
}
}
}
replaceInitPrims(asts);
for_vector(BaseAST, ast1, asts) {
if (SymExpr* se = toSymExpr(ast1)) {
// remove dead type expressions
if (se->getStmtExpr() == se)
if (se->var->hasFlag(FLAG_TYPE_VARIABLE))
se->remove();
}
}
}
// Remove typedef definitions
static void removeInitFields()
{
forv_Vec(DefExpr, def, gDefExprs)
{
if (! def->inTree()) continue;
if (! def->init) continue;
if (! def->sym->hasFlag(FLAG_TYPE_VARIABLE)) continue;
def->init->remove();
def->init = NULL;
}
}
static void removeMootFields() {
// Remove type fields, parameter fields, and _promotionType field
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (type->defPoint && type->defPoint->parentSymbol) {
if (AggregateType* ct = toAggregateType(type->type)) {
for_fields(field, ct) {
if (field->hasFlag(FLAG_TYPE_VARIABLE) ||
field->isParameter() ||
!strcmp(field->name, "_promotionType"))
field->defPoint->remove();
}
}
}
}
}
static void expandInitFieldPrims()
{
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_INIT_FIELDS))
{
initializeClass(call, toSymExpr(call->get(1))->var);
call->remove();
}
}
}
static void
fixTypeNames(AggregateType* ct)
{
const char default_domain_name[] = "DefaultRectangularDom";
if (!ct->symbol->hasFlag(FLAG_BASE_ARRAY) && isArrayClass(ct))
{
const char* domain_type = ct->getField("dom")->type->symbol->name;
const char* elt_type = ct->getField("eltType")->type->symbol->name;
ct->symbol->name = astr("[", domain_type, "] ", elt_type);
}
if (ct->instantiatedFrom &&
!strcmp(ct->instantiatedFrom->symbol->name, default_domain_name)) {
ct->symbol->name = astr("domain", ct->symbol->name+strlen(default_domain_name));
}
if (isRecordWrappedType(ct)) {
ct->symbol->name = ct->getField("_valueType")->type->symbol->name;
}
}
static void
setScalarPromotionType(AggregateType* ct) {
for_fields(field, ct) {
if (!strcmp(field->name, "_promotionType"))
ct->scalarPromotionType = field->type;
}
}
Removing a TAB that my Mac emacs seems to still not get rid of
/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include "resolution.h"
#include "astutil.h"
#include "stlUtil.h"
#include "build.h"
#include "caches.h"
#include "callInfo.h"
#include "CForLoop.h"
#include "expr.h"
#include "ForLoop.h"
#include "iterator.h"
#include "ParamForLoop.h"
#include "passes.h"
#include "resolveIntents.h"
#include "scopeResolve.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "WhileStmt.h"
#include "../ifa/prim_data.h"
#include "view.h"
#include <inttypes.h>
#include <map>
#include <sstream>
#include <vector>
// Allow disambiguation tracing to be controlled by the command-line option
// --explain-verbose.
#define ENABLE_TRACING_OF_DISAMBIGUATION 1
#ifdef ENABLE_TRACING_OF_DISAMBIGUATION
#define TRACE_DISAMBIGUATE_BY_MATCH(...) \
if (developer && DC.explain) fprintf(stderr, __VA_ARGS__)
#else
#define TRACE_DISAMBIGUATE_BY_MATCH(...)
#endif
/** Contextual info used by the disambiguation process.
*
* This class wraps information that is used by multiple functions during the
* function disambiguation process.
*/
class DisambiguationContext {
public:
/// The actual arguments from the call site.
Vec<Symbol*>* actuals;
/// The scope in which the call is made.
Expr* scope;
/// Whether or not to print out tracing information.
bool explain;
/// Indexes used when printing out tracing information.
int i, j;
/** A simple constructor that initializes all of the values except i and j.
*
* \param actuals The actual arguments from the call site.
* \param scope A block representing the scope the call was made in.
* \param explain Whether or not a trace of this disambiguation process should
* be printed for the developer.
*/
DisambiguationContext(Vec<Symbol*>* actuals, Expr* scope, bool explain) :
actuals(actuals), scope(scope), explain(explain), i(-1), j(-1) {}
/** A helper function used to set the i and j members.
*
* \param i The index of the left-hand side of the comparison.
* \param j The index of the right-hand side of the comparison.
*
* \return A constant reference to this disambiguation context.
*/
const DisambiguationContext& forPair(int newI, int newJ) {
this->i = newI;
this->j = newJ;
return *this;
}
};
/** A wrapper for candidates for function call resolution.
*
* If a best candidate was found than the function member will point to it.
*/
class ResolutionCandidate {
public:
/// A pointer to the best candidate function.
FnSymbol* fn;
/** The actual arguments for the candidate, aligned so that they have the same
* index as their corresponding formal argument in alignedFormals.
*/
Vec<Symbol*> alignedActuals;
/** The formal arguments for the candidate, aligned so that they have the same
* index as their corresponding actual argument in alignedActuals.
*/
Vec<ArgSymbol*> alignedFormals;
/// A symbol map for substitutions that were made during the copying process.
SymbolMap substitutions;
/** The main constructor.
*
* \param fn A function that is a candidate for the resolution process.
*/
ResolutionCandidate(FnSymbol* function) : fn(function) {}
/** Compute the alignment of actual and formal arguments for the wrapped
* function and the current call site.
*
* \param info The CallInfo object corresponding to the call site.
*
* \return If a valid alignment was found.
*/
bool computeAlignment(CallInfo& info);
/// Compute substitutions for wrapped function that is generic.
void computeSubstitutions();
};
/// State information used during the disambiguation process.
class DisambiguationState {
public:
/// Is fn1 more specific than fn2?
bool fn1MoreSpecific;
/// Is fn2 more specific than fn1?
bool fn2MoreSpecific;
/// Does fn1 require promotion?
bool fn1Promotes;
/// Does fn2 require promotion?
bool fn2Promotes;
/// 1 == fn1, 2 == fn2, -1 == conflicting signals
int paramPrefers;
/// Initialize the state to the starting values.
DisambiguationState()
: fn1MoreSpecific(false), fn2MoreSpecific(false),
fn1Promotes(false), fn2Promotes(false), paramPrefers(0) {}
/** Prints out information for tracing of the disambiguation process.
*
* \param DBMLoc A string representing the location in the DBM process the
* message is coming from.
* \param DC The disambiguation context.
*/
void printSummary(const char* DBMLoc, const DisambiguationContext& DC) {
if (this->fn1MoreSpecific) {
TRACE_DISAMBIGUATE_BY_MATCH("\n%s: Fn %d is more specific than Fn %d\n", DBMLoc, DC.i, DC.j);
} else {
TRACE_DISAMBIGUATE_BY_MATCH("\n%s: Fn %d is NOT more specific than Fn %d\n", DBMLoc, DC.i, DC.j);
}
if (this->fn2MoreSpecific) {
TRACE_DISAMBIGUATE_BY_MATCH("%s: Fn %d is more specific than Fn %d\n", DBMLoc, DC.j, DC.i);
} else {
TRACE_DISAMBIGUATE_BY_MATCH("%s: Fn %d is NOT more specific than Fn %d\n", DBMLoc, DC.j, DC.i);
}
}
};
//#
//# Global Variables
//#
bool resolved = false;
bool inDynamicDispatchResolution = false;
SymbolMap paramMap;
//#
//# Static Variables
//#
static int explainCallLine;
static ModuleSymbol* explainCallModule;
static Vec<CallExpr*> inits;
static Vec<FnSymbol*> resolvedFormals;
Vec<CallExpr*> callStack;
static Vec<CondStmt*> tryStack;
static bool tryFailure = false;
static Map<Type*,Type*> runtimeTypeMap; // map static types to runtime types
// e.g. array and domain runtime types
static Map<Type*,FnSymbol*> valueToRuntimeTypeMap; // convertValueToRuntimeType
static Map<Type*,FnSymbol*> runtimeTypeToValueMap; // convertRuntimeTypeToValue
static std::map<std::string, std::pair<AggregateType*, FnSymbol*> > functionTypeMap; // lookup table/cache for function types and their representative parents
static std::map<FnSymbol*, FnSymbol*> functionCaptureMap; //loopup table/cache for function captures
// map of compiler warnings that may need to be reissued for repeated
// calls; the inner compiler warning map is from the compilerWarning
// function; the outer compiler warning map is from the function
// containing the compilerWarning function
// to do: this needs to be a map from functions to multiple strings in
// order to support multiple compiler warnings are allowed to
// be in a single function
static Map<FnSymbol*,const char*> innerCompilerWarningMap;
static Map<FnSymbol*,const char*> outerCompilerWarningMap;
Map<Type*,FnSymbol*> autoCopyMap; // type to chpl__autoCopy function
Map<Type*,FnSymbol*> autoDestroyMap; // type to chpl__autoDestroy function
Map<FnSymbol*,FnSymbol*> iteratorLeaderMap; // iterator->leader map for promotion
Map<FnSymbol*,FnSymbol*> iteratorFollowerMap; // iterator->leader map for promotion
//#
//# Static Function Declarations
//#
static bool hasRefField(Type *type);
static bool typeHasRefField(Type *type);
static FnSymbol* resolveUninsertedCall(Type* type, CallExpr* call);
static void makeRefType(Type* type);
static void resolveAutoCopy(Type* type);
static void resolveAutoDestroy(Type* type);
static void resolveOther();
static FnSymbol*
protoIteratorMethod(IteratorInfo* ii, const char* name, Type* retType);
static void protoIteratorClass(FnSymbol* fn);
static bool isInstantiatedField(Symbol* field);
static Symbol* determineQueriedField(CallExpr* call);
static void resolveSpecifiedReturnType(FnSymbol* fn);
static bool fits_in_int(int width, Immediate* imm);
static bool fits_in_uint(int width, Immediate* imm);
static bool canInstantiate(Type* actualType, Type* formalType);
static bool canParamCoerce(Type* actualType, Symbol* actualSym, Type* formalType);
static bool
moreSpecific(FnSymbol* fn, Type* actualType, Type* formalType);
static bool
computeActualFormalAlignment(FnSymbol* fn,
Vec<Symbol*>& alignedActuals,
Vec<ArgSymbol*>& alignedFormals,
CallInfo& info);
static Type*
getInstantiationType(Type* actualType, Type* formalType);
static void
computeGenericSubs(SymbolMap &subs,
FnSymbol* fn,
Vec<Symbol*>& alignedActuals);
static FnSymbol*
expandVarArgs(FnSymbol* origFn, int numActuals);
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info);
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates,
FnSymbol* fn,
CallInfo& info);
static BlockStmt* getParentBlock(Expr* expr);
static bool
isMoreVisibleInternal(BlockStmt* block, FnSymbol* fn1, FnSymbol* fn2,
Vec<BlockStmt*>& visited);
static bool
isMoreVisible(Expr* expr, FnSymbol* fn1, FnSymbol* fn2);
static bool explainCallMatch(CallExpr* call);
static CallExpr* userCall(CallExpr* call);
static void
printResolutionErrorAmbiguous(
Vec<FnSymbol*>& candidateFns,
CallInfo* info);
static void
printResolutionErrorUnresolved(
Vec<FnSymbol*>& visibleFns,
CallInfo* info);
static void issueCompilerError(CallExpr* call);
static void reissueCompilerWarning(const char* str, int offset);
BlockStmt* getVisibilityBlock(Expr* expr);
static void buildVisibleFunctionMap();
static BlockStmt*
getVisibleFunctions(BlockStmt* block,
const char* name,
Vec<FnSymbol*>& visibleFns,
Vec<BlockStmt*>& visited);
static Expr* resolve_type_expr(Expr* expr);
static void makeNoop(CallExpr* call);
static void resolveDefaultGenericType(CallExpr* call);
static void
gatherCandidates(Vec<ResolutionCandidate*>& candidates,
Vec<FnSymbol*>& visibleFns,
CallInfo& info);
static void resolveNormalCall(CallExpr* call);
static void lvalueCheck(CallExpr* call);
static void resolveTupleAndExpand(CallExpr* call);
static void resolveTupleExpand(CallExpr* call);
static void resolveSetMember(CallExpr* call);
static void resolveMove(CallExpr* call);
static void resolveNew(CallExpr* call);
static bool formalRequiresTemp(ArgSymbol* formal);
static void insertFormalTemps(FnSymbol* fn);
static void addLocalCopiesAndWritebacks(FnSymbol* fn, SymbolMap& formals2vars);
static Expr* dropUnnecessaryCast(CallExpr* call);
static AggregateType* createAndInsertFunParentClass(CallExpr *call, const char *name);
static FnSymbol* createAndInsertFunParentMethod(CallExpr *call, AggregateType *parent, AList &arg_list, bool isFormal, Type *retType);
static std::string buildParentName(AList &arg_list, bool isFormal, Type *retType);
static AggregateType* createOrFindFunTypeFromAnnotation(AList &arg_list, CallExpr *call);
static Expr* createFunctionAsValue(CallExpr *call);
static bool
isOuterVar(Symbol* sym, FnSymbol* fn, Symbol* parent = NULL);
static bool
usesOuterVars(FnSymbol* fn, Vec<FnSymbol*> &seen);
static Expr* preFold(Expr* expr);
static void foldEnumOp(int op, EnumSymbol *e1, EnumSymbol *e2, Immediate *imm);
static bool isSubType(Type* sub, Type* super);
static void insertValueTemp(Expr* insertPoint, Expr* actual);
FnSymbol* requiresImplicitDestroy(CallExpr* call);
static Expr* postFold(Expr* expr);
static Expr* resolveExpr(Expr* expr);
static void
computeReturnTypeParamVectors(BaseAST* ast,
Symbol* retSymbol,
Vec<Type*>& retTypes,
Vec<Symbol*>& retParams);
static void
replaceSetterArgWithTrue(BaseAST* ast, FnSymbol* fn);
static void
replaceSetterArgWithFalse(BaseAST* ast, FnSymbol* fn, Symbol* ret);
static void
insertCasts(BaseAST* ast, FnSymbol* fn, Vec<CallExpr*>& casts);
static void buildValueFunction(FnSymbol* fn);
static bool
possible_signature_match(FnSymbol* fn, FnSymbol* gn);
static bool signature_match(FnSymbol* fn, FnSymbol* gn);
static void
collectInstantiatedAggregateTypes(Vec<Type*>& icts, Type* ct);
static bool isVirtualChild(FnSymbol* child, FnSymbol* parent);
static void addToVirtualMaps(FnSymbol* pfn, AggregateType* ct);
static void addAllToVirtualMaps(FnSymbol* fn, AggregateType* ct);
static void buildVirtualMaps();
static void
addVirtualMethodTableEntry(Type* type, FnSymbol* fn, bool exclusive = false);
static void resolveTypedefedArgTypes(FnSymbol* fn);
static void computeStandardModuleSet();
static void unmarkDefaultedGenerics();
static void resolveUses(ModuleSymbol* mod);
static void resolveExports();
static void resolveEnumTypes();
static void resolveDynamicDispatches();
static void insertRuntimeTypeTemps();
static void resolveAutoCopies();
static void resolveRecordInitializers();
static void insertDynamicDispatchCalls();
static Type* buildRuntimeTypeInfo(FnSymbol* fn);
static void insertReturnTemps();
static void initializeClass(Expr* stmt, Symbol* sym);
static void handleRuntimeTypes();
static void pruneResolvedTree();
static void removeCompilerWarnings();
static void removeUnusedFunctions();
static void removeUnusedTypes();
static void buildRuntimeTypeInitFns();
static void buildRuntimeTypeInitFn(FnSymbol* fn, Type* runtimeType);
static void removeUnusedGlobals();
static void removeParamArgs();
static void removeRandomPrimitives();
static void removeActualNames();
static void removeTypeBlocks();
static void removeFormalTypeAndInitBlocks();
static void replaceTypeArgsWithFormalTypeTemps();
static void replaceValuesWithRuntimeTypes();
static void removeWhereClauses();
static void replaceReturnedValuesWithRuntimeTypes();
static Expr* resolvePrimInit(CallExpr* call);
static void insertRuntimeInitTemps();
static void removeInitFields();
static void removeMootFields();
static void expandInitFieldPrims();
static void fixTypeNames(AggregateType* ct);
static void setScalarPromotionType(AggregateType* ct);
bool ResolutionCandidate::computeAlignment(CallInfo& info) {
if (alignedActuals.n != 0) alignedActuals.clear();
if (alignedFormals.n != 0) alignedFormals.clear();
return computeActualFormalAlignment(fn, alignedActuals, alignedFormals, info);
}
void ResolutionCandidate::computeSubstitutions() {
if (substitutions.n != 0) substitutions.clear();
computeGenericSubs(substitutions, fn, alignedActuals);
}
static bool hasRefField(Type *type) {
if (isPrimitiveType(type)) return false;
if (type->symbol->hasFlag(FLAG_OBJECT_CLASS)) return false;
if (!isClass(type)) { // record or union
if (AggregateType *ct = toAggregateType(type)) {
for_fields(field, ct) {
if (hasRefField(field->type)) return true;
}
}
return false;
}
return true;
}
static bool typeHasRefField(Type *type) {
if (AggregateType *ct = toAggregateType(type)) {
for_fields(field, ct) {
if (hasRefField(field->typeInfo())) return true;
}
}
return false;
}
//
// build reference type
//
static FnSymbol*
resolveUninsertedCall(Type* type, CallExpr* call) {
if (type->defaultInitializer) {
if (type->defaultInitializer->instantiationPoint)
type->defaultInitializer->instantiationPoint->insertAtHead(call);
else
type->symbol->defPoint->insertBefore(call);
} else {
chpl_gen_main->insertAtHead(call);
}
resolveCall(call);
call->remove();
return call->isResolved();
}
// Fills in the refType field of a type
// with the type's corresponding reference type.
static void makeRefType(Type* type) {
if (!type)
// Should this be an assert?
return;
if (type->refType) {
// Already done.
return;
}
if (type == dtMethodToken ||
type == dtUnknown ||
type->symbol->hasFlag(FLAG_REF) ||
type->symbol->hasFlag(FLAG_GENERIC)) {
return;
}
CallExpr* call = new CallExpr("_type_construct__ref", type->symbol);
FnSymbol* fn = resolveUninsertedCall(type, call);
type->refType = toAggregateType(fn->retType);
type->refType->getField(1)->type = type;
if (type->symbol->hasFlag(FLAG_ATOMIC_TYPE))
type->refType->symbol->addFlag(FLAG_ATOMIC_TYPE);
}
static void
resolveAutoCopy(Type* type) {
SET_LINENO(type->symbol);
Symbol* tmp = newTemp(type);
chpl_gen_main->insertAtHead(new DefExpr(tmp));
CallExpr* call = new CallExpr("chpl__autoCopy", tmp);
FnSymbol* fn = resolveUninsertedCall(type, call);
resolveFns(fn);
autoCopyMap.put(type, fn);
tmp->defPoint->remove();
}
static void
resolveAutoDestroy(Type* type) {
SET_LINENO(type->symbol);
Symbol* tmp = newTemp(type);
chpl_gen_main->insertAtHead(new DefExpr(tmp));
CallExpr* call = new CallExpr("chpl__autoDestroy", tmp);
FnSymbol* fn = resolveUninsertedCall(type, call);
resolveFns(fn);
autoDestroyMap.put(type, fn);
tmp->defPoint->remove();
}
FnSymbol* getAutoCopy(Type *t) {
return autoCopyMap.get(t);
}
FnSymbol* getAutoDestroy(Type* t) {
return autoDestroyMap.get(t);
}
const char* toString(Type* type) {
return type->getValType()->symbol->name;
}
const char* toString(CallInfo* info) {
bool method = false;
bool _this = false;
const char *str = "";
if (info->actuals.n > 1)
if (info->actuals.head()->type == dtMethodToken)
method = true;
if (!strcmp("this", info->name)) {
_this = true;
method = false;
}
if (method) {
if (info->actuals.v[1] && info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE))
str = astr(str, "type ", toString(info->actuals.v[1]->type), ".");
else
str = astr(str, toString(info->actuals.v[1]->type), ".");
}
if (!developer && !strncmp("_type_construct_", info->name, 16)) {
str = astr(str, info->name+16);
} else if (!developer && !strncmp("_construct_", info->name, 11)) {
str = astr(str, info->name+11);
} else if (!_this) {
str = astr(str, info->name);
}
if (!info->call->methodTag) {
if (info->call->square)
str = astr(str, "[");
else
str = astr(str, "(");
}
bool first = false;
int start = 0;
if (method)
start = 2;
if (_this)
start = 2;
for (int i = start; i < info->actuals.n; i++) {
if (!first)
first = true;
else
str = astr(str, ", ");
if (info->actualNames.v[i])
str = astr(str, info->actualNames.v[i], "=");
VarSymbol* var = toVarSymbol(info->actuals.v[i]);
if (info->actuals.v[i]->type->symbol->hasFlag(FLAG_ITERATOR_RECORD) &&
info->actuals.v[i]->type->defaultInitializer->hasFlag(FLAG_PROMOTION_WRAPPER))
str = astr(str, "promoted expression");
else if (info->actuals.v[i] && info->actuals.v[i]->hasFlag(FLAG_TYPE_VARIABLE))
str = astr(str, "type ", toString(info->actuals.v[i]->type));
else if (var && var->immediate) {
if (var->immediate->const_kind == CONST_KIND_STRING) {
str = astr(str, "\"", var->immediate->v_string, "\"");
} else {
const size_t bufSize = 512;
char buff[bufSize];
snprint_imm(buff, bufSize, *var->immediate);
str = astr(str, buff);
}
} else
str = astr(str, toString(info->actuals.v[i]->type));
}
if (!info->call->methodTag) {
if (info->call->square)
str = astr(str, "]");
else
str = astr(str, ")");
}
return str;
}
const char* toString(FnSymbol* fn) {
if (fn->userString) {
if (developer)
return astr(fn->userString, " [", istr(fn->id), "]");
else
return fn->userString;
}
const char* str;
int start = 0;
if (developer) {
// report the name as-is and include all args
str = fn->name;
} else {
if (fn->instantiatedFrom)
fn = fn->instantiatedFrom;
if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
// if not, make sure 'str' is built as desired
INT_ASSERT(!strncmp("_type_construct_", fn->name, 16));
str = astr(fn->name+16);
} else if (fn->hasFlag(FLAG_CONSTRUCTOR)) {
INT_ASSERT(!strncmp("_construct_", fn->name, 11));
str = astr(fn->name+11);
} else if (fn->isPrimaryMethod()) {
if (!strcmp(fn->name, "this")) {
INT_ASSERT(fn->hasFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION));
str = astr(toString(fn->getFormal(2)->type));
start = 1;
} else {
INT_ASSERT(! fn->hasFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION));
str = astr(toString(fn->getFormal(2)->type), ".", fn->name);
start = 2;
}
} else if (fn->hasFlag(FLAG_MODULE_INIT)) {
INT_ASSERT(!strncmp("chpl__init_", fn->name, 11)); //if not, fix next line
str = astr("top-level module statements for ", fn->name+11);
} else
str = astr(fn->name);
} // if !developer
bool skipParens =
fn->hasFlag(FLAG_NO_PARENS) ||
(fn->hasFlag(FLAG_TYPE_CONSTRUCTOR) && fn->numFormals() == 0) ||
(fn->hasFlag(FLAG_MODULE_INIT) && !developer);
if (!skipParens)
str = astr(str, "(");
bool first = false;
for (int i = start; i < fn->numFormals(); i++) {
ArgSymbol* arg = fn->getFormal(i+1);
if (arg->hasFlag(FLAG_IS_MEME))
continue;
if (!first) {
first = true;
if (skipParens)
str = astr(str, " ");
} else
str = astr(str, ", ");
if (arg->intent == INTENT_PARAM || arg->hasFlag(FLAG_INSTANTIATED_PARAM))
str = astr(str, "param ");
if (arg->hasFlag(FLAG_TYPE_VARIABLE))
str = astr(str, "type ", arg->name);
else if (arg->type == dtUnknown) {
SymExpr* sym = NULL;
if (arg->typeExpr)
sym = toSymExpr(arg->typeExpr->body.tail);
if (sym)
str = astr(str, arg->name, ": ", sym->var->name);
else
str = astr(str, arg->name);
} else if (arg->type == dtAny) {
str = astr(str, arg->name);
} else
str = astr(str, arg->name, ": ", toString(arg->type));
if (arg->variableExpr)
str = astr(str, " ...");
}
if (!skipParens)
str = astr(str, ")");
if (developer)
str = astr(str, " [", istr(fn->id), "]");
return str;
}
static FnSymbol*
protoIteratorMethod(IteratorInfo* ii, const char* name, Type* retType) {
FnSymbol* fn = new FnSymbol(name);
fn->addFlag(FLAG_AUTO_II);
if (strcmp(name, "advance"))
fn->addFlag(FLAG_INLINE);
fn->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
fn->addFlag(FLAG_METHOD);
fn->_this = new ArgSymbol(INTENT_BLANK, "this", ii->iclass);
fn->_this->addFlag(FLAG_ARG_THIS);
fn->retType = retType;
fn->insertFormalAtTail(fn->_this);
ii->iterator->defPoint->insertBefore(new DefExpr(fn));
normalize(fn);
// Pretend that this function is already resolved.
// Its body will be filled in during the lowerIterators pass.
fn->addFlag(FLAG_RESOLVED);
return fn;
}
static void
protoIteratorClass(FnSymbol* fn) {
INT_ASSERT(!fn->iteratorInfo);
SET_LINENO(fn);
IteratorInfo* ii = new IteratorInfo();
fn->iteratorInfo = ii;
fn->iteratorInfo->iterator = fn;
const char* className = astr(fn->name);
if (fn->_this)
className = astr(className, "_", fn->_this->type->symbol->cname);
ii->iclass = new AggregateType(AGGREGATE_CLASS);
TypeSymbol* cts = new TypeSymbol(astr("_ic_", className), ii->iclass);
cts->addFlag(FLAG_ITERATOR_CLASS);
add_root_type(ii->iclass); // Add super : dtObject.
fn->defPoint->insertBefore(new DefExpr(cts));
ii->irecord = new AggregateType(AGGREGATE_RECORD);
TypeSymbol* rts = new TypeSymbol(astr("_ir_", className), ii->irecord);
rts->addFlag(FLAG_ITERATOR_RECORD);
if (fn->retTag == RET_REF)
rts->addFlag(FLAG_REF_ITERATOR_CLASS);
fn->defPoint->insertBefore(new DefExpr(rts));
ii->tag = it_iterator;
ii->advance = protoIteratorMethod(ii, "advance", dtVoid);
ii->zip1 = protoIteratorMethod(ii, "zip1", dtVoid);
ii->zip2 = protoIteratorMethod(ii, "zip2", dtVoid);
ii->zip3 = protoIteratorMethod(ii, "zip3", dtVoid);
ii->zip4 = protoIteratorMethod(ii, "zip4", dtVoid);
ii->hasMore = protoIteratorMethod(ii, "hasMore", dtInt[INT_SIZE_DEFAULT]);
ii->getValue = protoIteratorMethod(ii, "getValue", fn->retType);
ii->init = protoIteratorMethod(ii, "init", dtVoid);
ii->incr = protoIteratorMethod(ii, "incr", dtVoid);
// The original iterator function is stashed in the defaultInitializer field
// of the iterator record type. Since we are only creating shell functions
// here, we still need a way to obtain the original iterator function, so we
// can fill in the bodies of the above 9 methods in the lowerIterators pass.
ii->irecord->defaultInitializer = fn;
ii->irecord->scalarPromotionType = fn->retType;
fn->retType = ii->irecord;
fn->retTag = RET_VALUE;
makeRefType(fn->retType);
ii->getIterator = new FnSymbol("_getIterator");
ii->getIterator->addFlag(FLAG_AUTO_II);
ii->getIterator->addFlag(FLAG_INLINE);
ii->getIterator->retType = ii->iclass;
ii->getIterator->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "ir", ii->irecord));
VarSymbol* ret = newTemp("_ic_", ii->iclass);
ii->getIterator->insertAtTail(new DefExpr(ret));
CallExpr* icAllocCall = callChplHereAlloc(ret->typeInfo()->symbol);
ii->getIterator->insertAtTail(new CallExpr(PRIM_MOVE, ret, icAllocCall));
ii->getIterator->insertAtTail(new CallExpr(PRIM_SETCID, ret));
ii->getIterator->insertAtTail(new CallExpr(PRIM_RETURN, ret));
fn->defPoint->insertBefore(new DefExpr(ii->getIterator));
// The _getIterator function is stashed in the defaultInitializer field of
// the iterator class type. This makes it easy to obtain the iterator given
// just a symbol of the iterator class type. This may include _getIterator
// and _getIteratorZip functions in the module code.
ii->iclass->defaultInitializer = ii->getIterator;
normalize(ii->getIterator);
resolveFns(ii->getIterator); // No shortcuts.
}
//
// returns true if the field was instantiated
//
static bool
isInstantiatedField(Symbol* field) {
TypeSymbol* ts = toTypeSymbol(field->defPoint->parentSymbol);
INT_ASSERT(ts);
AggregateType* ct = toAggregateType(ts->type);
INT_ASSERT(ct);
for_formals(formal, ct->defaultTypeConstructor) {
if (!strcmp(field->name, formal->name))
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
return true;
}
return false;
}
//
// determine field associated with query expression
//
static Symbol*
determineQueriedField(CallExpr* call) {
AggregateType* ct = toAggregateType(call->get(1)->getValType());
INT_ASSERT(ct);
SymExpr* last = toSymExpr(call->get(call->numActuals()));
INT_ASSERT(last);
VarSymbol* var = toVarSymbol(last->var);
INT_ASSERT(var && var->immediate);
if (var->immediate->const_kind == CONST_KIND_STRING) {
// field queried by name
return ct->getField(var->immediate->v_string, false);
} else {
// field queried by position
int position = var->immediate->int_value();
Vec<ArgSymbol*> args;
for_formals(arg, ct->defaultTypeConstructor) {
args.add(arg);
}
for (int i = 2; i < call->numActuals(); i++) {
SymExpr* actual = toSymExpr(call->get(i));
INT_ASSERT(actual);
VarSymbol* var = toVarSymbol(actual->var);
INT_ASSERT(var && var->immediate && var->immediate->const_kind == CONST_KIND_STRING);
for (int j = 0; j < args.n; j++) {
if (args.v[j] && !strcmp(args.v[j]->name, var->immediate->v_string))
args.v[j] = NULL;
}
}
forv_Vec(ArgSymbol, arg, args) {
if (arg) {
if (position == 1)
return ct->getField(arg->name, false);
position--;
}
}
}
return NULL;
}
//
// For some types, e.g. _domain/_array records, implementing
// Chapel's ref/out/... intents can be done simply by passing the
// value itself, rather than address-of. This function flags such cases
// by returning false, meaning "not OK to convert".
//
static bool
okToConvertFormalToRefType(Type* type) {
if (isRecordWrappedType(type))
// no, don't
return false;
// otherwise, proceed with the original plan
return true;
}
static void
resolveSpecifiedReturnType(FnSymbol* fn) {
resolveBlockStmt(fn->retExprType);
fn->retType = fn->retExprType->body.tail->typeInfo();
if (fn->retType != dtUnknown) {
if (fn->retTag == RET_REF) {
makeRefType(fn->retType);
fn->retType = fn->retType->refType;
}
fn->retExprType->remove();
if (fn->isIterator() && !fn->iteratorInfo) {
protoIteratorClass(fn);
}
}
}
//
// Generally, atomics must also be passed by reference when
// passed by blank intent. The following expression checks for
// these cases by looking for atomics passed by blank intent and
// changing their type to a ref type. Interestingly, this
// conversion does not seem to be required for single-locale
// compilation, but it is for multi-locale. Otherwise, updates
// to atomics are lost (as demonstrated by
// test/functions/bradc/intents/test_pass_atomic.chpl).
//
// I say "generally" because there are a few cases where passing
// atomics by reference breaks things -- primarily in
// constructors, assignment operators, and tuple construction.
// So we have some unfortunate special checks that dance around
// these cases.
//
// While I can't explain precisely why these special cases are
// required yet, here are the tests that tend to have problems
// without these special conditions:
//
// test/release/examples/benchmarks/hpcc/ra-atomics.chpl
// test/types/atomic/sungeun/no_atomic_assign.chpl
// test/functions/bradc/intents/test_construct_atomic_intent.chpl
// test/users/vass/barrierWF.test-1.chpl
// test/studies/shootout/spectral-norm/spectralnorm.chpl
// test/release/examples/benchmarks/ssca2/SSCA2_main.chpl
// test/parallel/taskPar/sungeun/barrier/*.chpl
//
static bool convertAtomicFormalTypeToRef(ArgSymbol* formal, FnSymbol* fn) {
return (formal->intent == INTENT_BLANK &&
!formal->hasFlag(FLAG_TYPE_VARIABLE) &&
isAtomicType(formal->type))
&& !fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR)
&& !fn->hasFlag(FLAG_CONSTRUCTOR)
&& strcmp(fn->name,"=") != 0
&& !fn->hasFlag(FLAG_BUILD_TUPLE);
}
void
resolveFormals(FnSymbol* fn) {
static Vec<FnSymbol*> done;
if (!fn->hasFlag(FLAG_GENERIC)) {
if (done.set_in(fn))
return;
done.set_add(fn);
for_formals(formal, fn) {
if (formal->type == dtUnknown) {
if (!formal->typeExpr) {
formal->type = dtObject;
} else {
resolveBlockStmt(formal->typeExpr);
formal->type = formal->typeExpr->body.tail->getValType();
}
}
//
// Fix up value types that need to be ref types.
//
if (formal->type->symbol->hasFlag(FLAG_REF))
// Already a ref type, so done.
continue;
if (formal->intent == INTENT_INOUT ||
formal->intent == INTENT_OUT ||
formal->intent == INTENT_REF ||
formal->intent == INTENT_CONST_REF ||
convertAtomicFormalTypeToRef(formal, fn) ||
formal->hasFlag(FLAG_WRAP_WRITTEN_FORMAL) ||
(formal == fn->_this &&
(isUnion(formal->type) ||
isRecord(formal->type)))) {
if (okToConvertFormalToRefType(formal->type)) {
makeRefType(formal->type);
formal->type = formal->type->refType;
// The type of the formal is its own ref type!
}
}
}
if (fn->retExprType)
resolveSpecifiedReturnType(fn);
resolvedFormals.set_add(fn);
}
}
static bool fits_in_int_helper(int width, int64_t val) {
switch (width) {
default: INT_FATAL("bad width in fits_in_int_helper");
case 1:
return (val == 0 || val == 1);
case 8:
return (val >= INT8_MIN && val <= INT8_MAX);
case 16:
return (val >= INT16_MIN && val <= INT16_MAX);
case 32:
return (val >= INT32_MIN && val <= INT32_MAX);
case 64:
// As an int64_t will always fit within a 64 bit int.
return true;
}
}
static bool fits_in_int(int width, Immediate* imm) {
if (imm->const_kind == NUM_KIND_INT && imm->num_index == INT_SIZE_DEFAULT) {
int64_t i = imm->int_value();
return fits_in_int_helper(width, i);
}
/* BLC: There is some question in my mind about whether this
function should include the following code as well -- that is,
whether default-sized uint params should get the same special
treatment in cases like this. I didn't enable it for now because
nothing seemed to rely on it and I didn't come up with a case
that would. But it's worth keeping around for future
consideration.
Similarly, we may want to consider enabling such param casts for
int sizes other then default-width.
else if (imm->const_kind == NUM_KIND_UINT &&
imm->num_index == INT_SIZE_DEFAULT) {
uint64_t u = imm->uint_value();
int64_t i = (int64_t)u;
if (i < 0)
return false;
return fits_in_int_helper(width, i);
}*/
return false;
}
static bool fits_in_uint_helper(int width, uint64_t val) {
switch (width) {
default: INT_FATAL("bad width in fits_in_uint_helper");
case 8:
return (val <= UINT8_MAX);
case 16:
return (val <= UINT16_MAX);
case 32:
return (val <= UINT32_MAX);
case 64:
// As a uint64_t will always fit inside a 64 bit uint.
return true;
}
}
static bool fits_in_uint(int width, Immediate* imm) {
if (imm->const_kind == NUM_KIND_INT && imm->num_index == INT_SIZE_DEFAULT) {
int64_t i = imm->int_value();
if (i < 0)
return false;
return fits_in_uint_helper(width, (uint64_t)i);
}
/* BLC: See comment just above in fits_in_int()...
else if (imm->const_kind == NUM_KIND_UINT && imm->num_index == INT_SIZE_64) {
uint64_t u = imm->uint_value();
return fits_in_uint_helper(width, u);
}*/
return false;
}
static void ensureEnumTypeResolved(EnumType* etype) {
INT_ASSERT( etype != NULL );
if( ! etype->integerType ) {
// Make sure to resolve all enum types.
for_enums(def, etype) {
if (def->init) {
Expr* enumTypeExpr =
resolve_type_expr(def->init);
Type* enumtype = enumTypeExpr->typeInfo();
if (enumtype == dtUnknown)
INT_FATAL(def->init, "Unable to resolve enumerator type expression");
// printf("Type of %s.%s is %s\n", etype->symbol->name, def->sym->name,
// enumtype->symbol->name);
}
}
// Now try computing the enum size...
etype->sizeAndNormalize();
}
INT_ASSERT(etype->integerType != NULL);
}
// Is this a legal actual argument where an l-value is required?
// I.e. for an out/inout/ref formal.
static bool
isLegalLvalueActualArg(ArgSymbol* formal, Expr* actual) {
if (SymExpr* se = toSymExpr(actual))
if (se->var->hasFlag(FLAG_EXPR_TEMP) ||
((se->var->hasFlag(FLAG_REF_TO_CONST) ||
se->var->isConstant()) && !formal->hasFlag(FLAG_ARG_THIS)) ||
se->var->isParameter())
if (okToConvertFormalToRefType(formal->type) ||
// If the user says 'const', it means 'const'.
// Honor FLAG_CONST if it is a coerce temp, too.
(se->var->hasFlag(FLAG_CONST) &&
(!se->var->hasFlag(FLAG_TEMP) || se->var->hasFlag(FLAG_COERCE_TEMP))
))
return false;
// Perhaps more checks are needed.
return true;
}
// Is this a legal actual argument for a 'const ref' formal?
// At present, params cannot be passed to 'const ref'.
static bool
isLegalConstRefActualArg(ArgSymbol* formal, Expr* actual) {
if (SymExpr* se = toSymExpr(actual))
if (se->var->isParameter())
if (okToConvertFormalToRefType(formal->type))
return false;
// Perhaps more checks are needed.
return true;
}
// Returns true iff dispatching the actualType to the formalType
// results in an instantiation.
static bool
canInstantiate(Type* actualType, Type* formalType) {
if (actualType == dtMethodToken)
return false;
if (formalType == dtAny)
return true;
if (formalType == dtIntegral && (is_int_type(actualType) || is_uint_type(actualType)))
return true;
if (formalType == dtAnyEnumerated && (is_enum_type(actualType)))
return true;
if (formalType == dtNumeric &&
(is_int_type(actualType) || is_uint_type(actualType) || is_imag_type(actualType) ||
is_real_type(actualType) || is_complex_type(actualType)))
return true;
if (formalType == dtString && actualType==dtStringC)
return true;
if (formalType == dtStringC && actualType==dtStringCopy)
return true;
if (formalType == dtIteratorRecord && actualType->symbol->hasFlag(FLAG_ITERATOR_RECORD))
return true;
if (formalType == dtIteratorClass && actualType->symbol->hasFlag(FLAG_ITERATOR_CLASS))
return true;
if (actualType == formalType)
return true;
if (actualType->instantiatedFrom && canInstantiate(actualType->instantiatedFrom, formalType))
return true;
return false;
}
//
// returns true if dispatching from actualType to formalType results
// in a compile-time coercion; this is a subset of canCoerce below as,
// for example, real(32) cannot be coerced to real(64) at compile-time
//
static bool canParamCoerce(Type* actualType, Symbol* actualSym, Type* formalType) {
if (is_bool_type(formalType) && is_bool_type(actualType))
return true;
if (is_int_type(formalType)) {
if (is_bool_type(actualType))
return true;
if (is_int_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
if (is_uint_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
//
// If the actual is an enum, check to see if *all* its values
// are small enough that they fit into this integer width
//
if (EnumType* etype = toEnumType(actualType)) {
ensureEnumTypeResolved(etype);
if (get_width(etype->getIntegerType()) <= get_width(formalType))
return true;
}
//
// For smaller integer types, if the argument is a param, does it
// store a value that's small enough that it could dispatch to
// this argument?
//
if (get_width(formalType) < 64) {
if (VarSymbol* var = toVarSymbol(actualSym))
if (var->immediate)
if (fits_in_int(get_width(formalType), var->immediate))
return true;
if (EnumType* etype = toEnumType(actualType)) {
ensureEnumTypeResolved(etype);
if (EnumSymbol* enumsym = toEnumSymbol(actualSym)) {
if (Immediate* enumval = enumsym->getImmediate()) {
if (fits_in_int(get_width(formalType), enumval)) {
return true;
}
}
}
}
}
}
if (is_uint_type(formalType)) {
if (is_bool_type(actualType))
return true;
if (is_uint_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
if (VarSymbol* var = toVarSymbol(actualSym))
if (var->immediate)
if (fits_in_uint(get_width(formalType), var->immediate))
return true;
}
return false;
}
//
// returns true iff dispatching the actualType to the formalType
// results in a coercion.
//
bool
canCoerce(Type* actualType, Symbol* actualSym, Type* formalType, FnSymbol* fn, bool* promotes) {
if (canParamCoerce(actualType, actualSym, formalType))
return true;
if (is_real_type(formalType)) {
if ((is_int_type(actualType) || is_uint_type(actualType))
&& get_width(formalType) >= 64)
return true;
if (is_real_type(actualType) &&
get_width(actualType) < get_width(formalType))
return true;
}
if (is_complex_type(formalType)) {
if ((is_int_type(actualType) || is_uint_type(actualType))
&& get_width(formalType) >= 128)
return true;
if (is_real_type(actualType) &&
(get_width(actualType) <= get_width(formalType)/2))
return true;
if (is_imag_type(actualType) &&
(get_width(actualType) <= get_width(formalType)/2))
return true;
if (is_complex_type(actualType) &&
(get_width(actualType) < get_width(formalType)))
return true;
}
if (isSyncType(actualType)) {
Type* baseType = actualType->getField("base_type")->type;
return canDispatch(baseType, NULL, formalType, fn, promotes);
}
if (actualType->symbol->hasFlag(FLAG_REF))
return canDispatch(actualType->getValType(), NULL, formalType, fn, promotes);
if (// isLcnSymbol(actualSym) && // What does this exclude?
actualType == dtStringC && formalType == dtString)
return true;
if (formalType == dtStringC && actualType == dtStringCopy)
return true;
if (formalType == dtString && actualType == dtStringCopy)
return true;
return false;
}
// Returns true iff the actualType can dispatch to the formalType.
// The function symbol is used to avoid scalar promotion on =.
// param is set if the actual is a parameter (compile-time constant).
bool
canDispatch(Type* actualType, Symbol* actualSym, Type* formalType, FnSymbol* fn, bool* promotes, bool paramCoerce) {
if (promotes)
*promotes = false;
if (actualType == formalType)
return true;
//
// The following check against FLAG_REF ensures that 'nil' can't be
// passed to a by-ref argument (for example, an atomic type). I
// found that without this, calls like autocopy(nil) became
// ambiguous when given the choice between the completely generic
// autocopy(x) and the autocopy(x: atomic int) (represented as
// autocopy(x: ref(atomic int)) internally).
//
if (actualType == dtNil && isClass(formalType) &&
!formalType->symbol->hasFlag(FLAG_REF))
return true;
if (actualType->refType == formalType)
return true;
if (!paramCoerce && canCoerce(actualType, actualSym, formalType, fn, promotes))
return true;
if (paramCoerce && canParamCoerce(actualType, actualSym, formalType))
return true;
forv_Vec(Type, parent, actualType->dispatchParents) {
if (parent == formalType || canDispatch(parent, NULL, formalType, fn, promotes)) {
return true;
}
}
if (fn &&
strcmp(fn->name, "=") &&
actualType->scalarPromotionType &&
(canDispatch(actualType->scalarPromotionType, NULL, formalType, fn))) {
if (promotes)
*promotes = true;
return true;
}
return false;
}
bool
isDispatchParent(Type* t, Type* pt) {
forv_Vec(Type, p, t->dispatchParents)
if (p == pt || isDispatchParent(p, pt))
return true;
return false;
}
static bool
moreSpecific(FnSymbol* fn, Type* actualType, Type* formalType) {
if (canDispatch(actualType, NULL, formalType, fn))
return true;
if (canInstantiate(actualType, formalType)) {
return true;
}
return false;
}
static bool
computeActualFormalAlignment(FnSymbol* fn,
Vec<Symbol*>& alignedActuals,
Vec<ArgSymbol*>& alignedFormals,
CallInfo& info) {
alignedActuals.fill(fn->numFormals());
alignedFormals.fill(info.actuals.n);
// Match named actuals against formal names in the function signature.
// Record successful matches.
for (int i = 0; i < alignedFormals.n; i++) {
if (info.actualNames.v[i]) {
bool match = false;
int j = 0;
for_formals(formal, fn) {
if (!strcmp(info.actualNames.v[i], formal->name)) {
match = true;
alignedFormals.v[i] = formal;
alignedActuals.v[j] = info.actuals.v[i];
break;
}
j++;
}
// Fail if no matching formal is found.
if (!match)
return false;
}
}
// Fill in unmatched formals in sequence with the remaining actuals.
// Record successful substitutions.
int j = 0;
ArgSymbol* formal = (fn->numFormals()) ? fn->getFormal(1) : NULL;
for (int i = 0; i < alignedFormals.n; i++) {
if (!info.actualNames.v[i]) {
bool match = false;
while (formal) {
if (formal->variableExpr)
return (fn->hasFlag(FLAG_GENERIC)) ? true : false;
if (!alignedActuals.v[j]) {
match = true;
alignedFormals.v[i] = formal;
alignedActuals.v[j] = info.actuals.v[i];
break;
}
formal = next_formal(formal);
j++;
}
// Fail if there are too many unnamed actuals.
if (!match && !(fn->hasFlag(FLAG_GENERIC) && fn->hasFlag(FLAG_TUPLE)))
return false;
}
}
// Make sure that any remaining formals are matched by name
// or have a default value.
while (formal) {
if (!alignedActuals.v[j] && !formal->defaultExpr)
// Fail if not.
return false;
formal = next_formal(formal);
j++;
}
return true;
}
//
// returns the type that a formal type should be instantiated to when
// instantiated by a given actual type
//
static Type*
getInstantiationType(Type* actualType, Type* formalType) {
if (canInstantiate(actualType, formalType)) {
return actualType;
}
if (Type* st = actualType->scalarPromotionType) {
if (canInstantiate(st, formalType))
return st;
}
if (Type* vt = actualType->getValType()) {
if (canInstantiate(vt, formalType))
return vt;
else if (Type* st = vt->scalarPromotionType)
if (canInstantiate(st, formalType))
return st;
}
return NULL;
}
static void
computeGenericSubs(SymbolMap &subs,
FnSymbol* fn,
Vec<Symbol*>& alignedActuals) {
int i = 0;
for_formals(formal, fn) {
if (formal->intent == INTENT_PARAM) {
if (alignedActuals.v[i] && alignedActuals.v[i]->isParameter()) {
if (!formal->type->symbol->hasFlag(FLAG_GENERIC) ||
canInstantiate(alignedActuals.v[i]->type, formal->type))
subs.put(formal, alignedActuals.v[i]);
} else if (!alignedActuals.v[i] && formal->defaultExpr) {
// break because default expression may reference generic
// arguments earlier in formal list; make those substitutions
// first (test/classes/bradc/paramInClass/weirdParamInit4)
if (subs.n)
break;
resolveBlockStmt(formal->defaultExpr);
SymExpr* se = toSymExpr(formal->defaultExpr->body.tail);
if (se && se->var->isParameter() &&
(!formal->type->symbol->hasFlag(FLAG_GENERIC) || canInstantiate(se->var->type, formal->type)))
subs.put(formal, se->var);
else
INT_FATAL(fn, "unable to handle default parameter");
}
} else if (formal->type->symbol->hasFlag(FLAG_GENERIC)) {
//
// check for field with specified generic type
//
if (!formal->hasFlag(FLAG_TYPE_VARIABLE) && formal->type != dtAny &&
strcmp(formal->name, "outer") && strcmp(formal->name, "meme") &&
(fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)))
USR_FATAL(formal, "invalid generic type specification on class field");
if (alignedActuals.v[i]) {
if (Type* type = getInstantiationType(alignedActuals.v[i]->type, formal->type)) {
// String literal actuals aligned with non-param generic
// formals of type dtAny will result in an instantiation of
// a dtString formal. This is in line with variable
// declarations with non-typed initializing expressions and
// non-param formals with string literal default expressions
// (see fix_def_expr() and hack_resolve_types() in
// normalize.cpp). This conversion is not performed for extern
// functions.
if ((!fn->hasFlag(FLAG_EXTERN)) && (formal->type == dtAny) &&
(!formal->hasFlag(FLAG_PARAM)) && (type == dtStringC) &&
(alignedActuals.v[i]->type == dtStringC) &&
(alignedActuals.v[i]->isImmediate()))
subs.put(formal, dtString->symbol);
else
subs.put(formal, type->symbol);
}
} else if (formal->defaultExpr) {
// break because default expression may reference generic
// arguments earlier in formal list; make those substitutions
// first (test/classes/bradc/genericTypes)
if (subs.n)
break;
resolveBlockStmt(formal->defaultExpr);
Type* defaultType = formal->defaultExpr->body.tail->typeInfo();
if (defaultType == dtTypeDefaultToken)
subs.put(formal, dtTypeDefaultToken->symbol);
else if (Type* type = getInstantiationType(defaultType, formal->type))
subs.put(formal, type->symbol);
}
}
i++;
}
}
/** Common code for multiple paths through expandVarArgs.
*
* This code handles the case where the number of varargs are known at compile
* time. It inserts the necessary code to copy the values into and out of the
* varargs tuple.
*/
static void
handleSymExprInExpandVarArgs(FnSymbol* workingFn, ArgSymbol* formal, SymExpr* sym) {
workingFn->addFlag(FLAG_EXPANDED_VARARGS);
// Handle specified number of variable arguments.
if (VarSymbol* n_var = toVarSymbol(sym->var)) {
if (n_var->type == dtInt[INT_SIZE_DEFAULT] && n_var->immediate) {
int n = n_var->immediate->int_value();
CallExpr* tupleCall = new CallExpr((formal->hasFlag(FLAG_TYPE_VARIABLE)) ?
"_type_construct__tuple" : "_construct__tuple");
for (int i = 0; i < n; i++) {
DefExpr* new_arg_def = formal->defPoint->copy();
ArgSymbol* new_formal = toArgSymbol(new_arg_def->sym);
new_formal->variableExpr = NULL;
tupleCall->insertAtTail(new SymExpr(new_formal));
new_formal->name = astr("_e", istr(i), "_", formal->name);
new_formal->cname = astr("_e", istr(i), "_", formal->cname);
formal->defPoint->insertBefore(new_arg_def);
}
VarSymbol* var = new VarSymbol(formal->name);
// Replace mappings to the old formal with mappings to the new variable.
if (workingFn->hasFlag(FLAG_PARTIAL_COPY)) {
for (int index = workingFn->partialCopyMap.n; --index >= 0;) {
SymbolMapElem& mapElem = workingFn->partialCopyMap.v[index];
if (mapElem.value == formal) {
mapElem.value = var;
break;
}
}
}
if (formal->hasFlag(FLAG_TYPE_VARIABLE)) {
var->addFlag(FLAG_TYPE_VARIABLE);
}
if (formal->intent == INTENT_OUT || formal->intent == INTENT_INOUT) {
int i = 1;
for_actuals(actual, tupleCall) {
VarSymbol* tmp = newTemp("_varargs_tmp_");
workingFn->insertBeforeReturnAfterLabel(new DefExpr(tmp));
workingFn->insertBeforeReturnAfterLabel(new CallExpr(PRIM_MOVE, tmp, new CallExpr(var, new_IntSymbol(i))));
workingFn->insertBeforeReturnAfterLabel(new CallExpr("=", actual->copy(), tmp));
i++;
}
}
tupleCall->insertAtHead(new_IntSymbol(n));
workingFn->insertAtHead(new CallExpr(PRIM_MOVE, var, tupleCall));
workingFn->insertAtHead(new DefExpr(var));
formal->defPoint->remove();
if (workingFn->hasFlag(FLAG_PARTIAL_COPY)) {
// If this is a partial copy, store the mapping for substitution later.
workingFn->partialCopyMap.put(formal, var);
} else {
// Otherwise, do the substitution now.
subSymbol(workingFn->body, formal, var);
}
if (workingFn->where) {
VarSymbol* var = new VarSymbol(formal->name);
if (formal->hasFlag(FLAG_TYPE_VARIABLE)) {
var->addFlag(FLAG_TYPE_VARIABLE);
}
workingFn->where->insertAtHead(new CallExpr(PRIM_MOVE, var, tupleCall->copy()));
workingFn->where->insertAtHead(new DefExpr(var));
subSymbol(workingFn->where, formal, var);
}
}
}
}
static FnSymbol*
expandVarArgs(FnSymbol* origFn, int numActuals) {
bool genericArgSeen = false;
FnSymbol* workingFn = origFn;
SymbolMap substitutions;
static Map<FnSymbol*,Vec<FnSymbol*>*> cache;
// check for cached stamped out function
if (Vec<FnSymbol*>* cfns = cache.get(origFn)) {
forv_Vec(FnSymbol, cfn, *cfns) {
if (cfn->numFormals() == numActuals) return cfn;
}
}
for_formals(formal, origFn) {
if (workingFn != origFn) {
formal = toArgSymbol(substitutions.get(formal));
}
if (!genericArgSeen && formal->variableExpr && !isDefExpr(formal->variableExpr->body.tail)) {
resolveBlockStmt(formal->variableExpr);
}
/*
* Set genericArgSeen to true if a generic argument appears before the
* argument with the variable expression.
*/
// INT_ASSERT(arg->type);
// Adding 'ref' intent to the "ret" arg of
// inline proc =(ref ret:syserr, x:syserr) { __primitive("=", ret, x); }
// in SysBasic.chpl:150 causes a segfault.
// The addition of the arg->type test in the folloiwng conditional is a
// workaround.
// A better approach would be to add a check that each formal of a function
// has a type (if that can be expected) and then fix the fault where it occurs.
if (formal->type && formal->type->symbol->hasFlag(FLAG_GENERIC)) {
genericArgSeen = true;
}
if (!formal->variableExpr) {
continue;
}
// Handle unspecified variable number of arguments.
if (DefExpr* def = toDefExpr(formal->variableExpr->body.tail)) {
int numCopies = numActuals - workingFn->numFormals() + 1;
if (numCopies <= 0) {
if (workingFn != origFn) delete workingFn;
return NULL;
}
if (workingFn == origFn) {
workingFn = origFn->copy(&substitutions);
INT_ASSERT(! workingFn->hasFlag(FLAG_RESOLVED));
workingFn->addFlag(FLAG_INVISIBLE_FN);
origFn->defPoint->insertBefore(new DefExpr(workingFn));
formal = static_cast<ArgSymbol*>(substitutions.get(formal));
}
Symbol* newSym = substitutions.get(def->sym);
SymExpr* newSymExpr = new SymExpr(new_IntSymbol(numCopies));
newSym->defPoint->replace(newSymExpr);
subSymbol(workingFn, newSym, new_IntSymbol(numCopies));
handleSymExprInExpandVarArgs(workingFn, formal, newSymExpr);
genericArgSeen = false;
} else if (SymExpr* sym = toSymExpr(formal->variableExpr->body.tail)) {
handleSymExprInExpandVarArgs(workingFn, formal, sym);
} else if (!workingFn->hasFlag(FLAG_GENERIC)) {
INT_FATAL("bad variableExpr");
}
}
Vec<FnSymbol*>* cfns = cache.get(origFn);
if (cfns == NULL) {
cfns = new Vec<FnSymbol*>();
}
cfns->add(workingFn);
cache.put(origFn, cfns);
return workingFn;
}
static void
resolve_type_constructor(FnSymbol* fn, CallInfo& info) {
SET_LINENO(fn);
CallExpr* typeConstructorCall = new CallExpr(astr("_type", fn->name));
for_formals(formal, fn) {
if (strcmp(formal->name, "meme")) {
if (fn->_this->type->symbol->hasFlag(FLAG_TUPLE)) {
if (formal->instantiatedFrom) {
typeConstructorCall->insertAtTail(formal->type->symbol);
} else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) {
typeConstructorCall->insertAtTail(paramMap.get(formal));
}
} else {
if (!strcmp(formal->name, "outer") || formal->type == dtMethodToken) {
typeConstructorCall->insertAtTail(formal);
} else if (formal->instantiatedFrom) {
typeConstructorCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal->type->symbol)));
} else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) {
typeConstructorCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(paramMap.get(formal))));
}
}
}
}
info.call->insertBefore(typeConstructorCall);
resolveCall(typeConstructorCall);
INT_ASSERT(typeConstructorCall->isResolved());
resolveFns(typeConstructorCall->isResolved());
fn->_this->type = typeConstructorCall->isResolved()->retType;
typeConstructorCall->remove();
}
/** Candidate filtering logic specific to concrete functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterConcreteCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
currCandidate->fn = expandVarArgs(currCandidate->fn, info.actuals.n);
if (!currCandidate->fn) return;
resolveTypedefedArgTypes(currCandidate->fn);
if (!currCandidate->computeAlignment(info)) {
return;
}
/*
* Make sure that type constructor is resolved before other constructors.
*/
if (currCandidate->fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR)) {
resolve_type_constructor(currCandidate->fn, info);
}
/*
* A derived generic type will use the type of its parent, and expects this to
* be instantiated before it is.
*/
resolveFormals(currCandidate->fn);
int coindex = -1;
for_formals(formal, currCandidate->fn) {
if (Symbol* actual = currCandidate->alignedActuals.v[++coindex]) {
if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) {
return;
}
if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formal->hasFlag(FLAG_INSTANTIATED_PARAM))) {
return;
}
}
}
candidates.add(currCandidate);
}
/** Candidate filtering logic specific to generic functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterGenericCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
currCandidate->fn = expandVarArgs(currCandidate->fn, info.actuals.n);
if (!currCandidate->fn) return;
if (!currCandidate->computeAlignment(info)) {
return;
}
/*
* Early rejection of generic functions.
*/
int coindex = 0;
for_formals(formal, currCandidate->fn) {
if (formal->type != dtUnknown) {
if (Symbol* actual = currCandidate->alignedActuals.v[coindex]) {
if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) {
return;
}
if (formal->type->symbol->hasFlag(FLAG_GENERIC)) {
Type* vt = actual->getValType();
Type* st = actual->type->scalarPromotionType;
Type* svt = (vt) ? vt->scalarPromotionType : NULL;
if (!canInstantiate(actual->type, formal->type) &&
(!vt || !canInstantiate(vt, formal->type)) &&
(!st || !canInstantiate(st, formal->type)) &&
(!svt || !canInstantiate(svt, formal->type))) {
return;
}
} else {
if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formal->hasFlag(FLAG_INSTANTIATED_PARAM))) {
return;
}
}
}
}
++coindex;
}
// Compute the param/type substitutions for generic arguments.
currCandidate->computeSubstitutions();
/*
* If no substitutions were made we can't instantiate this generic, and must
* reject it.
*/
if (currCandidate->substitutions.n > 0) {
/*
* Instantiate just enough of the generic to get through the rest of the
* filtering and disambiguation processes.
*/
currCandidate->fn = instantiateSignature(currCandidate->fn, currCandidate->substitutions, info.call);
if (currCandidate->fn != NULL) {
filterCandidate(candidates, currCandidate, info);
}
}
}
/** Tests to see if a function is a candidate for resolving a specific call. If
* it is a candidate, we add it to the candidate lists.
*
* This version of filterCandidate is called by other versions of
* filterCandidate, and shouldn't be called outside this family of functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates,
ResolutionCandidate* currCandidate,
CallInfo& info) {
if (currCandidate->fn->hasFlag(FLAG_GENERIC)) {
filterGenericCandidate(candidates, currCandidate, info);
} else {
filterConcreteCandidate(candidates, currCandidate, info);
}
}
/** Tests to see if a function is a candidate for resolving a specific call. If
* it is a candidate, we add it to the candidate lists.
*
* This version of filterCandidate is called by code outside the filterCandidate
* family of functions.
*
* \param candidates The list to add possible candidates to.
* \param currCandidate The current candidate to consider.
* \param info The CallInfo object for the call site.
*/
static void
filterCandidate(Vec<ResolutionCandidate*>& candidates, FnSymbol* fn, CallInfo& info) {
ResolutionCandidate* currCandidate = new ResolutionCandidate(fn);
filterCandidate(candidates, currCandidate, info);
if (candidates.tail() != currCandidate) {
// The candidate was not accepted. Time to clean it up.
delete currCandidate;
}
}
static BlockStmt*
getParentBlock(Expr* expr) {
for (Expr* tmp = expr->parentExpr; tmp; tmp = tmp->parentExpr) {
if (BlockStmt* block = toBlockStmt(tmp))
return block;
}
if (expr->parentSymbol) {
FnSymbol* parentFn = toFnSymbol(expr->parentSymbol);
if (parentFn && parentFn->instantiationPoint)
return parentFn->instantiationPoint;
else if (expr->parentSymbol->defPoint)
return getParentBlock(expr->parentSymbol->defPoint);
}
return NULL;
}
//
// helper routine for isMoreVisible (below);
//
static bool
isMoreVisibleInternal(BlockStmt* block, FnSymbol* fn1, FnSymbol* fn2,
Vec<BlockStmt*>& visited) {
//
// fn1 is more visible
//
if (fn1->defPoint->parentExpr == block)
return true;
//
// fn2 is more visible
//
if (fn2->defPoint->parentExpr == block)
return false;
visited.set_add(block);
//
// default to true if neither are visible
//
bool moreVisible = true;
//
// ensure f2 is not more visible via parent block, and recurse
//
if (BlockStmt* parentBlock = getParentBlock(block))
if (!visited.set_in(parentBlock))
moreVisible &= isMoreVisibleInternal(parentBlock, fn1, fn2, visited);
//
// ensure f2 is not more visible via module uses, and recurse
//
if (block && block->modUses) {
for_actuals(expr, block->modUses) {
SymExpr* se = toSymExpr(expr);
INT_ASSERT(se);
ModuleSymbol* mod = toModuleSymbol(se->var);
INT_ASSERT(mod);
if (!visited.set_in(mod->block))
moreVisible &= isMoreVisibleInternal(mod->block, fn1, fn2, visited);
}
}
return moreVisible;
}
//
// return true if fn1 is more visible than fn2 from expr
//
// assumption: fn1 and fn2 are visible from expr; if this assumption
// is violated, this function will return true
//
static bool
isMoreVisible(Expr* expr, FnSymbol* fn1, FnSymbol* fn2) {
//
// common-case check to see if functions have equal visibility
//
if (fn1->defPoint->parentExpr == fn2->defPoint->parentExpr) {
// Special check which makes cg-initializers inferior to user-defined constructors
// with the same args.
if (fn2->hasFlag(FLAG_DEFAULT_CONSTRUCTOR))
return true;
return false;
}
//
// call helper function with visited set to avoid infinite recursion
//
Vec<BlockStmt*> visited;
BlockStmt* block = toBlockStmt(expr);
if (!block)
block = getParentBlock(expr);
return isMoreVisibleInternal(block, fn1, fn2, visited);
}
static bool paramWorks(Symbol* actual, Type* formalType) {
Immediate* imm = NULL;
if (VarSymbol* var = toVarSymbol(actual)) {
imm = var->immediate;
}
if (EnumSymbol* enumsym = toEnumSymbol(actual)) {
ensureEnumTypeResolved(toEnumType(enumsym->type));
imm = enumsym->getImmediate();
}
if (imm) {
if (is_int_type(formalType)) {
return fits_in_int(get_width(formalType), imm);
}
if (is_uint_type(formalType)) {
return fits_in_uint(get_width(formalType), imm);
}
}
return false;
}
//
// This is a utility function that essentially tracks which function,
// if any, the param arguments prefer.
//
static inline void registerParamPreference(int& paramPrefers, int preference,
const char* argstr,
DisambiguationContext DC) {
if (paramPrefers == 0 || paramPrefers == preference) {
/* if the param currently has no preference or it matches the new
preference, preserve the current preference */
paramPrefers = preference;
TRACE_DISAMBIGUATE_BY_MATCH("param prefers %s\n", argstr);
} else {
/* otherwise its preference contradicts the previous arguments, so
mark it as not preferring either */
paramPrefers = -1;
TRACE_DISAMBIGUATE_BY_MATCH("param prefers differing things\n");
}
}
static bool considerParamMatches(Type* actualtype,
Type* arg1type, Type* arg2type) {
/* BLC: Seems weird to have to add this; could just add it in the enum
case if enums have to be special-cased here. Otherwise, how are the
int cases handled later...? */
if (actualtype->symbol->hasFlag(FLAG_REF)) {
actualtype = actualtype->getValType();
}
if (actualtype == arg1type && actualtype != arg2type) {
return true;
}
// If we don't have an exact match in the previous line, let's see if
// we have a bool(w1) passed to bool(w2) or non-bool case; This is
// based on the enum case developed in r20208
if (is_bool_type(actualtype) && is_bool_type(arg1type) && !is_bool_type(arg2type)) {
return true;
}
// Otherwise, have bool cast to default-sized integer over a smaller size
if (is_bool_type(actualtype) && actualtype != arg1type && actualtype != arg2type) {
return considerParamMatches(dtInt[INT_SIZE_DEFAULT], arg1type, arg2type);
}
if (is_enum_type(actualtype) && actualtype != arg1type && actualtype != arg2type) {
return considerParamMatches(dtInt[INT_SIZE_DEFAULT], arg1type, arg2type);
}
if (isSyncType(actualtype) && actualtype != arg1type && actualtype != arg2type) {
return considerParamMatches(actualtype->getField("base_type")->type,
arg1type, arg2type);
}
return false;
}
/** Compare two argument mappings, given a set of actual arguments, and set the
* disambiguation state appropriately.
*
* This function implements the argument mapping comparison component of the
* disambiguation procedure as detailed in section 13.14.3 of the Chapel
* language specification (page 107).
*
* \param fn1 The first function to be compared.
* \param formal1 The formal argument that correspond to the actual argument
* for the first function.
* \param fn2 The second function to be compared.
* \param formal2 The formal argument that correspond to the actual argument
* for the second function.
* \param actual The actual argument from the call site.
* \param DC The disambiguation context.
* \param DS The disambiguation state.
*/
static void testArgMapping(FnSymbol* fn1, ArgSymbol* formal1,
FnSymbol* fn2, ArgSymbol* formal2,
Symbol* actual,
const DisambiguationContext& DC,
DisambiguationState& DS) {
// We only want to deal with the value types here, avoiding odd overloads
// working (or not) due to _ref.
Type *f1Type = formal1->type->getValType();
Type *f2Type = formal2->type->getValType();
Type *actualType = actual->type->getValType();
TRACE_DISAMBIGUATE_BY_MATCH("Actual's type: %s\n", toString(actualType));
bool formal1Promotes = false;
canDispatch(actualType, actual, f1Type, fn1, &formal1Promotes);
DS.fn1Promotes |= formal1Promotes;
TRACE_DISAMBIGUATE_BY_MATCH("Formal 1's type: %s\n", toString(f1Type));
if (formal1Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("Actual requires promotion to match formal 1\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Actual DOES NOT require promotion to match formal 1\n");
}
if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 1 is an instantiated param.\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 1 is NOT an instantiated param.\n");
}
bool formal2Promotes = false;
canDispatch(actualType, actual, f2Type, fn1, &formal2Promotes);
DS.fn2Promotes |= formal2Promotes;
TRACE_DISAMBIGUATE_BY_MATCH("Formal 2's type: %s\n", toString(f2Type));
if (formal2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("Actual requires promotion to match formal 2\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Actual DOES NOT require promotion to match formal 2\n");
}
if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 2 is an instantiated param.\n");
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Formal 2 is NOT an instantiated param.\n");
}
if (f1Type == f2Type && formal1->hasFlag(FLAG_INSTANTIATED_PARAM) && !formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("A: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (f1Type == f2Type && !formal1->hasFlag(FLAG_INSTANTIATED_PARAM) && formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
TRACE_DISAMBIGUATE_BY_MATCH("B: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (!formal1Promotes && formal2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("C: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (formal1Promotes && !formal2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("D: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (f1Type == f2Type && !formal1->instantiatedFrom && formal2->instantiatedFrom) {
TRACE_DISAMBIGUATE_BY_MATCH("E: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (f1Type == f2Type && formal1->instantiatedFrom && !formal2->instantiatedFrom) {
TRACE_DISAMBIGUATE_BY_MATCH("F: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (formal1->instantiatedFrom != dtAny && formal2->instantiatedFrom == dtAny) {
TRACE_DISAMBIGUATE_BY_MATCH("G: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (formal1->instantiatedFrom == dtAny && formal2->instantiatedFrom != dtAny) {
TRACE_DISAMBIGUATE_BY_MATCH("H: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (considerParamMatches(actualType, f1Type, f2Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("In first param case\n");
// The actual matches formal1's type, but not formal2's
if (paramWorks(actual, f2Type)) {
// but the actual is a param and works for formal2
if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) {
// the param works equally well for both, but
// matches the first slightly better if we had to
// decide
registerParamPreference(DS.paramPrefers, 1, "formal1", DC);
} else if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
registerParamPreference(DS.paramPrefers, 2, "formal2", DC);
} else {
// neither is a param, but formal1 is an exact type
// match, so prefer that one
registerParamPreference(DS.paramPrefers, 1, "formal1", DC);
}
} else {
TRACE_DISAMBIGUATE_BY_MATCH("I: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
}
} else if (considerParamMatches(actualType, f2Type, f1Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("In second param case\n");
// The actual matches formal2's type, but not formal1's
if (paramWorks(actual, f1Type)) {
// but the actual is a param and works for formal1
if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) {
// the param works equally well for both, but
// matches the second slightly better if we had to
// decide
registerParamPreference(DS.paramPrefers, 2, "formal2", DC);
} else if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) {
registerParamPreference(DS.paramPrefers, 1, "formal1", DC);
} else {
// neither is a param, but formal1 is an exact type
// match, so prefer that one
registerParamPreference(DS.paramPrefers, 2, "formal2", DC);
}
} else {
TRACE_DISAMBIGUATE_BY_MATCH("J: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
}
} else if (moreSpecific(fn1, f1Type, f2Type) && f2Type != f1Type) {
TRACE_DISAMBIGUATE_BY_MATCH("K: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (moreSpecific(fn1, f2Type, f1Type) && f2Type != f1Type) {
TRACE_DISAMBIGUATE_BY_MATCH("L: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (is_int_type(f1Type) && is_uint_type(f2Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("M: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (is_int_type(f2Type) && is_uint_type(f1Type)) {
TRACE_DISAMBIGUATE_BY_MATCH("N: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else {
TRACE_DISAMBIGUATE_BY_MATCH("O: no information gained from argument\n");
}
}
/** Determines if fn1 is a better match than fn2.
*
* This function implements the function comparison component of the
* disambiguation procedure as detailed in section 13.14.3 of the Chapel
* language specification (page 106).
*
* \param candidate1 The function on the left-hand side of the comparison.
* \param candidate2 The function on the right-hand side of the comparison.
* \param DC The disambiguation context.
*
* \return True if fn1 is a more specific function than f2, false otherwise.
*/
static bool isBetterMatch(ResolutionCandidate* candidate1,
ResolutionCandidate* candidate2,
const DisambiguationContext& DC) {
DisambiguationState DS;
for (int k = 0; k < candidate1->alignedFormals.n; ++k) {
Symbol* actual = DC.actuals->v[k];
ArgSymbol* formal1 = candidate1->alignedFormals.v[k];
ArgSymbol* formal2 = candidate2->alignedFormals.v[k];
TRACE_DISAMBIGUATE_BY_MATCH("\nLooking at argument %d\n", k);
testArgMapping(candidate1->fn, formal1, candidate2->fn, formal2, actual, DC, DS);
}
if (!DS.fn1Promotes && DS.fn2Promotes) {
TRACE_DISAMBIGUATE_BY_MATCH("\nP: Fn %d does not require argument promotion; Fn %d does\n", DC.i, DC.j);
DS.printSummary("P", DC);
return true;
}
if (!(DS.fn1MoreSpecific || DS.fn2MoreSpecific)) {
// If the decision hasn't been made based on the argument mappings...
if (isMoreVisible(DC.scope, candidate1->fn, candidate2->fn)) {
TRACE_DISAMBIGUATE_BY_MATCH("\nQ: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (isMoreVisible(DC.scope, candidate2->fn, candidate1->fn)) {
TRACE_DISAMBIGUATE_BY_MATCH("\nR: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (DS.paramPrefers == 1) {
TRACE_DISAMBIGUATE_BY_MATCH("\nS: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (DS.paramPrefers == 2) {
TRACE_DISAMBIGUATE_BY_MATCH("\nT: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
} else if (candidate1->fn->where && !candidate2->fn->where) {
TRACE_DISAMBIGUATE_BY_MATCH("\nU: Fn %d is more specific\n", DC.i);
DS.fn1MoreSpecific = true;
} else if (!candidate1->fn->where && candidate2->fn->where) {
TRACE_DISAMBIGUATE_BY_MATCH("\nV: Fn %d is more specific\n", DC.j);
DS.fn2MoreSpecific = true;
}
}
DS.printSummary("W", DC);
return DS.fn1MoreSpecific && !DS.fn2MoreSpecific;
}
/** Find the best candidate from a list of candidates.
*
* This function finds the best Chapel function from a set of candidates, given
* a call site. This is an implementation of 13.14.3 of the Chapel language
* specification (page 106).
*
* \param candidates A list of the candidate functions, from which the best
* match is selected.
* \param DC The disambiguation context.
*
* \return The result of the disambiguation process.
*/
static ResolutionCandidate*
disambiguateByMatch(Vec<ResolutionCandidate*>& candidates, DisambiguationContext DC) {
// If index i is set then we can skip testing function F_i because we already
// know it can not be the best match.
std::vector<bool> notBest(candidates.n, false);
for (int i = 0; i < candidates.n; ++i) {
TRACE_DISAMBIGUATE_BY_MATCH("##########################\n");
TRACE_DISAMBIGUATE_BY_MATCH("# Considering function %d #\n", i);
TRACE_DISAMBIGUATE_BY_MATCH("##########################\n\n");
ResolutionCandidate* candidate1 = candidates.v[i];
bool best = true; // is fn1 the best candidate?
TRACE_DISAMBIGUATE_BY_MATCH("%s\n\n", toString(candidate1->fn));
if (notBest[i]) {
TRACE_DISAMBIGUATE_BY_MATCH("Already known to not be best match. Skipping.\n\n");
continue;
}
for (int j = 0; j < candidates.n; ++j) {
if (i == j) continue;
TRACE_DISAMBIGUATE_BY_MATCH("Comparing to function %d\n", j);
TRACE_DISAMBIGUATE_BY_MATCH("-----------------------\n");
ResolutionCandidate* candidate2 = candidates.v[j];
TRACE_DISAMBIGUATE_BY_MATCH("%s\n", toString(candidate2->fn));
if (isBetterMatch(candidate1, candidate2, DC.forPair(i, j))) {
TRACE_DISAMBIGUATE_BY_MATCH("X: Fn %d is a better match than Fn %d\n\n\n", i, j);
notBest[j] = true;
} else {
TRACE_DISAMBIGUATE_BY_MATCH("X: Fn %d is NOT a better match than Fn %d\n\n\n", i, j);
best = false;
break;
}
}
if (best) {
TRACE_DISAMBIGUATE_BY_MATCH("Y: Fn %d is the best match.\n\n\n", i);
return candidate1;
} else {
TRACE_DISAMBIGUATE_BY_MATCH("Y: Fn %d is NOT the best match.\n\n\n", i);
}
}
TRACE_DISAMBIGUATE_BY_MATCH("Z: No non-ambiguous best match.\n\n");
return NULL;
}
static bool
explainCallMatch(CallExpr* call) {
if (!call->isNamed(fExplainCall))
return false;
if (explainCallModule && explainCallModule != call->getModule())
return false;
if (explainCallLine != -1 && explainCallLine != call->linenum())
return false;
return true;
}
static CallExpr*
userCall(CallExpr* call) {
if (developer)
return call;
// If the called function is compiler-generated or is in one of the internal
// modules, back up the stack until a call is encountered whose target
// function is neither.
// TODO: This function should be rewritten so each test appears only once.
if (call->getFunction()->hasFlag(FLAG_COMPILER_GENERATED) ||
call->getModule()->modTag == MOD_INTERNAL) {
for (int i = callStack.n-1; i >= 0; i--) {
if (!callStack.v[i]->getFunction()->hasFlag(FLAG_COMPILER_GENERATED) &&
callStack.v[i]->getModule()->modTag != MOD_INTERNAL)
return callStack.v[i];
}
}
return call;
}
static void
printResolutionErrorAmbiguous(
Vec<FnSymbol*>& candidates,
CallInfo* info) {
CallExpr* call = userCall(info->call);
if (!strcmp("this", info->name)) {
USR_FATAL(call, "ambiguous access of '%s' by '%s'",
toString(info->actuals.v[1]->type),
toString(info));
} else {
const char* entity = "call";
if (!strncmp("_type_construct_", info->name, 16))
entity = "type specifier";
const char* str = toString(info);
if (info->scope) {
ModuleSymbol* mod = toModuleSymbol(info->scope->parentSymbol);
INT_ASSERT(mod);
str = astr(mod->name, ".", str);
}
USR_FATAL_CONT(call, "ambiguous %s '%s'", entity, str);
if (developer) {
for (int i = callStack.n-1; i>=0; i--) {
CallExpr* cs = callStack.v[i];
FnSymbol* f = cs->getFunction();
if (f->instantiatedFrom)
USR_PRINT(callStack.v[i], " instantiated from %s", f->name);
else
break;
}
}
bool printed_one = false;
forv_Vec(FnSymbol, fn, candidates) {
USR_PRINT(fn, "%s %s",
printed_one ? " " : "candidates are:",
toString(fn));
printed_one = true;
}
USR_STOP();
}
}
static void
printResolutionErrorUnresolved(
Vec<FnSymbol*>& visibleFns,
CallInfo* info) {
CallExpr* call = userCall(info->call);
if (!strcmp("_cast", info->name)) {
if (!info->actuals.head()->hasFlag(FLAG_TYPE_VARIABLE)) {
USR_FATAL(call, "illegal cast to non-type",
toString(info->actuals.v[1]->type),
toString(info->actuals.v[0]->type));
} else {
USR_FATAL(call, "illegal cast from %s to %s",
toString(info->actuals.v[1]->type),
toString(info->actuals.v[0]->type));
}
} else if (!strcmp("free", info->name)) {
if (info->actuals.n > 0 &&
isRecord(info->actuals.v[2]->type))
USR_FATAL(call, "delete not allowed on records");
} else if (!strcmp("these", info->name)) {
if (info->actuals.n == 2 &&
info->actuals.v[0]->type == dtMethodToken)
USR_FATAL(call, "cannot iterate over values of type %s",
toString(info->actuals.v[1]->type));
} else if (!strcmp("_type_construct__tuple", info->name)) {
if (info->call->argList.length == 0)
USR_FATAL(call, "tuple size must be specified");
SymExpr* sym = toSymExpr(info->call->get(1));
if (!sym || !sym->var->isParameter()) {
USR_FATAL(call, "tuple size must be static");
} else {
USR_FATAL(call, "invalid tuple");
}
} else if (!strcmp("=", info->name)) {
if (info->actuals.v[0] && !info->actuals.v[0]->hasFlag(FLAG_TYPE_VARIABLE) &&
info->actuals.v[1] && info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE)) {
USR_FATAL(call, "illegal assignment of type to value");
} else if (info->actuals.v[0] && info->actuals.v[0]->hasFlag(FLAG_TYPE_VARIABLE) &&
info->actuals.v[1] && !info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE)) {
USR_FATAL(call, "illegal assignment of value to type");
} else if (info->actuals.v[1]->type == dtNil) {
USR_FATAL(call, "type mismatch in assignment from nil to %s",
toString(info->actuals.v[0]->type));
} else {
USR_FATAL(call, "type mismatch in assignment from %s to %s",
toString(info->actuals.v[1]->type),
toString(info->actuals.v[0]->type));
}
} else if (!strcmp("this", info->name)) {
Type* type = info->actuals.v[1]->getValType();
if (type->symbol->hasFlag(FLAG_ITERATOR_RECORD)) {
USR_FATAL(call, "illegal access of iterator or promoted expression");
} else if (type->symbol->hasFlag(FLAG_FUNCTION_CLASS)) {
USR_FATAL(call, "illegal access of first class function");
} else {
USR_FATAL(call, "unresolved access of '%s' by '%s'",
toString(info->actuals.v[1]->type),
toString(info));
}
} else {
const char* entity = "call";
if (!strncmp("_type_construct_", info->name, 16))
entity = "type specifier";
const char* str = toString(info);
if (info->scope) {
ModuleSymbol* mod = toModuleSymbol(info->scope->parentSymbol);
INT_ASSERT(mod);
str = astr(mod->name, ".", str);
}
USR_FATAL_CONT(call, "unresolved %s '%s'", entity, str);
if (visibleFns.n > 0) {
if (developer) {
for (int i = callStack.n-1; i>=0; i--) {
CallExpr* cs = callStack.v[i];
FnSymbol* f = cs->getFunction();
if (f->instantiatedFrom)
USR_PRINT(callStack.v[i], " instantiated from %s", f->name);
else
break;
}
}
bool printed_one = false;
forv_Vec(FnSymbol, fn, visibleFns) {
// Consider "visible functions are"
USR_PRINT(fn, "%s %s",
printed_one ? " " : "candidates are:",
toString(fn));
printed_one = true;
}
}
if (visibleFns.n == 1 &&
visibleFns.v[0]->numFormals() == 0
&& !strncmp("_type_construct_", info->name, 16))
USR_PRINT(call, "did you forget the 'new' keyword?");
USR_STOP();
}
}
static void issueCompilerError(CallExpr* call) {
//
// Disable compiler warnings in internal modules that are triggered
// within a dynamic dispatch context because of potential user
// confusion. Removed the following code and See the following
// tests:
//
// test/arrays/bradc/workarounds/arrayOfSpsArray.chpl
// test/arrays/deitz/part4/test_array_of_associative_arrays.chpl
// test/classes/bradc/arrayInClass/genericArrayInClass-otharrs.chpl
//
if (call->isPrimitive(PRIM_WARNING))
if (inDynamicDispatchResolution)
if (call->getModule()->modTag == MOD_INTERNAL &&
callStack.head()->getModule()->modTag == MOD_INTERNAL)
return;
//
// If an errorDepth was specified, report a diagnostic about the call
// that deep into the callStack. The default depth is 1.
//
FnSymbol* fn = toFnSymbol(call->parentSymbol);
VarSymbol* depthParam = toVarSymbol(paramMap.get(toDefExpr(fn->formals.tail)->sym));
int64_t depth;
bool foundDepthVal;
if (depthParam && depthParam->immediate &&
depthParam->immediate->const_kind == NUM_KIND_INT) {
depth = depthParam->immediate->int_value();
foundDepthVal = true;
} else {
depth = 1;
foundDepthVal = false;
}
if (depth > callStack.n - 1) {
if (foundDepthVal)
USR_WARN(call, "compiler diagnostic depth value exceeds call stack depth");
depth = callStack.n - 1;
}
if (depth < 0) {
USR_WARN(call, "compiler diagnostic depth value can not be negative");
depth = 0;
}
CallExpr* from = NULL;
for (int i = callStack.n-1 - depth; i >= 0; i--) {
from = callStack.v[i];
// We report calls whose target function is not compiler-generated and is
// not defined in one of the internal modules.
if (from->linenum() > 0 &&
from->getModule()->modTag != MOD_INTERNAL &&
!from->getFunction()->hasFlag(FLAG_COMPILER_GENERATED))
break;
}
const char* str = "";
for_formals(arg, fn) {
if (foundDepthVal && arg->defPoint == fn->formals.tail)
continue;
VarSymbol* var = toVarSymbol(paramMap.get(arg));
INT_ASSERT(var && var->immediate && var->immediate->const_kind == CONST_KIND_STRING);
str = astr(str, var->immediate->v_string);
}
if (call->isPrimitive(PRIM_ERROR)) {
USR_FATAL(from, "%s", str);
} else {
USR_WARN(from, "%s", str);
}
if (FnSymbol* fn = toFnSymbol(callStack.tail()->isResolved()))
innerCompilerWarningMap.put(fn, str);
if (FnSymbol* fn = toFnSymbol(callStack.v[callStack.n-1 - depth]->isResolved()))
outerCompilerWarningMap.put(fn, str);
}
static void reissueCompilerWarning(const char* str, int offset) {
//
// Disable compiler warnings in internal modules that are triggered
// within a dynamic dispatch context because of potential user
// confusion. See note in 'issueCompileError' above.
//
if (inDynamicDispatchResolution)
if (callStack.tail()->getModule()->modTag == MOD_INTERNAL &&
callStack.head()->getModule()->modTag == MOD_INTERNAL)
return;
CallExpr* from = NULL;
for (int i = callStack.n-offset; i >= 0; i--) {
from = callStack.v[i];
// We report calls whose target function is not compiler-generated and is
// not defined in one of the internal modules.
if (from->linenum() > 0 &&
from->getModule()->modTag != MOD_INTERNAL &&
!from->getFunction()->hasFlag(FLAG_COMPILER_GENERATED))
break;
}
USR_WARN(from, "%s", str);
}
class VisibleFunctionBlock {
public:
Map<const char*,Vec<FnSymbol*>*> visibleFunctions;
VisibleFunctionBlock() { }
};
static Map<BlockStmt*,VisibleFunctionBlock*> visibleFunctionMap;
static int nVisibleFunctions = 0; // for incremental build
static Map<BlockStmt*,BlockStmt*> visibilityBlockCache;
static Vec<BlockStmt*> standardModuleSet;
//
// return true if expr is a CondStmt with chpl__tryToken as its condition
//
static bool isTryTokenCond(Expr* expr) {
CondStmt* cond = toCondStmt(expr);
if (!cond) return false;
SymExpr* sym = toSymExpr(cond->condExpr);
if (!sym) return false;
return sym->var == gTryToken;
}
//
// return the innermost block for searching for visible functions
//
BlockStmt*
getVisibilityBlock(Expr* expr) {
if (BlockStmt* block = toBlockStmt(expr->parentExpr)) {
if (block->blockTag == BLOCK_SCOPELESS)
return getVisibilityBlock(block);
else if (block->parentExpr && isTryTokenCond(block->parentExpr)) {
// Make the visibility block of the then and else blocks of a
// conditional using chpl__tryToken be the block containing the
// conditional statement. Without this, there were some cases where
// a function gets instantiated into one side of the conditional but
// used in both sides, then the side with the instantiation gets
// folded out leaving expressions with no visibility block.
// test/functions/iterators/angeles/dynamic.chpl is an example that
// currently fails without this.
return getVisibilityBlock(block->parentExpr);
} else
return block;
} else if (expr->parentExpr) {
return getVisibilityBlock(expr->parentExpr);
} else if (Symbol* s = expr->parentSymbol) {
FnSymbol* fn = toFnSymbol(s);
if (fn && fn->instantiationPoint)
return fn->instantiationPoint;
else
return getVisibilityBlock(s->defPoint);
} else {
INT_FATAL(expr, "Expresion has no visibility block.");
return NULL;
}
}
static void buildVisibleFunctionMap() {
for (int i = nVisibleFunctions; i < gFnSymbols.n; i++) {
FnSymbol* fn = gFnSymbols.v[i];
if (!fn->hasFlag(FLAG_INVISIBLE_FN) && fn->defPoint->parentSymbol && !isArgSymbol(fn->defPoint->parentSymbol)) {
BlockStmt* block = NULL;
if (fn->hasFlag(FLAG_AUTO_II)) {
block = theProgram->block;
} else {
block = getVisibilityBlock(fn->defPoint);
//
// add all functions in standard modules to theProgram
//
if (standardModuleSet.set_in(block))
block = theProgram->block;
}
VisibleFunctionBlock* vfb = visibleFunctionMap.get(block);
if (!vfb) {
vfb = new VisibleFunctionBlock();
visibleFunctionMap.put(block, vfb);
}
Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(fn->name);
if (!fns) {
fns = new Vec<FnSymbol*>();
vfb->visibleFunctions.put(fn->name, fns);
}
fns->add(fn);
}
}
nVisibleFunctions = gFnSymbols.n;
}
static BlockStmt*
getVisibleFunctions(BlockStmt* block,
const char* name,
Vec<FnSymbol*>& visibleFns,
Vec<BlockStmt*>& visited) {
//
// all functions in standard modules are stored in a single block
//
if (standardModuleSet.set_in(block))
block = theProgram->block;
//
// avoid infinite recursion due to modules with mutual uses
//
if (visited.set_in(block))
return NULL;
if (isModuleSymbol(block->parentSymbol))
visited.set_add(block);
bool canSkipThisBlock = true;
VisibleFunctionBlock* vfb = visibleFunctionMap.get(block);
if (vfb) {
canSkipThisBlock = false; // cannot skip if this block defines functions
Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(name);
if (fns) {
visibleFns.append(*fns);
}
}
if (block->modUses) {
for_actuals(expr, block->modUses) {
SymExpr* se = toSymExpr(expr);
INT_ASSERT(se);
ModuleSymbol* mod = toModuleSymbol(se->var);
INT_ASSERT(mod);
canSkipThisBlock = false; // cannot skip if this block uses modules
getVisibleFunctions(mod->block, name, visibleFns, visited);
}
}
//
// visibilityBlockCache contains blocks that can be skipped
//
if (BlockStmt* next = visibilityBlockCache.get(block)) {
getVisibleFunctions(next, name, visibleFns, visited);
return (canSkipThisBlock) ? next : block;
}
if (block != rootModule->block) {
BlockStmt* next = getVisibilityBlock(block);
BlockStmt* cache = getVisibleFunctions(next, name, visibleFns, visited);
if (cache)
visibilityBlockCache.put(block, cache);
return (canSkipThisBlock) ? cache : block;
}
return NULL;
}
// Ensure 'parent' is the block before which we want to do the capturing.
static void verifyTaskFnCall(BlockStmt* parent, CallExpr* call) {
if (call->isNamed("coforall_fn") || call->isNamed("on_fn")) {
INT_ASSERT(parent->isForLoop());
} else if (call->isNamed("cobegin_fn")) {
DefExpr* first = toDefExpr(parent->getFirstExpr());
// just documenting the current state
INT_ASSERT(first && !strcmp(first->sym->name, "_cobeginCount"));
} else {
INT_ASSERT(call->isNamed("begin_fn"));
}
}
//
// Allow invoking isConstValWillNotChange() even on formals
// with blank and 'const' intents.
//
static bool isConstValWillNotChange(Symbol* sym) {
if (ArgSymbol* arg = toArgSymbol(sym)) {
IntentTag cInt = concreteIntent(arg->intent, arg->type->getValType());
return cInt == INTENT_CONST_IN;
}
return sym->isConstValWillNotChange();
}
//
// Returns the expression that we want to capture before.
//
// Why not just 'parent'? In users/shetag/fock/fock-dyn-prog-cntr.chpl,
// we cannot do parent->insertBefore() because parent->list is null.
// That's because we have: if ... then cobegin ..., so 'parent' is
// immediately under CondStmt. This motivated me for cobegins to capture
// inside of the 'parent' block, at the beginning of it.
//
static Expr* parentToMarker(BlockStmt* parent, CallExpr* call) {
if (call->isNamed("cobegin_fn")) {
// I want to be cute and keep _cobeginCount def and move
// as the first two statements in the block.
DefExpr* def = toDefExpr(parent->body.head);
INT_ASSERT(def);
// Just so we know what we are doing.
INT_ASSERT(!strcmp((def->sym->name), "_cobeginCount"));
CallExpr* move = toCallExpr(def->next);
INT_ASSERT(move);
SymExpr* arg1 = toSymExpr(move->get(1));
INT_ASSERT(arg1->var == def->sym);
// And this is where we want to insert:
return move->next;
}
// Otherwise insert before 'parent'
return parent;
}
// map: (block id) -> (map: sym -> sym)
typedef std::map<int, SymbolMap*> CapturedValueMap;
static CapturedValueMap capturedValues;
static void freeCache(CapturedValueMap& c) {
for (std::map<int, SymbolMap*>::iterator it = c.begin(); it != c.end(); ++it)
delete it->second;
}
//
// Generate code to store away the value of 'varActual' before
// the cobegin or the coforall loop starts. Use this value
// instead of 'varActual' as the actual to the task function,
// meaning (later in compilation) in the argument bundle.
//
// This is to ensure that all task functions use the same value
// for their respective formal when that has an 'in'-like intent,
// even if 'varActual' is modified between creations of
// the multiple task functions.
//
static void captureTaskIntentValues(int argNum, ArgSymbol* formal,
Expr* actual, Symbol* varActual,
CallInfo& info, CallExpr* call,
FnSymbol* taskFn)
{
BlockStmt* parent = toBlockStmt(call->parentExpr);
INT_ASSERT(parent);
if (taskFn->hasFlag(FLAG_ON) && !parent->isForLoop()) {
// coforall ... { on ... { .... }} ==> there is an intermediate BlockStmt
parent = toBlockStmt(parent->parentExpr);
INT_ASSERT(parent);
}
if (fVerify && (argNum == 0 || (argNum == 1 && taskFn->hasFlag(FLAG_ON))))
verifyTaskFnCall(parent, call); //assertions only
Expr* marker = parentToMarker(parent, call);
if (varActual->defPoint->parentExpr == parent) {
// Index variable of the coforall loop? Do not capture it!
if (fVerify) {
// This is what currently happens.
CallExpr* move = toCallExpr(varActual->defPoint->next);
INT_ASSERT(move);
INT_ASSERT(move->isPrimitive(PRIM_MOVE));
SymExpr* src = toSymExpr(move->get(2));
INT_ASSERT(src);
INT_ASSERT(!strcmp(src->var->name, "_indexOfInterest"));
}
// do nothing
return;
}
SymbolMap*& symap = capturedValues[parent->id];
Symbol* captemp = NULL;
if (symap)
captemp = symap->get(varActual);
else
symap = new SymbolMap();
if (!captemp) {
captemp = newTemp(astr(formal->name, "_captemp"), formal->type);
marker->insertBefore(new DefExpr(captemp));
// todo: once AMM is in effect, drop chpl__autoCopy - do straight move
FnSymbol* autoCopy = getAutoCopy(formal->type);
if (autoCopy)
marker->insertBefore("'move'(%S,%S(%S))", captemp, autoCopy, varActual);
else if (isReferenceType(varActual->type) &&
!isReferenceType(captemp->type))
marker->insertBefore("'move'(%S,'deref'(%S))", captemp, varActual);
else
marker->insertBefore("'move'(%S,%S)", captemp, varActual);
symap->put(varActual, captemp);
}
actual->replace(new SymExpr(captemp));
Symbol*& iact = info.actuals.v[argNum];
INT_ASSERT(iact == varActual);
iact = captemp;
}
//
// Copy the type of the actual into the type of the corresponding formal
// of a task function. (I think resolution wouldn't make this happen
// automatically and correctly in all cases.)
// Also do captureTaskIntentValues() when needed.
//
static void handleTaskIntentArgs(CallExpr* call, FnSymbol* taskFn,
CallInfo& info)
{
INT_ASSERT(taskFn);
if (!needsCapture(taskFn)) {
// A task function should have args only if it needsCapture.
if (taskFn->hasFlag(FLAG_ON)) {
// Documenting the current state: fn_on gets a chpl_localeID_t arg.
INT_ASSERT(call->numActuals() == 1);
} else {
INT_ASSERT(!isTaskFun(taskFn) || call->numActuals() == 0);
}
return;
}
int argNum = -1;
for_formals_actuals(formal, actual, call) {
argNum++;
SymExpr* symexpActual = toSymExpr(actual);
if (!symexpActual) {
// We add NamedExpr args in propagateExtraLeaderArgs().
NamedExpr* namedexpActual = toNamedExpr(actual);
INT_ASSERT(namedexpActual);
symexpActual = toSymExpr(namedexpActual->actual);
}
INT_ASSERT(symexpActual); // because of how we invoke a task function
Symbol* varActual = symexpActual->var;
// If 'call' is in a generic function, it is supposed to have been
// instantiated by now. Otherwise our task function has to remain generic.
INT_ASSERT(!varActual->type->symbol->hasFlag(FLAG_GENERIC));
// Need to copy varActual->type even for type variables.
// BTW some formals' types may have been set in createTaskFunctions().
formal->type = varActual->type;
// If the actual is a ref, still need to capture it => remove ref.
if (isReferenceType(varActual->type)) {
Type* deref = varActual->type->getValType();
// todo: replace needsCapture() with always resolveArgIntent(formal)
// then checking (formal->intent & INTENT_FLAG_IN)
if (needsCapture(deref)) {
formal->type = deref;
// If the formal has a ref intent, DO need a ref type => restore it.
resolveArgIntent(formal);
if (formal->intent & INTENT_FLAG_REF) {
formal->type = varActual->type;
}
}
}
if (varActual->hasFlag(FLAG_TYPE_VARIABLE))
formal->addFlag(FLAG_TYPE_VARIABLE);
// This does not capture records/strings that are passed
// by blank or const intent. As of this writing (6'2015)
// records and strings are (incorrectly) captured at the point
// when the task function/arg bundle is created.
if (taskFn->hasFlag(FLAG_COBEGIN_OR_COFORALL) &&
!isConstValWillNotChange(varActual) &&
(concreteIntent(formal->intent, formal->type->getValType())
& INTENT_FLAG_IN))
// skip dummy_locale_arg: chpl_localeID_t
if (argNum != 0 || !taskFn->hasFlag(FLAG_ON))
captureTaskIntentValues(argNum, formal, actual, varActual, info, call,
taskFn);
}
// Even if some formals are (now) types, if 'taskFn' remained generic,
// gatherCandidates() would not instantiate it, for some reason.
taskFn->removeFlag(FLAG_GENERIC);
}
static Expr*
resolve_type_expr(Expr* expr) {
Expr* result = NULL;
for_exprs_postorder(e, expr) {
result = preFold(e);
if (CallExpr* call = toCallExpr(result)) {
if (call->parentSymbol) {
callStack.add(call);
resolveCall(call);
FnSymbol* fn = call->isResolved();
if (fn && call->parentSymbol) {
resolveFormals(fn);
if (fn->retTag == RET_PARAM || fn->retTag == RET_TYPE ||
fn->retType == dtUnknown)
resolveFns(fn);
}
callStack.pop();
}
}
result = postFold(result);
}
return result;
}
static void
makeNoop(CallExpr* call) {
if (call->baseExpr)
call->baseExpr->remove();
while (call->numActuals())
call->get(1)->remove();
call->primitive = primitives[PRIM_NOOP];
}
//
// The following several functions support const-ness checking.
// Which is tailored to how our existing Chapel code is written
// and to the current constructor story. In particular:
//
// * Const-ness of fields is not honored within constructors
// and initialize() functions
//
// * A function invoked directly from a constructor or initialize()
// are treated as if were a constructor.
//
// The implementation also tends to the case where such an invocation
// occurs inside a task function within the constructor or initialize().
//
// THESE RULES ARE INTERIM.
// They will change - and the Chapel code will need to be updated -
// for the upcoming new constructor story.
//
// Implementation note: we need to propagate the constness property
// through temp assignments, dereferences, and calls to methods with
// FLAG_REF_TO_CONST_WHEN_CONST_THIS.
//
static void findNonTaskFnParent(CallExpr* call,
FnSymbol*& parent, int& stackIdx) {
// We assume that 'call' is at the top of the call stack.
INT_ASSERT(callStack.n >= 1);
INT_ASSERT(callStack.v[callStack.n-1] == call ||
callStack.v[callStack.n-1] == call->parentExpr);
int ix;
for (ix = callStack.n-1; ix >= 0; ix--) {
CallExpr* curr = callStack.v[ix];
Symbol* parentSym = curr->parentSymbol;
FnSymbol* parentFn = toFnSymbol(parentSym);
if (!parentFn)
break;
if (!isTaskFun(parentFn)) {
stackIdx = ix;
parent = parentFn;
return;
}
}
// backup plan
parent = toFnSymbol(call->parentSymbol);
stackIdx = -1;
}
static bool isConstructorLikeFunction(FnSymbol* fn) {
return fn->hasFlag(FLAG_CONSTRUCTOR) || !strcmp(fn->name, "initialize");
}
// Is 'call' in a constructor or in initialize()?
// This includes being in a task function invoked from the above.
static bool isInConstructorLikeFunction(CallExpr* call) {
FnSymbol* parent;
int stackIdx;
findNonTaskFnParent(call, parent, stackIdx); // sets the args
return parent && isConstructorLikeFunction(parent);
}
// Is the function of interest invoked from a constructor
// or initialize(), with the constructor's or intialize's 'this'
// as the receiver actual.
static bool isInvokedFromConstructorLikeFunction(int stackIdx) {
if (stackIdx > 0) {
CallExpr* call2 = callStack.v[stackIdx - 1];
if (FnSymbol* parent2 = toFnSymbol(call2->parentSymbol))
if (isConstructorLikeFunction(parent2))
if (call2->numActuals() >= 2)
if (SymExpr* thisArg2 = toSymExpr(call2->get(2)))
if (thisArg2->var->hasFlag(FLAG_ARG_THIS))
return true;
}
return false;
}
// Check whether the actual comes from accessing a const field of 'this'
// and the call is in a function invoked directly from this's constructor.
// In such case, fields of 'this' are not considered 'const',
// so we remove the const-ness flag.
static bool checkAndUpdateIfLegalFieldOfThis(CallExpr* call, Expr* actual,
FnSymbol*& nonTaskFnParent) {
int stackIdx;
findNonTaskFnParent(call, nonTaskFnParent, stackIdx); // sets the args
if (SymExpr* se = toSymExpr(actual))
if (se->var->hasFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS))
if (isInvokedFromConstructorLikeFunction(stackIdx)) {
// Yes, this is the case we are looking for.
se->var->removeFlag(FLAG_REF_TO_CONST);
return true;
}
return false;
}
// little helper
static Symbol* getBaseSymForConstCheck(CallExpr* call) {
// ensure this is a method call
INT_ASSERT(call->get(1)->typeInfo() == dtMethodToken);
SymExpr* baseExpr = toSymExpr(call->get(2));
INT_ASSERT(baseExpr); // otherwise, cannot do the checking
return baseExpr->var;
}
// If 'call' is an access to a const thing, for example a const field
// or a field of a const record, set const flag(s) on the symbol
// that stores the result of 'call'.
static void setFlagsAndCheckForConstAccess(Symbol* dest,
CallExpr* call, FnSymbol* resolvedFn)
{
// Is the outcome of 'call' a reference to a const?
bool refConst = resolvedFn->hasFlag(FLAG_REF_TO_CONST);
// Another flag that's relevant.
const bool constWCT = resolvedFn->hasFlag(FLAG_REF_TO_CONST_WHEN_CONST_THIS);
// The second flag does not make sense when the first flag is set.
INT_ASSERT(!(refConst && constWCT));
// The symbol whose field is accessed, if applicable:
Symbol* baseSym = NULL;
if (refConst) {
if (resolvedFn->hasFlag(FLAG_FIELD_ACCESSOR) &&
// promotion wrappers are not handled currently
!resolvedFn->hasFlag(FLAG_PROMOTION_WRAPPER)
)
baseSym = getBaseSymForConstCheck(call);
} else if (constWCT) {
baseSym = getBaseSymForConstCheck(call);
if (baseSym->isConstant() ||
baseSym->hasFlag(FLAG_REF_TO_CONST) ||
baseSym->hasFlag(FLAG_CONST)
)
refConst = true;
else
// The result is not constant.
baseSym = NULL;
} else if (dest->hasFlag(FLAG_ARRAY_ALIAS) &&
resolvedFn->hasFlag(FLAG_AUTO_COPY_FN) &&
!dest->hasFlag(FLAG_CONST))
{
// We are creating a var alias - ensure aliasee is not const either.
SymExpr* aliaseeSE = toSymExpr(call->get(1));
INT_ASSERT(aliaseeSE);
if (aliaseeSE->var->isConstant() ||
aliaseeSE->var->hasFlag(FLAG_CONST))
USR_FATAL_CONT(call, "creating a non-const alias '%s' of a const array or domain", dest->name);
}
// Do not consider it const if it is an access to 'this'
// in a constructor. Todo: will need to reconcile with UMM.
// btw (baseSym != NULL) ==> (refConst == true).
if (baseSym) {
// Aside: at this point 'baseSym' can have reference or value type,
// seemingly without a particular rule.
if (baseSym->hasFlag(FLAG_ARG_THIS) &&
isInConstructorLikeFunction(call)
)
refConst = false;
}
if (refConst) {
if (isReferenceType(dest->type))
dest->addFlag(FLAG_REF_TO_CONST);
else
dest->addFlag(FLAG_CONST);
if (baseSym && baseSym->hasFlag(FLAG_ARG_THIS))
// 'call' can be a field accessor or an array element accessor or ?
dest->addFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS);
// Propagate this flag. btw (recConst && constWCT) ==> (baseSym != NULL)
if (constWCT && baseSym->hasFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS))
dest->addFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS);
}
}
// Report an error when storing a sync or single variable into a tuple.
// This is because currently we deallocate memory excessively in this case.
static void checkForStoringIntoTuple(CallExpr* call, FnSymbol* resolvedFn)
{
// Do not perform the checks if:
// not building a tuple
if (!resolvedFn->hasFlag(FLAG_BUILD_TUPLE) ||
// sync/single tuples are used in chpl__autoCopy(x: _tuple), allow them
resolvedFn->hasFlag(FLAG_ALLOW_REF) ||
// sync/single tuple *types* and params seem OK
resolvedFn->retTag != RET_VALUE)
return;
for_formals_actuals(formal, actual, call)
if (isSyncType(formal->type)) {
const char* name = "";
if (SymExpr* aSE = toSymExpr(actual))
if (!aSE->var->hasFlag(FLAG_TEMP))
name = aSE->var->name;
USR_FATAL_CONT(actual, "storing a sync or single variable %s in a tuple is not currently implemented - apply readFE() or readFF()", name);
}
}
// If 'fn' is the default assignment for a record type, return
// the name of that record type; otherwise return NULL.
static const char* defaultRecordAssignmentTo(FnSymbol* fn) {
if (!strcmp("=", fn->name)) {
if (fn->hasFlag(FLAG_COMPILER_GENERATED)) {
Type* desttype = fn->getFormal(1)->type->getValType();
INT_ASSERT(desttype != dtUnknown); // otherwise this test is unreliable
if (isRecord(desttype) || isUnion(desttype))
return desttype->symbol->name;
}
}
return NULL;
}
//
// special case cast of class w/ type variables that is not generic
// i.e. type variables are type definitions (have default types)
//
static void
resolveDefaultGenericType(CallExpr* call) {
SET_LINENO(call);
for_actuals(actual, call) {
if (NamedExpr* ne = toNamedExpr(actual))
actual = ne->actual;
if (SymExpr* te = toSymExpr(actual)) {
if (TypeSymbol* ts = toTypeSymbol(te->var)) {
if (AggregateType* ct = toAggregateType(ts->type)) {
if (ct->symbol->hasFlag(FLAG_GENERIC)) {
CallExpr* cc = new CallExpr(ct->defaultTypeConstructor->name);
te->replace(cc);
resolveCall(cc);
cc->replace(new SymExpr(cc->typeInfo()->symbol));
}
}
}
if (VarSymbol* vs = toVarSymbol(te->var)) {
// Fix for complicated extern vars like
// extern var x: c_ptr(c_int);
if( vs->hasFlag(FLAG_EXTERN) && vs->hasFlag(FLAG_TYPE_VARIABLE) &&
vs->defPoint && vs->defPoint->init ) {
if( CallExpr* def = toCallExpr(vs->defPoint->init) ) {
vs->defPoint->init = resolveExpr(def);
te->replace(new SymExpr(vs->defPoint->init->typeInfo()->symbol));
}
}
}
}
}
}
static void
gatherCandidates(Vec<ResolutionCandidate*>& candidates,
Vec<FnSymbol*>& visibleFns,
CallInfo& info) {
// Search user-defined (i.e. non-compiler-generated) functions first.
forv_Vec(FnSymbol, visibleFn, visibleFns) {
if (visibleFn->hasFlag(FLAG_COMPILER_GENERATED)) {
continue;
}
if (info.call->methodTag &&
! (visibleFn->hasFlag(FLAG_NO_PARENS) ||
visibleFn->hasFlag(FLAG_TYPE_CONSTRUCTOR))) {
continue;
}
if (fExplainVerbose &&
((explainCallLine && explainCallMatch(info.call)) ||
info.call->id == explainCallID))
{
USR_PRINT(visibleFn, "Considering function: %s", toString(visibleFn));
}
filterCandidate(candidates, visibleFn, info);
}
// Return if we got a successful match with user-defined functions.
if (candidates.n) {
return;
}
// No. So search compiler-defined functions.
forv_Vec(FnSymbol, visibleFn, visibleFns) {
if (!visibleFn->hasFlag(FLAG_COMPILER_GENERATED)) {
continue;
}
if (info.call->methodTag &&
! (visibleFn->hasFlag(FLAG_NO_PARENS) ||
visibleFn->hasFlag(FLAG_TYPE_CONSTRUCTOR))) {
continue;
}
if (fExplainVerbose &&
((explainCallLine && explainCallMatch(info.call)) ||
info.call->id == explainCallID))
{
USR_PRINT(visibleFn, "Considering function: %s", toString(visibleFn));
}
filterCandidate(candidates, visibleFn, info);
}
}
void
resolveCall(CallExpr* call)
{
if (call->primitive)
{
switch (call->primitive->tag)
{
default: /* do nothing */ break;
case PRIM_TUPLE_AND_EXPAND: resolveTupleAndExpand(call); break;
case PRIM_TUPLE_EXPAND: resolveTupleExpand(call); break;
case PRIM_SET_MEMBER: resolveSetMember(call); break;
case PRIM_MOVE: resolveMove(call); break;
case PRIM_TYPE_INIT:
case PRIM_INIT: resolveDefaultGenericType(call); break;
case PRIM_NO_INIT: resolveDefaultGenericType(call); break;
case PRIM_NEW: resolveNew(call); break;
}
}
else
{
resolveNormalCall(call);
}
}
void resolveNormalCall(CallExpr* call) {
resolveDefaultGenericType(call);
CallInfo info(call);
Vec<FnSymbol*> visibleFns; // visible functions
//
// update visible function map as necessary
//
if (gFnSymbols.n != nVisibleFunctions) {
buildVisibleFunctionMap();
}
if (!call->isResolved()) {
if (!info.scope) {
Vec<BlockStmt*> visited;
getVisibleFunctions(getVisibilityBlock(call), info.name, visibleFns, visited);
} else {
if (VisibleFunctionBlock* vfb = visibleFunctionMap.get(info.scope)) {
if (Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(info.name)) {
visibleFns.append(*fns);
}
}
}
} else {
visibleFns.add(call->isResolved());
handleTaskIntentArgs(call, call->isResolved(), info);
}
if ((explainCallLine && explainCallMatch(call)) ||
call->id == explainCallID)
{
USR_PRINT(call, "call: %s", toString(&info));
if (visibleFns.n == 0)
USR_PRINT(call, "no visible functions found");
bool first = true;
forv_Vec(FnSymbol, visibleFn, visibleFns) {
USR_PRINT(visibleFn, "%s %s",
first ? "visible functions are:" : " ",
toString(visibleFn));
first = false;
}
}
Vec<ResolutionCandidate*> candidates;
gatherCandidates(candidates, visibleFns, info);
if ((explainCallLine && explainCallMatch(info.call)) ||
call->id == explainCallID)
{
if (candidates.n == 0) {
USR_PRINT(info.call, "no candidates found");
} else {
bool first = true;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
USR_PRINT(candidate->fn, "%s %s",
first ? "candidates are:" : " ",
toString(candidate->fn));
first = false;
}
}
}
Expr* scope = (info.scope) ? info.scope : getVisibilityBlock(call);
bool explain = fExplainVerbose &&
((explainCallLine && explainCallMatch(call)) ||
info.call->id == explainCallID);
DisambiguationContext DC(&info.actuals, scope, explain);
ResolutionCandidate* best = disambiguateByMatch(candidates, DC);
if (best && best->fn) {
/*
* Finish instantiating the body. This is a noop if the function wasn't
* partially instantiated.
*/
instantiateBody(best->fn);
if (explainCallLine && explainCallMatch(call)) {
USR_PRINT(best->fn, "best candidate is: %s", toString(best->fn));
}
}
// Future work note: the repeated check to best and best->fn means that we
// could probably restructure this function to a better form.
if (call->partialTag && (!best || !best->fn ||
!best->fn->hasFlag(FLAG_NO_PARENS))) {
if (best != NULL) {
delete best;
best = NULL;
}
} else if (!best) {
if (tryStack.n) {
tryFailure = true;
return;
} else {
if (candidates.n > 0) {
Vec<FnSymbol*> candidateFns;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
candidateFns.add(candidate->fn);
}
printResolutionErrorAmbiguous(candidateFns, &info);
} else {
printResolutionErrorUnresolved(visibleFns, &info);
}
}
} else {
best->fn = defaultWrap(best->fn, &best->alignedFormals, &info);
reorderActuals(best->fn, &best->alignedFormals, &info);
coerceActuals(best->fn, &info);
best->fn = promotionWrap(best->fn, &info);
}
FnSymbol* resolvedFn = best != NULL ? best->fn : NULL;
forv_Vec(ResolutionCandidate*, candidate, candidates) {
delete candidate;
}
if (call->partialTag) {
if (!resolvedFn) {
return;
}
call->partialTag = false;
}
if (resolvedFn &&
!strcmp("=", resolvedFn->name) &&
isRecord(resolvedFn->getFormal(1)->type) &&
resolvedFn->getFormal(2)->type == dtNil) {
USR_FATAL(userCall(call), "type mismatch in assignment from nil to %s",
toString(resolvedFn->getFormal(1)->type));
}
if (!resolvedFn) {
INT_FATAL(call, "unable to resolve call");
}
if (call->parentSymbol) {
SET_LINENO(call);
call->baseExpr->replace(new SymExpr(resolvedFn));
}
if (resolvedFn->hasFlag(FLAG_MODIFIES_CONST_FIELDS))
// Not allowed if it is not called directly from a constructor.
if (!isInConstructorLikeFunction(call) ||
!getBaseSymForConstCheck(call)->hasFlag(FLAG_ARG_THIS)
)
USR_FATAL_CONT(call, "illegal call to %s() - it modifies 'const' fields of 'this', therefore it can be invoked only directly from a constructor on the object being constructed", resolvedFn->name);
lvalueCheck(call);
checkForStoringIntoTuple(call, resolvedFn);
if (const char* str = innerCompilerWarningMap.get(resolvedFn)) {
reissueCompilerWarning(str, 2);
if (callStack.n >= 2)
if (FnSymbol* fn = toFnSymbol(callStack.v[callStack.n-2]->isResolved()))
outerCompilerWarningMap.put(fn, str);
}
if (const char* str = outerCompilerWarningMap.get(resolvedFn)) {
reissueCompilerWarning(str, 1);
}
}
static void lvalueCheck(CallExpr* call)
{
// Check to ensure the actual supplied to an OUT, INOUT or REF argument
// is an lvalue.
for_formals_actuals(formal, actual, call) {
bool errorMsg = false;
switch (formal->intent) {
case INTENT_BLANK:
case INTENT_IN:
case INTENT_CONST:
case INTENT_CONST_IN:
case INTENT_PARAM:
case INTENT_TYPE:
// not checking them here
break;
case INTENT_INOUT:
case INTENT_OUT:
case INTENT_REF:
if (!isLegalLvalueActualArg(formal, actual))
errorMsg = true;
break;
case INTENT_CONST_REF:
if (!isLegalConstRefActualArg(formal, actual))
errorMsg = true;
break;
default:
// all intents should be covered above
INT_ASSERT(false);
break;
}
FnSymbol* nonTaskFnParent = NULL;
if (errorMsg &&
// sets nonTaskFnParent
checkAndUpdateIfLegalFieldOfThis(call, actual, nonTaskFnParent)
) {
errorMsg = false;
nonTaskFnParent->addFlag(FLAG_MODIFIES_CONST_FIELDS);
}
if (errorMsg) {
if (nonTaskFnParent->hasFlag(FLAG_SUPPRESS_LVALUE_ERRORS))
// we are asked to ignore errors here
return;
FnSymbol* calleeFn = call->isResolved();
INT_ASSERT(calleeFn == formal->defPoint->parentSymbol); // sanity
if (calleeFn->hasFlag(FLAG_ASSIGNOP)) {
// This assert is FYI. Perhaps can remove it if it fails.
INT_ASSERT(callStack.n > 0 && callStack.v[callStack.n-1] == call);
const char* recordName =
defaultRecordAssignmentTo(toFnSymbol(call->parentSymbol));
if (recordName && callStack.n >= 2)
// blame on the caller of the caller, if available
USR_FATAL_CONT(callStack.v[callStack.n-2],
"cannot assign to a record of the type %s"
" using the default assignment operator"
" because it has 'const' field(s)", recordName);
else
USR_FATAL_CONT(actual, "illegal lvalue in assignment");
}
else
{
ModuleSymbol* mod = calleeFn->getModule();
char cn1 = calleeFn->name[0];
const char* calleeParens = (isalpha(cn1) || cn1 == '_') ? "()" : "";
// Should this be the same condition as in insertLineNumber() ?
if (developer || mod->modTag == MOD_USER) {
USR_FATAL_CONT(actual, "non-lvalue actual is passed to %s formal '%s'"
" of %s%s", formal->intentDescrString(), formal->name,
calleeFn->name, calleeParens);
} else {
USR_FATAL_CONT(actual, "non-lvalue actual is passed to a %s formal of"
" %s%s", formal->intentDescrString(),
calleeFn->name, calleeParens);
}
}
}
}
}
// We do some const-related work upon PRIM_MOVE
static void setConstFlagsAndCheckUponMove(Symbol* lhs, Expr* rhs) {
// If this assigns into a loop index variable from a non-var iterator,
// mark the variable constant.
if (SymExpr* rhsSE = toSymExpr(rhs)) {
// If RHS is this special variable...
if (rhsSE->var->hasFlag(FLAG_INDEX_OF_INTEREST)) {
INT_ASSERT(lhs->hasFlag(FLAG_INDEX_VAR));
// ... and not of a reference type
// todo: differentiate based on ref-ness, not _ref type
// todo: not all const if it is zippered and one of iterators is var
if (!isReferenceType(rhsSE->var->type))
// ... and not an array (arrays are always yielded by reference)
if (!rhsSE->var->type->symbol->hasFlag(FLAG_ARRAY))
// ... then mark LHS constant.
lhs->addFlag(FLAG_CONST);
}
} else if (CallExpr* rhsCall = toCallExpr(rhs)) {
if (rhsCall->isPrimitive(PRIM_GET_MEMBER)) {
if (SymExpr* rhsBase = toSymExpr(rhsCall->get(1))) {
if (rhsBase->var->hasFlag(FLAG_CONST) ||
rhsBase->var->hasFlag(FLAG_REF_TO_CONST)
)
lhs->addFlag(FLAG_REF_TO_CONST);
} else {
INT_ASSERT(false); // PRIM_GET_MEMBER of a non-SymExpr??
}
} else if (FnSymbol* resolvedFn = rhsCall->isResolved()) {
setFlagsAndCheckForConstAccess(lhs, rhsCall, resolvedFn);
}
}
}
static void resolveTupleAndExpand(CallExpr* call) {
SymExpr* se = toSymExpr(call->get(1));
int size = 0;
for (int i = 0; i < se->var->type->substitutions.n; i++) {
if (se->var->type->substitutions.v[i].key) {
if (!strcmp("size", se->var->type->substitutions.v[i].key->name)) {
size = toVarSymbol(se->var->type->substitutions.v[i].value)->immediate->int_value();
break;
}
}
}
INT_ASSERT(size);
CallExpr* noop = new CallExpr(PRIM_NOOP);
call->getStmtExpr()->insertBefore(noop);
VarSymbol* tmp = gTrue;
for (int i = 1; i <= size; i++) {
VarSymbol* tmp1 = newTemp("_tuple_and_expand_tmp_");
tmp1->addFlag(FLAG_MAYBE_PARAM);
tmp1->addFlag(FLAG_MAYBE_TYPE);
VarSymbol* tmp2 = newTemp("_tuple_and_expand_tmp_");
tmp2->addFlag(FLAG_MAYBE_PARAM);
tmp2->addFlag(FLAG_MAYBE_TYPE);
VarSymbol* tmp3 = newTemp("_tuple_and_expand_tmp_");
tmp3->addFlag(FLAG_MAYBE_PARAM);
tmp3->addFlag(FLAG_MAYBE_TYPE);
VarSymbol* tmp4 = newTemp("_tuple_and_expand_tmp_");
tmp4->addFlag(FLAG_MAYBE_PARAM);
tmp4->addFlag(FLAG_MAYBE_TYPE);
call->getStmtExpr()->insertBefore(new DefExpr(tmp1));
call->getStmtExpr()->insertBefore(new DefExpr(tmp2));
call->getStmtExpr()->insertBefore(new DefExpr(tmp3));
call->getStmtExpr()->insertBefore(new DefExpr(tmp4));
call->getStmtExpr()->insertBefore(
new CallExpr(PRIM_MOVE, tmp1,
new CallExpr(se->copy(), new_IntSymbol(i))));
CallExpr* query = new CallExpr(PRIM_QUERY, tmp1);
for (int i = 2; i < call->numActuals(); i++)
query->insertAtTail(call->get(i)->copy());
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp2, query));
call->getStmtExpr()->insertBefore(
new CallExpr(PRIM_MOVE, tmp3,
new CallExpr("==", tmp2, call->get(3)->copy())));
call->getStmtExpr()->insertBefore(
new CallExpr(PRIM_MOVE, tmp4,
new CallExpr("&", tmp3, tmp)));
tmp = tmp4;
}
call->replace(new SymExpr(tmp));
noop->replace(call); // put call back in ast for function resolution
makeNoop(call);
}
static void resolveTupleExpand(CallExpr* call) {
SymExpr* sym = toSymExpr(call->get(1));
Type* type = sym->var->getValType();
if (!type->symbol->hasFlag(FLAG_TUPLE))
USR_FATAL(call, "invalid tuple expand primitive");
int size = 0;
for (int i = 0; i < type->substitutions.n; i++) {
if (type->substitutions.v[i].key) {
if (!strcmp("size", type->substitutions.v[i].key->name)) {
size = toVarSymbol(type->substitutions.v[i].value)->immediate->int_value();
break;
}
}
}
if (size == 0)
INT_FATAL(call, "Invalid tuple expand primitive");
CallExpr* parent = toCallExpr(call->parentExpr);
CallExpr* noop = new CallExpr(PRIM_NOOP);
call->getStmtExpr()->insertBefore(noop);
for (int i = 1; i <= size; i++) {
VarSymbol* tmp = newTemp("_tuple_expand_tmp_");
tmp->addFlag(FLAG_MAYBE_TYPE);
DefExpr* def = new DefExpr(tmp);
call->getStmtExpr()->insertBefore(def);
CallExpr* e = NULL;
if (!call->parentSymbol->hasFlag(FLAG_EXPAND_TUPLES_WITH_VALUES)) {
e = new CallExpr(sym->copy(), new_IntSymbol(i));
} else {
e = new CallExpr(PRIM_GET_MEMBER_VALUE, sym->copy(),
new_StringSymbol(astr("x", istr(i))));
}
CallExpr* move = new CallExpr(PRIM_MOVE, tmp, e);
call->getStmtExpr()->insertBefore(move);
call->insertBefore(new SymExpr(tmp));
}
call->remove();
noop->replace(call); // put call back in ast for function resolution
makeNoop(call);
// increase tuple rank
if (parent && parent->isNamed("_type_construct__tuple")) {
parent->get(1)->replace(new SymExpr(new_IntSymbol(parent->numActuals()-1)));
}
}
static void resolveSetMember(CallExpr* call) {
// Get the field name.
SymExpr* sym = toSymExpr(call->get(2));
if (!sym)
INT_FATAL(call, "bad set member primitive");
VarSymbol* var = toVarSymbol(sym->var);
if (!var || !var->immediate)
INT_FATAL(call, "bad set member primitive");
const char* name = var->immediate->v_string;
// Special case: An integer field name is actually a tuple member index.
{
int64_t i;
if (get_int(sym, &i)) {
name = astr("x", istr(i));
call->get(2)->replace(new SymExpr(new_StringSymbol(name)));
}
}
AggregateType* ct = toAggregateType(call->get(1)->typeInfo());
if (!ct)
INT_FATAL(call, "bad set member primitive");
Symbol* fs = NULL;
for_fields(field, ct) {
if (!strcmp(field->name, name)) {
fs = field; break;
}
}
if (!fs)
INT_FATAL(call, "bad set member primitive");
Type* t = call->get(3)->typeInfo();
// I think this never happens, so can be turned into an assert. <hilde>
if (t == dtUnknown)
INT_FATAL(call, "Unable to resolve field type");
if (t == dtNil && fs->type == dtUnknown)
USR_FATAL(call->parentSymbol, "unable to determine type of field from nil");
if (fs->type == dtUnknown)
fs->type = t;
if (t != fs->type && t != dtNil && t != dtObject) {
USR_FATAL(userCall(call),
"cannot assign expression of type %s to field of type %s",
toString(t), toString(fs->type));
}
}
static void resolveMove(CallExpr* call) {
Expr* rhs = call->get(2);
Symbol* lhs = NULL;
if (SymExpr* se = toSymExpr(call->get(1)))
lhs = se->var;
INT_ASSERT(lhs);
FnSymbol* fn = toFnSymbol(call->parentSymbol);
bool isReturn = fn ? lhs == fn->getReturnSymbol() : false;
if (lhs->hasFlag(FLAG_TYPE_VARIABLE) && !isTypeExpr(rhs)) {
if (isReturn) {
if (!call->parentSymbol->hasFlag(FLAG_RUNTIME_TYPE_INIT_FN))
USR_FATAL(call, "illegal return of value where type is expected");
} else {
USR_FATAL(call, "illegal assignment of value to type");
}
}
if (!lhs->hasFlag(FLAG_TYPE_VARIABLE) && !lhs->hasFlag(FLAG_MAYBE_TYPE) && isTypeExpr(rhs)) {
if (isReturn) {
USR_FATAL(call, "illegal return of type where value is expected");
} else {
USR_FATAL(call, "illegal assignment of type to value");
}
}
// do not resolve function return type yet
// except for constructors
if (fn && call->parentExpr != fn->where && call->parentExpr != fn->retExprType &&
isReturn && fn->_this != lhs) {
if (fn->retType == dtUnknown) {
return;
}
}
Type* rhsType = rhs->typeInfo();
if (rhsType == dtVoid) {
if (isReturn && (lhs->type == dtVoid || lhs->type == dtUnknown))
{
// It is OK to assign void to the return value variable as long as its
// type is void or is not yet established.
}
else
{
if (CallExpr* rhsFn = toCallExpr(rhs)) {
if (FnSymbol* rhsFnSym = rhsFn->isResolved()) {
USR_FATAL(userCall(call),
"illegal use of function that does not return a value: '%s'",
rhsFnSym->name);
}
}
USR_FATAL(userCall(call),
"illegal use of function that does not return a value");
}
}
if (lhs->type == dtUnknown || lhs->type == dtNil)
lhs->type = rhsType;
Type* lhsType = lhs->type;
setConstFlagsAndCheckUponMove(lhs, rhs);
if (CallExpr* call = toCallExpr(rhs)) {
if (FnSymbol* fn = call->isResolved()) {
if (rhsType == dtUnknown) {
USR_FATAL_CONT(fn, "unable to resolve return type of function '%s'", fn->name);
USR_FATAL(rhs, "called recursively at this point");
}
}
}
if (rhsType == dtUnknown)
USR_FATAL(call, "unable to resolve type");
if (rhsType == dtNil && lhsType != dtNil && !isClass(lhsType))
USR_FATAL(userCall(call), "type mismatch in assignment from nil to %s",
toString(lhsType));
Type* lhsBaseType = lhsType->getValType();
Type* rhsBaseType = rhsType->getValType();
bool isChplHereAlloc = false;
// Fix up calls inserted by callChplHereAlloc()
if (CallExpr* rhsCall = toCallExpr(rhs)) {
// Here we are going to fix up calls inserted by
// callChplHereAlloc() and callChplHereFree()
//
// Currently this code assumes that such primitives are only
// inserted by the compiler. TODO: Add a check to make sure
// these are the ones added by the above functions.
//
if (rhsCall->isPrimitive(PRIM_SIZEOF)) {
// Fix up arg to sizeof(), as we may not have known the
// type earlier
SymExpr* sizeSym = toSymExpr(rhsCall->get(1));
INT_ASSERT(sizeSym);
rhs->replace(new CallExpr(PRIM_SIZEOF, sizeSym->var->typeInfo()->symbol));
return;
} else if (rhsCall->isPrimitive(PRIM_CAST_TO_VOID_STAR)) {
if (isReferenceType(rhsCall->get(1)->typeInfo())) {
// Add a dereference as needed, as we did not have complete
// type information earlier
SymExpr* castVar = toSymExpr(rhsCall->get(1));
INT_ASSERT(castVar);
VarSymbol* derefTmp = newTemp("castDeref", castVar->typeInfo()->getValType());
call->insertBefore(new DefExpr(derefTmp));
call->insertBefore(new CallExpr(PRIM_MOVE, derefTmp,
new CallExpr(PRIM_DEREF,
new SymExpr(castVar->var))));
rhsCall->replace(new CallExpr(PRIM_CAST_TO_VOID_STAR,
new SymExpr(derefTmp)));
}
} else if (rhsCall->isResolved() == gChplHereAlloc) {
// Insert cast below for calls to chpl_here_*alloc()
isChplHereAlloc = true;
}
}
if (!isChplHereAlloc && rhsType != dtNil &&
rhsBaseType != lhsBaseType &&
!isDispatchParent(rhsBaseType, lhsBaseType))
USR_FATAL(userCall(call), "type mismatch in assignment from %s to %s",
toString(rhsType), toString(lhsType));
if (isChplHereAlloc ||
(rhsType != lhsType && isDispatchParent(rhsBaseType, lhsBaseType))) {
Symbol* tmp = newTemp("cast_tmp", rhsType);
call->insertBefore(new DefExpr(tmp));
call->insertBefore(new CallExpr(PRIM_MOVE, tmp, rhs->remove()));
call->insertAtTail(new CallExpr(PRIM_CAST,
isChplHereAlloc ? lhs->type->symbol :
lhsBaseType->symbol, tmp));
}
}
// Some new expressions are converted in normalize(). For example, a call to a
// type function is resolved at this point.
// The syntax supports calling the result of a type function as a constructor,
// but this is not fully implemented.
static void
resolveNew(CallExpr* call)
{
// This is a 'new' primitive, so we expect the argument to be a constructor
// call.
CallExpr* ctor = toCallExpr(call->get(1));
// May need to resolve ctor here.
if (FnSymbol* fn = ctor->isResolved())
{
// If the function is a constructor, just bridge out the 'new' primitive
// and call the constructor. Done.
if (fn->hasFlag(FLAG_CONSTRUCTOR))
{
call->replace(ctor);
return;
}
// Not a constructor, so issue an error.
USR_FATAL(call, "invalid use of 'new' on %s", fn->name);
return;
}
if (UnresolvedSymExpr* urse = toUnresolvedSymExpr(ctor->baseExpr))
{
USR_FATAL(call, "invalid use of 'new' on %s", urse->unresolved);
return;
}
USR_FATAL(call, "invalid use of 'new'");
}
//
// This tells us whether we can rely on the compiler's back end (e.g.,
// C) to provide the copy for us for 'in' or 'const in' intents when
// passing an argument of type 't'.
//
static bool backendRequiresCopyForIn(Type* t) {
return (isRecord(t) ||
t->symbol->hasFlag(FLAG_ARRAY) ||
t->symbol->hasFlag(FLAG_DOMAIN));
}
// Returns true if the formal needs an internal temporary, false otherwise.
static bool
formalRequiresTemp(ArgSymbol* formal) {
//
// get the formal's function
//
FnSymbol* fn = toFnSymbol(formal->defPoint->parentSymbol);
INT_ASSERT(fn);
return
//
// 'out' and 'inout' intents are passed by ref at the C level, so we
// need to make an explicit copy in the codegen'd function */
//
(formal->intent == INTENT_OUT ||
formal->intent == INTENT_INOUT ||
//
// 'in' and 'const in' also require a copy, but for simple types
// (like ints or class references), we can rely on C's copy when
// passing the argument, as long as the routine is not
// inlined.
//
((formal->intent == INTENT_IN || formal->intent == INTENT_CONST_IN) &&
(backendRequiresCopyForIn(formal->type) || !fn->hasFlag(FLAG_INLINE)))
//
// The following case reduces memory leaks for zippered forall
// leader/follower pairs where the communicated intermediate
// result is a tuple of ranges, but I can't explain why it'd be
// needed. Tom has said that iterators haven't really been
// bolted down in terms of memory leaks, so future work would be
// to remove this hack and close the leak properly.
//
|| strcmp(formal->name, "followThis") == 0
);
}
static void
insertFormalTemps(FnSymbol* fn) {
SymbolMap formals2vars;
for_formals(formal, fn) {
if (formalRequiresTemp(formal)) {
SET_LINENO(formal);
VarSymbol* tmp = newTemp(astr("_formal_tmp_", formal->name));
formals2vars.put(formal, tmp);
}
}
if (formals2vars.n > 0) {
// The names of formals in the body of this function are replaced with the
// names of their corresponding local temporaries.
update_symbols(fn->body, &formals2vars);
// Add calls to chpl__initCopy to create local copies as necessary.
// Add writeback code for out and inout intents.
addLocalCopiesAndWritebacks(fn, formals2vars);
}
}
// Given the map from formals to local "_formal_tmp_" variables, this function
// adds code as necessary
// - to copy the formal into the temporary at the start of the function
// - and copy it back when done.
// The copy in is needed for "inout", "in" and "const in" intents.
// The copy out is needed for "inout" and "out" intents.
// Blank intent is treated like "const", and normally copies the formal through
// chpl__autoCopy.
// Note that autoCopy is called in this case, but not for "inout", "in" and "const in".
// Either record-wrapped types are always passed by ref, or some unexpected
// behavior will result by applying "in" intents to them.
static void addLocalCopiesAndWritebacks(FnSymbol* fn, SymbolMap& formals2vars)
{
// Enumerate the formals that have local temps.
form_Map(SymbolMapElem, e, formals2vars) {
ArgSymbol* formal = toArgSymbol(e->key); // Get the formal.
Symbol* tmp = e->value; // Get the temp.
SET_LINENO(formal);
// TODO: Move this closer to the location (in code) where we determine
// whether tmp owns its value or not. That is, push setting these flags
// (or not) into the cases below, as appropriate.
Type* formalType = formal->type->getValType();
if ((formal->intent == INTENT_BLANK ||
formal->intent == INTENT_CONST ||
formal->intent == INTENT_CONST_IN) &&
!isSyncType(formalType) &&
!isRefCountedType(formalType))
{
tmp->addFlag(FLAG_CONST);
tmp->addFlag(FLAG_INSERT_AUTO_DESTROY);
}
// This switch adds the extra code inside the current function necessary
// to implement the ref-to-value semantics, where needed.
switch (formal->intent)
{
// Make sure we handle every case.
default:
INT_FATAL("Unhandled INTENT case.");
break;
// These cases are weeded out by formalRequiresTemp() above.
case INTENT_PARAM:
case INTENT_TYPE:
case INTENT_REF:
case INTENT_CONST_REF:
INT_FATAL("Unexpected INTENT case.");
break;
case INTENT_OUT:
if (formal->defaultExpr && formal->defaultExpr->body.tail->typeInfo() != dtTypeDefaultToken) {
BlockStmt* defaultExpr = formal->defaultExpr->copy();
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, defaultExpr->body.tail->remove()));
fn->insertAtHead(defaultExpr);
} else {
VarSymbol* refTmp = newTemp("_formal_ref_tmp_");
VarSymbol* typeTmp = newTemp("_formal_type_tmp_");
typeTmp->addFlag(FLAG_MAYBE_TYPE);
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_INIT, typeTmp)));
fn->insertAtHead(new CallExpr(PRIM_MOVE, typeTmp, new CallExpr(PRIM_TYPEOF, refTmp)));
fn->insertAtHead(new CallExpr(PRIM_MOVE, refTmp, new CallExpr(PRIM_DEREF, formal)));
fn->insertAtHead(new DefExpr(refTmp));
fn->insertAtHead(new DefExpr(typeTmp));
}
break;
case INTENT_INOUT:
case INTENT_IN:
case INTENT_CONST_IN:
// TODO: Adding a formal temp for INTENT_CONST_IN is conservative.
// If the compiler verifies in a separate pass that it is never written,
// we don't have to copy it.
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr("chpl__initCopy", formal)));
tmp->addFlag(FLAG_INSERT_AUTO_DESTROY);
break;
case INTENT_BLANK:
case INTENT_CONST:
{
TypeSymbol* ts = formal->type->symbol;
if (!getRecordWrappedFlags(ts).any() &&
!ts->hasFlag(FLAG_ITERATOR_CLASS) &&
!ts->hasFlag(FLAG_ITERATOR_RECORD) &&
!getSyncFlags(ts).any()) {
if (fn->hasFlag(FLAG_BEGIN)) {
// autoCopy/autoDestroy will be added later, in parallel pass
// by insertAutoCopyDestroyForTaskArg()
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, formal));
tmp->removeFlag(FLAG_INSERT_AUTO_DESTROY);
} else {
// Note that because we reject the case of record-wrapped types above,
// the only way we can get a formal whose call to chpl__autoCopy does
// anything different from calling chpl__initCopy is if the formal is a
// tuple containing a record-wrapped type. This is probably not
// intentional: It gives tuple-wrapped record-wrapped types different
// behavior from bare record-wrapped types.
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr("chpl__autoCopy", formal)));
// WORKAROUND:
// This is a temporary bug fix that results in leaked memory.
//
// Here we avoid calling the destructor for any formals that
// are records or have records because the call may result
// in repeatedly freeing memory if the user defined
// destructor calls delete on any fields. I think we
// probably need a similar change in the INOUT/IN case
// above. See test/types/records/sungeun/destructor3.chpl
// and test/users/recordbug3.chpl.
//
// For records, this problem should go away if/when we
// implement 'const ref' intents and make them the default
// for records.
//
// Another solution (and the one that would fix records in
// classes) is to call the user record's default
// constructor if it takes no arguments. This is not the
// currently described behavior in the spec. This would
// require the user to implement a default constructor if
// explicit memory allocation is required.
//
if (!isAggregateType(formal->type) ||
(isRecord(formal->type) &&
((formal->type->getModule()->modTag==MOD_INTERNAL) ||
(formal->type->getModule()->modTag==MOD_STANDARD))) ||
!typeHasRefField(formal->type))
tmp->addFlag(FLAG_INSERT_AUTO_DESTROY);
}
} else
{
fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, formal));
// If this is a simple move, then we did not call chpl__autoCopy to
// create tmp, so then it is a bad idea to insert a call to
// chpl__autodestroy later.
tmp->removeFlag(FLAG_INSERT_AUTO_DESTROY);
}
break;
}
}
fn->insertAtHead(new DefExpr(tmp));
// For inout or out intent, this assigns the modified value back to the
// formal at the end of the function body.
if (formal->intent == INTENT_INOUT || formal->intent == INTENT_OUT) {
fn->insertBeforeReturnAfterLabel(new CallExpr("=", formal, tmp));
}
}
}
//
//
//
static Expr* dropUnnecessaryCast(CallExpr* call) {
// Check for and remove casts to the original type and size
Expr* result = call;
if (!call->isNamed("_cast"))
INT_FATAL("dropUnnecessaryCasts called on non _cast call");
if (SymExpr* sym = toSymExpr(call->get(2))) {
if (VarSymbol* var = toVarSymbol(sym->var)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
Type* oldType = var->type;
Type* newType = sym->var->type;
if (newType == oldType) {
result = new SymExpr(var);
call->replace(result);
}
}
} else if (EnumSymbol* e = toEnumSymbol(sym->var)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
EnumType* oldType = toEnumType(e->type);
EnumType* newType = toEnumType(sym->var->type);
if (newType && oldType == newType) {
result = new SymExpr(e);
call->replace(result);
}
}
}
}
return result;
}
/*
Creates the parent class which will represent the function's type. Children of the parent class will capture different functions which
happen to share the same function type. By using the parent class we can assign new values onto variable that match the function type
but may currently be pointing at a different function.
*/
static AggregateType* createAndInsertFunParentClass(CallExpr *call, const char *name) {
AggregateType *parent = new AggregateType(AGGREGATE_CLASS);
TypeSymbol *parent_ts = new TypeSymbol(name, parent);
parent_ts->addFlag(FLAG_FUNCTION_CLASS);
// Because this function type needs to be globally visible (because we don't know the modules it will be passed to), we put
// it at the highest scope
theProgram->block->body.insertAtTail(new DefExpr(parent_ts));
parent->dispatchParents.add(dtObject);
dtObject->dispatchChildren.add(parent);
VarSymbol* parent_super = new VarSymbol("super", dtObject);
parent_super->addFlag(FLAG_SUPER_CLASS);
parent->fields.insertAtHead(new DefExpr(parent_super));
build_constructors(parent);
buildDefaultDestructor(parent);
return parent;
}
/*
To mimic a function call, we create a .this method for the parent class. This will allow the object to look and feel like a
first-class function, by both being an object and being invoked using parentheses syntax. Children of the parent class will
override this method and wrap the function that is being used as a first-class value.
To focus on just the types of the arguments and not their names or default values, we use the parent method's names and types
as the basis for all children which override it.
The function is put at the highest scope so that all functions of a given type will share the same parent class.
*/
static FnSymbol* createAndInsertFunParentMethod(CallExpr *call, AggregateType *parent, AList &arg_list, bool isFormal, Type *retType) {
FnSymbol* parent_method = new FnSymbol("this");
parent_method->addFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION);
parent_method->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
parent_method->addFlag(FLAG_METHOD);
ArgSymbol* thisParentSymbol = new ArgSymbol(INTENT_BLANK, "this", parent);
thisParentSymbol->addFlag(FLAG_ARG_THIS);
parent_method->insertFormalAtTail(thisParentSymbol);
parent_method->_this = thisParentSymbol;
int i = 0, alength = arg_list.length;
//We handle the arg list differently depending on if it's a list of formal args or actual args
if (isFormal) {
for_alist(formalExpr, arg_list) {
DefExpr* dExp = toDefExpr(formalExpr);
ArgSymbol* fArg = toArgSymbol(dExp->sym);
if (fArg->type != dtVoid) {
ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, fArg->name, fArg->type);
if (fArg->typeExpr)
newFormal->typeExpr = fArg->typeExpr->copy();
parent_method->insertFormalAtTail(newFormal);
}
}
}
else {
char name_buffer[100];
int name_index = 0;
for_alist(actualExpr, arg_list) {
sprintf(name_buffer, "name%i", name_index++);
if (i != (alength-1)) {
SymExpr* sExpr = toSymExpr(actualExpr);
if (sExpr->var->type != dtVoid) {
ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, name_buffer, sExpr->var->type);
parent_method->insertFormalAtTail(newFormal);
}
}
++i;
}
}
if (retType != dtVoid) {
VarSymbol *tmp = newTemp("_return_tmp_", retType);
parent_method->insertAtTail(new DefExpr(tmp));
parent_method->insertAtTail(new CallExpr(PRIM_RETURN, tmp));
}
// Because this function type needs to be globally visible (because we don't know the modules it will be passed to), we put
// it at the highest scope
theProgram->block->body.insertAtTail(new DefExpr(parent_method));
normalize(parent_method);
parent->methods.add(parent_method);
return parent_method;
}
/*
Builds up the name of the parent for lookup by looking through the types of the arguments, either formal or actual
*/
static std::string buildParentName(AList &arg_list, bool isFormal, Type *retType) {
std::ostringstream oss;
oss << "chpl__fcf_type_";
bool isFirst = true;
if (isFormal) {
if (arg_list.length == 0) {
oss << "void";
}
else {
for_alist(formalExpr, arg_list) {
DefExpr* dExp = toDefExpr(formalExpr);
ArgSymbol* fArg = toArgSymbol(dExp->sym);
if (!isFirst)
oss << "_";
oss << fArg->type->symbol->cname;
isFirst = false;
}
}
oss << "_";
oss << retType->symbol->cname;
}
else {
int i = 0, alength = arg_list.length;
if (alength == 1) {
oss << "void_";
}
for_alist(actualExpr, arg_list) {
if (!isFirst)
oss << "_";
SymExpr* sExpr = toSymExpr(actualExpr);
++i;
oss << sExpr->var->type->symbol->cname;
isFirst = false;
}
}
return oss.str();
}
/*
Helper function for creating or finding the parent class for a given function type specified
by the type signature. The last type given in the signature is the return type, the remainder
represent arguments to the function.
*/
static AggregateType* createOrFindFunTypeFromAnnotation(AList &arg_list, CallExpr *call) {
AggregateType *parent;
SymExpr *retTail = toSymExpr(arg_list.tail);
Type *retType = retTail->var->type;
std::string parent_name = buildParentName(arg_list, false, retType);
if (functionTypeMap.find(parent_name) != functionTypeMap.end()) {
parent = functionTypeMap[parent_name].first;
} else {
parent = createAndInsertFunParentClass(call, parent_name.c_str());
FnSymbol* parent_method = createAndInsertFunParentMethod(call, parent, arg_list, false, retType);
functionTypeMap[parent_name] = std::pair<AggregateType*, FnSymbol*>(parent, parent_method);
}
return parent;
}
/*
Captures a function as a first-class value by creating an object that will represent the function. The class is
created at the same scope as the function being referenced. Each class is unique and shared among all
uses of that function as a value. Once built, the class will override the .this method of the parent and wrap
the call to the function being captured as a value. Then, an instance of the class is instantiated and returned.
*/
static Expr*
createFunctionAsValue(CallExpr *call) {
static int unique_fcf_id = 0;
UnresolvedSymExpr* use = toUnresolvedSymExpr(call->get(1));
INT_ASSERT(use);
const char *flname = use->unresolved;
Vec<FnSymbol*> visibleFns;
Vec<BlockStmt*> visited;
getVisibleFunctions(getVisibilityBlock(call), flname, visibleFns, visited);
if (visibleFns.n > 1) {
USR_FATAL(call, "%s: can not capture overloaded functions as values",
visibleFns.v[0]->name);
}
INT_ASSERT(visibleFns.n == 1);
FnSymbol* captured_fn = visibleFns.head();
//Check to see if we've already cached the capture somewhere
if (functionCaptureMap.find(captured_fn) != functionCaptureMap.end()) {
return new CallExpr(functionCaptureMap[captured_fn]);
}
resolveFormals(captured_fn);
resolveFns(captured_fn);
AggregateType *parent;
FnSymbol *thisParentMethod;
std::string parent_name = buildParentName(captured_fn->formals, true, captured_fn->retType);
if (functionTypeMap.find(parent_name) != functionTypeMap.end()) {
std::pair<AggregateType*, FnSymbol*> ctfs = functionTypeMap[parent_name];
parent = ctfs.first;
thisParentMethod = ctfs.second;
}
else {
parent = createAndInsertFunParentClass(call, parent_name.c_str());
thisParentMethod = createAndInsertFunParentMethod(call, parent, captured_fn->formals, true, captured_fn->retType);
functionTypeMap[parent_name] = std::pair<AggregateType*, FnSymbol*>(parent, thisParentMethod);
}
AggregateType *ct = new AggregateType(AGGREGATE_CLASS);
std::ostringstream fcf_name;
fcf_name << "_chpl_fcf_" << unique_fcf_id++ << "_" << flname;
TypeSymbol *ts = new TypeSymbol(astr(fcf_name.str().c_str()), ct);
call->parentExpr->insertBefore(new DefExpr(ts));
ct->dispatchParents.add(parent);
bool inserted = parent->dispatchChildren.add_exclusive(ct);
INT_ASSERT(inserted);
VarSymbol* super = new VarSymbol("super", parent);
super->addFlag(FLAG_SUPER_CLASS);
ct->fields.insertAtHead(new DefExpr(super));
build_constructors(ct);
buildDefaultDestructor(ct);
FnSymbol *thisMethod = new FnSymbol("this");
thisMethod->addFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION);
thisMethod->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken));
thisMethod->addFlag(FLAG_METHOD);
ArgSymbol *thisSymbol = new ArgSymbol(INTENT_BLANK, "this", ct);
thisSymbol->addFlag(FLAG_ARG_THIS);
thisMethod->insertFormalAtTail(thisSymbol);
thisMethod->_this = thisSymbol;
CallExpr *innerCall = new CallExpr(captured_fn);
int skip = 2;
for_alist(formalExpr, thisParentMethod->formals) {
//Skip the first two arguments from the parent, which are _mt and this
if (skip) {
--skip;
continue;
}
DefExpr* dExp = toDefExpr(formalExpr);
ArgSymbol* fArg = toArgSymbol(dExp->sym);
ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, fArg->name, fArg->type);
if (fArg->typeExpr)
newFormal->typeExpr = fArg->typeExpr->copy();
SymExpr* argSym = new SymExpr(newFormal);
innerCall->insertAtTail(argSym);
thisMethod->insertFormalAtTail(newFormal);
}
std::vector<CallExpr*> calls;
collectCallExprs(captured_fn, calls);
for_vector(CallExpr, cl, calls) {
if (cl->isPrimitive(PRIM_YIELD)) {
USR_FATAL_CONT(cl, "Iterators not allowed in first class functions");
}
}
if (captured_fn->retType == dtVoid) {
thisMethod->insertAtTail(innerCall);
}
else {
VarSymbol *tmp = newTemp("_return_tmp_");
thisMethod->insertAtTail(new DefExpr(tmp));
thisMethod->insertAtTail(new CallExpr(PRIM_MOVE, tmp, innerCall));
thisMethod->insertAtTail(new CallExpr(PRIM_RETURN, tmp));
}
call->parentExpr->insertBefore(new DefExpr(thisMethod));
normalize(thisMethod);
ct->methods.add(thisMethod);
FnSymbol *wrapper = new FnSymbol("wrapper");
wrapper->addFlag(FLAG_INLINE);
wrapper->insertAtTail(new CallExpr(PRIM_RETURN, new CallExpr(PRIM_CAST, parent->symbol, new CallExpr(ct->defaultInitializer))));
call->getStmtExpr()->insertBefore(new DefExpr(wrapper));
normalize(wrapper);
CallExpr *call_wrapper = new CallExpr(wrapper);
functionCaptureMap[captured_fn] = wrapper;
return call_wrapper;
}
//
// returns true if the symbol is defined in an outer function to fn
// third argument not used at call site
//
static bool
isOuterVar(Symbol* sym, FnSymbol* fn, Symbol* parent /* = NULL*/) {
if (!parent)
parent = fn->defPoint->parentSymbol;
if (!isFnSymbol(parent))
return false;
else if (sym->defPoint->parentSymbol == parent)
return true;
else
return isOuterVar(sym, fn, parent->defPoint->parentSymbol);
}
//
// finds outer vars directly used in a function
//
static bool
usesOuterVars(FnSymbol* fn, Vec<FnSymbol*> &seen) {
std::vector<BaseAST*> asts;
collect_asts(fn, asts);
for_vector(BaseAST, ast, asts) {
if (toCallExpr(ast)) {
CallExpr *call = toCallExpr(ast);
//dive into calls
Vec<FnSymbol*> visibleFns;
Vec<BlockStmt*> visited;
getVisibleFunctions(getVisibilityBlock(call), call->parentSymbol->name, visibleFns, visited);
forv_Vec(FnSymbol, called_fn, visibleFns) {
bool seen_this_fn = false;
forv_Vec(FnSymbol, seen_fn, seen) {
if (called_fn == seen_fn) {
seen_this_fn = true;
break;
}
}
if (!seen_this_fn) {
seen.add(called_fn);
if (usesOuterVars(called_fn, seen)) {
return true;
}
}
}
}
if (SymExpr* symExpr = toSymExpr(ast)) {
Symbol* sym = symExpr->var;
if (isLcnSymbol(sym)) {
if (isOuterVar(sym, fn))
return true;
}
}
}
return false;
}
static bool
isNormalField(Symbol* field)
{
if( field->hasFlag(FLAG_IMPLICIT_ALIAS_FIELD) ) return false;
if( field->hasFlag(FLAG_TYPE_VARIABLE) ) return false;
if( field->hasFlag(FLAG_SUPER_CLASS) ) return false;
// TODO -- this will break user fields named outer!
if( 0 == strcmp("outer", field->name)) return false;
return true;
}
static CallExpr* toPrimToLeaderCall(Expr* expr) {
if (CallExpr* call = toCallExpr(expr))
if (call->isPrimitive(PRIM_TO_LEADER) ||
call->isPrimitive(PRIM_TO_STANDALONE))
return call;
return NULL;
}
// Recursively resolve typedefs
static Type* resolveTypeAlias(SymExpr* se)
{
if (! se)
return NULL;
// Quick exit if the type is already known.
Type* result = se->getValType();
if (result != dtUnknown)
return result;
VarSymbol* var = toVarSymbol(se->var);
if (! var)
return NULL;
DefExpr* def = var->defPoint;
SET_LINENO(def);
Expr* typeExpr = resolve_type_expr(def->init);
SymExpr* tse = toSymExpr(typeExpr);
return resolveTypeAlias(tse);
}
// Returns NULL if no substitution was made. Otherwise, returns the expression
// that replaced 'call'.
static Expr* resolveTupleIndexing(CallExpr* call, Symbol* baseVar)
{
if (call->numActuals() != 3)
USR_FATAL(call, "illegal tuple indexing expression");
Type* indexType = call->get(3)->getValType();
if (!is_int_type(indexType) && !is_uint_type(indexType))
USR_FATAL(call, "tuple indexing expression is not of integral type");
AggregateType* baseType = toAggregateType(baseVar->getValType());
int64_t index;
uint64_t uindex;
char field[8];
if (get_int(call->get(3), &index)) {
sprintf(field, "x%" PRId64, index);
if (index <= 0 || index >= baseType->fields.length)
USR_FATAL(call, "tuple index out-of-bounds error (%ld)", index);
} else if (get_uint(call->get(3), &uindex)) {
sprintf(field, "x%" PRIu64, uindex);
if (uindex <= 0 || uindex >= (unsigned long)baseType->fields.length)
USR_FATAL(call, "tuple index out-of-bounds error (%lu)", uindex);
} else {
return NULL; // not a tuple indexing expression
}
Type* fieldType = baseType->getField(field)->type;
// Decomposing into a loop index variable from a non-var iterator?
// In some cases, extract the value and mark constant.
// See e.g. test/statements/vass/index-variable-const-errors.chpl
bool intoIndexVarByVal = false;
// If decomposing this special variable
// or another tuple that we just decomposed.
if (baseVar->hasFlag(FLAG_INDEX_OF_INTEREST)) {
// Find the destination.
CallExpr* move = toCallExpr(call->parentExpr);
INT_ASSERT(move && move->isPrimitive(PRIM_MOVE));
SymExpr* destSE = toSymExpr(move->get(1));
INT_ASSERT(destSE);
if (!isReferenceType(baseVar->type) &&
!isReferenceType(fieldType)) {
if (destSE->var->hasFlag(FLAG_INDEX_VAR)) {
// The destination is constant only if both the tuple
// and the current component are non-references.
// And it's not an array (arrays are always yielded by reference)
// - see boundaries() in release/examples/benchmarks/miniMD/miniMD.
if (!fieldType->symbol->hasFlag(FLAG_ARRAY)) {
destSE->var->addFlag(FLAG_CONST);
}
} else {
INT_ASSERT(destSE->var->hasFlag(FLAG_TEMP));
// We are detupling into another tuple,
// which will be detupled later.
destSE->var->addFlag(FLAG_INDEX_OF_INTEREST);
}
}
if (!isReferenceType(baseVar->type))
// If either a non-var iterator or zippered,
// extract with PRIM_GET_MEMBER_VALUE.
intoIndexVarByVal = true;
}
Expr* result;
if (isReferenceType(fieldType) || intoIndexVarByVal)
result = new CallExpr(PRIM_GET_MEMBER_VALUE, baseVar, new_StringSymbol(field));
else
result = new CallExpr(PRIM_GET_MEMBER, baseVar, new_StringSymbol(field));
call->replace(result);
return result;
}
// Returns NULL if no substitution was made. Otherwise, returns the expression
// that replaced the PRIM_INIT (or PRIM_NO_INIT) expression.
// Here, "replaced" means that the PRIM_INIT (or PRIM_NO_INIT) primitive is no
// longer in the tree.
static Expr* resolvePrimInit(CallExpr* call)
{
Expr* result = NULL;
// ('init' foo) --> A default value or the result of an initializer call.
// ('no_init' foo) --> Ditto, only in some cases a simpler default value.
// The argument is expected to be a type variable.
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (!se->var->hasFlag(FLAG_TYPE_VARIABLE))
USR_FATAL(call, "invalid type specification");
Type* type = resolveTypeAlias(se);
// Do not resolve PRIM_INIT on extern types.
// These are removed later.
// It is useful to leave them in the tree, because PRIM_INIT behaves like an
// expression and has a type.
if (type->symbol->hasFlag(FLAG_EXTERN))
{
CallExpr* stmt = toCallExpr(call->parentExpr);
INT_ASSERT(stmt->isPrimitive(PRIM_MOVE));
// makeNoop(stmt);
// result = stmt;
return result;
}
// Do not resolve runtime type values yet.
// Let these flow through to replaceInitPrims().
if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
return result;
SET_LINENO(call);
if (type->defaultValue ||
type->symbol->hasFlag(FLAG_TUPLE)) {
// Very special case for the method token.
// Unfortunately, dtAny cannot (currently) bind to dtMethodToken, so
// inline proc _defaultOf(type t) where t==_MT cannot be written in module
// code.
// Maybe it would be better to indicate which calls are method calls
// through the use of a flag. Until then, we just fake in the needed
// result and short-circuit the resolution of _defaultOf(type _MT).
if (type == dtMethodToken)
{
result = new SymExpr(gMethodToken);
call->replace(result);
return result;
}
}
if (type->defaultInitializer)
{
if (type->symbol->hasFlag(FLAG_ITERATOR_RECORD))
// defaultInitializers for iterator record types cannot be called as
// default constructors. So give up now!
return result;
}
CallExpr* defOfCall = new CallExpr("_defaultOf", type->symbol);
call->replace(defOfCall);
resolveCall(defOfCall);
resolveFns(defOfCall->isResolved());
result = postFold(defOfCall);
return result;
}
static Expr*
preFold(Expr* expr) {
Expr* result = expr;
if (CallExpr* call = toCallExpr(expr)) {
// Match calls that look like: (<type-symbol> <immediate-integer>)
// and replace them with: <new-type-symbol>
// <type-symbol> is in {dtBools, dtInt, dtUint, dtReal, dtImag, dtComplex}.
// This replaces, e.g. ( dtInt[INT_SIZE_DEFAULT] 32) with dtInt[INT_SIZE_32].
if (SymExpr* sym = toSymExpr(call->baseExpr)) {
if (TypeSymbol* type = toTypeSymbol(sym->var)) {
if (call->numActuals() == 1) {
if (SymExpr* arg = toSymExpr(call->get(1))) {
if (VarSymbol* var = toVarSymbol(arg->var)) {
if (var->immediate) {
if (NUM_KIND_INT == var->immediate->const_kind ||
NUM_KIND_UINT == var->immediate->const_kind) {
int size;
if (NUM_KIND_INT == var->immediate->const_kind) {
size = var->immediate->int_value();
} else {
size = (int)var->immediate->uint_value();
}
TypeSymbol* tsize = NULL;
if (type == dtBools[BOOL_SIZE_SYS]->symbol) {
switch (size) {
case 8: tsize = dtBools[BOOL_SIZE_8]->symbol; break;
case 16: tsize = dtBools[BOOL_SIZE_16]->symbol; break;
case 32: tsize = dtBools[BOOL_SIZE_32]->symbol; break;
case 64: tsize = dtBools[BOOL_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for bool", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtInt[INT_SIZE_DEFAULT]->symbol) {
switch (size) {
case 8: tsize = dtInt[INT_SIZE_8]->symbol; break;
case 16: tsize = dtInt[INT_SIZE_16]->symbol; break;
case 32: tsize = dtInt[INT_SIZE_32]->symbol; break;
case 64: tsize = dtInt[INT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for int", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtUInt[INT_SIZE_DEFAULT]->symbol) {
switch (size) {
case 8: tsize = dtUInt[INT_SIZE_8]->symbol; break;
case 16: tsize = dtUInt[INT_SIZE_16]->symbol; break;
case 32: tsize = dtUInt[INT_SIZE_32]->symbol; break;
case 64: tsize = dtUInt[INT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for uint", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtReal[FLOAT_SIZE_64]->symbol) {
switch (size) {
case 32: tsize = dtReal[FLOAT_SIZE_32]->symbol; break;
case 64: tsize = dtReal[FLOAT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for real", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtImag[FLOAT_SIZE_64]->symbol) {
switch (size) {
case 32: tsize = dtImag[FLOAT_SIZE_32]->symbol; break;
case 64: tsize = dtImag[FLOAT_SIZE_64]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for imag", size);
}
result = new SymExpr(tsize);
call->replace(result);
} else if (type == dtComplex[COMPLEX_SIZE_128]->symbol) {
switch (size) {
case 64: tsize = dtComplex[COMPLEX_SIZE_64]->symbol; break;
case 128: tsize = dtComplex[COMPLEX_SIZE_128]->symbol; break;
default:
USR_FATAL( call, "illegal size %d for complex", size);
}
result = new SymExpr(tsize);
call->replace(result);
}
}
}
}
}
}
}
}
if (SymExpr* sym = toSymExpr(call->baseExpr)) {
if (isLcnSymbol(sym->var)) {
Expr* base = call->baseExpr;
base->replace(new UnresolvedSymExpr("this"));
call->insertAtHead(base);
call->insertAtHead(gMethodToken);
}
}
if (CallExpr* base = toCallExpr(call->baseExpr)) {
if (base->partialTag) {
for_actuals_backward(actual, base) {
actual->remove();
call->insertAtHead(actual);
}
base->replace(base->baseExpr->remove());
} else {
VarSymbol* this_temp = newTemp("_this_tmp_");
this_temp->addFlag(FLAG_EXPR_TEMP);
base->replace(new UnresolvedSymExpr("this"));
CallExpr* move = new CallExpr(PRIM_MOVE, this_temp, base);
call->insertAtHead(new SymExpr(this_temp));
call->insertAtHead(gMethodToken);
call->getStmtExpr()->insertBefore(new DefExpr(this_temp));
call->getStmtExpr()->insertBefore(move);
result = move;
return result;
}
}
if (call->isNamed("this")) {
SymExpr* base = toSymExpr(call->get(2));
INT_ASSERT(base);
if (isVarSymbol(base->var) && base->var->hasFlag(FLAG_TYPE_VARIABLE)) {
if (call->numActuals() == 2)
USR_FATAL(call, "illegal call of type");
int64_t index;
if (!get_int(call->get(3), &index))
USR_FATAL(call, "illegal type index expression");
char field[8];
sprintf(field, "x%" PRId64, index);
result = new SymExpr(base->var->type->getField(field)->type->symbol);
call->replace(result);
} else if (base && isLcnSymbol(base->var)) {
//
// resolve tuple indexing by an integral parameter
//
Type* t = base->var->getValType();
if (t->symbol->hasFlag(FLAG_TUPLE))
if (Expr* expr = resolveTupleIndexing(call, base->var))
result = expr; // call was replaced by expr
}
}
else if (call->isPrimitive(PRIM_INIT))
{
if (Expr* expr = resolvePrimInit(call))
{
// call was replaced by expr.
result = expr;
}
// No default value yet, so defer resolution of this init
// primitive until record initializer resolution.
} else if (call->isPrimitive(PRIM_NO_INIT)) {
// Lydia note: fUseNoinit does not control this section. This was
// necessary because with the definition of type defaults in the module
// code, return temporary variables would cause an infinite loop by
// trying to default initialize within the default initialization
// definition. (It is safe for these temporaries to skip default
// initialization, as they will always be assigned a value before they
// are returned.) Thus noinit must remain attached to these temporaries,
// even if --no-use-noinit is thrown. This is an implementation detail
// that the user does not need to care about.
// fUseNoinit controls the insertion of PRIM_NO_INIT statements in the
// normalize pass.
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (!se->var->hasFlag(FLAG_TYPE_VARIABLE))
USR_FATAL(call, "invalid type specification");
Type* type = call->get(1)->getValType();
if (isAggregateType(type)) {
if (type->symbol->hasFlag(FLAG_IGNORE_NOINIT)) {
// These types deal with their uninitialized fields differently than
// normal records/classes. They may require special case
// implementations, but were capable of being isolated from the new
// cases that do work.
bool nowarn = false;
// In the case of temporary variables that use noinit (at this point
// only return variables), it is not useful to warn the user we are
// still default initializing the values as they weren't the ones to
// tell us to use noinit in the first place. So squash the warning
// in this case.
if (call->parentExpr) {
CallExpr* parent = toCallExpr(call->parentExpr);
if (parent && parent->isPrimitive(PRIM_MOVE)) {
// Should always be true, but just in case...
if (SymExpr* holdsDest = toSymExpr(parent->get(1))) {
Symbol* dest = holdsDest->var;
if (dest->hasFlag(FLAG_TEMP) && !strcmp(dest->name, "ret")) {
nowarn = true;
}
}
}
}
if (!nowarn)
USR_WARN("type %s does not currently support noinit, using default initialization", type->symbol->name);
result = new CallExpr(PRIM_INIT, call->get(1)->remove());
call->replace(result);
inits.add((CallExpr *)result);
} else {
result = call;
inits.add(call);
}
}
} else if (call->isPrimitive(PRIM_TYPEOF)) {
Type* type = call->get(1)->getValType();
if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
result = new CallExpr("chpl__convertValueToRuntimeType", call->get(1)->remove());
call->replace(result);
// If this call is inside a BLOCK_TYPE_ONLY, it will be removed and the
// runtime type will not be initialized. Unset this bit to fix.
//
// Assumption: The block we need to modify is either the parent or
// grandparent expression of the call.
BlockStmt* blk = NULL;
if ((blk = toBlockStmt(result->parentExpr))) {
// If the call's parent expression is a block, we assume it to
// be a scopeless type_only block.
INT_ASSERT(blk->blockTag & BLOCK_TYPE);
} else {
// The grandparent block doesn't necessarily have the BLOCK_TYPE_ONLY
// flag.
blk = toBlockStmt(result->parentExpr->parentExpr);
}
if (blk) {
(unsigned&)(blk->blockTag) &= ~(unsigned)BLOCK_TYPE_ONLY;
}
}
} else if (call->isPrimitive(PRIM_QUERY)) {
Symbol* field = determineQueriedField(call);
if (field && (field->hasFlag(FLAG_PARAM) || field->hasFlag(FLAG_TYPE_VARIABLE))) {
result = new CallExpr(field->name, gMethodToken, call->get(1)->remove());
call->replace(result);
} else if (isInstantiatedField(field)) {
VarSymbol* tmp = newTemp("_instantiated_field_tmp_");
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_TUPLE) && field->name[0] == 'x')
result = new CallExpr(PRIM_GET_MEMBER_VALUE, call->get(1)->remove(), new_StringSymbol(field->name));
else
result = new CallExpr(field->name, gMethodToken, call->get(1)->remove());
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, result));
call->replace(new CallExpr(PRIM_TYPEOF, tmp));
} else
USR_FATAL(call, "invalid query -- queried field must be a type or parameter");
} else if (call->isPrimitive(PRIM_CAPTURE_FN)) {
result = createFunctionAsValue(call);
call->replace(result);
} else if (call->isPrimitive(PRIM_CREATE_FN_TYPE)) {
AggregateType *parent = createOrFindFunTypeFromAnnotation(call->argList, call);
result = new SymExpr(parent->symbol);
call->replace(result);
} else if (call->isNamed("chpl__initCopy") ||
call->isNamed("chpl__autoCopy")) {
if (call->numActuals() == 1) {
if (SymExpr* symExpr = toSymExpr(call->get(1))) {
if (VarSymbol* var = toVarSymbol(symExpr->var)) {
if (var->immediate) {
result = new SymExpr(var);
call->replace(result);
}
} else {
if (EnumSymbol* var = toEnumSymbol(symExpr->var)) {
// Treat enum values as immediates
result = new SymExpr(var);
call->replace(result);
}
}
}
}
} else if (call->isNamed("_cast")) {
result = dropUnnecessaryCast(call);
if (result == call) {
// The cast was not dropped. Remove integer casts on immediate values.
if (SymExpr* sym = toSymExpr(call->get(2))) {
if (VarSymbol* var = toVarSymbol(sym->var)) {
if (var->immediate) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
Type* oldType = var->type;
Type* newType = sym->var->type;
if ((is_int_type(oldType) || is_uint_type(oldType) ||
is_bool_type(oldType)) &&
(is_int_type(newType) || is_uint_type(newType) ||
is_bool_type(newType) || is_enum_type(newType) ||
(newType == dtStringC))) {
VarSymbol* typevar = toVarSymbol(newType->defaultValue);
EnumType* typeenum = toEnumType(newType);
if (typevar) {
if (!typevar->immediate)
INT_FATAL("unexpected case in cast_fold");
Immediate coerce = *typevar->immediate;
coerce_immediate(var->immediate, &coerce);
result = new SymExpr(new_ImmediateSymbol(&coerce));
call->replace(result);
} else if (typeenum) {
int64_t value, count = 0;
bool replaced = false;
if (!get_int(call->get(2), &value)) {
INT_FATAL("unexpected case in cast_fold");
}
for_enums(constant, typeenum) {
if (!get_int(constant->init, &count)) {
count++;
}
if (count == value) {
result = new SymExpr(constant->sym);
call->replace(result);
replaced = true;
break;
}
}
if (!replaced) {
USR_FATAL(call->get(2), "enum cast out of bounds");
}
} else {
INT_FATAL("unexpected case in cast_fold");
}
}
}
}
} else if (EnumSymbol* enumSym = toEnumSymbol(sym->var)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
Type* newType = sym->var->type;
if (newType == dtStringC) {
result = new SymExpr(new_StringSymbol(enumSym->name));
call->replace(result);
}
}
}
}
}
} else if (call->isNamed("==")) {
if (isTypeExpr(call->get(1)) && isTypeExpr(call->get(2))) {
Type* lt = call->get(1)->getValType();
Type* rt = call->get(2)->getValType();
if (lt != dtUnknown && rt != dtUnknown &&
!lt->symbol->hasFlag(FLAG_GENERIC) &&
!rt->symbol->hasFlag(FLAG_GENERIC)) {
result = (lt == rt) ? new SymExpr(gTrue) : new SymExpr(gFalse);
call->replace(result);
}
}
} else if (call->isNamed("!=")) {
if (isTypeExpr(call->get(1)) && isTypeExpr(call->get(2))) {
Type* lt = call->get(1)->getValType();
Type* rt = call->get(2)->getValType();
if (lt != dtUnknown && rt != dtUnknown &&
!lt->symbol->hasFlag(FLAG_GENERIC) &&
!rt->symbol->hasFlag(FLAG_GENERIC)) {
result = (lt != rt) ? new SymExpr(gTrue) : new SymExpr(gFalse);
call->replace(result);
}
}
} else if (call->isNamed("_type_construct__tuple") && !call->isResolved()) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
if (VarSymbol* var = toVarSymbol(sym->var)) {
if (var->immediate) {
int rank = var->immediate->int_value();
if (rank != call->numActuals() - 1) {
if (call->numActuals() != 2)
INT_FATAL(call, "bad homogeneous tuple");
Expr* actual = call->get(2);
for (int i = 1; i < rank; i++) {
call->insertAtTail(actual->copy());
}
}
}
}
}
} else if (call->isPrimitive(PRIM_BLOCK_PARAM_LOOP)) {
ParamForLoop* paramLoop = toParamForLoop(call->parentExpr);
result = paramLoop->foldForResolve();
} else if (call->isPrimitive(PRIM_LOGICAL_FOLDER)) {
bool removed = false;
SymExpr* sym1 = toSymExpr(call->get(1));
if (VarSymbol* sym = toVarSymbol(sym1->var)) {
if (sym->immediate || paramMap.get(sym)) {
CallExpr* mvCall = toCallExpr(call->parentExpr);
SymExpr* sym = toSymExpr(mvCall->get(1));
VarSymbol* var = toVarSymbol(sym->var);
removed = true;
var->addFlag(FLAG_MAYBE_PARAM);
result = call->get(2)->remove();
call->replace(result);
}
}
if (!removed) {
result = call->get(2)->remove();
call->replace(result);
}
} else if (call->isPrimitive(PRIM_ADDR_OF)) {
// remove set ref if already a reference
if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) {
result = call->get(1)->remove();
call->replace(result);
} else {
// This test is turned off if we are in a wrapper function.
FnSymbol* fn = call->getFunction();
if (!fn->hasFlag(FLAG_WRAPPER)) {
SymExpr* lhs = NULL;
// check legal var function return
if (CallExpr* move = toCallExpr(call->parentExpr)) {
if (move->isPrimitive(PRIM_MOVE)) {
lhs = toSymExpr(move->get(1));
if (lhs && lhs->var == fn->getReturnSymbol()) {
SymExpr* ret = toSymExpr(call->get(1));
INT_ASSERT(ret);
if (ret->var->defPoint->getFunction() == move->getFunction() &&
!ret->var->type->symbol->hasFlag(FLAG_ITERATOR_RECORD) &&
!ret->var->type->symbol->hasFlag(FLAG_ARRAY))
// Should this conditional include domains, distributions, sync and/or single?
USR_FATAL(ret, "illegal expression to return by ref");
if (ret->var->isConstant() || ret->var->isParameter())
USR_FATAL(ret, "function cannot return constant by ref");
}
}
}
//
// check that the operand of 'addr of' is a legal lvalue.
if (SymExpr* rhs = toSymExpr(call->get(1))) {
if (!(lhs && lhs->var->hasFlag(FLAG_REF_VAR) && lhs->var->hasFlag(FLAG_CONST))) {
if (rhs->var->hasFlag(FLAG_EXPR_TEMP) || rhs->var->isConstant() || rhs->var->isParameter()) {
if (lhs && lhs->var->hasFlag(FLAG_REF_VAR)) {
if (rhs->var->isImmediate()) {
USR_FATAL_CONT(call, "Cannot set a non-const reference to a literal value.");
} else {
// We should not fall into this case... should be handled in normalize
INT_FATAL(call, "Cannot set a non-const reference to a const variable.");
}
} else {
// This probably indicates that an invalid 'addr of' primitive
// was inserted, which would be the compiler's fault, not the
// user's.
// At least, we might perform the check at or before the 'addr
// of' primitive is inserted.
INT_FATAL(call, "A non-lvalue appears where an lvalue is expected.");
}
}
}
}
}
}
} else if (call->isPrimitive(PRIM_DEREF)) {
// remove deref if arg is already a value
if (!call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) {
result = call->get(1)->remove();
call->replace(result);
}
} else if (call->isPrimitive(PRIM_TYPE_TO_STRING)) {
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se && se->var->hasFlag(FLAG_TYPE_VARIABLE));
result = new SymExpr(new_StringSymbol(se->var->type->symbol->name));
call->replace(result);
} else if (call->isPrimitive(PRIM_WIDE_GET_LOCALE) ||
call->isPrimitive(PRIM_WIDE_GET_NODE)) {
Type* type = call->get(1)->getValType();
//
// ensure .locale (and on) are applied to lvalues or classes
// (locale type is a class)
//
SymExpr* se = toSymExpr(call->get(1));
if (se->var->hasFlag(FLAG_EXPR_TEMP) && !isClass(type))
USR_WARN(se, "accessing the locale of a local expression");
//
// if .locale is applied to an expression of array, domain, or distribution
// wrapper type, apply .locale to the _value field of the
// wrapper
//
if (isRecordWrappedType(type)) {
VarSymbol* tmp = newTemp("_locale_tmp_");
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
result = new CallExpr("_value", gMethodToken, call->get(1)->remove());
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, result));
call->insertAtTail(tmp);
}
} else if (call->isPrimitive(PRIM_TO_STANDALONE)) {
FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer;
CallExpr* standaloneCall = new CallExpr(iterator->name);
for_formals(formal, iterator) {
standaloneCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal)));
}
// "tag" should be placed at the end of the formals in the source code as
// well, to avoid insertion of an order wrapper.
standaloneCall->insertAtTail(new NamedExpr("tag", new SymExpr(gStandaloneTag)));
call->replace(standaloneCall);
result = standaloneCall;
} else if (call->isPrimitive(PRIM_TO_LEADER)) {
FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer;
CallExpr* leaderCall;
if (FnSymbol* leader = iteratorLeaderMap.get(iterator))
leaderCall = new CallExpr(leader);
else
leaderCall = new CallExpr(iterator->name);
for_formals(formal, iterator) {
leaderCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal)));
}
// "tag" should be placed at the end of the formals in the source code as
// well, to avoid insertion of an order wrapper.
leaderCall->insertAtTail(new NamedExpr("tag", new SymExpr(gLeaderTag)));
call->replace(leaderCall);
result = leaderCall;
} else if (call->isPrimitive(PRIM_TO_FOLLOWER)) {
FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer;
CallExpr* followerCall;
if (FnSymbol* follower = iteratorFollowerMap.get(iterator))
followerCall = new CallExpr(follower);
else
followerCall = new CallExpr(iterator->name);
for_formals(formal, iterator) {
followerCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal)));
}
// "tag", "followThis" and optionally "fast" should be placed at the end
// of the formals in the source code as well, to avoid insertion of an
// order wrapper.
followerCall->insertAtTail(new NamedExpr("tag", new SymExpr(gFollowerTag)));
followerCall->insertAtTail(new NamedExpr(iterFollowthisArgname, call->get(2)->remove()));
if (call->numActuals() > 1) {
followerCall->insertAtTail(new NamedExpr("fast", call->get(2)->remove()));
}
call->replace(followerCall);
result = followerCall;
} else if (call->isPrimitive(PRIM_NUM_FIELDS)) {
AggregateType* classtype = toAggregateType(toSymExpr(call->get(1))->var->type);
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
}
result = new SymExpr(new_IntSymbol(fieldcount));
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_NUM_TO_NAME)) {
AggregateType* classtype = toAggregateType(toSymExpr(call->get(1))->var->type);
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
int fieldnum = var->immediate->int_value();
int fieldcount = 0;
const char* name = NULL;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if (fieldcount == fieldnum) {
name = field->name;
}
}
if (!name) {
// In this case, we ran out of fields without finding the number
// specified. This is the user's error.
USR_FATAL(call, "'%d' is not a valid field number", fieldnum);
}
result = new SymExpr(new_StringSymbol(name));
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_VALUE_BY_NUM)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
int fieldnum = var->immediate->int_value();
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if (fieldcount == fieldnum) {
result = new CallExpr(PRIM_GET_MEMBER, call->get(1)->copy(),
new_StringSymbol(field->name));
break;
}
}
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_ID_BY_NUM)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
int fieldnum = var->immediate->int_value();
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if (fieldcount == fieldnum) {
result = new SymExpr(new_IntSymbol(field->id));
break;
}
}
call->replace(result);
} else if (call->isPrimitive(PRIM_FIELD_VALUE_BY_NAME)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
INT_ASSERT( classtype != NULL );
classtype = toAggregateType(classtype->getValType());
INT_ASSERT( classtype != NULL );
VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var);
INT_ASSERT( var != NULL );
Immediate* imm = var->immediate;
INT_ASSERT( classtype != NULL );
// fail horribly if immediate is not a string .
INT_ASSERT(imm->const_kind == CONST_KIND_STRING);
const char* fieldname = imm->v_string;
int fieldcount = 0;
for_fields(field, classtype) {
if( ! isNormalField(field) ) continue;
fieldcount++;
if ( 0 == strcmp(field->name, fieldname) ) {
result = new CallExpr(PRIM_GET_MEMBER, call->get(1)->copy(),
new_StringSymbol(field->name));
break;
}
}
call->replace(result);
} else if (call->isPrimitive(PRIM_ENUM_MIN_BITS) || call->isPrimitive(PRIM_ENUM_IS_SIGNED)) {
EnumType* et = toEnumType(toSymExpr(call->get(1))->var->type);
ensureEnumTypeResolved(et);
result = NULL;
if( call->isPrimitive(PRIM_ENUM_MIN_BITS) ) {
result = new SymExpr(new_IntSymbol(get_width(et->integerType)));
} else if( call->isPrimitive(PRIM_ENUM_IS_SIGNED) ) {
if( is_int_type(et->integerType) )
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
}
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_UNION_TYPE)) {
AggregateType* classtype = toAggregateType(call->get(1)->typeInfo());
if( isUnion(classtype) )
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_ATOMIC_TYPE)) {
if (isAtomicType(call->get(1)->typeInfo()))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_SYNC_TYPE)) {
Type* syncType = call->get(1)->typeInfo();
if (syncType->symbol->hasFlag(FLAG_SYNC))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_SINGLE_TYPE)) {
Type* singleType = call->get(1)->typeInfo();
if (singleType->symbol->hasFlag(FLAG_SINGLE))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_TUPLE_TYPE)) {
Type* tupleType = call->get(1)->typeInfo();
if (tupleType->symbol->hasFlag(FLAG_TUPLE))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
} else if (call->isPrimitive(PRIM_IS_STAR_TUPLE_TYPE)) {
Type* tupleType = call->get(1)->typeInfo();
INT_ASSERT(tupleType->symbol->hasFlag(FLAG_TUPLE));
if (tupleType->symbol->hasFlag(FLAG_STAR_TUPLE))
result = new SymExpr(gTrue);
else
result = new SymExpr(gFalse);
call->replace(result);
}
}
//
// ensure result of pre-folding is in the AST
//
INT_ASSERT(result->parentSymbol);
return result;
}
static void foldEnumOp(int op, EnumSymbol *e1, EnumSymbol *e2, Immediate *imm) {
int64_t val1 = -1, val2 = -1, count = 0;
// ^^^ This is an assumption that "long" on the compiler host is at
// least as big as "int" on the target. This is not guaranteed to be true.
EnumType *type1, *type2;
type1 = toEnumType(e1->type);
type2 = toEnumType(e2->type);
INT_ASSERT(type1 && type2);
// Loop over the enum values to find the int value of e1
for_enums(constant, type1) {
if (!get_int(constant->init, &count)) {
count++;
}
if (constant->sym == e1) {
val1 = count;
break;
}
}
// Loop over the enum values to find the int value of e2
count = 0;
for_enums(constant, type2) {
if (!get_int(constant->init, &count)) {
count++;
}
if (constant->sym == e2) {
val2 = count;
break;
}
}
// All operators on enum types result in a bool
imm->const_kind = NUM_KIND_BOOL;
imm->num_index = BOOL_SIZE_SYS;
switch (op) {
default: INT_FATAL("fold constant op not supported"); break;
case P_prim_equal:
imm->v_bool = val1 == val2;
break;
case P_prim_notequal:
imm->v_bool = val1 != val2;
break;
case P_prim_less:
imm->v_bool = val1 < val2;
break;
case P_prim_lessorequal:
imm->v_bool = val1 <= val2;
break;
case P_prim_greater:
imm->v_bool = val1 > val2;
break;
case P_prim_greaterorequal:
imm->v_bool = val1 >= val2;
break;
}
}
#define FOLD_CALL1(prim) \
if (SymExpr* sym = toSymExpr(call->get(1))) { \
if (VarSymbol* lhs = toVarSymbol(sym->var)) { \
if (lhs->immediate) { \
Immediate i3; \
fold_constant(prim, lhs->immediate, NULL, &i3); \
result = new SymExpr(new_ImmediateSymbol(&i3)); \
call->replace(result); \
} \
} \
}
#define FOLD_CALL2(prim) \
if (SymExpr* sym = toSymExpr(call->get(1))) { \
if (VarSymbol* lhs = toVarSymbol(sym->var)) { \
if (lhs->immediate) { \
if (SymExpr* sym = toSymExpr(call->get(2))) { \
if (VarSymbol* rhs = toVarSymbol(sym->var)) { \
if (rhs->immediate) { \
Immediate i3; \
fold_constant(prim, lhs->immediate, rhs->immediate, &i3); \
result = new SymExpr(new_ImmediateSymbol(&i3)); \
call->replace(result); \
} \
} \
} \
} \
} else if (EnumSymbol* lhs = toEnumSymbol(sym->var)) { \
if (SymExpr* sym = toSymExpr(call->get(2))) { \
if (EnumSymbol* rhs = toEnumSymbol(sym->var)) { \
Immediate imm; \
foldEnumOp(prim, lhs, rhs, &imm); \
result = new SymExpr(new_ImmediateSymbol(&imm)); \
call->replace(result); \
} \
} \
} \
}
static bool
isSubType(Type* sub, Type* super) {
if (sub == super)
return true;
forv_Vec(Type, parent, sub->dispatchParents) {
if (isSubType(parent, super))
return true;
}
return false;
}
static void
insertValueTemp(Expr* insertPoint, Expr* actual) {
if (SymExpr* se = toSymExpr(actual)) {
if (!se->var->type->refType) {
VarSymbol* tmp = newTemp("_value_tmp_", se->var->getValType());
insertPoint->insertBefore(new DefExpr(tmp));
insertPoint->insertBefore(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_DEREF, se->var)));
se->var = tmp;
}
}
}
//
// returns resolved function if the function requires an implicit
// destroy of its returned value (i.e. reference count)
//
// Currently, FLAG_DONOR_FN is only relevant when placed on
// chpl__autoCopy().
//
FnSymbol*
requiresImplicitDestroy(CallExpr* call) {
if (FnSymbol* fn = call->isResolved()) {
FnSymbol* parent = call->getFunction();
INT_ASSERT(parent);
if (!parent->hasFlag(FLAG_DONOR_FN) &&
// No autocopy/destroy calls in a donor function (this might
// need to change when this flag is used more generally)).
// Currently, this assumes we have thoughtfully written
// chpl__autoCopy functions.
// Return type is a record (which includes array, record, and
// dist) or a ref counted type that is passed by reference
(isRecord(fn->retType) ||
(fn->retType->symbol->hasFlag(FLAG_REF) &&
isRefCountedType(fn->retType->getValType()))) &&
// These are special functions where we don't want to destroy
// the result
!fn->hasFlag(FLAG_NO_IMPLICIT_COPY) &&
!fn->isIterator() &&
!fn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE) &&
!fn->hasFlag(FLAG_DONOR_FN) &&
!fn->hasFlag(FLAG_INIT_COPY_FN) &&
strcmp(fn->name, "=") &&
strcmp(fn->name, "_defaultOf") &&
!fn->hasFlag(FLAG_AUTO_II) &&
!fn->hasFlag(FLAG_CONSTRUCTOR) &&
!fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
return fn;
}
}
return NULL;
}
static Expr*
postFold(Expr* expr) {
Expr* result = expr;
if (!expr->parentSymbol)
return result;
SET_LINENO(expr);
if (CallExpr* call = toCallExpr(expr)) {
if (FnSymbol* fn = call->isResolved()) {
if (fn->retTag == RET_PARAM || fn->hasFlag(FLAG_MAYBE_PARAM)) {
VarSymbol* ret = toVarSymbol(fn->getReturnSymbol());
if (ret && ret->immediate) {
result = new SymExpr(ret);
expr->replace(result);
} else if (EnumSymbol* es = toEnumSymbol(fn->getReturnSymbol())) {
result = new SymExpr(es);
expr->replace(result);
} else if (fn->retTag == RET_PARAM) {
USR_FATAL(call, "param function does not resolve to a param symbol");
}
}
if (fn->hasFlag(FLAG_MAYBE_TYPE) && fn->getReturnSymbol()->hasFlag(FLAG_TYPE_VARIABLE))
fn->retTag = RET_TYPE;
if (fn->retTag == RET_TYPE) {
Symbol* ret = fn->getReturnSymbol();
if (!ret->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
result = new SymExpr(ret->type->symbol);
expr->replace(result);
}
}
} else if (call->isPrimitive(PRIM_QUERY_TYPE_FIELD) ||
call->isPrimitive(PRIM_QUERY_PARAM_FIELD)) {
SymExpr* classWrap = toSymExpr(call->get(1));
// Really should be a symExpr
INT_ASSERT(classWrap);
AggregateType* ct = toAggregateType(classWrap->var->type);
if (!ct) {
USR_FATAL(call, "Attempted to obtain field of a type that was not a record or class");
}
const char* memberName = get_string(call->get(2));
// Finds the field matching the specified name.
Vec<Symbol *> keys;
ct->substitutions.get_keys(keys);
forv_Vec(Symbol, key, keys) {
if (!strcmp(memberName, key->name)) {
// If there is a substitution for it, replace this call with that
// substitution
if (Symbol* value = ct->substitutions.get(key)) {
result = new SymExpr(value);
expr->replace(result);
}
}
}
}
// param initialization should not involve PRIM_ASSIGN or "=".
else if (call->isPrimitive(PRIM_MOVE)) {
bool set = false;
if (SymExpr* lhs = toSymExpr(call->get(1))) {
if (lhs->var->hasFlag(FLAG_MAYBE_PARAM) || lhs->var->isParameter()) {
if (paramMap.get(lhs->var))
INT_FATAL(call, "parameter set multiple times");
VarSymbol* lhsVar = toVarSymbol(lhs->var);
// We are expecting the LHS to be a var (what else could it be?
if (lhsVar->immediate) {
// The value of the LHS of this move has already been
// established, most likely through a construct like
// if (cond) return x;
// return y;
// In this case, the first 'true' conditional that hits a return
// can fast-forward to the end of the routine, and some
// resolution time can be saved.
// Re-enable the fatal error to catch this case; the correct
// solution is to ensure that the containing expression is never
// resolved, using the abbreviated resolution suggested above.
// INT_ASSERT(!lhsVar->immediate);
set = true; // That is, set previously.
} else {
if (SymExpr* rhs = toSymExpr(call->get(2))) {
if (VarSymbol* rhsVar = toVarSymbol(rhs->var)) {
if (rhsVar->immediate) {
paramMap.put(lhs->var, rhsVar);
lhs->var->defPoint->remove();
makeNoop(call);
set = true;
}
}
if (EnumSymbol* rhsv = toEnumSymbol(rhs->var)) {
paramMap.put(lhs->var, rhsv);
lhs->var->defPoint->remove();
makeNoop(call);
set = true;
}
}
}
if (!set && lhs->var->isParameter())
USR_FATAL(call, "Initializing parameter '%s' to value not known at compile time", lhs->var->name);
}
if (!set) {
if (lhs->var->hasFlag(FLAG_MAYBE_TYPE)) {
// Add FLAG_TYPE_VARIABLE when relevant
if (SymExpr* rhs = toSymExpr(call->get(2))) {
if (rhs->var->hasFlag(FLAG_TYPE_VARIABLE))
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
} else if (CallExpr* rhs = toCallExpr(call->get(2))) {
if (FnSymbol* fn = rhs->isResolved()) {
if (fn->retTag == RET_TYPE)
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
} else if (rhs->isPrimitive(PRIM_DEREF)) {
if (isTypeExpr(rhs->get(1)))
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
}
}
}
if (CallExpr* rhs = toCallExpr(call->get(2))) {
if (rhs->isPrimitive(PRIM_TYPEOF)) {
lhs->var->addFlag(FLAG_TYPE_VARIABLE);
}
if (FnSymbol* fn = rhs->isResolved()) {
if (!strcmp(fn->name, "=") && fn->retType == dtVoid) {
call->replace(rhs->remove());
result = rhs;
set = true;
}
}
}
}
if (!set) {
if (lhs->var->hasFlag(FLAG_EXPR_TEMP) &&
!lhs->var->hasFlag(FLAG_TYPE_VARIABLE)) {
if (CallExpr* rhsCall = toCallExpr(call->get(2))) {
if (requiresImplicitDestroy(rhsCall)) {
lhs->var->addFlag(FLAG_INSERT_AUTO_COPY);
lhs->var->addFlag(FLAG_INSERT_AUTO_DESTROY);
}
}
}
if (isReferenceType(lhs->var->type) ||
lhs->var->type->symbol->hasFlag(FLAG_REF_ITERATOR_CLASS) ||
lhs->var->type->symbol->hasFlag(FLAG_ARRAY))
// Should this conditional include domains, distributions, sync and/or single?
lhs->var->removeFlag(FLAG_EXPR_TEMP);
}
if (!set) {
if (CallExpr* rhs = toCallExpr(call->get(2))) {
if (rhs->isPrimitive(PRIM_NO_INIT)) {
// If the lhs is a primitive, then we can safely just remove this
// value. Otherwise the type needs to be resolved a little
// further and so this statement can't be removed until
// resolveRecordInitializers
if (!isAggregateType(rhs->get(1)->getValType())) {
makeNoop(call);
}
}
}
}
}
} else if (call->isPrimitive(PRIM_GET_MEMBER)) {
Type* baseType = call->get(1)->getValType();
const char* memberName = get_string(call->get(2));
Symbol* sym = baseType->getField(memberName);
SymExpr* left = toSymExpr(call->get(1));
if (left && left->var->hasFlag(FLAG_TYPE_VARIABLE)) {
result = new SymExpr(sym->type->symbol);
call->replace(result);
} else if (sym->isParameter()) {
Vec<Symbol*> keys;
baseType->substitutions.get_keys(keys);
forv_Vec(Symbol, key, keys) {
if (!strcmp(sym->name, key->name)) {
if (Symbol* value = baseType->substitutions.get(key)) {
result = new SymExpr(value);
call->replace(result);
}
}
}
}
} else if (call->isPrimitive(PRIM_IS_SUBTYPE)) {
if (isTypeExpr(call->get(1)) || isTypeExpr(call->get(2))) {
Type* lt = call->get(2)->getValType(); // a:t cast is cast(t,a)
Type* rt = call->get(1)->getValType();
if (lt != dtUnknown && rt != dtUnknown && lt != dtAny &&
rt != dtAny && !lt->symbol->hasFlag(FLAG_GENERIC)) {
bool is_true = false;
if (lt->instantiatedFrom == rt)
is_true = true;
if (isSubType(lt, rt))
is_true = true;
result = (is_true) ? new SymExpr(gTrue) : new SymExpr(gFalse);
call->replace(result);
}
}
} else if (call->isPrimitive(PRIM_CAST)) {
Type* t= call->get(1)->typeInfo();
if (t == dtUnknown)
INT_FATAL(call, "Unable to resolve type");
call->get(1)->replace(new SymExpr(t->symbol));
} else if (call->isPrimitive("string_compare")) {
SymExpr* lhs = toSymExpr(call->get(1));
SymExpr* rhs = toSymExpr(call->get(2));
INT_ASSERT(lhs && rhs);
if (lhs->var->isParameter() && rhs->var->isParameter()) {
const char* lstr = get_string(lhs);
const char* rstr = get_string(rhs);
int comparison = strcmp(lstr, rstr);
result = new SymExpr(new_IntSymbol(comparison));
call->replace(result);
}
} else if (call->isPrimitive("string_concat")) {
SymExpr* lhs = toSymExpr(call->get(1));
SymExpr* rhs = toSymExpr(call->get(2));
INT_ASSERT(lhs && rhs);
if (lhs->var->isParameter() && rhs->var->isParameter()) {
const char* lstr = get_string(lhs);
const char* rstr = get_string(rhs);
result = new SymExpr(new_StringSymbol(astr(lstr, rstr)));
call->replace(result);
}
} else if (call->isPrimitive("string_length")) {
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (se->var->isParameter()) {
const char* str = get_string(se);
result = new SymExpr(new_IntSymbol(strlen(str), INT_SIZE_DEFAULT));
call->replace(result);
}
} else if (call->isPrimitive("ascii")) {
SymExpr* se = toSymExpr(call->get(1));
INT_ASSERT(se);
if (se->var->isParameter()) {
const char* str = get_string(se);
result = new SymExpr(new_IntSymbol((int)str[0], INT_SIZE_DEFAULT));
call->replace(result);
}
} else if (call->isPrimitive("string_contains")) {
SymExpr* lhs = toSymExpr(call->get(1));
SymExpr* rhs = toSymExpr(call->get(2));
INT_ASSERT(lhs && rhs);
if (lhs->var->isParameter() && rhs->var->isParameter()) {
const char* lstr = get_string(lhs);
const char* rstr = get_string(rhs);
result = new SymExpr(strstr(lstr, rstr) ? gTrue : gFalse);
call->replace(result);
}
} else if (call->isPrimitive(PRIM_UNARY_MINUS)) {
FOLD_CALL1(P_prim_minus);
} else if (call->isPrimitive(PRIM_UNARY_PLUS)) {
FOLD_CALL1(P_prim_plus);
} else if (call->isPrimitive(PRIM_UNARY_NOT)) {
FOLD_CALL1(P_prim_not);
} else if (call->isPrimitive(PRIM_UNARY_LNOT)) {
FOLD_CALL1(P_prim_lnot);
} else if (call->isPrimitive(PRIM_ADD)) {
FOLD_CALL2(P_prim_add);
} else if (call->isPrimitive(PRIM_SUBTRACT)) {
FOLD_CALL2(P_prim_subtract);
} else if (call->isPrimitive(PRIM_MULT)) {
FOLD_CALL2(P_prim_mult);
} else if (call->isPrimitive(PRIM_DIV)) {
FOLD_CALL2(P_prim_div);
} else if (call->isPrimitive(PRIM_MOD)) {
FOLD_CALL2(P_prim_mod);
} else if (call->isPrimitive(PRIM_EQUAL)) {
FOLD_CALL2(P_prim_equal);
} else if (call->isPrimitive(PRIM_NOTEQUAL)) {
FOLD_CALL2(P_prim_notequal);
} else if (call->isPrimitive(PRIM_LESSOREQUAL)) {
FOLD_CALL2(P_prim_lessorequal);
} else if (call->isPrimitive(PRIM_GREATEROREQUAL)) {
FOLD_CALL2(P_prim_greaterorequal);
} else if (call->isPrimitive(PRIM_LESS)) {
FOLD_CALL2(P_prim_less);
} else if (call->isPrimitive(PRIM_GREATER)) {
FOLD_CALL2(P_prim_greater);
} else if (call->isPrimitive(PRIM_AND)) {
FOLD_CALL2(P_prim_and);
} else if (call->isPrimitive(PRIM_OR)) {
FOLD_CALL2(P_prim_or);
} else if (call->isPrimitive(PRIM_XOR)) {
FOLD_CALL2(P_prim_xor);
} else if (call->isPrimitive(PRIM_POW)) {
FOLD_CALL2(P_prim_pow);
} else if (call->isPrimitive(PRIM_LSH)) {
FOLD_CALL2(P_prim_lsh);
} else if (call->isPrimitive(PRIM_RSH)) {
FOLD_CALL2(P_prim_rsh);
} else if (call->isPrimitive(PRIM_ARRAY_ALLOC) ||
call->isPrimitive(PRIM_SYNC_INIT) ||
call->isPrimitive(PRIM_SYNC_LOCK) ||
call->isPrimitive(PRIM_SYNC_UNLOCK) ||
call->isPrimitive(PRIM_SYNC_WAIT_FULL) ||
call->isPrimitive(PRIM_SYNC_WAIT_EMPTY) ||
call->isPrimitive(PRIM_SYNC_SIGNAL_FULL) ||
call->isPrimitive(PRIM_SYNC_SIGNAL_EMPTY) ||
call->isPrimitive(PRIM_SINGLE_INIT) ||
call->isPrimitive(PRIM_SINGLE_LOCK) ||
call->isPrimitive(PRIM_SINGLE_UNLOCK) ||
call->isPrimitive(PRIM_SINGLE_WAIT_FULL) ||
call->isPrimitive(PRIM_SINGLE_SIGNAL_FULL) ||
call->isPrimitive(PRIM_WRITEEF) ||
call->isPrimitive(PRIM_WRITEFF) ||
call->isPrimitive(PRIM_WRITEXF) ||
call->isPrimitive(PRIM_READFF) ||
call->isPrimitive(PRIM_READFE) ||
call->isPrimitive(PRIM_READXX) ||
call->isPrimitive(PRIM_SYNC_IS_FULL) ||
call->isPrimitive(PRIM_SINGLE_WRITEEF) ||
call->isPrimitive(PRIM_SINGLE_READFF) ||
call->isPrimitive(PRIM_SINGLE_READXX) ||
call->isPrimitive(PRIM_SINGLE_IS_FULL) ||
call->isPrimitive(PRIM_EXECUTE_TASKS_IN_LIST) ||
call->isPrimitive(PRIM_FREE_TASK_LIST) ||
(call->primitive &&
(!strncmp("_fscan", call->primitive->name, 6) ||
!strcmp("_readToEndOfLine", call->primitive->name) ||
!strcmp("_now_timer", call->primitive->name)))) {
//
// these primitives require temps to dereference actuals
// why not do this to all primitives?
//
for_actuals(actual, call) {
insertValueTemp(call->getStmtExpr(), actual);
}
}
} else if (SymExpr* sym = toSymExpr(expr)) {
if (Symbol* val = paramMap.get(sym->var)) {
CallExpr* call = toCallExpr(sym->parentExpr);
if (call && call->get(1) == sym) {
// This is a place where param substitution has already determined the
// value of a move or assignment, so we can just ignore the update.
if (call->isPrimitive(PRIM_MOVE)) {
makeNoop(call);
return result;
}
// The substitution usually happens before resolution, so for
// assignment, we key off of the name :-(
if (call->isNamed("="))
{
makeNoop(call);
return result;
}
}
if (sym->var->type != dtUnknown && sym->var->type != val->type) {
CallExpr* cast = new CallExpr("_cast", sym->var, val);
sym->replace(cast);
result = preFold(cast);
} else {
sym->var = val;
}
}
}
if (CondStmt* cond = toCondStmt(result->parentExpr)) {
if (cond->condExpr == result) {
if (Expr* expr = cond->foldConstantCondition()) {
result = expr;
} else {
//
// push try block
//
if (SymExpr* se = toSymExpr(result))
if (se->var == gTryToken)
tryStack.add(cond);
}
}
}
//
// pop try block and delete else
//
if (tryStack.n) {
if (BlockStmt* block = toBlockStmt(result)) {
if (tryStack.tail()->thenStmt == block) {
tryStack.tail()->replace(block->remove());
tryStack.pop();
}
}
}
return result;
}
static bool is_param_resolved(FnSymbol* fn, Expr* expr) {
if (BlockStmt* block = toBlockStmt(expr)) {
if (block->isWhileStmt() == true) {
USR_FATAL(expr, "param function cannot contain a non-param while loop");
} else if (block->isForLoop() == true) {
USR_FATAL(expr, "param function cannot contain a non-param for loop");
} else if (block->isLoopStmt() == true) {
USR_FATAL(expr, "param function cannot contain a non-param loop");
}
}
if (BlockStmt* block = toBlockStmt(expr->parentExpr)) {
if (isCondStmt(block->parentExpr)) {
USR_FATAL(block->parentExpr,
"param function cannot contain a non-param conditional");
}
}
if (paramMap.get(fn->getReturnSymbol())) {
CallExpr* call = toCallExpr(fn->body->body.tail);
INT_ASSERT(call);
INT_ASSERT(call->isPrimitive(PRIM_RETURN));
call->get(1)->replace(new SymExpr(paramMap.get(fn->getReturnSymbol())));
return true; // param function is resolved
}
return false;
}
// Resolves an expression and manages the callStack and tryStack.
// On success, returns the call that was passed in.
// On a try failure, returns either the expression preceding the elseStmt,
// substituted for the body of the param condition (if that substitution could
// be made), or NULL.
// If null, then resolution of the current block should be aborted. tryFailure
// is true in this case, so the search for a matching elseStmt continue in the
// surrounding block or call.
static Expr*
resolveExpr(Expr* expr) {
Expr* const origExpr = expr;
FnSymbol* fn = toFnSymbol(expr->parentSymbol);
SET_LINENO(expr);
if (SymExpr* se = toSymExpr(expr)) {
if (se->var) {
makeRefType(se->var->type);
}
}
expr = preFold(expr);
if (fn && fn->retTag == RET_PARAM) {
if (is_param_resolved(fn, expr)) {
return expr;
}
}
if (DefExpr* def = toDefExpr(expr)) {
if (def->init) {
Expr* init = preFold(def->init);
init = resolveExpr(init);
// expr is unchanged, so is treated as "resolved".
}
if (def->sym->hasFlag(FLAG_CHPL__ITER)) {
implementForallIntents1(def);
}
}
if (CallExpr* call = toCallExpr(expr)) {
if (call->isPrimitive(PRIM_ERROR) ||
call->isPrimitive(PRIM_WARNING)) {
issueCompilerError(call);
}
// Resolve expressions of the form: <type> ( args )
// These will be constructor calls (or type constructor calls) that slipped
// past normalization due to the use of typedefs.
if (SymExpr* se = toSymExpr(call->baseExpr)) {
if (TypeSymbol* ts = toTypeSymbol(se->var)) {
if (call->numActuals() == 0 ||
(call->numActuals() == 2 && isSymExpr(call->get(1)) &&
toSymExpr(call->get(1))->var == gMethodToken)) {
// This looks like a typedef, so ignore it.
} else {
// More needed here ... .
INT_FATAL(ts, "not yet implemented.");
}
}
}
callStack.add(call);
resolveCall(call);
if (!tryFailure && call->isResolved()) {
if (CallExpr* origToLeaderCall = toPrimToLeaderCall(origExpr))
// ForallLeaderArgs: process the leader that 'call' invokes.
implementForallIntents2(call, origToLeaderCall);
resolveFns(call->isResolved());
}
if (tryFailure) {
if (tryStack.tail()->parentSymbol == fn) {
// The code in the 'true' branch of a tryToken conditional has failed
// to resolve fully. Roll the callStack back to the function where
// the nearest tryToken conditional is and replace the entire
// conditional with the 'false' branch then continue resolution on
// it. If the 'true' branch did fully resolve, we would replace the
// conditional with the 'true' branch instead.
while (callStack.n > 0 &&
callStack.tail()->isResolved() !=
tryStack.tail()->elseStmt->parentSymbol) {
callStack.pop();
}
BlockStmt* block = tryStack.tail()->elseStmt;
tryStack.tail()->replace(block->remove());
tryStack.pop();
if (!block->prev)
block->insertBefore(new CallExpr(PRIM_NOOP));
return block->prev;
} else {
return NULL;
}
}
callStack.pop();
}
if (SymExpr* sym = toSymExpr(expr)) {
// Avoid record constructors via cast
// should be fixed by out-of-order resolution
CallExpr* parent = toCallExpr(sym->parentExpr);
if (!parent ||
!parent->isPrimitive(PRIM_IS_SUBTYPE) ||
!sym->var->hasFlag(FLAG_TYPE_VARIABLE)) {
if (AggregateType* ct = toAggregateType(sym->typeInfo())) {
if (!ct->symbol->hasFlag(FLAG_GENERIC) &&
!ct->symbol->hasFlag(FLAG_ITERATOR_CLASS) &&
!ct->symbol->hasFlag(FLAG_ITERATOR_RECORD)) {
resolveFormals(ct->defaultTypeConstructor);
if (resolvedFormals.set_in(ct->defaultTypeConstructor)) {
if (ct->defaultTypeConstructor->hasFlag(FLAG_PARTIAL_COPY))
instantiateBody(ct->defaultTypeConstructor);
resolveFns(ct->defaultTypeConstructor);
}
}
}
}
}
return postFold(expr);
}
void
resolveBlockStmt(BlockStmt* blockStmt) {
for_exprs_postorder(expr, blockStmt) {
expr = resolveExpr(expr);
if (tryFailure) {
if (expr == NULL)
return;
tryFailure = false;
}
}
}
static void
computeReturnTypeParamVectors(BaseAST* ast,
Symbol* retSymbol,
Vec<Type*>& retTypes,
Vec<Symbol*>& retParams) {
if (CallExpr* call = toCallExpr(ast)) {
if (call->isPrimitive(PRIM_MOVE)) {
if (SymExpr* sym = toSymExpr(call->get(1))) {
if (sym->var == retSymbol) {
if (SymExpr* sym = toSymExpr(call->get(2)))
retParams.add(sym->var);
else
retParams.add(NULL);
retTypes.add(call->get(2)->typeInfo());
}
}
}
}
AST_CHILDREN_CALL(ast, computeReturnTypeParamVectors, retSymbol, retTypes, retParams);
}
static void
replaceSetterArgWithTrue(BaseAST* ast, FnSymbol* fn) {
if (SymExpr* se = toSymExpr(ast)) {
if (se->var == fn->setter->sym) {
se->var = gTrue;
if (fn->isIterator())
USR_WARN(fn, "setter argument is not supported in iterators");
}
}
AST_CHILDREN_CALL(ast, replaceSetterArgWithTrue, fn);
}
static void
replaceSetterArgWithFalse(BaseAST* ast, FnSymbol* fn, Symbol* ret) {
if (SymExpr* se = toSymExpr(ast)) {
if (se->var == fn->setter->sym)
se->var = gFalse;
else if (se->var == ret) {
if (CallExpr* move = toCallExpr(se->parentExpr))
if (move->isPrimitive(PRIM_MOVE))
if (CallExpr* call = toCallExpr(move->get(2)))
if (call->isPrimitive(PRIM_ADDR_OF))
call->primitive = primitives[PRIM_DEREF];
}
}
AST_CHILDREN_CALL(ast, replaceSetterArgWithFalse, fn, ret);
}
static void
insertCasts(BaseAST* ast, FnSymbol* fn, Vec<CallExpr*>& casts) {
if (CallExpr* call = toCallExpr(ast)) {
if (call->parentSymbol == fn) {
if (call->isPrimitive(PRIM_MOVE)) {
if (SymExpr* lhs = toSymExpr(call->get(1))) {
Type* lhsType = lhs->var->type;
if (lhsType != dtUnknown) {
Expr* rhs = call->get(2);
Type* rhsType = rhs->typeInfo();
if (rhsType != lhsType &&
rhsType->refType != lhsType &&
rhsType != lhsType->refType) {
SET_LINENO(rhs);
rhs->remove();
Symbol* tmp = NULL;
if (SymExpr* se = toSymExpr(rhs)) {
tmp = se->var;
} else {
tmp = newTemp("_cast_tmp_", rhs->typeInfo());
call->insertBefore(new DefExpr(tmp));
call->insertBefore(new CallExpr(PRIM_MOVE, tmp, rhs));
}
CallExpr* cast = new CallExpr("_cast", lhsType->symbol, tmp);
call->insertAtTail(cast);
casts.add(cast);
}
}
}
}
}
}
AST_CHILDREN_CALL(ast, insertCasts, fn, casts);
}
static void instantiate_default_constructor(FnSymbol* fn) {
//
// instantiate initializer
//
if (fn->instantiatedFrom) {
INT_ASSERT(!fn->retType->defaultInitializer);
FnSymbol* instantiatedFrom = fn->instantiatedFrom;
while (instantiatedFrom->instantiatedFrom)
instantiatedFrom = instantiatedFrom->instantiatedFrom;
CallExpr* call = new CallExpr(instantiatedFrom->retType->defaultInitializer);
for_formals(formal, fn) {
if (formal->type == dtMethodToken || formal == fn->_this) {
call->insertAtTail(formal);
} else if (paramMap.get(formal)) {
call->insertAtTail(new NamedExpr(formal->name, new SymExpr(paramMap.get(formal))));
} else {
Symbol* field = fn->retType->getField(formal->name);
if (instantiatedFrom->hasFlag(FLAG_TUPLE)) {
call->insertAtTail(field);
} else {
call->insertAtTail(new NamedExpr(formal->name, new SymExpr(field)));
}
}
}
fn->insertBeforeReturn(call);
resolveCall(call);
fn->retType->defaultInitializer = call->isResolved();
INT_ASSERT(fn->retType->defaultInitializer);
// resolveFns(fn->retType->defaultInitializer);
call->remove();
}
}
static void buildValueFunction(FnSymbol* fn) {
if (!fn->isIterator()) {
FnSymbol* copy;
bool valueFunctionExists = fn->valueFunction;
if (!valueFunctionExists) {
// Build the value function when it does not already exist.
copy = fn->copy();
copy->removeFlag(FLAG_RESOLVED);
copy->addFlag(FLAG_INVISIBLE_FN);
if (fn->hasFlag(FLAG_NO_IMPLICIT_COPY))
copy->addFlag(FLAG_NO_IMPLICIT_COPY);
copy->retTag = RET_VALUE; // Change ret flag to value (not ref).
fn->defPoint->insertBefore(new DefExpr(copy));
fn->valueFunction = copy;
Symbol* ret = copy->getReturnSymbol();
replaceSetterArgWithFalse(copy, copy, ret);
replaceSetterArgWithTrue(fn, fn);
} else {
copy = fn->valueFunction;
}
resolveFns(copy);
} else {
replaceSetterArgWithTrue(fn, fn);
}
}
static void resolveReturnType(FnSymbol* fn)
{
// Resolve return type.
Symbol* ret = fn->getReturnSymbol();
Type* retType = ret->type;
if (retType == dtUnknown) {
Vec<Type*> retTypes;
Vec<Symbol*> retParams;
computeReturnTypeParamVectors(fn, ret, retTypes, retParams);
if (retTypes.n == 1)
retType = retTypes.head();
else if (retTypes.n > 1) {
for (int i = 0; i < retTypes.n; i++) {
bool best = true;
for (int j = 0; j < retTypes.n; j++) {
if (retTypes.v[i] != retTypes.v[j]) {
bool requireScalarPromotion = false;
if (!canDispatch(retTypes.v[j], retParams.v[j], retTypes.v[i], fn, &requireScalarPromotion))
best = false;
if (requireScalarPromotion)
best = false;
}
}
if (best) {
retType = retTypes.v[i];
break;
}
}
}
if (!fn->iteratorInfo) {
if (retTypes.n == 0)
retType = dtVoid;
}
}
ret->type = retType;
if (!fn->iteratorInfo) {
if (retType == dtUnknown)
USR_FATAL(fn, "unable to resolve return type");
fn->retType = retType;
}
}
// Simple wrappers to check if a function is a specific type of iterator
static bool isIteratorOfType(FnSymbol* fn, Symbol* iterTag) {
if (fn->isIterator()) {
for_formals(formal, fn) {
if (formal->type == iterTag->type && paramMap.get(formal) == iterTag) {
return true;
}
}
}
return false;
}
static bool isLeaderIterator(FnSymbol* fn) {
return isIteratorOfType(fn, gLeaderTag);
}
static bool isFollowerIterator(FnSymbol* fn) {
return isIteratorOfType(fn, gFollowerTag);
}
static bool isStandaloneIterator(FnSymbol* fn) {
return isIteratorOfType(fn, gStandaloneTag);
}
void
resolveFns(FnSymbol* fn) {
if (fn->isResolved())
return;
fn->addFlag(FLAG_RESOLVED);
if (fn->hasFlag(FLAG_EXTERN)) {
resolveBlockStmt(fn->body);
resolveReturnType(fn);
return;
}
if (fn->hasFlag(FLAG_FUNCTION_PROTOTYPE))
return;
//
// Mark serial loops that yield inside of follower and standalone iterators
// as order independent. By using a forall loop, a user is asserting that
// their loop is order independent. Here we just mark the serial loops inside
// of the "follower" with this information. Note that only loops that yield
// are marked since other loops are not necessarily order independent. Only
// the inner most loop of a loop nest will be marked.
//
if (isFollowerIterator(fn) || isStandaloneIterator(fn)) {
std::vector<CallExpr*> callExprs;
collectCallExprs(fn->body, callExprs);
for_vector(CallExpr, call, callExprs) {
if (call->isPrimitive(PRIM_YIELD)) {
if (LoopStmt* loop = LoopStmt::findEnclosingLoop(call)) {
if (loop->isCoforallLoop() == false) {
loop->orderIndependentSet(true);
}
}
}
}
}
//
// Mark leader and standalone parallel iterators for inlining. Also stash a
// pristine copy of the iterator (required by forall intents)
//
if (isLeaderIterator(fn) || isStandaloneIterator(fn)) {
fn->addFlag(FLAG_INLINE_ITERATOR);
stashPristineCopyOfLeaderIter(fn, /*ignore_isResolved:*/ true);
}
if (fn->retTag == RET_REF) {
buildValueFunction(fn);
}
insertFormalTemps(fn);
resolveBlockStmt(fn->body);
if (tryFailure) {
fn->removeFlag(FLAG_RESOLVED);
return;
}
if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
AggregateType* ct = toAggregateType(fn->retType);
if (!ct)
INT_FATAL(fn, "Constructor has no class type");
setScalarPromotionType(ct);
fixTypeNames(ct);
}
resolveReturnType(fn);
//
// insert casts as necessary
//
if (fn->retTag != RET_PARAM) {
Vec<CallExpr*> casts;
insertCasts(fn->body, fn, casts);
forv_Vec(CallExpr, cast, casts) {
resolveCall(cast);
if (cast->isResolved()) {
resolveFns(cast->isResolved());
}
}
}
if (fn->isIterator() && !fn->iteratorInfo) {
protoIteratorClass(fn);
}
// Resolve base class type constructors as well.
if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) {
forv_Vec(Type, parent, fn->retType->dispatchParents) {
if (toAggregateType(parent) && parent != dtValue && parent != dtObject && parent->defaultTypeConstructor) {
resolveFormals(parent->defaultTypeConstructor);
if (resolvedFormals.set_in(parent->defaultTypeConstructor)) {
resolveFns(parent->defaultTypeConstructor);
}
}
}
if (AggregateType* ct = toAggregateType(fn->retType)) {
for_fields(field, ct) {
if (AggregateType* fct = toAggregateType(field->type)) {
if (fct->defaultTypeConstructor) {
resolveFormals(fct->defaultTypeConstructor);
if (resolvedFormals.set_in(fct->defaultTypeConstructor)) {
resolveFns(fct->defaultTypeConstructor);
}
}
}
}
}
// This instantiates the default constructor for the corresponding type constructor.
instantiate_default_constructor(fn);
//
// resolve destructor
//
if (AggregateType* ct = toAggregateType(fn->retType)) {
if (!ct->destructor &&
!ct->symbol->hasFlag(FLAG_REF)) {
VarSymbol* tmp = newTemp(ct);
CallExpr* call = new CallExpr("~chpl_destroy", gMethodToken, tmp);
// In case resolveCall drops other stuff into the tree ahead of the
// call, we wrap everything in a block for safe removal.
BlockStmt* block = new BlockStmt();
block->insertAtHead(call);
fn->insertAtHead(block);
fn->insertAtHead(new DefExpr(tmp));
resolveCall(call);
resolveFns(call->isResolved());
ct->destructor = call->isResolved();
block->remove();
tmp->defPoint->remove();
}
}
}
//
// mark privatized classes
//
if (fn->hasFlag(FLAG_PRIVATIZED_CLASS)) {
if (fn->getReturnSymbol() == gTrue) {
fn->getFormal(1)->type->symbol->addFlag(FLAG_PRIVATIZED_CLASS);
}
}
}
static bool
possible_signature_match(FnSymbol* fn, FnSymbol* gn) {
if (fn->name != gn->name)
return false;
if (fn->numFormals() != gn->numFormals())
return false;
for (int i = 3; i <= fn->numFormals(); i++) {
ArgSymbol* fa = fn->getFormal(i);
ArgSymbol* ga = gn->getFormal(i);
if (strcmp(fa->name, ga->name))
return false;
}
return true;
}
static bool
signature_match(FnSymbol* fn, FnSymbol* gn) {
if (fn->name != gn->name)
return false;
if (fn->numFormals() != gn->numFormals())
return false;
for (int i = 3; i <= fn->numFormals(); i++) {
ArgSymbol* fa = fn->getFormal(i);
ArgSymbol* ga = gn->getFormal(i);
if (strcmp(fa->name, ga->name))
return false;
if (fa->type != ga->type)
return false;
}
return true;
}
//
// add to vector icts all types instantiated from ct
//
static void
collectInstantiatedAggregateTypes(Vec<Type*>& icts, Type* ct) {
forv_Vec(TypeSymbol, ts, gTypeSymbols) {
if (ts->type->defaultTypeConstructor)
if (!ts->hasFlag(FLAG_GENERIC) &&
ts->type->defaultTypeConstructor->instantiatedFrom ==
ct->defaultTypeConstructor)
icts.add(ts->type);
}
}
//
// return true if child overrides parent in dispatch table
//
static bool
isVirtualChild(FnSymbol* child, FnSymbol* parent) {
if (Vec<FnSymbol*>* children = virtualChildrenMap.get(parent)) {
forv_Vec(FnSymbol*, candidateChild, *children) {
if (candidateChild == child)
return true;
}
}
return false;
}
static void
addToVirtualMaps(FnSymbol* pfn, AggregateType* ct) {
forv_Vec(FnSymbol, cfn, ct->methods) {
if (cfn && !cfn->instantiatedFrom && possible_signature_match(pfn, cfn)) {
Vec<Type*> types;
if (ct->symbol->hasFlag(FLAG_GENERIC))
collectInstantiatedAggregateTypes(types, ct);
else
types.add(ct);
forv_Vec(Type, type, types) {
SymbolMap subs;
if (ct->symbol->hasFlag(FLAG_GENERIC))
subs.put(cfn->getFormal(2), type->symbol);
for (int i = 3; i <= cfn->numFormals(); i++) {
ArgSymbol* arg = cfn->getFormal(i);
if (arg->intent == INTENT_PARAM) {
subs.put(arg, paramMap.get(pfn->getFormal(i)));
} else if (arg->type->symbol->hasFlag(FLAG_GENERIC)) {
subs.put(arg, pfn->getFormal(i)->type->symbol);
}
}
FnSymbol* fn = cfn;
if (subs.n) {
fn = instantiate(fn, subs, NULL);
if (fn) {
if (type->defaultTypeConstructor->instantiationPoint)
fn->instantiationPoint = type->defaultTypeConstructor->instantiationPoint;
else
fn->instantiationPoint = toBlockStmt(type->defaultTypeConstructor->defPoint->parentExpr);
INT_ASSERT(fn->instantiationPoint);
}
}
if (fn) {
resolveFormals(fn);
if (signature_match(pfn, fn)) {
resolveFns(fn);
if (fn->retType->symbol->hasFlag(FLAG_ITERATOR_RECORD) &&
pfn->retType->symbol->hasFlag(FLAG_ITERATOR_RECORD)) {
if (!isSubType(fn->retType->defaultInitializer->iteratorInfo->getValue->retType,
pfn->retType->defaultInitializer->iteratorInfo->getValue->retType)) {
USR_FATAL_CONT(pfn, "conflicting return type specified for '%s: %s'", toString(pfn),
pfn->retType->defaultInitializer->iteratorInfo->getValue->retType->symbol->name);
USR_FATAL_CONT(fn, " overridden by '%s: %s'", toString(fn),
fn->retType->defaultInitializer->iteratorInfo->getValue->retType->symbol->name);
USR_STOP();
} else {
pfn->retType->dispatchChildren.add_exclusive(fn->retType);
fn->retType->dispatchParents.add_exclusive(pfn->retType);
Type* pic = pfn->retType->defaultInitializer->iteratorInfo->iclass;
Type* ic = fn->retType->defaultInitializer->iteratorInfo->iclass;
INT_ASSERT(ic->symbol->hasFlag(FLAG_ITERATOR_CLASS));
// Iterator classes are created as normal top-level classes (inheriting
// from dtObject). Here, we want to re-parent ic with pic, so
// we need to remove and replace the object base class.
INT_ASSERT(ic->dispatchParents.n == 1);
Type* parent = ic->dispatchParents.only();
if (parent == dtObject)
{
int item = parent->dispatchChildren.index(ic);
parent->dispatchChildren.remove(item);
ic->dispatchParents.remove(0);
}
pic->dispatchChildren.add_exclusive(ic);
ic->dispatchParents.add_exclusive(pic);
continue; // do not add to virtualChildrenMap; handle in _getIterator
}
} else if (!isSubType(fn->retType, pfn->retType)) {
USR_FATAL_CONT(pfn, "conflicting return type specified for '%s: %s'", toString(pfn), pfn->retType->symbol->name);
USR_FATAL_CONT(fn, " overridden by '%s: %s'", toString(fn), fn->retType->symbol->name);
USR_STOP();
}
{
Vec<FnSymbol*>* fns = virtualChildrenMap.get(pfn);
if (!fns) fns = new Vec<FnSymbol*>();
fns->add(fn);
virtualChildrenMap.put(pfn, fns);
fn->addFlag(FLAG_VIRTUAL);
pfn->addFlag(FLAG_VIRTUAL);
}
{
Vec<FnSymbol*>* fns = virtualRootsMap.get(fn);
if (!fns) fns = new Vec<FnSymbol*>();
bool added = false;
//
// check if parent or child already exists in vector
//
for (int i = 0; i < fns->n; i++) {
//
// if parent already exists, do not add child to vector
//
if (isVirtualChild(pfn, fns->v[i])) {
added = true;
break;
}
//
// if child already exists, replace with parent
//
if (isVirtualChild(fns->v[i], pfn)) {
fns->v[i] = pfn;
added = true;
break;
}
}
if (!added)
fns->add(pfn);
virtualRootsMap.put(fn, fns);
}
}
}
}
}
}
}
static void
addAllToVirtualMaps(FnSymbol* fn, AggregateType* ct) {
forv_Vec(Type, t, ct->dispatchChildren) {
AggregateType* ct = toAggregateType(t);
if (ct->defaultTypeConstructor &&
(ct->defaultTypeConstructor->hasFlag(FLAG_GENERIC) ||
ct->defaultTypeConstructor->isResolved()))
addToVirtualMaps(fn, ct);
if (!ct->instantiatedFrom)
addAllToVirtualMaps(fn, ct);
}
}
static void
buildVirtualMaps() {
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->hasFlag(FLAG_WRAPPER))
// Only "true" functions are used to populate virtual maps.
continue;
if (! fn->isResolved())
// Only functions that are actually used go into the virtual map.
continue;
if (fn->hasFlag(FLAG_NO_PARENS))
// Parenthesesless functions are statically bound; that is, they are not
// dispatched through the virtual table.
continue;
if (fn->retTag == RET_PARAM || fn->retTag == RET_TYPE)
// Only run-time functions populate the virtual map.
continue;
if (fn->numFormals() > 1 && fn->getFormal(1)->type == dtMethodToken) {
// Only methods go in the virtual function table.
if (AggregateType* pt = toAggregateType(fn->getFormal(2)->type)) {
if (isClass(pt) && !pt->symbol->hasFlag(FLAG_GENERIC)) {
addAllToVirtualMaps(fn, pt);
}
}
}
}
}
static void
addVirtualMethodTableEntry(Type* type, FnSymbol* fn, bool exclusive /*= false*/) {
Vec<FnSymbol*>* fns = virtualMethodTable.get(type);
if (!fns) fns = new Vec<FnSymbol*>();
if (exclusive) {
forv_Vec(FnSymbol, f, *fns) {
if (f == fn)
return;
}
}
fns->add(fn);
virtualMethodTable.put(type, fns);
}
void
parseExplainFlag(char* flag, int* line, ModuleSymbol** module) {
*line = 0;
if (strcmp(flag, "")) {
char *token, *str1 = NULL, *str2 = NULL;
token = strstr(flag, ":");
if (token) {
*token = '\0';
str1 = token+1;
token = strstr(str1, ":");
if (token) {
*token = '\0';
str2 = token + 1;
}
}
if (str1) {
if (str2 || !atoi(str1)) {
forv_Vec(ModuleSymbol, mod, allModules) {
if (!strcmp(mod->name, str1)) {
*module = mod;
break;
}
}
if (!*module)
USR_FATAL("invalid module name '%s' passed to --explain-call flag", str1);
} else
*line = atoi(str1);
if (str2)
*line = atoi(str2);
}
if (*line == 0)
*line = -1;
}
}
static void resolveExternVarSymbols()
{
forv_Vec(VarSymbol, vs, gVarSymbols)
{
if (! vs->hasFlag(FLAG_EXTERN))
continue;
DefExpr* def = vs->defPoint;
Expr* init = def->next;
// We expect the expression following the DefExpr for an extern to be a
// type block that initializes the variable.
BlockStmt* block = toBlockStmt(init);
if (block)
resolveBlockStmt(block);
}
}
static void resolveTypedefedArgTypes(FnSymbol* fn)
{
for_formals(formal, fn)
{
INT_ASSERT(formal->type); // Should be *something*.
if (formal->type != dtUnknown)
continue;
if (BlockStmt* block = formal->typeExpr)
{
if (SymExpr* se = toSymExpr(block->body.first()))
{
if (se->var->hasFlag(FLAG_TYPE_VARIABLE))
{
Type* type = resolveTypeAlias(toSymExpr(se));
INT_ASSERT(type);
formal->type = type;
}
}
}
}
}
static void
computeStandardModuleSet() {
standardModuleSet.set_add(rootModule->block);
standardModuleSet.set_add(theProgram->block);
Vec<ModuleSymbol*> stack;
stack.add(standardModule);
while (ModuleSymbol* mod = stack.pop()) {
if (mod->block->modUses) {
for_actuals(expr, mod->block->modUses) {
SymExpr* se = toSymExpr(expr);
INT_ASSERT(se);
ModuleSymbol* use = toModuleSymbol(se->var);
INT_ASSERT(use);
if (!standardModuleSet.set_in(use->block)) {
stack.add(use);
standardModuleSet.set_add(use->block);
}
}
}
}
}
void
resolve() {
parseExplainFlag(fExplainCall, &explainCallLine, &explainCallModule);
computeStandardModuleSet();
// call _nilType nil so as to not confuse the user
dtNil->symbol->name = gNil->name;
bool changed = true;
while (changed) {
changed = false;
forv_Vec(FnSymbol, fn, gFnSymbols) {
changed = fn->tag_generic() || changed;
}
}
unmarkDefaultedGenerics();
resolveExternVarSymbols();
// --ipe does not build a mainModule
if (mainModule)
resolveUses(mainModule);
// --ipe does not build printModuleInitModule
if (printModuleInitModule)
resolveUses(printModuleInitModule);
// --ipe does not build chpl_gen_main
if (chpl_gen_main)
resolveFns(chpl_gen_main);
USR_STOP();
resolveExports();
resolveEnumTypes();
resolveDynamicDispatches();
insertRuntimeTypeTemps();
resolveAutoCopies();
resolveRecordInitializers();
resolveOther();
insertDynamicDispatchCalls();
insertReturnTemps();
handleRuntimeTypes();
pruneResolvedTree();
freeCache(ordersCache);
freeCache(defaultsCache);
freeCache(genericsCache);
freeCache(coercionsCache);
freeCache(promotionsCache);
freeCache(capturedValues);
Vec<VisibleFunctionBlock*> vfbs;
visibleFunctionMap.get_values(vfbs);
forv_Vec(VisibleFunctionBlock, vfb, vfbs) {
Vec<Vec<FnSymbol*>*> vfns;
vfb->visibleFunctions.get_values(vfns);
forv_Vec(Vec<FnSymbol*>, vfn, vfns) {
delete vfn;
}
delete vfb;
}
visibleFunctionMap.clear();
visibilityBlockCache.clear();
forv_Vec(BlockStmt, stmt, gBlockStmts) {
stmt->moduleUseClear();
}
resolved = true;
}
static void unmarkDefaultedGenerics() {
//
// make it so that arguments with types that have default values for
// all generic arguments used those defaults
//
// FLAG_MARKED_GENERIC is used to identify places where the user inserted
// '?' (queries) to mark such a type as generic.
//
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (!fn->inTree())
continue;
bool unmark = fn->hasFlag(FLAG_GENERIC);
for_formals(formal, fn) {
if (formal->type->hasGenericDefaults) {
if (!formal->hasFlag(FLAG_MARKED_GENERIC) &&
formal != fn->_this &&
!formal->hasFlag(FLAG_IS_MEME)) {
SET_LINENO(formal);
formal->typeExpr = new BlockStmt(new CallExpr(formal->type->defaultTypeConstructor));
insert_help(formal->typeExpr, NULL, formal);
formal->type = dtUnknown;
} else {
unmark = false;
}
} else if (formal->type->symbol->hasFlag(FLAG_GENERIC) || formal->intent == INTENT_PARAM) {
unmark = false;
}
}
if (unmark) {
fn->removeFlag(FLAG_GENERIC);
INT_ASSERT(false);
}
}
}
// Resolve uses in postorder (removing back-links).
// We have to resolve modules in dependency order,
// so that the types of globals are ready when we need them.
static void resolveUses(ModuleSymbol* mod)
{
static Vec<ModuleSymbol*> initMods;
static int module_resolution_depth = 0;
// Test and set to break loops and prevent infinite recursion.
if (initMods.set_in(mod))
return;
initMods.set_add(mod);
++module_resolution_depth;
// I use my parent implicitly.
if (ModuleSymbol* parent = mod->defPoint->getModule())
if (parent != theProgram && parent != rootModule)
resolveUses(parent);
// Now, traverse my use statements, and call the initializer for each
// module I use.
forv_Vec(ModuleSymbol, usedMod, mod->modUseList)
resolveUses(usedMod);
// Finally, myself.
if (fPrintModuleResolution)
fprintf(stderr, "%2d Resolving module %s ...", module_resolution_depth, mod->name);
FnSymbol* fn = mod->initFn;
resolveFormals(fn);
resolveFns(fn);
if (fPrintModuleResolution)
putc('\n', stderr);
--module_resolution_depth;
}
static void resolveExports() {
// We need to resolve any additional functions that will be exported.
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->hasFlag(FLAG_EXPORT)) {
SET_LINENO(fn);
resolveFormals(fn);
resolveFns(fn);
}
}
}
static void resolveEnumTypes() {
// need to handle enumerated types better
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (EnumType* et = toEnumType(type->type)) {
ensureEnumTypeResolved(et);
}
}
}
static void resolveDynamicDispatches() {
inDynamicDispatchResolution = true;
int num_types;
do {
num_types = gTypeSymbols.n;
{
Vec<Vec<FnSymbol*>*> values;
virtualChildrenMap.get_values(values);
forv_Vec(Vec<FnSymbol*>, value, values) {
delete value;
}
}
virtualChildrenMap.clear();
{
Vec<Vec<FnSymbol*>*> values;
virtualRootsMap.get_values(values);
forv_Vec(Vec<FnSymbol*>, value, values) {
delete value;
}
}
virtualRootsMap.clear();
buildVirtualMaps();
} while (num_types != gTypeSymbols.n);
for (int i = 0; i < virtualRootsMap.n; i++) {
if (virtualRootsMap.v[i].key) {
for (int j = 0; j < virtualRootsMap.v[i].value->n; j++) {
FnSymbol* root = virtualRootsMap.v[i].value->v[j];
addVirtualMethodTableEntry(root->_this->type, root, true);
}
}
}
Vec<Type*> ctq;
ctq.add(dtObject);
forv_Vec(Type, ct, ctq) {
if (Vec<FnSymbol*>* parentFns = virtualMethodTable.get(ct)) {
forv_Vec(FnSymbol, pfn, *parentFns) {
Vec<Type*> childSet;
if (Vec<FnSymbol*>* childFns = virtualChildrenMap.get(pfn)) {
forv_Vec(FnSymbol, cfn, *childFns) {
forv_Vec(Type, pt, cfn->_this->type->dispatchParents) {
if (pt == ct) {
if (!childSet.set_in(cfn->_this->type)) {
addVirtualMethodTableEntry(cfn->_this->type, cfn);
childSet.set_add(cfn->_this->type);
}
break;
}
}
}
}
forv_Vec(Type, childType, ct->dispatchChildren) {
if (!childSet.set_in(childType)) {
addVirtualMethodTableEntry(childType, pfn);
}
}
}
}
forv_Vec(Type, child, ct->dispatchChildren) {
ctq.add(child);
}
}
for (int i = 0; i < virtualMethodTable.n; i++) {
if (virtualMethodTable.v[i].key) {
virtualMethodTable.v[i].value->reverse();
for (int j = 0; j < virtualMethodTable.v[i].value->n; j++) {
virtualMethodMap.put(virtualMethodTable.v[i].value->v[j], j);
}
}
}
inDynamicDispatchResolution = false;
if (fPrintDispatch) {
printf("Dynamic dispatch table:\n");
for (int i = 0; i < virtualMethodTable.n; i++) {
if (Type* t = virtualMethodTable.v[i].key) {
printf(" %s\n", toString(t));
for (int j = 0; j < virtualMethodTable.v[i].value->n; j++) {
printf(" %s\n", toString(virtualMethodTable.v[i].value->v[j]));
}
}
}
}
}
static void insertRuntimeTypeTemps() {
forv_Vec(TypeSymbol, ts, gTypeSymbols) {
if (ts->defPoint &&
ts->defPoint->parentSymbol &&
ts->hasFlag(FLAG_HAS_RUNTIME_TYPE) &&
!ts->hasFlag(FLAG_GENERIC)) {
SET_LINENO(ts);
VarSymbol* tmp = newTemp("_runtime_type_tmp_", ts->type);
ts->type->defaultInitializer->insertBeforeReturn(new DefExpr(tmp));
CallExpr* call = new CallExpr("chpl__convertValueToRuntimeType", tmp);
ts->type->defaultInitializer->insertBeforeReturn(call);
resolveCall(call);
resolveFns(call->isResolved());
valueToRuntimeTypeMap.put(ts->type, call->isResolved());
call->remove();
tmp->defPoint->remove();
}
}
}
static void resolveAutoCopies() {
forv_Vec(TypeSymbol, ts, gTypeSymbols) {
if (!ts->defPoint->parentSymbol)
continue; // Type is not in tree
if (ts->hasFlag(FLAG_GENERIC))
continue; // Consider only concrete types.
if (ts->hasFlag(FLAG_SYNTACTIC_DISTRIBUTION))
continue; // Skip the "dmapped" pseudo-type.
if (isRecord(ts->type) || getSyncFlags(ts).any())
{
resolveAutoCopy(ts->type);
resolveAutoDestroy(ts->type);
}
}
}
static void resolveRecordInitializers() {
//
// resolve PRIM_INITs for records
//
forv_Vec(CallExpr, init, inits)
{
// Ignore if dead.
if (!init->parentSymbol)
continue;
Type* type = init->get(1)->typeInfo();
// Don't resolve initializers for runtime types.
// These have to be resolved after runtime types are replaced by values in
// insertRuntimeInitTemps().
if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
continue;
// Extract the value type.
if (type->symbol->hasFlag(FLAG_REF))
type = type->getValType();
// Resolve the AggregateType that has noinit used on it.
if (init->isPrimitive(PRIM_NO_INIT)) {
// Replaces noinit with a call to the defaultTypeConstructor,
// providing the param and type arguments necessary to allocate
// space for the instantiation of this (potentially) generic type.
// defaultTypeConstructor calls are already cleaned up at the end of
// function resolution, so the noinit cleanup would be redundant.
SET_LINENO(init);
CallExpr* res = new CallExpr(type->defaultTypeConstructor);
for_formals(formal, type->defaultTypeConstructor) {
Vec<Symbol *> keys;
// Finds each named argument in the type constructor and inserts
// the substitution provided.
type->substitutions.get_keys(keys);
// I don't think we can guarantee that the substitutions will be
// in the same order as the arguments for the defaultTypeConstructor.
// That would make this O(n) instead of potentially O(n*n)
forv_Vec(Symbol, key, keys) {
if (!strcmp(formal->name, key->name)) {
Symbol* formalVal = type->substitutions.get(key);
res->insertAtTail(new NamedExpr(formal->name,
new SymExpr(formalVal)));
}
}
}
init->get(1)->replace(res);
resolveCall(res);
makeNoop((CallExpr *)init->parentExpr);
// Now that we've resolved the type constructor and thus resolved the
// generic type of the variable we were assigning to, the outer move
// is no longer needed, so remove it and continue to the next init.
continue;
}
// This could be an assert...
if (type->defaultValue)
INT_FATAL(init, "PRIM_INIT should have been replaced already");
SET_LINENO(init);
if (type->symbol->hasFlag(FLAG_DISTRIBUTION)) {
// This initialization cannot be replaced by a _defaultOf function
// earlier in the compiler, there is not enough information to build a
// default function for it. When we have the ability to call a
// constructor from a type alias, it can be moved directly into module
// code
Symbol* tmp = newTemp("_distribution_tmp_");
init->getStmtExpr()->insertBefore(new DefExpr(tmp));
CallExpr* classCall = new CallExpr(type->getField("_valueType")->type->defaultInitializer);
CallExpr* move = new CallExpr(PRIM_MOVE, tmp, classCall);
init->getStmtExpr()->insertBefore(move);
resolveCall(classCall);
resolveFns(classCall->isResolved());
resolveCall(move);
CallExpr* distCall = new CallExpr("chpl__buildDistValue", tmp);
init->replace(distCall);
resolveCall(distCall);
resolveFns(distCall->isResolved());
} else {
CallExpr* call = new CallExpr("_defaultOf", type->symbol);
init->replace(call);
resolveNormalCall(call);
// At this point in the compiler, we can resolve the _defaultOf function
// for the type, so do so.
if (call->isResolved())
resolveFns(call->isResolved());
}
}
}
//
// Resolve other things we might want later
//
static void resolveOther() {
//
// When compiling with --minimal-modules, gPrintModuleInitFn is not
// defined.
//
if (gPrintModuleInitFn) {
// Resolve the function that will print module init order
resolveFns(gPrintModuleInitFn);
}
}
static void insertDynamicDispatchCalls() {
// Select resolved calls whose function appears in the virtualChildrenMap.
// These are the dynamically-dispatched calls.
forv_Vec(CallExpr, call, gCallExprs) {
if (!call->parentSymbol) continue;
if (!call->getStmtExpr()) continue;
FnSymbol* key = call->isResolved();
if (!key) continue;
Vec<FnSymbol*>* fns = virtualChildrenMap.get(key);
if (!fns) continue;
SET_LINENO(call);
//Check to see if any of the overridden methods reference outer variables. If they do, then when we later change the
//signature in flattenFunctions, the vtable style will break (function signatures will no longer match). To avoid this
//we switch to the if-block style in the case where outer variables are discovered.
//Note: This is conservative, as we haven't finished resolving functions and calls yet, we check all possibilities.
bool referencesOuterVars = false;
Vec<FnSymbol*> seen;
referencesOuterVars = usesOuterVars(key, seen);
if (!referencesOuterVars) {
for (int i = 0; i < fns->n; ++i) {
seen.clear();
if ( (referencesOuterVars = usesOuterVars(key, seen)) ) {
break;
}
}
}
if ((fns->n + 1 > fConditionalDynamicDispatchLimit) && (!referencesOuterVars)) {
//
// change call of root method into virtual method call;
// Insert function SymExpr and virtual method temp at head of argument
// list.
//
// N.B.: The following variable must have the same size as the type of
// chpl__class_id / chpl_cid_* -- otherwise communication will cause
// problems when it tries to read the cid of a remote class. See
// test/classes/sungeun/remoteDynamicDispatch.chpl (on certain
// machines and configurations).
VarSymbol* cid = newTemp("_virtual_method_tmp_", dtInt[INT_SIZE_32]);
call->getStmtExpr()->insertBefore(new DefExpr(cid));
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, cid, new CallExpr(PRIM_GETCID, call->get(2)->copy())));
call->get(1)->insertBefore(new SymExpr(cid));
// "remove" here means VMT calls are not really "resolved".
// That is, calls to isResolved() return NULL.
call->get(1)->insertBefore(call->baseExpr->remove());
call->primitive = primitives[PRIM_VIRTUAL_METHOD_CALL];
// This clause leads to necessary reference temporaries not being inserted,
// while the clause below works correctly. <hilde>
// Increase --conditional-dynamic-dispatch-limit to see this.
} else {
forv_Vec(FnSymbol, fn, *fns) {
Type* type = fn->getFormal(2)->type;
CallExpr* subcall = call->copy();
SymExpr* tmp = new SymExpr(gNil);
// Build the IF block.
BlockStmt* ifBlock = new BlockStmt();
VarSymbol* cid = newTemp("_dynamic_dispatch_tmp_", dtBool);
ifBlock->insertAtTail(new DefExpr(cid));
ifBlock->insertAtTail(new CallExpr(PRIM_MOVE, cid,
new CallExpr(PRIM_TESTCID,
call->get(2)->copy(),
type->symbol)));
VarSymbol* _ret = NULL;
if (key->retType != dtVoid) {
_ret = newTemp("_return_tmp_", key->retType);
ifBlock->insertAtTail(new DefExpr(_ret));
}
// Build the TRUE block.
BlockStmt* trueBlock = new BlockStmt();
if (fn->retType == key->retType) {
if (_ret)
trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, _ret, subcall));
else
trueBlock->insertAtTail(subcall);
} else if (isSubType(fn->retType, key->retType)) {
// Insert a cast to the overridden method's return type
VarSymbol* castTemp = newTemp("_cast_tmp_", fn->retType);
trueBlock->insertAtTail(new DefExpr(castTemp));
trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, castTemp,
subcall));
INT_ASSERT(_ret);
trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, _ret,
new CallExpr(PRIM_CAST,
key->retType->symbol,
castTemp)));
} else
INT_FATAL(key, "unexpected case");
// Build the FALSE block.
BlockStmt* falseBlock = NULL;
if (_ret)
falseBlock = new BlockStmt(new CallExpr(PRIM_MOVE, _ret, tmp));
else
falseBlock = new BlockStmt(tmp);
ifBlock->insertAtTail(new CondStmt(
new SymExpr(cid),
trueBlock,
falseBlock));
if (key->retType == dtUnknown)
INT_FATAL(call, "bad parent virtual function return type");
call->getStmtExpr()->insertBefore(ifBlock);
if (_ret)
call->replace(new SymExpr(_ret));
else
call->remove();
tmp->replace(call);
subcall->baseExpr->replace(new SymExpr(fn));
if (SymExpr* se = toSymExpr(subcall->get(2))) {
VarSymbol* tmp = newTemp("_cast_tmp_", type);
se->getStmtExpr()->insertBefore(new DefExpr(tmp));
se->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_CAST, type->symbol, se->var)));
se->replace(new SymExpr(tmp));
} else if (CallExpr* ce = toCallExpr(subcall->get(2)))
if (ce->isPrimitive(PRIM_CAST))
ce->get(1)->replace(new SymExpr(type->symbol));
else
INT_FATAL(subcall, "unexpected");
else
INT_FATAL(subcall, "unexpected");
}
}
}
}
static Type*
buildRuntimeTypeInfo(FnSymbol* fn) {
SET_LINENO(fn);
AggregateType* ct = new AggregateType(AGGREGATE_RECORD);
TypeSymbol* ts = new TypeSymbol(astr("_RuntimeTypeInfo"), ct);
for_formals(formal, fn) {
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM))
continue;
VarSymbol* field = new VarSymbol(formal->name, formal->type);
ct->fields.insertAtTail(new DefExpr(field));
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
field->addFlag(FLAG_TYPE_VARIABLE);
}
theProgram->block->insertAtTail(new DefExpr(ts));
ct->symbol->addFlag(FLAG_RUNTIME_TYPE_VALUE);
makeRefType(ts->type); // make sure the new type has a ref type.
return ct;
}
static void insertReturnTemps() {
//
// Insert return temps for functions that return values if no
// variable captures the result. If the value is a sync/single var or a
// reference to a sync/single var, pass it through the _statementLevelSymbol
// function to get the semantics of reading a sync/single var. If the value
// is an iterator pass it through another overload of
// _statementLevelSymbol to iterate through it for side effects.
// Note that we do not do this for --minimal-modules compilation
// because we do not support sync/singles for minimal modules.
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->parentSymbol) {
if (FnSymbol* fn = call->isResolved()) {
if (fn->retType != dtVoid) {
CallExpr* parent = toCallExpr(call->parentExpr);
if (!parent && !isDefExpr(call->parentExpr)) { // no use
SET_LINENO(call); // TODO: reset_ast_loc() below?
VarSymbol* tmp = newTemp("_return_tmp_", fn->retType);
DefExpr* def = new DefExpr(tmp);
call->insertBefore(def);
if (!fMinimalModules &&
((fn->retType->getValType() &&
isSyncType(fn->retType->getValType())) ||
isSyncType(fn->retType) ||
fn->isIterator())) {
CallExpr* sls = new CallExpr("_statementLevelSymbol", tmp);
call->insertBefore(sls);
reset_ast_loc(sls, call);
resolveCall(sls);
INT_ASSERT(sls->isResolved());
resolveFns(sls->isResolved());
}
def->insertAfter(new CallExpr(PRIM_MOVE, tmp, call->remove()));
}
}
}
}
}
}
//
// insert code to initialize a class or record
//
static void
initializeClass(Expr* stmt, Symbol* sym) {
AggregateType* ct = toAggregateType(sym->type);
INT_ASSERT(ct);
for_fields(field, ct) {
if (!field->hasFlag(FLAG_SUPER_CLASS)) {
SET_LINENO(field);
if (field->type->defaultValue) {
stmt->insertBefore(new CallExpr(PRIM_SET_MEMBER, sym, field, field->type->defaultValue));
} else if (isRecord(field->type)) {
VarSymbol* tmp = newTemp("_init_class_tmp_", field->type);
stmt->insertBefore(new DefExpr(tmp));
initializeClass(stmt, tmp);
stmt->insertBefore(new CallExpr(PRIM_SET_MEMBER, sym, field, tmp));
}
}
}
}
static void handleRuntimeTypes()
{
// insertRuntimeTypeTemps is also called earlier in resolve(). That call
// can insert variables that need autoCopies and inserting autoCopies can
// insert things that need runtime type temps. These need to be fixed up
// by insertRuntimeTypeTemps before buildRuntimeTypeInitFns is called to
// update the type -> runtimeType mapping. Without this, there is an
// actual/formal type mismatch (with --verify) for the code:
// record R { var A: [1..1][1..1] real; }
insertRuntimeTypeTemps();
buildRuntimeTypeInitFns();
replaceValuesWithRuntimeTypes();
replaceReturnedValuesWithRuntimeTypes();
insertRuntimeInitTemps();
}
//
// pruneResolvedTree -- prunes and cleans the AST after all of the
// function calls and types have been resolved
//
static void
pruneResolvedTree() {
removeUnusedFunctions();
if (fRemoveUnreachableBlocks)
deadBlockElimination();
removeRandomPrimitives();
replaceTypeArgsWithFormalTypeTemps();
removeParamArgs();
removeUnusedGlobals();
removeUnusedTypes();
removeActualNames();
removeFormalTypeAndInitBlocks();
removeTypeBlocks();
removeInitFields();
removeWhereClauses();
removeMootFields();
expandInitFieldPrims();
removeCompilerWarnings();
}
static void clearDefaultInitFns(FnSymbol* unusedFn) {
// Before removing an unused function, check if it is a defaultInitializer.
// If unusedFn is a defaultInitializer, its retType's defaultInitializer
// field will be unusedFn. Set the defaultInitializer field to NULL so the
// removed function doesn't leave behind a garbage pointer.
if (unusedFn->retType->defaultInitializer == unusedFn) {
unusedFn->retType->defaultInitializer = NULL;
}
}
static void removeUnusedFunctions() {
// Remove unused functions
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->hasFlag(FLAG_PRINT_MODULE_INIT_FN)) continue;
if (fn->defPoint && fn->defPoint->parentSymbol) {
if (! fn->isResolved() || fn->retTag == RET_PARAM) {
clearDefaultInitFns(fn);
fn->defPoint->remove();
}
}
}
}
static void removeCompilerWarnings() {
// Warnings have now been issued, no need to keep the function around.
// Remove calls to compilerWarning and let dead code elimination handle
// the rest.
typedef MapElem<FnSymbol*, const char*> FnSymbolElem;
form_Map(FnSymbolElem, el, innerCompilerWarningMap) {
forv_Vec(CallExpr, call, *(el->key->calledBy)) {
call->remove();
}
}
}
static bool
isUnusedClass(AggregateType *ct) {
// Special case for global types.
if (ct->symbol->hasFlag(FLAG_GLOBAL_TYPE_SYMBOL))
return false;
// Runtime types are assumed to be always used.
if (ct->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE))
return false;
// Uses of iterator records get inserted in lowerIterators
if (ct->symbol->hasFlag(FLAG_ITERATOR_RECORD))
return false;
// FALSE if initializers are used
if (ct->defaultInitializer && ct->defaultInitializer->isResolved())
return false;
// FALSE if the type constructor is used.
if (ct->defaultTypeConstructor && ct->defaultTypeConstructor->isResolved())
return false;
bool allChildrenUnused = true;
forv_Vec(Type, child, ct->dispatchChildren) {
AggregateType* childClass = toAggregateType(child);
INT_ASSERT(childClass);
if (!isUnusedClass(childClass)) {
allChildrenUnused = false;
break;
}
}
return allChildrenUnused;
}
// Remove unused types
static void removeUnusedTypes() {
// Remove unused aggregate types.
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (type->defPoint && type->defPoint->parentSymbol)
{
// Skip ref and runtime value types:
// ref types are handled below;
// runtime value types are assumed to be always used.
if (type->hasFlag(FLAG_REF))
continue;
if (type->hasFlag(FLAG_RUNTIME_TYPE_VALUE))
continue;
if (AggregateType* ct = toAggregateType(type->type))
if (isUnusedClass(ct))
ct->symbol->defPoint->remove();
}
}
// Remove unused ref types.
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (type->defPoint && type->defPoint->parentSymbol) {
if (type->hasFlag(FLAG_REF)) {
// Get the value type of the ref type.
if (AggregateType* ct = toAggregateType(type->getValType())) {
if (isUnusedClass(ct)) {
// If the value type is unused, its ref type can also be removed.
type->defPoint->remove();
}
}
// If the default type constructor for this ref type is in the tree, it
// can be removed.
if (type->type->defaultTypeConstructor->defPoint->parentSymbol)
type->type->defaultTypeConstructor->defPoint->remove();
}
}
}
}
static void removeUnusedGlobals()
{
forv_Vec(DefExpr, def, gDefExprs)
{
// Remove unused global variables
if (toVarSymbol(def->sym))
if (toModuleSymbol(def->parentSymbol))
if (def->sym->type == dtUnknown)
def->remove();
}
}
static void removeRandomPrimitive(CallExpr* call)
{
if (! call->primitive)
// TODO: This is weird.
// Calls which trigger this case appear as the init clause of a type
// variable.
// The parent module or function may be resolved, but apparently the type
// variable is resolved only if it is used.
// Generally speaking, we resolve a declaration only if it is used.
// But right now, we only apply this test to functions.
// The test should be extended to variable declarations as well. That is,
// variables need only be resolved if they are actually used.
return;
// A primitive.
switch (call->primitive->tag)
{
default: /* do nothing */ break;
case PRIM_NOOP:
call->remove();
break;
case PRIM_TYPEOF:
{
// Remove move(x, PRIM_TYPEOF(y)) calls -- useless after this
CallExpr* parentCall = toCallExpr(call->parentExpr);
if (parentCall && parentCall->isPrimitive(PRIM_MOVE) &&
parentCall->get(2) == call) {
parentCall->remove();
} else {
// Replace PRIM_TYPEOF with argument
call->replace(call->get(1)->remove());
}
}
break;
case PRIM_CAST:
// Remove trivial casts.
if (call->get(1)->typeInfo() == call->get(2)->typeInfo())
call->replace(call->get(2)->remove());
break;
case PRIM_SET_MEMBER:
case PRIM_GET_MEMBER:
case PRIM_GET_MEMBER_VALUE:
{
// Remove member accesses of types
// Replace string literals with field symbols in member primitives
Type* baseType = call->get(1)->typeInfo();
if (baseType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE))
break;
if (!call->parentSymbol->hasFlag(FLAG_REF) &&
baseType->symbol->hasFlag(FLAG_REF))
baseType = baseType->getValType();
const char* memberName = get_string(call->get(2));
Symbol* sym = baseType->getField(memberName);
if (sym->hasFlag(FLAG_TYPE_VARIABLE) ||
!strcmp(sym->name, "_promotionType") ||
sym->isParameter())
call->getStmtExpr()->remove();
else {
SET_LINENO(call->get(2));
call->get(2)->replace(new SymExpr(sym));
}
}
break;
// Maybe this can be pushed into the following case, where a PRIM_MOVE gets
// removed if its rhs is a type symbol. That is, resolution of a
// PRIM_TYPE_INIT replaces the primitive with symexpr that contains a type symbol.
case PRIM_TYPE_INIT:
{
// A "type init" call that is in the tree should always have a callExpr
// parent, as guaranteed by CallExpr::verify().
CallExpr* parent = toCallExpr(call->parentExpr);
// We expect all PRIM_TYPE_INIT primitives to have a PRIM_MOVE
// parent, following the insertion of call temps.
if (parent->isPrimitive(PRIM_MOVE))
parent->remove();
else
INT_FATAL(parent, "expected parent of PRIM_TYPE_EXPR to be a PRIM_MOVE");
}
break;
case PRIM_MOVE:
{
// Remove types to enable --baseline
SymExpr* sym = toSymExpr(call->get(2));
if (sym && isTypeSymbol(sym->var))
call->remove();
}
break;
}
}
// Remove the method token, parameter and type arguments from
// function signatures and corresponding calls.
static void removeParamArgs()
{
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols)
{
if (! fn->isResolved())
// Don't bother with unresolved functions.
// They will be removed from the tree.
continue;
for_formals(formal, fn)
{
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM) ||
formal->type == dtMethodToken)
{
// Remove the argument from the call site.
forv_Vec(CallExpr, call, *fn->calledBy)
{
// Don't bother with calls that are not in the tree.
if (! call->parentSymbol)
continue;
// Performance note: AList::get(int) also performs a linear search.
for_formals_actuals(cf, ca, call)
{
if (cf == formal)
{
ca->remove();
break;
}
}
}
formal->defPoint->remove();
}
}
}
}
static void removeRandomPrimitives()
{
forv_Vec(CallExpr, call, gCallExprs)
{
// Don't bother with calls that are not in the tree.
if (! call->parentSymbol)
continue;
// Ignore calls to actual functions.
if (call->isResolved())
continue;
// Only primitives remain.
removeRandomPrimitive(call);
}
}
static void removeActualNames()
{
forv_Vec(NamedExpr, named, gNamedExprs)
{
if (! named->parentSymbol)
continue;
// Remove names of named actuals
Expr* actual = named->actual;
actual->remove();
named->replace(actual);
}
}
static void removeTypeBlocks()
{
forv_Vec(BlockStmt, block, gBlockStmts)
{
if (! block->parentSymbol)
continue;
// Remove type blocks--code that exists only to determine types
if (block->blockTag & BLOCK_TYPE_ONLY)
{
block->remove();
}
}
}
//
// buildRuntimeTypeInitFns: Build a 'chpl__convertRuntimeTypeToValue'
// (value) function for all functions tagged as runtime type
// initialization functions. Also, build a function to return the
// runtime type for all runtime type initialization functions.
//
// Functions flagged with the "runtime type init fn" pragma
// (FLAG_RUNTIME_TYPE_INIT_FN during compilation) are designed to
// specify to the compiler how to create a new value of a given type
// from the arguments to the function. These arguments effectively
// supply whatever static and/or runtime information is required to
// build such a value (and therefore effectively represent the
// "type"). Any non-static arguments are bundled into a runtime type
// (record) by the compiler and passed around to represent the type at
// execution time.
//
// The actual type specified is fully-resolved during function resolution. So
// the "runtime type" mechanism is a way to create a parameterized type, but up
// to a point handle it uniformly in the compiler.
// Perhaps a more complete implementation of generic types with inheritance
// would get rid of the need for this specialized machinery.
//
// In practice, we currently use these to create
// runtime types for domains and arrays (via procedures named
// 'chpl__buildDomainRuntimeType' and 'chpl__buildArrayRuntimeType',
// respectively).
//
// For each such flagged function:
//
// - Clone the function, naming it 'chpl__convertRuntimeTypeToValue'
// and change it to a value function
//
// - Replace the body of the original function with a new function
// that returns the dynamic runtime type info
//
// Subsequently, the functions as written in the modules are now
// called 'chpl__convertRuntimeTypeToValue' and used to initialize
// variables with runtime types later in insertRuntimeInitTemps().
//
// Notice also that the original functions had been marked as type
// functions during parsing even though they were not written as such
// (see addPragmaFlags() in build.cpp for more info). Now they are
// actually type functions.
//
static void buildRuntimeTypeInitFns() {
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
// Look only at functions flagged as "runtime type init fn".
if (fn->hasFlag(FLAG_RUNTIME_TYPE_INIT_FN)) {
// Look only at resolved instances.
if (! fn->isResolved())
continue;
INT_ASSERT(fn->retType->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE));
SET_LINENO(fn);
// Build a new runtime type for this function
Type* runtimeType = buildRuntimeTypeInfo(fn);
runtimeTypeMap.put(fn->retType, runtimeType);
// Build chpl__convertRuntimeTypeToValue() instance.
buildRuntimeTypeInitFn(fn, runtimeType);
}
}
}
}
// Build a function to return the runtime type by modifying
// the original function.
static void buildRuntimeTypeInitFn(FnSymbol* fn, Type* runtimeType)
{
// Clone the original function and call the clone chpl__convertRuntimeTypeToValue.
FnSymbol* runtimeTypeToValueFn = fn->copy();
INT_ASSERT(runtimeTypeToValueFn->hasFlag(FLAG_RESOLVED));
runtimeTypeToValueFn->name = astr("chpl__convertRuntimeTypeToValue");
runtimeTypeToValueFn->cname = runtimeTypeToValueFn->name;
// Remove this flag from the clone.
runtimeTypeToValueFn->removeFlag(FLAG_RUNTIME_TYPE_INIT_FN);
// Make the clone a value function.
runtimeTypeToValueFn->getReturnSymbol()->removeFlag(FLAG_TYPE_VARIABLE);
runtimeTypeToValueFn->retTag = RET_VALUE;
fn->defPoint->insertBefore(new DefExpr(runtimeTypeToValueFn));
// Remove static arguments from the RTTV function.
for_formals(formal, runtimeTypeToValueFn)
{
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM))
formal->defPoint->remove();
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
{
Symbol* field = runtimeType->getField(formal->name);
if (! field->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
formal->defPoint->remove();
}
}
// Insert the clone (convertRuntimeTypeToValue) into the runtimeTypeToValueMap.
runtimeTypeToValueMap.put(runtimeType, runtimeTypeToValueFn);
// Change the return type of the original function.
fn->retType = runtimeType;
fn->getReturnSymbol()->type = runtimeType;
// Build a new body for the original function.
BlockStmt* block = new BlockStmt();
VarSymbol* var = newTemp("_return_tmp_", fn->retType);
block->insertAtTail(new DefExpr(var));
// Bundle all non-static arguments into the runtime type record.
// Remove static arguments from this specialized buildRuntimeType function.
for_formals(formal, fn)
{
if (formal->hasFlag(FLAG_INSTANTIATED_PARAM))
continue;
Symbol* field = runtimeType->getField(formal->name);
if (formal->hasFlag(FLAG_TYPE_VARIABLE) &&
! field->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE))
continue;
block->insertAtTail(new CallExpr(PRIM_SET_MEMBER, var, field, formal));
}
block->insertAtTail(new CallExpr(PRIM_RETURN, var));
// Replace the body of the orignal chpl__buildRuntime...Type() function.
fn->body->replace(block);
}
static void removeFormalTypeAndInitBlocks()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
for_formals(formal, fn) {
// Remove formal default values
if (formal->defaultExpr)
formal->defaultExpr->remove();
// Remove formal type expressions
if (formal->typeExpr)
formal->typeExpr->remove();
}
}
}
}
static void replaceTypeArgsWithFormalTypeTemps()
{
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (! fn->isResolved())
// Don't bother with unresolved functions.
// They will be removed from the tree.
continue;
// Skip this function if it is not in the tree.
if (! fn->defPoint)
continue;
if (! fn->defPoint->parentSymbol)
continue;
// We do not remove type args from extern functions
// TODO: Find out if we really support type args in extern functions.
if (fn->hasFlag(FLAG_EXTERN))
continue;
for_formals(formal, fn)
{
// We are only interested in type formals
if (! formal->hasFlag(FLAG_TYPE_VARIABLE))
continue;
// Replace the formal with a _formal_type_tmp_.
SET_LINENO(formal);
VarSymbol* tmp = newTemp("_formal_type_tmp_", formal->type);
fn->insertAtHead(new DefExpr(tmp));
subSymbol(fn, formal, tmp);
// Remove the corresponding actual from all call sites.
forv_Vec(CallExpr, call, *fn->calledBy)
{
for_formals_actuals(cf, ca, call)
{
if (cf == formal)
{
ca->remove();
break;
}
}
}
formal->defPoint->remove();
//
// If we're removing the formal representing 'this' (if it's a
// type, say), we need to nullify the 'this' pointer in the
// function as well to avoid assumptions that it's legal later.
//
if (formal == fn->_this) {
fn->_this = NULL;
}
}
}
}
static void replaceValuesWithRuntimeTypes()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
for_formals(formal, fn) {
if (formal->hasFlag(FLAG_TYPE_VARIABLE) &&
formal->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
if (FnSymbol* fn = valueToRuntimeTypeMap.get(formal->type)) {
Type* rt = (fn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) ?
fn->retType : runtimeTypeMap.get(fn->retType);
INT_ASSERT(rt);
formal->type = rt;
formal->removeFlag(FLAG_TYPE_VARIABLE);
}
}
}
}
}
}
static void removeWhereClauses()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
if (fn->where)
fn->where->remove();
}
}
}
static void replaceReturnedValuesWithRuntimeTypes()
{
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (fn->defPoint && fn->defPoint->parentSymbol) {
if (fn->retTag == RET_TYPE) {
VarSymbol* ret = toVarSymbol(fn->getReturnSymbol());
if (ret && ret->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
if (FnSymbol* rtfn = valueToRuntimeTypeMap.get(ret->type)) {
Type* rt = (rtfn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) ?
rtfn->retType : runtimeTypeMap.get(rtfn->retType);
INT_ASSERT(rt);
ret->type = rt;
fn->retType = ret->type;
fn->retTag = RET_VALUE;
}
}
}
}
}
}
static void replaceInitPrims(std::vector<BaseAST*>& asts)
{
for_vector(BaseAST, ast, asts) {
if (CallExpr* call = toCallExpr(ast)) {
// We are only interested in INIT primitives.
if (call->isPrimitive(PRIM_INIT)) {
FnSymbol* parent = toFnSymbol(call->parentSymbol);
// Call must be in the tree and lie in a resolved function.
if (! parent || ! parent->isResolved())
continue;
SymExpr* se = toSymExpr(call->get(1));
Type* rt = se->var->type;
if (rt->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) {
// ('init' foo), where typeof(foo) has flag "runtime type value"
//
// ==>
//
// (var _runtime_type_tmp_1)
// ('move' _runtime_type_tmp_1 ('.v' foo "field1"))
// (var _runtime_type_tmp_2)
// ('move' _runtime_type_tmp_2 ('.v' foo "field2"))
// (chpl__convertRuntimeTypeToValue _runtime_type_tmp_1 _rtt_2 ... )
SET_LINENO(call);
FnSymbol* runtimeTypeToValueFn = runtimeTypeToValueMap.get(rt);
INT_ASSERT(runtimeTypeToValueFn);
CallExpr* runtimeTypeToValueCall = new CallExpr(runtimeTypeToValueFn);
for_formals(formal, runtimeTypeToValueFn) {
Symbol* field = rt->getField(formal->name);
INT_ASSERT(field);
VarSymbol* tmp = newTemp("_runtime_type_tmp_", field->type);
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp,
new CallExpr(PRIM_GET_MEMBER_VALUE, se->var, field)));
if (formal->hasFlag(FLAG_TYPE_VARIABLE))
tmp->addFlag(FLAG_TYPE_VARIABLE);
runtimeTypeToValueCall->insertAtTail(tmp);
}
VarSymbol* tmp = newTemp("_runtime_type_tmp_", runtimeTypeToValueFn->retType);
call->getStmtExpr()->insertBefore(new DefExpr(tmp));
call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, runtimeTypeToValueCall));
INT_ASSERT(autoCopyMap.get(tmp->type));
call->replace(new CallExpr(autoCopyMap.get(tmp->type), tmp));
} else if (rt->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
//
// This is probably related to a comment that used to handle
// this case elsewhere:
//
// special handling of tuple constructor to avoid
// initialization of array based on an array type symbol
// rather than a runtime array type
//
// this code added during the introduction of the new
// keyword; it should be removed when possible
//
call->getStmtExpr()->remove();
}
else
{
Expr* expr = resolvePrimInit(call);
if (! expr)
{
// This PRIM_INIT could not be resolved.
// But that's OK if it's an extern type.
// (We don't expect extern types to have initializers.)
// Also, we don't generate initializers for iterator records.
// Maybe we can avoid adding PRIM_INIT for these cases in the first
// place....
if (rt->symbol->hasFlag(FLAG_EXTERN) ||
rt->symbol->hasFlag(FLAG_ITERATOR_RECORD))
{
INT_ASSERT(toCallExpr(call->parentExpr)->isPrimitive(PRIM_MOVE));
makeNoop(toCallExpr(call->parentExpr));
continue;
}
INT_FATAL(call, "PRIM_INIT should have already been handled");
}
}
}
}
}
}
static void insertRuntimeInitTemps() {
std::vector<BaseAST*> asts;
collect_asts_postorder(rootModule, asts);
// Collect asts which are definitions of VarSymbols that are type variables
// and are flagged as runtime types.
for_vector(BaseAST, ast, asts) {
if (DefExpr* def = toDefExpr(ast)) {
if (isVarSymbol(def->sym) &&
def->sym->hasFlag(FLAG_TYPE_VARIABLE) &&
def->sym->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) {
// Collapse these through the runtimeTypeMap ...
Type* rt = runtimeTypeMap.get(def->sym->type);
INT_ASSERT(rt);
def->sym->type = rt;
// ... and remove the type variable flag
// (Make these declarations look like normal vars.)
def->sym->removeFlag(FLAG_TYPE_VARIABLE);
}
}
}
replaceInitPrims(asts);
for_vector(BaseAST, ast1, asts) {
if (SymExpr* se = toSymExpr(ast1)) {
// remove dead type expressions
if (se->getStmtExpr() == se)
if (se->var->hasFlag(FLAG_TYPE_VARIABLE))
se->remove();
}
}
}
// Remove typedef definitions
static void removeInitFields()
{
forv_Vec(DefExpr, def, gDefExprs)
{
if (! def->inTree()) continue;
if (! def->init) continue;
if (! def->sym->hasFlag(FLAG_TYPE_VARIABLE)) continue;
def->init->remove();
def->init = NULL;
}
}
static void removeMootFields() {
// Remove type fields, parameter fields, and _promotionType field
forv_Vec(TypeSymbol, type, gTypeSymbols) {
if (type->defPoint && type->defPoint->parentSymbol) {
if (AggregateType* ct = toAggregateType(type->type)) {
for_fields(field, ct) {
if (field->hasFlag(FLAG_TYPE_VARIABLE) ||
field->isParameter() ||
!strcmp(field->name, "_promotionType"))
field->defPoint->remove();
}
}
}
}
}
static void expandInitFieldPrims()
{
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_INIT_FIELDS))
{
initializeClass(call, toSymExpr(call->get(1))->var);
call->remove();
}
}
}
static void
fixTypeNames(AggregateType* ct)
{
const char default_domain_name[] = "DefaultRectangularDom";
if (!ct->symbol->hasFlag(FLAG_BASE_ARRAY) && isArrayClass(ct))
{
const char* domain_type = ct->getField("dom")->type->symbol->name;
const char* elt_type = ct->getField("eltType")->type->symbol->name;
ct->symbol->name = astr("[", domain_type, "] ", elt_type);
}
if (ct->instantiatedFrom &&
!strcmp(ct->instantiatedFrom->symbol->name, default_domain_name)) {
ct->symbol->name = astr("domain", ct->symbol->name+strlen(default_domain_name));
}
if (isRecordWrappedType(ct)) {
ct->symbol->name = ct->getField("_valueType")->type->symbol->name;
}
}
static void
setScalarPromotionType(AggregateType* ct) {
for_fields(field, ct) {
if (!strcmp(field->name, "_promotionType"))
ct->scalarPromotionType = field->type;
}
}
|
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_plot_renderer.h"
#include "qwt_plot.h"
#include "qwt_painter.h"
#include "qwt_plot_layout.h"
#include "qwt_abstract_legend.h"
#include "qwt_scale_widget.h"
#include "qwt_scale_engine.h"
#include "qwt_text.h"
#include "qwt_text_label.h"
#include "qwt_math.h"
#include <qpainter.h>
#include <qpaintengine.h>
#include <qtransform.h>
#include <qprinter.h>
#include <qprintdialog.h>
#include <qfiledialog.h>
#include <qfileinfo.h>
#include <qstyle.h>
#include <qstyleoption.h>
#include <qimagewriter.h>
#ifndef QWT_NO_SVG
#ifdef QT_SVG_LIB
#include <qsvggenerator.h>
#endif
#endif
class QwtPlotRenderer::PrivateData
{
public:
PrivateData():
discardFlags( QwtPlotRenderer::DiscardBackground ),
layoutFlags( QwtPlotRenderer::DefaultLayout )
{
}
QwtPlotRenderer::DiscardFlags discardFlags;
QwtPlotRenderer::LayoutFlags layoutFlags;
};
static void qwtRenderBackground( QPainter *painter,
const QRectF &rect, const QWidget *widget )
{
if ( widget->testAttribute( Qt::WA_StyledBackground ) )
{
QStyleOption opt;
opt.initFrom( widget );
opt.rect = rect.toAlignedRect();
widget->style()->drawPrimitive(
QStyle::PE_Widget, &opt, painter, widget);
}
else
{
const QBrush brush =
widget->palette().brush( widget->backgroundRole() );
painter->fillRect( rect, brush );
}
}
/*!
Constructor
\param parent Parent object
*/
QwtPlotRenderer::QwtPlotRenderer( QObject *parent ):
QObject( parent )
{
d_data = new PrivateData;
}
//! Destructor
QwtPlotRenderer::~QwtPlotRenderer()
{
delete d_data;
}
/*!
Change a flag, indicating what to discard from rendering
\param flag Flag to change
\param on On/Off
\sa DiscardFlag, testDiscardFlag(), setDiscardFlags(), discardFlags()
*/
void QwtPlotRenderer::setDiscardFlag( DiscardFlag flag, bool on )
{
if ( on )
d_data->discardFlags |= flag;
else
d_data->discardFlags &= ~flag;
}
/*!
Check if a flag is set.
\param flag Flag to be tested
\sa DiscardFlag, setDiscardFlag(), setDiscardFlags(), discardFlags()
*/
bool QwtPlotRenderer::testDiscardFlag( DiscardFlag flag ) const
{
return d_data->discardFlags & flag;
}
/*!
Set the flags, indicating what to discard from rendering
\param flags Flags
\sa DiscardFlag, setDiscardFlag(), testDiscardFlag(), discardFlags()
*/
void QwtPlotRenderer::setDiscardFlags( DiscardFlags flags )
{
d_data->discardFlags = flags;
}
/*!
\return Flags, indicating what to discard from rendering
\sa DiscardFlag, setDiscardFlags(), setDiscardFlag(), testDiscardFlag()
*/
QwtPlotRenderer::DiscardFlags QwtPlotRenderer::discardFlags() const
{
return d_data->discardFlags;
}
/*!
Change a layout flag
\param flag Flag to change
\param on On/Off
\sa LayoutFlag, testLayoutFlag(), setLayoutFlags(), layoutFlags()
*/
void QwtPlotRenderer::setLayoutFlag( LayoutFlag flag, bool on )
{
if ( on )
d_data->layoutFlags |= flag;
else
d_data->layoutFlags &= ~flag;
}
/*!
Check if a flag is set.
\param flag Flag to be tested
\sa LayoutFlag, setLayoutFlag(), setLayoutFlags(), layoutFlags()
*/
bool QwtPlotRenderer::testLayoutFlag( LayoutFlag flag ) const
{
return d_data->layoutFlags & flag;
}
/*!
Set the layout flags
\param flags Flags
\sa LayoutFlag, setLayoutFlag(), testLayoutFlag(), layoutFlags()
*/
void QwtPlotRenderer::setLayoutFlags( LayoutFlags flags )
{
d_data->layoutFlags = flags;
}
/*!
\return Layout flags
\sa LayoutFlag, setLayoutFlags(), setLayoutFlag(), testLayoutFlag()
*/
QwtPlotRenderer::LayoutFlags QwtPlotRenderer::layoutFlags() const
{
return d_data->layoutFlags;
}
/*!
Render a plot to a file
The format of the document will be autodetected from the
suffix of the filename.
\param plot Plot widget
\param fileName Path of the file, where the document will be stored
\param sizeMM Size for the document in millimeters.
\param resolution Resolution in dots per Inch (dpi)
*/
void QwtPlotRenderer::renderDocument( QwtPlot *plot,
const QString &fileName, const QSizeF &sizeMM, int resolution )
{
renderDocument( plot, fileName,
QFileInfo( fileName ).suffix(), sizeMM, resolution );
}
/*!
Render a plot to a file
Supported formats are:
- pdf\n
Portable Document Format PDF
- ps\n
Postcript
- svg\n
Scalable Vector Graphics SVG
- all image formats supported by Qt\n
see QImageWriter::supportedImageFormats()
Scalable vector graphic formats like PDF or SVG are superior to
raster graphics formats.
\param plot Plot widget
\param fileName Path of the file, where the document will be stored
\param format Format for the document
\param sizeMM Size for the document in millimeters.
\param resolution Resolution in dots per Inch (dpi)
\sa renderTo(), render(), QwtPainter::setRoundingAlignment()
*/
void QwtPlotRenderer::renderDocument( QwtPlot *plot,
const QString &fileName, const QString &format,
const QSizeF &sizeMM, int resolution )
{
if ( plot == NULL || sizeMM.isEmpty() || resolution <= 0 )
return;
QString title = plot->title().text();
if ( title.isEmpty() )
title = "Plot Document";
const double mmToInch = 1.0 / 25.4;
const QSizeF size = sizeMM * mmToInch * resolution;
const QRectF documentRect( 0.0, 0.0, size.width(), size.height() );
const QString fmt = format.toLower();
if ( fmt == "pdf" || fmt == "ps" )
{
#ifndef QT_NO_PRINTER
QPrinter printer;
printer.setFullPage( true );
printer.setPaperSize( sizeMM, QPrinter::Millimeter );
printer.setDocName( title );
printer.setOutputFileName( fileName );
printer.setOutputFormat( ( format == "pdf" )
? QPrinter::PdfFormat : QPrinter::PostScriptFormat );
printer.setResolution( resolution );
QPainter painter( &printer );
render( plot, &painter, documentRect );
#endif
}
else if ( fmt == "svg" )
{
#ifndef QWT_NO_SVG
#ifdef QT_SVG_LIB
#if QT_VERSION >= 0x040500
QSvgGenerator generator;
generator.setTitle( title );
generator.setFileName( fileName );
generator.setResolution( resolution );
generator.setViewBox( documentRect );
QPainter painter( &generator );
render( plot, &painter, documentRect );
#endif
#endif
#endif
}
else
{
if ( QImageWriter::supportedImageFormats().indexOf(
format.toLatin1() ) >= 0 )
{
const QRect imageRect = documentRect.toRect();
const int dotsPerMeter = qRound( resolution * mmToInch * 1000.0 );
QImage image( imageRect.size(), QImage::Format_ARGB32 );
image.setDotsPerMeterX( dotsPerMeter );
image.setDotsPerMeterY( dotsPerMeter );
image.fill( QColor( Qt::white ).rgb() );
QPainter painter( &image );
render( plot, &painter, imageRect );
painter.end();
image.save( fileName, format.toLatin1() );
}
}
}
/*!
\brief Render the plot to a \c QPaintDevice
This function renders the contents of a QwtPlot instance to
\c QPaintDevice object. The target rectangle is derived from
its device metrics.
\param plot Plot to be rendered
\param paintDevice device to paint on, f.e a QImage
\sa renderDocument(), render(), QwtPainter::setRoundingAlignment()
*/
void QwtPlotRenderer::renderTo(
QwtPlot *plot, QPaintDevice &paintDevice ) const
{
int w = paintDevice.width();
int h = paintDevice.height();
QPainter p( &paintDevice );
render( plot, &p, QRectF( 0, 0, w, h ) );
}
/*!
\brief Render the plot to a QPrinter
This function renders the contents of a QwtPlot instance to
\c QPaintDevice object. The size is derived from the printer
metrics.
\param plot Plot to be rendered
\param printer Printer to paint on
\sa renderDocument(), render(), QwtPainter::setRoundingAlignment()
*/
#ifndef QT_NO_PRINTER
void QwtPlotRenderer::renderTo(
QwtPlot *plot, QPrinter &printer ) const
{
int w = printer.width();
int h = printer.height();
QRectF rect( 0, 0, w, h );
double aspect = rect.width() / rect.height();
if ( ( aspect < 1.0 ) )
rect.setHeight( aspect * rect.width() );
QPainter p( &printer );
render( plot, &p, rect );
}
#endif
#ifndef QWT_NO_SVG
#ifdef QT_SVG_LIB
#if QT_VERSION >= 0x040500
/*!
\brief Render the plot to a QSvgGenerator
If the generator has a view box, the plot will be rendered into it.
If it has no viewBox but a valid size the target coordinates
will be (0, 0, generator.width(), generator.height()). Otherwise
the target rectangle will be QRectF(0, 0, 800, 600);
\param plot Plot to be rendered
\param generator SVG generator
*/
void QwtPlotRenderer::renderTo(
QwtPlot *plot, QSvgGenerator &generator ) const
{
QRectF rect = generator.viewBoxF();
if ( rect.isEmpty() )
rect.setRect( 0, 0, generator.width(), generator.height() );
if ( rect.isEmpty() )
rect.setRect( 0, 0, 800, 600 ); // something
QPainter p( &generator );
render( plot, &p, rect );
}
#endif
#endif
#endif
/*!
Paint the contents of a QwtPlot instance into a given rectangle.
\param plot Plot to be rendered
\param painter Painter
\param plotRect Bounding rectangle
\sa renderDocument(), renderTo(), QwtPainter::setRoundingAlignment()
*/
void QwtPlotRenderer::render( QwtPlot *plot,
QPainter *painter, const QRectF &plotRect ) const
{
if ( painter == 0 || !painter->isActive() ||
!plotRect.isValid() || plot->size().isNull() )
return;
if ( !( d_data->discardFlags & DiscardBackground ) )
qwtRenderBackground( painter, plotRect, plot );
/*
The layout engine uses the same methods as they are used
by the Qt layout system. Therefore we need to calculate the
layout in screen coordinates and paint with a scaled painter.
*/
QTransform transform;
transform.scale(
double( painter->device()->logicalDpiX() ) / plot->logicalDpiX(),
double( painter->device()->logicalDpiY() ) / plot->logicalDpiY() );
QRectF layoutRect = transform.inverted().mapRect( plotRect );
QwtPlotLayout *layout = plot->plotLayout();
int baseLineDists[QwtPlot::axisCnt];
int canvasMargins[QwtPlot::axisCnt];
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
canvasMargins[ axisId ] = layout->canvasMargin( axisId );
if ( d_data->layoutFlags & FrameWithScales )
{
QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget )
{
baseLineDists[axisId] = scaleWidget->margin();
scaleWidget->setMargin( 0 );
}
if ( !plot->axisEnabled( axisId ) )
{
int left = 0;
int right = 0;
int top = 0;
int bottom = 0;
// When we have a scale the frame is painted on
// the position of the backbone - otherwise we
// need to introduce a margin around the canvas
switch( axisId )
{
case QwtPlot::yLeft:
layoutRect.adjust( 1, 0, 0, 0 );
break;
case QwtPlot::yRight:
layoutRect.adjust( 0, 0, -1, 0 );
break;
case QwtPlot::xTop:
layoutRect.adjust( 0, 1, 0, 0 );
break;
case QwtPlot::xBottom:
layoutRect.adjust( 0, 0, 0, -1 );
break;
default:
break;
}
layoutRect.adjust( left, top, right, bottom );
}
}
}
// Calculate the layout for the document.
QwtPlotLayout::Options layoutOptions =
QwtPlotLayout::IgnoreScrollbars | QwtPlotLayout::IgnoreFrames;
if ( d_data->discardFlags & DiscardLegend )
layoutOptions |= QwtPlotLayout::IgnoreLegend;
if ( d_data->discardFlags & DiscardTitle )
layoutOptions |= QwtPlotLayout::IgnoreTitle;
if ( d_data->discardFlags & DiscardFooter )
layoutOptions |= QwtPlotLayout::IgnoreFooter;
layout->activate( plot, layoutRect, layoutOptions );
// canvas
QwtScaleMap maps[QwtPlot::axisCnt];
buildCanvasMaps( plot, layout->canvasRect(), maps );
if ( updateCanvasMargins( plot, layout->canvasRect(), maps ) )
{
// recalculate maps and layout, when the margins
// have been changed
layout->activate( plot, layoutRect, layoutOptions );
buildCanvasMaps( plot, layout->canvasRect(), maps );
}
// now start painting
painter->save();
painter->setWorldTransform( transform, true );
renderCanvas( plot, painter, layout->canvasRect(), maps );
if ( !( d_data->discardFlags & DiscardTitle )
&& ( !plot->titleLabel()->text().isEmpty() ) )
{
renderTitle( plot, painter, layout->titleRect() );
}
if ( !( d_data->discardFlags & DiscardFooter )
&& ( !plot->footerLabel()->text().isEmpty() ) )
{
renderFooter( plot, painter, layout->footerRect() );
}
if ( !( d_data->discardFlags & DiscardLegend )
&& plot->legend() && !plot->legend()->isEmpty() )
{
renderLegend( plot, painter, layout->legendRect() );
}
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget )
{
int baseDist = scaleWidget->margin();
int startDist, endDist;
scaleWidget->getBorderDistHint( startDist, endDist );
renderScale( plot, painter, axisId, startDist, endDist,
baseDist, layout->scaleRect( axisId ) );
}
}
painter->restore();
// restore all setting to their original attributes.
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
if ( d_data->layoutFlags & FrameWithScales )
{
QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget )
scaleWidget->setMargin( baseLineDists[axisId] );
}
layout->setCanvasMargin( canvasMargins[axisId] );
}
layout->invalidate();
}
/*!
Render the title into a given rectangle.
\param plot Plot widget
\param painter Painter
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderTitle( const QwtPlot *plot,
QPainter *painter, const QRectF &rect ) const
{
painter->setFont( plot->titleLabel()->font() );
const QColor color = plot->titleLabel()->palette().color(
QPalette::Active, QPalette::Text );
painter->setPen( color );
plot->titleLabel()->text().draw( painter, rect );
}
/*!
Render the footer into a given rectangle.
\param plot Plot widget
\param painter Painter
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderFooter( const QwtPlot *plot,
QPainter *painter, const QRectF &rect ) const
{
painter->setFont( plot->footerLabel()->font() );
const QColor color = plot->footerLabel()->palette().color(
QPalette::Active, QPalette::Text );
painter->setPen( color );
plot->footerLabel()->text().draw( painter, rect );
}
/*!
Render the legend into a given rectangle.
\param plot Plot widget
\param painter Painter
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderLegend( const QwtPlot *plot,
QPainter *painter, const QRectF &rect ) const
{
if ( plot->legend() )
{
bool fillBackground = !( d_data->discardFlags & DiscardBackground );
plot->legend()->renderLegend( painter, rect, fillBackground );
}
}
/*!
\brief Paint a scale into a given rectangle.
Paint the scale into a given rectangle.
\param plot Plot widget
\param painter Painter
\param axisId Axis
\param startDist Start border distance
\param endDist End border distance
\param baseDist Base distance
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderScale( const QwtPlot *plot,
QPainter *painter,
int axisId, int startDist, int endDist, int baseDist,
const QRectF &rect ) const
{
if ( !plot->axisEnabled( axisId ) )
return;
const QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget->isColorBarEnabled()
&& scaleWidget->colorBarWidth() > 0 )
{
scaleWidget->drawColorBar( painter, scaleWidget->colorBarRect( rect ) );
const int off = scaleWidget->colorBarWidth() + scaleWidget->spacing();
if ( scaleWidget->scaleDraw()->orientation() == Qt::Horizontal )
baseDist += off;
else
baseDist += off;
}
painter->save();
QwtScaleDraw::Alignment align;
double x, y, w;
switch ( axisId )
{
case QwtPlot::yLeft:
{
x = rect.right() - 1.0 - baseDist;
y = rect.y() + startDist;
w = rect.height() - startDist - endDist;
align = QwtScaleDraw::LeftScale;
break;
}
case QwtPlot::yRight:
{
x = rect.left() + baseDist;
y = rect.y() + startDist;
w = rect.height() - startDist - endDist;
align = QwtScaleDraw::RightScale;
break;
}
case QwtPlot::xTop:
{
x = rect.left() + startDist;
y = rect.bottom() - 1.0 - baseDist;
w = rect.width() - startDist - endDist;
align = QwtScaleDraw::TopScale;
break;
}
case QwtPlot::xBottom:
{
x = rect.left() + startDist;
y = rect.top() + baseDist;
w = rect.width() - startDist - endDist;
align = QwtScaleDraw::BottomScale;
break;
}
default:
return;
}
scaleWidget->drawTitle( painter, align, rect );
painter->setFont( scaleWidget->font() );
QwtScaleDraw *sd = const_cast<QwtScaleDraw *>( scaleWidget->scaleDraw() );
const QPointF sdPos = sd->pos();
const double sdLength = sd->length();
sd->move( x, y );
sd->setLength( w );
QPalette palette = scaleWidget->palette();
palette.setCurrentColorGroup( QPalette::Active );
sd->draw( painter, palette );
// reset previous values
sd->move( sdPos );
sd->setLength( sdLength );
painter->restore();
}
/*!
Render the canvas into a given rectangle.
\param plot Plot widget
\param painter Painter
\param map Maps mapping between plot and paint device coordinates
\param canvasRect Canvas rectangle
*/
void QwtPlotRenderer::renderCanvas( const QwtPlot *plot,
QPainter *painter, const QRectF &canvasRect,
const QwtScaleMap *map ) const
{
const QWidget *canvas = plot->canvas();
painter->save();
QPainterPath clipPath;
QRectF r = canvasRect.adjusted( 0.0, 0.0, -1.0, -1.0 );
if ( d_data->layoutFlags & FrameWithScales )
{
r.adjust( -1.0, -1.0, 1.0, 1.0 );
painter->setPen( QPen( Qt::black ) );
if ( !( d_data->discardFlags & DiscardCanvasBackground ) )
{
const QBrush bgBrush =
canvas->palette().brush( plot->backgroundRole() );
painter->setBrush( bgBrush );
}
QwtPainter::drawRect( painter, r );
}
else
{
if ( !( d_data->discardFlags & DiscardCanvasBackground ) )
{
qwtRenderBackground( painter, r, canvas );
if ( canvas->testAttribute( Qt::WA_StyledBackground ) )
{
// The clip region is calculated in integers
// To avoid too much rounding errors better
// calculate it in target device resolution
// TODO ...
int x1 = qCeil( canvasRect.left() );
int x2 = qFloor( canvasRect.right() );
int y1 = qCeil( canvasRect.top() );
int y2 = qFloor( canvasRect.bottom() );
const QRect r( x1, y1, x2 - x1 - 1, y2 - y1 - 1 );
( void ) QMetaObject::invokeMethod(
const_cast< QWidget *>( canvas ), "borderPath", Qt::DirectConnection,
Q_RETURN_ARG( QPainterPath, clipPath ), Q_ARG( QRect, r ) );
}
}
}
painter->restore();
painter->save();
if ( clipPath.isEmpty() )
painter->setClipRect( canvasRect );
else
painter->setClipPath( clipPath );
plot->drawItems( painter, canvasRect, map );
painter->restore();
}
/*!
Calculated the scale maps for rendering the canvas
\param plot Plot widget
\param canvasRect Target rectangle
\param maps Scale maps to be calculated
*/
void QwtPlotRenderer::buildCanvasMaps( const QwtPlot *plot,
const QRectF &canvasRect, QwtScaleMap maps[] ) const
{
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
maps[axisId].setTransformation(
plot->axisScaleEngine( axisId )->transformation() );
const QwtScaleDiv &scaleDiv = plot->axisScaleDiv( axisId );
maps[axisId].setScaleInterval(
scaleDiv.lowerBound(), scaleDiv.upperBound() );
double from, to;
if ( plot->axisEnabled( axisId ) )
{
const int sDist = plot->axisWidget( axisId )->startBorderDist();
const int eDist = plot->axisWidget( axisId )->endBorderDist();
const QRectF &scaleRect = plot->plotLayout()->scaleRect( axisId );
if ( axisId == QwtPlot::xTop || axisId == QwtPlot::xBottom )
{
from = scaleRect.left() + sDist;
to = scaleRect.right() - eDist;
}
else
{
from = scaleRect.bottom() - eDist;
to = scaleRect.top() + sDist;
}
}
else
{
int margin = plot->plotLayout()->canvasMargin( axisId );
if ( axisId == QwtPlot::yLeft || axisId == QwtPlot::yRight )
{
from = canvasRect.bottom() - margin;
to = canvasRect.top() + margin;
}
else
{
from = canvasRect.left() + margin;
to = canvasRect.right() - margin;
}
}
maps[axisId].setPaintInterval( from, to );
}
}
bool QwtPlotRenderer::updateCanvasMargins( QwtPlot *plot,
const QRectF &canvasRect, const QwtScaleMap maps[] ) const
{
double margins[QwtPlot::axisCnt];
plot->getCanvasMarginsHint( maps, canvasRect,
margins[QwtPlot::yLeft], margins[QwtPlot::xTop],
margins[QwtPlot::yRight], margins[QwtPlot::xBottom] );
bool marginsChanged = false;
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
if ( margins[axisId] >= 0.0 )
{
const int m = qCeil( margins[axisId] );
plot->plotLayout()->setCanvasMargin( m, axisId);
marginsChanged = true;
}
}
return marginsChanged;
}
/*!
\brief Execute a file dialog and render the plot to the selected file
The document will be rendered in 85dpi for a size 30x20cm
\param plot Plot widget
\param documentName Default document name
\note exportTo() is handy for testing, but usually an application
wants to configure the export individually
using renderDocument() or even more low level methods
of QwtPlotRenderer.
*/
bool QwtPlotRenderer::exportTo( QwtPlot *plot, const QString &documentName )
{
if ( plot == NULL )
return false;
QString fileName = documentName;
// What about translation
#ifndef QT_NO_FILEDIALOG
const QList<QByteArray> imageFormats =
QImageWriter::supportedImageFormats();
QStringList filter;
#ifndef QT_NO_PRINTER
filter += QString( "PDF " ) + tr( "Documents" ) + " (*.pdf)";
#endif
#ifndef QWT_NO_SVG
filter += QString( "SVG " ) + tr( "Documents" ) + " (*.svg)";
#endif
#ifndef QT_NO_PRINTER
filter += QString( "Postscript " ) + tr( "Documents" ) + " (*.ps)";
#endif
if ( imageFormats.size() > 0 )
{
QString imageFilter( tr( "Images" ) );
imageFilter += " (";
for ( int i = 0; i < imageFormats.size(); i++ )
{
if ( i > 0 )
imageFilter += " ";
imageFilter += "*.";
imageFilter += imageFormats[i];
}
imageFilter += ")";
filter += imageFilter;
}
fileName = QFileDialog::getSaveFileName(
NULL, tr( "Export File Name" ), fileName,
filter.join( ";;" ), NULL, QFileDialog::DontConfirmOverwrite );
#endif
if ( fileName.isEmpty() )
return false;
renderDocument( plot, fileName, QSizeF( 300, 200 ), 85 );
return true;
}
Qt5 adjustments
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_plot_renderer.h"
#include "qwt_plot.h"
#include "qwt_painter.h"
#include "qwt_plot_layout.h"
#include "qwt_abstract_legend.h"
#include "qwt_scale_widget.h"
#include "qwt_scale_engine.h"
#include "qwt_text.h"
#include "qwt_text_label.h"
#include "qwt_math.h"
#include <qpainter.h>
#include <qpaintengine.h>
#include <qtransform.h>
#include <qprinter.h>
#include <qprintdialog.h>
#include <qfiledialog.h>
#include <qfileinfo.h>
#include <qstyle.h>
#include <qstyleoption.h>
#include <qimagewriter.h>
#ifndef QWT_NO_SVG
#ifdef QT_SVG_LIB
#include <qsvggenerator.h>
#endif
#endif
class QwtPlotRenderer::PrivateData
{
public:
PrivateData():
discardFlags( QwtPlotRenderer::DiscardBackground ),
layoutFlags( QwtPlotRenderer::DefaultLayout )
{
}
QwtPlotRenderer::DiscardFlags discardFlags;
QwtPlotRenderer::LayoutFlags layoutFlags;
};
static void qwtRenderBackground( QPainter *painter,
const QRectF &rect, const QWidget *widget )
{
if ( widget->testAttribute( Qt::WA_StyledBackground ) )
{
QStyleOption opt;
opt.initFrom( widget );
opt.rect = rect.toAlignedRect();
widget->style()->drawPrimitive(
QStyle::PE_Widget, &opt, painter, widget);
}
else
{
const QBrush brush =
widget->palette().brush( widget->backgroundRole() );
painter->fillRect( rect, brush );
}
}
/*!
Constructor
\param parent Parent object
*/
QwtPlotRenderer::QwtPlotRenderer( QObject *parent ):
QObject( parent )
{
d_data = new PrivateData;
}
//! Destructor
QwtPlotRenderer::~QwtPlotRenderer()
{
delete d_data;
}
/*!
Change a flag, indicating what to discard from rendering
\param flag Flag to change
\param on On/Off
\sa DiscardFlag, testDiscardFlag(), setDiscardFlags(), discardFlags()
*/
void QwtPlotRenderer::setDiscardFlag( DiscardFlag flag, bool on )
{
if ( on )
d_data->discardFlags |= flag;
else
d_data->discardFlags &= ~flag;
}
/*!
Check if a flag is set.
\param flag Flag to be tested
\sa DiscardFlag, setDiscardFlag(), setDiscardFlags(), discardFlags()
*/
bool QwtPlotRenderer::testDiscardFlag( DiscardFlag flag ) const
{
return d_data->discardFlags & flag;
}
/*!
Set the flags, indicating what to discard from rendering
\param flags Flags
\sa DiscardFlag, setDiscardFlag(), testDiscardFlag(), discardFlags()
*/
void QwtPlotRenderer::setDiscardFlags( DiscardFlags flags )
{
d_data->discardFlags = flags;
}
/*!
\return Flags, indicating what to discard from rendering
\sa DiscardFlag, setDiscardFlags(), setDiscardFlag(), testDiscardFlag()
*/
QwtPlotRenderer::DiscardFlags QwtPlotRenderer::discardFlags() const
{
return d_data->discardFlags;
}
/*!
Change a layout flag
\param flag Flag to change
\param on On/Off
\sa LayoutFlag, testLayoutFlag(), setLayoutFlags(), layoutFlags()
*/
void QwtPlotRenderer::setLayoutFlag( LayoutFlag flag, bool on )
{
if ( on )
d_data->layoutFlags |= flag;
else
d_data->layoutFlags &= ~flag;
}
/*!
Check if a flag is set.
\param flag Flag to be tested
\sa LayoutFlag, setLayoutFlag(), setLayoutFlags(), layoutFlags()
*/
bool QwtPlotRenderer::testLayoutFlag( LayoutFlag flag ) const
{
return d_data->layoutFlags & flag;
}
/*!
Set the layout flags
\param flags Flags
\sa LayoutFlag, setLayoutFlag(), testLayoutFlag(), layoutFlags()
*/
void QwtPlotRenderer::setLayoutFlags( LayoutFlags flags )
{
d_data->layoutFlags = flags;
}
/*!
\return Layout flags
\sa LayoutFlag, setLayoutFlags(), setLayoutFlag(), testLayoutFlag()
*/
QwtPlotRenderer::LayoutFlags QwtPlotRenderer::layoutFlags() const
{
return d_data->layoutFlags;
}
/*!
Render a plot to a file
The format of the document will be autodetected from the
suffix of the filename.
\param plot Plot widget
\param fileName Path of the file, where the document will be stored
\param sizeMM Size for the document in millimeters.
\param resolution Resolution in dots per Inch (dpi)
*/
void QwtPlotRenderer::renderDocument( QwtPlot *plot,
const QString &fileName, const QSizeF &sizeMM, int resolution )
{
renderDocument( plot, fileName,
QFileInfo( fileName ).suffix(), sizeMM, resolution );
}
/*!
Render a plot to a file
Supported formats are:
- pdf\n
Portable Document Format PDF
- ps\n
Postcript
- svg\n
Scalable Vector Graphics SVG
- all image formats supported by Qt\n
see QImageWriter::supportedImageFormats()
Scalable vector graphic formats like PDF or SVG are superior to
raster graphics formats.
\param plot Plot widget
\param fileName Path of the file, where the document will be stored
\param format Format for the document
\param sizeMM Size for the document in millimeters.
\param resolution Resolution in dots per Inch (dpi)
\sa renderTo(), render(), QwtPainter::setRoundingAlignment()
*/
void QwtPlotRenderer::renderDocument( QwtPlot *plot,
const QString &fileName, const QString &format,
const QSizeF &sizeMM, int resolution )
{
if ( plot == NULL || sizeMM.isEmpty() || resolution <= 0 )
return;
QString title = plot->title().text();
if ( title.isEmpty() )
title = "Plot Document";
const double mmToInch = 1.0 / 25.4;
const QSizeF size = sizeMM * mmToInch * resolution;
const QRectF documentRect( 0.0, 0.0, size.width(), size.height() );
const QString fmt = format.toLower();
if ( fmt == "pdf" )
{
#ifndef QT_NO_PRINTER
QPrinter printer;
printer.setFullPage( true );
printer.setPaperSize( sizeMM, QPrinter::Millimeter );
printer.setDocName( title );
printer.setOutputFileName( fileName );
printer.setOutputFormat( QPrinter::PdfFormat );
printer.setResolution( resolution );
QPainter painter( &printer );
render( plot, &painter, documentRect );
#endif
}
else if ( fmt == "ps" )
{
#if QT_VERSION < 0x050000
#ifndef QT_NO_PRINTER
QPrinter printer;
printer.setFullPage( true );
printer.setPaperSize( sizeMM, QPrinter::Millimeter );
printer.setDocName( title );
printer.setOutputFileName( fileName );
printer.setOutputFormat( QPrinter::PostScriptFormat );
printer.setResolution( resolution );
QPainter painter( &printer );
render( plot, &painter, documentRect );
#endif
#endif
}
else if ( fmt == "svg" )
{
#ifndef QWT_NO_SVG
#ifdef QT_SVG_LIB
#if QT_VERSION >= 0x040500
QSvgGenerator generator;
generator.setTitle( title );
generator.setFileName( fileName );
generator.setResolution( resolution );
generator.setViewBox( documentRect );
QPainter painter( &generator );
render( plot, &painter, documentRect );
#endif
#endif
#endif
}
else
{
if ( QImageWriter::supportedImageFormats().indexOf(
format.toLatin1() ) >= 0 )
{
const QRect imageRect = documentRect.toRect();
const int dotsPerMeter = qRound( resolution * mmToInch * 1000.0 );
QImage image( imageRect.size(), QImage::Format_ARGB32 );
image.setDotsPerMeterX( dotsPerMeter );
image.setDotsPerMeterY( dotsPerMeter );
image.fill( QColor( Qt::white ).rgb() );
QPainter painter( &image );
render( plot, &painter, imageRect );
painter.end();
image.save( fileName, format.toLatin1() );
}
}
}
/*!
\brief Render the plot to a \c QPaintDevice
This function renders the contents of a QwtPlot instance to
\c QPaintDevice object. The target rectangle is derived from
its device metrics.
\param plot Plot to be rendered
\param paintDevice device to paint on, f.e a QImage
\sa renderDocument(), render(), QwtPainter::setRoundingAlignment()
*/
void QwtPlotRenderer::renderTo(
QwtPlot *plot, QPaintDevice &paintDevice ) const
{
int w = paintDevice.width();
int h = paintDevice.height();
QPainter p( &paintDevice );
render( plot, &p, QRectF( 0, 0, w, h ) );
}
/*!
\brief Render the plot to a QPrinter
This function renders the contents of a QwtPlot instance to
\c QPaintDevice object. The size is derived from the printer
metrics.
\param plot Plot to be rendered
\param printer Printer to paint on
\sa renderDocument(), render(), QwtPainter::setRoundingAlignment()
*/
#ifndef QT_NO_PRINTER
void QwtPlotRenderer::renderTo(
QwtPlot *plot, QPrinter &printer ) const
{
int w = printer.width();
int h = printer.height();
QRectF rect( 0, 0, w, h );
double aspect = rect.width() / rect.height();
if ( ( aspect < 1.0 ) )
rect.setHeight( aspect * rect.width() );
QPainter p( &printer );
render( plot, &p, rect );
}
#endif
#ifndef QWT_NO_SVG
#ifdef QT_SVG_LIB
#if QT_VERSION >= 0x040500
/*!
\brief Render the plot to a QSvgGenerator
If the generator has a view box, the plot will be rendered into it.
If it has no viewBox but a valid size the target coordinates
will be (0, 0, generator.width(), generator.height()). Otherwise
the target rectangle will be QRectF(0, 0, 800, 600);
\param plot Plot to be rendered
\param generator SVG generator
*/
void QwtPlotRenderer::renderTo(
QwtPlot *plot, QSvgGenerator &generator ) const
{
QRectF rect = generator.viewBoxF();
if ( rect.isEmpty() )
rect.setRect( 0, 0, generator.width(), generator.height() );
if ( rect.isEmpty() )
rect.setRect( 0, 0, 800, 600 ); // something
QPainter p( &generator );
render( plot, &p, rect );
}
#endif
#endif
#endif
/*!
Paint the contents of a QwtPlot instance into a given rectangle.
\param plot Plot to be rendered
\param painter Painter
\param plotRect Bounding rectangle
\sa renderDocument(), renderTo(), QwtPainter::setRoundingAlignment()
*/
void QwtPlotRenderer::render( QwtPlot *plot,
QPainter *painter, const QRectF &plotRect ) const
{
if ( painter == 0 || !painter->isActive() ||
!plotRect.isValid() || plot->size().isNull() )
return;
if ( !( d_data->discardFlags & DiscardBackground ) )
qwtRenderBackground( painter, plotRect, plot );
/*
The layout engine uses the same methods as they are used
by the Qt layout system. Therefore we need to calculate the
layout in screen coordinates and paint with a scaled painter.
*/
QTransform transform;
transform.scale(
double( painter->device()->logicalDpiX() ) / plot->logicalDpiX(),
double( painter->device()->logicalDpiY() ) / plot->logicalDpiY() );
QRectF layoutRect = transform.inverted().mapRect( plotRect );
QwtPlotLayout *layout = plot->plotLayout();
int baseLineDists[QwtPlot::axisCnt];
int canvasMargins[QwtPlot::axisCnt];
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
canvasMargins[ axisId ] = layout->canvasMargin( axisId );
if ( d_data->layoutFlags & FrameWithScales )
{
QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget )
{
baseLineDists[axisId] = scaleWidget->margin();
scaleWidget->setMargin( 0 );
}
if ( !plot->axisEnabled( axisId ) )
{
int left = 0;
int right = 0;
int top = 0;
int bottom = 0;
// When we have a scale the frame is painted on
// the position of the backbone - otherwise we
// need to introduce a margin around the canvas
switch( axisId )
{
case QwtPlot::yLeft:
layoutRect.adjust( 1, 0, 0, 0 );
break;
case QwtPlot::yRight:
layoutRect.adjust( 0, 0, -1, 0 );
break;
case QwtPlot::xTop:
layoutRect.adjust( 0, 1, 0, 0 );
break;
case QwtPlot::xBottom:
layoutRect.adjust( 0, 0, 0, -1 );
break;
default:
break;
}
layoutRect.adjust( left, top, right, bottom );
}
}
}
// Calculate the layout for the document.
QwtPlotLayout::Options layoutOptions =
QwtPlotLayout::IgnoreScrollbars | QwtPlotLayout::IgnoreFrames;
if ( d_data->discardFlags & DiscardLegend )
layoutOptions |= QwtPlotLayout::IgnoreLegend;
if ( d_data->discardFlags & DiscardTitle )
layoutOptions |= QwtPlotLayout::IgnoreTitle;
if ( d_data->discardFlags & DiscardFooter )
layoutOptions |= QwtPlotLayout::IgnoreFooter;
layout->activate( plot, layoutRect, layoutOptions );
// canvas
QwtScaleMap maps[QwtPlot::axisCnt];
buildCanvasMaps( plot, layout->canvasRect(), maps );
if ( updateCanvasMargins( plot, layout->canvasRect(), maps ) )
{
// recalculate maps and layout, when the margins
// have been changed
layout->activate( plot, layoutRect, layoutOptions );
buildCanvasMaps( plot, layout->canvasRect(), maps );
}
// now start painting
painter->save();
painter->setWorldTransform( transform, true );
renderCanvas( plot, painter, layout->canvasRect(), maps );
if ( !( d_data->discardFlags & DiscardTitle )
&& ( !plot->titleLabel()->text().isEmpty() ) )
{
renderTitle( plot, painter, layout->titleRect() );
}
if ( !( d_data->discardFlags & DiscardFooter )
&& ( !plot->footerLabel()->text().isEmpty() ) )
{
renderFooter( plot, painter, layout->footerRect() );
}
if ( !( d_data->discardFlags & DiscardLegend )
&& plot->legend() && !plot->legend()->isEmpty() )
{
renderLegend( plot, painter, layout->legendRect() );
}
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget )
{
int baseDist = scaleWidget->margin();
int startDist, endDist;
scaleWidget->getBorderDistHint( startDist, endDist );
renderScale( plot, painter, axisId, startDist, endDist,
baseDist, layout->scaleRect( axisId ) );
}
}
painter->restore();
// restore all setting to their original attributes.
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
if ( d_data->layoutFlags & FrameWithScales )
{
QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget )
scaleWidget->setMargin( baseLineDists[axisId] );
}
layout->setCanvasMargin( canvasMargins[axisId] );
}
layout->invalidate();
}
/*!
Render the title into a given rectangle.
\param plot Plot widget
\param painter Painter
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderTitle( const QwtPlot *plot,
QPainter *painter, const QRectF &rect ) const
{
painter->setFont( plot->titleLabel()->font() );
const QColor color = plot->titleLabel()->palette().color(
QPalette::Active, QPalette::Text );
painter->setPen( color );
plot->titleLabel()->text().draw( painter, rect );
}
/*!
Render the footer into a given rectangle.
\param plot Plot widget
\param painter Painter
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderFooter( const QwtPlot *plot,
QPainter *painter, const QRectF &rect ) const
{
painter->setFont( plot->footerLabel()->font() );
const QColor color = plot->footerLabel()->palette().color(
QPalette::Active, QPalette::Text );
painter->setPen( color );
plot->footerLabel()->text().draw( painter, rect );
}
/*!
Render the legend into a given rectangle.
\param plot Plot widget
\param painter Painter
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderLegend( const QwtPlot *plot,
QPainter *painter, const QRectF &rect ) const
{
if ( plot->legend() )
{
bool fillBackground = !( d_data->discardFlags & DiscardBackground );
plot->legend()->renderLegend( painter, rect, fillBackground );
}
}
/*!
\brief Paint a scale into a given rectangle.
Paint the scale into a given rectangle.
\param plot Plot widget
\param painter Painter
\param axisId Axis
\param startDist Start border distance
\param endDist End border distance
\param baseDist Base distance
\param rect Bounding rectangle
*/
void QwtPlotRenderer::renderScale( const QwtPlot *plot,
QPainter *painter,
int axisId, int startDist, int endDist, int baseDist,
const QRectF &rect ) const
{
if ( !plot->axisEnabled( axisId ) )
return;
const QwtScaleWidget *scaleWidget = plot->axisWidget( axisId );
if ( scaleWidget->isColorBarEnabled()
&& scaleWidget->colorBarWidth() > 0 )
{
scaleWidget->drawColorBar( painter, scaleWidget->colorBarRect( rect ) );
const int off = scaleWidget->colorBarWidth() + scaleWidget->spacing();
if ( scaleWidget->scaleDraw()->orientation() == Qt::Horizontal )
baseDist += off;
else
baseDist += off;
}
painter->save();
QwtScaleDraw::Alignment align;
double x, y, w;
switch ( axisId )
{
case QwtPlot::yLeft:
{
x = rect.right() - 1.0 - baseDist;
y = rect.y() + startDist;
w = rect.height() - startDist - endDist;
align = QwtScaleDraw::LeftScale;
break;
}
case QwtPlot::yRight:
{
x = rect.left() + baseDist;
y = rect.y() + startDist;
w = rect.height() - startDist - endDist;
align = QwtScaleDraw::RightScale;
break;
}
case QwtPlot::xTop:
{
x = rect.left() + startDist;
y = rect.bottom() - 1.0 - baseDist;
w = rect.width() - startDist - endDist;
align = QwtScaleDraw::TopScale;
break;
}
case QwtPlot::xBottom:
{
x = rect.left() + startDist;
y = rect.top() + baseDist;
w = rect.width() - startDist - endDist;
align = QwtScaleDraw::BottomScale;
break;
}
default:
return;
}
scaleWidget->drawTitle( painter, align, rect );
painter->setFont( scaleWidget->font() );
QwtScaleDraw *sd = const_cast<QwtScaleDraw *>( scaleWidget->scaleDraw() );
const QPointF sdPos = sd->pos();
const double sdLength = sd->length();
sd->move( x, y );
sd->setLength( w );
QPalette palette = scaleWidget->palette();
palette.setCurrentColorGroup( QPalette::Active );
sd->draw( painter, palette );
// reset previous values
sd->move( sdPos );
sd->setLength( sdLength );
painter->restore();
}
/*!
Render the canvas into a given rectangle.
\param plot Plot widget
\param painter Painter
\param map Maps mapping between plot and paint device coordinates
\param canvasRect Canvas rectangle
*/
void QwtPlotRenderer::renderCanvas( const QwtPlot *plot,
QPainter *painter, const QRectF &canvasRect,
const QwtScaleMap *map ) const
{
const QWidget *canvas = plot->canvas();
painter->save();
QPainterPath clipPath;
QRectF r = canvasRect.adjusted( 0.0, 0.0, -1.0, -1.0 );
if ( d_data->layoutFlags & FrameWithScales )
{
r.adjust( -1.0, -1.0, 1.0, 1.0 );
painter->setPen( QPen( Qt::black ) );
if ( !( d_data->discardFlags & DiscardCanvasBackground ) )
{
const QBrush bgBrush =
canvas->palette().brush( plot->backgroundRole() );
painter->setBrush( bgBrush );
}
QwtPainter::drawRect( painter, r );
}
else
{
if ( !( d_data->discardFlags & DiscardCanvasBackground ) )
{
qwtRenderBackground( painter, r, canvas );
if ( canvas->testAttribute( Qt::WA_StyledBackground ) )
{
// The clip region is calculated in integers
// To avoid too much rounding errors better
// calculate it in target device resolution
// TODO ...
int x1 = qCeil( canvasRect.left() );
int x2 = qFloor( canvasRect.right() );
int y1 = qCeil( canvasRect.top() );
int y2 = qFloor( canvasRect.bottom() );
const QRect r( x1, y1, x2 - x1 - 1, y2 - y1 - 1 );
( void ) QMetaObject::invokeMethod(
const_cast< QWidget *>( canvas ), "borderPath", Qt::DirectConnection,
Q_RETURN_ARG( QPainterPath, clipPath ), Q_ARG( QRect, r ) );
}
}
}
painter->restore();
painter->save();
if ( clipPath.isEmpty() )
painter->setClipRect( canvasRect );
else
painter->setClipPath( clipPath );
plot->drawItems( painter, canvasRect, map );
painter->restore();
}
/*!
Calculated the scale maps for rendering the canvas
\param plot Plot widget
\param canvasRect Target rectangle
\param maps Scale maps to be calculated
*/
void QwtPlotRenderer::buildCanvasMaps( const QwtPlot *plot,
const QRectF &canvasRect, QwtScaleMap maps[] ) const
{
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
maps[axisId].setTransformation(
plot->axisScaleEngine( axisId )->transformation() );
const QwtScaleDiv &scaleDiv = plot->axisScaleDiv( axisId );
maps[axisId].setScaleInterval(
scaleDiv.lowerBound(), scaleDiv.upperBound() );
double from, to;
if ( plot->axisEnabled( axisId ) )
{
const int sDist = plot->axisWidget( axisId )->startBorderDist();
const int eDist = plot->axisWidget( axisId )->endBorderDist();
const QRectF &scaleRect = plot->plotLayout()->scaleRect( axisId );
if ( axisId == QwtPlot::xTop || axisId == QwtPlot::xBottom )
{
from = scaleRect.left() + sDist;
to = scaleRect.right() - eDist;
}
else
{
from = scaleRect.bottom() - eDist;
to = scaleRect.top() + sDist;
}
}
else
{
int margin = plot->plotLayout()->canvasMargin( axisId );
if ( axisId == QwtPlot::yLeft || axisId == QwtPlot::yRight )
{
from = canvasRect.bottom() - margin;
to = canvasRect.top() + margin;
}
else
{
from = canvasRect.left() + margin;
to = canvasRect.right() - margin;
}
}
maps[axisId].setPaintInterval( from, to );
}
}
bool QwtPlotRenderer::updateCanvasMargins( QwtPlot *plot,
const QRectF &canvasRect, const QwtScaleMap maps[] ) const
{
double margins[QwtPlot::axisCnt];
plot->getCanvasMarginsHint( maps, canvasRect,
margins[QwtPlot::yLeft], margins[QwtPlot::xTop],
margins[QwtPlot::yRight], margins[QwtPlot::xBottom] );
bool marginsChanged = false;
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
if ( margins[axisId] >= 0.0 )
{
const int m = qCeil( margins[axisId] );
plot->plotLayout()->setCanvasMargin( m, axisId);
marginsChanged = true;
}
}
return marginsChanged;
}
/*!
\brief Execute a file dialog and render the plot to the selected file
The document will be rendered in 85dpi for a size 30x20cm
\param plot Plot widget
\param documentName Default document name
\note exportTo() is handy for testing, but usually an application
wants to configure the export individually
using renderDocument() or even more low level methods
of QwtPlotRenderer.
*/
bool QwtPlotRenderer::exportTo( QwtPlot *plot, const QString &documentName )
{
if ( plot == NULL )
return false;
QString fileName = documentName;
// What about translation
#ifndef QT_NO_FILEDIALOG
const QList<QByteArray> imageFormats =
QImageWriter::supportedImageFormats();
QStringList filter;
#ifndef QT_NO_PRINTER
filter += QString( "PDF " ) + tr( "Documents" ) + " (*.pdf)";
#endif
#ifndef QWT_NO_SVG
filter += QString( "SVG " ) + tr( "Documents" ) + " (*.svg)";
#endif
#ifndef QT_NO_PRINTER
filter += QString( "Postscript " ) + tr( "Documents" ) + " (*.ps)";
#endif
if ( imageFormats.size() > 0 )
{
QString imageFilter( tr( "Images" ) );
imageFilter += " (";
for ( int i = 0; i < imageFormats.size(); i++ )
{
if ( i > 0 )
imageFilter += " ";
imageFilter += "*.";
imageFilter += imageFormats[i];
}
imageFilter += ")";
filter += imageFilter;
}
fileName = QFileDialog::getSaveFileName(
NULL, tr( "Export File Name" ), fileName,
filter.join( ";;" ), NULL, QFileDialog::DontConfirmOverwrite );
#endif
if ( fileName.isEmpty() )
return false;
renderDocument( plot, fileName, QSizeF( 300, 200 ), 85 );
return true;
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------
// Implementation of the TPC tracker
//
// Origin: Marian Ivanov Marian.Ivanov@cern.ch
//
// AliTPC parallel tracker
//
// The track fitting is based on Kalman filtering approach
// The track finding steps:
// 1. Seeding - with and without vertex constraint
// - seeding with vertex constain done at first n^2 proble
// - seeding without vertex constraint n^3 problem
// 2. Tracking - follow prolongation road - find cluster - update kalman track
// The seeding and tracking is repeated several times, in different seeding region.
// This approach enables to find the track which cannot be seeded in some region of TPC
// This can happen because of low momenta (track do not reach outer radius), or track is currently in the ded region between sectors, or the track is for the moment overlapped with other track (seed quality is poor) ...
// With this approach we reach almost 100 % efficiency also for high occupancy events.
// (If the seeding efficiency in a region is about 90 % than with logical or of several
// regions we will reach 100% (in theory - supposing independence)
// Repeating several seeding - tracking procedures some of the tracks can be find
// several times.
// The procedures to remove multi find tacks are impremented:
// RemoveUsed2 - fast procedure n problem -
// Algorithm - Sorting tracks according quality
// remove tracks with some shared fraction
// Sharing in respect to all tacks
// Signing clusters in gold region
// FindSplitted - slower algorithm n^2
// Sort the tracks according quality
// Loop over pair of tracks
// If overlap with other track bigger than threshold - remove track
//
// FindCurling - Finds the pair of tracks which are curling
// - About 10% of tracks can be find with this procedure
// The combinatorial background is too big to be used in High
// multiplicity environment
// - n^2 problem - Slow procedure - currently it is disabled because of
// low efficiency
//
// The number of splitted tracks can be reduced disabling the sharing of the cluster.
// tpcRecoParam-> SetClusterSharing(kFALSE);
// IT IS HIGHLY non recomended to use it in high flux enviroonment
// Even using this switch some tracks can be found more than once
// (because of multiple seeding and low quality tracks which will not cross full chamber)
//
//
// The tracker itself can be debugged - the information about tracks can be stored in several // phases of the reconstruction
// To enable storage of the TPC tracks in the ESD friend track
// use AliTPCReconstructor::SetStreamLevel(n);
//
// The debug level - different procedure produce tree for numerical debugging of code and data (see comments foEStreamFlags in AliTPCtracker.h )
//
//
// Adding systematic errors to the covariance:
//
// The systematic errors due to the misalignment and miscalibration are added to the covariance matrix
// of the tracks (not to the clusters as they are dependent):
// The parameters form AliTPCRecoParam are used AliTPCRecoParam::GetSystematicError
// The systematic errors are expressed there in RMS - position (cm), angle (rad), curvature (1/GeV)
// The default values are 0.
//
// The systematic errors are added to the covariance matrix in following places:
//
// 1. During fisrt itteration - AliTPCtracker::FillESD
// 2. Second iteration -
// 2.a ITS->TPC - AliTPCtracker::ReadSeeds
// 2.b TPC->TRD - AliTPCtracker::PropagateBack
// 3. Third iteration -
// 3.a TRD->TPC - AliTPCtracker::ReadSeeds
// 3.b TPC->ITS - AliTPCtracker::RefitInward
//
/* $Id$ */
#include "Riostream.h"
#include <TClonesArray.h>
#include <TFile.h>
#include <TObjArray.h>
#include <TTree.h>
#include <TMatrixD.h>
#include <TGraphErrors.h>
#include <TTimeStamp.h>
#include "AliLog.h"
#include "AliComplexCluster.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"
#include "AliESDVertex.h"
#include "AliKink.h"
#include "AliV0.h"
#include "AliHelix.h"
#include "AliRunLoader.h"
#include "AliTPCClustersRow.h"
#include "AliTPCParam.h"
#include "AliTPCReconstructor.h"
#include "AliTPCpolyTrack.h"
#include "AliTPCreco.h"
#include "AliTPCseed.h"
#include "AliTPCtrackerSector.h"
#include "AliTPCtracker.h"
#include "TStopwatch.h"
#include "AliTPCReconstructor.h"
#include "AliAlignObj.h"
#include "AliTrackPointArray.h"
#include "TRandom.h"
#include "AliTPCcalibDB.h"
#include "AliTPCcalibDButil.h"
#include "AliTPCTransform.h"
#include "AliTPCClusterParam.h"
#include "AliTPCdEdxInfo.h"
#include "AliDCSSensorArray.h"
#include "AliDCSSensor.h"
#include "AliDAQ.h"
#include "AliCosmicTracker.h"
#include "AliTPCROC.h"
#include "AliMathBase.h"
//
#include "AliESDfriendTrack.h"
using std::cout;
using std::cerr;
using std::endl;
ClassImp(AliTPCtracker)
//__________________________________________________________________
AliTPCtracker::AliTPCtracker()
:AliTracker(),
fkNIS(0),
fInnerSec(0),
fkNOS(0),
fOuterSec(0),
fN(0),
fSectors(0),
fInput(0),
fOutput(0),
fSeedTree(0),
fTreeDebug(0),
fEvent(0),
fEventHLT(0),
fDebug(0),
fNewIO(kFALSE),
fNtracks(0),
fSeeds(0),
fIteration(0),
fkParam(0),
fDebugStreamer(0),
fUseHLTClusters(4),
fClExtraRoadY(0.),
fClExtraRoadZ(0.),
fExtraClErrYZ2(0),
fExtraClErrY2(0),
fExtraClErrZ2(0),
fPrimaryDCAZCut(-1),
fPrimaryDCAYCut(-1),
fDisableSecondaries(kFALSE),
fCrossTalkSignalArray(0),
fClPointersPool(0),
fClPointersPoolPtr(0),
fClPointersPoolSize(0),
fSeedsPool(0),
fHelixPool(0),
fETPPool(0),
fFreeSeedsID(500),
fNFreeSeeds(0),
fLastSeedID(-1),
fAccountDistortions(0)
{
//
// default constructor
//
for (Int_t irow=0; irow<200; irow++){
fXRow[irow]=0;
fYMax[irow]=0;
fPadLength[irow]=0;
}
}
//_____________________________________________________________________
Int_t AliTPCtracker::UpdateTrack(AliTPCseed * track, Int_t accept){
//
//update track information using current cluster - track->fCurrentCluster
AliTPCclusterMI* c =track->GetCurrentCluster();
if (accept > 0) //sign not accepted clusters
track->SetCurrentClusterIndex1(track->GetCurrentClusterIndex1() | 0x8000);
else // unsign accpeted clusters
track->SetCurrentClusterIndex1(track->GetCurrentClusterIndex1() & 0xffff7fff);
UInt_t i = track->GetCurrentClusterIndex1();
Int_t sec=(i&0xff000000)>>24;
//Int_t row = (i&0x00ff0000)>>16;
track->SetRow((i&0x00ff0000)>>16);
track->SetSector(sec);
// Int_t index = i&0xFFFF;
int row = track->GetRow();
if (sec>=fkParam->GetNInnerSector()) {
row += fkParam->GetNRowLow();
track->SetRow(row);
}
track->SetClusterIndex2(row, i);
//track->fFirstPoint = row;
//if ( track->fLastPoint<row) track->fLastPoint =row;
// if (track->fRow<0 || track->fRow>=kMaxRow) {
// printf("problem\n");
//}
if (track->GetFirstPoint()>row)
track->SetFirstPoint(row);
if (track->GetLastPoint()<row)
track->SetLastPoint(row);
//RS track->SetClusterPointer(row,c);
//
Double_t angle2 = track->GetSnp()*track->GetSnp();
//
//SET NEW Track Point
//
if (angle2<1) //PH sometimes angle2 is very big. To be investigated...
{
angle2 = TMath::Sqrt(angle2/(1-angle2));
AliTPCTrackerPoints::Point &point =*((AliTPCTrackerPoints::Point*)track->GetTrackPoint(row));
//
point.SetSigmaY(c->GetSigmaY2()/track->GetCurrentSigmaY2());
point.SetSigmaZ(c->GetSigmaZ2()/track->GetCurrentSigmaZ2());
point.SetErrY(sqrt(track->GetErrorY2()));
point.SetErrZ(sqrt(track->GetErrorZ2()));
//
point.SetX(track->GetX());
point.SetY(track->GetY());
point.SetZ(track->GetZ());
point.SetAngleY(angle2);
point.SetAngleZ(track->GetTgl());
if (track->IsShared(row)){
track->SetErrorY2(track->GetErrorY2()*4);
track->SetErrorZ2(track->GetErrorZ2()*4);
}
}
Double_t chi2 = track->GetPredictedChi2(track->GetCurrentCluster());
//
// track->SetErrorY2(track->GetErrorY2()*1.3);
// track->SetErrorY2(track->GetErrorY2()+0.01);
// track->SetErrorZ2(track->GetErrorZ2()*1.3);
// track->SetErrorZ2(track->GetErrorZ2()+0.005);
//}
if (accept>0) return 0;
if (track->GetNumberOfClusters()%20==0){
// if (track->fHelixIn){
// TClonesArray & larr = *(track->fHelixIn);
// Int_t ihelix = larr.GetEntriesFast();
// new(larr[ihelix]) AliHelix(*track) ;
//}
}
if (AliTPCReconstructor::StreamLevel()&kStreamUpdateTrack) {
Int_t event = (fEvent==NULL)? 0: fEvent->GetEventNumberInFile();
AliExternalTrackParam param(*track);
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"UpdateTrack"<<
"cl.="<<c<<
"event="<<event<<
"track.="<<¶m<<
"\n";
}
track->SetNoCluster(0);
return track->Update(c,chi2,i);
}
Int_t AliTPCtracker::AcceptCluster(AliTPCseed * seed, AliTPCclusterMI * cluster)
{
//
// decide according desired precision to accept given
// cluster for tracking
Double_t yt = seed->GetY(),zt = seed->GetZ();
// RS: use propagation only if the seed in far from the cluster
const double kTolerance = 10e-4; // assume track is at cluster X if X-distance below this
if (TMath::Abs(seed->GetX()-cluster->GetX())>kTolerance) seed->GetProlongation(cluster->GetX(),yt,zt);
Double_t sy2=ErrY2(seed,cluster);
Double_t sz2=ErrZ2(seed,cluster);
Double_t sdistancey2 = sy2+seed->GetSigmaY2();
Double_t sdistancez2 = sz2+seed->GetSigmaZ2();
Double_t dy=seed->GetCurrentCluster()->GetY()-yt;
Double_t dz=seed->GetCurrentCluster()->GetZ()-zt;
Double_t rdistancey2 = (seed->GetCurrentCluster()->GetY()-yt)*
(seed->GetCurrentCluster()->GetY()-yt)/sdistancey2;
Double_t rdistancez2 = (seed->GetCurrentCluster()->GetZ()-zt)*
(seed->GetCurrentCluster()->GetZ()-zt)/sdistancez2;
Double_t rdistance2 = rdistancey2+rdistancez2;
//Int_t accept =0;
if (AliTPCReconstructor::StreamLevel()>2 && ( (fIteration>0)|| (seed->GetNumberOfClusters()>20))) {
// if (AliTPCReconstructor::StreamLevel()>2 && seed->GetNumberOfClusters()>20) {
Float_t rmsy2 = seed->GetCurrentSigmaY2();
Float_t rmsz2 = seed->GetCurrentSigmaZ2();
Float_t rmsy2p30 = seed->GetCMeanSigmaY2p30();
Float_t rmsz2p30 = seed->GetCMeanSigmaZ2p30();
Float_t rmsy2p30R = seed->GetCMeanSigmaY2p30R();
Float_t rmsz2p30R = seed->GetCMeanSigmaZ2p30R();
AliExternalTrackParam param(*seed);
static TVectorD gcl(3),gtr(3);
Float_t gclf[3];
param.GetXYZ(gcl.GetMatrixArray());
cluster->GetGlobalXYZ(gclf);
gcl[0]=gclf[0]; gcl[1]=gclf[1]; gcl[2]=gclf[2];
Int_t nclSeed=seed->GetNumberOfClusters();
int seedType = seed->GetSeedType();
if (AliTPCReconstructor::StreamLevel()&kStreamErrParam) { // flag:stream in debug mode cluster and track extrapolation at given row together with error nad shape estimate
Int_t eventNr = fEvent->GetEventNumberInFile();
(*fDebugStreamer)<<"ErrParam"<<
"iter="<<fIteration<<
"eventNr="<<eventNr<<
"Cl.="<<cluster<<
"nclSeed="<<nclSeed<<
"seedType="<<seedType<<
"T.="<<¶m<<
"dy="<<dy<<
"dz="<<dz<<
"yt="<<yt<<
"zt="<<zt<<
"gcl.="<<&gcl<<
"gtr.="<<>r<<
"erry2="<<sy2<<
"errz2="<<sz2<<
"rmsy2="<<rmsy2<<
"rmsz2="<<rmsz2<<
"rmsy2p30="<<rmsy2p30<<
"rmsz2p30="<<rmsz2p30<<
"rmsy2p30R="<<rmsy2p30R<<
"rmsz2p30R="<<rmsz2p30R<<
// normalize distance -
"rdisty="<<rdistancey2<<
"rdistz="<<rdistancez2<<
"rdist="<<rdistance2<< //
"\n";
}
}
//return 0; // temporary
if (rdistance2>32) return 3;
if ((rdistancey2>9. || rdistancez2>9.) && cluster->GetType()==0)
return 2; //suspisiouce - will be changed
if ((rdistancey2>6.25 || rdistancez2>6.25) && cluster->GetType()>0)
// strict cut on overlaped cluster
return 2; //suspisiouce - will be changed
if ( (rdistancey2>1. || rdistancez2>6.25 )
&& cluster->GetType()<0){
seed->SetNFoundable(seed->GetNFoundable()-1);
return 2;
}
if (fUseHLTClusters == 3 || fUseHLTClusters == 4) {
if (fIteration==2){
if(!AliTPCReconstructor::GetRecoParam()->GetUseHLTOnePadCluster()) {
if (TMath::Abs(cluster->GetSigmaY2()) < kAlmost0)
return 2;
}
}
}
return 0;
}
//_____________________________________________________________________________
AliTPCtracker::AliTPCtracker(const AliTPCParam *par):
AliTracker(),
fkNIS(par->GetNInnerSector()/2),
fInnerSec(0),
fkNOS(par->GetNOuterSector()/2),
fOuterSec(0),
fN(0),
fSectors(0),
fInput(0),
fOutput(0),
fSeedTree(0),
fTreeDebug(0),
fEvent(0),
fEventHLT(0),
fDebug(0),
fNewIO(0),
fNtracks(0),
fSeeds(0),
fIteration(0),
fkParam(0),
fDebugStreamer(0),
fUseHLTClusters(4),
fClExtraRoadY(0.),
fClExtraRoadZ(0.),
fExtraClErrYZ2(0),
fExtraClErrY2(0),
fExtraClErrZ2(0),
fPrimaryDCAZCut(-1),
fPrimaryDCAYCut(-1),
fDisableSecondaries(kFALSE),
fCrossTalkSignalArray(0),
fClPointersPool(0),
fClPointersPoolPtr(0),
fClPointersPoolSize(0),
fSeedsPool(0),
fHelixPool(0),
fETPPool(0),
fFreeSeedsID(500),
fNFreeSeeds(0),
fLastSeedID(-1),
fAccountDistortions(0)
{
//---------------------------------------------------------------------
// The main TPC tracker constructor
//---------------------------------------------------------------------
fInnerSec=new AliTPCtrackerSector[fkNIS];
fOuterSec=new AliTPCtrackerSector[fkNOS];
Int_t i;
for (i=0; i<fkNIS; i++) fInnerSec[i].Setup(par,0);
for (i=0; i<fkNOS; i++) fOuterSec[i].Setup(par,1);
fkParam = par;
Int_t nrowlow = par->GetNRowLow();
Int_t nrowup = par->GetNRowUp();
for (i=0;i<nrowlow;i++){
fXRow[i] = par->GetPadRowRadiiLow(i);
fPadLength[i]= par->GetPadPitchLength(0,i);
fYMax[i] = fXRow[i]*TMath::Tan(0.5*par->GetInnerAngle());
}
for (i=0;i<nrowup;i++){
fXRow[i+nrowlow] = par->GetPadRowRadiiUp(i);
fPadLength[i+nrowlow] = par->GetPadPitchLength(60,i);
fYMax[i+nrowlow] = fXRow[i+nrowlow]*TMath::Tan(0.5*par->GetOuterAngle());
}
if (AliTPCReconstructor::StreamLevel()>0) {
fDebugStreamer = new TTreeSRedirector("TPCdebug.root","recreate");
AliTPCReconstructor::SetDebugStreamer(fDebugStreamer);
}
//
fSeedsPool = new TClonesArray("AliTPCseed",1000);
fClPointersPool = new AliTPCclusterMI*[kMaxFriendTracks*kMaxRow];
memset(fClPointersPool,0,kMaxFriendTracks*kMaxRow*sizeof(AliTPCclusterMI*));
fClPointersPoolPtr = fClPointersPool;
fClPointersPoolSize = kMaxFriendTracks;
//
// crosstalk array and matrix initialization
Int_t nROCs = 72;
Int_t nTimeBinsAll = AliTPCcalibDB::Instance()->GetMaxTimeBinAllPads() ;
Int_t nWireSegments = 11;
fCrossTalkSignalArray = new TObjArray(nROCs*4); //
fCrossTalkSignalArray->SetOwner(kTRUE);
for (Int_t isector=0; isector<4*nROCs; isector++){
TMatrixD * crossTalkSignal = new TMatrixD(nWireSegments,nTimeBinsAll);
for (Int_t imatrix = 0; imatrix<11; imatrix++)
for (Int_t jmatrix = 0; jmatrix<nTimeBinsAll; jmatrix++){
(*crossTalkSignal)[imatrix][jmatrix]=0.;
}
fCrossTalkSignalArray->AddAt(crossTalkSignal,isector);
}
}
//________________________________________________________________________
AliTPCtracker::AliTPCtracker(const AliTPCtracker &t):
AliTracker(t),
fkNIS(t.fkNIS),
fInnerSec(0),
fkNOS(t.fkNOS),
fOuterSec(0),
fN(0),
fSectors(0),
fInput(0),
fOutput(0),
fSeedTree(0),
fTreeDebug(0),
fEvent(0),
fEventHLT(0),
fDebug(0),
fNewIO(kFALSE),
fNtracks(0),
fSeeds(0),
fIteration(0),
fkParam(0),
fDebugStreamer(0),
fUseHLTClusters(4),
fClExtraRoadY(0.),
fClExtraRoadZ(0.),
fExtraClErrYZ2(0),
fExtraClErrY2(0),
fExtraClErrZ2(0),
fPrimaryDCAZCut(-1),
fPrimaryDCAYCut(-1),
fDisableSecondaries(kFALSE),
fCrossTalkSignalArray(0),
fClPointersPool(0),
fClPointersPoolPtr(0),
fClPointersPoolSize(0),
fSeedsPool(0),
fHelixPool(0),
fETPPool(0),
fFreeSeedsID(500),
fNFreeSeeds(0),
fAccountDistortions(0)
{
//------------------------------------
// dummy copy constructor
//------------------------------------------------------------------
fOutput=t.fOutput;
for (Int_t irow=0; irow<200; irow++){
fXRow[irow]=0;
fYMax[irow]=0;
fPadLength[irow]=0;
}
}
AliTPCtracker & AliTPCtracker::operator=(const AliTPCtracker& /*r*/)
{
//------------------------------
// dummy
//--------------------------------------------------------------
return *this;
}
//_____________________________________________________________________________
AliTPCtracker::~AliTPCtracker() {
//------------------------------------------------------------------
// TPC tracker destructor
//------------------------------------------------------------------
delete[] fInnerSec;
delete[] fOuterSec;
if (fSeeds) {
fSeeds->Clear();
delete fSeeds;
}
delete[] fClPointersPool;
if (fCrossTalkSignalArray) delete fCrossTalkSignalArray;
if (fDebugStreamer) delete fDebugStreamer;
if (fSeedsPool) {
for (int isd=fSeedsPool->GetEntriesFast();isd--;) {
AliTPCseed* seed = (AliTPCseed*)fSeedsPool->At(isd);
if (seed) {
seed->SetClusterOwner(kFALSE);
seed->SetClustersArrayTMP(0);
}
}
delete fSeedsPool;
}
if (fHelixPool) fHelixPool->Delete();
delete fHelixPool;
if (fETPPool) fETPPool->Delete();
delete fETPPool;
}
void AliTPCtracker::FillESD(const TObjArray* arr)
{
//
//
//fill esds using updated tracks
if (!fEvent) return;
AliESDtrack iotrack;
// write tracks to the event
// store index of the track
Int_t nseed=arr->GetEntriesFast();
//FindKinks(arr,fEvent);
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
pt->UpdatePoints();
AddCovariance(pt);
if (AliTPCReconstructor::StreamLevel()&kStreamFillESD) {
(*fDebugStreamer)<<"FillESD"<< // flag: stream track information in FillESD function (after track Iteration 0)
"Tr0.="<<pt<<
"\n";
}
// pt->PropagateTo(fkParam->GetInnerRadiusLow());
if (pt->GetKinkIndex(0)<=0){ //don't propagate daughter tracks
pt->PropagateTo(fkParam->GetInnerRadiusLow());
}
if (( pt->GetPoints()[2]- pt->GetPoints()[0])>5 && pt->GetPoints()[3]>0.8){
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
// iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
MakeESDBitmaps(pt, &iotrack);
fEvent->AddTrack(&iotrack);
continue;
}
if ( (pt->GetNumberOfClusters()>70)&& (Float_t(pt->GetNumberOfClusters())/Float_t(pt->GetNFoundable()))>0.55) {
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
//iotrack.SetTPCindex(i);
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
// iotrack.SetTPCpid(pt->fTPCr);
fEvent->AddTrack(&iotrack);
continue;
}
//
// short tracks - maybe decays
//RS Seed don't keep their cluster pointers, cache cluster usage stat. for fast evaluation
// FillSeedClusterStatCache(pt); // RS use this slow method only if info on shared statistics is needed
if ( (pt->GetNumberOfClusters()>30) && (Float_t(pt->GetNumberOfClusters())/Float_t(pt->GetNFoundable()))>0.70) {
Int_t found,foundable; //,shared;
//GetCachedSeedClusterStatistic(0,60,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//pt->GetClusterStatistic(0,60,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(0,60,found, foundable);
if ( (found>20) && (pt->GetNShared()/float(pt->GetNumberOfClusters())<0.2)){
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
//iotrack.SetTPCindex(i);
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
//iotrack.SetTPCpid(pt->fTPCr);
fEvent->AddTrack(&iotrack);
continue;
}
}
if ( (pt->GetNumberOfClusters()>20) && (Float_t(pt->GetNumberOfClusters())/Float_t(pt->GetNFoundable()))>0.8) {
Int_t found,foundable;//,shared;
//RS GetCachedSeedClusterStatistic(0,60,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//pt->GetClusterStatistic(0,60,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(0,60,found,foundable);
if (found<20) continue;
if (pt->GetNShared()/float(pt->GetNumberOfClusters())>0.2) continue;
//
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
//iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
fEvent->AddTrack(&iotrack);
continue;
}
// short tracks - secondaties
//
if ( (pt->GetNumberOfClusters()>30) ) {
Int_t found,foundable;//,shared;
//GetCachedSeedClusterStatistic(128,158,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//pt->GetClusterStatistic(128,158,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(128,158,found, foundable);
if ( (found>20) && (pt->GetNShared()/float(pt->GetNumberOfClusters())<0.2) &&float(found)/float(foundable)>0.8){
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
//iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
fEvent->AddTrack(&iotrack);
continue;
}
}
if ( (pt->GetNumberOfClusters()>15)) {
Int_t found,foundable,shared;
//GetCachedSeedClusterStatistic(138,158,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS pt->GetClusterStatistic(138,158,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(138,158,found, foundable);
if (found<15) continue;
if (foundable<=0) continue;
if (pt->GetNShared()/float(pt->GetNumberOfClusters())>0.2) continue;
if (float(found)/float(foundable)<0.8) continue;
//
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
// iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
fEvent->AddTrack(&iotrack);
continue;
}
}
// >> account for suppressed tracks in the kink indices (RS)
int nESDtracks = fEvent->GetNumberOfTracks();
for (int it=nESDtracks;it--;) {
AliESDtrack* esdTr = fEvent->GetTrack(it);
if (!esdTr || !esdTr->GetKinkIndex(0)) continue;
for (int ik=0;ik<3;ik++) {
int knkId=0;
if (!(knkId=esdTr->GetKinkIndex(ik))) break; // no more kinks for this track
AliESDkink* kink = fEvent->GetKink(TMath::Abs(knkId)-1);
if (!kink) {
AliError(Form("ESDTrack%d refers to non-existing kink %d",it,TMath::Abs(knkId)-1));
continue;
}
kink->SetIndex(it, knkId<0 ? 0:1); // update track index of the kink: mother at 0, daughter at 1
}
}
// << account for suppressed tracks in the kink indices (RS)
AliInfo(Form("Number of filled ESDs-\t%d\n",fEvent->GetNumberOfTracks()));
}
Double_t AliTPCtracker::ErrY2(AliTPCseed* seed, const AliTPCclusterMI * cl){
//
//
// Use calibrated cluster error from OCDB
//
AliTPCClusterParam * clparam = AliTPCcalibDB::Instance()->GetClusterParam();
//
Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
Int_t ctype = cl->GetType();
Int_t type = (cl->GetRow()<63) ? 0: (cl->GetRow()>126) ? 1:2;
Double_t angle = seed->GetSnp()*seed->GetSnp();
angle = TMath::Sqrt(TMath::Abs(angle/(1.-angle)));
Double_t erry2 = clparam->GetError0Par(0,type, z,angle);
if (ctype<0) {
erry2+=0.5; // edge cluster
}
erry2*=erry2;
Double_t addErr=0;
const Double_t *errInner = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInner();
const Double_t *errInnerDeep = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInnerDeepY();
double dr = TMath::Abs(cl->GetX()-85.);
addErr=errInner[0]*TMath::Exp(-dr/errInner[1]);
if (errInnerDeep[0]>0) addErr += errInnerDeep[0]*TMath::Exp(-dr/errInnerDeep[1]);
erry2+=addErr*addErr;
const Double_t *errCluster = (AliTPCReconstructor::GetSystematicErrorCluster()) ? AliTPCReconstructor::GetSystematicErrorCluster() : AliTPCReconstructor::GetRecoParam()->GetSystematicErrorCluster();
erry2+=errCluster[0]*errCluster[0];
seed->SetErrorY2(erry2);
//
return erry2;
//calculate look-up table at the beginning
// static Bool_t ginit = kFALSE;
// static Float_t gnoise1,gnoise2,gnoise3;
// static Float_t ggg1[10000];
// static Float_t ggg2[10000];
// static Float_t ggg3[10000];
// static Float_t glandau1[10000];
// static Float_t glandau2[10000];
// static Float_t glandau3[10000];
// //
// static Float_t gcor01[500];
// static Float_t gcor02[500];
// static Float_t gcorp[500];
// //
// //
// if (ginit==kFALSE){
// for (Int_t i=1;i<500;i++){
// Float_t rsigma = float(i)/100.;
// gcor02[i] = TMath::Max(0.78 +TMath::Exp(7.4*(rsigma-1.2)),0.6);
// gcor01[i] = TMath::Max(0.72 +TMath::Exp(3.36*(rsigma-1.2)),0.6);
// gcorp[i] = TMath::Max(TMath::Power((rsigma+0.5),1.5),1.2);
// }
// //
// for (Int_t i=3;i<10000;i++){
// //
// //
// // inner sector
// Float_t amp = float(i);
// Float_t padlength =0.75;
// gnoise1 = 0.0004/padlength;
// Float_t nel = 0.268*amp;
// Float_t nprim = 0.155*amp;
// ggg1[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.001*nel/(padlength*padlength))/nel;
// glandau1[i] = (2.+0.12*nprim)*0.5* (2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau1[i]>1) glandau1[i]=1;
// glandau1[i]*=padlength*padlength/12.;
// //
// // outer short
// padlength =1.;
// gnoise2 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg2[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau2[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau2[i]>1) glandau2[i]=1;
// glandau2[i]*=padlength*padlength/12.;
// //
// //
// // outer long
// padlength =1.5;
// gnoise3 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg3[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau3[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau3[i]>1) glandau3[i]=1;
// glandau3[i]*=padlength*padlength/12.;
// //
// }
// ginit = kTRUE;
// }
// //
// //
// //
// Int_t amp = int(TMath::Abs(cl->GetQ()));
// if (amp>9999) {
// seed->SetErrorY2(1.);
// return 1.;
// }
// Float_t snoise2;
// Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
// Int_t ctype = cl->GetType();
// Float_t padlength= GetPadPitchLength(seed->GetRow());
// Double_t angle2 = seed->GetSnp()*seed->GetSnp();
// angle2 = angle2/(1-angle2);
// //
// //cluster "quality"
// Int_t rsigmay = int(100.*cl->GetSigmaY2()/(seed->GetCurrentSigmaY2()));
// Float_t res;
// //
// if (fSectors==fInnerSec){
// snoise2 = gnoise1;
// res = ggg1[amp]*z+glandau1[amp]*angle2;
// if (ctype==0) res *= gcor01[rsigmay];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmay];
// }
// }
// else {
// if (padlength<1.1){
// snoise2 = gnoise2;
// res = ggg2[amp]*z+glandau2[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmay];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmay];
// }
// }
// else{
// snoise2 = gnoise3;
// res = ggg3[amp]*z+glandau3[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmay];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmay];
// }
// }
// }
// if (ctype<0){
// res+=0.005;
// res*=2.4; // overestimate error 2 times
// }
// res+= snoise2;
// if (res<2*snoise2)
// res = 2*snoise2;
// seed->SetErrorY2(res);
// return res;
}
Double_t AliTPCtracker::ErrZ2(AliTPCseed* seed, const AliTPCclusterMI * cl){
//
//
// Use calibrated cluster error from OCDB
//
AliTPCClusterParam * clparam = AliTPCcalibDB::Instance()->GetClusterParam();
//
Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
Int_t ctype = cl->GetType();
Int_t type = (cl->GetRow()<63) ? 0: (cl->GetRow()>126) ? 1:2;
//
Double_t angle2 = seed->GetSnp()*seed->GetSnp();
angle2 = seed->GetTgl()*seed->GetTgl()*(1+angle2/(1-angle2));
Double_t angle = TMath::Sqrt(TMath::Abs(angle2));
Double_t errz2 = clparam->GetError0Par(1,type, z,angle);
if (ctype<0) {
errz2+=0.5; // edge cluster
}
errz2*=errz2;
Double_t addErr=0;
const Double_t *errInner = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInner();
const Double_t *errInnerDeepZ = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInnerDeepZ();
double dr = TMath::Abs(cl->GetX()-85.);
addErr=errInner[0]*TMath::Exp(-dr/errInner[1]);
if (errInnerDeepZ[0]>0) addErr += errInnerDeepZ[0]*TMath::Exp(-dr/errInnerDeepZ[1]);
errz2+=addErr*addErr;
const Double_t *errCluster = (AliTPCReconstructor::GetSystematicErrorCluster()) ? AliTPCReconstructor::GetSystematicErrorCluster() : AliTPCReconstructor::GetRecoParam()->GetSystematicErrorCluster();
errz2+=errCluster[1]*errCluster[1];
seed->SetErrorZ2(errz2);
//
return errz2;
// //seed->SetErrorY2(0.1);
// //return 0.1;
// //calculate look-up table at the beginning
// static Bool_t ginit = kFALSE;
// static Float_t gnoise1,gnoise2,gnoise3;
// static Float_t ggg1[10000];
// static Float_t ggg2[10000];
// static Float_t ggg3[10000];
// static Float_t glandau1[10000];
// static Float_t glandau2[10000];
// static Float_t glandau3[10000];
// //
// static Float_t gcor01[1000];
// static Float_t gcor02[1000];
// static Float_t gcorp[1000];
// //
// //
// if (ginit==kFALSE){
// for (Int_t i=1;i<1000;i++){
// Float_t rsigma = float(i)/100.;
// gcor02[i] = TMath::Max(0.81 +TMath::Exp(6.8*(rsigma-1.2)),0.6);
// gcor01[i] = TMath::Max(0.72 +TMath::Exp(2.04*(rsigma-1.2)),0.6);
// gcorp[i] = TMath::Max(TMath::Power((rsigma+0.5),1.5),1.2);
// }
// //
// for (Int_t i=3;i<10000;i++){
// //
// //
// // inner sector
// Float_t amp = float(i);
// Float_t padlength =0.75;
// gnoise1 = 0.0004/padlength;
// Float_t nel = 0.268*amp;
// Float_t nprim = 0.155*amp;
// ggg1[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.001*nel/(padlength*padlength))/nel;
// glandau1[i] = (2.+0.12*nprim)*0.5* (2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau1[i]>1) glandau1[i]=1;
// glandau1[i]*=padlength*padlength/12.;
// //
// // outer short
// padlength =1.;
// gnoise2 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg2[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau2[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau2[i]>1) glandau2[i]=1;
// glandau2[i]*=padlength*padlength/12.;
// //
// //
// // outer long
// padlength =1.5;
// gnoise3 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg3[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau3[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau3[i]>1) glandau3[i]=1;
// glandau3[i]*=padlength*padlength/12.;
// //
// }
// ginit = kTRUE;
// }
// //
// //
// //
// Int_t amp = int(TMath::Abs(cl->GetQ()));
// if (amp>9999) {
// seed->SetErrorY2(1.);
// return 1.;
// }
// Float_t snoise2;
// Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
// Int_t ctype = cl->GetType();
// Float_t padlength= GetPadPitchLength(seed->GetRow());
// //
// Double_t angle2 = seed->GetSnp()*seed->GetSnp();
// // if (angle2<0.6) angle2 = 0.6;
// angle2 = seed->GetTgl()*seed->GetTgl()*(1+angle2/(1-angle2));
// //
// //cluster "quality"
// Int_t rsigmaz = int(100.*cl->GetSigmaZ2()/(seed->GetCurrentSigmaZ2()));
// Float_t res;
// //
// if (fSectors==fInnerSec){
// snoise2 = gnoise1;
// res = ggg1[amp]*z+glandau1[amp]*angle2;
// if (ctype==0) res *= gcor01[rsigmaz];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmaz];
// }
// }
// else {
// if (padlength<1.1){
// snoise2 = gnoise2;
// res = ggg2[amp]*z+glandau2[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmaz];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmaz];
// }
// }
// else{
// snoise2 = gnoise3;
// res = ggg3[amp]*z+glandau3[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmaz];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmaz];
// }
// }
// }
// if (ctype<0){
// res+=0.002;
// res*=1.3;
// }
// if ((ctype<0) &&<70){
// res+=0.002;
// res*=1.3;
// }
// res += snoise2;
// if (res<2*snoise2)
// res = 2*snoise2;
// if (res>3) res =3;
// seed->SetErrorZ2(res);
// return res;
}
void AliTPCtracker::RotateToLocal(AliTPCseed *seed)
{
//rotate to track "local coordinata
Float_t x = seed->GetX();
Float_t y = seed->GetY();
Float_t ymax = x*TMath::Tan(0.5*fSectors->GetAlpha());
if (y > ymax) {
seed->SetRelativeSector((seed->GetRelativeSector()+1) % fN);
if (!seed->Rotate(fSectors->GetAlpha()))
return;
} else if (y <-ymax) {
seed->SetRelativeSector((seed->GetRelativeSector()-1+fN) % fN);
if (!seed->Rotate(-fSectors->GetAlpha()))
return;
}
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F1old(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature
//-----------------------------------------------------------------
Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
(y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
(x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
if ( xr*xr+yr*yr<=0.00000000000001) return 100;
return -xr*yr/sqrt(xr*xr+yr*yr);
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F1(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature
//-----------------------------------------------------------------
x3 -=x1;
x2 -=x1;
y3 -=y1;
y2 -=y1;
//
Double_t det = x3*y2-x2*y3;
if (TMath::Abs(det)<1e-10){
return 100;
}
//
Double_t u = 0.5* (x2*(x2-x3)+y2*(y2-y3))/det;
Double_t x0 = x3*0.5-y3*u;
Double_t y0 = y3*0.5+x3*u;
Double_t c2 = 1/TMath::Sqrt(x0*x0+y0*y0);
if (det<0) c2*=-1;
return c2;
}
Double_t AliTPCtracker::F2(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature
//-----------------------------------------------------------------
x3 -=x1;
x2 -=x1;
y3 -=y1;
y2 -=y1;
//
Double_t det = x3*y2-x2*y3;
if (TMath::Abs(det)<1e-10) {
return 100;
}
//
Double_t u = 0.5* (x2*(x2-x3)+y2*(y2-y3))/det;
Double_t x0 = x3*0.5-y3*u;
Double_t y0 = y3*0.5+x3*u;
Double_t c2 = 1/TMath::Sqrt(x0*x0+y0*y0);
if (det<0) c2*=-1;
x0+=x1;
x0*=c2;
return x0;
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F2old(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature times center of curvature
//-----------------------------------------------------------------
Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
(y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
(x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
return -a/(d*y1-b)*xr/sqrt(xr*xr+yr*yr);
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F3(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t z1,Double_t z2) const
{
//-----------------------------------------------------------------
// Initial approximation of the tangent of the track dip angle
//-----------------------------------------------------------------
return (z1 - z2)/sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
Double_t AliTPCtracker::F3n(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t z1,Double_t z2, Double_t c) const
{
//-----------------------------------------------------------------
// Initial approximation of the tangent of the track dip angle
//-----------------------------------------------------------------
// Double_t angle1;
//angle1 = (z1-z2)*c/(TMath::ASin(c*x1-ni)-TMath::ASin(c*x2-ni));
//
Double_t d = TMath::Sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
if (TMath::Abs(d*c*0.5)>1) return 0;
Double_t angle2 = asinf(d*c*0.5);
angle2 = (z1-z2)*c/(angle2*2.);
return angle2;
}
Bool_t AliTPCtracker::GetProlongation(Double_t x1, Double_t x2, Double_t x[5], Double_t &y, Double_t &z) const
{//-----------------------------------------------------------------
// This function find proloncation of a track to a reference plane x=x2.
//-----------------------------------------------------------------
Double_t dx=x2-x1;
if (TMath::Abs(x[4]*x1 - x[2]) >= 0.999) {
return kFALSE;
}
Double_t c1=x[4]*x1 - x[2], r1=TMath::Sqrt((1.-c1)*(1.+c1));
Double_t c2=x[4]*x2 - x[2], r2=TMath::Sqrt((1.-c2)*(1.+c2));
y = x[0];
z = x[1];
Double_t dy = dx*(c1+c2)/(r1+r2);
Double_t dz = 0;
//
Double_t delta = x[4]*dx*(c1+c2)/(c1*r2 + c2*r1);
dz = x[3]*asinf(delta)/x[4];
y+=dy;
z+=dz;
return kTRUE;
}
Bool_t AliTPCtracker::GetProlongationLine(Double_t x1, Double_t x2, Double_t x[5], Double_t &y, Double_t &z) const
{//-----------------------------------------------------------------
// This function find straight line prolongation of a track to a reference plane x=x2.
//-----------------------------------------------------------------
if (TMath::Abs(x[2]) >= 0.999) return kFALSE;
Double_t c1=- x[2], dx2r = (x2-x1)/TMath::Sqrt((1.-c1)*(1.+c1));
y = x[0] + dx2r*c1;
z = x[1] + dx2r*x[3];
return kTRUE;
}
Int_t AliTPCtracker::LoadClusters (TTree *const tree)
{
// load clusters
//
fInput = tree;
return LoadClusters();
}
Int_t AliTPCtracker::LoadClusters(const TObjArray *arr)
{
//
// load clusters to the memory
AliTPCClustersRow *clrow = 0; //RS: why this new? new AliTPCClustersRow("AliTPCclusterMI");
Int_t lower = arr->LowerBound();
Int_t entries = arr->GetEntriesFast();
AliWarning("Sector Change ins not checked in LoadClusters(const TObjArray *arr)");
for (Int_t i=lower; i<entries; i++) {
clrow = (AliTPCClustersRow*) arr->At(i);
if(!clrow) continue;
TClonesArray* arr = clrow->GetArray();
if(!arr) continue;
int ncl = arr->GetEntriesFast();
if (ncl<1) continue;
//
Int_t sec,row;
fkParam->AdjustSectorRow(clrow->GetID(),sec,row);
for (Int_t icl=ncl; icl--;) {
Transform((AliTPCclusterMI*)(arr->At(icl)));
}
//
// RS: Check for possible sector change due to the distortions: TODO
//
AliTPCtrackerRow * tpcrow=0;
Int_t left=0;
if (sec<fkNIS*2){
tpcrow = &(fInnerSec[sec%fkNIS][row]);
left = sec/fkNIS;
}
else{
tpcrow = &(fOuterSec[(sec-fkNIS*2)%fkNOS][row]);
left = (sec-fkNIS*2)/fkNOS;
}
if (left ==0){
tpcrow->SetN1(ncl);
for (Int_t j=0;j<ncl;++j)
tpcrow->SetCluster1(j, *(AliTPCclusterMI*)(arr->At(j)));
}
if (left ==1){
tpcrow->SetN2(ncl);
for (Int_t j=0;j<ncl;++j)
tpcrow->SetCluster2(j, *(AliTPCclusterMI*)(arr->At(j)));
}
clrow->GetArray()->Clear(); // RS AliTPCclusterMI does not allocate memory
}
//
// delete clrow;
LoadOuterSectors();
LoadInnerSectors();
return 0;
}
Int_t AliTPCtracker::LoadClusters(const TClonesArray *arr)
{
//
// load clusters to the memory from one
// TClonesArray
//
// RS: Check for possible sector change due to the distortions: TODO
AliWarning("Sector Change ins not checked in LoadClusters(const TClonesArray *arr)");
//
//
AliTPCclusterMI *clust=0;
Int_t count[72][96] = { {0} , {0} };
// loop over clusters
for (Int_t icl=0; icl<arr->GetEntriesFast(); icl++) {
clust = (AliTPCclusterMI*)arr->At(icl);
if(!clust) continue;
//printf("cluster: det %d, row %d \n", clust->GetDetector(),clust->GetRow());
// transform clusters
Transform(clust);
// count clusters per pad row
count[clust->GetDetector()][clust->GetRow()]++;
}
// insert clusters to sectors
for (Int_t icl=0; icl<arr->GetEntriesFast(); icl++) {
clust = (AliTPCclusterMI*)arr->At(icl);
if(!clust) continue;
Int_t sec = clust->GetDetector();
Int_t row = clust->GetRow();
// filter overlapping pad rows needed by HLT
if(sec<fkNIS*2) { //IROCs
if(row == 30) continue;
}
else { // OROCs
if(row == 27 || row == 76) continue;
}
// Int_t left=0;
if (sec<fkNIS*2){
// left = sec/fkNIS;
fInnerSec[sec%fkNIS].InsertCluster(clust, count[sec][row], fkParam);
}
else{
// left = (sec-fkNIS*2)/fkNOS;
fOuterSec[(sec-fkNIS*2)%fkNOS].InsertCluster(clust, count[sec][row], fkParam);
}
}
// Load functions must be called behind LoadCluster(TClonesArray*)
// needed by HLT
//LoadOuterSectors();
//LoadInnerSectors();
return 0;
}
Int_t AliTPCtracker::LoadClusters()
{
//
// load clusters to the memory
static AliTPCClustersRow *clrow= new AliTPCClustersRow("AliTPCclusterMI");
//
// TTree * tree = fClustersArray.GetTree();
AliInfo("LoadClusters()\n");
fNClusters = 0;
TTree * tree = fInput;
TBranch * br = tree->GetBranch("Segment");
br->SetAddress(&clrow);
double cutZ2X = AliTPCReconstructor::GetPrimaryZ2XCut();
double cutZOutSector = AliTPCReconstructor::GetZOutSectorCut();
if (cutZOutSector>0 && AliTPCReconstructor::GetExtendedRoads())
cutZOutSector += AliTPCReconstructor::GetExtendedRoads()[1];
//
if (cutZ2X>0 || cutZOutSector>0) {
AliInfoF("Cut on cluster |Z/X| : %s, on cluster Z on wrong CE side: %s",
cutZ2X>0 ? Form("%.3f",cutZ2X) : "N/A",
cutZOutSector>0 ? Form("%.3f",cutZOutSector) : "N/A");
}
Int_t j=Int_t(tree->GetEntries());
for (Int_t i=0; i<j; i++) {
br->GetEntry(i);
//
TClonesArray* clArr = clrow->GetArray();
int nClus = clArr->GetEntriesFast();
Int_t sec,row;
fkParam->AdjustSectorRow(clrow->GetID(),sec,row);
for (Int_t icl=nClus; icl--;) Transform((AliTPCclusterMI*)(clArr->At(icl)));
//
AliTPCtrackerRow * tpcrow=0;
Int_t left=0;
if (sec<fkNIS*2){
tpcrow = &(fInnerSec[sec%fkNIS][row]);
left = sec/fkNIS;
}
else{
tpcrow = &(fOuterSec[(sec-fkNIS*2)%fkNOS][row]);
left = (sec-fkNIS*2)/fkNOS;
}
int nClusAdd = 0;
if (left ==0){ // A side
for (int k=0;k<nClus;k++) {
const AliTPCclusterMI& cl = *((AliTPCclusterMI*)clArr->At(k));
if (cutZOutSector>0 && cl.GetZ()<-cutZOutSector) continue;
if (cutZ2X>0 && cl.GetZ()/cl.GetX() > cutZ2X) continue;
tpcrow->SetCluster1(nClusAdd++, cl);
}
tpcrow->SetN1(nClusAdd);
}
if (left ==1){ // C side
for (int k=0;k<nClus;k++) {
const AliTPCclusterMI& cl = *((AliTPCclusterMI*)clArr->At(k));
if (cutZOutSector>0 && cl.GetZ()>cutZOutSector) continue;
if (cutZ2X>0 && cl.GetZ()/cl.GetX() < -cutZ2X) continue;
tpcrow->SetCluster2(nClusAdd++, cl);
}
tpcrow->SetN2(nClusAdd);
}
fNClusters += nClusAdd;
}
//
//clrow->Clear("C");
clrow->Clear(); // RS AliTPCclusterMI does not allocate memory
LoadOuterSectors();
LoadInnerSectors();
cout << " =================================================================================================================================== " << endl;
cout << " AliTPCReconstructor::GetRecoParam()->GetUseIonTailCorrection() = " << AliTPCReconstructor::GetRecoParam()->GetUseIonTailCorrection() << endl;
cout << " AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection() = " << AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection() << endl;
cout << " =================================================================================================================================== " << endl;
if (AliTPCReconstructor::GetRecoParam()->GetUseIonTailCorrection()) ApplyTailCancellation();
if (AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection()!=0.) CalculateXtalkCorrection();
if (AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection()!=0.) ApplyXtalkCorrection();
//if (AliTPCReconstructor::GetRecoParam()->GetUseOulierClusterFilter()) FilterOutlierClusters();
/*
static int maxClus[18][2][kMaxRow]={0};
int maxAcc=0,nclEv=0, capacity=0;
for (int isec=0;isec<18;isec++) {
for (int irow=0;irow<kMaxRow;irow++) {
AliTPCtrackerRow * tpcrow = irow>62 ? &(fOuterSec[isec][irow-63]) : &(fInnerSec[isec][irow]);
maxClus[isec][0][irow] = TMath::Max(maxClus[isec][0][irow], tpcrow->GetN1());
maxClus[isec][1][irow] = TMath::Max(maxClus[isec][1][irow], tpcrow->GetN2());
maxAcc += maxClus[isec][0][irow]+maxClus[isec][1][irow];
nclEv += tpcrow->GetN();
capacity += tpcrow->GetClusters1()->Capacity();
capacity += tpcrow->GetClusters2()->Capacity();
}
}
printf("RS:AccumulatedSpace: %d for %d | pointers: %d\n",maxAcc,nclEv,capacity);
*/
return 0;
}
void AliTPCtracker::CalculateXtalkCorrection(){
//
// Calculate crosstalk estimate
//
TStopwatch sw;
sw.Start();
const Int_t nROCs = 72;
const Int_t nIterations=3; //
// 0.) reset crosstalk matrix
//
for (Int_t isector=0; isector<nROCs*4; isector++){ //set all ellemts of crosstalk matrix to 0
TMatrixD * crossTalkMatrix = (TMatrixD*)fCrossTalkSignalArray->At(isector);
if (crossTalkMatrix)(*crossTalkMatrix)*=0;
}
//
// 1.) Filling part -- loop over clusters
//
Double_t missingChargeFactor= AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrectionMissingCharge();
for (Int_t iter=0; iter<nIterations;iter++){
for (Int_t isector=0; isector<36; isector++){ // loop over sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
Int_t sec=0;
if (isector<18) sec=isector+18*iside;
if (isector>=18) sec=18+isector+18*iside;
for (Int_t row = 0;row<nrows;row++){ // loop over rows
//
//
Int_t wireSegmentID = fkParam->GetWireSegment(sec,row);
Float_t nPadsPerSegment = (Float_t)(fkParam->GetNPadsPerSegment(wireSegmentID));
TMatrixD &crossTalkSignal = *((TMatrixD*)fCrossTalkSignalArray->At(sec));
TMatrixD &crossTalkSignalCache = *((TMatrixD*)fCrossTalkSignalArray->At(sec+nROCs*2)); // this is the cache value of the crosstalk from previous iteration
TMatrixD &crossTalkSignalBelow = *((TMatrixD*)fCrossTalkSignalArray->At(sec+nROCs));
Int_t nCols=crossTalkSignal.GetNcols();
//
AliTPCtrackerRow& tpcrow = sector[row];
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
for (Int_t i=0;i<ncl;i++) { // loop over clusters
AliTPCclusterMI *clXtalk= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
Int_t timeBinXtalk = clXtalk->GetTimeBin();
Double_t rmsPadMin2=0.5*0.5+(fkParam->GetDiffT()*fkParam->GetDiffT())*(TMath::Abs((clXtalk->GetZ()-fkParam->GetZLength())))/(fkParam->GetPadPitchWidth(sec)*fkParam->GetPadPitchWidth(sec)); // minimal PRF width - 0.5 is the PRF in the pad units - we should et it from fkparam getters
Double_t rmsTimeMin2=1+(fkParam->GetDiffL()*fkParam->GetDiffL())*(TMath::Abs((clXtalk->GetZ()-fkParam->GetZLength())))/(fkParam->GetZWidth()*fkParam->GetZWidth()); // minimal PRF width - 1 is the TRF in the time bin units - we should et it from fkParam getters
Double_t rmsTime2 = clXtalk->GetSigmaZ2()/(fkParam->GetZWidth()*fkParam->GetZWidth());
Double_t rmsPad2 = clXtalk->GetSigmaY2()/(fkParam->GetPadPitchWidth(sec)*fkParam->GetPadPitchWidth(sec));
if (rmsPadMin2>rmsPad2){
rmsPad2=rmsPadMin2;
}
if (rmsTimeMin2>rmsTime2){
rmsTime2=rmsTimeMin2;
}
Double_t norm= 2.*TMath::Exp(-1.0/(2.*rmsTime2))+2.*TMath::Exp(-4.0/(2.*rmsTime2))+1.;
Double_t qTotXtalk = 0.;
Double_t qTotXtalkMissing = 0.;
for (Int_t itb=timeBinXtalk-2, idelta=-2; itb<=timeBinXtalk+2; itb++,idelta++) {
if (itb<0 || itb>=nCols) continue;
Double_t missingCharge=0;
Double_t trf= TMath::Exp(-idelta*idelta/(2.*rmsTime2));
if (missingChargeFactor>0) {
for (Int_t dpad=-2; dpad<=2; dpad++){
Double_t qPad = clXtalk->GetMax()*TMath::Exp(-dpad*dpad/(2.*rmsPad2))*trf;
if (TMath::Nint(qPad-crossTalkSignalCache[wireSegmentID][itb])<=fkParam->GetZeroSup()){
missingCharge+=qPad+crossTalkSignalCache[wireSegmentID][itb];
}else{
missingCharge+=crossTalkSignalCache[wireSegmentID][itb];
}
}
}
qTotXtalk = clXtalk->GetQ()*trf/norm+missingCharge*missingChargeFactor;
qTotXtalkMissing = missingCharge;
crossTalkSignal[wireSegmentID][itb]+= qTotXtalk/nPadsPerSegment;
crossTalkSignalBelow[wireSegmentID][itb]+= qTotXtalkMissing/nPadsPerSegment;
} // end of time bin loop
} // end of cluster loop
} // end of rows loop
} // end of side loop
} // end of sector loop
//
// copy crosstalk matrix to cached used for next itteration
//
//
// 2.) dump the crosstalk matrices to tree for further investigation
// a.) to estimate fluctuation of pedestal in indiviula wire segments
// b.) to check correlation between regions
// c.) to check relative conribution of signal below threshold to crosstalk
if (AliTPCReconstructor::StreamLevel()&kStreamCrosstalkMatrix) {
for (Int_t isector=0; isector<nROCs; isector++){ //set all ellemts of crosstalk matrix to 0
TMatrixD * crossTalkMatrix = (TMatrixD*)fCrossTalkSignalArray->At(isector);
TMatrixD * crossTalkMatrixBelow = (TMatrixD*)fCrossTalkSignalArray->At(isector+nROCs);
TMatrixD * crossTalkMatrixCache = (TMatrixD*)fCrossTalkSignalArray->At(isector+nROCs*2);
TVectorD vecAll(crossTalkMatrix->GetNrows());
TVectorD vecBelow(crossTalkMatrix->GetNrows());
TVectorD vecCache(crossTalkMatrixCache->GetNrows());
//
for (Int_t itime=0; itime<crossTalkMatrix->GetNcols(); itime++){
for (Int_t iwire=0; iwire<crossTalkMatrix->GetNrows(); iwire++){
vecAll[iwire]=(*crossTalkMatrix)(iwire,itime);
vecBelow[iwire]=(*crossTalkMatrixBelow)(iwire,itime);
vecCache[iwire]=(*crossTalkMatrixCache)(iwire,itime);
}
(*fDebugStreamer)<<"crosstalkMatrix"<<
"iter="<<iter<< //iteration
"sector="<<isector<< // sector
"itime="<<itime<< // time bin index
"vecAll.="<<&vecAll<< // crosstalk charge + charge below threshold
"vecCache.="<<&vecCache<< // crosstalk charge + charge below threshold
"vecBelow.="<<&vecBelow<< // crosstalk contribution from signal below threshold
"\n";
}
}
}
if (iter<nIterations-1) for (Int_t isector=0; isector<nROCs*2; isector++){ //set all ellemts of crosstalk matrix to 0
TMatrixD * crossTalkMatrix = (TMatrixD*)fCrossTalkSignalArray->At(isector);
TMatrixD * crossTalkMatrixCache = (TMatrixD*)fCrossTalkSignalArray->At(isector+nROCs*2);
if (crossTalkMatrix){
(*crossTalkMatrixCache)*=0;
(*crossTalkMatrixCache)+=(*crossTalkMatrix);
(*crossTalkMatrix)*=0;
}
}
}
sw.Stop();
AliInfoF("timing: %e/%e real/cpu",sw.RealTime(),sw.CpuTime());
//
}
void AliTPCtracker::FilterOutlierClusters(){
//
// filter outlier clusters
//
/*
1.)..... booking part
nSectors=72;
nTimeBins=fParam->Get....
TH2F hisTime("","", sector,0,sector, nTimeBins,0,nTimeBins);
TH2F hisPadRow("","", sector,0,sector, nPadRows,0,nPadRows);
2.) .... filling part
.... cluster loop { hisTime.Fill(cluster->GetDetector(),cluster->GetTimeBin()); }
3.) ...filtering part
sector loop { calculate median,mean80 and rms80 of the nclusters per time bin; calculate median,mean80 and rms80 of the nclusters per par row; .... export values to the debug streamers - to decide which threshold to be used... }
sector loop
{ disable clusters in time bins > mean+ n rms80+ offsetTime disable clusters in padRow > mean+ n rms80+ offsetPadRow // how to dislable clusters? - new bit to introduce }
//
4. Disabling clusters
*/
//
// 1.) booking part
//
// AliTPCcalibDB *db=AliTPCcalibDB::Instance();
Int_t nSectors=AliTPCROC::Instance()->GetNSectors();
Int_t nTimeBins= 1100; // *Bug here - we should get NTimeBins from ALTRO - Parameters not relyable
Int_t nPadRows=(AliTPCROC::Instance()->GetNRows(0) + AliTPCROC::Instance()->GetNRows(36));
// parameters for filtering
const Double_t nSigmaCut=9.; // should be in recoParam ?
const Double_t offsetTime=100; // should be in RecoParam ? -
const Double_t offsetPadRow=300; // should be in RecoParam ?
const Double_t offsetTimeAccept=8; // should be in RecoParam ? - obtained as mean +1 rms in high IR pp
TH2F hisTime("hisSectorTime","hisSectorTime", nSectors,0,nSectors, nTimeBins,0,nTimeBins);
TH2F hisPadRow("hisSectorRow","hisSectorRow", nSectors,0,nSectors, nPadRows,0,nPadRows);
//
// 2.) Filling part -- loop over clusters
//
for (Int_t isector=0; isector<36; isector++){ // loop over sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row];
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
for (Int_t i=0;i<ncl;i++) { // loop over clusters
AliTPCclusterMI *cluster= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
hisTime.Fill(cluster->GetDetector(),cluster->GetTimeBin());
hisPadRow.Fill(cluster->GetDetector(),cluster->GetRow());
}
}
}
}
//
// 3. Filtering part
//
TVectorD vecTime(nTimeBins);
TVectorD vecPadRow(nPadRows);
TVectorD vecMedianSectorTime(nSectors);
TVectorD vecRMSSectorTime(nSectors);
TVectorD vecMedianSectorTimeOut6(nSectors);
TVectorD vecMedianSectorTimeOut9(nSectors);//
TVectorD vecMedianSectorTimeOut(nSectors);//
TVectorD vecMedianSectorPadRow(nSectors);
TVectorD vecRMSSectorPadRow(nSectors);
TVectorD vecMedianSectorPadRowOut6(nSectors);
TVectorD vecMedianSectorPadRowOut9(nSectors);
TVectorD vecMedianSectorPadRowOut(nSectors);
TVectorD vecSectorOut6(nSectors);
TVectorD vecSectorOut9(nSectors);
TMatrixD matSectorCluster(nSectors,2);
//
// 3.a) median, rms calculations for hisTime
//
for (Int_t isec=0; isec<nSectors; isec++){
vecMedianSectorTimeOut6[isec]=0;
vecMedianSectorTimeOut9[isec]=0;
for (Int_t itime=0; itime<nTimeBins; itime++){
vecTime[itime]=hisTime.GetBinContent(isec+1, itime+1);
}
Double_t median= TMath::Mean(nTimeBins,vecTime.GetMatrixArray());
Double_t rms= TMath::RMS(nTimeBins,vecTime.GetMatrixArray());
vecMedianSectorTime[isec]=median;
vecRMSSectorTime[isec]=rms;
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) AliInfo(TString::Format("Sector TimeStat: %d\t%8.0f\t%8.0f",isec,median,rms).Data());
//
// declare outliers
for (Int_t itime=0; itime<nTimeBins; itime++){
Double_t entries= hisTime.GetBinContent(isec+1, itime+1);
if (entries>median+6.*rms+offsetTime) {
vecMedianSectorTimeOut6[isec]+=1;
}
if (entries>median+9.*rms+offsetTime) {
vecMedianSectorTimeOut9[isec]+=1;
}
}
}
//
// 3.b) median, rms calculations for hisPadRow
//
for (Int_t isec=0; isec<nSectors; isec++){
vecMedianSectorPadRowOut6[isec]=0;
vecMedianSectorPadRowOut9[isec]=0;
for (Int_t ipadrow=0; ipadrow<nPadRows; ipadrow++){
vecPadRow[ipadrow]=hisPadRow.GetBinContent(isec+1, ipadrow+1);
}
Int_t nPadRowsSector= AliTPCROC::Instance()->GetNRows(isec);
Double_t median= TMath::Mean(nPadRowsSector,vecPadRow.GetMatrixArray());
Double_t rms= TMath::RMS(nPadRowsSector,vecPadRow.GetMatrixArray());
vecMedianSectorPadRow[isec]=median;
vecRMSSectorPadRow[isec]=rms;
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) AliInfo(TString::Format("Sector PadRowStat: %d\t%8.0f\t%8.0f",isec,median,rms).Data());
//
// declare outliers
for (Int_t ipadrow=0; ipadrow<nPadRows; ipadrow++){
Double_t entries= hisPadRow.GetBinContent(isec+1, ipadrow+1);
if (entries>median+6.*rms+offsetPadRow) {
vecMedianSectorPadRowOut6[isec]+=1;
}
if (entries>median+9.*rms+offsetPadRow) {
vecMedianSectorPadRowOut9[isec]+=1;
}
}
}
//
// 3.c) filter outlier sectors
//
Double_t medianSectorTime = TMath::Median(nSectors, vecTime.GetMatrixArray());
Double_t mean69SectorTime, rms69SectorTime=0;
AliMathBase::EvaluateUni(nSectors, vecTime.GetMatrixArray(), mean69SectorTime,rms69SectorTime,69);
for (Int_t isec=0; isec<nSectors; isec++){
vecSectorOut6[isec]=0;
vecSectorOut9[isec]=0;
matSectorCluster(isec,0)=0;
matSectorCluster(isec,1)=0;
if (TMath::Abs(vecMedianSectorTime[isec])>(mean69SectorTime+6.*(rms69SectorTime+ offsetTimeAccept))) {
vecSectorOut6[isec]=1;
}
if (TMath::Abs(vecMedianSectorTime[isec])>(mean69SectorTime+9.*(rms69SectorTime+ offsetTimeAccept))){
vecSectorOut9[isec]=1;
}
}
// light version of export variable
Int_t filteredSector= vecSectorOut9.Sum(); // light version of export variable
Int_t filteredSectorTime= vecMedianSectorTimeOut9.Sum();
Int_t filteredSectorPadRow= vecMedianSectorPadRowOut9.Sum();
if (fEvent) if (fEvent->GetHeader()){
fEvent->GetHeader()->SetTPCNoiseFilterCounter(0,TMath::Min(filteredSector,255));
fEvent->GetHeader()->SetTPCNoiseFilterCounter(1,TMath::Min(filteredSectorTime,255));
fEvent->GetHeader()->SetTPCNoiseFilterCounter(2,TMath::Min(filteredSectorPadRow,255));
}
//
// 4. Disabling clusters in outlier layers
//
Int_t counterAll=0;
Int_t counterOut=0;
for (Int_t isector=0; isector<36; isector++){ // loop over sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row];
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
for (Int_t i=0;i<ncl;i++) { // loop over clusters
AliTPCclusterMI *cluster= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
Double_t medianTime=vecMedianSectorTime[cluster->GetDetector()];
Double_t medianPadRow=vecMedianSectorPadRow[cluster->GetDetector()];
Double_t rmsTime=vecRMSSectorTime[cluster->GetDetector()];
Double_t rmsPadRow=vecRMSSectorPadRow[cluster->GetDetector()];
Int_t entriesPadRow=hisPadRow.GetBinContent(cluster->GetDetector()+1, cluster->GetRow()+1);
Int_t entriesTime=hisTime.GetBinContent(cluster->GetDetector()+1, cluster->GetTimeBin()+1);
Bool_t isOut=kFALSE;
if (vecSectorOut9[cluster->GetDetector()]>0.5) {
isOut=kTRUE;
}
if (entriesTime>medianTime+nSigmaCut*rmsTime+offsetTime) {
isOut=kTRUE;
vecMedianSectorTimeOut[cluster->GetDetector()]++;
}
if (entriesPadRow>medianPadRow+nSigmaCut*rmsPadRow+offsetPadRow) {
isOut=kTRUE;
vecMedianSectorPadRowOut[cluster->GetDetector()]++;
}
counterAll++;
matSectorCluster(cluster->GetDetector(),0)+=1;
if (isOut){
cluster->Disable();
counterOut++;
matSectorCluster(cluster->GetDetector(),1)+=1;
}
}
}
}
}
for (Int_t isec=0; isec<nSectors; isec++){
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) AliInfo(TString::Format("Sector Stat: %d\t%8.0f\t%8.0f",isec,matSectorCluster(isec,1),matSectorCluster(isec,0)).Data());
}
//
// dump info to streamer - for later tuning of cuts
//
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) { // stream TPC data ouliers filtering infomation
AliLog::Flush();
AliInfo(TString::Format("Cluster counter: (%d/%d) (Filtered/All)",counterOut,counterAll).Data());
for (Int_t iSec=0; iSec<nSectors; iSec++){
if (vecSectorOut9[iSec]>0 || matSectorCluster(iSec,1)>0) {
AliInfo(TString::Format("Filtered sector\t%d",iSec).Data());
Double_t vecMedTime =TMath::Median(72,vecMedianSectorTime.GetMatrixArray());
Double_t vecMedPadRow =TMath::Median(72,vecMedianSectorPadRow.GetMatrixArray());
Double_t vecMedCluster=(counterAll-counterOut)/72;
AliInfo(TString::Format("VecMedianSectorTime\t(%4.4f/%4.4f/%4.4f)", vecMedianSectorTimeOut[iSec],vecMedianSectorTime[iSec],vecMedTime).Data());
AliInfo(TString::Format("VecMedianSectorPadRow\t(%4.4f/%4.4f/%4.4f)", vecMedianSectorPadRowOut[iSec],vecMedianSectorPadRow[iSec],vecMedPadRow).Data());
AliInfo(TString::Format("MatSectorCluster\t(%4.4f/%4.4f/%4.4f)\n", matSectorCluster(iSec,1), matSectorCluster(iSec,0), vecMedCluster).Data());
AliLog::Flush();
}
}
AliLog::Flush();
Int_t eventNr = fEvent->GetEventNumberInFile();
(*fDebugStreamer)<<"filterClusterInfo"<<
// minimal set variables for the ESDevent
"eventNr="<<eventNr<<
"counterAll="<<counterAll<<
"counterOut="<<counterOut<<
"matSectotCluster.="<<&matSectorCluster<< //
//
"filteredSector="<<filteredSector<< // counter filtered sectors
"filteredSectorTime="<<filteredSectorTime<< // counter filtered time bins
"filteredSectorPadRow="<<filteredSectorPadRow<< // counter filtered pad-rows
// per sector outlier information
"medianSectorTime="<<medianSectorTime<< // median number of clusters per sector/timebin
"mean69SectorTime="<<mean69SectorTime<< // LTM statistic mean of clusters per sector/timebin
"rms69SectorTime="<<rms69SectorTime<< // LTM statistic RMS of clusters per sector/timebin
"vecSectorOut6.="<<&vecSectorOut6<< // flag array sector - 6 sigma +accept margin outlier
"vecSectorOut9.="<<&vecSectorOut9<< // flag array sector - 9 sigma + accept margin outlier
// per sector/timebin outlier detection
"vecMedianSectorTime.="<<&vecMedianSectorTime<<
"vecRMSSectorTime.="<<&vecRMSSectorTime<<
"vecMedianSectorTimeOut6.="<<&vecMedianSectorTimeOut6<<
"vecMedianSectorTimeOut9.="<<&vecMedianSectorTimeOut9<<
"vecMedianSectorTimeOut0.="<<&vecMedianSectorTimeOut<<
// per sector/pad-row outlier detection
"vecMedianSectorPadRow.="<<&vecMedianSectorPadRow<<
"vecRMSSectorPadRow.="<<&vecRMSSectorPadRow<<
"vecMedianSectorPadRowOut6.="<<&vecMedianSectorPadRowOut6<<
"vecMedianSectorPadRowOut9.="<<&vecMedianSectorPadRowOut9<<
"vecMedianSectorPadRowOut9.="<<&vecMedianSectorPadRowOut<<
"\n";
((*fDebugStreamer)<<"filterClusterInfo").GetTree()->Write();
fDebugStreamer->GetFile()->Flush();
}
}
void AliTPCtracker::UnloadClusters()
{
//
// unload clusters from the memory
//
Int_t nrows = fOuterSec->GetNRows();
for (Int_t sec = 0;sec<fkNOS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fOuterSec[sec%fkNOS][row]);
// if (tpcrow){
// if (tpcrow->fClusters1) delete []tpcrow->fClusters1;
// if (tpcrow->fClusters2) delete []tpcrow->fClusters2;
//}
tpcrow->ResetClusters();
}
//
nrows = fInnerSec->GetNRows();
for (Int_t sec = 0;sec<fkNIS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fInnerSec[sec%fkNIS][row]);
//if (tpcrow){
// if (tpcrow->fClusters1) delete []tpcrow->fClusters1;
//if (tpcrow->fClusters2) delete []tpcrow->fClusters2;
//}
tpcrow->ResetClusters();
}
fNClusters = 0;
return ;
}
void AliTPCtracker::FillClusterArray(TObjArray* array) const{
//
// Filling cluster to the array - For visualization purposes
//
Int_t nrows=0;
nrows = fOuterSec->GetNRows();
for (Int_t sec = 0;sec<fkNOS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fOuterSec[sec%fkNOS][row]);
if (!tpcrow) continue;
for (Int_t icl = 0;icl<tpcrow->GetN();icl++){
array->AddLast((TObject*)((*tpcrow)[icl]));
}
}
nrows = fInnerSec->GetNRows();
for (Int_t sec = 0;sec<fkNIS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fInnerSec[sec%fkNIS][row]);
if (!tpcrow) continue;
for (Int_t icl = 0;icl<tpcrow->GetN();icl++){
array->AddLast((TObject*)(*tpcrow)[icl]);
}
}
}
Int_t AliTPCtracker::Transform(AliTPCclusterMI * cluster){
//
// transformation
// RS: return sector in which the cluster appears accounting for eventual distortions
const double kMaxY2X = AliTPCTransform::GetMaxY2X(); // tg of sector angular span
const double kSinSect = TMath::Sin(TMath::Pi()/9), kCosSect = TMath::Cos(TMath::Pi()/9);
//
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform() ;
if (!transform) {
AliFatal("Tranformations not in calibDB");
return -1;
}
if (!transform->GetCurrentRecoParam()) transform->SetCurrentRecoParam((AliTPCRecoParam*)AliTPCReconstructor::GetRecoParam());
Double_t x[3]={static_cast<Double_t>(cluster->GetRow()),static_cast<Double_t>(cluster->GetPad()),static_cast<Double_t>(cluster->GetTimeBin())};
Int_t idROC = cluster->GetDetector();
transform->Transform(x,&idROC,0,1);
// if (cluster->GetDetector()%36>17){
// x[1]*=-1;
//}
//RS: Check if cluster goes outside of sector angular boundaries
float yMax = x[0]*kMaxY2X;
if (x[1]>yMax) {
cluster->SetSectorChanged(kTRUE);
AliTPCTransform::RotateToSectorUp(x,idROC);
}
else if (x[1]<-yMax) {
cluster->SetSectorChanged(kTRUE);
AliTPCTransform::RotateToSectorDown(x,idROC);
}
//
// in debug mode check the transformation
//
if ((AliTPCReconstructor::StreamLevel()&kStreamTransform)>0) {
Float_t gx[3];
cluster->GetGlobalXYZ(gx);
Int_t event = (fEvent==NULL)? 0: fEvent->GetEventNumberInFile();
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Transform"<< // needed for debugging of the cluster transformation, resp. used for later visualization
"event="<<event<<
"x0="<<x[0]<<
"x1="<<x[1]<<
"x2="<<x[2]<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"Cl.="<<cluster<<
"\n";
}
cluster->SetX(x[0]);
cluster->SetY(x[1]);
cluster->SetZ(x[2]);
// The old stuff:
//
//
//
//if (!fkParam->IsGeoRead()) fkParam->ReadGeoMatrices();
if (AliTPCReconstructor::GetRecoParam()->GetUseSectorAlignment() && (!calibDB->HasAlignmentOCDB())){
TGeoHMatrix *mat = fkParam->GetClusterMatrix(cluster->GetDetector());
//TGeoHMatrix mat;
Double_t pos[3]= {cluster->GetX(),cluster->GetY(),cluster->GetZ()};
Double_t posC[3]={cluster->GetX(),cluster->GetY(),cluster->GetZ()};
if (mat) mat->LocalToMaster(pos,posC);
else{
// chack Loading of Geo matrices from GeoManager - TEMPORARY FIX
}
cluster->SetX(posC[0]);
cluster->SetY(posC[1]);
cluster->SetZ(posC[2]);
}
return idROC;
}
void AliTPCtracker::ApplyXtalkCorrection(){
//
// ApplyXtalk correction
// Loop over all clusters
// add to each cluster signal corresponding to common Xtalk mode for given time bin at given wire segment
// cluster loop
TStopwatch sw;
sw.Start();
for (Int_t isector=0; isector<36; isector++){ //loop tracking sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row]; // row object
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
Int_t xSector=0; // sector number in the TPC convention 0-72
if (isector<18){ //if IROC
xSector=isector+(iside>0)*18;
}else{
xSector=isector+18; // isector -18 +36
if (iside>0) xSector+=18;
}
TMatrixD &crossTalkMatrix= *((TMatrixD*)fCrossTalkSignalArray->At(xSector));
Int_t wireSegmentID = fkParam->GetWireSegment(xSector,row);
for (Int_t i=0;i<ncl;i++) {
AliTPCclusterMI *cluster= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
Int_t iTimeBin=TMath::Nint(cluster->GetTimeBin());
Double_t xTalk= crossTalkMatrix[wireSegmentID][iTimeBin];
cluster->SetMax(cluster->GetMax()+xTalk);
const Double_t kDummy=4;
Double_t sumxTalk=xTalk*kDummy; // should be calculated via time response function
cluster->SetQ(cluster->GetQ()+sumxTalk);
if ((AliTPCReconstructor::StreamLevel()&kStreamXtalk)>0) { // flag: stream crosstalk correctio as applied to cluster
TTreeSRedirector &cstream = *fDebugStreamer;
if (gRandom->Rndm() > 0.){
cstream<<"Xtalk"<<
"isector=" << isector << // sector [0,36]
"iside=" << iside << // side A or C
"row=" << row << // padrow
"i=" << i << // index of the cluster
"xSector=" << xSector << // sector [0,72]
"wireSegmentID=" << wireSegmentID << // anode wire segment id [0,10]
"iTimeBin=" << iTimeBin << // timebin of the corrected cluster
"xTalk=" << xTalk << // Xtalk contribution added to Qmax
"sumxTalk=" << sumxTalk << // Xtalk contribution added to Qtot (roughly 3*Xtalk)
"cluster.=" << cluster << // corrected cluster object
"\n";
}
}// dump the results to the debug streamer if in debug mode
}
}
}
}
sw.Stop();
AliInfoF("timing: %e/%e real/cpu",sw.RealTime(),sw.CpuTime());
//
}
void AliTPCtracker::ApplyTailCancellation(){
//
// Correct the cluster charge for the ion tail effect
// The TimeResponse function accessed via AliTPCcalibDB (TPC/Calib/IonTail)
//
TStopwatch sw;
sw.Start();
// Retrieve
TObjArray *ionTailArr = (TObjArray*)AliTPCcalibDB::Instance()->GetIonTailArray();
if (!ionTailArr) {AliFatal("TPC - Missing IonTail OCDB object");}
TObject *rocFactorIROC = ionTailArr->FindObject("factorIROC");
TObject *rocFactorOROC = ionTailArr->FindObject("factorOROC");
Float_t factorIROC = (atof(rocFactorIROC->GetTitle()));
Float_t factorOROC = (atof(rocFactorOROC->GetTitle()));
// find the number of clusters for the whole TPC (nclALL)
Int_t nclALL=0;
for (Int_t isector=0; isector<36; isector++){
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
nclALL += sector.GetNClInSector(0);
nclALL += sector.GetNClInSector(1);
}
//RS changed from heap allocation in the loop to stack allocation
TGraphErrors * graphRes[20];
Float_t indexAmpGraphs[20];
// AliTPCclusterMI* rowClusterArray[kMaxClusterPerRow]; // caches clusters for each row // RS avoid trashing the heap
// start looping over all clusters
for (Int_t iside=0; iside<2; iside++){ // loop over sides
//
//
for (Int_t secType=0; secType<2; secType++){ //loop over inner or outer sector
// cache experimantal tuning factor for the different chamber type
const Float_t ampfactor = (secType==0)?factorIROC:factorOROC;
std::cout << " ampfactor = " << ampfactor << std::endl;
//
for (Int_t sec = 0;sec<fkNOS;sec++){ //loop overs sectors
//
//
// Cache time response functions and their positons to COG of the cluster
// TGraphErrors ** graphRes = new TGraphErrors *[20]; // RS avoid heap allocations if stack can be used
// Float_t * indexAmpGraphs = new Float_t[20]; // RS Moved outside of the loop
memset(graphRes,0,20*sizeof(TGraphErrors*));
memset(indexAmpGraphs,0,20*sizeof(float));
//for (Int_t icache=0; icache<20; icache++) //RS
//{
// graphRes[icache] = NULL;
// indexAmpGraphs[icache] = 0;
// }
///////////////////////////// --> position fo sie loop
if (!AliTPCcalibDB::Instance()->GetTailcancelationGraphs(sec+36*secType+18*iside,graphRes,indexAmpGraphs))
{
continue;
}
AliTPCtrackerSector §or= (secType==0)?fInnerSec[sec]:fOuterSec[sec];
Int_t nrows = sector.GetNRows(); // number of rows
Int_t nclSector = sector.GetNClInSector(iside); // ncl per sector to be used for debugging
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row]; // row object
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
// Order clusters in time for the proper correction of ion tail
Float_t qTotArray[ncl]; // arrays to be filled with modified Qtot and Qmax values in order to avoid float->int conversion
Float_t qMaxArray[ncl];
Int_t sortedClusterIndex[ncl];
Float_t sortedClusterTimeBin[ncl];
//TObjArray *rowClusterArray = new TObjArray(ncl); // cache clusters for each row // RS avoid trashing the heap
AliTPCclusterMI* rowClusterArray[ncl]; // caches clusters for each row // RS avoid trashing the heap
// memset(rowClusterArray,0,sizeof(AliTPCclusterMI*)*ncl); //.Clear();
//if (rowClusterArray.GetSize()<ncl) rowClusterArray.Expand(ncl);
for (Int_t i=0;i<ncl;i++)
{
qTotArray[i]=0;
qMaxArray[i]=0;
sortedClusterIndex[i]=i;
AliTPCclusterMI *rowcl= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
rowClusterArray[i] = rowcl;
//if (rowcl) {
// rowClusterArray.AddAt(rowcl,i);
//} else {
// rowClusterArray.RemoveAt(i);
//}
// Fill the timebin info to the array in order to sort wrt tb
if (!rowcl) {
sortedClusterTimeBin[i]=0.0;
} else {
sortedClusterTimeBin[i] = rowcl->GetTimeBin();
}
}
TMath::Sort(ncl,sortedClusterTimeBin,sortedClusterIndex,kFALSE); // sort clusters in time
// Main cluster correction loops over clusters
for (Int_t icl0=0; icl0<ncl;icl0++){ // first loop over clusters
AliTPCclusterMI *cl0= rowClusterArray[sortedClusterIndex[icl0]]; //RS static_cast<AliTPCclusterMI*>(rowClusterArray.At(sortedClusterIndex[icl0]));
if (!cl0) continue;
Int_t nclPad=0;
//for (Int_t icl1=0; icl1<ncl;icl1++){ // second loop over clusters
// RS: time increases with index since sorted -> cl0->GetTimeBin()>cl1->GetTimeBin() means that icl0>icl1
for (Int_t icl1=0; icl1<icl0;icl1++){ // second loop over clusters
AliTPCclusterMI *cl1= rowClusterArray[sortedClusterIndex[icl1]];//RS static_cast<AliTPCclusterMI*>(rowClusterArray.At(sortedClusterIndex[icl1]));
if (!cl1) continue;
// RS no needed with proper loop organization
//if (cl0->GetTimeBin()<= cl1->GetTimeBin()) continue; // no contibution to the tail if later
int dpad = TMath::Abs(cl0->GetPad()-cl1->GetPad());
if (dpad>4) continue; // no contribution if far away in pad direction
// RS no point in iterating further with sorted clusters once large distance reached
if (cl0->GetTimeBin()-cl1->GetTimeBin()>600) continue; // out of the range of response function
// RS: what about dpad=4?
if (dpad<4) nclPad++; // count ncl for every pad for debugging
// Get the correction values for Qmax and Qtot and find total correction for a given cluster
Double_t ionTailMax=0.;
Double_t ionTailTotal=0.;
GetTailValue(ampfactor,ionTailMax,ionTailTotal,graphRes,indexAmpGraphs,cl0,cl1);
ionTailMax=TMath::Abs(ionTailMax);
ionTailTotal=TMath::Abs(ionTailTotal);
qTotArray[icl0]+=ionTailTotal;
qMaxArray[icl0]+=ionTailMax;
// Dump some info for debugging while clusters are being corrected
if ((AliTPCReconstructor::StreamLevel()&kStreamIonTail)>0) { // flag: stream ion tail correction as applied to cluster
TTreeSRedirector &cstream = *fDebugStreamer;
if (gRandom->Rndm() > 0.999){
cstream<<"IonTail"<<
"cl0.=" <<cl0 << // cluster 0 (to be corrected)
"cl1.=" <<cl1 << // cluster 1 (previous cluster)
"ionTailTotal=" <<ionTailTotal << // ion Tail from cluster 1 contribution to cluster0
"ionTailMax=" <<ionTailMax << // ion Tail from cluster 1 contribution to cluster0
"\n";
}
}// dump the results to the debug streamer if in debug mode
}//end of second loop over clusters
// Set corrected values of the corrected cluster
cl0->SetQ(TMath::Nint(Float_t(cl0->GetQ())+Float_t(qTotArray[icl0])));
cl0->SetMax(TMath::Nint(Float_t(cl0->GetMax())+qMaxArray[icl0]));
// Dump some info for debugging after clusters are corrected
if ((AliTPCReconstructor::StreamLevel()&kStreamIonTail)>0) {
TTreeSRedirector &cstream = *fDebugStreamer;
if (gRandom->Rndm() > 0.999){
cstream<<"IonTailCorrected"<<
"cl0.=" << cl0 << // cluster 0 with huge Qmax
"ionTailTotalPerCluster=" << qTotArray[icl0] <<
"ionTailMaxPerCluster=" << qMaxArray[icl0] <<
"nclALL=" << nclALL <<
"nclSector=" << nclSector <<
"nclRow=" << ncl <<
"nclPad=" << nclPad <<
"row=" << row <<
"sector=" << sec <<
"icl0=" << icl0 <<
"\n";
}
}// dump the results to the debug streamer if in debug mode
}//end of first loop over cluster
// delete rowClusterArray; // RS was moved to stack allocation
}//end of loop over rows
for (int i=0; i<20; i++) delete graphRes[i];
// delete [] graphRes; //RS was changed to stack allocation
// delete [] indexAmpGraphs;
}//end of loop over sectors
}//end of loop over IROC/OROC
}// end of side loop
sw.Stop();
AliInfoF("timing: %e/%e real/cpu",sw.RealTime(),sw.CpuTime());
//
}
//_____________________________________________________________________________
void AliTPCtracker::GetTailValue(Float_t ampfactor,Double_t &ionTailMax, Double_t &ionTailTotal,TGraphErrors **graphRes,Float_t *indexAmpGraphs,AliTPCclusterMI *cl0,AliTPCclusterMI *cl1){
//
// Function in order to calculate the amount of the correction to be added for a given cluster, return values are ionTailTaoltal and ionTailMax
// Parameters:
// cl0 - cluster to be modified
// cl1 - source cluster ion tail of this cluster will be added to the cl0 (accroding time and pad response function)
//
const Double_t kMinPRF = 0.5; // minimal PRF width
ionTailTotal = 0.; // correction value to be added to Qtot of cl0
ionTailMax = 0.; // correction value to be added to Qmax of cl0
Float_t qTot0 = cl0->GetQ(); // cl0 Qtot info
Float_t qTot1 = cl1->GetQ(); // cl1 Qtot info
Int_t sectorPad = cl1->GetDetector(); // sector number
Int_t padcl0 = TMath::Nint(cl0->GetPad()); // pad0
Int_t padcl1 = TMath::Nint(cl1->GetPad()); // pad1
Float_t padWidth = (sectorPad < 36)?0.4:0.6; // pad width in cm
const Int_t deltaTimebin = TMath::Nint(TMath::Abs(cl1->GetTimeBin()-cl0->GetTimeBin()))+12; //distance between pads of cl1 and cl0 increased by 12 bins
Double_t rmsPad1I = (cl1->GetSigmaY2()==0)?0.5/kMinPRF:(0.5*padWidth/TMath::Sqrt(cl1->GetSigmaY2()));
Double_t rmsPad0I = (cl0->GetSigmaY2()==0)?0.5/kMinPRF:(0.5*padWidth/TMath::Sqrt(cl0->GetSigmaY2()));
// RS avoid useless calculations
//Double_t sumAmp1=0.;
//for (Int_t idelta =-2; idelta<=2;idelta++){
// sumAmp1+=TMath::Exp(-idelta*idelta*rmsPad1I);
//}
// Double_t sumAmp0=0.;
//for (Int_t idelta =-2; idelta<=2;idelta++){
// sumAmp0+=TMath::Exp(-idelta*idelta*rmsPad0I));
//}
double tmp = TMath::Exp(-rmsPad1I);
double sumAmp1 = 1.+2.*tmp*(1.+tmp*tmp*tmp);
tmp = TMath::Exp(-rmsPad0I);
double sumAmp0 = 1.+2.*tmp*(1.+tmp*tmp*tmp);
// Apply the correction --> cl1 corrects cl0 (loop over cl1's pads and find which pads of cl0 are going to be corrected)
Int_t padScan=2; // +-2 pad-timebin window will be scanned
for (Int_t ipad1=padcl1-padScan; ipad1<=padcl1+padScan; ipad1++) {
//
//
Float_t deltaPad1 = TMath::Abs(cl1->GetPad()-(Float_t)ipad1);
Double_t amp1 = TMath::Exp(-(deltaPad1*deltaPad1)*rmsPad1I)/sumAmp1; // normalized pad response function
Float_t qTotPad1 = amp1*qTot1; // used as a factor to multipliy the response function
// find closest value of cl1 to COG (among the time response functions' amplitude array --> to select proper t.r.f.)
Int_t ampIndex = 0;
Float_t diffAmp = TMath::Abs(deltaPad1-indexAmpGraphs[0]);
for (Int_t j=0;j<20;j++) {
if (diffAmp > TMath::Abs(deltaPad1-indexAmpGraphs[j]) && indexAmpGraphs[j]!=0)
{
diffAmp = TMath::Abs(deltaPad1-indexAmpGraphs[j]);
ampIndex = j;
}
}
if (!graphRes[ampIndex]) continue;
if (deltaTimebin+2 >= graphRes[ampIndex]->GetN()) continue;
if (graphRes[ampIndex]->GetY()[deltaTimebin+2]>=0) continue;
for (Int_t ipad0=padcl0-padScan; ipad0<=padcl0+padScan; ipad0++) {
//
//
if (ipad1!=ipad0) continue; // check if ipad1 channel sees ipad0 channel, if not no correction to be applied.
Float_t deltaPad0 = TMath::Abs(cl0->GetPad()-(Float_t)ipad0);
Double_t amp0 = TMath::Exp(-(deltaPad0*deltaPad0)*rmsPad0I)/sumAmp0; // normalized pad resp function
Float_t qMaxPad0 = amp0*qTot0;
// Add 5 timebin range contribution around the max peak (-+2 tb window)
for (Int_t itb=deltaTimebin-2; itb<=deltaTimebin+2; itb++) {
if (itb<0) continue;
if (itb>=graphRes[ampIndex]->GetN()) continue;
// calculate contribution to qTot
Float_t tailCorr = TMath::Abs((qTotPad1*ampfactor)*(graphRes[ampIndex])->GetY()[itb]);
if (ipad1!=padcl0) {
ionTailTotal += TMath::Min(qMaxPad0,tailCorr); // for side pad
} else {
ionTailTotal += tailCorr; // for center pad
}
// calculate contribution to qMax
if (itb == deltaTimebin && ipad1 == padcl0) ionTailMax += tailCorr;
} // end of tb correction loop which is applied over 5 tb range
} // end of cl0 loop
} // end of cl1 loop
}
//_____________________________________________________________________________
Int_t AliTPCtracker::LoadOuterSectors() {
//-----------------------------------------------------------------
// This function fills outer TPC sectors with clusters.
//-----------------------------------------------------------------
Int_t nrows = fOuterSec->GetNRows();
UInt_t index=0;
for (Int_t sec = 0;sec<fkNOS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fOuterSec[sec%fkNOS][row]);
Int_t sec2 = sec+2*fkNIS;
//left
Int_t ncl = tpcrow->GetN1();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster1(ncl));
index=(((sec2<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//right
ncl = tpcrow->GetN2();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster2(ncl));
index=((((sec2+fkNOS)<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//
// write indexes for fast acces
//
for (Int_t i=510;i--;) tpcrow->SetFastCluster(i,-1);
for (Int_t i=0;i<tpcrow->GetN();i++){
Int_t zi = Int_t((*tpcrow)[i]->GetZ()+255.);
tpcrow->SetFastCluster(zi,i); // write index
}
Int_t last = 0;
for (Int_t i=0;i<510;i++){
if (tpcrow->GetFastCluster(i)<0)
tpcrow->SetFastCluster(i,last);
else
last = tpcrow->GetFastCluster(i);
}
}
fN=fkNOS;
fSectors=fOuterSec;
return 0;
}
//_____________________________________________________________________________
Int_t AliTPCtracker::LoadInnerSectors() {
//-----------------------------------------------------------------
// This function fills inner TPC sectors with clusters.
//-----------------------------------------------------------------
Int_t nrows = fInnerSec->GetNRows();
UInt_t index=0;
for (Int_t sec = 0;sec<fkNIS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fInnerSec[sec%fkNIS][row]);
//
//left
Int_t ncl = tpcrow->GetN1();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster1(ncl));
index=(((sec<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//right
ncl = tpcrow->GetN2();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster2(ncl));
index=((((sec+fkNIS)<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//
// write indexes for fast acces
//
for (Int_t i=0;i<510;i++)
tpcrow->SetFastCluster(i,-1);
for (Int_t i=0;i<tpcrow->GetN();i++){
Int_t zi = Int_t((*tpcrow)[i]->GetZ()+255.);
tpcrow->SetFastCluster(zi,i); // write index
}
Int_t last = 0;
for (Int_t i=0;i<510;i++){
if (tpcrow->GetFastCluster(i)<0)
tpcrow->SetFastCluster(i,last);
else
last = tpcrow->GetFastCluster(i);
}
}
fN=fkNIS;
fSectors=fInnerSec;
return 0;
}
//_________________________________________________________________________
AliTPCclusterMI *AliTPCtracker::GetClusterMI(Int_t index) const {
//--------------------------------------------------------------------
// Return pointer to a given cluster
//--------------------------------------------------------------------
if (index<0) return 0; // no cluster
Int_t sec=(index&0xff000000)>>24;
Int_t row=(index&0x00ff0000)>>16;
Int_t ncl=(index&0x00007fff)>>00;
const AliTPCtrackerRow * tpcrow=0;
TClonesArray * clrow =0;
if (sec<0 || sec>=fkNIS*4) {
AliWarning(Form("Wrong sector %d",sec));
return 0x0;
}
if (sec<fkNIS*2){
AliTPCtrackerSector& tracksec = fInnerSec[sec%fkNIS];
if (tracksec.GetNRows()<=row) return 0;
tpcrow = &(tracksec[row]);
if (tpcrow==0) return 0;
if (sec<fkNIS) {
if (tpcrow->GetN1()<=ncl) return 0;
clrow = tpcrow->GetClusters1();
}
else {
if (tpcrow->GetN2()<=ncl) return 0;
clrow = tpcrow->GetClusters2();
}
}
else {
AliTPCtrackerSector& tracksec = fOuterSec[(sec-fkNIS*2)%fkNOS];
if (tracksec.GetNRows()<=row) return 0;
tpcrow = &(tracksec[row]);
if (tpcrow==0) return 0;
if (sec-2*fkNIS<fkNOS) {
if (tpcrow->GetN1()<=ncl) return 0;
clrow = tpcrow->GetClusters1();
}
else {
if (tpcrow->GetN2()<=ncl) return 0;
clrow = tpcrow->GetClusters2();
}
}
return (AliTPCclusterMI*)clrow->At(ncl);
}
Int_t AliTPCtracker::FollowToNext(AliTPCseed& t, Int_t nr) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation to next pad row
//-----------------------------------------------------------------
//
const double kRoadY = 1., kRoadZ = 1.;
Double_t x= GetXrow(nr), ymax=GetMaxY(nr);
//
//
AliTPCclusterMI *cl=0;
Int_t tpcindex= t.GetClusterIndex2(nr);
//
// update current shape info every 5 pad-row
// if ( (nr%5==0) || t.GetNumberOfClusters()<2 || (t.fCurrentSigmaY2<0.0001) ){
GetShape(&t,nr);
//}
//
if (fIteration>0 && tpcindex>=-1){ //if we have already clusters
//
if (tpcindex==-1) return 0; //track in dead zone
if (tpcindex >= 0){ //
cl = t.GetClusterPointer(nr); // cluster might not be there during track finding, but is attached in refits
if (cl==0) cl = GetClusterMI(tpcindex);
t.SetCurrentClusterIndex1(tpcindex);
}
if (cl){
Int_t relativesector = ((tpcindex&0xff000000)>>24)%18; // if previously accepted cluster in different sector
Float_t angle = relativesector*fSectors->GetAlpha()+fSectors->GetAlphaShift();
//
if (angle<-TMath::Pi()) angle += 2*TMath::Pi();
if (angle>=TMath::Pi()) angle -= 2*TMath::Pi();
if (TMath::Abs(angle-t.GetAlpha())>0.001){
Double_t rotation = angle-t.GetAlpha();
t.SetRelativeSector(relativesector);
if (!t.Rotate(rotation)) {
t.SetClusterIndex(nr, t.GetClusterIndex(nr) | 0x8000);
return 0;
}
}
if (!t.PropagateTo(cl->GetX())) { // RS: go directly to cluster X
t.SetClusterIndex(nr, t.GetClusterIndex(nr) | 0x8000);
return 0;
}
//
t.SetCurrentCluster(cl);
t.SetRow(nr);
Int_t accept = AcceptCluster(&t,t.GetCurrentCluster());
if ((tpcindex&0x8000)==0) accept =0;
if (accept<3) {
//if founded cluster is acceptible
if (cl->IsUsed(11)) { // id cluster is shared inrease uncertainty
t.SetErrorY2(t.GetErrorY2()+0.03);
t.SetErrorZ2(t.GetErrorZ2()+0.03);
t.SetErrorY2(t.GetErrorY2()*3);
t.SetErrorZ2(t.GetErrorZ2()*3);
}
t.SetNFoundable(t.GetNFoundable()+1);
UpdateTrack(&t,accept);
return 1;
}
else { // Remove old cluster from track
t.SetClusterIndex(nr, -3);
//RS t.SetClusterPointer(nr, 0);
}
}
}
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()) return 0; // cut on angle
if (fIteration>1 && IsFindable(t)){
// not look for new cluster during refitting
t.SetNFoundable(t.GetNFoundable()+1);
return 0;
}
//
UInt_t index=0;
// if (TMath::Abs(t.GetSnp())>0.95 || TMath::Abs(x*t.GetC()-t.GetEta())>0.95) return 0;// patch 28 fev 06
//
if (fAccountDistortions && !DistortX(&t,x,nr)) {
if (fIteration==0) t.SetRemoval(10);
return 0;
}
if (!t.PropagateTo(x)) {
if (fIteration==0) t.SetRemoval(10);
return 0;
}
//
Double_t y = t.GetY();
ymax = x*AliTPCTransform::GetMaxY2X();
if (TMath::Abs(y)>ymax){
if (y > ymax) {
t.SetRelativeSector((t.GetRelativeSector()+1) % fN);
if (!t.Rotate(fSectors->GetAlpha()))
return 0;
} else if (y <-ymax) {
t.SetRelativeSector((t.GetRelativeSector()-1+fN) % fN);
if (!t.Rotate(-fSectors->GetAlpha()))
return 0;
}
x = GetXrow(nr);
if (fAccountDistortions && !DistortX(&t,x,nr)) {
if (fIteration==0) t.SetRemoval(10);
return 0;
}
if (!t.PropagateTo(x)) { //RS:? to check: here we may have back and forth prop. Use PropagateParamOnly?
if (fIteration==0) t.SetRemoval(10);
return 0;
}
y = t.GetY();
ymax = x*AliTPCTransform::GetMaxY2X();
}
//
Double_t z=t.GetZ();
//
if (!IsActive(t.GetRelativeSector(),nr)) { // RS:? How distortions affect this
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
//AliInfo(Form("A - Sector%d phi %f - alpha %f", t.fRelativeSector,y/x, t.GetAlpha()));
Bool_t isActive = IsActive(t.GetRelativeSector(),nr); //RS:? Why do we check this again?
Bool_t isActive2 = (nr>=fInnerSec->GetNRows()) ?
fOuterSec[t.GetRelativeSector()][nr-fInnerSec->GetNRows()].GetN()>0 :
fInnerSec[t.GetRelativeSector()][nr].GetN()>0;
if (!isActive || !isActive2) return 0;
const AliTPCtrackerRow &krow=GetRow(t.GetRelativeSector(),nr);
if ( (t.GetSigmaY2()<0) || t.GetSigmaZ2()<0) return 0;
//
// RS:? This check must be modified: with distortions the dead zone is not well defined
if (TMath::Abs(TMath::Abs(y)-ymax)<krow.GetDeadZone()){
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
else {
if (IsFindable(t))
// if (TMath::Abs(z)<(AliTPCReconstructor::GetCtgRange()*x+10) && TMath::Abs(z)<fkParam->GetZLength(0) && (TMath::Abs(t.GetSnp())<AliTPCReconstructor::GetMaxSnpTracker()))
t.SetNFoundable(t.GetNFoundable()+1);
else
return 0;
}
//calculate
if (krow) {
// cl = krow.FindNearest2(y+10.,z,roady,roadz,index);
cl = krow.FindNearest2(y,z,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,index);
if (cl) t.SetCurrentClusterIndex1(krow.GetIndex(index));
}
if (cl) {
t.SetCurrentCluster(cl);
t.SetRow(nr);
if (fIteration==2&&cl->IsUsed(10)) return 0;
Int_t accept = AcceptCluster(&t,t.GetCurrentCluster());
if (fIteration==2&&cl->IsUsed(11)) {
t.SetErrorY2(t.GetErrorY2()+0.03);
t.SetErrorZ2(t.GetErrorZ2()+0.03);
t.SetErrorY2(t.GetErrorY2()*3);
t.SetErrorZ2(t.GetErrorZ2()*3);
}
/*
if (t.fCurrentCluster->IsUsed(10)){
//
//
t.fNShared++;
if (t.fNShared>0.7*t.GetNumberOfClusters()) {
t.fRemoval =10;
return 0;
}
}
*/
if (accept<3) UpdateTrack(&t,accept);
} else {
if ( fIteration==0 && t.GetNFoundable()*0.5 > t.GetNumberOfClusters()) t.SetRemoval(10);
}
return 1;
}
//_________________________________________________________________________
Bool_t AliTPCtracker::GetTrackPoint(Int_t index, AliTrackPoint &p ) const
{
// Get track space point by index
// return false in case the cluster doesn't exist
AliTPCclusterMI *cl = GetClusterMI(index);
if (!cl) return kFALSE;
Int_t sector = (index&0xff000000)>>24;
// Int_t row = (index&0x00ff0000)>>16;
Float_t xyz[3];
// xyz[0] = fkParam->GetPadRowRadii(sector,row);
xyz[0] = cl->GetX();
xyz[1] = cl->GetY();
xyz[2] = cl->GetZ();
Float_t sin,cos;
fkParam->AdjustCosSin(sector,cos,sin);
Float_t x = cos*xyz[0]-sin*xyz[1];
Float_t y = cos*xyz[1]+sin*xyz[0];
Float_t cov[6];
Float_t sigmaY2 = 0.027*cl->GetSigmaY2();
if (sector < fkParam->GetNInnerSector()) sigmaY2 *= 2.07;
Float_t sigmaZ2 = 0.066*cl->GetSigmaZ2();
if (sector < fkParam->GetNInnerSector()) sigmaZ2 *= 1.77;
cov[0] = sin*sin*sigmaY2;
cov[1] = -sin*cos*sigmaY2;
cov[2] = 0.;
cov[3] = cos*cos*sigmaY2;
cov[4] = 0.;
cov[5] = sigmaZ2;
p.SetXYZ(x,y,xyz[2],cov);
AliGeomManager::ELayerID iLayer;
Int_t idet;
if (sector < fkParam->GetNInnerSector()) {
iLayer = AliGeomManager::kTPC1;
idet = sector;
}
else {
iLayer = AliGeomManager::kTPC2;
idet = sector - fkParam->GetNInnerSector();
}
UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,idet);
p.SetVolumeID(volid);
return kTRUE;
}
Int_t AliTPCtracker::UpdateClusters(AliTPCseed& t, Int_t nr) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation to next pad row
//-----------------------------------------------------------------
t.SetCurrentCluster(0);
t.SetCurrentClusterIndex1(-3);
Double_t xt=t.GetX();
Int_t row = GetRowNumber(xt)-1;
Double_t ymax= GetMaxY(nr);
if (row < nr) return 1; // don't prolongate if not information until now -
// if (TMath::Abs(t.GetSnp())>0.9 && t.GetNumberOfClusters()>40. && fIteration!=2) {
// t.fRemoval =10;
// return 0; // not prolongate strongly inclined tracks
// }
// if (TMath::Abs(t.GetSnp())>0.95) {
// t.fRemoval =10;
// return 0; // not prolongate strongly inclined tracks
// }// patch 28 fev 06
const double kRoadY = 1., kRoadZ = 1.;
Double_t x= GetXrow(nr);
Double_t y,z;
//t.PropagateTo(x+0.02);
//t.PropagateTo(x+0.01);
if (!t.PropagateTo(x)){
return 0;
}
//
y=t.GetY();
z=t.GetZ();
if (TMath::Abs(y)>ymax){
if (y > ymax) {
t.SetRelativeSector((t.GetRelativeSector()+1) % fN);
if (!t.Rotate(fSectors->GetAlpha()))
return 0;
} else if (y <-ymax) {
t.SetRelativeSector((t.GetRelativeSector()-1+fN) % fN);
if (!t.Rotate(-fSectors->GetAlpha()))
return 0;
}
// if (!t.PropagateTo(x)){
// return 0;
//}
return 1;
//y = t.GetY();
}
//
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()) return 0;
if (!IsActive(t.GetRelativeSector(),nr)) {
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
//AliInfo(Form("A - Sector%d phi %f - alpha %f", t.fRelativeSector,y/x, t.GetAlpha()));
AliTPCtrackerRow &krow=GetRow(t.GetRelativeSector(),nr);
if (TMath::Abs(TMath::Abs(y)-ymax)<krow.GetDeadZone()){
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
else
{
// if (TMath::Abs(t.GetZ())<(AliTPCReconstructor::GetCtgRange()*t.GetX()+10) && (TMath::Abs(t.GetSnp())<AliTPCReconstructor::GetMaxSnpTracker()))
if (IsFindable(t)) t.SetNFoundable(t.GetNFoundable()+1);
else
return 0;
}
// update current
if ( (nr%2==0) || t.GetNumberOfClusters()<2){
// t.fCurrentSigmaY = GetSigmaY(&t);
//t.fCurrentSigmaZ = GetSigmaZ(&t);
GetShape(&t,nr);
}
AliTPCclusterMI *cl=0;
Int_t index=0;
//
Double_t roady = 1.;
Double_t roadz = 1.;
//
if (!cl){
index = t.GetClusterIndex2(nr);
if ( (index >= 0) && (index&0x8000)==0){
//RS cl = t.GetClusterPointer(nr);
//RS if ( (cl==0) && (index >= 0)) cl = GetClusterMI(index);
if ( index >= 0 ) cl = GetClusterMI(index);
t.SetCurrentClusterIndex1(index);
if (cl) {
t.SetCurrentCluster(cl);
return 1;
}
}
}
// if (index<0) return 0;
UInt_t uindex = TMath::Abs(index);
if (krow) {
//cl = krow.FindNearest2(y+10,z,roady,roadz,uindex);
cl = krow.FindNearest2(y,z,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,uindex);
}
if (cl) t.SetCurrentClusterIndex1(krow.GetIndex(uindex));
t.SetCurrentCluster(cl);
return 1;
}
Int_t AliTPCtracker::FollowToNextCluster(AliTPCseed & t, Int_t nr) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation to next pad row
//-----------------------------------------------------------------
//update error according neighborhoud
if (t.GetCurrentCluster()) {
t.SetRow(nr);
Int_t accept = AcceptCluster(&t,t.GetCurrentCluster());
if (t.GetCurrentCluster()->IsUsed(10)){
//
//
// t.fErrorZ2*=2;
// t.fErrorY2*=2;
t.SetNShared(t.GetNShared()+1);
if (t.GetNShared()>0.7*t.GetNumberOfClusters()) {
t.SetRemoval(10);
return 0;
}
}
if (fIteration>0) accept = 0;
if (accept<3) UpdateTrack(&t,accept);
} else {
if (fIteration==0){
if ( t.GetNumberOfClusters()>18 && ( (t.GetSigmaY2()+t.GetSigmaZ2())>0.16 + fExtraClErrYZ2 )) t.SetRemoval(10);
if ( t.GetNumberOfClusters()>18 && t.GetChi2()/t.GetNumberOfClusters()>6 ) t.SetRemoval(10);
if (( (t.GetNFoundable()*0.5 > t.GetNumberOfClusters()) || t.GetNoCluster()>15)) t.SetRemoval(10);
}
}
return 1;
}
//_____________________________________________________________________________
Int_t AliTPCtracker::FollowProlongation(AliTPCseed& t, Int_t rf, Int_t step, Bool_t fromSeeds) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation.
//-----------------------------------------------------------------
Double_t xt=t.GetX();
//
Double_t alpha=t.GetAlpha();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
//
t.SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
Int_t first = GetRowNumber(xt);
if (!fromSeeds)
first -= step;
if (first < 0)
first = 0;
for (Int_t nr= first; nr>=rf; nr-=step) {
// update kink info
if (t.GetKinkIndexes()[0]>0){
for (Int_t i=0;i<3;i++){
Int_t index = t.GetKinkIndexes()[i];
if (index==0) break;
if (index<0) continue;
//
AliKink * kink = (AliKink*)fEvent->GetKink(index-1);
if (!kink){
printf("PROBLEM\n");
}
else{
Int_t kinkrow = kink->GetTPCRow0()+2+Int_t(0.5/(0.05+kink->GetAngle(2)));
if (kinkrow==nr){
AliExternalTrackParam paramd(t);
kink->SetDaughter(paramd);
kink->SetStatus(2,5);
kink->Update();
}
}
}
}
if (nr==80) t.UpdateReference();
if (nr<fInnerSec->GetNRows())
fSectors = fInnerSec;
else
fSectors = fOuterSec;
if (FollowToNext(t,nr)==0)
if (!t.IsActive())
return 0;
}
return 1;
}
Int_t AliTPCtracker::FollowBackProlongation(AliTPCseed& t, Int_t rf, Bool_t fromSeeds) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation.
//-----------------------------------------------------------------
//
Double_t xt=t.GetX();
Double_t alpha=t.GetAlpha();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
t.SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
Int_t first = t.GetFirstPoint();
Int_t ri = GetRowNumber(xt);
// if (!fromSeeds) ri += 1;
if (xt<0) ri += 1; // RS
if (first<ri) first = ri;
//
if (first<0) first=0;
for (Int_t nr=first; nr<=rf; nr++) {
// if ( (TMath::Abs(t.GetSnp())>0.95)) break;//patch 28 fev 06
if (t.GetKinkIndexes()[0]<0){
for (Int_t i=0;i<3;i++){
Int_t index = t.GetKinkIndexes()[i];
if (index==0) break;
if (index>0) continue;
index = TMath::Abs(index);
AliKink * kink = (AliKink*)fEvent->GetKink(index-1);
if (!kink){
printf("PROBLEM\n");
}
else{
Int_t kinkrow = kink->GetTPCRow0()-2-Int_t(0.5/(0.05+kink->GetAngle(2)));
if (kinkrow==nr){
AliExternalTrackParam paramm(t);
kink->SetMother(paramm);
kink->SetStatus(2,1);
kink->Update();
}
}
}
}
//
if (nr<fInnerSec->GetNRows())
fSectors = fInnerSec;
else
fSectors = fOuterSec;
FollowToNext(t,nr);
}
return 1;
}
Float_t AliTPCtracker::OverlapFactor(AliTPCseed * s1, AliTPCseed * s2, Int_t &sum1, Int_t & sum2)
{
// overlapping factor
//
sum1=0;
sum2=0;
Int_t sum=0;
//
Float_t dz2 =(s1->GetZ() - s2->GetZ());
dz2*=dz2;
Float_t dy2 =TMath::Abs((s1->GetY() - s2->GetY()));
dy2*=dy2;
Float_t distance = TMath::Sqrt(dz2+dy2);
if (distance>4.) return 0; // if there are far away - not overlap - to reduce combinatorics
// Int_t offset =0;
Int_t firstpoint = TMath::Min(s1->GetFirstPoint(),s2->GetFirstPoint());
Int_t lastpoint = TMath::Max(s1->GetLastPoint(),s2->GetLastPoint());
if (lastpoint>=kMaxRow)
lastpoint = kMaxRow-1;
if (firstpoint<0)
firstpoint = 0;
if (firstpoint>lastpoint) {
firstpoint =lastpoint;
// lastpoint = kMaxRow-1;
}
// for (Int_t i=firstpoint-1;i<lastpoint+1;i++){
// if (s1->GetClusterIndex2(i)>0) sum1++;
// if (s2->GetClusterIndex2(i)>0) sum2++;
// if (s1->GetClusterIndex2(i)==s2->GetClusterIndex2(i) && s1->GetClusterIndex2(i)>0) {
// sum++;
// }
// }
// RS: faster version + fix(?): clusterindex starts from 0
for (Int_t i=firstpoint-1;i<lastpoint+1;i++){
int ind1=s1->GetClusterIndex2(i), ind2=s2->GetClusterIndex2(i);
if (ind1>=0) sum1++;
if (ind2>=0) sum2++;
if (ind1==ind2 && ind1>=0) sum++;
}
if (sum<5) return 0;
Float_t summin = TMath::Min(sum1+1,sum2+1);
Float_t ratio = (sum+1)/Float_t(summin);
return ratio;
}
void AliTPCtracker::SignShared(AliTPCseed * s1, AliTPCseed * s2)
{
// shared clusters
//
Float_t thetaCut = 0.2;//+10.*TMath::Sqrt(s1->GetSigmaTglZ()+ s2->GetSigmaTglZ());
if (TMath::Abs(s1->GetTgl()-s2->GetTgl())>thetaCut) return;
Float_t minCl = TMath::Min(s1->GetNumberOfClusters(),s2->GetNumberOfClusters());
Int_t cutN0 = TMath::Max(5,TMath::Nint(0.1*minCl));
//
Int_t sumshared=0;
//
//Int_t firstpoint = TMath::Max(s1->GetFirstPoint(),s2->GetFirstPoint());
//Int_t lastpoint = TMath::Min(s1->GetLastPoint(),s2->GetLastPoint());
Int_t firstpoint = 0;
Int_t lastpoint = kMaxRow;
//
// if (firstpoint>=lastpoint-5) return;;
for (Int_t i=firstpoint;i<lastpoint;i++){
// if ( (s1->GetClusterIndex2(i)&0xFFFF8FFF)==(s2->GetClusterIndex2(i)&0xFFFF8FFF) && s1->GetClusterIndex2(i)>0) {
if ( (s1->GetClusterIndex2(i))==(s2->GetClusterIndex2(i)) && s1->GetClusterIndex2(i)>=0) {
sumshared++;
}
}
if (sumshared>cutN0){
// sign clusters
//
for (Int_t i=firstpoint;i<lastpoint;i++){
// if ( (s1->GetClusterIndex2(i)&0xFFFF8FFF)==(s2->GetClusterIndex2(i)&0xFFFF8FFF) && s1->GetClusterIndex2(i)>0) {
if ( (s1->GetClusterIndex2(i))==(s2->GetClusterIndex2(i)) && s1->GetClusterIndex2(i)>=0) {
const AliTPCTrackerPoints::Point *p1 = s1->GetTrackPoint(i);
const AliTPCTrackerPoints::Point *p2 = s2->GetTrackPoint(i);;
if (s1->IsActive()&&s2->IsActive()){
s1->SetShared(i);
s2->SetShared(i);
}
}
}
}
//
if (sumshared>cutN0){
for (Int_t i=0;i<4;i++){
if (s1->GetOverlapLabel(3*i)==0){
s1->SetOverlapLabel(3*i, s2->GetLabel());
s1->SetOverlapLabel(3*i+1,sumshared);
s1->SetOverlapLabel(3*i+2,s2->GetUniqueID());
break;
}
}
for (Int_t i=0;i<4;i++){
if (s2->GetOverlapLabel(3*i)==0){
s2->SetOverlapLabel(3*i, s1->GetLabel());
s2->SetOverlapLabel(3*i+1,sumshared);
s2->SetOverlapLabel(3*i+2,s1->GetUniqueID());
break;
}
}
}
}
void AliTPCtracker::SignShared(TObjArray * arr)
{
//
//sort trackss according sectors
//
for (Int_t i=0; i<arr->GetEntriesFast(); i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
//if (pt) RotateToLocal(pt);
pt->SetSort(0);
}
arr->UnSort();
arr->Sort(); // sorting according relative sectors
arr->Expand(arr->GetEntries());
//
//
Int_t nseed=arr->GetEntriesFast();
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
for (Int_t j=0;j<12;j++){
pt->SetOverlapLabel(j,0);
}
}
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
if (pt->GetRemoval()>10) continue;
for (Int_t j=i+1; j<nseed; j++){
AliTPCseed *pt2=(AliTPCseed*)arr->UncheckedAt(j);
if (TMath::Abs(pt->GetRelativeSector()-pt2->GetRelativeSector())>1) continue;
// if (pt2){
if (pt2->GetRemoval()<=10) {
//if ( TMath::Abs(pt->GetRelativeSector()-pt2->GetRelativeSector())>0) break;
SignShared(pt,pt2);
}
}
}
}
void AliTPCtracker::SortTracks(TObjArray * arr, Int_t mode) const
{
//
//sort tracks in array according mode criteria
Int_t nseed = arr->GetEntriesFast();
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
pt->SetSort(mode);
}
arr->UnSort();
arr->Sort();
}
void AliTPCtracker::RemoveUsed2(TObjArray * arr, Float_t factor1, Float_t factor2, Int_t minimal)
{
//
// Loop over all tracks and remove overlaped tracks (with lower quality)
// Algorithm:
// 1. Unsign clusters
// 2. Sort tracks according quality
// Quality is defined by the number of cluster between first and last points
//
// 3. Loop over tracks - decreasing quality order
// a.) remove - If the fraction of shared cluster less than factor (1- n or 2)
// b.) remove - If the minimal number of clusters less than minimal and not ITS
// c.) if track accepted - sign clusters
//
//Called in - AliTPCtracker::Clusters2Tracks()
// - AliTPCtracker::PropagateBack()
// - AliTPCtracker::RefitInward()
//
// Arguments:
// factor1 - factor for constrained
// factor2 - for non constrained tracks
// if (Float_t(shared+1)/Float_t(found+1)>factor) - DELETE
//
UnsignClusters();
//
Int_t nseed = arr->GetEntriesFast();
// Float_t quality = new Float_t[nseed];
// Int_t * indexes = new Int_t[nseed];
Float_t quality[nseed]; //RS Use stack allocations
Int_t indexes[nseed];
Int_t good =0;
//
//
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt){
quality[i]=-1;
continue;
}
pt->UpdatePoints(); //select first last max dens points
Float_t * points = pt->GetPoints();
if (points[3]<0.8) quality[i] =-1;
quality[i] = (points[2]-points[0])+pt->GetNumberOfClusters();
//prefer high momenta tracks if overlaps
quality[i] *= TMath::Sqrt(TMath::Abs(pt->Pt())+0.5);
}
TMath::Sort(nseed,quality,indexes);
//
//
for (Int_t itrack=0; itrack<nseed; itrack++) {
Int_t trackindex = indexes[itrack];
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(trackindex);
if (!pt) continue;
//
if (quality[trackindex]<0){
MarkSeedFree( arr->RemoveAt(trackindex) );
continue;
}
//
//
Int_t first = Int_t(pt->GetPoints()[0]);
Int_t last = Int_t(pt->GetPoints()[2]);
Double_t factor = (pt->GetBConstrain()) ? factor1: factor2;
//
Int_t found,foundable,shared;
GetSeedClusterStatistic(pt, first,last, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
//RS pt->GetClusterStatistic(first,last, found, foundable,shared,kFALSE); // better to get statistic in "high-dens" region do't use full track as in line bellow
//MI pt->GetClusterStatistic(0,kMaxRow, found, foundable,shared,kFALSE);
Bool_t itsgold =kFALSE;
if (pt->GetESD()){
Int_t dummy[12];
if (pt->GetESD()->GetITSclusters(dummy)>4) itsgold= kTRUE;
}
if (!itsgold){
//
if (Float_t(shared+1)/Float_t(found+1)>factor){
if (pt->GetKinkIndexes()[0]!=0) continue; //don't remove tracks - part of the kinks
if( (AliTPCReconstructor::StreamLevel()&kStreamRemoveUsed)>0){ // flag:stream information about TPC tracks which were descarded (double track removal)
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"RemoveUsed"<<
"iter="<<fIteration<<
"pt.="<<pt<<
"\n";
}
MarkSeedFree( arr->RemoveAt(trackindex) );
continue;
}
if (pt->GetNumberOfClusters()<50&&(found-0.5*shared)<minimal){ //remove short tracks
if (pt->GetKinkIndexes()[0]!=0) continue; //don't remove tracks - part of the kinks
if( (AliTPCReconstructor::StreamLevel()&kStreamRemoveShort)>0){ // flag:stream information about TPC tracks which were discarded (short track removal)
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"RemoveShort"<<
"iter="<<fIteration<<
"pt.="<<pt<<
"\n";
}
MarkSeedFree( arr->RemoveAt(trackindex) );
continue;
}
}
good++;
//if (sharedfactor>0.4) continue;
if (pt->GetKinkIndexes()[0]>0) continue;
//Remove tracks with undefined properties - seems
if (pt->GetSigmaY2()<kAlmost0) continue; // ? what is the origin ?
//
for (Int_t i=first; i<last; i++) {
Int_t index=pt->GetClusterIndex2(i);
// if (index<0 || index&0x8000 ) continue;
if (index<0 || index&0x8000 ) continue;
AliTPCclusterMI *c= GetClusterMI(index); //RS pt->GetClusterPointer(i);
if (!c) continue;
c->Use(10);
}
}
fNtracks = good;
if (fDebug>0){
Info("RemoveUsed","\n*****\nNumber of good tracks after shared removal\t%d\n",fNtracks);
}
// delete []quality; // RS was moved to stack allocation
// delete []indexes;
}
void AliTPCtracker::DumpClusters(Int_t iter, TObjArray *trackArray)
{
//
// Dump clusters after reco
// signed and unsigned cluster can be visualized
// 1. Unsign all cluster
// 2. Sign all used clusters
// 3. Dump clusters
UnsignClusters();
Int_t nseed = trackArray->GetEntries();
for (Int_t i=0; i<nseed; i++){
AliTPCseed *pt=(AliTPCseed*)trackArray->UncheckedAt(i);
if (!pt) {
continue;
}
Bool_t isKink=pt->GetKinkIndex(0)!=0;
for (Int_t j=0; j<kMaxRow; ++j) {
Int_t index=pt->GetClusterIndex2(j);
if (index<0) continue;
AliTPCclusterMI *c= GetClusterMI(index); //RS pt->GetClusterPointer(j);
if (!c) continue;
if (isKink) c->Use(100); // kink
c->Use(10); // by default usage 10
}
}
//
Int_t eventNr = fEvent->GetEventNumberInFile();
for (Int_t sec=0;sec<fkNIS;sec++){
for (Int_t row=0;row<fInnerSec->GetNRows();row++){
TClonesArray *cla = fInnerSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN1();icl++){
AliTPCclusterMI* cl = (AliTPCclusterMI*)cla->At(icl);
Float_t gx[3]; cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
cla = fInnerSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN2();icl++){
AliTPCclusterMI* cl = (AliTPCclusterMI*)cla->At(icl);
Float_t gx[3]; cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
}
}
for (Int_t sec=0;sec<fkNOS;sec++){
for (Int_t row=0;row<fOuterSec->GetNRows();row++){
TClonesArray *cla = fOuterSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN1();icl++){
Float_t gx[3];
AliTPCclusterMI* cl = (AliTPCclusterMI*) cla->At(icl);
cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
cla = fOuterSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN2();icl++){
Float_t gx[3];
AliTPCclusterMI* cl = (AliTPCclusterMI*) cla->At(icl);
cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
}
}
}
void AliTPCtracker::UnsignClusters()
{
//
// loop over all clusters and unsign them
//
for (Int_t sec=0;sec<fkNIS;sec++){
for (Int_t row=0;row<fInnerSec->GetNRows();row++){
TClonesArray *cla = fInnerSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN1();icl++)
// if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
cla = fInnerSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN2();icl++)
//if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
}
}
for (Int_t sec=0;sec<fkNOS;sec++){
for (Int_t row=0;row<fOuterSec->GetNRows();row++){
TClonesArray *cla = fOuterSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN1();icl++)
//if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
cla = fOuterSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN2();icl++)
//if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
}
}
}
void AliTPCtracker::SignClusters(const TObjArray * arr, Float_t fnumber, Float_t fdensity)
{
//
//sign clusters to be "used"
//
// snumber and sdensity sign number of sigmas - bellow mean value to be accepted
// loop over "primaries"
Float_t sumdens=0;
Float_t sumdens2=0;
Float_t sumn =0;
Float_t sumn2 =0;
Float_t sumchi =0;
Float_t sumchi2 =0;
Float_t sum =0;
TStopwatch timer;
timer.Start();
Int_t nseed = arr->GetEntriesFast();
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
if (!(pt->IsActive())) continue;
Float_t dens = pt->GetNumberOfClusters()/Float_t(pt->GetNFoundable());
if ( (dens>0.7) && (pt->GetNumberOfClusters()>70)){
sumdens += dens;
sumdens2+= dens*dens;
sumn += pt->GetNumberOfClusters();
sumn2 += pt->GetNumberOfClusters()*pt->GetNumberOfClusters();
Float_t chi2 = pt->GetChi2()/pt->GetNumberOfClusters();
if (chi2>5) chi2=5;
sumchi +=chi2;
sumchi2 +=chi2*chi2;
sum++;
}
}
Float_t mdensity = 0.9;
Float_t meann = 130;
Float_t meanchi = 1;
Float_t sdensity = 0.1;
Float_t smeann = 10;
Float_t smeanchi =0.4;
if (sum>20){
mdensity = sumdens/sum;
meann = sumn/sum;
meanchi = sumchi/sum;
//
sdensity = sumdens2/sum-mdensity*mdensity;
if (sdensity >= 0)
sdensity = TMath::Sqrt(sdensity);
else
sdensity = 0.1;
//
smeann = sumn2/sum-meann*meann;
if (smeann >= 0)
smeann = TMath::Sqrt(smeann);
else
smeann = 10;
//
smeanchi = sumchi2/sum - meanchi*meanchi;
if (smeanchi >= 0)
smeanchi = TMath::Sqrt(smeanchi);
else
smeanchi = 0.4;
}
//REMOVE SHORT DELTAS or tracks going out of sensitive volume of TPC
//
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
if (pt->GetBSigned()) continue;
if (pt->GetBConstrain()) continue;
//if (!(pt->IsActive())) continue;
/*
Int_t found,foundable,shared;
pt->GetClusterStatistic(0,kMaxRow,found, foundable,shared);
if (shared/float(found)>0.3) {
if (shared/float(found)>0.9 ){
//MarkSeedFree( arr->RemoveAt(i) );
}
continue;
}
*/
Bool_t isok =kFALSE;
if ( (pt->GetNShared()/pt->GetNumberOfClusters()<0.5) &&pt->GetNumberOfClusters()>60)
isok = kTRUE;
if ((TMath::Abs(1/pt->GetC())<100.) && (pt->GetNShared()/pt->GetNumberOfClusters()<0.7))
isok =kTRUE;
if (TMath::Abs(pt->GetZ()/pt->GetX())>1.1)
isok =kTRUE;
if ( (TMath::Abs(pt->GetSnp()>0.7) && pt->GetD(0,0)>60.))
isok =kTRUE;
if (isok)
for (Int_t j=0; j<kMaxRow; ++j) {
Int_t index=pt->GetClusterIndex2(j);
if (index<0) continue;
AliTPCclusterMI *c= GetClusterMI(index);//pt->GetClusterPointer(j);
if (!c) continue;
//if (!(c->IsUsed(10))) c->Use();
c->Use(10);
}
}
//
Double_t maxchi = meanchi+2.*smeanchi;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
//if (!(pt->IsActive())) continue;
if (pt->GetBSigned()) continue;
Double_t chi = pt->GetChi2()/pt->GetNumberOfClusters();
if (chi>maxchi) continue;
Float_t bfactor=1;
Float_t dens = pt->GetNumberOfClusters()/Float_t(pt->GetNFoundable());
//sign only tracks with enoug big density at the beginning
if ((pt->GetDensityFirst(40)<0.75) && pt->GetNumberOfClusters()<meann) continue;
Double_t mindens = TMath::Max(double(mdensity-sdensity*fdensity*bfactor),0.65);
Double_t minn = TMath::Max(Int_t(meann-fnumber*smeann*bfactor),50);
// if (pt->fBConstrain) mindens = TMath::Max(mdensity-sdensity*fdensity*bfactor,0.65);
if ( (pt->GetRemoval()==10) && (pt->GetSnp()>0.8)&&(dens>mindens))
minn=0;
if ((dens>mindens && pt->GetNumberOfClusters()>minn) && chi<maxchi ){
//Int_t noc=pt->GetNumberOfClusters();
pt->SetBSigned(kTRUE);
for (Int_t j=0; j<kMaxRow; ++j) {
Int_t index=pt->GetClusterIndex2(j);
if (index<0) continue;
AliTPCclusterMI *c= GetClusterMI(index); //RS pt->GetClusterPointer(j);
if (!c) continue;
// if (!(c->IsUsed(10))) c->Use();
c->Use(10);
}
}
}
// gLastCheck = nseed;
// arr->Compress();
if (fDebug>0){
timer.Print();
}
}
Int_t AliTPCtracker::RefitInward(AliESDEvent *event)
{
//
// back propagation of ESD tracks
//
//return 0;
if (!event) return 0;
fEvent = event;
fEventHLT = 0;
// extract correction object for multiplicity dependence of dEdx
TObjArray * gainCalibArray = AliTPCcalibDB::Instance()->GetTimeGainSplinesRun(event->GetRunNumber());
AliTPCTransform *transform = AliTPCcalibDB::Instance()->GetTransform() ;
if (!transform) {
AliFatal("Tranformations not in RefitInward");
return 0;
}
transform->SetCurrentRecoParam((AliTPCRecoParam*)AliTPCReconstructor::GetRecoParam());
const AliTPCRecoParam * recoParam = AliTPCcalibDB::Instance()->GetTransform()->GetCurrentRecoParam();
Int_t nContribut = event->GetNumberOfTracks();
TGraphErrors * graphMultDependenceDeDx = 0x0;
if (recoParam && recoParam->GetUseMultiplicityCorrectionDedx() && gainCalibArray) {
if (recoParam->GetUseTotCharge()) {
graphMultDependenceDeDx = (TGraphErrors *) gainCalibArray->FindObject("TGRAPHERRORS_MEANQTOT_MULTIPLICITYDEPENDENCE_BEAM_ALL");
} else {
graphMultDependenceDeDx = (TGraphErrors *) gainCalibArray->FindObject("TGRAPHERRORS_MEANQMAX_MULTIPLICITYDEPENDENCE_BEAM_ALL");
}
}
//
ReadSeeds(event,2);
fIteration=2;
//PrepareForProlongation(fSeeds,1);
PropagateForward2(fSeeds);
RemoveUsed2(fSeeds,0.4,0.4,20);
Int_t entriesSeed=fSeeds->GetEntries();
TObjArray arraySeed(entriesSeed);
for (Int_t i=0;i<entriesSeed;i++) {
arraySeed.AddAt(fSeeds->At(i),i);
}
SignShared(&arraySeed);
// FindCurling(fSeeds, event,2); // find multi found tracks
FindSplitted(fSeeds, event,2); // find multi found tracks
if ((AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC)>0) FindMultiMC(fSeeds, fEvent,2); // flag: stream MC infomation about the multiple find track (ONLY for MC data)
Int_t ntracks=0;
Int_t nseed = fSeeds->GetEntriesFast();
//
// RS: the cluster pointers are not permanently attached to the seed during the tracking, need to attach temporarily
AliTPCclusterMI* seedClusters[kMaxRow];
int seedsInFriends = 0;
int seedsInFriendsNorm = event->GetNTPCFriend2Store();
if (seedsInFriendsNorm>nseed) seedsInFriendsNorm = nseed; // all friends are stored
//
fClPointersPoolPtr = fClPointersPool;
//
for (Int_t i=0;i<nseed;i++) {
AliTPCseed * seed = (AliTPCseed*) fSeeds->UncheckedAt(i);
if (!seed) continue;
if (seed->GetKinkIndex(0)>0) UpdateKinkQualityD(seed); // update quality informations for kinks
AliESDtrack *esd=event->GetTrack(i);
//
//RS: if needed, attach temporary cluster array
const AliTPCclusterMI** seedClustersSave = seed->GetClusters();
if (!seedClustersSave) { //RS: temporary attach clusters
for (int ir=kMaxRow;ir--;) {
int idx = seed->GetClusterIndex2(ir);
seedClusters[ir] = idx<0 ? 0 : GetClusterMI(idx);
}
seed->SetClustersArrayTMP(seedClusters);
}
//
//
if (seed->GetNumberOfClusters()<60 && seed->GetNumberOfClusters()<(esd->GetTPCclusters(0) -5)*0.8) {
AliExternalTrackParam paramIn;
AliExternalTrackParam paramOut;
//
Int_t ncl = seed->RefitTrack(seed,¶mIn,¶mOut);
//
if ((AliTPCReconstructor::StreamLevel() & kStreamRecoverIn)>0) { // flag: stream track information for track failing in RefitInward function and recovered back
(*fDebugStreamer)<<"RecoverIn"<<
"seed.="<<seed<<
"esd.="<<esd<<
"pin.="<<¶mIn<<
"pout.="<<¶mOut<<
"ncl="<<ncl<<
"\n";
}
if (ncl>15) {
seed->Set(paramIn.GetX(),paramIn.GetAlpha(),paramIn.GetParameter(),paramIn.GetCovariance());
seed->SetNumberOfClusters(ncl);
}
}
seed->PropagateTo(fkParam->GetInnerRadiusLow());
seed->UpdatePoints();
AddCovariance(seed);
MakeESDBitmaps(seed, esd);
seed->CookdEdx(0.02,0.6);
CookLabel(seed,0.1); //For comparison only
//
if (((AliTPCReconstructor::StreamLevel()&kStreamRefitInward)>0) && seed!=0) {
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"RefitInward"<< // flag: stream track information in RefitInward function (after tracking Iteration 2)
"Esd.="<<esd<<
"Track.="<<seed<<
"\n";
}
if (seed->GetNumberOfClusters()>15) {
esd->UpdateTrackParams(seed,AliESDtrack::kTPCrefit);
esd->SetTPCPoints(seed->GetPoints());
esd->SetTPCPointsF(seed->GetNFoundable());
Int_t ndedx = seed->GetNCDEDX(0);
Float_t sdedx = seed->GetSDEDX(0);
Float_t dedx = seed->GetdEdx();
// apply mutliplicity dependent dEdx correction if available
if (graphMultDependenceDeDx) {
Double_t corrGain = AliTPCcalibDButil::EvalGraphConst(graphMultDependenceDeDx, nContribut);
dedx += (1 - corrGain)*50.; // MIP is normalized to 50
}
esd->SetTPCsignal(dedx, sdedx, ndedx);
//
// fill new dEdx information
//
Double32_t signal[4];
Double32_t signalMax[4];
Char_t ncl[3];
Char_t nrows[3];
//
for(Int_t iarr=0;iarr<3;iarr++) {
signal[iarr] = seed->GetDEDXregion(iarr+1);
signalMax[iarr] = seed->GetDEDXregion(iarr+5);
ncl[iarr] = seed->GetNCDEDX(iarr+1);
nrows[iarr] = seed->GetNCDEDXInclThres(iarr+1);
}
signal[3] = seed->GetDEDXregion(4);
signalMax[3] = seed->GetDEDXregion(8);
//
AliTPCdEdxInfo * infoTpcPid = new AliTPCdEdxInfo();
infoTpcPid->SetTPCSignalRegionInfo(signal, ncl, nrows);
infoTpcPid->SetTPCSignalsQmax(signalMax);
esd->SetTPCdEdxInfo(infoTpcPid);
//
// add seed to the esd track in Calib level
//
Bool_t storeFriend = seedsInFriendsNorm>0 && (!esd->GetFriendNotStored())
&& seedsInFriends<(kMaxFriendTracks-1)
&& gRandom->Rndm()<(kMaxFriendTracks)/Float_t(seedsInFriendsNorm);
// if (AliTPCReconstructor::StreamLevel()>0 &&storeFriend){
//AliInfoF("Store: %d Stored %d / %d FrOff: %d",storeFriend,seedsInFriends,seedsInFriendsNorm,esd->GetFriendNotStored());
if (storeFriend){ // RS: seed is needed for calibration, regardless on streamlevel
seedsInFriends++;
// RS: this is the only place where the seed is created not in the pool,
// since it should belong to ESDevent
//AliTPCseed * seedCopy = new AliTPCseed(*seed, kTRUE);
//esd->AddCalibObject(seedCopy);
//
//RS to avoid the cloning the seeds and clusters we will declare the seed to own its
// clusters and reattach the clusters pointers from the pool, so they are saved in the friends
seed->SetClusterOwner(kTRUE);
memcpy(fClPointersPoolPtr,seedClusters,kMaxRow*sizeof(AliTPCclusterMI*));
seed->SetClustersArrayTMP(fClPointersPoolPtr);
esd->AddCalibObject(seed);
fClPointersPoolPtr += kMaxRow;
}
else seed->SetClustersArrayTMP((AliTPCclusterMI**)seedClustersSave);
//
ntracks++;
}
else{
//printf("problem\n");
}
//
//RS if seed does not own clusters, then it was not added to friends: detach temporary clusters !!!
if (!seedClustersSave && !seed->GetClusterOwner()) seed->SetClustersArrayTMP(0);
//
}
//FindKinks(fSeeds,event);
if ((AliTPCReconstructor::StreamLevel()&kStreamClDump)>0) DumpClusters(2,fSeeds); // dump clusters at the end of process (signed with useage flags)
Info("RefitInward","Number of refitted tracks %d",ntracks);
AliCosmicTracker::FindCosmic(event, kTRUE);
FillClusterOccupancyInfo();
return 0;
}
Int_t AliTPCtracker::PropagateBack(AliESDEvent *event)
{
//
// back propagation of ESD tracks
//
if (!event) return 0;
fEvent = event;
fEventHLT = 0;
fIteration = 1;
ReadSeeds(event,1);
PropagateBack(fSeeds);
RemoveUsed2(fSeeds,0.4,0.4,20);
//FindCurling(fSeeds, fEvent,1);
FindSplitted(fSeeds, event,1); // find multi found tracks
if ((AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC)>0) FindMultiMC(fSeeds, fEvent,1); // find multi found tracks
//
// RS: the cluster pointers are not permanently attached to the seed during the tracking, need to attach temporarily
AliTPCclusterMI* seedClusters[kMaxRow];
//
Int_t nseed = fSeeds->GetEntriesFast();
Int_t ntracks=0;
for (Int_t i=0;i<nseed;i++){
AliTPCseed * seed = (AliTPCseed*) fSeeds->UncheckedAt(i);
if (!seed) continue;
AliESDtrack *esd=event->GetTrack(i);
if (!esd) continue; //never happen
//
//RS: if needed, attach temporary cluster array
const AliTPCclusterMI** seedClustersSave = seed->GetClusters();
if (!seedClustersSave) { //RS: temporary attach clusters
for (int ir=kMaxRow;ir--;) {
int idx = seed->GetClusterIndex2(ir);
seedClusters[ir] = idx<0 ? 0 : GetClusterMI(idx);
}
seed->SetClustersArrayTMP(seedClusters);
}
//
if (seed->GetKinkIndex(0)<0) UpdateKinkQualityM(seed); // update quality informations for kinks
seed->UpdatePoints();
AddCovariance(seed);
if (seed->GetNumberOfClusters()<60 && seed->GetNumberOfClusters()<(esd->GetTPCclusters(0) -5)*0.8){
AliExternalTrackParam paramIn;
AliExternalTrackParam paramOut;
Int_t ncl = seed->RefitTrack(seed,¶mIn,¶mOut);
if ((AliTPCReconstructor::StreamLevel()&kStreamRecoverBack)>0) { // flag: stream track information for track faling PropagateBack function and recovered back (RefitTrack)
(*fDebugStreamer)<<"RecoverBack"<<
"seed.="<<seed<<
"esd.="<<esd<<
"pin.="<<¶mIn<<
"pout.="<<¶mOut<<
"ncl="<<ncl<<
"\n";
}
if (ncl>15) {
seed->Set(paramOut.GetX(),paramOut.GetAlpha(),paramOut.GetParameter(),paramOut.GetCovariance());
seed->SetNumberOfClusters(ncl);
}
}
seed->CookdEdx(0.02,0.6);
CookLabel(seed,0.1); //For comparison only
if (seed->GetNumberOfClusters()>15){
esd->UpdateTrackParams(seed,AliESDtrack::kTPCout);
esd->SetTPCPoints(seed->GetPoints());
esd->SetTPCPointsF(seed->GetNFoundable());
Int_t ndedx = seed->GetNCDEDX(0);
Float_t sdedx = seed->GetSDEDX(0);
Float_t dedx = seed->GetdEdx();
esd->SetTPCsignal(dedx, sdedx, ndedx);
ntracks++;
Int_t eventnumber = event->GetEventNumberInFile();// patch 28 fev 06
// This is most likely NOT the event number you'd like to use. It has nothing to do with the 'real' event number
if (((AliTPCReconstructor::StreamLevel()&kStreamCPropagateBack)>0) && esd) {
(*fDebugStreamer)<<"PropagateBack"<< // flag: stream track information in PropagateBack function (after tracking Iteration 1)
"Tr0.="<<seed<<
"esd.="<<esd<<
"EventNrInFile="<<eventnumber<<
"\n";
}
}
//
if (!seedClustersSave) seed->SetClustersArrayTMP(0); //RS detach temporary clusters !!!
//
}
if (AliTPCReconstructor::StreamLevel()&kStreamClDump) DumpClusters(1,fSeeds); // flag:stream clusters at the end of process (signed with usage flag)
//FindKinks(fSeeds,event);
Info("PropagateBack","Number of back propagated tracks %d",ntracks);
fEvent =0;
fEventHLT = 0;
return 0;
}
Int_t AliTPCtracker::PostProcess(AliESDEvent *event)
{
//
// Post process events
//
if (!event) return 0;
//
// Set TPC event status
//
// event affected by HV dip
// reset TPC status
if(IsTPCHVDipEvent(event)) {
event->ResetDetectorStatus(AliDAQ::kTPC);
}
//printf("Status %d \n", event->IsDetectorOn(AliDAQ::kTPC));
return 0;
}
void AliTPCtracker::DeleteSeeds()
{
//
fSeeds->Clear();
ResetSeedsPool();
// delete fSeeds; // RS avoid unnecessary deletes
// fSeeds =0;
}
void AliTPCtracker::ReadSeeds(const AliESDEvent *const event, Int_t direction)
{
//
//read seeds from the event
Int_t nentr=event->GetNumberOfTracks();
if (fDebug>0){
Info("ReadSeeds", "Number of ESD tracks: %d\n", nentr);
}
if (fSeeds)
DeleteSeeds();
if (!fSeeds) fSeeds = new TObjArray(nentr);
else if (fSeeds->GetSize()<nentr) fSeeds->Expand(nentr); //RS reuse array
//
UnsignClusters();
// Int_t ntrk=0;
for (Int_t i=0; i<nentr; i++) {
AliESDtrack *esd=event->GetTrack(i);
ULong_t status=esd->GetStatus();
if (!(status&AliESDtrack::kTPCin)) continue;
AliTPCtrack t(*esd);
t.SetNumberOfClusters(0);
// AliTPCseed *seed = new AliTPCseed(t,t.GetAlpha());
AliTPCseed *seed = new( NextFreeSeed() ) AliTPCseed(t/*,t.GetAlpha()*/);
seed->SetPoolID(fLastSeedID);
seed->SetUniqueID(esd->GetID());
AddCovariance(seed); //add systematic ucertainty
for (Int_t ikink=0;ikink<3;ikink++) {
Int_t index = esd->GetKinkIndex(ikink);
seed->GetKinkIndexes()[ikink] = index;
if (index==0) continue;
index = TMath::Abs(index);
AliESDkink * kink = fEvent->GetKink(index-1);
if (kink&&esd->GetKinkIndex(ikink)<0){
if ((status & AliESDtrack::kTRDrefit) != 0) kink->SetStatus(1,2);
if ((status & AliESDtrack::kITSout) != 0) kink->SetStatus(1,0);
}
if (kink&&esd->GetKinkIndex(ikink)>0){
if ((status & AliESDtrack::kTRDrefit) != 0) kink->SetStatus(1,6);
if ((status & AliESDtrack::kITSout) != 0) kink->SetStatus(1,4);
}
}
if (((status&AliESDtrack::kITSout)==0)&&(direction==1)) seed->ResetCovariance(10.);
//RS if ( direction ==2 &&(status & AliESDtrack::kTRDrefit) == 0 ) seed->ResetCovariance(10.);
if ( direction ==2 &&(status & AliESDtrack::kTRDrefit) == 0 ) seed->ResetCovariance(10.);
//if ( direction ==2 && ((status & AliESDtrack::kTPCout) == 0) ) {
// fSeeds->AddAt(0,i);
// MarkSeedFree( seed );
// continue;
//}
//
//
// rotate to the local coordinate system
//
fSectors=fInnerSec; fN=fkNIS;
Double_t alpha=seed->GetAlpha();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
Int_t ns=Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN;
alpha =ns*fSectors->GetAlpha() + fSectors->GetAlphaShift();
alpha-=seed->GetAlpha();
if (alpha<-TMath::Pi()) alpha += 2*TMath::Pi();
if (alpha>=TMath::Pi()) alpha -= 2*TMath::Pi();
if (TMath::Abs(alpha) > 0.001) { // This should not happen normally
AliWarning(Form("Rotating track over %f",alpha));
if (!seed->Rotate(alpha)) {
MarkSeedFree( seed );
continue;
}
}
seed->SetESD(esd);
// sign clusters
if (esd->GetKinkIndex(0)<=0){
for (Int_t irow=0;irow<kMaxRow;irow++){
Int_t index = seed->GetClusterIndex2(irow);
if (index >= 0){
//
AliTPCclusterMI * cl = GetClusterMI(index);
//RS seed->SetClusterPointer(irow,cl);
if (cl){
if ((index & 0x8000)==0){
cl->Use(10); // accepted cluster
}else{
cl->Use(6); // close cluster not accepted
}
}else{
Info("ReadSeeds","Not found cluster");
}
}
}
}
fSeeds->AddAt(seed,i);
}
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds3(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay, Int_t ddsec) {
//-----------------------------------------------------------------
// This function creates track seeds.
// SEEDING WITH VERTEX CONSTRAIN
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
const double kRoadY = 1., kRoadZ = 0.6;
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Double_t x[5], c[15];
// Int_t di = i1-i2;
//
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed();
seed->SetPoolID(fLastSeedID);
Double_t alpha=fSectors->GetAlpha(), shift=fSectors->GetAlphaShift();
Double_t cs=cos(alpha), sn=sin(alpha);
//
// Double_t x1 =fOuterSec->GetX(i1);
//Double_t xx2=fOuterSec->GetX(i2);
Double_t x1 =GetXrow(i1);
Double_t xx2=GetXrow(i2);
Double_t x3=GetX(), y3=GetY(), z3=GetZ();
Int_t imiddle = (i2+i1)/2; //middle pad row index
Double_t xm = GetXrow(imiddle); // radius of middle pad-row
const AliTPCtrackerRow& krm=GetRow(sec,imiddle); //middle pad -row
//
Int_t ns =sec;
const AliTPCtrackerRow& kr1=GetRow(ns,i1);
Double_t ymax = GetMaxY(i1)-kr1.GetDeadZone()-1.5;
Double_t ymaxm = GetMaxY(imiddle)-kr1.GetDeadZone()-1.5;
//
// change cut on curvature if it can't reach this layer
// maximal curvature set to reach it
Double_t dvertexmax = TMath::Sqrt((x1-x3)*(x1-x3)+(ymax+5-y3)*(ymax+5-y3));
if (dvertexmax*0.5*cuts[0]>0.85){
cuts[0] = 0.85/(dvertexmax*0.5+1.);
}
Double_t r2min = 1/(cuts[0]*cuts[0]); //minimal square of radius given by cut
// Int_t ddsec = 1;
if (deltay>0) ddsec = 0;
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
Double_t y1=kr1[is]->GetY(), z1=kr1[is]->GetZ();
//if (TMath::Abs(y1)>ymax) continue;
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y1))> deltay ) continue; // seed only at the edge
// find possible directions
Float_t anglez = (z1-z3)/(x1-x3);
Float_t extraz = z1 - anglez*(x1-xx2); // extrapolated z
//
//
//find rotation angles relative to line given by vertex and point 1
Double_t dvertex2 = (x1-x3)*(x1-x3)+(y1-y3)*(y1-y3);
Double_t dvertex = TMath::Sqrt(dvertex2);
Double_t angle13 = TMath::ATan((y1-y3)/(x1-x3));
Double_t cs13 = cos(-angle13), sn13 = sin(-angle13);
//
// loop over 2 sectors
Int_t dsec1=-ddsec;
Int_t dsec2= ddsec;
if (y1<0) dsec2= 0;
if (y1>0) dsec1= 0;
Double_t dddz1=0; // direction of delta inclination in z axis
Double_t dddz2=0;
if ( (z1-z3)>0)
dddz1 =1;
else
dddz2 =1;
//
for (Int_t dsec = dsec1; dsec<=dsec2;dsec++){
Int_t sec2 = sec + dsec;
//
// AliTPCtrackerRow& kr2 = fOuterSec[(sec2+fkNOS)%fkNOS][i2];
//AliTPCtrackerRow& kr2m = fOuterSec[(sec2+fkNOS)%fkNOS][imiddle];
AliTPCtrackerRow& kr2 = GetRow((sec2+fkNOS)%fkNOS,i2);
AliTPCtrackerRow& kr2m = GetRow((sec2+fkNOS)%fkNOS,imiddle);
Int_t index1 = TMath::Max(kr2.Find(extraz-0.6-dddz1*TMath::Abs(z1)*0.05)-1,0);
Int_t index2 = TMath::Min(kr2.Find(extraz+0.6+dddz2*TMath::Abs(z1)*0.05)+1,kr2);
// rotation angles to p1-p3
Double_t cs13r = cos(-angle13+dsec*alpha)/dvertex, sn13r = sin(-angle13+dsec*alpha)/dvertex;
Double_t x2, y2, z2;
//
// Double_t dymax = maxangle*TMath::Abs(x1-xx2);
//
Double_t dxx0 = (xx2-x3)*cs13r;
Double_t dyy0 = (xx2-x3)*sn13r;
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr2[js];
if (kcl->IsUsed(10)) continue;
if (kcl->IsDisabled()) {
continue;
}
//
//calcutate parameters
//
Double_t yy0 = dyy0 +(kcl->GetY()-y3)*cs13r;
// stright track
if (TMath::Abs(yy0)<0.000001) continue;
Double_t xx0 = dxx0 -(kcl->GetY()-y3)*sn13r;
Double_t y0 = 0.5*(xx0*xx0+yy0*yy0-xx0)/yy0;
Double_t r02 = (0.25+y0*y0)*dvertex2;
//curvature (radius) cut
if (r02<r2min) continue;
nin0++;
//
Double_t c0 = 1/TMath::Sqrt(r02);
if (yy0>0) c0*=-1.;
//Double_t dfi0 = 2.*TMath::ASin(dvertex*c0*0.5);
//Double_t dfi1 = 2.*TMath::ASin(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
Double_t dfi0 = 2.*asinf(dvertex*c0*0.5);
Double_t dfi1 = 2.*asinf(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
//
//
Double_t z0 = kcl->GetZ();
Double_t zzzz2 = z1-(z1-z3)*dfi1/dfi0;
if (TMath::Abs(zzzz2-z0)>0.5) continue;
nin1++;
//
Double_t dip = (z1-z0)*c0/dfi1;
Double_t x0 = (0.5*cs13+y0*sn13)*dvertex*c0;
//
y2 = kcl->GetY();
if (dsec==0){
x2 = xx2;
z2 = kcl->GetZ();
}
else
{
// rotation
z2 = kcl->GetZ();
x2= xx2*cs-y2*sn*dsec;
y2=+xx2*sn*dsec+y2*cs;
}
x[0] = y1;
x[1] = z1;
x[2] = x0;
x[3] = dip;
x[4] = c0;
//
//
// do we have cluster at the middle ?
Double_t ym,zm;
GetProlongation(x1,xm,x,ym,zm);
UInt_t dummy;
AliTPCclusterMI * cm=0;
if (TMath::Abs(ym)-ymaxm<0){
cm = krm.FindNearest2(ym,zm,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
else{
// rotate y1 to system 0
// get state vector in rotated system
Double_t yr1 = (-0.5*sn13+y0*cs13)*dvertex*c0;
Double_t xr2 = x0*cs+yr1*sn*dsec;
Double_t xr[5]={kcl->GetY(),kcl->GetZ(), xr2, dip, c0};
//
GetProlongation(xx2,xm,xr,ym,zm);
if (TMath::Abs(ym)-ymaxm<0){
cm = kr2m.FindNearest2(ym,zm,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
}
// Double_t dym = 0;
// Double_t dzm = 0;
// if (cm){
// dym = ym - cm->GetY();
// dzm = zm - cm->GetZ();
// }
nin2++;
//
//
Double_t sy1=kr1[is]->GetSigmaY2()*2., sz1=kr1[is]->GetSigmaZ2()*2.;
Double_t sy2=kcl->GetSigmaY2()*2., sz2=kcl->GetSigmaZ2()*2.;
//Double_t sy3=400*3./12., sy=0.1, sz=0.1;
Double_t sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
//Double_t sy3=25000*x[4]*x[4]*60+0.5, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
UInt_t index=kr1.GetIndex(is);
if (seed) {MarkSeedFree(seed); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, ns*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
track->SetSeed1(i1);
track->SetSeed2(i2);
track->SetSeedType(3);
//if (dsec==0) {
FollowProlongation(*track, (i1+i2)/2,1);
Int_t foundable,found,shared;
GetSeedClusterStatistic(track,(i1+i2)/2,i1, found, foundable, shared, kTRUE); //RS: seeds don't keep their clusters
//RS track->GetClusterStatistic((i1+i2)/2,i1, found, foundable, shared, kTRUE);
if ((found<0.55*foundable) || shared>0.5*found || (track->GetSigmaY2()+track->GetSigmaZ2())>0.5){
MarkSeedFree(seed); seed = 0;
continue;
}
//}
nin++;
FollowProlongation(*track, i2,1);
//Int_t rc = 1;
track->SetBConstrain(1);
// track->fLastPoint = i1+fInnerSec->GetNRows(); // first cluster in track position
track->SetLastPoint(i1); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters() ) {
MarkSeedFree(seed); seed = 0;
continue;
}
nout1++;
Double_t zv, bz=GetBz();
if ( !track->GetZAt(0.,bz,zv) ) { MarkSeedFree( seed ); seed = 0; continue; }
//
if (fDisableSecondaries) {
if (TMath::Abs(zv)>fPrimaryDCAZCut) { MarkSeedFree( seed ); seed = 0; continue; }
double yv;
if ( !track->GetZAt(0.,bz,yv) ) { MarkSeedFree( seed ); seed = 0; continue; }
if (TMath::Abs(zv)>fPrimaryDCAZCut) { MarkSeedFree( seed ); seed = 0; continue; }
}
//
// Z VERTEX CONDITION
if (TMath::Abs(zv-z3)>cuts[2]) {
FollowProlongation(*track, TMath::Max(i2-20,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2]){
FollowProlongation(*track, TMath::Max(i2-40,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2] &&(track->GetNumberOfClusters() > track->GetNFoundable()*0.7)){
// make seed without constrain
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,1.);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(1);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
continue;
}
else{
MarkSeedFree( seed ); seed = 0;
continue;
}
}
}
track->SetSeedType(0);
arr->AddLast(track); // note, track is seed, don't free the seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
nout2++;
// don't consider other combinations
if (track->GetNumberOfClusters() > track->GetNFoundable()*0.8)
break;
}
}
}
if (fDebug>3){
Info("MakeSeeds3","\nSeeding statistic:\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2);
}
if (seed) MarkSeedFree( seed );
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds3Dist(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay, Int_t ddsec) {
//-----------------------------------------------------------------
// This function creates track seeds, accounting for distortions
// SEEDING WITH VERTEX CONSTRAIN
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Double_t x[5], c[15];
// Int_t di = i1-i2;
//
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed();
seed->SetPoolID(fLastSeedID);
Double_t alpha=fSectors->GetAlpha(), shift=fSectors->GetAlphaShift();
Double_t cs=cos(alpha), sn=sin(alpha);
//
Double_t x1def = GetXrow(i1);
Double_t xx2def = GetXrow(i2);
Double_t x3=GetX(), y3=GetY(), z3=GetZ();
Int_t imiddle = (i2+i1)/2; //middle pad row index
const AliTPCtrackerRow& krm=GetRow(sec,imiddle); //middle pad -row
//
Int_t ns =sec;
const AliTPCtrackerRow& kr1=GetRow(ns,i1);
Double_t ymax = GetMaxY(i1)-kr1.GetDeadZone()-1.5;
Double_t ymaxm = GetMaxY(imiddle)-kr1.GetDeadZone()-1.5; // RS check ymax
//
// change cut on curvature if it can't reach this layer
// maximal curvature set to reach it
Double_t dvertexmax = TMath::Sqrt((x1def-x3)*(x1def-x3)+(ymax+5-y3)*(ymax+5-y3));
if (dvertexmax*0.5*cuts[0]>0.85){
cuts[0] = 0.85/(dvertexmax*0.5+1.);
}
Double_t r2min = 1/(cuts[0]*cuts[0]); //minimal square of radius given by cut
// Int_t ddsec = 1;
if (deltay>0) ddsec = 0;
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
const AliTPCclusterMI* clkr1 = kr1[is];
Double_t x1=clkr1->GetX(), y1=clkr1->GetY(), z1=clkr1->GetZ();
//if (TMath::Abs(y1)>ymax) continue;
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y1))> deltay ) continue; // seed only at the edge
// find possible directions
double dx13 = x1-x3, dy13 = y1-y3, dz13 = z1-z3;
double anglez = dz13/dx13;
double extraz = z1 - anglez*(x1-xx2def); // extrapolated z
//
//
//find rotation angles relative to line given by vertex and point 1
Double_t dvertex2 = dx13*dx13+dy13*dy13;
Double_t dvertex = TMath::Sqrt(dvertex2);
Double_t angle13 = TMath::ATan(dy13/dx13);
Double_t cs13 = cos(-angle13), sn13 = sin(-angle13);
//
// loop over 2 sectors
Int_t dsec1=-ddsec;
Int_t dsec2= ddsec;
if (y1<0) dsec2= 0;
if (y1>0) dsec1= 0;
Double_t dddz1=0; // direction of delta inclination in z axis
Double_t dddz2=0;
if ( dz13>0 ) dddz1 =1;
else dddz2 =1;
//
for (Int_t dsec = dsec1; dsec<=dsec2;dsec++){
Int_t sec2 = sec + dsec;
//
// AliTPCtrackerRow& kr2 = fOuterSec[(sec2+fkNOS)%fkNOS][i2];
//AliTPCtrackerRow& kr2m = fOuterSec[(sec2+fkNOS)%fkNOS][imiddle];
AliTPCtrackerRow& kr2 = GetRow((sec2+fkNOS)%fkNOS,i2);
AliTPCtrackerRow& kr2m = GetRow((sec2+fkNOS)%fkNOS,imiddle);
Int_t index1 = TMath::Max(kr2.Find(extraz-0.6-dddz1*TMath::Abs(z1)*0.05)-1,0);
Int_t index2 = TMath::Min(kr2.Find(extraz+0.6+dddz2*TMath::Abs(z1)*0.05)+1,kr2);
// rotation angles to p1-p3
Double_t cs13r = cos(-angle13+dsec*alpha)/dvertex, sn13r = sin(-angle13+dsec*alpha)/dvertex;
//
// Double_t dymax = maxangle*TMath::Abs(x1-xx2);
//
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr2[js];
if (kcl->IsUsed(10)) continue;
if (kcl->IsDisabled()) {
continue;
}
//
double x2=kcl->GetX(), y2=kcl->GetY(), z2=kcl->GetZ();
double dy23 = y2-y3, dx23 = x2-x3;
//calcutate parameters
Double_t dxx0 = dx23*cs13r;
Double_t dyy0 = dx23*sn13r;
//
Double_t yy0 = dyy0 +dy23*cs13r;
// stright track
if (TMath::Abs(yy0)<0.000001) continue;
Double_t xx0 = dxx0 -dy23*sn13r;
Double_t y0 = 0.5*(xx0*xx0+yy0*yy0-xx0)/yy0;
Double_t r02 = (0.25+y0*y0)*dvertex2;
//curvature (radius) cut
if (r02<r2min) continue;
nin0++;
//
Double_t c0 = 1/TMath::Sqrt(r02);
if (yy0>0) c0*=-1.;
//Double_t dfi0 = 2.*TMath::ASin(dvertex*c0*0.5);
//Double_t dfi1 = 2.*TMath::ASin(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
Double_t dfi0 = 2.*AliTPCFastMath::FastAsin(dvertex*c0*0.5);
Double_t dfi1 = 2.*AliTPCFastMath::FastAsin(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
//
Double_t zzzz2 = z1-dz13*dfi1/dfi0;
if (TMath::Abs(zzzz2-z2)>0.5) continue;
nin1++;
//
Double_t dip = (z1-z2)*c0/dfi1;
Double_t x0 = (0.5*cs13+y0*sn13)*dvertex*c0;
//
if (dsec!=0) {
// rotation
double xt2 = x2;
x2= xt2*cs-y2*sn*dsec;
y2=+xt2*sn*dsec+y2*cs;
}
x[0] = y1;
x[1] = z1;
x[2] = x0;
x[3] = dip;
x[4] = c0;
//
//
// do we have cluster at the middle ?
Double_t xm = GetXrow(imiddle), ym, zm; // radius of middle pad-row
GetProlongation(x1,xm,x,ym,zm);
// account for distortion
double dxDist = GetDistortionX(xm,ym,zm,sec,imiddle);
if (TMath::Abs(dxDist)>0.1) {
GetProlongation(x1,xm+dxDist,x,ym,zm); //RS:? can we use straight line here?
}
UInt_t dummy;
AliTPCclusterMI * cm=0;
if (TMath::Abs(ym)-ymaxm<0){ //RS:? redefine ymax?
cm = krm.FindNearest2(ym,zm,1.0,0.6,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
else{
// rotate y1 to system 0
// get state vector in rotated system
Double_t yr1 = (-0.5*sn13+y0*cs13)*dvertex*c0;
Double_t xr2 = x0*cs+yr1*sn*dsec;
Double_t xr[5]={kcl->GetY(),kcl->GetZ(), xr2, dip, c0};
//
GetProlongation(kcl->GetX(),xm,xr,ym,zm);
double dxDist = GetDistortionX(xm,ym,zm,sec,imiddle);
if (TMath::Abs(dxDist)>0.1) {
GetProlongation(x1,xm+dxDist,x,ym,zm); //RS:? can we use straight line here?
}
//
if (TMath::Abs(ym)-ymaxm<0){
cm = kr2m.FindNearest2(ym,zm,1.0,0.6,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
}
// Double_t dym = 0;
// Double_t dzm = 0;
// if (cm){
// dym = ym - cm->GetY();
// dzm = zm - cm->GetZ();
// }
nin2++;
//
//
Double_t sy1=kr1[is]->GetSigmaY2()*2., sz1=kr1[is]->GetSigmaZ2()*2.;
Double_t sy2=kcl->GetSigmaY2()*2., sz2=kcl->GetSigmaZ2()*2.;
//Double_t sy3=400*3./12., sy=0.1, sz=0.1;
Double_t sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
//Double_t sy3=25000*x[4]*x[4]*60+0.5, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
UInt_t index=kr1.GetIndex(is);
if (seed) {MarkSeedFree(seed); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, ns*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
track->SetSeed1(i1);
track->SetSeed2(i2);
track->SetSeedType(3);
//if (dsec==0) {
FollowProlongation(*track, (i1+i2)/2,1);
Int_t foundable,found,shared;
track->GetClusterStatistic((i1+i2)/2,i1, found, foundable, shared, kTRUE);
if ((found<0.55*foundable) || shared>0.5*found || (track->GetSigmaY2()+track->GetSigmaZ2())>0.5){
MarkSeedFree(seed); seed = 0;
continue;
}
//}
nin++;
FollowProlongation(*track, i2,1);
//Int_t rc = 1;
track->SetBConstrain(1);
// track->fLastPoint = i1+fInnerSec->GetNRows(); // first cluster in track position
track->SetLastPoint(i1); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters() ) {
MarkSeedFree(seed); seed = 0;
continue;
}
nout1++;
// Z VERTEX CONDITION
Double_t zv, bz=GetBz();
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2]) {
FollowProlongation(*track, TMath::Max(i2-20,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2]){
FollowProlongation(*track, TMath::Max(i2-40,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2] &&(track->GetNumberOfClusters() > track->GetNFoundable()*0.7)){
// make seed without constrain
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,1.);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(1);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
continue;
}
else{
MarkSeedFree( seed ); seed = 0;
continue;
}
}
}
track->SetSeedType(0);
arr->AddLast(track); // note, track is seed, don't free the seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
nout2++;
// don't consider other combinations
if (track->GetNumberOfClusters() > track->GetNFoundable()*0.8)
break;
}
}
}
if (fDebug>3){
Info("MakeSeeds3Dist","\nSeeding statistic:\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2);
}
if (seed) MarkSeedFree( seed );
}
void AliTPCtracker::MakeSeeds5(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay) {
//-----------------------------------------------------------------
// This function creates track seeds.
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Int_t nout3 =0;
Double_t x[5], c[15];
//
// make temporary seed
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
//
//
// first 3 padrows
Double_t x1 = GetXrow(i1-1);
const AliTPCtrackerRow& kr1=GetRow(sec,i1-1);
Double_t y1max = GetMaxY(i1-1)-kr1.GetDeadZone()-1.5;
//
Double_t x1p = GetXrow(i1);
const AliTPCtrackerRow& kr1p=GetRow(sec,i1);
//
Double_t x1m = GetXrow(i1-2);
const AliTPCtrackerRow& kr1m=GetRow(sec,i1-2);
//
//last 3 padrow for seeding
AliTPCtrackerRow& kr3 = GetRow((sec+fkNOS)%fkNOS,i1-7);
Double_t x3 = GetXrow(i1-7);
// Double_t y3max= GetMaxY(i1-7)-kr3.fDeadZone-1.5;
//
AliTPCtrackerRow& kr3p = GetRow((sec+fkNOS)%fkNOS,i1-6);
Double_t x3p = GetXrow(i1-6);
//
AliTPCtrackerRow& kr3m = GetRow((sec+fkNOS)%fkNOS,i1-8);
Double_t x3m = GetXrow(i1-8);
//
//
// middle padrow
Int_t im = i1-4; //middle pad row index
Double_t xm = GetXrow(im); // radius of middle pad-row
const AliTPCtrackerRow& krm=GetRow(sec,im); //middle pad -row
// Double_t ymmax = GetMaxY(im)-kr1.fDeadZone-1.5;
//
//
Double_t deltax = x1-x3;
Double_t dymax = deltax*cuts[1];
Double_t dzmax = deltax*cuts[3];
//
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
Double_t y1=kr1[is]->GetY(), z1=kr1[is]->GetZ();
//
if (deltay>0 && TMath::Abs(y1max-TMath::Abs(y1))> deltay ) continue; // seed only at the edge
//
Int_t index1 = TMath::Max(kr3.Find(z1-dzmax)-1,0);
Int_t index2 = TMath::Min(kr3.Find(z1+dzmax)+1,kr3);
//
Double_t y3, z3;
//
//
UInt_t index;
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr3[js];
if (kcl->IsDisabled()) {
continue;
}
if (kcl->IsUsed(10)) continue;
y3 = kcl->GetY();
// apply angular cuts
if (TMath::Abs(y1-y3)>dymax) continue;
//x3 = x3;
z3 = kcl->GetZ();
if (TMath::Abs(z1-z3)>dzmax) continue;
//
Double_t angley = (y1-y3)/(x1-x3);
Double_t anglez = (z1-z3)/(x1-x3);
//
Double_t erry = TMath::Abs(angley)*(x1-x1m)*0.5+0.5;
Double_t errz = TMath::Abs(anglez)*(x1-x1m)*0.5+0.5;
//
Double_t yyym = angley*(xm-x1)+y1;
Double_t zzzm = anglez*(xm-x1)+z1;
const AliTPCclusterMI *kcm = krm.FindNearest2(yyym,zzzm,erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
if (!kcm) continue;
if (kcm->IsUsed(10)) continue;
if (kcm->IsDisabled()) {
continue;
}
erry = TMath::Abs(angley)*(x1-x1m)*0.4+0.5;
errz = TMath::Abs(anglez)*(x1-x1m)*0.4+0.5;
//
//
//
Int_t used =0;
Int_t found =0;
//
// look around first
const AliTPCclusterMI *kc1m = kr1m.FindNearest2(angley*(x1m-x1)+y1,
anglez*(x1m-x1)+z1,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc1m){
found++;
if (kc1m->IsUsed(10)) used++;
}
const AliTPCclusterMI *kc1p = kr1p.FindNearest2(angley*(x1p-x1)+y1,
anglez*(x1p-x1)+z1,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc1p){
found++;
if (kc1p->IsUsed(10)) used++;
}
if (used>1) continue;
if (found<1) continue;
//
// look around last
const AliTPCclusterMI *kc3m = kr3m.FindNearest2(angley*(x3m-x3)+y3,
anglez*(x3m-x3)+z3,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc3m){
found++;
if (kc3m->IsUsed(10)) used++;
}
else
continue;
const AliTPCclusterMI *kc3p = kr3p.FindNearest2(angley*(x3p-x3)+y3,
anglez*(x3p-x3)+z3,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc3p){
found++;
if (kc3p->IsUsed(10)) used++;
}
else
continue;
if (used>1) continue;
if (found<3) continue;
//
Double_t x2,y2,z2;
x2 = xm;
y2 = kcm->GetY();
z2 = kcm->GetZ();
//
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]) >= cuts[0]) continue;
nin0++;
//
x[2]=F2(x1,y1,x2,y2,x3,y3);
nin1++;
//
x[3]=F3n(x1,y1,x2,y2,z1,z2,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
nin2++;
//
//
Double_t sy1=0.1, sz1=0.1;
Double_t sy2=0.1, sz2=0.1;
Double_t sy3=0.1, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
index=kr1.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, sec*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
nin++;
FollowProlongation(*track, i1-7,1);
if (track->GetNumberOfClusters() < track->GetNFoundable()*0.75 ||
track->GetNShared()>0.6*track->GetNumberOfClusters() || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.6+fExtraClErrYZ2){
MarkSeedFree( seed ); seed = 0;
continue;
}
nout1++;
nout2++;
//Int_t rc = 1;
FollowProlongation(*track, i2,1);
track->SetBConstrain(0);
track->SetLastPoint(i1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters()<track->GetNFoundable()*0.7 ||
track->GetNShared()>2. || track->GetChi2()/track->GetNumberOfClusters()>6 || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.5+fExtraClErrYZ2) {
MarkSeedFree( seed ); seed = 0;
continue;
}
{
FollowProlongation(*track, TMath::Max(i2-10,0),1);
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,0.9);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(4);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
}
//arr->AddLast(track);
//seed = new AliTPCseed;
nout3++;
}
}
if (fDebug>3){
Info("MakeSeeds5","\nSeeding statiistic:\t%d\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2,nout3);
}
if (seed) MarkSeedFree(seed);
}
void AliTPCtracker::MakeSeeds5Dist(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay) {
//-----------------------------------------------------------------
// This function creates track seeds, accounting for distortions
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Int_t nout3 =0;
Double_t x[5], c[15];
//
// make temporary seed
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
//
//
// first 3 padrows
Double_t x1Def = GetXrow(i1-1);
const AliTPCtrackerRow& kr1=GetRow(sec,i1-1);
Double_t y1max = GetMaxY(i1-1)-kr1.GetDeadZone()-1.5;
//
Double_t x1pDef = GetXrow(i1);
const AliTPCtrackerRow& kr1p=GetRow(sec,i1);
//
Double_t x1mDef = GetXrow(i1-2);
const AliTPCtrackerRow& kr1m=GetRow(sec,i1-2);
double dx11mDef = x1Def-x1mDef;
double dx11pDef = x1Def-x1pDef;
//
//last 3 padrow for seeding
AliTPCtrackerRow& kr3 = GetRow((sec+fkNOS)%fkNOS,i1-7);
Double_t x3Def = GetXrow(i1-7);
// Double_t y3max= GetMaxY(i1-7)-kr3.fDeadZone-1.5;
//
AliTPCtrackerRow& kr3p = GetRow((sec+fkNOS)%fkNOS,i1-6);
Double_t x3pDef = GetXrow(i1-6);
//
AliTPCtrackerRow& kr3m = GetRow((sec+fkNOS)%fkNOS,i1-8);
Double_t x3mDef = GetXrow(i1-8);
//
double dx33mDef = x3Def-x3mDef;
double dx33pDef = x3Def-x3pDef;
//
// middle padrow
Int_t im = i1-4; //middle pad row index
Double_t xmDef = GetXrow(im); // radius of middle pad-row
const AliTPCtrackerRow& krm=GetRow(sec,im); //middle pad -row
// Double_t ymmax = GetMaxY(im)-kr1.fDeadZone-1.5;
//
//
Double_t deltax = x1Def-x3Def;
Double_t dymax = deltax*cuts[1];
Double_t dzmax = deltax*cuts[3];
//
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
const AliTPCclusterMI* clkr1 = kr1[is];
Double_t x1=clkr1->GetX(), y1=clkr1->GetY(), z1=clkr1->GetZ();
//
if (deltay>0 && TMath::Abs(y1max-TMath::Abs(y1))> deltay ) continue; // seed only at the edge //RS:? dead zones?
//
Int_t index1 = TMath::Max(kr3.Find(z1-dzmax)-1,0);
Int_t index2 = TMath::Min(kr3.Find(z1+dzmax)+1,kr3);
//
Double_t x3,y3,z3;
//
//
UInt_t index;
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr3[js];
if (kcl->IsDisabled()) {
continue;
}
if (kcl->IsUsed(10)) continue;
y3 = kcl->GetY();
// apply angular cuts
if (TMath::Abs(y1-y3)>dymax) continue;
//x3 = x3;
z3 = kcl->GetZ();
if (TMath::Abs(z1-z3)>dzmax) continue;
x3 = kcl->GetX();
//
double dx13 = x1-x3;
Double_t angley = (y1-y3)/dx13;
Double_t anglez = (z1-z3)/dx13;
//
Double_t erry = TMath::Abs(angley)*dx11mDef*0.5+0.5; // RS: use ideal X differences assuming
Double_t errz = TMath::Abs(anglez)*dx11mDef*0.5+0.5; // that the distortions are ~same on close rows
//
Double_t yyym = angley*(xmDef-x1Def)+y1; // RS: idem, assume distortions cancels in the difference
Double_t zzzm = anglez*(xmDef-x1Def)+z1;
const AliTPCclusterMI *kcm = krm.FindNearest2(yyym,zzzm,erry,errz,index);
if (!kcm) continue;
if (kcm->IsUsed(10)) continue;
if (kcm->IsDisabled()) {
continue;
}
erry = TMath::Abs(angley)*dx11mDef*0.4+0.5;
errz = TMath::Abs(anglez)*dx11mDef*0.4+0.5;
//
//
//
Int_t used =0;
Int_t found =0;
//
// look around first
const AliTPCclusterMI *kc1m = kr1m.FindNearest2(-angley*dx11mDef+y1, // RS: idem, assume distortions cancels in the difference
-anglez*dx11mDef+z1,
erry,errz,index);
//
if (kc1m){
found++;
if (kc1m->IsUsed(10)) used++;
}
const AliTPCclusterMI *kc1p = kr1p.FindNearest2(-angley*dx11pDef+y1, // RS: idem, assume distortions cancels in the difference
-anglez*dx11pDef+z1,
erry,errz,index);
//
if (kc1p){
found++;
if (kc1p->IsUsed(10)) used++;
}
if (used>1) continue;
if (found<1) continue;
//
// look around last
const AliTPCclusterMI *kc3m = kr3m.FindNearest2(-angley*dx33mDef+y3, // RS: idem, assume distortions cancels in the difference
-anglez*dx33mDef+z3,
erry,errz,index);
//
if (kc3m){
found++;
if (kc3m->IsUsed(10)) used++;
}
else
continue;
const AliTPCclusterMI *kc3p = kr3p.FindNearest2(-angley*dx33pDef+y3, // RS: idem, assume distortions cancels in the difference
-anglez*dx33pDef+z3,
erry,errz,index);
//
if (kc3p){
found++;
if (kc3p->IsUsed(10)) used++;
}
else
continue;
if (used>1) continue;
if (found<3) continue;
//
Double_t x2,y2,z2;
x2 = kcm->GetZ();
y2 = kcm->GetY();
z2 = kcm->GetZ();
//
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]) >= cuts[0]) continue;
nin0++;
//
x[2]=F2(x1,y1,x2,y2,x3,y3);
nin1++;
//
x[3]=F3n(x1,y1,x2,y2,z1,z2,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
nin2++;
//
//
Double_t sy1=0.1, sz1=0.1;
Double_t sy2=0.1, sz2=0.1;
Double_t sy3=0.1, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
index=kr1.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, sec*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
nin++;
FollowProlongation(*track, i1-7,1);
if (track->GetNumberOfClusters() < track->GetNFoundable()*0.75 ||
track->GetNShared()>0.6*track->GetNumberOfClusters() || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.6){
MarkSeedFree( seed ); seed = 0;
continue;
}
nout1++;
nout2++;
//Int_t rc = 1;
FollowProlongation(*track, i2,1);
track->SetBConstrain(0);
track->SetLastPoint(i1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters()<track->GetNFoundable()*0.7 ||
track->GetNShared()>2. || track->GetChi2()/track->GetNumberOfClusters()>6 || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.5 ) {
MarkSeedFree( seed ); seed = 0;
continue;
}
{
FollowProlongation(*track, TMath::Max(i2-10,0),1);
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,0.9);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(4);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
}
//arr->AddLast(track);
//seed = new AliTPCseed;
nout3++;
}
}
if (fDebug>3){
Info("MakeSeeds5Dist","\nSeeding statiistic:\t%d\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2,nout3);
}
if (seed) MarkSeedFree(seed);
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds2(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t */*cuts[4]*/,
Float_t deltay, Bool_t /*bconstrain*/) {
//-----------------------------------------------------------------
// This function creates track seeds - without vertex constraint
//-----------------------------------------------------------------
// cuts[0] - fP4 cut - not applied
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut - not applied
// cuts[3] - fP3 cut
const double kRoadZ = 1.2, kRoadY = 1.2;
Int_t nin0=0;
Int_t nin1=0;
Int_t nin2=0;
Int_t nin3=0;
// Int_t nin4=0;
//Int_t nin5=0;
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
Int_t row0 = (i1+i2)/2;
Int_t drow = (i1-i2)/2;
const AliTPCtrackerRow& kr0=fSectors[sec][row0];
AliTPCtrackerRow * kr=0;
AliTPCpolyTrack polytrack;
Int_t nclusters=fSectors[sec][row0];
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Int_t sumused=0;
Int_t cused=0;
Int_t cnused=0;
for (Int_t is=0; is < nclusters; is++) { //LOOP over clusters
Int_t nfound =0;
Int_t nfoundable =0;
for (Int_t iter =1; iter<2; iter++){ //iterations
const AliTPCtrackerRow& krm=fSectors[sec][row0-iter];
const AliTPCtrackerRow& krp=fSectors[sec][row0+iter];
const AliTPCclusterMI * cl= kr0[is];
if (cl->IsDisabled()) {
continue;
}
if (cl->IsUsed(10)) {
cused++;
}
else{
cnused++;
}
Double_t x = kr0.GetX();
// Initialization of the polytrack
nfound =0;
nfoundable =0;
polytrack.Reset();
//
Double_t y0= cl->GetY();
Double_t z0= cl->GetZ();
Float_t erry = 0;
Float_t errz = 0;
Double_t ymax = fSectors->GetMaxY(row0)-kr0.GetDeadZone()-1.5;
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y0))> deltay ) continue; // seed only at the edge
erry = (0.5)*cl->GetSigmaY2()/TMath::Sqrt(cl->GetQ())*6;
errz = (0.5)*cl->GetSigmaZ2()/TMath::Sqrt(cl->GetQ())*6;
polytrack.AddPoint(x,y0,z0,erry, errz);
sumused=0;
if (cl->IsUsed(10)) sumused++;
Float_t roady = (5*TMath::Sqrt(cl->GetSigmaY2()+0.2)+1.)*iter;
Float_t roadz = (5*TMath::Sqrt(cl->GetSigmaZ2()+0.2)+1.)*iter;
//
x = krm.GetX();
AliTPCclusterMI * cl1 = krm.FindNearest(y0,z0,roady+fClExtraRoadY,roadz+fClExtraRoadZ);
if (cl1 && TMath::Abs(ymax-TMath::Abs(y0))) {
erry = (0.5)*cl1->GetSigmaY2()/TMath::Sqrt(cl1->GetQ())*3;
errz = (0.5)*cl1->GetSigmaZ2()/TMath::Sqrt(cl1->GetQ())*3;
if (cl1->IsUsed(10)) sumused++;
polytrack.AddPoint(x,cl1->GetY(),cl1->GetZ(),erry,errz);
}
//
x = krp.GetX();
AliTPCclusterMI * cl2 = krp.FindNearest(y0,z0,roady+fClExtraRoadY,roadz+fClExtraRoadZ);
if (cl2) {
erry = (0.5)*cl2->GetSigmaY2()/TMath::Sqrt(cl2->GetQ())*3;
errz = (0.5)*cl2->GetSigmaZ2()/TMath::Sqrt(cl2->GetQ())*3;
if (cl2->IsUsed(10)) sumused++;
polytrack.AddPoint(x,cl2->GetY(),cl2->GetZ(),erry,errz);
}
//
if (sumused>0) continue;
nin0++;
polytrack.UpdateParameters();
// follow polytrack
//
Double_t yn,zn;
nfoundable = polytrack.GetN();
nfound = nfoundable;
//
for (Int_t ddrow = iter+1; ddrow<drow;ddrow++){
Float_t maxdist = 0.8*(1.+3./(ddrow));
for (Int_t delta = -1;delta<=1;delta+=2){
Int_t row = row0+ddrow*delta;
kr = &(fSectors[sec][row]);
Double_t xn = kr->GetX();
Double_t ymax1 = fSectors->GetMaxY(row)-kr->GetDeadZone()-1.5;
polytrack.GetFitPoint(xn,yn,zn);
if (TMath::Abs(yn)>ymax1) continue;
nfoundable++;
AliTPCclusterMI * cln = kr->FindNearest(yn,zn,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ);
if (cln) {
Float_t dist = TMath::Sqrt( (yn-cln->GetY())*(yn-cln->GetY())+(zn-cln->GetZ())*(zn-cln->GetZ()));
if (dist<maxdist){
/*
erry = (dist+0.3)*cln->GetSigmaY2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
errz = (dist+0.3)*cln->GetSigmaZ2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
if (cln->IsUsed(10)) {
// printf("used\n");
sumused++;
erry*=2;
errz*=2;
}
*/
erry=0.1;
errz=0.1;
polytrack.AddPoint(xn,cln->GetY(),cln->GetZ(),erry, errz);
nfound++;
}
}
}
if ( (sumused>3) || (sumused>0.5*nfound) || (nfound<0.6*nfoundable)) break;
polytrack.UpdateParameters();
}
}
if ( (sumused>3) || (sumused>0.5*nfound)) {
//printf("sumused %d\n",sumused);
continue;
}
nin1++;
Double_t dy,dz;
polytrack.GetFitDerivation(kr0.GetX(),dy,dz);
AliTPCpolyTrack track2;
polytrack.Refit(track2,0.5+TMath::Abs(dy)*0.3,0.4+TMath::Abs(dz)*0.3);
if (track2.GetN()<0.5*nfoundable) continue;
nin2++;
if ((nfound>0.6*nfoundable) &&( nfoundable>0.4*(i1-i2))) {
//
// test seed with and without constrain
for (Int_t constrain=0; constrain<=0;constrain++){
// add polytrack candidate
Double_t x[5], c[15];
Double_t x1,x2,x3,y1,y2,y3,z1,z2,z3;
track2.GetBoundaries(x3,x1);
x2 = (x1+x3)/2.;
track2.GetFitPoint(x1,y1,z1);
track2.GetFitPoint(x2,y2,z2);
track2.GetFitPoint(x3,y3,z3);
//
//is track pointing to the vertex ?
Double_t x0,y0,z0;
x0=0;
polytrack.GetFitPoint(x0,y0,z0);
if (constrain) {
x2 = x3;
y2 = y3;
z2 = z3;
x3 = 0;
y3 = 0;
z3 = 0;
}
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
// if (TMath::Abs(x[4]) >= cuts[0]) continue; //
x[2]=F2(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]*x1-x[2]) >= cuts[1]) continue;
//x[3]=F3(x1,y1,x2,y2,z1,z2);
x[3]=F3n(x1,y1,x3,y3,z1,z3,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
Double_t sy =0.1, sz =0.1;
Double_t sy1=0.02, sz1=0.02;
Double_t sy2=0.02, sz2=0.02;
Double_t sy3=0.02;
if (constrain){
sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
}
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x3,y3,z1,z3)-x[3])/sy;
Double_t f31=(F3(x1,y1,x3,y3,z1+sz,z3)-x[3])/sz;
Double_t f32=(F3(x1,y1,x3,y3+sy,z1,z3)-x[3])/sy;
Double_t f34=(F3(x1,y1,x3,y3,z1,z3+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
//Int_t row1 = fSectors->GetRowNumber(x1);
Int_t row1 = GetRowNumber(x1);
UInt_t index=0;
//kr0.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1,sec*alpha+shift,x,c,index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
Int_t rc=FollowProlongation(*track, i2);
if (constrain) track->SetBConstrain(1);
else
track->SetBConstrain(0);
track->SetLastPoint(row1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (rc==0 || track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters()) {
MarkSeedFree( seed ); seed = 0;
}
else {
arr->AddLast(track); // track IS seed, don't free seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
}
nin3++;
}
} // if accepted seed
}
if (fDebug>3){
Info("MakeSeeds2","\nSeeding statiistic:\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin3);
}
if (seed) MarkSeedFree( seed );
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds2Dist(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t */*cuts[4]*/,
Float_t deltay, Bool_t /*bconstrain*/) {
//-----------------------------------------------------------------
// This function creates track seeds, accounting for distortions - without vertex constraint
//-----------------------------------------------------------------
// cuts[0] - fP4 cut - not applied
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut - not applied
// cuts[3] - fP3 cut
Int_t nin0=0;
Int_t nin1=0;
Int_t nin2=0;
Int_t nin3=0;
// Int_t nin4=0;
//Int_t nin5=0;
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
Int_t row0 = (i1+i2)/2;
Int_t drow = (i1-i2)/2;
const AliTPCtrackerRow& kr0=fSectors[sec][row0];
AliTPCtrackerRow * kr=0;
AliTPCpolyTrack polytrack;
Int_t nclusters=fSectors[sec][row0];
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Int_t sumused=0;
Int_t cused=0;
Int_t cnused=0;
for (Int_t is=0; is < nclusters; is++) { //LOOP over clusters
Int_t nfound =0;
Int_t nfoundable =0;
for (Int_t iter =1; iter<2; iter++){ //iterations
const AliTPCtrackerRow& krm=fSectors[sec][row0-iter];
const AliTPCtrackerRow& krp=fSectors[sec][row0+iter];
const AliTPCclusterMI * cl= kr0[is];
if (cl->IsDisabled()) {
continue;
}
if (cl->IsUsed(10)) {
cused++;
}
else{
cnused++;
}
Double_t x = kr0.GetX();
// Initialization of the polytrack
nfound =0;
nfoundable =0;
polytrack.Reset();
//
Double_t y0= cl->GetY();
Double_t z0= cl->GetZ();
Float_t erry = 0;
Float_t errz = 0;
Double_t ymax = fSectors->GetMaxY(row0)-kr0.GetDeadZone()-1.5;
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y0))> deltay ) continue; // seed only at the edge
erry = (0.5)*cl->GetSigmaY2()/TMath::Sqrt(cl->GetQ())*6;
errz = (0.5)*cl->GetSigmaZ2()/TMath::Sqrt(cl->GetQ())*6;
polytrack.AddPoint(x,y0,z0,erry, errz);
sumused=0;
if (cl->IsUsed(10)) sumused++;
Float_t roady = (5*TMath::Sqrt(cl->GetSigmaY2()+0.2)+1.)*iter;
Float_t roadz = (5*TMath::Sqrt(cl->GetSigmaZ2()+0.2)+1.)*iter;
//
x = krm.GetX();
AliTPCclusterMI * cl1 = krm.FindNearest(y0,z0,roady,roadz);
if (cl1 && TMath::Abs(ymax-TMath::Abs(y0))) {
erry = (0.5)*cl1->GetSigmaY2()/TMath::Sqrt(cl1->GetQ())*3;
errz = (0.5)*cl1->GetSigmaZ2()/TMath::Sqrt(cl1->GetQ())*3;
if (cl1->IsUsed(10)) sumused++;
polytrack.AddPoint(x,cl1->GetY(),cl1->GetZ(),erry,errz);
}
//
x = krp.GetX();
AliTPCclusterMI * cl2 = krp.FindNearest(y0,z0,roady,roadz);
if (cl2) {
erry = (0.5)*cl2->GetSigmaY2()/TMath::Sqrt(cl2->GetQ())*3;
errz = (0.5)*cl2->GetSigmaZ2()/TMath::Sqrt(cl2->GetQ())*3;
if (cl2->IsUsed(10)) sumused++;
polytrack.AddPoint(x,cl2->GetY(),cl2->GetZ(),erry,errz);
}
//
if (sumused>0) continue;
nin0++;
polytrack.UpdateParameters();
// follow polytrack
roadz = 1.2;
roady = 1.2;
//
Double_t yn,zn;
nfoundable = polytrack.GetN();
nfound = nfoundable;
//
for (Int_t ddrow = iter+1; ddrow<drow;ddrow++){
Float_t maxdist = 0.8*(1.+3./(ddrow));
for (Int_t delta = -1;delta<=1;delta+=2){
Int_t row = row0+ddrow*delta;
kr = &(fSectors[sec][row]);
Double_t xn = kr->GetX();
Double_t ymax1 = fSectors->GetMaxY(row)-kr->GetDeadZone()-1.5;
polytrack.GetFitPoint(xn,yn,zn);
if (TMath::Abs(yn)>ymax1) continue;
nfoundable++;
AliTPCclusterMI * cln = kr->FindNearest(yn,zn,roady,roadz);
if (cln) {
Float_t dist = TMath::Sqrt( (yn-cln->GetY())*(yn-cln->GetY())+(zn-cln->GetZ())*(zn-cln->GetZ()));
if (dist<maxdist){
/*
erry = (dist+0.3)*cln->GetSigmaY2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
errz = (dist+0.3)*cln->GetSigmaZ2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
if (cln->IsUsed(10)) {
// printf("used\n");
sumused++;
erry*=2;
errz*=2;
}
*/
erry=0.1;
errz=0.1;
polytrack.AddPoint(xn,cln->GetY(),cln->GetZ(),erry, errz);
nfound++;
}
}
}
if ( (sumused>3) || (sumused>0.5*nfound) || (nfound<0.6*nfoundable)) break;
polytrack.UpdateParameters();
}
}
if ( (sumused>3) || (sumused>0.5*nfound)) {
//printf("sumused %d\n",sumused);
continue;
}
nin1++;
Double_t dy,dz;
polytrack.GetFitDerivation(kr0.GetX(),dy,dz);
AliTPCpolyTrack track2;
polytrack.Refit(track2,0.5+TMath::Abs(dy)*0.3,0.4+TMath::Abs(dz)*0.3);
if (track2.GetN()<0.5*nfoundable) continue;
nin2++;
if ((nfound>0.6*nfoundable) &&( nfoundable>0.4*(i1-i2))) {
//
// test seed with and without constrain
for (Int_t constrain=0; constrain<=0;constrain++){
// add polytrack candidate
Double_t x[5], c[15];
Double_t x1,x2,x3,y1,y2,y3,z1,z2,z3;
track2.GetBoundaries(x3,x1);
x2 = (x1+x3)/2.;
track2.GetFitPoint(x1,y1,z1);
track2.GetFitPoint(x2,y2,z2);
track2.GetFitPoint(x3,y3,z3);
//
//is track pointing to the vertex ?
Double_t x0,y0,z0;
x0=0;
polytrack.GetFitPoint(x0,y0,z0);
if (constrain) {
x2 = x3;
y2 = y3;
z2 = z3;
x3 = 0;
y3 = 0;
z3 = 0;
}
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
// if (TMath::Abs(x[4]) >= cuts[0]) continue; //
x[2]=F2(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]*x1-x[2]) >= cuts[1]) continue;
//x[3]=F3(x1,y1,x2,y2,z1,z2);
x[3]=F3n(x1,y1,x3,y3,z1,z3,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
Double_t sy =0.1, sz =0.1;
Double_t sy1=0.02, sz1=0.02;
Double_t sy2=0.02, sz2=0.02;
Double_t sy3=0.02;
if (constrain){
sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
}
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x3,y3,z1,z3)-x[3])/sy;
Double_t f31=(F3(x1,y1,x3,y3,z1+sz,z3)-x[3])/sz;
Double_t f32=(F3(x1,y1,x3,y3+sy,z1,z3)-x[3])/sy;
Double_t f34=(F3(x1,y1,x3,y3,z1,z3+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
//Int_t row1 = fSectors->GetRowNumber(x1);
Int_t row1 = GetRowNumber(x1);
UInt_t index=0;
//kr0.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1,sec*alpha+shift,x,c,index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
Int_t rc=FollowProlongation(*track, i2);
if (constrain) track->SetBConstrain(1);
else
track->SetBConstrain(0);
track->SetLastPoint(row1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (rc==0 || track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters()) {
MarkSeedFree( seed ); seed = 0;
}
else {
arr->AddLast(track); // track IS seed, don't free seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
}
nin3++;
}
} // if accepted seed
}
if (fDebug>3){
Info("MakeSeeds2","\nSeeding statiistic:\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin3);
}
if (seed) MarkSeedFree( seed );
}
AliTPCseed *AliTPCtracker::MakeSeed(AliTPCseed *const track, Float_t r0, Float_t r1, Float_t r2)
{
//
//
//reseed using track points
Int_t p0 = int(r0*track->GetNumberOfClusters()); // point 0
Int_t p1 = int(r1*track->GetNumberOfClusters());
Int_t p2 = int(r2*track->GetNumberOfClusters()); // last point
Int_t pp2=0;
Double_t x0[3],x1[3],x2[3];
for (Int_t i=0;i<3;i++){
x0[i]=-1;
x1[i]=-1;
x2[i]=-1;
}
// find track position at given ratio of the length
Int_t sec0=0, sec1=0, sec2=0;
Int_t index=-1;
Int_t clindex;
for (Int_t i=0;i<kMaxRow;i++){
if (track->GetClusterIndex2(i)>=0){
index++;
const AliTPCTrackerPoints::Point *trpoint =track->GetTrackPoint(i);
if ( (index<p0) || x0[0]<0 ){
if (trpoint->GetX()>1){
clindex = track->GetClusterIndex2(i);
if (clindex >= 0){
x0[0] = trpoint->GetX();
x0[1] = trpoint->GetY();
x0[2] = trpoint->GetZ();
sec0 = ((clindex&0xff000000)>>24)%18;
}
}
}
if ( (index<p1) &&(trpoint->GetX()>1)){
clindex = track->GetClusterIndex2(i);
if (clindex >= 0){
x1[0] = trpoint->GetX();
x1[1] = trpoint->GetY();
x1[2] = trpoint->GetZ();
sec1 = ((clindex&0xff000000)>>24)%18;
}
}
if ( (index<p2) &&(trpoint->GetX()>1)){
clindex = track->GetClusterIndex2(i);
if (clindex >= 0){
x2[0] = trpoint->GetX();
x2[1] = trpoint->GetY();
x2[2] = trpoint->GetZ();
sec2 = ((clindex&0xff000000)>>24)%18;
pp2 = i;
}
}
}
}
Double_t alpha, cs,sn, xx2,yy2;
//
alpha = (sec1-sec2)*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= x1[0]*cs-x1[1]*sn;
yy2= x1[0]*sn+x1[1]*cs;
x1[0] = xx2;
x1[1] = yy2;
//
alpha = (sec0-sec2)*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= x0[0]*cs-x0[1]*sn;
yy2= x0[0]*sn+x0[1]*cs;
x0[0] = xx2;
x0[1] = yy2;
//
//
//
Double_t x[5],c[15];
//
x[0]=x2[1];
x[1]=x2[2];
x[4]=F1(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]);
// if (x[4]>1) return 0;
x[2]=F2(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]);
x[3]=F3n(x2[0],x2[1],x0[0],x0[1],x2[2],x0[2],x[4]);
//if (TMath::Abs(x[3]) > 2.2) return 0;
//if (TMath::Abs(x[2]) > 1.99) return 0;
//
Double_t sy =0.1, sz =0.1;
//
Double_t sy1=0.02+track->GetSigmaY2(), sz1=0.02+track->GetSigmaZ2();
Double_t sy2=0.01+track->GetSigmaY2(), sz2=0.01+track->GetSigmaZ2();
Double_t sy3=0.01+track->GetSigmaY2();
//
Double_t f40=(F1(x2[0],x2[1]+sy,x1[0],x1[1],x0[0],x0[1])-x[4])/sy;
Double_t f42=(F1(x2[0],x2[1],x1[0],x1[1]+sy,x0[0],x0[1])-x[4])/sy;
Double_t f43=(F1(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]+sy)-x[4])/sy;
Double_t f20=(F2(x2[0],x2[1]+sy,x1[0],x1[1],x0[0],x0[1])-x[2])/sy;
Double_t f22=(F2(x2[0],x2[1],x1[0],x1[1]+sy,x0[0],x0[1])-x[2])/sy;
Double_t f23=(F2(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]+sy)-x[2])/sy;
//
Double_t f30=(F3(x2[0],x2[1]+sy,x0[0],x0[1],x2[2],x0[2])-x[3])/sy;
Double_t f31=(F3(x2[0],x2[1],x0[0],x0[1],x2[2]+sz,x0[2])-x[3])/sz;
Double_t f32=(F3(x2[0],x2[1],x0[0],x0[1]+sy,x2[2],x0[2])-x[3])/sy;
Double_t f34=(F3(x2[0],x2[1],x0[0],x0[1],x2[2],x0[2]+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// Int_t row1 = fSectors->GetRowNumber(x2[0]);
AliTPCseed *seed = new( NextFreeSeed() ) AliTPCseed(x2[0], sec2*fSectors->GetAlpha()+fSectors->GetAlphaShift(), x, c, 0);
seed->SetPoolID(fLastSeedID);
// Double_t y0,z0,y1,z1, y2,z2;
//seed->GetProlongation(x0[0],y0,z0);
// seed->GetProlongation(x1[0],y1,z1);
//seed->GetProlongation(x2[0],y2,z2);
// seed =0;
seed->SetLastPoint(pp2);
seed->SetFirstPoint(pp2);
return seed;
}
AliTPCseed *AliTPCtracker::ReSeed(const AliTPCseed *track, Float_t r0, Float_t r1, Float_t r2)
{
//
//
//reseed using founded clusters
//
// Find the number of clusters
Int_t nclusters = 0;
for (Int_t irow=0;irow<kMaxRow;irow++){
if (track->GetClusterIndex(irow)>0) nclusters++;
}
//
Int_t ipos[3];
ipos[0] = TMath::Max(int(r0*nclusters),0); // point 0 cluster
ipos[1] = TMath::Min(int(r1*nclusters),nclusters-1); //
ipos[2] = TMath::Min(int(r2*nclusters),nclusters-1); // last point
//
//
Double_t xyz[3][3]={{0}};
Int_t row[3]={0},sec[3]={0,0,0};
//
// find track row position at given ratio of the length
Int_t index=-1;
for (Int_t irow=0;irow<kMaxRow;irow++){
if (track->GetClusterIndex2(irow)<0) continue;
index++;
for (Int_t ipoint=0;ipoint<3;ipoint++){
if (index<=ipos[ipoint]) row[ipoint] = irow;
}
}
//
//Get cluster and sector position
for (Int_t ipoint=0;ipoint<3;ipoint++){
Int_t clindex = track->GetClusterIndex2(row[ipoint]);
AliTPCclusterMI * cl = clindex<0 ? 0:GetClusterMI(clindex);
if (cl==0) {
//Error("Bug\n");
// AliTPCclusterMI * cl = GetClusterMI(clindex);
return 0;
}
sec[ipoint] = ((clindex&0xff000000)>>24)%18;
xyz[ipoint][0] = GetXrow(row[ipoint]);
xyz[ipoint][1] = cl->GetY();
xyz[ipoint][2] = cl->GetZ();
}
//
//
// Calculate seed state vector and covariance matrix
Double_t alpha, cs,sn, xx2,yy2;
//
alpha = (sec[1]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[1][0]*cs-xyz[1][1]*sn;
yy2= xyz[1][0]*sn+xyz[1][1]*cs;
xyz[1][0] = xx2;
xyz[1][1] = yy2;
//
alpha = (sec[0]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[0][0]*cs-xyz[0][1]*sn;
yy2= xyz[0][0]*sn+xyz[0][1]*cs;
xyz[0][0] = xx2;
xyz[0][1] = yy2;
//
//
//
Double_t x[5],c[15];
//
x[0]=xyz[2][1];
x[1]=xyz[2][2];
x[4]=F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[2]=F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[3]=F3n(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2],x[4]);
//
Double_t sy =0.1, sz =0.1;
//
Double_t sy1=0.2, sz1=0.2;
Double_t sy2=0.2, sz2=0.2;
Double_t sy3=0.2;
//
Double_t f40=(F1(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f42=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f43=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[4])/sy;
Double_t f20=(F2(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f22=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f23=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[2])/sy;
//
Double_t f30=(F3(xyz[2][0],xyz[2][1]+sy,xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f31=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2]+sz,xyz[0][2])-x[3])/sz;
Double_t f32=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1]+sy,xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f34=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2]+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// Int_t row1 = fSectors->GetRowNumber(xyz[2][0]);
AliTPCseed *seed=new( NextFreeSeed() ) AliTPCseed(xyz[2][0], sec[2]*fSectors->GetAlpha()+fSectors->GetAlphaShift(), x, c, 0);
seed->SetPoolID(fLastSeedID);
seed->SetLastPoint(row[2]);
seed->SetFirstPoint(row[2]);
return seed;
}
AliTPCseed *AliTPCtracker::ReSeed(AliTPCseed *track,Int_t r0, Bool_t forward)
{
//
//
//reseed using founded clusters
//
Double_t xyz[3][3];
Int_t row[3]={0,0,0};
Int_t sec[3]={0,0,0};
//
// forward direction
if (forward){
for (Int_t irow=r0;irow<kMaxRow;irow++){
if (track->GetClusterIndex(irow)>0){
row[0] = irow;
break;
}
}
for (Int_t irow=kMaxRow;irow>r0;irow--){
if (track->GetClusterIndex(irow)>0){
row[2] = irow;
break;
}
}
for (Int_t irow=row[2]-15;irow>row[0];irow--){
if (track->GetClusterIndex(irow)>0){
row[1] = irow;
break;
}
}
//
}
if (!forward){
for (Int_t irow=0;irow<r0;irow++){
if (track->GetClusterIndex(irow)>0){
row[0] = irow;
break;
}
}
for (Int_t irow=r0;irow>0;irow--){
if (track->GetClusterIndex(irow)>0){
row[2] = irow;
break;
}
}
for (Int_t irow=row[2]-15;irow>row[0];irow--){
if (track->GetClusterIndex(irow)>0){
row[1] = irow;
break;
}
}
}
//
if ((row[2]-row[0])<20) return 0;
if (row[1]==0) return 0;
//
//
//Get cluster and sector position
for (Int_t ipoint=0;ipoint<3;ipoint++){
Int_t clindex = track->GetClusterIndex2(row[ipoint]);
AliTPCclusterMI * cl = clindex<0 ? 0:GetClusterMI(clindex);
if (cl==0) {
//Error("Bug\n");
// AliTPCclusterMI * cl = GetClusterMI(clindex);
return 0;
}
sec[ipoint] = ((clindex&0xff000000)>>24)%18;
xyz[ipoint][0] = GetXrow(row[ipoint]);
const AliTPCTrackerPoints::Point * point = track->GetTrackPoint(row[ipoint]);
if (point&&ipoint<2){
//
xyz[ipoint][1] = point->GetY();
xyz[ipoint][2] = point->GetZ();
}
else{
xyz[ipoint][1] = cl->GetY();
xyz[ipoint][2] = cl->GetZ();
}
}
//
//
//
//
// Calculate seed state vector and covariance matrix
Double_t alpha, cs,sn, xx2,yy2;
//
alpha = (sec[1]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[1][0]*cs-xyz[1][1]*sn;
yy2= xyz[1][0]*sn+xyz[1][1]*cs;
xyz[1][0] = xx2;
xyz[1][1] = yy2;
//
alpha = (sec[0]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[0][0]*cs-xyz[0][1]*sn;
yy2= xyz[0][0]*sn+xyz[0][1]*cs;
xyz[0][0] = xx2;
xyz[0][1] = yy2;
//
//
//
Double_t x[5],c[15];
//
x[0]=xyz[2][1];
x[1]=xyz[2][2];
x[4]=F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[2]=F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[3]=F3n(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2],x[4]);
//
Double_t sy =0.1, sz =0.1;
//
Double_t sy1=0.2, sz1=0.2;
Double_t sy2=0.2, sz2=0.2;
Double_t sy3=0.2;
//
Double_t f40=(F1(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f42=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f43=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[4])/sy;
Double_t f20=(F2(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f22=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f23=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[2])/sy;
//
Double_t f30=(F3(xyz[2][0],xyz[2][1]+sy,xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f31=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2]+sz,xyz[0][2])-x[3])/sz;
Double_t f32=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1]+sy,xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f34=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2]+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// Int_t row1 = fSectors->GetRowNumber(xyz[2][0]);
AliTPCseed *seed=new( NextFreeSeed() ) AliTPCseed(xyz[2][0], sec[2]*fSectors->GetAlpha()+fSectors->GetAlphaShift(), x, c, 0);
seed->SetPoolID(fLastSeedID);
seed->SetLastPoint(row[2]);
seed->SetFirstPoint(row[2]);
for (Int_t i=row[0];i<row[2];i++){
seed->SetClusterIndex(i, track->GetClusterIndex(i));
}
return seed;
}
void AliTPCtracker::FindMultiMC(const TObjArray * array, AliESDEvent */*esd*/, Int_t iter)
{
//
// find multi tracks - THIS FUNCTION IS ONLY FOR DEBUG PURPOSES
// USES MC LABELS
// Use AliTPCReconstructor::StreamLevel()& kStreamFindMultiMC if you want to tune parameters - cuts
//
// Two reasons to have multiple find tracks
// 1. Curling tracks can be find more than once
// 2. Splitted tracks
// a.) Multiple seeding to increase tracking efficiency - (~ 100% reached)
// b.) Edge effect on the sector boundaries
//
//
// Algorithm done in 2 phases - because of CPU consumption
// it is n^2 algorithm - for lead-lead 20000x20000 combination are investigated
//
// Algorihm for curling tracks sign:
// 1 phase -makes a very rough fast cuts to minimize combinatorics
// a.) opposite sign
// b.) one of the tracks - not pointing to the primary vertex -
// c.) delta tan(theta)
// d.) delta phi
// 2 phase - calculates DCA between tracks - time consument
//
// fast cuts
//
// General cuts - for splitted tracks and for curling tracks
//
const Float_t kMaxdPhi = 0.2; // maximal distance in phi
//
// Curling tracks cuts
//
//
//
//
Int_t nentries = array->GetEntriesFast();
if (!fHelixPool) fHelixPool = new TClonesArray("AliHelix",nentries+50);
fHelixPool->Clear();
TClonesArray& helixes = *fHelixPool;
Float_t xm[nentries];
Float_t dz0[nentries];
Float_t dz1[nentries];
//
//
TStopwatch timer;
timer.Start();
//
// Find track COG in x direction - point with best defined parameters
//
for (Int_t i=0;i<nentries;i++){
AliTPCseed* track = (AliTPCseed*)array->At(i);
if (!track) continue;
track->SetCircular(0);
new (helixes[i]) AliHelix(*track);
Int_t ncl=0;
xm[i]=0;
Float_t dz[2];
track->GetDZ(GetX(),GetY(),GetZ(),GetBz(),dz);
dz0[i]=dz[0];
dz1[i]=dz[1];
for (Int_t icl=0; icl<kMaxRow; icl++){
int tpcindex= track->GetClusterIndex2(icl);
const AliTPCclusterMI * cl = (tpcindex<0) ? 0:GetClusterMI(tpcindex);
//RS AliTPCclusterMI * cl = track->GetClusterPointer(icl);
if (cl) {
xm[i]+=cl->GetX();
ncl++;
}
}
if (ncl>0) xm[i]/=Float_t(ncl);
}
//
for (Int_t i0=0;i0<nentries;i0++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i0);
if (!track0) continue;
AliHelix* hlxi0 = (AliHelix*)helixes[i0];
Float_t xc0 = hlxi0->GetHelix(6);
Float_t yc0 = hlxi0->GetHelix(7);
Float_t r0 = hlxi0->GetHelix(8);
Float_t rc0 = TMath::Sqrt(xc0*xc0+yc0*yc0);
Float_t fi0 = TMath::ATan2(yc0,xc0);
for (Int_t i1=i0+1;i1<nentries;i1++){
AliTPCseed * track1 = (AliTPCseed*)array->At(i1);
if (!track1) continue;
Int_t lab0=track0->GetLabel();
Int_t lab1=track1->GetLabel();
if (TMath::Abs(lab0)!=TMath::Abs(lab1)) continue;
//
AliHelix* hlxi1 = (AliHelix*)helixes[i1];
Float_t xc1 = hlxi1->GetHelix(6);
Float_t yc1 = hlxi1->GetHelix(7);
Float_t r1 = hlxi1->GetHelix(8);
Float_t rc1 = TMath::Sqrt(xc1*xc1+yc1*yc1);
Float_t fi1 = TMath::ATan2(yc1,xc1);
//
Float_t dfi = fi0-fi1;
//
//
if (dfi>1.5*TMath::Pi()) dfi-=TMath::Pi(); // take care about edge effect
if (dfi<-1.5*TMath::Pi()) dfi+=TMath::Pi(); //
if (TMath::Abs(dfi)>kMaxdPhi&&hlxi0->GetHelix(4)*hlxi1->GetHelix(4)<0){
//
// if short tracks with undefined sign
fi1 = -TMath::ATan2(yc1,-xc1);
dfi = fi0-fi1;
}
Float_t dtheta = TMath::Abs(track0->GetTgl()-track1->GetTgl())<TMath::Abs(track0->GetTgl()+track1->GetTgl())? track0->GetTgl()-track1->GetTgl():track0->GetTgl()+track1->GetTgl();
//
// debug stream to tune "fast cuts"
//
Double_t dist[3]; // distance at X
Double_t mdist[3]={0,0,0}; // mean distance X+-40cm
track0->GetDistance(track1,0.5*(xm[i0]+xm[i1])-40.,dist,AliTracker::GetBz());
for (Int_t i=0;i<3;i++) mdist[i]+=TMath::Abs(dist[i]);
track0->GetDistance(track1,0.5*(xm[i0]+xm[i1])+40.,dist,AliTracker::GetBz());
for (Int_t i=0;i<3;i++) mdist[i]+=TMath::Abs(dist[i]);
track0->GetDistance(track1,0.5*(xm[i0]+xm[i1]),dist,AliTracker::GetBz());
for (Int_t i=0;i<3;i++) mdist[i]+=TMath::Abs(dist[i]);
for (Int_t i=0;i<3;i++) mdist[i]*=0.33333;
Float_t sum =0;
Float_t sums=0;
for (Int_t icl=0; icl<kMaxRow; icl++){
Int_t tpcindex0 = track0->GetClusterIndex2(icl);
Int_t tpcindex1 = track1->GetClusterIndex2(icl);
//RS AliTPCclusterMI * cl0 = track0->GetClusterPointer(icl);
//RS AliTPCclusterMI * cl1 = track1->GetClusterPointer(icl);
//RS if (cl0&&cl1) {
if (tpcindex0>=0 && tpcindex1>=0) {
sum++;
if (tpcindex0==tpcindex1) sums++; //RS if (cl0==cl1) sums++;
}
}
//
if ((AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC)>0) { // flag: stream MC infomation about the multiple find track (ONLY for MC data)
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Multi"<<
"iter="<<iter<<
"lab0="<<lab0<<
"lab1="<<lab1<<
"Tr0.="<<track0<< // seed0
"Tr1.="<<track1<< // seed1
"h0.="<<hlxi0<<
"h1.="<<hlxi1<<
//
"sum="<<sum<< //the sum of rows with cl in both
"sums="<<sums<< //the sum of shared clusters
"xm0="<<xm[i0]<< // the center of track
"xm1="<<xm[i1]<< // the x center of track
// General cut variables
"dfi="<<dfi<< // distance in fi angle
"dtheta="<<dtheta<< // distance int theta angle
//
"dz00="<<dz0[i0]<<
"dz01="<<dz0[i1]<<
"dz10="<<dz1[i1]<<
"dz11="<<dz1[i1]<<
"dist0="<<dist[0]<< //distance x
"dist1="<<dist[1]<< //distance y
"dist2="<<dist[2]<< //distance z
"mdist0="<<mdist[0]<< //distance x
"mdist1="<<mdist[1]<< //distance y
"mdist2="<<mdist[2]<< //distance z
//
"r0="<<r0<<
"rc0="<<rc0<<
"fi0="<<fi0<<
"fi1="<<fi1<<
"r1="<<r1<<
"rc1="<<rc1<<
"\n";
}
}
}
if (fHelixPool) fHelixPool->Clear();
// delete [] helixes; // RS moved to stack
// delete [] xm;
// delete [] dz0;
// delete [] dz1;
if (AliTPCReconstructor::StreamLevel()>0) {
AliInfo("Time for curling tracks removal DEBUGGING MC");
timer.Print();
}
}
void AliTPCtracker::FindSplitted(TObjArray * array, AliESDEvent */*esd*/, Int_t /*iter*/){
//
// Find Splitted tracks and remove the one with worst quality
// Corresponding debug streamer to tune selections - "Splitted2"
// Algorithm:
// 0. Sort tracks according quality
// 1. Propagate the tracks to the reference radius
// 2. Double_t loop to select close tracks (only to speed up process)
// 3. Calculate cluster overlap ratio - and remove the track if bigger than a threshold
// 4. Delete temporary parameters
//
const Double_t xref=GetXrow(63); // reference radius -IROC/OROC boundary
// rough cuts
const Double_t kCutP1=10; // delta Z cut 10 cm
const Double_t kCutP2=0.15; // delta snp(fi) cut 0.15
const Double_t kCutP3=0.15; // delta tgl(theta) cut 0.15
const Double_t kCutAlpha=0.15; // delta alpha cut
Int_t firstpoint = 0;
Int_t lastpoint = kMaxRow;
//
Int_t nentries = array->GetEntriesFast();
if (!fETPPool) fETPPool = new TClonesArray("AliExternalTrackParam",nentries+50);
else fETPPool->Clear();
TClonesArray ¶ms = *fETPPool;
//
//
TStopwatch timer;
timer.Start();
//
//0. Sort tracks according quality
//1. Propagate the ext. param to reference radius
Int_t nseed = array->GetEntriesFast();
if (nseed<=0) return;
Float_t quality[nseed];
Int_t indexes[nseed];
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)array->UncheckedAt(i);
if (!pt){
quality[i]=-1;
continue;
}
pt->UpdatePoints(); //select first last max dens points
Float_t * points = pt->GetPoints();
if (points[3]<0.8) quality[i] =-1;
quality[i] = (points[2]-points[0])+pt->GetNumberOfClusters();
//prefer high momenta tracks if overlaps
quality[i] *= TMath::Sqrt(TMath::Abs(pt->Pt())+0.5);
AliExternalTrackParam* parI = new (params[i]) AliExternalTrackParam(*pt);
// params[i]=(*pt);
AliTracker::PropagateTrackParamOnlyToBxByBz(parI,xref,5.,kTRUE);
// AliTracker::PropagateTrackToBxByBz(parI,xref,pt->GetMass(),1.,kTRUE); //RS What is the point of 2nd propagation
}
TMath::Sort(nseed,quality,indexes);
//
// 3. Loop over pair of tracks
//
for (Int_t i0=0; i0<nseed; i0++) {
Int_t index0=indexes[i0];
if (!(array->UncheckedAt(index0))) continue;
AliTPCseed *s1 = (AliTPCseed*)array->UncheckedAt(index0);
if (!s1->IsActive()) continue;
AliExternalTrackParam &par0=*(AliExternalTrackParam*)params[index0];
for (Int_t i1=i0+1; i1<nseed; i1++) {
Int_t index1=indexes[i1];
if (!(array->UncheckedAt(index1))) continue;
AliTPCseed *s2 = (AliTPCseed*)array->UncheckedAt(index1);
if (!s2->IsActive()) continue;
if (s2->GetKinkIndexes()[0]!=0)
if (s2->GetKinkIndexes()[0] == -s1->GetKinkIndexes()[0]) continue;
AliExternalTrackParam &par1=*(AliExternalTrackParam*)params[index1];
if (TMath::Abs(par0.GetParameter()[3]-par1.GetParameter()[3])>kCutP3) continue;
if (TMath::Abs(par0.GetParameter()[1]-par1.GetParameter()[1])>kCutP1) continue;
if (TMath::Abs(par0.GetParameter()[2]-par1.GetParameter()[2])>kCutP2) continue;
Double_t dAlpha= TMath::Abs(par0.GetAlpha()-par1.GetAlpha());
if (dAlpha>TMath::Pi()) dAlpha-=TMath::Pi();
if (TMath::Abs(dAlpha)>kCutAlpha) continue;
//
Int_t sumShared=0;
Int_t nall0=0;
Int_t nall1=0;
Int_t firstShared=lastpoint, lastShared=firstpoint;
Int_t firstRow=lastpoint, lastRow=firstpoint;
//
// for (Int_t i=firstpoint;i<lastpoint;i++){
// if (s1->GetClusterIndex2(i)>0) nall0++;
// if (s2->GetClusterIndex2(i)>0) nall1++;
// if (s1->GetClusterIndex2(i)>0 && s2->GetClusterIndex2(i)>0) {
// if (i<firstRow) firstRow=i;
// if (i>lastRow) lastRow=i;
// }
// if ( (s1->GetClusterIndex2(i))==(s2->GetClusterIndex2(i)) && s1->GetClusterIndex2(i)>0) {
// if (i<firstShared) firstShared=i;
// if (i>lastShared) lastShared=i;
// sumShared++;
// }
// }
//
// RS: faster version + fix(?) ">" -> ">="
for (Int_t i=firstpoint;i<lastpoint;i++){
int ind1=s1->GetClusterIndex2(i),ind2=s2->GetClusterIndex2(i);
if (ind1>=0) nall0++; // RS: ">" -> ">="
if (ind2>=0) nall1++;
if (ind1>=0 && ind2>=0) {
if (i<firstRow) firstRow=i;
if (i>lastRow) lastRow=i;
}
if ( (ind1==ind2) && ind1>=0) {
if (i<firstShared) firstShared=i;
if (i>lastShared) lastShared=i;
sumShared++;
}
}
Double_t ratio0 = Float_t(sumShared)/Float_t(TMath::Min(nall0+1,nall1+1));
Double_t ratio1 = Float_t(sumShared)/Float_t(TMath::Max(nall0+1,nall1+1));
if ((AliTPCReconstructor::StreamLevel()&kStreamSplitted2)>0){ // flag:stream information about discarded TPC tracks pair algorithm
TTreeSRedirector &cstream = *fDebugStreamer;
Int_t n0=s1->GetNumberOfClusters();
Int_t n1=s2->GetNumberOfClusters();
Int_t n0F=s1->GetNFoundable();
Int_t n1F=s2->GetNFoundable();
Int_t lab0=s1->GetLabel();
Int_t lab1=s2->GetLabel();
cstream<<"Splitted2"<< // flag:stream information about discarded TPC tracks pair algorithm
"iter="<<fIteration<<
"lab0="<<lab0<< // MC label if exist
"lab1="<<lab1<< // MC label if exist
"index0="<<index0<<
"index1="<<index1<<
"ratio0="<<ratio0<< // shared ratio
"ratio1="<<ratio1<< // shared ratio
"p0.="<<&par0<< // track parameters
"p1.="<<&par1<<
"s0.="<<s1<< // full seed
"s1.="<<s2<<
"n0="<<n0<< // number of clusters track 0
"n1="<<n1<< // number of clusters track 1
"nall0="<<nall0<< // number of clusters track 0
"nall1="<<nall1<< // number of clusters track 1
"n0F="<<n0F<< // number of findable
"n1F="<<n1F<< // number of findable
"shared="<<sumShared<< // number of shared clusters
"firstS="<<firstShared<< // first and the last shared row
"lastS="<<lastShared<<
"firstRow="<<firstRow<< // first and the last row with cluster
"lastRow="<<lastRow<< //
"\n";
}
//
// remove track with lower quality
//
if (ratio0>AliTPCReconstructor::GetRecoParam()->GetCutSharedClusters(0) ||
ratio1>AliTPCReconstructor::GetRecoParam()->GetCutSharedClusters(1)){
//
//
//
MarkSeedFree( array->RemoveAt(index1) );
}
}
}
//
// 4. Delete temporary array
//
if (fETPPool) fETPPool->Clear();
// delete [] params; // RS moved to stack
// delete [] quality;
// delete [] indexes;
}
void AliTPCtracker::FindCurling(const TObjArray * array, AliESDEvent */*esd*/, Int_t iter)
{
//
// find Curling tracks
// Use AliTPCReconstructor::StreamLevel()&kStreamFindCurling if you want to tune parameters - cuts
//
//
// Algorithm done in 2 phases - because of CPU consumption
// it is n^2 algorithm - for lead-lead 20000x20000 combination are investigated
// see detal in MC part what can be used to cut
//
//
//
const Float_t kMaxC = 400; // maximal curvature to of the track
const Float_t kMaxdTheta = 0.15; // maximal distance in theta
const Float_t kMaxdPhi = 0.15; // maximal distance in phi
const Float_t kPtRatio = 0.3; // ratio between pt
const Float_t kMinDCAR = 2.; // distance to the primary vertex in r - see cpipe cut
//
// Curling tracks cuts
//
//
const Float_t kMaxDeltaRMax = 40; // distance in outer radius
const Float_t kMaxDeltaRMin = 5.; // distance in lower radius - see cpipe cut
const Float_t kMinAngle = 2.9; // angle between tracks
const Float_t kMaxDist = 5; // biggest distance
//
// The cuts can be tuned using the "MC information stored in Multi tree ==> see FindMultiMC
/*
Fast cuts:
TCut csign("csign","Tr0.fP[4]*Tr1.fP[4]<0"); //opposite sign
TCut cmax("cmax","abs(Tr0.GetC())>1/400");
TCut cda("cda","sqrt(dtheta^2+dfi^2)<0.15");
TCut ccratio("ccratio","abs((Tr0.fP[4]+Tr1.fP[4])/(abs(Tr0.fP[4])+abs(Tr1.fP[4])))<0.3");
TCut cpipe("cpipe", "min(abs(r0-rc0),abs(r1-rc1))>5");
//
TCut cdrmax("cdrmax","abs(abs(rc0+r0)-abs(rc1+r1))<40")
TCut cdrmin("cdrmin","abs(abs(rc0+r0)-abs(rc1+r1))<10")
//
Multi->Draw("dfi","iter==0"+csign+cmax+cda+ccratio); ~94% of curling tracks fulfill
Multi->Draw("min(abs(r0-rc0),abs(r1-rc1))","iter==0&&abs(lab1)==abs(lab0)"+csign+cmax+cda+ccratio+cpipe+cdrmin+cdrmax); //80%
//
Curling2->Draw("dfi","iter==0&&abs(lab0)==abs(lab1)"+csign+cmax+cdtheta+cdfi+ccratio)
*/
//
//
//
Int_t nentries = array->GetEntriesFast();
if (!fHelixPool) fHelixPool = new TClonesArray("AliHelix",nentries+100);
fHelixPool->Clear();
TClonesArray& helixes = *fHelixPool;
for (Int_t i=0;i<nentries;i++){
AliTPCseed* track = (AliTPCseed*)array->At(i);
if (!track) continue;
track->SetCircular(0);
new (helixes[i]) AliHelix(*track);
}
//
//
TStopwatch timer;
timer.Start();
Double_t phase[2][2]={{0,0},{0,0}},radius[2]={0,0};
//
// Find tracks
//
//
for (Int_t i0=0;i0<nentries;i0++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i0);
if (!track0) continue;
if (TMath::Abs(track0->GetC())<1/kMaxC) continue;
AliHelix* hlxi0 = (AliHelix*)helixes[i0];
Float_t xc0 = hlxi0->GetHelix(6);
Float_t yc0 = hlxi0->GetHelix(7);
Float_t r0 = hlxi0->GetHelix(8);
Float_t rc0 = TMath::Sqrt(xc0*xc0+yc0*yc0);
Float_t fi0 = TMath::ATan2(yc0,xc0);
for (Int_t i1=i0+1;i1<nentries;i1++){
AliTPCseed * track1 = (AliTPCseed*)array->At(i1);
if (!track1) continue;
if (TMath::Abs(track1->GetC())<1/kMaxC) continue;
AliHelix* hlxi1 = (AliHelix*)helixes[i1];
Float_t xc1 = hlxi1->GetHelix(6);
Float_t yc1 = hlxi1->GetHelix(7);
Float_t r1 = hlxi1->GetHelix(8);
Float_t rc1 = TMath::Sqrt(xc1*xc1+yc1*yc1);
Float_t fi1 = TMath::ATan2(yc1,xc1);
//
Float_t dfi = fi0-fi1;
//
//
if (dfi>1.5*TMath::Pi()) dfi-=TMath::Pi(); // take care about edge effect
if (dfi<-1.5*TMath::Pi()) dfi+=TMath::Pi(); //
Float_t dtheta = TMath::Abs(track0->GetTgl()-track1->GetTgl())<TMath::Abs(track0->GetTgl()+track1->GetTgl())? track0->GetTgl()-track1->GetTgl():track0->GetTgl()+track1->GetTgl();
//
//
// FIRST fast cuts
if (track0->GetBConstrain()&&track1->GetBConstrain()) continue; // not constrained
if (track1->GetSigned1Pt()*track0->GetSigned1Pt()>0) continue; // not the same sign
if ( TMath::Abs(track1->GetTgl()+track0->GetTgl())>kMaxdTheta) continue; //distance in the Theta
if ( TMath::Abs(dfi)>kMaxdPhi) continue; //distance in phi
if ( TMath::Sqrt(dfi*dfi+dtheta*dtheta)>kMaxdPhi) continue; //common angular offset
//
Float_t pt0 = track0->GetSignedPt();
Float_t pt1 = track1->GetSignedPt();
if ((TMath::Abs(pt0+pt1)/(TMath::Abs(pt0)+TMath::Abs(pt1)))>kPtRatio) continue;
if ((iter==1) && TMath::Abs(TMath::Abs(rc0+r0)-TMath::Abs(rc1+r1))>kMaxDeltaRMax) continue;
if ((iter!=1) &&TMath::Abs(TMath::Abs(rc0-r0)-TMath::Abs(rc1-r1))>kMaxDeltaRMin) continue;
if (TMath::Min(TMath::Abs(rc0-r0),TMath::Abs(rc1-r1))<kMinDCAR) continue;
//
//
// Now find closest approach
//
//
//
Int_t npoints = hlxi0->GetRPHIintersections(*hlxi1, phase, radius,10);
if (npoints==0) continue;
hlxi0->GetClosestPhases(*hlxi1, phase);
//
Double_t xyz0[3];
Double_t xyz1[3];
Double_t hangles[3];
hlxi0->Evaluate(phase[0][0],xyz0);
hlxi1->Evaluate(phase[0][1],xyz1);
hlxi0->GetAngle(phase[0][0],*hlxi1,phase[0][1],hangles);
Double_t deltah[2],deltabest;
if (TMath::Abs(hangles[2])<kMinAngle) continue;
if (npoints>0){
Int_t ibest=0;
hlxi0->ParabolicDCA(*hlxi1,phase[0][0],phase[0][1],radius[0],deltah[0],2);
if (npoints==2){
hlxi0->ParabolicDCA(*hlxi1,phase[1][0],phase[1][1],radius[1],deltah[1],2);
if (deltah[1]<deltah[0]) ibest=1;
}
deltabest = TMath::Sqrt(deltah[ibest]);
hlxi0->Evaluate(phase[ibest][0],xyz0);
hlxi1->Evaluate(phase[ibest][1],xyz1);
hlxi0->GetAngle(phase[ibest][0],*hlxi1,phase[ibest][1],hangles);
Double_t radiusbest = TMath::Sqrt(radius[ibest]);
//
if (deltabest>kMaxDist) continue;
// if (mindcar+mindcaz<40 && (TMath::Abs(hangles[2])<kMinAngle ||deltabest>3)) continue;
Bool_t sign =kFALSE;
if (hangles[2]>kMinAngle) sign =kTRUE;
//
if (sign){
// circular[i0] = kTRUE;
// circular[i1] = kTRUE;
if (track0->OneOverPt()<track1->OneOverPt()){
track0->SetCircular(track0->GetCircular()+1);
track1->SetCircular(track1->GetCircular()+2);
}
else{
track1->SetCircular(track1->GetCircular()+1);
track0->SetCircular(track0->GetCircular()+2);
}
}
if ((AliTPCReconstructor::StreamLevel()&kStreamFindCurling)>0){ // flag: stream track infroamtion if the FindCurling tracks method
//
//debug stream to tune "fine" cuts
Int_t lab0=track0->GetLabel();
Int_t lab1=track1->GetLabel();
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Curling2"<<
"iter="<<iter<<
"lab0="<<lab0<<
"lab1="<<lab1<<
"Tr0.="<<track0<<
"Tr1.="<<track1<<
//
"r0="<<r0<<
"rc0="<<rc0<<
"fi0="<<fi0<<
"r1="<<r1<<
"rc1="<<rc1<<
"fi1="<<fi1<<
"dfi="<<dfi<<
"dtheta="<<dtheta<<
//
"npoints="<<npoints<<
"hangles0="<<hangles[0]<<
"hangles1="<<hangles[1]<<
"hangles2="<<hangles[2]<<
"xyz0="<<xyz0[2]<<
"xyzz1="<<xyz1[2]<<
"radius="<<radiusbest<<
"deltabest="<<deltabest<<
"phase0="<<phase[ibest][0]<<
"phase1="<<phase[ibest][1]<<
"\n";
}
}
}
}
if (fHelixPool) fHelixPool->Clear();
// delete [] helixes; //RS moved to stack
if (AliTPCReconstructor::StreamLevel()>1) {
AliInfo("Time for curling tracks removal");
timer.Print();
}
}
void AliTPCtracker::FindKinks(TObjArray * array, AliESDEvent *esd)
{
//
// find kinks
//
//
// RS something is wrong in this routine: not all seeds are assigned to daughters and mothers array, but they all are queried
// to check later
TObjArray kinks(10000);
Int_t nentries = array->GetEntriesFast();
Char_t sign[nentries];
UChar_t nclusters[nentries];
Float_t alpha[nentries];
UChar_t usage[nentries];
Float_t zm[nentries];
Float_t z0[nentries];
Float_t fim[nentries];
Bool_t shared[nentries];
Bool_t circular[nentries];
Float_t dca[nentries];
AliKink *kink = new AliKink();
//
if (!fHelixPool) fHelixPool = new TClonesArray("AliHelix",nentries+100);
fHelixPool->Clear();
TClonesArray& helixes = *fHelixPool;
//const AliESDVertex * primvertex = esd->GetVertex();
//
// nentries = array->GetEntriesFast();
//
//
//
for (Int_t i=0;i<nentries;i++){
sign[i]=0;
usage[i]=0;
AliTPCseed* track = (AliTPCseed*)array->At(i);
if (!track) continue;
track->SetCircular(0);
shared[i] = kFALSE;
track->UpdatePoints();
if (( track->GetPoints()[2]- track->GetPoints()[0])>5 && track->GetPoints()[3]>0.8){
}
nclusters[i]=track->GetNumberOfClusters();
alpha[i] = track->GetAlpha();
AliHelix* hlxi = new (helixes[i]) AliHelix(*track);
Double_t xyz[3];
hlxi->Evaluate(0,xyz);
sign[i] = (track->GetC()>0) ? -1:1;
Double_t x,y,z;
x=160;
if (track->GetProlongation(x,y,z)){
zm[i] = z;
fim[i] = alpha[i]+TMath::ATan2(y,x);
}
else{
zm[i] = track->GetZ();
fim[i] = alpha[i];
}
z0[i]=1000;
circular[i]= kFALSE;
if (track->GetProlongation(0,y,z)) z0[i] = z;
dca[i] = track->GetD(0,0);
}
//
//
TStopwatch timer;
timer.Start();
Int_t ncandidates =0;
Int_t nall =0;
Int_t ntracks=0;
Double_t phase[2][2]={{0,0},{0,0}},radius[2]={0,0};
//
// Find circling track
//
for (Int_t i0=0;i0<nentries;i0++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i0);
if (!track0) continue;
if (track0->GetNumberOfClusters()<40) continue;
if (TMath::Abs(1./track0->GetC())>200) continue;
AliHelix* hlxi0 = (AliHelix*)helixes[i0];
//
for (Int_t i1=i0+1;i1<nentries;i1++){
AliTPCseed * track1 = (AliTPCseed*)array->At(i1);
if (!track1) continue;
if (track1->GetNumberOfClusters()<40) continue;
if ( TMath::Abs(track1->GetTgl()+track0->GetTgl())>0.1) continue;
if (track0->GetBConstrain()&&track1->GetBConstrain()) continue;
if (TMath::Abs(1./track1->GetC())>200) continue;
if (track1->GetSigned1Pt()*track0->GetSigned1Pt()>0) continue;
if (track1->GetTgl()*track0->GetTgl()>0) continue;
if (TMath::Max(TMath::Abs(1./track0->GetC()),TMath::Abs(1./track1->GetC()))>190) continue;
if (track0->GetBConstrain()&&track1->OneOverPt()<track0->OneOverPt()) continue; //returning - lower momenta
if (track1->GetBConstrain()&&track0->OneOverPt()<track1->OneOverPt()) continue; //returning - lower momenta
//
Float_t mindcar = TMath::Min(TMath::Abs(dca[i0]),TMath::Abs(dca[i1]));
if (mindcar<5) continue;
Float_t mindcaz = TMath::Min(TMath::Abs(z0[i0]-GetZ()),TMath::Abs(z0[i1]-GetZ()));
if (mindcaz<5) continue;
if (mindcar+mindcaz<20) continue;
//
AliHelix* hlxi1 = (AliHelix*)helixes[i1];
//
Float_t xc0 = hlxi0->GetHelix(6);
Float_t yc0 = hlxi0->GetHelix(7);
Float_t r0 = hlxi0->GetHelix(8);
Float_t xc1 = hlxi1->GetHelix(6);
Float_t yc1 = hlxi1->GetHelix(7);
Float_t r1 = hlxi1->GetHelix(8);
Float_t rmean = (r0+r1)*0.5;
Float_t delta =TMath::Sqrt((xc1-xc0)*(xc1-xc0)+(yc1-yc0)*(yc1-yc0));
//if (delta>30) continue;
if (delta>rmean*0.25) continue;
if (TMath::Abs(r0-r1)/rmean>0.3) continue;
//
Int_t npoints = hlxi0->GetRPHIintersections(*hlxi1, phase, radius,10);
if (npoints==0) continue;
hlxi0->GetClosestPhases(*hlxi1, phase);
//
Double_t xyz0[3];
Double_t xyz1[3];
Double_t hangles[3];
hlxi0->Evaluate(phase[0][0],xyz0);
hlxi1->Evaluate(phase[0][1],xyz1);
hlxi0->GetAngle(phase[0][0],*hlxi1,phase[0][1],hangles);
Double_t deltah[2],deltabest;
if (hangles[2]<2.8) continue;
if (npoints>0){
Int_t ibest=0;
hlxi0->ParabolicDCA(*hlxi1,phase[0][0],phase[0][1],radius[0],deltah[0],2);
if (npoints==2){
hlxi0->ParabolicDCA(*hlxi1,phase[1][0],phase[1][1],radius[1],deltah[1],2);
if (deltah[1]<deltah[0]) ibest=1;
}
deltabest = TMath::Sqrt(deltah[ibest]);
hlxi0->Evaluate(phase[ibest][0],xyz0);
hlxi1->Evaluate(phase[ibest][1],xyz1);
hlxi0->GetAngle(phase[ibest][0],*hlxi1,phase[ibest][1],hangles);
Double_t radiusbest = TMath::Sqrt(radius[ibest]);
//
if (deltabest>6) continue;
if (mindcar+mindcaz<40 && (hangles[2]<3.12||deltabest>3)) continue;
Bool_t lsign =kFALSE;
if (hangles[2]>3.06) lsign =kTRUE;
//
if (lsign){
circular[i0] = kTRUE;
circular[i1] = kTRUE;
if (track0->OneOverPt()<track1->OneOverPt()){
track0->SetCircular(track0->GetCircular()+1);
track1->SetCircular(track1->GetCircular()+2);
}
else{
track1->SetCircular(track1->GetCircular()+1);
track0->SetCircular(track0->GetCircular()+2);
}
}
if (lsign&&((AliTPCReconstructor::StreamLevel()&kStreamFindCurling)>0)){
//debug stream
Int_t lab0=track0->GetLabel();
Int_t lab1=track1->GetLabel();
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Curling"<<
"lab0="<<lab0<<
"lab1="<<lab1<<
"Tr0.="<<track0<<
"Tr1.="<<track1<<
"dca0="<<dca[i0]<<
"dca1="<<dca[i1]<<
"mindcar="<<mindcar<<
"mindcaz="<<mindcaz<<
"delta="<<delta<<
"rmean="<<rmean<<
"npoints="<<npoints<<
"hangles0="<<hangles[0]<<
"hangles2="<<hangles[2]<<
"xyz0="<<xyz0[2]<<
"xyzz1="<<xyz1[2]<<
"z0="<<z0[i0]<<
"z1="<<z0[i1]<<
"radius="<<radiusbest<<
"deltabest="<<deltabest<<
"phase0="<<phase[ibest][0]<<
"phase1="<<phase[ibest][1]<<
"\n";
}
}
}
}
//
// Finf kinks loop
//
//
for (Int_t i =0;i<nentries;i++){
if (sign[i]==0) continue;
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (track0==0) {
AliInfo("seed==0");
continue;
}
ntracks++;
//
Double_t cradius0 = 40*40;
Double_t cradius1 = 270*270;
Double_t cdist1=8.;
Double_t cdist2=8.;
Double_t cdist3=0.55;
AliHelix* hlxi = (AliHelix*)helixes[i];
for (Int_t j =i+1;j<nentries;j++){
nall++;
if (sign[j]*sign[i]<1) continue;
int ncltot = nclusters[i];
ncltot += nclusters[j];
if ( ncltot>200) continue;
if ( ncltot<80) continue;
if ( TMath::Abs(zm[i]-zm[j])>60.) continue;
if ( TMath::Abs(fim[i]-fim[j])>0.6 && TMath::Abs(fim[i]-fim[j])<5.7 ) continue;
//AliTPCseed * track1 = (AliTPCseed*)array->At(j); Double_t phase[2][2],radius[2];
AliHelix* hlxj = (AliHelix*)helixes[j];
Int_t npoints = hlxi->GetRPHIintersections(*hlxj, phase, radius,20);
if (npoints<1) continue;
// cuts on radius
if (npoints==1){
if (radius[0]<cradius0||radius[0]>cradius1) continue;
}
else{
if ( (radius[0]<cradius0||radius[0]>cradius1) && (radius[1]<cradius0||radius[1]>cradius1) ) continue;
}
//
Double_t delta1=10000,delta2=10000;
// cuts on the intersection radius
hlxi->LinearDCA(*hlxj,phase[0][0],phase[0][1],radius[0],delta1);
if (radius[0]<20&&delta1<1) continue; //intersection at vertex
if (radius[0]<10&&delta1<3) continue; //intersection at vertex
if (npoints==2){
hlxi->LinearDCA(*hlxj,phase[1][0],phase[1][1],radius[1],delta2);
if (radius[1]<20&&delta2<1) continue; //intersection at vertex
if (radius[1]<10&&delta2<3) continue; //intersection at vertex
}
//
Double_t distance1 = TMath::Min(delta1,delta2);
if (distance1>cdist1) continue; // cut on DCA linear approximation
//
npoints = hlxi->GetRPHIintersections(*hlxj, phase, radius,20);
hlxi->ParabolicDCA(*hlxj,phase[0][0],phase[0][1],radius[0],delta1);
if (radius[0]<20&&delta1<1) continue; //intersection at vertex
if (radius[0]<10&&delta1<3) continue; //intersection at vertex
//
if (npoints==2){
hlxi->ParabolicDCA(*hlxj,phase[1][0],phase[1][1],radius[1],delta2);
if (radius[1]<20&&delta2<1) continue; //intersection at vertex
if (radius[1]<10&&delta2<3) continue; //intersection at vertex
}
distance1 = TMath::Min(delta1,delta2);
Float_t rkink =0;
if (delta1<delta2){
rkink = TMath::Sqrt(radius[0]);
}
else{
rkink = TMath::Sqrt(radius[1]);
}
if (distance1>cdist2) continue;
//
//
AliTPCseed * track1 = (AliTPCseed*)array->At(j);
//
//
Int_t row0 = GetRowNumber(rkink);
if (row0<10) continue;
if (row0>150) continue;
//
//
Float_t dens00=-1,dens01=-1;
Float_t dens10=-1,dens11=-1;
//
Int_t found,foundable;//,ishared;
//RS Seed don't keep their cluster pointers, cache cluster usage stat. for fast evaluation
// FillSeedClusterStatCache(track0); // RS: Use this slow method only if sharing stat. is needed and used
//
//GetCachedSeedClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track0->GetClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE);
track0->GetClusterStatistic(0,row0-5, found, foundable);
if (foundable>5) dens00 = Float_t(found)/Float_t(foundable);
//
//GetCachedSeedClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track0->GetClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE);
track0->GetClusterStatistic(row0+5,155, found, foundable);
if (foundable>5) dens01 = Float_t(found)/Float_t(foundable);
//
//
//RS Seed don't keep their cluster pointers, cache cluster usage stat. for fast evaluation
// FillSeedClusterStatCache(track1); // RS: Use this slow method only if sharing stat. is needed and used
//
//GetCachedSeedClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track1->GetClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE);
track1->GetClusterStatistic(0,row0-5, found, foundable);
if (foundable>10) dens10 = Float_t(found)/Float_t(foundable);
//
//GetCachedSeedClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track1->GetClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE);
track1->GetClusterStatistic(row0+5,155, found, foundable);
if (foundable>10) dens11 = Float_t(found)/Float_t(foundable);
//
if (dens00<dens10 && dens01<dens11) continue;
if (dens00>dens10 && dens01>dens11) continue;
if (TMath::Max(dens00,dens10)<0.1) continue;
if (TMath::Max(dens01,dens11)<0.3) continue;
//
if (TMath::Min(dens00,dens10)>0.6) continue;
if (TMath::Min(dens01,dens11)>0.6) continue;
//
AliTPCseed * ktrack0, *ktrack1;
if (dens00>dens10){
ktrack0 = track0;
ktrack1 = track1;
}
else{
ktrack0 = track1;
ktrack1 = track0;
}
if (TMath::Abs(ktrack0->GetC())>5) continue; // cut on the curvature for mother particle
AliExternalTrackParam paramm(*ktrack0);
AliExternalTrackParam paramd(*ktrack1);
if (row0>60&&ktrack1->GetReference().GetX()>90.)new (¶md) AliExternalTrackParam(ktrack1->GetReference());
//
//
kink->SetMother(paramm);
kink->SetDaughter(paramd);
kink->Update();
Float_t x[3] = { static_cast<Float_t>(kink->GetPosition()[0]),static_cast<Float_t>(kink->GetPosition()[1]),static_cast<Float_t>(kink->GetPosition()[2])};
Int_t index[4];
fkParam->Transform0to1(x,index);
fkParam->Transform1to2(x,index);
row0 = GetRowNumber(x[0]);
if (kink->GetR()<100) continue;
if (kink->GetR()>240) continue;
if (kink->GetPosition()[2]/kink->GetR()>AliTPCReconstructor::GetCtgRange()) continue; //out of fiducial volume
if (kink->GetDistance()>cdist3) continue;
Float_t dird = kink->GetDaughterP()[0]*kink->GetPosition()[0]+kink->GetDaughterP()[1]*kink->GetPosition()[1]; // rough direction estimate
if (dird<0) continue;
Float_t dirm = kink->GetMotherP()[0]*kink->GetPosition()[0]+kink->GetMotherP()[1]*kink->GetPosition()[1]; // rough direction estimate
if (dirm<0) continue;
Float_t mpt = TMath::Sqrt(kink->GetMotherP()[0]*kink->GetMotherP()[0]+kink->GetMotherP()[1]*kink->GetMotherP()[1]);
if (mpt<0.2) continue;
if (mpt<1){
//for high momenta momentum not defined well in first iteration
Double_t qt = TMath::Sin(kink->GetAngle(2))*ktrack1->GetP();
if (qt>0.35) continue;
}
kink->SetLabel(CookLabel(ktrack0,0.4,0,row0),0);
kink->SetLabel(CookLabel(ktrack1,0.4,row0,kMaxRow),1);
if (dens00>dens10){
kink->SetTPCDensity(dens00,0,0);
kink->SetTPCDensity(dens01,0,1);
kink->SetTPCDensity(dens10,1,0);
kink->SetTPCDensity(dens11,1,1);
kink->SetIndex(i,0);
kink->SetIndex(j,1);
}
else{
kink->SetTPCDensity(dens10,0,0);
kink->SetTPCDensity(dens11,0,1);
kink->SetTPCDensity(dens00,1,0);
kink->SetTPCDensity(dens01,1,1);
kink->SetIndex(j,0);
kink->SetIndex(i,1);
}
if (mpt<1||kink->GetAngle(2)>0.1){
// angle and densities not defined yet
if (kink->GetTPCDensityFactor()<0.8) continue;
if ((2-kink->GetTPCDensityFactor())*kink->GetDistance() >0.25) continue;
if (kink->GetAngle(2)*ktrack0->GetP()<0.003) continue; //too small angle
if (kink->GetAngle(2)>0.2&&kink->GetTPCDensityFactor()<1.15) continue;
if (kink->GetAngle(2)>0.2&&kink->GetTPCDensity(0,1)>0.05) continue;
Float_t criticalangle = track0->GetSigmaSnp2()+track0->GetSigmaTgl2();
criticalangle+= track1->GetSigmaSnp2()+track1->GetSigmaTgl2();
criticalangle= 3*TMath::Sqrt(criticalangle);
if (criticalangle>0.02) criticalangle=0.02;
if (kink->GetAngle(2)<criticalangle) continue;
}
//
Int_t drow = Int_t(2.+0.5/(0.05+kink->GetAngle(2))); // overlap region defined
Float_t shapesum =0;
Float_t sum = 0;
for ( Int_t row = row0-drow; row<row0+drow;row++){
if (row<0) continue;
if (row>155) continue;
//RS if (ktrack0->GetClusterPointer(row)) {
if (ktrack0->GetClusterIndex2(row)>=0) {
const AliTPCTrackerPoints::Point *point = ktrack0->GetTrackPoint(row);
shapesum+=point->GetSigmaY()+point->GetSigmaZ();
sum++;
}
//RS if (ktrack1->GetClusterPointer(row)){
if (ktrack1->GetClusterIndex2(row)>=0) {
const AliTPCTrackerPoints::Point *point =ktrack1->GetTrackPoint(row);
shapesum+=point->GetSigmaY()+point->GetSigmaZ();
sum++;
}
}
if (sum<4){
kink->SetShapeFactor(-1.);
}
else{
kink->SetShapeFactor(shapesum/sum);
}
// esd->AddKink(kink);
//
// kink->SetMother(paramm);
//kink->SetDaughter(paramd);
Double_t chi2P2 = paramm.GetParameter()[2]-paramd.GetParameter()[2];
chi2P2*=chi2P2;
chi2P2/=paramm.GetCovariance()[5]+paramd.GetCovariance()[5];
Double_t chi2P3 = paramm.GetParameter()[3]-paramd.GetParameter()[3];
chi2P3*=chi2P3;
chi2P3/=paramm.GetCovariance()[9]+paramd.GetCovariance()[9];
//
if ((AliTPCReconstructor::StreamLevel()&kStreamFindKinks)>0) { // flag: stream track infroamtion in the FindKinks method
(*fDebugStreamer)<<"kinkLpt"<<
"chi2P2="<<chi2P2<<
"chi2P3="<<chi2P3<<
"p0.="<<¶mm<<
"p1.="<<¶md<<
"k.="<<kink<<
"\n";
}
if ( chi2P2+chi2P3<AliTPCReconstructor::GetRecoParam()->GetKinkAngleCutChi2(0)){
continue;
}
//
kinks.AddLast(kink);
kink = new AliKink;
ncandidates++;
}
}
//
// sort the kinks according quality - and refit them towards vertex
//
Int_t nkinks = kinks.GetEntriesFast();
Float_t quality[nkinks];
Int_t indexes[nkinks];
AliTPCseed *mothers[nkinks];
AliTPCseed *daughters[nkinks];
memset(mothers,0,nkinks*sizeof(AliTPCseed*));
memset(daughters,0,nkinks*sizeof(AliTPCseed*));
//
//
for (Int_t i=0;i<nkinks;i++){
quality[i] =100000;
AliKink *kinkl = (AliKink*)kinks.At(i);
//
// refit kinks towards vertex
//
Int_t index0 = kinkl->GetIndex(0);
Int_t index1 = kinkl->GetIndex(1);
AliTPCseed * ktrack0 = (AliTPCseed*)array->At(index0);
AliTPCseed * ktrack1 = (AliTPCseed*)array->At(index1);
//
Int_t sumn=ktrack0->GetNumberOfClusters()+ktrack1->GetNumberOfClusters();
//
// Refit Kink under if too small angle
//
if (kinkl->GetAngle(2)<0.05){
//
// RS: if possible, remove kink before reseeding
if (kinkl->GetDistance()>0.5 || kinkl->GetR()<110 || kinkl->GetR()>240) {
delete kinks.RemoveAt(i);
continue;
}
//
kinkl->SetTPCRow0(GetRowNumber(kinkl->GetR()));
Int_t row0 = kinkl->GetTPCRow0();
Int_t drow = Int_t(2.+0.5/(0.05+kinkl->GetAngle(2)));
//
Int_t last = row0-drow;
if (last<40) last=40;
if (last<ktrack0->GetFirstPoint()+25) last = ktrack0->GetFirstPoint()+25;
AliTPCseed* seed0 = ReSeed(ktrack0,last,kFALSE);
//
Int_t first = row0+drow;
if (first>130) first=130;
if (first>ktrack1->GetLastPoint()-25) first = TMath::Max(ktrack1->GetLastPoint()-25,30);
AliTPCseed* seed1 = ReSeed(ktrack1,first,kTRUE);
//
if (seed0 && seed1) {
kinkl->SetStatus(1,8);
if (RefitKink(*seed0,*seed1,*kinkl)) kinkl->SetStatus(1,9);
row0 = GetRowNumber(kinkl->GetR());
sumn = seed0->GetNumberOfClusters()+seed1->GetNumberOfClusters();
mothers[i] = seed0;
daughters[i] = seed1;
}
else {
delete kinks.RemoveAt(i);
if (seed0) MarkSeedFree( seed0 );
if (seed1) MarkSeedFree( seed1 );
continue;
}
}
//
if (kinkl) quality[i] = 160*((0.1+kinkl->GetDistance())*(2.-kinkl->GetTPCDensityFactor()))/(sumn+40.); //the longest -clossest will win
}
TMath::Sort(nkinks,quality,indexes,kFALSE);
//
//remove double find kinks
//
for (Int_t ikink0=1;ikink0<nkinks;ikink0++){
AliKink * kink0 = (AliKink*) kinks.At(indexes[ikink0]);
if (!kink0) continue;
//
for (Int_t ikink1=0;ikink1<ikink0;ikink1++){
kink0 = (AliKink*) kinks.At(indexes[ikink0]);
if (!kink0) continue;
AliKink * kink1 = (AliKink*) kinks.At(indexes[ikink1]);
if (!kink1) continue;
// if not close kink continue
if (TMath::Abs(kink1->GetPosition()[2]-kink0->GetPosition()[2])>10) continue;
if (TMath::Abs(kink1->GetPosition()[1]-kink0->GetPosition()[1])>10) continue;
if (TMath::Abs(kink1->GetPosition()[0]-kink0->GetPosition()[0])>10) continue;
//
AliTPCseed &mother0 = mothers[indexes[ikink0]] ? *mothers[indexes[ikink0]] : *((AliTPCseed*)array->At(kink0->GetIndex(0)));
AliTPCseed &daughter0 = daughters[indexes[ikink0]] ? *daughters[indexes[ikink0]] : *((AliTPCseed*)array->At(kink0->GetIndex(1)));
AliTPCseed &mother1 = mothers[indexes[ikink1]] ? *mothers[indexes[ikink1]] : *((AliTPCseed*)array->At(kink1->GetIndex(0)));
AliTPCseed &daughter1 = daughters[indexes[ikink1]] ? *daughters[indexes[ikink1]] : *((AliTPCseed*)array->At(kink1->GetIndex(1)));
Int_t row0 = (kink0->GetTPCRow0()+kink1->GetTPCRow0())/2;
//
Int_t same = 0;
Int_t both = 0;
Int_t samem = 0;
Int_t bothm = 0;
Int_t samed = 0;
Int_t bothd = 0;
//
for (Int_t i=0;i<row0;i++){
if (mother0.GetClusterIndex(i)>0 && mother1.GetClusterIndex(i)>0){
both++;
bothm++;
if (mother0.GetClusterIndex(i)==mother1.GetClusterIndex(i)){
same++;
samem++;
}
}
}
for (Int_t i=row0;i<158;i++){
//if (daughter0.GetClusterIndex(i)>0 && daughter0.GetClusterIndex(i)>0){ // RS: Bug?
if (daughter0.GetClusterIndex(i)>0 && daughter1.GetClusterIndex(i)>0){
both++;
bothd++;
if (mother0.GetClusterIndex(i)==mother1.GetClusterIndex(i)){
same++;
samed++;
}
}
}
Float_t ratio = Float_t(same+1)/Float_t(both+1);
Float_t ratiom = Float_t(samem+1)/Float_t(bothm+1);
Float_t ratiod = Float_t(samed+1)/Float_t(bothd+1);
if (ratio>0.3 && ratiom>0.5 &&ratiod>0.5) {
Int_t sum0 = mother0.GetNumberOfClusters()+daughter0.GetNumberOfClusters();
Int_t sum1 = mother1.GetNumberOfClusters()+daughter1.GetNumberOfClusters();
if (sum1>sum0){
shared[kink0->GetIndex(0)]= kTRUE;
shared[kink0->GetIndex(1)]= kTRUE;
delete kinks.RemoveAt(indexes[ikink0]);
break;
}
else{
shared[kink1->GetIndex(0)]= kTRUE;
shared[kink1->GetIndex(1)]= kTRUE;
delete kinks.RemoveAt(indexes[ikink1]);
}
}
}
}
for (Int_t i=0;i<nkinks;i++){
AliKink * kinkl = (AliKink*) kinks.At(indexes[i]);
if (!kinkl) continue;
kinkl->SetTPCRow0(GetRowNumber(kinkl->GetR()));
Int_t index0 = kinkl->GetIndex(0);
Int_t index1 = kinkl->GetIndex(1);
if (circular[index0]||(circular[index1]&&kinkl->GetDistance()>0.2)) continue;
kinkl->SetMultiple(usage[index0],0);
kinkl->SetMultiple(usage[index1],1);
if (kinkl->GetMultiple()[0]+kinkl->GetMultiple()[1]>2) continue;
if (kinkl->GetMultiple()[0]+kinkl->GetMultiple()[1]>0 && quality[indexes[i]]>0.2) continue;
if (kinkl->GetMultiple()[0]+kinkl->GetMultiple()[1]>0 && kinkl->GetDistance()>0.2) continue;
if (circular[index0]||(circular[index1]&&kinkl->GetDistance()>0.1)) continue;
AliTPCseed * ktrack0 = (AliTPCseed*)array->At(index0);
AliTPCseed * ktrack1 = (AliTPCseed*)array->At(index1);
if (!ktrack0 || !ktrack1) continue;
Int_t index = esd->AddKink(kinkl);
//
//
if ( ktrack0->GetKinkIndex(0)==0 && ktrack1->GetKinkIndex(0)==0) { //best kink
if ( (mothers[indexes[i]]) && daughters[indexes[i]] &&
mothers[indexes[i]]->GetNumberOfClusters()>20 && // where they reseeded?
daughters[indexes[i]]->GetNumberOfClusters()>20 &&
(mothers[indexes[i]]->GetNumberOfClusters()+daughters[indexes[i]]->GetNumberOfClusters())>100){
*ktrack0 = *mothers[indexes[i]];
*ktrack1 = *daughters[indexes[i]];
}
}
//
ktrack0->SetKinkIndex(usage[index0],-(index+1));
ktrack1->SetKinkIndex(usage[index1], (index+1));
usage[index0]++;
usage[index1]++;
}
//
// Remove tracks corresponding to shared kink's
//
for (Int_t i=0;i<nentries;i++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (!track0) continue;
if (track0->GetKinkIndex(0)!=0) continue;
if (shared[i]) MarkSeedFree( array->RemoveAt(i) );
}
//
//
RemoveUsed2(array,0.5,0.4,30);
UnsignClusters();
for (Int_t i=0;i<nentries;i++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (!track0) continue;
track0->CookdEdx(0.02,0.6);
track0->CookPID();
}
//
// RS use stack allocation instead of the heap
AliTPCseed mother,daughter;
AliKink kinkl;
//
for (Int_t i=0;i<nentries;i++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (!track0) continue;
if (track0->Pt()<1.4) continue;
//remove double high momenta tracks - overlapped with kink candidates
Int_t ishared=0;
Int_t all =0;
for (Int_t icl=track0->GetFirstPoint();icl<track0->GetLastPoint(); icl++){
Int_t tpcindex = track0->GetClusterIndex2(icl);
if (tpcindex<0) continue;
AliTPCclusterMI *cl = GetClusterMI(tpcindex);
all++;
if (cl->IsUsed(10)) ishared++;
}
if (Float_t(ishared+1)/Float_t(all+1)>0.5) {
MarkSeedFree( array->RemoveAt(i) );
continue;
}
//
if (track0->GetKinkIndex(0)!=0) continue;
if (track0->GetNumberOfClusters()<80) continue;
// AliTPCseed *pmother = new AliTPCseed(); // RS use stack allocation
// AliTPCseed *pdaughter = new AliTPCseed();
// AliKink *pkink = new AliKink;
//
if (CheckKinkPoint(track0,mother,daughter, kinkl)){
if (mother.GetNumberOfClusters()<30||daughter.GetNumberOfClusters()<20) {
// delete pmother; // RS used stack allocation
// delete pdaughter;
// delete pkink;
continue; //too short tracks
}
if (mother.Pt()<1.4) {
// delete pmother; // RS used stack allocation
// delete pdaughter;
// delete pkink;
continue;
}
Int_t row0= kinkl.GetTPCRow0();
if (kinkl.GetDistance()>0.5 || kinkl.GetR()<110. || kinkl.GetR()>240.) {
// delete pmother; // RS used stack allocation
// delete pdaughter;
// delete pkink;
continue;
}
//
Int_t index = esd->AddKink(&kinkl);
mother.SetKinkIndex(0,-(index+1));
daughter.SetKinkIndex(0,index+1);
if (mother.GetNumberOfClusters()>50) {
MarkSeedFree( array->RemoveAt(i) );
AliTPCseed* mtc = new( NextFreeSeed() ) AliTPCseed(mother);
mtc->SetPoolID(fLastSeedID);
array->AddAt(mtc,i);
}
else{
AliTPCseed* mtc = new( NextFreeSeed() ) AliTPCseed(mother);
mtc->SetPoolID(fLastSeedID);
array->AddLast(mtc);
}
AliTPCseed* dtc = new( NextFreeSeed() ) AliTPCseed(daughter);
dtc->SetPoolID(fLastSeedID);
array->AddLast(dtc);
for (Int_t icl=0;icl<row0;icl++) {
Int_t tpcindex= mother.GetClusterIndex2(icl);
if (tpcindex<0) continue;
AliTPCclusterMI *cl = GetClusterMI(tpcindex);
if (cl) cl->Use(20);
}
//
for (Int_t icl=row0;icl<158;icl++) {
Int_t tpcindex= mother.GetClusterIndex2(icl);
if (tpcindex<0) continue;
AliTPCclusterMI *cl = GetClusterMI(tpcindex);
if (cl) cl->Use(20);
}
//
}
//delete pmother; // RS used stack allocation
//delete pdaughter;
//delete pkink;
}
for (int i=nkinks;i--;) {
if (mothers[i]) MarkSeedFree( mothers[i] );
if (daughters[i]) MarkSeedFree( daughters[i] );
}
// delete [] daughters;
// delete [] mothers;
//
// RS: most of heap array are converted to stack arrays
// delete [] dca;
// delete []circular;
// delete []shared;
// delete []quality;
// delete []indexes;
//
delete kink;
// delete[]fim;
// delete[] zm;
// delete[] z0;
// delete [] usage;
// delete[] alpha;
// delete[] nclusters;
// delete[] sign;
// delete[] helixes;
if (fHelixPool) fHelixPool->Clear();
kinks.Delete();
//delete kinks;
AliInfo(Form("Ncandidates=\t%d\t%d\t%d\t%d\n",esd->GetNumberOfKinks(),ncandidates,ntracks,nall));
timer.Print();
}
Int_t AliTPCtracker::RefitKink(AliTPCseed &mother, AliTPCseed &daughter, const AliESDkink &knk)
{
//
// refit kink towards to the vertex
//
//
AliKink &kink=(AliKink &)knk;
Int_t row0 = GetRowNumber(kink.GetR());
FollowProlongation(mother,0);
mother.Reset(kFALSE);
//
FollowProlongation(daughter,row0);
daughter.Reset(kFALSE);
FollowBackProlongation(daughter,158);
daughter.Reset(kFALSE);
Int_t first = TMath::Max(row0-20,30);
Int_t last = TMath::Min(row0+20,140);
//
const Int_t kNdiv =5;
AliTPCseed param0[kNdiv]; // parameters along the track
AliTPCseed param1[kNdiv]; // parameters along the track
AliKink kinks[kNdiv]; // corresponding kink parameters
//
Int_t rows[kNdiv];
for (Int_t irow=0; irow<kNdiv;irow++){
rows[irow] = first +((last-first)*irow)/(kNdiv-1);
}
// store parameters along the track
//
for (Int_t irow=0;irow<kNdiv;irow++){
FollowBackProlongation(mother, rows[irow]);
FollowProlongation(daughter,rows[kNdiv-1-irow]);
param0[irow] = mother;
param1[kNdiv-1-irow] = daughter;
}
//
// define kinks
for (Int_t irow=0; irow<kNdiv-1;irow++){
if (param0[irow].GetNumberOfClusters()<kNdiv||param1[irow].GetNumberOfClusters()<kNdiv) continue;
kinks[irow].SetMother(param0[irow]);
kinks[irow].SetDaughter(param1[irow]);
kinks[irow].Update();
}
//
// choose kink with best "quality"
Int_t index =-1;
Double_t mindist = 10000;
for (Int_t irow=0;irow<kNdiv;irow++){
if (param0[irow].GetNumberOfClusters()<20||param1[irow].GetNumberOfClusters()<20) continue;
if (TMath::Abs(kinks[irow].GetR())>240.) continue;
if (TMath::Abs(kinks[irow].GetR())<100.) continue;
//
Float_t normdist = TMath::Abs(param0[irow].GetX()-kinks[irow].GetR())*(0.1+kink.GetDistance());
normdist/= (param0[irow].GetNumberOfClusters()+param1[irow].GetNumberOfClusters()+40.);
if (normdist < mindist){
mindist = normdist;
index = irow;
}
}
//
if (index==-1) return 0;
//
//
param0[index].Reset(kTRUE);
FollowProlongation(param0[index],0);
//
mother = param0[index];
daughter = param1[index]; // daughter in vertex
//
kink.SetMother(mother);
kink.SetDaughter(daughter);
kink.Update();
kink.SetTPCRow0(GetRowNumber(kink.GetR()));
kink.SetTPCncls(param0[index].GetNumberOfClusters(),0);
kink.SetTPCncls(param1[index].GetNumberOfClusters(),1);
kink.SetLabel(CookLabel(&mother,0.4, 0,kink.GetTPCRow0()),0);
kink.SetLabel(CookLabel(&daughter,0.4, kink.GetTPCRow0(),kMaxRow),1);
mother.SetLabel(kink.GetLabel(0));
daughter.SetLabel(kink.GetLabel(1));
return 1;
}
void AliTPCtracker::UpdateKinkQualityM(AliTPCseed * seed){
//
// update Kink quality information for mother after back propagation
//
if (seed->GetKinkIndex(0)>=0) return;
for (Int_t ikink=0;ikink<3;ikink++){
Int_t index = seed->GetKinkIndex(ikink);
if (index>=0) break;
index = TMath::Abs(index)-1;
AliESDkink * kink = fEvent->GetKink(index);
kink->SetTPCDensity(-1,0,0);
kink->SetTPCDensity(1,0,1);
//
Int_t row0 = kink->GetTPCRow0() - 2 - Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row0<15) row0=15;
//
Int_t row1 = kink->GetTPCRow0() + 2 + Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row1>145) row1=145;
//
Int_t found,foundable;//,shared;
//GetSeedClusterStatistic(seed,0,row0, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
//RS seed->GetClusterStatistic(0,row0, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(0,row0, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),0,0);
//
//GetSeedClusterStatistic(seed,row1,155, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
//RS seed->GetClusterStatistic(row1,155, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(row1,155, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),0,1);
}
}
void AliTPCtracker::UpdateKinkQualityD(AliTPCseed * seed){
//
// update Kink quality information for daughter after refit
//
if (seed->GetKinkIndex(0)<=0) return;
for (Int_t ikink=0;ikink<3;ikink++){
Int_t index = seed->GetKinkIndex(ikink);
if (index<=0) break;
index = TMath::Abs(index)-1;
AliESDkink * kink = fEvent->GetKink(index);
kink->SetTPCDensity(-1,1,0);
kink->SetTPCDensity(-1,1,1);
//
Int_t row0 = kink->GetTPCRow0() -2 - Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row0<15) row0=15;
//
Int_t row1 = kink->GetTPCRow0() +2 + Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row1>145) row1=145;
//
Int_t found,foundable;//,shared;
//GetSeedClusterStatistic(0,row0, found, foundable,shared,kFALS); //RS: seeds don't keep their clusters
//seed->GetClusterStatistic(0,row0, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(0,row0, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),1,0);
//
//GetSeedClusterStatistic(row1,155, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
// seed->GetClusterStatistic(row1,155, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(row1,155, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),1,1);
}
}
Int_t AliTPCtracker::CheckKinkPoint(AliTPCseed*seed,AliTPCseed &mother, AliTPCseed &daughter, const AliESDkink &knk)
{
//
// check kink point for given track
// if return value=0 kink point not found
// otherwise seed0 correspond to mother particle
// seed1 correspond to daughter particle
// kink parameter of kink point
AliKink &kink=(AliKink &)knk;
Int_t middlerow = (seed->GetFirstPoint()+seed->GetLastPoint())/2;
Int_t first = seed->GetFirstPoint();
Int_t last = seed->GetLastPoint();
if (last-first<20) return 0; // shortest length - 2*30 = 60 pad-rows
AliTPCseed *seed1 = ReSeed(seed,middlerow+20, kTRUE); //middle of chamber
if (!seed1) return 0;
FollowProlongation(*seed1,seed->GetLastPoint()-20);
seed1->Reset(kTRUE);
FollowProlongation(*seed1,158);
seed1->Reset(kTRUE);
last = seed1->GetLastPoint();
//
AliTPCseed *seed0 = new( NextFreeSeed() ) AliTPCseed(*seed);
seed0->SetPoolID(fLastSeedID);
seed0->Reset(kFALSE);
seed0->Reset();
//
AliTPCseed param0[20]; // parameters along the track
AliTPCseed param1[20]; // parameters along the track
AliKink kinks[20]; // corresponding kink parameters
Int_t rows[20];
for (Int_t irow=0; irow<20;irow++){
rows[irow] = first +((last-first)*irow)/19;
}
// store parameters along the track
//
for (Int_t irow=0;irow<20;irow++){
FollowBackProlongation(*seed0, rows[irow]);
FollowProlongation(*seed1,rows[19-irow]);
param0[irow] = *seed0;
param1[19-irow] = *seed1;
}
//
// define kinks
for (Int_t irow=0; irow<19;irow++){
kinks[irow].SetMother(param0[irow]);
kinks[irow].SetDaughter(param1[irow]);
kinks[irow].Update();
}
//
// choose kink with biggest change of angle
Int_t index =-1;
Double_t maxchange= 0;
for (Int_t irow=1;irow<19;irow++){
if (TMath::Abs(kinks[irow].GetR())>240.) continue;
if (TMath::Abs(kinks[irow].GetR())<110.) continue;
Float_t quality = TMath::Abs(kinks[irow].GetAngle(2))/(3.+TMath::Abs(kinks[irow].GetR()-param0[irow].GetX()));
if ( quality > maxchange){
maxchange = quality;
index = irow;
//
}
}
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
if (index<0) return 0;
//
Int_t row0 = GetRowNumber(kinks[index].GetR()); //row 0 estimate
seed0 = new( NextFreeSeed() ) AliTPCseed(param0[index]);
seed0->SetPoolID(fLastSeedID);
seed1 = new( NextFreeSeed() ) AliTPCseed(param1[index]);
seed1->SetPoolID(fLastSeedID);
seed0->Reset(kFALSE);
seed1->Reset(kFALSE);
seed0->ResetCovariance(10.);
seed1->ResetCovariance(10.);
FollowProlongation(*seed0,0);
FollowBackProlongation(*seed1,158);
mother = *seed0; // backup mother at position 0
seed0->Reset(kFALSE);
seed1->Reset(kFALSE);
seed0->ResetCovariance(10.);
seed1->ResetCovariance(10.);
//
first = TMath::Max(row0-20,0);
last = TMath::Min(row0+20,158);
//
for (Int_t irow=0; irow<20;irow++){
rows[irow] = first +((last-first)*irow)/19;
}
// store parameters along the track
//
for (Int_t irow=0;irow<20;irow++){
FollowBackProlongation(*seed0, rows[irow]);
FollowProlongation(*seed1,rows[19-irow]);
param0[irow] = *seed0;
param1[19-irow] = *seed1;
}
//
// define kinks
for (Int_t irow=0; irow<19;irow++){
kinks[irow].SetMother(param0[irow]);
kinks[irow].SetDaughter(param1[irow]);
// param0[irow].Dump();
//param1[irow].Dump();
kinks[irow].Update();
}
//
// choose kink with biggest change of angle
index =-1;
maxchange= 0;
for (Int_t irow=0;irow<20;irow++){
if (TMath::Abs(kinks[irow].GetR())>250.) continue;
if (TMath::Abs(kinks[irow].GetR())<90.) continue;
Float_t quality = TMath::Abs(kinks[irow].GetAngle(2))/(3.+TMath::Abs(kinks[irow].GetR()-param0[irow].GetX()));
if ( quality > maxchange){
maxchange = quality;
index = irow;
//
}
}
//
//
if (index==-1 || param0[index].GetNumberOfClusters()+param1[index].GetNumberOfClusters()<100){
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
return 0;
}
// Float_t anglesigma = TMath::Sqrt(param0[index].fC22+param0[index].fC33+param1[index].fC22+param1[index].fC33);
kink.SetMother(param0[index]);
kink.SetDaughter(param1[index]);
kink.Update();
Double_t chi2P2 = param0[index].GetParameter()[2]-param1[index].GetParameter()[2];
chi2P2*=chi2P2;
chi2P2/=param0[index].GetCovariance()[5]+param1[index].GetCovariance()[5];
Double_t chi2P3 = param0[index].GetParameter()[3]-param1[index].GetParameter()[3];
chi2P3*=chi2P3;
chi2P3/=param0[index].GetCovariance()[9]+param1[index].GetCovariance()[9];
//
if (AliTPCReconstructor::StreamLevel()&kStreamFindKinks) { // flag: stream track infroamtion in the FindKinks method
(*fDebugStreamer)<<"kinkHpt"<<
"chi2P2="<<chi2P2<<
"chi2P3="<<chi2P3<<
"p0.="<<¶m0[index]<<
"p1.="<<¶m1[index]<<
"k.="<<&kink<<
"\n";
}
if ( chi2P2+chi2P3<AliTPCReconstructor::GetRecoParam()->GetKinkAngleCutChi2(0)){
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
return 0;
}
row0 = GetRowNumber(kink.GetR());
kink.SetTPCRow0(row0);
kink.SetLabel(CookLabel(seed0,0.5,0,row0),0);
kink.SetLabel(CookLabel(seed1,0.5,row0,158),1);
kink.SetIndex(-10,0);
kink.SetIndex(int(param0[index].GetNumberOfClusters()+param1[index].GetNumberOfClusters()),1);
kink.SetTPCncls(param0[index].GetNumberOfClusters(),0);
kink.SetTPCncls(param1[index].GetNumberOfClusters(),1);
//
//
// new (&mother) AliTPCseed(param0[index]);
daughter = param1[index];
daughter.SetLabel(kink.GetLabel(1));
param0[index].Reset(kTRUE);
FollowProlongation(param0[index],0);
mother = param0[index];
mother.SetLabel(kink.GetLabel(0));
if ( chi2P2+chi2P3<AliTPCReconstructor::GetRecoParam()->GetKinkAngleCutChi2(1)){
mother=*seed;
}
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
//
return 1;
}
AliTPCseed* AliTPCtracker::ReSeed(AliTPCseed *t)
{
//
// reseed - refit - track
//
Int_t first = 0;
// Int_t last = fSectors->GetNRows()-1;
//
if (fSectors == fOuterSec){
first = TMath::Max(first, t->GetFirstPoint()-fInnerSec->GetNRows());
//last =
}
else
first = t->GetFirstPoint();
//
AliTPCseed * seed = MakeSeed(t,0.1,0.5,0.9);
FollowBackProlongation(*t,fSectors->GetNRows()-1);
t->Reset(kFALSE);
FollowProlongation(*t,first);
return seed;
}
//_____________________________________________________________________________
Int_t AliTPCtracker::ReadSeeds(const TFile *inp) {
//-----------------------------------------------------------------
// This function reades track seeds.
//-----------------------------------------------------------------
TDirectory *savedir=gDirectory;
TFile *in=(TFile*)inp;
if (!in->IsOpen()) {
cerr<<"AliTPCtracker::ReadSeeds(): input file is not open !\n";
return 1;
}
in->cd();
TTree *seedTree=(TTree*)in->Get("Seeds");
if (!seedTree) {
cerr<<"AliTPCtracker::ReadSeeds(): ";
cerr<<"can't get a tree with track seeds !\n";
return 2;
}
AliTPCtrack *seed=new AliTPCtrack;
seedTree->SetBranchAddress("tracks",&seed);
if (fSeeds==0) fSeeds=new TObjArray(15000);
Int_t n=(Int_t)seedTree->GetEntries();
for (Int_t i=0; i<n; i++) {
seedTree->GetEvent(i);
AliTPCseed* sdc = new( NextFreeSeed() ) AliTPCseed(*seed/*,seed->GetAlpha()*/);
sdc->SetPoolID(fLastSeedID);
fSeeds->AddLast(sdc);
}
delete seed; // RS: this seed is not from the pool, delete it !!!
delete seedTree;
savedir->cd();
return 0;
}
Int_t AliTPCtracker::Clusters2TracksHLT (AliESDEvent *const esd, const AliESDEvent *hltEvent)
{
//
// clusters to tracks
if (fSeeds) DeleteSeeds();
else ResetSeedsPool();
fEvent = esd;
fEventHLT = hltEvent;
fAccountDistortions = AliTPCReconstructor::GetRecoParam()->GetAccountDistortions();
if (AliTPCReconstructor::GetRecoParam()->GetUseOulierClusterFilter()) FilterOutlierClusters();
AliTPCTransform *transform = AliTPCcalibDB::Instance()->GetTransform() ;
transform->SetCurrentRecoParam((AliTPCRecoParam*)AliTPCReconstructor::GetRecoParam());
transform->SetCurrentTimeStamp( esd->GetTimeStamp());
transform->SetCurrentRun(esd->GetRunNumber());
//
if (AliTPCReconstructor::GetExtendedRoads()){
fClExtraRoadY = AliTPCReconstructor::GetExtendedRoads()[0];
fClExtraRoadZ = AliTPCReconstructor::GetExtendedRoads()[1];
AliInfoF("Additional errors for roads: Y:%f Z:%f",fClExtraRoadY,fClExtraRoadZ);
}
const Double_t *errCluster = (AliTPCReconstructor::GetSystematicErrorCluster()) ?
AliTPCReconstructor::GetSystematicErrorCluster() :
AliTPCReconstructor::GetRecoParam()->GetSystematicErrorCluster();
//
fExtraClErrY2 = errCluster[0]*errCluster[0];
fExtraClErrZ2 = errCluster[1]*errCluster[1];
fExtraClErrYZ2 = fExtraClErrY2 + fExtraClErrZ2;
AliInfoF("Additional errors for clusters: Y:%f Z:%f",errCluster[0],errCluster[1]);
//
if (AliTPCReconstructor::GetPrimaryDCACut()) {
fPrimaryDCAYCut = AliTPCReconstructor::GetPrimaryDCACut()[0];
fPrimaryDCAZCut = AliTPCReconstructor::GetPrimaryDCACut()[1];
fDisableSecondaries = kTRUE;
AliInfoF("Only primaries will be tracked with DCAY=%f and DCAZ=%f cuts",fPrimaryDCAYCut,fPrimaryDCAZCut);
}
//
Clusters2Tracks();
fEventHLT = 0;
if (!fSeeds) return 1;
FillESD(fSeeds);
if ((AliTPCReconstructor::StreamLevel()&kStreamClDump)>0) DumpClusters(0,fSeeds);
return 0;
//
}
Int_t AliTPCtracker::Clusters2Tracks(AliESDEvent *const esd)
{
//
// clusters to tracks
return Clusters2TracksHLT( esd, 0);
}
//_____________________________________________________________________________
Int_t AliTPCtracker::Clusters2Tracks() {
//-----------------------------------------------------------------
// This is a track finder.
//-----------------------------------------------------------------
TDirectory *savedir=gDirectory;
TStopwatch timer;
fIteration = 0;
fSeeds = Tracking();
if (fDebug>0){
Info("Clusters2Tracks","Time for tracking: \t");timer.Print();timer.Start();
}
//activate again some tracks
for (Int_t i=0; i<fSeeds->GetEntriesFast(); i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<20) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
CookLabel(pt,0.1);
if (pt->GetRemoval()==10) {
if (pt->GetDensityFirst(20)>0.8 || pt->GetDensityFirst(30)>0.8 || pt->GetDensityFirst(40)>0.7)
pt->Desactivate(10); // make track again active // MvL: should be 0 ?
else{
pt->Desactivate(20);
MarkSeedFree( fSeeds->RemoveAt(i) );
}
}
}
//
RemoveUsed2(fSeeds,0.85,0.85,0);
if (AliTPCReconstructor::GetRecoParam()->GetDoKinks()) FindKinks(fSeeds,fEvent);
//FindCurling(fSeeds, fEvent,0);
if (AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC) FindMultiMC(fSeeds, fEvent,-1); // find multi found tracks
RemoveUsed2(fSeeds,0.5,0.4,20);
FindSplitted(fSeeds, fEvent,0); // find multi found tracks
if (AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC) FindMultiMC(fSeeds, fEvent,0); // find multi found tracks
// //
// // refit short tracks
// //
Int_t nseed=fSeeds->GetEntriesFast();
//
Int_t found = 0;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<15) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
CookLabel(pt,0.1); //For comparison only
//if ((pt->IsActive() || (pt->fRemoval==10) )&& nc>50 &&pt->GetNumberOfClusters()>0.4*pt->fNFoundable){
if ((pt->IsActive() || (pt->GetRemoval()==10) )){
found++;
if (fDebug>0) cerr<<found<<'\r';
pt->SetLab2(i);
}
else
MarkSeedFree( fSeeds->RemoveAt(i) );
}
//RemoveOverlap(fSeeds,0.99,7,kTRUE);
SignShared(fSeeds);
//RemoveUsed(fSeeds,0.9,0.9,6);
//
nseed=fSeeds->GetEntriesFast();
found = 0;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<15) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
t.SetUniqueID(i);
t.CookdEdx(0.02,0.6);
// CheckKinkPoint(&t,0.05);
//if ((pt->IsActive() || (pt->fRemoval==10) )&& nc>50 &&pt->GetNumberOfClusters()>0.4*pt->fNFoundable){
if ((pt->IsActive() || (pt->GetRemoval()==10) )){
found++;
if (fDebug>0){
cerr<<found<<'\r';
}
pt->SetLab2(i);
}
else
MarkSeedFree( fSeeds->RemoveAt(i) );
//AliTPCseed * seed1 = ReSeed(pt,0.05,0.5,1);
//if (seed1){
// FollowProlongation(*seed1,0);
// Int_t n = seed1->GetNumberOfClusters();
// printf("fP4\t%f\t%f\n",seed1->GetC(),pt->GetC());
// printf("fN\t%d\t%d\n", seed1->GetNumberOfClusters(),pt->GetNumberOfClusters());
//
//}
//AliTPCseed * seed2 = ReSeed(pt,0.95,0.5,0.05);
}
SortTracks(fSeeds, 1);
/*
fIteration = 1;
PrepareForBackProlongation(fSeeds,5.);
PropagateBack(fSeeds);
printf("Time for back propagation: \t");timer.Print();timer.Start();
fIteration = 2;
PrepareForProlongation(fSeeds,5.);
PropagateForard2(fSeeds);
printf("Time for FORWARD propagation: \t");timer.Print();timer.Start();
// RemoveUsed(fSeeds,0.7,0.7,6);
//RemoveOverlap(fSeeds,0.9,7,kTRUE);
nseed=fSeeds->GetEntriesFast();
found = 0;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<15) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
t.CookdEdx(0.02,0.6);
// CookLabel(pt,0.1); //For comparison only
//if ((pt->IsActive() || (pt->fRemoval==10) )&& nc>50 &&pt->GetNumberOfClusters()>0.4*pt->fNFoundable){
if ((pt->IsActive() || (pt->fRemoval==10) )){
cerr<<found++<<'\r';
}
else
MarkSeedFree( fSeeds->RemoveAt(i) );
pt->fLab2 = i;
}
*/
// fNTracks = found;
if (fDebug>0){
Info("Clusters2Tracks","Time for overlap removal, track writing and dedx cooking: \t"); timer.Print();timer.Start();
}
//
// cerr<<"Number of found tracks : "<<"\t"<<found<<endl;
Info("Clusters2Tracks","Number of found tracks %d",found);
savedir->cd();
// UnloadClusters();
//
return 0;
}
void AliTPCtracker::Tracking(TObjArray * arr)
{
//
// tracking of the seeds
//
fSectors = fOuterSec;
ParallelTracking(arr,150,63);
fSectors = fOuterSec;
ParallelTracking(arr,63,0);
}
TObjArray * AliTPCtracker::Tracking(Int_t seedtype, Int_t i1, Int_t i2, Float_t cuts[4], Float_t dy, Int_t dsec)
{
//
//
//tracking routine
static TObjArray arrTracks;
TObjArray * arr = &arrTracks;
//
fSectors = fOuterSec;
TStopwatch timer;
timer.Start();
for (Int_t sec=0;sec<fkNOS;sec++){
if (fAccountDistortions) {
if (seedtype==3) MakeSeeds3Dist(arr,sec,i1,i2,cuts,dy, dsec);
if (seedtype==4) MakeSeeds5Dist(arr,sec,i1,i2,cuts,dy);
if (seedtype==2) MakeSeeds2Dist(arr,sec,i1,i2,cuts,dy); //RS
}
else {
if (seedtype==3) MakeSeeds3(arr,sec,i1,i2,cuts,dy, dsec);
if (seedtype==4) MakeSeeds5(arr,sec,i1,i2,cuts,dy);
if (seedtype==2) MakeSeeds2(arr,sec,i1,i2,cuts,dy); //RS
}
//
}
if (fDebug>0){
Info("Tracking","\nSeeding - %d\t%d\t%d\t%d\n",seedtype,i1,i2,arr->GetEntriesFast());
timer.Print();
timer.Start();
}
Tracking(arr);
if (fDebug>0){
timer.Print();
}
return arr;
}
TObjArray * AliTPCtracker::Tracking()
{
// tracking
//
if (AliTPCReconstructor::GetRecoParam()->GetSpecialSeeding()) return TrackingSpecial();
TStopwatch timer;
timer.Start();
Int_t nup=fOuterSec->GetNRows()+fInnerSec->GetNRows();
TObjArray * seeds = fSeeds;
if (!seeds) seeds = new TObjArray;
else seeds->Clear();
TObjArray * arr=0;
Int_t fLastSeedRowSec=AliTPCReconstructor::GetRecoParam()->GetLastSeedRowSec();
Int_t gapPrim = AliTPCReconstructor::GetRecoParam()->GetSeedGapPrim();
Int_t gapSec = AliTPCReconstructor::GetRecoParam()->GetSeedGapSec();
Int_t gap =20;
Float_t cuts[4];
cuts[0] = 0.002;
cuts[1] = 1.5;
cuts[2] = 3.;
cuts[3] = 3.;
Float_t fnumber = 3.0;
Float_t fdensity = 3.0;
// make HLT seeds
if (AliTPCReconstructor::GetRecoParam()->GetUseHLTPreSeeding()) {
arr = MakeSeedsHLT( fEventHLT );
if( arr ){
SumTracks(seeds,arr);
delete arr;
arr=0;
//cout<<"HLT tracks left after sorting: "<<seeds->GetEntriesFast()<<endl;
//SignClusters(seeds,fnumber,fdensity);
}
}
//
//find primaries
cuts[0]=0.0066;
for (Int_t delta = 0; delta<18; delta+=gapPrim){
//
cuts[0]=0.0070;
cuts[1] = 1.5;
arr = Tracking(3,nup-1-delta,nup-1-delta-gap,cuts,-1,1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
for (Int_t i=2;i<6;i+=2){
// seed high pt tracks
cuts[0]=0.0022;
cuts[1]=0.3;
arr = Tracking(3,nup-i-delta,nup-i-delta-gap,cuts,-1,0);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
}
fnumber = 4;
fdensity = 4.;
// RemoveUsed(seeds,0.9,0.9,1);
// UnsignClusters();
// SignClusters(seeds,fnumber,fdensity);
//find primaries
cuts[0]=0.0077;
for (Int_t delta = 20; delta<120; delta+=gapPrim){
//
// seed high pt tracks
cuts[0]=0.0060;
cuts[1]=0.3;
cuts[2]=6.;
arr = Tracking(3,nup-delta,nup-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
cuts[0]=0.003;
cuts[1]=0.3;
cuts[2]=6.;
arr = Tracking(3,nup-delta-5,nup-delta-5-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
cuts[0] = 0.01;
cuts[1] = 2.0;
cuts[2] = 3.;
cuts[3] = 2.0;
fnumber = 2.;
fdensity = 2.;
if (fDebug>0){
Info("Tracking()","\n\nPrimary seeding\t%d\n\n",seeds->GetEntriesFast());
timer.Print();
timer.Start();
}
// RemoveUsed(seeds,0.75,0.75,1);
//UnsignClusters();
//SignClusters(seeds,fnumber,fdensity);
if (fDisableSecondaries) return seeds;
// find secondaries
cuts[0] = 0.3;
cuts[1] = 1.5;
cuts[2] = 3.;
cuts[3] = 1.5;
arr = Tracking(4,nup-1,nup-1-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-2,nup-2-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-3,nup-3-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-5,nup-5-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-7,nup-7-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
//
arr = Tracking(4,nup-9,nup-9-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
for (Int_t delta = 9; delta<30; delta+=gapSec){
//
cuts[0] = 0.3;
cuts[1] = 1.5;
cuts[2] = 3.;
cuts[3] = 1.5;
arr = Tracking(4,nup-1-delta,nup-1-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-3-delta,nup-5-delta-gap,cuts,4);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
}
fnumber = 1;
fdensity = 1;
//
// change cuts
fnumber = 2.;
fdensity = 2.;
cuts[0]=0.0080;
// find secondaries
for (Int_t delta = 30; delta<fLastSeedRowSec; delta+=gapSec){
//
cuts[0] = 0.3;
cuts[1] = 3.5;
cuts[2] = 3.;
cuts[3] = 3.5;
arr = Tracking(4,nup-1-delta,nup-1-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-5-delta,nup-5-delta-gap,cuts,5 );
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
if (fDebug>0){
Info("Tracking()","\n\nSecondary seeding\t%d\n\n",seeds->GetEntriesFast());
timer.Print();
timer.Start();
}
return seeds;
//
}
TObjArray * AliTPCtracker::TrackingSpecial()
{
//
// seeding adjusted for laser and cosmic tests - short tracks with big inclination angle
// no primary vertex seeding tried
//
TStopwatch timer;
timer.Start();
Int_t nup=fOuterSec->GetNRows()+fInnerSec->GetNRows();
TObjArray * seeds = fSeeds;
if (!seeds) seeds = new TObjArray;
else seeds->Clear();
TObjArray * arr=0;
Int_t gap = 15;
Float_t cuts[4];
Float_t fnumber = 3.0;
Float_t fdensity = 3.0;
// find secondaries
cuts[0] = AliTPCReconstructor::GetRecoParam()->GetMaxC(); // max curvature
cuts[1] = 3.5; // max tan(phi) angle for seeding
cuts[2] = 3.; // not used (cut on z primary vertex)
cuts[3] = 3.5; // max tan(theta) angle for seeding
for (Int_t delta = 0; nup-delta-gap-1>0; delta+=3){
//
arr = Tracking(4,nup-1-delta,nup-1-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
if (fDebug>0){
Info("Tracking()","\n\nSecondary seeding\t%d\n\n",seeds->GetEntriesFast());
timer.Print();
timer.Start();
}
return seeds;
//
}
void AliTPCtracker::SumTracks(TObjArray *arr1,TObjArray *&arr2)
{
//
//sum tracks to common container
//remove suspicious tracks
// RS: Attention: supplied tracks come in the static array, don't delete them
Int_t nseed = arr2->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt=(AliTPCseed*)arr2->UncheckedAt(i);
if (pt){
//
// remove tracks with too big curvature
//
if (TMath::Abs(pt->GetC())>AliTPCReconstructor::GetRecoParam()->GetMaxC()){
MarkSeedFree( arr2->RemoveAt(i) );
continue;
}
// REMOVE VERY SHORT TRACKS
if (pt->GetNumberOfClusters()<20){
MarkSeedFree( arr2->RemoveAt(i) );
continue;
}// patch 28 fev06
// NORMAL ACTIVE TRACK
if (pt->IsActive()){
arr1->AddLast(arr2->RemoveAt(i));
continue;
}
//remove not usable tracks
if (pt->GetRemoval()!=10){
MarkSeedFree( arr2->RemoveAt(i) );
continue;
}
// ENABLE ONLY ENOUGH GOOD STOPPED TRACKS
if (pt->GetDensityFirst(20)>0.8 || pt->GetDensityFirst(30)>0.8 || pt->GetDensityFirst(40)>0.7)
arr1->AddLast(arr2->RemoveAt(i));
else{
MarkSeedFree( arr2->RemoveAt(i) );
}
}
}
// delete arr2; arr2 = 0; // RS: this is static array, don't delete it
}
void AliTPCtracker::ParallelTracking(TObjArray *const arr, Int_t rfirst, Int_t rlast)
{
//
// try to track in parralel
Int_t nseed=arr->GetEntriesFast();
//prepare seeds for tracking
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i), &t=*pt;
if (!pt) continue;
if (!t.IsActive()) continue;
// follow prolongation to the first layer
if ( (fSectors ==fInnerSec) || (t.GetFirstPoint()-fkParam->GetNRowLow()>rfirst+1) )
FollowProlongation(t, rfirst+1);
}
//
for (Int_t nr=rfirst; nr>=rlast; nr--){
if (nr<fInnerSec->GetNRows())
fSectors = fInnerSec;
else
fSectors = fOuterSec;
// make indexes with the cluster tracks for given
// find nearest cluster
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i), &t=*pt;
if (!pt) continue;
if (nr==80) pt->UpdateReference();
if (!pt->IsActive()) continue;
// if ( (fSectors ==fOuterSec) && (pt->fFirstPoint-fkParam->GetNRowLow())<nr) continue;
if (pt->GetRelativeSector()>17) {
continue;
}
UpdateClusters(t,nr);
}
// prolonagate to the nearest cluster - if founded
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
if (!pt->IsActive()) continue;
// if ((fSectors ==fOuterSec) && (pt->fFirstPoint-fkParam->GetNRowLow())<nr) continue;
if (pt->GetRelativeSector()>17) {
continue;
}
FollowToNextCluster(*pt,nr);
}
}
}
void AliTPCtracker::PrepareForBackProlongation(const TObjArray *const arr,Float_t fac) const
{
//
//
// if we use TPC track itself we have to "update" covariance
//
Int_t nseed= arr->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt) {
pt->Modify(fac);
//
//rotate to current local system at first accepted point
Int_t index = pt->GetClusterIndex2(pt->GetFirstPoint());
Int_t sec = (index&0xff000000)>>24;
sec = sec%18;
Float_t angle1 = fInnerSec->GetAlpha()*sec+fInnerSec->GetAlphaShift();
if (angle1>TMath::Pi())
angle1-=2.*TMath::Pi();
Float_t angle2 = pt->GetAlpha();
if (TMath::Abs(angle1-angle2)>0.001){
if (!pt->Rotate(angle1-angle2)) return;
//angle2 = pt->GetAlpha();
//pt->fRelativeSector = pt->GetAlpha()/fInnerSec->GetAlpha();
//if (pt->GetAlpha()<0)
// pt->fRelativeSector+=18;
//sec = pt->fRelativeSector;
}
}
}
}
void AliTPCtracker::PrepareForProlongation(TObjArray *const arr, Float_t fac) const
{
//
//
// if we use TPC track itself we have to "update" covariance
//
Int_t nseed= arr->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt) {
pt->Modify(fac);
pt->SetFirstPoint(pt->GetLastPoint());
}
}
}
Int_t AliTPCtracker::PropagateBack(const TObjArray *const arr)
{
//
// make back propagation
//
Int_t nseed= arr->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt&& pt->GetKinkIndex(0)<=0) {
//AliTPCseed *pt2 = new AliTPCseed(*pt);
fSectors = fInnerSec;
//FollowBackProlongation(*pt,fInnerSec->GetNRows()-1);
//fSectors = fOuterSec;
FollowBackProlongation(*pt,fInnerSec->GetNRows()+fOuterSec->GetNRows()-1,1);
//if (pt->GetNumberOfClusters()<(pt->fEsd->GetTPCclusters(0)) ){
// Error("PropagateBack","Not prolonged track %d",pt->GetLabel());
// FollowBackProlongation(*pt2,fInnerSec->GetNRows()+fOuterSec->GetNRows()-1);
//}
}
if (pt&& pt->GetKinkIndex(0)>0) {
AliESDkink * kink = fEvent->GetKink(pt->GetKinkIndex(0)-1);
pt->SetFirstPoint(kink->GetTPCRow0());
fSectors = fInnerSec;
FollowBackProlongation(*pt,fInnerSec->GetNRows()+fOuterSec->GetNRows()-1,1);
}
CookLabel(pt,0.3);
}
return 0;
}
Int_t AliTPCtracker::PropagateForward2(const TObjArray *const arr)
{
//
// make forward propagation
//
Int_t nseed= arr->GetEntriesFast();
//
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt) {
FollowProlongation(*pt,0,1,1);
CookLabel(pt,0.3);
}
}
return 0;
}
Int_t AliTPCtracker::PropagateForward()
{
//
// propagate track forward
//UnsignClusters();
Int_t nseed = fSeeds->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)fSeeds->UncheckedAt(i);
if (pt){
AliTPCseed &t = *pt;
Double_t alpha=t.GetAlpha() - fSectors->GetAlphaShift();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
t.SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
}
}
fSectors = fOuterSec;
ParallelTracking(fSeeds,fOuterSec->GetNRows()+fInnerSec->GetNRows()-1,fInnerSec->GetNRows());
fSectors = fInnerSec;
ParallelTracking(fSeeds,fInnerSec->GetNRows()-1,0);
return 1;
}
Int_t AliTPCtracker::PropagateBack(AliTPCseed *const pt, Int_t row0, Int_t row1)
{
//
// make back propagation, in between row0 and row1
//
if (pt) {
fSectors = fInnerSec;
Int_t r1;
//
if (row1<fSectors->GetNRows())
r1 = row1;
else
r1 = fSectors->GetNRows()-1;
if (row0<fSectors->GetNRows()&& r1>0 )
FollowBackProlongation(*pt,r1);
if (row1<=fSectors->GetNRows())
return 0;
//
r1 = row1 - fSectors->GetNRows();
if (r1<=0) return 0;
if (r1>=fOuterSec->GetNRows()) return 0;
fSectors = fOuterSec;
return FollowBackProlongation(*pt,r1);
}
return 0;
}
void AliTPCtracker::GetShape(AliTPCseed * seed, Int_t row)
{
// gets cluster shape
//
AliTPCClusterParam * clparam = AliTPCcalibDB::Instance()->GetClusterParam();
Float_t zdrift = TMath::Abs((fkParam->GetZLength(0)-TMath::Abs(seed->GetZ())));
Int_t type = (seed->GetSector() < fkParam->GetNSector()/2) ? 0: (row>126) ? 1:2;
Double_t angulary = seed->GetSnp();
if (TMath::Abs(angulary)>AliTPCReconstructor::GetMaxSnpTracker()) {
angulary = TMath::Sign(AliTPCReconstructor::GetMaxSnpTracker(),angulary);
}
angulary = angulary*angulary/((1.-angulary)*(1.+angulary));
Double_t angularz = seed->GetTgl()*seed->GetTgl()*(1.+angulary);
Double_t sigmay = clparam->GetRMS0(0,type,zdrift,TMath::Sqrt(TMath::Abs(angulary)));
Double_t sigmaz = clparam->GetRMS0(1,type,zdrift,TMath::Sqrt(TMath::Abs(angularz)));
seed->SetCurrentSigmaY2(sigmay*sigmay);
seed->SetCurrentSigmaZ2(sigmaz*sigmaz);
// Float_t sd2 = TMath::Abs((fkParam->GetZLength(0)-TMath::Abs(seed->GetZ())))*fkParam->GetDiffL()*fkParam->GetDiffL();
// // Float_t padlength = fkParam->GetPadPitchLength(seed->fSector);
// Float_t padlength = GetPadPitchLength(row);
// //
// Float_t sresy = (seed->GetSector() < fkParam->GetNSector()/2) ? 0.2 :0.3;
// seed->SetCurrentSigmaY2(sd2+padlength*padlength*angulary/12.+sresy*sresy);
// //
// Float_t sresz = fkParam->GetZSigma();
// seed->SetCurrentSigmaZ2(sd2+padlength*padlength*angularz*angularz*(1+angulary)/12.+sresz*sresz);
/*
Float_t wy = GetSigmaY(seed);
Float_t wz = GetSigmaZ(seed);
wy*=wy;
wz*=wz;
if (TMath::Abs(wy/seed->fCurrentSigmaY2-1)>0.0001 || TMath::Abs(wz/seed->fCurrentSigmaZ2-1)>0.0001 ){
printf("problem\n");
}
*/
}
//__________________________________________________________________________
void AliTPCtracker::CookLabel(AliKalmanTrack *tk, Float_t wrong) const {
//--------------------------------------------------------------------
//This function "cooks" a track label. If label<0, this track is fake.
//--------------------------------------------------------------------
// AliTPCseed * t = dynamic_cast<AliTPCseed*>(tk);
// if(!t){
// printf("%s:%d wrong type \n",(char*)__FILE__,__LINE__);
// return;
// }
AliTPCseed * t = (AliTPCseed*)tk; // RS avoid slow dynamic cast
Int_t noc=t->GetNumberOfClusters();
if (noc<10){
//printf("\nnot founded prolongation\n\n\n");
//t->Dump();
return ;
}
Int_t lb[kMaxRow];
Int_t mx[kMaxRow];
AliTPCclusterMI *clusters[kMaxRow];
//
for (Int_t i=0;i<kMaxRow;i++) {
clusters[i]=0;
lb[i]=mx[i]=0;
}
Int_t i;
Int_t current=0;
for (i=0; i<kMaxRow && current<noc; i++) {
Int_t index=t->GetClusterIndex2(i);
if (index<=0) continue;
if (index&0x8000) continue;
//
clusters[current++]=GetClusterMI(index);
// if (t->GetClusterPointer(i)){
// clusters[current]=t->GetClusterPointer(i);
// current++;
// }
}
noc = current;
Int_t lab=123456789;
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
lab=TMath::Abs(c->GetLabel(0));
Int_t j;
for (j=0; j<noc; j++) if (lb[j]==lab || mx[j]==0) break;
lb[j]=lab;
(mx[j])++;
}
Int_t max=0;
for (i=0; i<noc; i++) if (mx[i]>max) {max=mx[i]; lab=lb[i];}
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (TMath::Abs(c->GetLabel(1)) == lab ||
TMath::Abs(c->GetLabel(2)) == lab ) max++;
}
if (noc<=0) { lab=-1; return;}
if ((1.- Float_t(max)/(noc)) > wrong) lab=-lab;
else {
Int_t tail=Int_t(0.10*noc);
max=0;
Int_t ind=0;
for (i=1; i<kMaxRow&&ind<tail; i++) {
// AliTPCclusterMI *c=clusters[noc-i];
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (lab == TMath::Abs(c->GetLabel(0)) ||
lab == TMath::Abs(c->GetLabel(1)) ||
lab == TMath::Abs(c->GetLabel(2))) max++;
ind++;
}
if (max < Int_t(0.5*tail)) lab=-lab;
}
t->SetLabel(lab);
// delete[] lb;
//delete[] mx;
//delete[] clusters;
}
//__________________________________________________________________________
Int_t AliTPCtracker::CookLabel(AliTPCseed *const t, Float_t wrong,Int_t first, Int_t last) const {
//--------------------------------------------------------------------
//This function "cooks" a track label. If label<0, this track is fake.
//--------------------------------------------------------------------
Int_t noc=t->GetNumberOfClusters();
if (noc<10){
//printf("\nnot founded prolongation\n\n\n");
//t->Dump();
return -1;
}
Int_t lb[kMaxRow];
Int_t mx[kMaxRow];
AliTPCclusterMI *clusters[kMaxRow];
//
for (Int_t i=0;i<kMaxRow;i++) {
clusters[i]=0;
lb[i]=mx[i]=0;
}
Int_t i;
Int_t current=0;
for (i=0; i<kMaxRow && current<noc; i++) {
if (i<first) continue;
if (i>last) continue;
Int_t index=t->GetClusterIndex2(i);
if (index<=0) continue;
if (index&0x8000) continue;
//
clusters[current++]=GetClusterMI(index);
// if (t->GetClusterPointer(i)){
// clusters[current]=t->GetClusterPointer(i);
// current++;
// }
}
noc = current;
//if (noc<5) return -1;
Int_t lab=123456789;
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
lab=TMath::Abs(c->GetLabel(0));
Int_t j;
for (j=0; j<noc; j++) if (lb[j]==lab || mx[j]==0) break;
lb[j]=lab;
(mx[j])++;
}
Int_t max=0;
for (i=0; i<noc; i++) if (mx[i]>max) {max=mx[i]; lab=lb[i];}
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (TMath::Abs(c->GetLabel(1)) == lab ||
TMath::Abs(c->GetLabel(2)) == lab ) max++;
}
if (noc<=0) { lab=-1; return -1;}
if ((1.- Float_t(max)/(noc)) > wrong) lab=-lab;
else {
Int_t tail=Int_t(0.10*noc);
max=0;
Int_t ind=0;
for (i=1; i<kMaxRow&&ind<tail; i++) {
// AliTPCclusterMI *c=clusters[noc-i];
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (lab == TMath::Abs(c->GetLabel(0)) ||
lab == TMath::Abs(c->GetLabel(1)) ||
lab == TMath::Abs(c->GetLabel(2))) max++;
ind++;
}
if (max < Int_t(0.5*tail)) lab=-lab;
}
// t->SetLabel(lab);
return lab;
// delete[] lb;
//delete[] mx;
//delete[] clusters;
}
Int_t AliTPCtracker::GetRowNumber(Double_t x[3]) const
{
//return pad row number for given x vector
Float_t phi = TMath::ATan2(x[1],x[0]);
if(phi<0) phi=2.*TMath::Pi()+phi;
// Get the local angle in the sector philoc
const Float_t kRaddeg = 180/3.14159265358979312;
Float_t phiangle = (Int_t (phi*kRaddeg/20.) + 0.5)*20./kRaddeg;
Double_t localx = x[0]*TMath::Cos(phiangle)-x[1]*TMath::Sin(phiangle);
return GetRowNumber(localx);
}
void AliTPCtracker::MakeESDBitmaps(AliTPCseed *t, AliESDtrack *esd)
{
//-----------------------------------------------------------------------
// Fill the cluster and sharing bitmaps of the track
//-----------------------------------------------------------------------
Int_t firstpoint = 0;
Int_t lastpoint = kMaxRow;
// AliTPCclusterMI *cluster;
Int_t nclsf = 0;
TBits clusterMap(kMaxRow);
TBits sharedMap(kMaxRow);
TBits fitMap(kMaxRow);
for (int iter=firstpoint; iter<lastpoint; iter++) {
// Change to cluster pointers to see if we have a cluster at given padrow
Int_t tpcindex= t->GetClusterIndex2(iter);
if (tpcindex>=0) {
clusterMap.SetBitNumber(iter, kTRUE);
if (t->IsShared(iter)) sharedMap.SetBitNumber(iter,kTRUE); // RS shared flag moved to seed
//
if ( (tpcindex&0x8000) == 0) {
fitMap.SetBitNumber(iter, kTRUE);
nclsf++;
}
}
// if (t->GetClusterIndex(iter) >= 0 && (t->GetClusterIndex(iter) & 0x8000) == 0) {
// fitMap.SetBitNumber(iter, kTRUE);
// nclsf++;
// }
}
esd->SetTPCClusterMap(clusterMap);
esd->SetTPCSharedMap(sharedMap);
esd->SetTPCFitMap(fitMap);
if (nclsf != t->GetNumberOfClusters())
AliDebug(3,Form("Inconsistency between ncls %d and indices %d (found %d)",t->GetNumberOfClusters(),nclsf,esd->GetTPCClusterMap().CountBits()));
}
Bool_t AliTPCtracker::IsFindable(AliTPCseed & track){
//
// return flag if there is findable cluster at given position
//
Float_t kDeltaZ=10;
Float_t z = track.GetZ();
if (TMath::Abs(z)<(AliTPCReconstructor::GetCtgRange()*track.GetX()+kDeltaZ) &&
TMath::Abs(z)<fkParam->GetZLength(0) &&
(TMath::Abs(track.GetSnp())<AliTPCReconstructor::GetMaxSnpTracker()))
return kTRUE;
return kFALSE;
}
void AliTPCtracker::AddCovariance(AliTPCseed * seed){
//
// Adding systematic error estimate to the covariance matrix
// !!!! the systematic error for element 4 is in 1/GeV
// 03.03.2012 MI changed in respect to the previous versions
// in case systemtic errors defiend statically no correlation added (needed for CPass0)
const Double_t *param = (AliTPCReconstructor::GetSystematicError()!=NULL) ? AliTPCReconstructor::GetSystematicError():AliTPCReconstructor::GetRecoParam()->GetSystematicError();
//
// use only the diagonal part if not specified otherwise
if (!AliTPCReconstructor::GetRecoParam()->GetUseSystematicCorrelation() || AliTPCReconstructor::GetSystematicError()) return AddCovarianceAdd(seed);
//
Double_t *covarS= (Double_t*)seed->GetCovariance();
Double_t factor[5]={1,1,1,1,1};
factor[0]= TMath::Sqrt(TMath::Abs((covarS[0] + param[0]*param[0])/covarS[0]));
factor[1]= TMath::Sqrt(TMath::Abs((covarS[2] + param[1]*param[1])/covarS[2]));
factor[2]= TMath::Sqrt(TMath::Abs((covarS[5] + param[2]*param[2])/covarS[5]));
factor[3]= TMath::Sqrt(TMath::Abs((covarS[9] + param[3]*param[3])/covarS[9]));
factor[4]= TMath::Sqrt(TMath::Abs((covarS[14] +param[4]*param[4])/covarS[14]));
//
factor[0]=factor[2];
factor[4]=factor[2];
// 0
// 1 2
// 3 4 5
// 6 7 8 9
// 10 11 12 13 14
for (Int_t i=0; i<5; i++){
for (Int_t j=i; j<5; j++){
Int_t index=seed->GetIndex(i,j);
covarS[index]*=factor[i]*factor[j];
}
}
}
void AliTPCtracker::AddCovarianceAdd(AliTPCseed * seed){
//
// Adding systematic error - as additive factor without correlation
//
// !!!! the systematic error for element 4 is in 1/GeV
// 03.03.2012 MI changed in respect to the previous versions
const Double_t *param = (AliTPCReconstructor::GetSystematicError()!=NULL) ? AliTPCReconstructor::GetSystematicError():AliTPCReconstructor::GetRecoParam()->GetSystematicError();
Double_t *covarIn= (Double_t*)seed->GetCovariance();
Double_t covar[15];
for (Int_t i=0;i<15;i++) covar[i]=0;
// 0
// 1 2
// 3 4 5
// 6 7 8 9
// 10 11 12 13 14
covar[0] = param[0]*param[0];
covar[2] = param[1]*param[1];
covar[5] = param[2]*param[2];
covar[9] = param[3]*param[3];
covar[14]= param[4]*param[4];
//
covar[1]=TMath::Sqrt((covar[0]*covar[2]))*covarIn[1]/TMath::Sqrt((covarIn[0]*covarIn[2]));
//
covar[3]=TMath::Sqrt((covar[0]*covar[5]))*covarIn[3]/TMath::Sqrt((covarIn[0]*covarIn[5]));
covar[4]=TMath::Sqrt((covar[2]*covar[5]))*covarIn[4]/TMath::Sqrt((covarIn[2]*covarIn[5]));
//
covar[6]=TMath::Sqrt((covar[0]*covar[9]))*covarIn[6]/TMath::Sqrt((covarIn[0]*covarIn[9]));
covar[7]=TMath::Sqrt((covar[2]*covar[9]))*covarIn[7]/TMath::Sqrt((covarIn[2]*covarIn[9]));
covar[8]=TMath::Sqrt((covar[5]*covar[9]))*covarIn[8]/TMath::Sqrt((covarIn[5]*covarIn[9]));
//
covar[10]=TMath::Sqrt((covar[0]*covar[14]))*covarIn[10]/TMath::Sqrt((covarIn[0]*covarIn[14]));
covar[11]=TMath::Sqrt((covar[2]*covar[14]))*covarIn[11]/TMath::Sqrt((covarIn[2]*covarIn[14]));
covar[12]=TMath::Sqrt((covar[5]*covar[14]))*covarIn[12]/TMath::Sqrt((covarIn[5]*covarIn[14]));
covar[13]=TMath::Sqrt((covar[9]*covar[14]))*covarIn[13]/TMath::Sqrt((covarIn[9]*covarIn[14]));
//
seed->AddCovariance(covar);
}
//_____________________________________________________________________________
Bool_t AliTPCtracker::IsTPCHVDipEvent(AliESDEvent const *esdEvent)
{
//
// check events affected by TPC HV dip
//
if(!esdEvent) return kFALSE;
// Init TPC OCDB
AliTPCcalibDB *db=AliTPCcalibDB::Instance();
if(!db) return kFALSE;
db->SetRun(esdEvent->GetRunNumber());
// maximum allowed voltage before an event is identified as a dip event
// and scanning period
const Double_t kTPCHVdip = db->GetParameters()->GetMaxDipVoltage();
const Double_t dipEventScanPeriod = db->GetParameters()->GetVoltageDipScanPeriod();
const Double_t tevSec = esdEvent->GetTimeStamp();
for(Int_t sector=0; sector<72; sector++)
{
// don't use excluded chambers, since the state is not defined at all
if (!db->GetChamberHVStatus(sector)) continue;
// get hv sensor of the chamber
AliDCSSensor *sensor = db->GetChamberHVSensor(sector);
if (!sensor) continue;
TGraph *grSensor=sensor->GetGraph();
if (!grSensor) continue;
if (grSensor->GetN()<1) continue;
// get median
const Double_t median = db->GetChamberHighVoltageMedian(sector);
if(median < 1.) continue;
for (Int_t ipoint=0; ipoint<grSensor->GetN()-1; ++ipoint){
Double_t nextTime=grSensor->GetX()[ipoint+1]*3600+sensor->GetStartTime();
if (tevSec-dipEventScanPeriod>nextTime) continue;
const Float_t deltaV=TMath::Abs(grSensor->GetY()[ipoint]-median);
if (deltaV>kTPCHVdip) {
AliDebug(3,Form("HV dip detected in ROC '%02d' with dV '%.2f' at time stamp '%.0f'",sector,deltaV,tevSec));
return kTRUE;
}
if (nextTime>tevSec+dipEventScanPeriod) break;
}
}
return kFALSE;
}
//________________________________________
void AliTPCtracker::MarkSeedFree(TObject *sd)
{
// account that this seed is "deleted"
// AliTPCseed* seed = dynamic_cast<AliTPCseed*>(sd);
// if (!seed) {
// AliError(Form("Freeing of non-AliTPCseed %p from the pool is requested",sd));
// return;
// }
AliTPCseed* seed = (AliTPCseed*)sd;
int id = seed->GetPoolID();
if (id<0) {
AliError(Form("Freeing of seed %p NOT from the pool is requested",sd));
return;
}
// AliInfo(Form("%d %p",id, seed));
fSeedsPool->RemoveAt(id);
if (fFreeSeedsID.GetSize()<=fNFreeSeeds) fFreeSeedsID.Set( 2*fNFreeSeeds + 100 );
fFreeSeedsID.GetArray()[fNFreeSeeds++] = id;
}
//________________________________________
TObject *&AliTPCtracker::NextFreeSeed()
{
// return next free slot where the seed can be created
fLastSeedID = fNFreeSeeds ? fFreeSeedsID.GetArray()[--fNFreeSeeds] : fSeedsPool->GetEntriesFast();
// AliInfo(Form("%d",fLastSeedID));
return (*fSeedsPool)[ fLastSeedID ];
//
}
//________________________________________
void AliTPCtracker::ResetSeedsPool()
{
// mark all seeds in the pool as unused
AliInfo(Form("CurrentSize: %d, BookedUpTo: %d, free: %d",fSeedsPool->GetSize(),fSeedsPool->GetEntriesFast(),fNFreeSeeds));
fNFreeSeeds = 0;
fSeedsPool->Clear(); // RS: nominally the seeds may allocate memory...
}
Int_t AliTPCtracker::PropagateToRowHLT(AliTPCseed *pt, int nrow)
{
AliTPCseed &t=*pt;
Double_t x= GetXrow(nrow);
Double_t ymax= GetMaxY(nrow);
Int_t rotate = 0;
Int_t nRotations=0;
int ret = 1;
do{
rotate = 0;
if (!t.PropagateTo(x) ){
//cout<<"can't propagate to row "<<nrow<<", x="<<t.GetX()<<" -> "<<x<<endl;
//t.Print();
ret = 0;
break;
}
t.SetRow(nrow);
Double_t y = t.GetY();
if( y > ymax ) {
if( rotate!=-1 ) rotate=1;
} else if (y <-ymax) {
if( rotate!=1 ) rotate = -1;
}
if( rotate==0 ) break;
//cout<<"rotate at row "<<nrow<<": "<<rotate<<endl;
if (!t.Rotate( rotate==1 ?fSectors->GetAlpha() :-fSectors->GetAlpha())) {
//cout<<"can't rotate "<<endl;
ret=0;
break;
}
nRotations+= rotate;
}while(rotate!=0);
if( nRotations!=0 ){
int newSec= t.GetRelativeSector()+nRotations;
if( newSec>=fN ) newSec-=fN;
else if( newSec<0 ) newSec +=fN;
//cout<<"rotate at row "<<nrow<<": "<<nRotations<<" times "<<" sec "
//<< t.GetRelativeSector()<<" -> "<<newSec<<endl;
t.SetRelativeSector(newSec);
}
return ret;
}
void AliTPCtracker::TrackFollowingHLT(TObjArray *const arr )
{
//
// try to track in parralel
AliFatal("RS: This method is not yet aware of cluster pointers no present in the in-memory tracks");
Int_t nRows=fOuterSec->GetNRows()+fInnerSec->GetNRows();
fSectors=fInnerSec;
Int_t nseed=arr->GetEntriesFast();
//cout<<"Parallel tracking My.."<<endl;
double shapeY2[kMaxRow], shapeZ2[kMaxRow];
Int_t clusterIndex[kMaxRow];
for (Int_t iSeed=0; iSeed<nseed; iSeed++) {
//if( iSeed!=1 ) continue;
AliTPCseed *pt=(AliTPCseed*) (arr->UncheckedAt(iSeed));
if (!pt) continue;
AliTPCseed &t=*pt;
//cout <<"Pt "<<t.GetSigned1Pt()<<endl;
// t.Print();
for( int iter=0; iter<3; iter++ ){
t.Reset();
t.SetLastPoint(0); // first cluster in track position
t.SetFirstPoint(nRows-1);
t.ResetCovariance(.1);
t.SetNumberOfClusters(0);
for( int i=0; i<nRows; i++ ){
shapeY2[i]=1.;
shapeZ2[i]=1.;
clusterIndex[i]=-1;
t.SetClusterIndex2(i,-1);
t.SetClusterIndex(i,-1);
}
// pick up the clusters
Double_t roady = 20.;
Double_t roadz = 20.;
double roadr = 5;
AliTPCseed t0(t);
t0.Reset();
int nClusters = 0;
{
t0.SetRelativeSector(t.GetRelativeSector());
t0.SetLastPoint(0); // first cluster in track position
t0.SetFirstPoint(kMaxRow);
for (Int_t nr=0; nr<nRows; nr++){
if( nr<fInnerSec->GetNRows() ) fSectors=fInnerSec;
else fSectors=fOuterSec;
if( !PropagateToRowHLT(&t0, nr ) ){ break; }
if (TMath::Abs(t0.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()){
//cout<<"Snp is too big: "<<t0.GetSnp()<<endl;
continue;
}
if (!IsActive(t0.GetRelativeSector(),nr)) {
continue;
}
if( iter==0 ){
GetShape(&t0,nr);
shapeY2[nr]=t0.GetCurrentSigmaY2();
shapeZ2[nr]=t0.GetCurrentSigmaZ2();
}
AliTPCtrackerRow &krow=GetRow(t0.GetRelativeSector(),nr);
if( !krow ) continue;
t.SetClusterIndex2(nr,-3); // foundable
t.SetClusterIndex(nr,-3);
AliTPCclusterMI *cl=0;
UInt_t uindex = 0;
cl = krow.FindNearest2(t0.GetY(),t0.GetZ(),roady+fClExtraRoadY,roadz+fClExtraRoadZ,uindex);
if (!cl ) continue;
double dy = cl->GetY()-t0.GetY();
double dz = cl->GetZ()-t0.GetZ();
double dr = sqrt(dy*dy+dz*dz);
if( dr>roadr ){
//cout<<"row "<<nr<<", best cluster r= "<<dr<<" y,z = "<<dy<<" "<<dz<<endl;
continue;
}
//cout<<"row "<<nr<<", found cluster r= "<<dr<<" y,z = "<<dy<<" "<<dz<<endl;
t0.SetClusterPointer(nr, cl);
clusterIndex[nr] = krow.GetIndex(uindex);
if( t0.GetFirstPoint()>nr ) t0.SetFirstPoint(nr);
t0.SetLastPoint(nr);
nClusters++;
}
}
if( nClusters <3 ){
//cout<<"NOT ENOUGTH CLUSTERS: "<<nClusters<<endl;
break;
}
Int_t basePoints[3] = {t0.GetFirstPoint(),t0.GetFirstPoint(),t0.GetLastPoint()};
// find midpoint
{
Int_t midRow = (t0.GetLastPoint()-t0.GetFirstPoint())/2;
int dist=200;
for( int nr=t0.GetFirstPoint()+1; nr< t0.GetLastPoint(); nr++){
//if (t0.GetClusterIndex2(nr)<0) continue;
if( !t0.GetClusterPointer(nr) ) continue;
int d = TMath::Abs(nr-midRow);
if( d < dist ){
dist = d;
basePoints[1] = nr;
}
}
}
// first fit 3 base points
if( 1||iter<2 ){
//cout<<"Fit3: "<<endl;
for( int icl=0; icl<3; icl++){
int nr = basePoints[icl];
int lr=nr;
if( nr>=fInnerSec->GetNRows()){
lr = nr - fInnerSec->GetNRows();
fSectors=fOuterSec;
} else fSectors=fInnerSec;
AliTPCclusterMI *cl=t0.GetClusterPointer(nr);
if(!cl){
//cout<<"WRONG!!!!"<<endl;
continue;
}
int iSec = cl->GetDetector() %fkNIS;
int rotate = iSec - t.GetRelativeSector();
if( rotate!=0 ){
//cout<<"Rotate at row"<<nr<<" to "<<rotate<<" sectors"<<endl;
if (!t.Rotate( rotate*fSectors->GetAlpha()) ) {
//cout<<"can't rotate "<<endl;
break;
}
t.SetRelativeSector(iSec);
}
Double_t x= cl->GetX();
if (!t.PropagateTo(x)){
//cout<<"can't propagate to x="<<x<<endl;
break;
}
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()){
//cout<<"Snp is too big: "<<t.GetSnp()<<endl;
break;
}
//cout<<"fit3 : row "<<nr<<" ind = "<<clusterIndex[nr]<<endl;
t.SetCurrentClusterIndex1(clusterIndex[nr]);
t.SetCurrentCluster(cl);
t.SetRow(lr);
t.SetErrorY2(shapeY2[nr]);
t.SetErrorZ2(shapeZ2[nr]);
if( icl==0 ){
double cov[15];
for( int j=0; j<15; j++ ) cov[j]=0;
cov[0]=10;
cov[2]=10;
cov[5]=.5;
cov[9]=.5;
cov[14]=1.;
t.AliExternalTrackParam::AddCovariance(cov);
}
if( !UpdateTrack(&t,0) ){
//cout<<"Can not update"<<endl;
//t.Print();
t.SetClusterIndex2(nr,-1);
t.SetClusterIndex(nr,-1);
t.SetClusterPointer(nr,0);
break;
}
//t.SetClusterPointer(nr, cl);
}
//t.SetLastPoint(t0.GetLastPoint());
//t.SetFirstPoint(t0.GetFirstPoint());
//cout<<"Fit: "<<endl;
for (Int_t nr=t0.GetLastPoint(); nr>=t0.GetFirstPoint(); nr-- ){
int lr=nr;
if( nr>=fInnerSec->GetNRows()){
lr = nr - fInnerSec->GetNRows();
fSectors=fOuterSec;
} else fSectors=fInnerSec;
if(1|| iter<2 ){
if( nr == basePoints[0] ) continue;
if( nr == basePoints[1] ) continue;
if( nr == basePoints[2] ) continue;
}
AliTPCclusterMI *cl=t0.GetClusterPointer(nr);
if(!cl) continue;
int iSec = cl->GetDetector() %fkNIS;
int rotate = iSec - t.GetRelativeSector();
if( rotate!=0 ){
//cout<<"Rotate at row"<<nr<<" to "<<rotate<<" sectors"<<endl;
if (!t.Rotate( rotate*fSectors->GetAlpha()) ) {
//cout<<"can't rotate "<<endl;
break;
}
t.SetRelativeSector(iSec);
}
Double_t x= cl->GetX();
if (!t.PropagateTo(x)){
//cout<<"can't propagate to x="<<x<<endl;
break;
}
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()){
//cout<<"Snp is too big: "<<t.GetSnp()<<endl;
break;
}
//cout<<"fit: row "<<nr<<" ind = "<<clusterIndex[nr]<<endl;
t.SetCurrentClusterIndex1(clusterIndex[nr]);
t.SetCurrentCluster(cl);
t.SetRow(lr);
t.SetErrorY2(shapeY2[nr]);
t.SetErrorZ2(shapeZ2[nr]);
if( !UpdateTrack(&t,0) ){
//cout<<"Can not update"<<endl;
//t.Print();
t.SetClusterIndex2(nr,-1);
t.SetClusterIndex(nr,-1);
break;
}
//t.SetClusterPointer(nr, cl);
}
}
//cout<<"After iter "<<iter<<": N clusters="<<t.GetNumberOfClusters()<<" : "<<nClusters<<endl;
}
//cout<<"fitted track"<<iSeed<<endl;
//t.Print();
//cout<<"Statistics: "<<endl;
Int_t foundable,found,shared;
//t.GetClusterStatistic(0,nRows, found, foundable, shared, kTRUE);
t.GetClusterStatistic(0,nRows, found, foundable); //RS shared info is not used, use faster method
t.SetNFoundable(foundable);
//cout<<"found "<<found<<" foundable "<<foundable<<" shared "<<shared<<endl;
}
}
TObjArray * AliTPCtracker::MakeSeedsHLT(const AliESDEvent *hltEvent)
{
// tracking
//
AliFatal("RS: This method is not yet aware of cluster pointers no present in the in-memory tracks");
if( !hltEvent ) return 0;
Int_t nentr=hltEvent->GetNumberOfTracks();
AliInfo(Form("Using %d HLT tracks for seeding",nentr));
TObjArray * seeds = new TObjArray(nentr);
Int_t nup=fOuterSec->GetNRows()+fInnerSec->GetNRows();
Int_t index = 0;
Int_t nTr=hltEvent->GetNumberOfTracks();
for( int itr=0; itr<nTr; itr++ ){
//if( itr!=97 ) continue;
const AliExternalTrackParam *param = hltEvent->GetTrack(itr)->GetTPCInnerParam();
if( !param ) continue;
//if( TMath::Abs(esdTr->GetSigned1Pt())>1 ) continue;
//if( TMath::Abs(esdTr->GetTgl())>1. ) continue;
AliTPCtrack tr;
tr.Set(param->GetX(),param->GetAlpha(),param->GetParameter(),param->GetCovariance());
tr.SetNumberOfClusters(0);
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed(tr);
Double_t alpha=seed->GetAlpha();// - fSectors->GetAlphaShift();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
//
seed->SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
Double_t alphaSec = fSectors->GetAlpha() * seed->GetRelativeSector() + fSectors->GetAlphaShift();
if (alphaSec >= TMath::Pi()) alphaSec -= 2.*TMath::Pi();
if (alphaSec < -TMath::Pi()) alphaSec += 2.*TMath::Pi();
seed->Rotate(alphaSec - alpha);
seed->SetPoolID(fLastSeedID);
seed->SetIsSeeding(kTRUE);
seed->SetSeed1(nup-1);
seed->SetSeed2(nup-2);
seed->SetSeedType(0);
seed->SetFirstPoint(-1);
seed->SetLastPoint(-1);
seeds->AddLast(seed); // note, track is seed, don't free the seed
index++;
//if( index>3 ) break;
}
fSectors = fOuterSec;
TrackFollowingHLT(seeds );
nTr = seeds->GetEntriesFast();
for( int itr=0; itr<nTr; itr++ ){
AliTPCseed * seed = (AliTPCseed*) seeds->UncheckedAt(itr);
if( !seed ) continue;
//FollowBackProlongation(*seed,0);
// cout<<seed->GetNumberOfClusters()<<endl;
Int_t foundable,found;//,shared;
// seed->GetClusterStatistic(0,nup, found, foundable, shared, kTRUE); //RS shared info is not used, use faster method
seed->GetClusterStatistic(0,nup, found, foundable);
seed->SetNFoundable(foundable);
//cout<<"found "<<found<<" foundable "<<foundable<<" shared "<<shared<<endl;
//if ((found<0.55*foundable) || shared>0.5*found ){// || (seed->GetSigmaY2()+seed->GetSigmaZ2())>0.5){
//MarkSeedFree(seeds->RemoveAt(itr));
//continue;
//}
if (seed->GetNumberOfClusters()<30 ||
seed->GetNumberOfClusters() < seed->GetNFoundable()*0.6 ||
seed->GetNShared()>0.4*seed->GetNumberOfClusters() ) {
MarkSeedFree(seeds->RemoveAt(itr));
continue;
}
for( int ir=0; ir<nup; ir++){
AliTPCclusterMI *c = seed->GetClusterPointer(ir);
if( c ) c->Use(10);
}
}
std::cout<<"\n\nHLT tracks left: "<<seeds->GetEntries()<<" out of "<<hltEvent->GetNumberOfTracks()<<endl<<endl;
return seeds;
}
void AliTPCtracker::FillClusterOccupancyInfo()
{
//fill the cluster occupancy info into the ESD friend
AliESDfriend* esdFriend = static_cast<AliESDfriend*>(fEvent->FindListObject("AliESDfriend"));
if (!esdFriend) return;
for (Int_t isector=0; isector<18; isector++){
AliTPCtrackerSector &iroc = fInnerSec[isector];
AliTPCtrackerSector &oroc = fOuterSec[isector];
//all clusters
esdFriend->SetNclustersTPC(isector, iroc.GetNClInSector(0));
esdFriend->SetNclustersTPC(isector+18,iroc.GetNClInSector(1));
esdFriend->SetNclustersTPC(isector+36,oroc.GetNClInSector(0));
esdFriend->SetNclustersTPC(isector+54,oroc.GetNClInSector(1));
//clusters used in tracking
esdFriend->SetNclustersTPCused(isector, iroc.GetNClUsedInSector(0));
esdFriend->SetNclustersTPCused(isector+18, iroc.GetNClUsedInSector(1));
esdFriend->SetNclustersTPCused(isector+36, oroc.GetNClUsedInSector(0));
esdFriend->SetNclustersTPCused(isector+54, oroc.GetNClUsedInSector(1));
}
}
void AliTPCtracker::FillSeedClusterStatCache(const AliTPCseed* seed)
{
//RS fill cache for seed's cluster statistics evaluation buffer
for (int i=kMaxRow;i--;) {
Int_t index = seed->GetClusterIndex2(i);
fClStatFoundable[i] = (index!=-1);
fClStatFound[i] = fClStatShared[i] = kFALSE;
if (index<0 || (index&0x8000)) continue;
const AliTPCclusterMI* cl = GetClusterMI(index);
if (cl->IsUsed(10)) fClStatShared[i] = kTRUE;
}
}
void AliTPCtracker::GetCachedSeedClusterStatistic(Int_t first, Int_t last, Int_t &found, Int_t &foundable, Int_t &shared, Bool_t plus2) const
{
//RS calculation of cached seed statistics
found = 0;
foundable = 0;
shared = 0;
//
for (Int_t i=first;i<last; i++){
if (fClStatFoundable[i]) foundable++;
else continue;
//
if (fClStatFound[i]) found++;
else continue;
//
if (fClStatShared[i]) {
shared++;
continue;
}
if (!plus2) continue; //take also neighborhoud
//
if ( i>0 && fClStatShared[i-1]) {
shared++;
continue;
}
if ( i<(kMaxRow-1) && fClStatShared[i+1]) {
shared++;
continue;
}
}
}
void AliTPCtracker::GetSeedClusterStatistic(const AliTPCseed* seed, Int_t first, Int_t last, Int_t &found, Int_t &foundable, Int_t &shared, Bool_t plus2) const
{
// RS: get cluster stat. on given region, faster for small regions than cachin the whole seed stat.
//
found = 0;
foundable = 0;
shared =0;
for (Int_t i=first;i<last; i++){
Int_t index = seed->GetClusterIndex2(i);
if (index!=-1) foundable++;
if (index&0x8000) continue;
if (index>=0) found++;
else continue;
const AliTPCclusterMI* cl = GetClusterMI(index);
if (cl->IsUsed(10)) {
shared++;
continue;
}
if (!plus2) continue; //take also neighborhoud
//
if (i>0) {
index = seed->GetClusterIndex2(i-1);
cl = index<0 ? 0:GetClusterMI(index);
if (cl && cl->IsUsed(10)) {
shared++;
continue;
}
}
if (i<(kMaxRow-1)) {
index = seed->GetClusterIndex2(i+1);
cl = index<0 ? 0:GetClusterMI(index);
if (cl && cl->IsUsed(10)) {
shared++;
continue;
}
}
}
}
Bool_t AliTPCtracker::DistortX(const AliTPCseed* seed, double& x, int row)
{
// distort X by the distorion at track location on given row
//
//RS:? think to unset fAccountDistortions if no maps are used
if (!AliTPCReconstructor::GetRecoParam()->GetUseCorrectionMap()) return kTRUE;
double xyz[3];
int rowInp = row;//RS
if (!seed->GetYZAt(x,AliTracker::GetBz(),&xyz[1])) return kFALSE; //RS:? Think to cache fBz?
xyz[0] = x;
int roc = seed->GetRelativeSector();
if (seed->GetZ()<0) roc += 18;
if (row>62) {
roc += 36;
row -= 63;
}
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform();
if (!transform) AliFatal("Tranformations not in calibDB");
x += transform->EvalCorrectionMap(roc,row,xyz,0);
return kTRUE;
}
Double_t AliTPCtracker::GetDistortionX(double x, double y, double z, int sec, int row)
{
// get X distortion at location on given row
//
if (!AliTPCReconstructor::GetRecoParam()->GetUseCorrectionMap()) return 0;
double xyz[3] = {x,y,z};
int rowInp = row;
int secInp = sec;
if (z<0) sec += 18;
if (row>62) {
sec += 36;
row -= 63;
}
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform() ;
if (!transform) AliFatal("Tranformations not in calibDB");
return transform->EvalCorrectionMap(sec,row,xyz,0);
}
Double_t AliTPCtracker::GetYSectEdgeDist(int sec, int row, double y, double z)
{
// get the signed shift for maxY of the sector/row accounting for distortion
// Slow way, to speed up
if (!AliTPCReconstructor::GetRecoParam()->GetUseCorrectionMap()) return 0;
double ymax = 0.9*GetMaxY(row); // evaluate distortions at 5% of pad lenght from the edge
if (y<0) ymax = -ymax;
double xyz[3] = {GetXrow(row),ymax,z};
if (z<0) sec += 18;
if (row>62) {
sec += 36;
row -= 63;
}
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform();
if (!transform) AliFatal("Tranformations not in calibDB");
// change of distance from the edge due to the X shift
double dxtg = transform->EvalCorrectionMap(sec,row,xyz,0)*AliTPCTransform::GetMaxY2X();
double dy = transform->EvalCorrectionMap(sec,row,xyz,1);
return dy + (y>0?dxtg:-dxtg);
//
}
Int_t AliTPCtracker::GetTrackSector(double alpha)
{
//convert alpha to sector
if (alpha<0) alpha += TMath::Pi()*2;
int sec = alpha/(TMath::Pi()/9);
return sec;
}
void AliTPCtracker::CleanESDFriendsObjects(AliESDEvent* esd)
{
// RS: remove seeds stored in friend's calib object contained w/o changing its ownership
//
AliInfo("Removing own seeds from friend tracks");
AliESDfriend* esdF = esd->FindFriend();
int ntr = esd->GetNumberOfTracks();
for (int itr=ntr;itr--;) {
AliESDtrack* trc = esd->GetTrack(itr);
AliESDfriendTrack* trcF = (AliESDfriendTrack*)trc->GetFriendTrack();
if (!trcF) continue;
AliTPCseed* seed = (AliTPCseed*)trcF->GetTPCseed();
if (seed) {
trcF->RemoveCalibObject((TObject*)seed);
seed->SetClusterOwner(kFALSE);
seed->SetClustersArrayTMP(0);
}
}
//
}
//__________________________________________________________________
void AliTPCtracker::CleanESDTracksObjects(TObjArray* trcList)
{
// RS: remove seeds stored in friend's calib object contained w/o changing its ownership
//
int ntr = trcList->GetEntriesFast();
for (int itr=0;itr<ntr;itr++) {
TObject *obj = trcList->At(itr);
AliESDfriendTrack* trcF = (obj->IsA()==AliESDtrack::Class()) ?
(AliESDfriendTrack*)((AliESDtrack*)obj)->GetFriendTrack() : (AliESDfriendTrack*)obj;
if (!trcF) continue;
AliTPCseed* seed = (AliTPCseed*)trcF->GetTPCseed();
if (seed) {
trcF->RemoveCalibObject((TObject*)seed);
seed->SetClusterOwner(kFALSE);
seed->SetClustersArrayTMP(0);
}
}
//
}
Version of MakeSeeds2 aware of distortions
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------
// Implementation of the TPC tracker
//
// Origin: Marian Ivanov Marian.Ivanov@cern.ch
//
// AliTPC parallel tracker
//
// The track fitting is based on Kalman filtering approach
// The track finding steps:
// 1. Seeding - with and without vertex constraint
// - seeding with vertex constain done at first n^2 proble
// - seeding without vertex constraint n^3 problem
// 2. Tracking - follow prolongation road - find cluster - update kalman track
// The seeding and tracking is repeated several times, in different seeding region.
// This approach enables to find the track which cannot be seeded in some region of TPC
// This can happen because of low momenta (track do not reach outer radius), or track is currently in the ded region between sectors, or the track is for the moment overlapped with other track (seed quality is poor) ...
// With this approach we reach almost 100 % efficiency also for high occupancy events.
// (If the seeding efficiency in a region is about 90 % than with logical or of several
// regions we will reach 100% (in theory - supposing independence)
// Repeating several seeding - tracking procedures some of the tracks can be find
// several times.
// The procedures to remove multi find tacks are impremented:
// RemoveUsed2 - fast procedure n problem -
// Algorithm - Sorting tracks according quality
// remove tracks with some shared fraction
// Sharing in respect to all tacks
// Signing clusters in gold region
// FindSplitted - slower algorithm n^2
// Sort the tracks according quality
// Loop over pair of tracks
// If overlap with other track bigger than threshold - remove track
//
// FindCurling - Finds the pair of tracks which are curling
// - About 10% of tracks can be find with this procedure
// The combinatorial background is too big to be used in High
// multiplicity environment
// - n^2 problem - Slow procedure - currently it is disabled because of
// low efficiency
//
// The number of splitted tracks can be reduced disabling the sharing of the cluster.
// tpcRecoParam-> SetClusterSharing(kFALSE);
// IT IS HIGHLY non recomended to use it in high flux enviroonment
// Even using this switch some tracks can be found more than once
// (because of multiple seeding and low quality tracks which will not cross full chamber)
//
//
// The tracker itself can be debugged - the information about tracks can be stored in several // phases of the reconstruction
// To enable storage of the TPC tracks in the ESD friend track
// use AliTPCReconstructor::SetStreamLevel(n);
//
// The debug level - different procedure produce tree for numerical debugging of code and data (see comments foEStreamFlags in AliTPCtracker.h )
//
//
// Adding systematic errors to the covariance:
//
// The systematic errors due to the misalignment and miscalibration are added to the covariance matrix
// of the tracks (not to the clusters as they are dependent):
// The parameters form AliTPCRecoParam are used AliTPCRecoParam::GetSystematicError
// The systematic errors are expressed there in RMS - position (cm), angle (rad), curvature (1/GeV)
// The default values are 0.
//
// The systematic errors are added to the covariance matrix in following places:
//
// 1. During fisrt itteration - AliTPCtracker::FillESD
// 2. Second iteration -
// 2.a ITS->TPC - AliTPCtracker::ReadSeeds
// 2.b TPC->TRD - AliTPCtracker::PropagateBack
// 3. Third iteration -
// 3.a TRD->TPC - AliTPCtracker::ReadSeeds
// 3.b TPC->ITS - AliTPCtracker::RefitInward
//
/* $Id$ */
#include "Riostream.h"
#include <TClonesArray.h>
#include <TFile.h>
#include <TObjArray.h>
#include <TTree.h>
#include <TMatrixD.h>
#include <TGraphErrors.h>
#include <TTimeStamp.h>
#include "AliLog.h"
#include "AliComplexCluster.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"
#include "AliESDVertex.h"
#include "AliKink.h"
#include "AliV0.h"
#include "AliHelix.h"
#include "AliRunLoader.h"
#include "AliTPCClustersRow.h"
#include "AliTPCParam.h"
#include "AliTPCReconstructor.h"
#include "AliTPCpolyTrack.h"
#include "AliTPCreco.h"
#include "AliTPCseed.h"
#include "AliTPCtrackerSector.h"
#include "AliTPCtracker.h"
#include "TStopwatch.h"
#include "AliTPCReconstructor.h"
#include "AliAlignObj.h"
#include "AliTrackPointArray.h"
#include "TRandom.h"
#include "AliTPCcalibDB.h"
#include "AliTPCcalibDButil.h"
#include "AliTPCTransform.h"
#include "AliTPCClusterParam.h"
#include "AliTPCdEdxInfo.h"
#include "AliDCSSensorArray.h"
#include "AliDCSSensor.h"
#include "AliDAQ.h"
#include "AliCosmicTracker.h"
#include "AliTPCROC.h"
#include "AliMathBase.h"
//
#include "AliESDfriendTrack.h"
using std::cout;
using std::cerr;
using std::endl;
ClassImp(AliTPCtracker)
//__________________________________________________________________
AliTPCtracker::AliTPCtracker()
:AliTracker(),
fkNIS(0),
fInnerSec(0),
fkNOS(0),
fOuterSec(0),
fN(0),
fSectors(0),
fInput(0),
fOutput(0),
fSeedTree(0),
fTreeDebug(0),
fEvent(0),
fEventHLT(0),
fDebug(0),
fNewIO(kFALSE),
fNtracks(0),
fSeeds(0),
fIteration(0),
fkParam(0),
fDebugStreamer(0),
fUseHLTClusters(4),
fClExtraRoadY(0.),
fClExtraRoadZ(0.),
fExtraClErrYZ2(0),
fExtraClErrY2(0),
fExtraClErrZ2(0),
fPrimaryDCAZCut(-1),
fPrimaryDCAYCut(-1),
fDisableSecondaries(kFALSE),
fCrossTalkSignalArray(0),
fClPointersPool(0),
fClPointersPoolPtr(0),
fClPointersPoolSize(0),
fSeedsPool(0),
fHelixPool(0),
fETPPool(0),
fFreeSeedsID(500),
fNFreeSeeds(0),
fLastSeedID(-1),
fAccountDistortions(0)
{
//
// default constructor
//
for (Int_t irow=0; irow<200; irow++){
fXRow[irow]=0;
fYMax[irow]=0;
fPadLength[irow]=0;
}
}
//_____________________________________________________________________
Int_t AliTPCtracker::UpdateTrack(AliTPCseed * track, Int_t accept){
//
//update track information using current cluster - track->fCurrentCluster
AliTPCclusterMI* c =track->GetCurrentCluster();
if (accept > 0) //sign not accepted clusters
track->SetCurrentClusterIndex1(track->GetCurrentClusterIndex1() | 0x8000);
else // unsign accpeted clusters
track->SetCurrentClusterIndex1(track->GetCurrentClusterIndex1() & 0xffff7fff);
UInt_t i = track->GetCurrentClusterIndex1();
Int_t sec=(i&0xff000000)>>24;
//Int_t row = (i&0x00ff0000)>>16;
track->SetRow((i&0x00ff0000)>>16);
track->SetSector(sec);
// Int_t index = i&0xFFFF;
int row = track->GetRow();
if (sec>=fkParam->GetNInnerSector()) {
row += fkParam->GetNRowLow();
track->SetRow(row);
}
track->SetClusterIndex2(row, i);
//track->fFirstPoint = row;
//if ( track->fLastPoint<row) track->fLastPoint =row;
// if (track->fRow<0 || track->fRow>=kMaxRow) {
// printf("problem\n");
//}
if (track->GetFirstPoint()>row)
track->SetFirstPoint(row);
if (track->GetLastPoint()<row)
track->SetLastPoint(row);
//RS track->SetClusterPointer(row,c);
//
Double_t angle2 = track->GetSnp()*track->GetSnp();
//
//SET NEW Track Point
//
if (angle2<1) //PH sometimes angle2 is very big. To be investigated...
{
angle2 = TMath::Sqrt(angle2/(1-angle2));
AliTPCTrackerPoints::Point &point =*((AliTPCTrackerPoints::Point*)track->GetTrackPoint(row));
//
point.SetSigmaY(c->GetSigmaY2()/track->GetCurrentSigmaY2());
point.SetSigmaZ(c->GetSigmaZ2()/track->GetCurrentSigmaZ2());
point.SetErrY(sqrt(track->GetErrorY2()));
point.SetErrZ(sqrt(track->GetErrorZ2()));
//
point.SetX(track->GetX());
point.SetY(track->GetY());
point.SetZ(track->GetZ());
point.SetAngleY(angle2);
point.SetAngleZ(track->GetTgl());
if (track->IsShared(row)){
track->SetErrorY2(track->GetErrorY2()*4);
track->SetErrorZ2(track->GetErrorZ2()*4);
}
}
Double_t chi2 = track->GetPredictedChi2(track->GetCurrentCluster());
//
// track->SetErrorY2(track->GetErrorY2()*1.3);
// track->SetErrorY2(track->GetErrorY2()+0.01);
// track->SetErrorZ2(track->GetErrorZ2()*1.3);
// track->SetErrorZ2(track->GetErrorZ2()+0.005);
//}
if (accept>0) return 0;
if (track->GetNumberOfClusters()%20==0){
// if (track->fHelixIn){
// TClonesArray & larr = *(track->fHelixIn);
// Int_t ihelix = larr.GetEntriesFast();
// new(larr[ihelix]) AliHelix(*track) ;
//}
}
if (AliTPCReconstructor::StreamLevel()&kStreamUpdateTrack) {
Int_t event = (fEvent==NULL)? 0: fEvent->GetEventNumberInFile();
AliExternalTrackParam param(*track);
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"UpdateTrack"<<
"cl.="<<c<<
"event="<<event<<
"track.="<<¶m<<
"\n";
}
track->SetNoCluster(0);
return track->Update(c,chi2,i);
}
Int_t AliTPCtracker::AcceptCluster(AliTPCseed * seed, AliTPCclusterMI * cluster)
{
//
// decide according desired precision to accept given
// cluster for tracking
Double_t yt = seed->GetY(),zt = seed->GetZ();
// RS: use propagation only if the seed in far from the cluster
const double kTolerance = 10e-4; // assume track is at cluster X if X-distance below this
if (TMath::Abs(seed->GetX()-cluster->GetX())>kTolerance) seed->GetProlongation(cluster->GetX(),yt,zt);
Double_t sy2=ErrY2(seed,cluster);
Double_t sz2=ErrZ2(seed,cluster);
Double_t sdistancey2 = sy2+seed->GetSigmaY2();
Double_t sdistancez2 = sz2+seed->GetSigmaZ2();
Double_t dy=seed->GetCurrentCluster()->GetY()-yt;
Double_t dz=seed->GetCurrentCluster()->GetZ()-zt;
Double_t rdistancey2 = (seed->GetCurrentCluster()->GetY()-yt)*
(seed->GetCurrentCluster()->GetY()-yt)/sdistancey2;
Double_t rdistancez2 = (seed->GetCurrentCluster()->GetZ()-zt)*
(seed->GetCurrentCluster()->GetZ()-zt)/sdistancez2;
Double_t rdistance2 = rdistancey2+rdistancez2;
//Int_t accept =0;
if (AliTPCReconstructor::StreamLevel()>2 && ( (fIteration>0)|| (seed->GetNumberOfClusters()>20))) {
// if (AliTPCReconstructor::StreamLevel()>2 && seed->GetNumberOfClusters()>20) {
Float_t rmsy2 = seed->GetCurrentSigmaY2();
Float_t rmsz2 = seed->GetCurrentSigmaZ2();
Float_t rmsy2p30 = seed->GetCMeanSigmaY2p30();
Float_t rmsz2p30 = seed->GetCMeanSigmaZ2p30();
Float_t rmsy2p30R = seed->GetCMeanSigmaY2p30R();
Float_t rmsz2p30R = seed->GetCMeanSigmaZ2p30R();
AliExternalTrackParam param(*seed);
static TVectorD gcl(3),gtr(3);
Float_t gclf[3];
param.GetXYZ(gcl.GetMatrixArray());
cluster->GetGlobalXYZ(gclf);
gcl[0]=gclf[0]; gcl[1]=gclf[1]; gcl[2]=gclf[2];
Int_t nclSeed=seed->GetNumberOfClusters();
int seedType = seed->GetSeedType();
if (AliTPCReconstructor::StreamLevel()&kStreamErrParam) { // flag:stream in debug mode cluster and track extrapolation at given row together with error nad shape estimate
Int_t eventNr = fEvent->GetEventNumberInFile();
(*fDebugStreamer)<<"ErrParam"<<
"iter="<<fIteration<<
"eventNr="<<eventNr<<
"Cl.="<<cluster<<
"nclSeed="<<nclSeed<<
"seedType="<<seedType<<
"T.="<<¶m<<
"dy="<<dy<<
"dz="<<dz<<
"yt="<<yt<<
"zt="<<zt<<
"gcl.="<<&gcl<<
"gtr.="<<>r<<
"erry2="<<sy2<<
"errz2="<<sz2<<
"rmsy2="<<rmsy2<<
"rmsz2="<<rmsz2<<
"rmsy2p30="<<rmsy2p30<<
"rmsz2p30="<<rmsz2p30<<
"rmsy2p30R="<<rmsy2p30R<<
"rmsz2p30R="<<rmsz2p30R<<
// normalize distance -
"rdisty="<<rdistancey2<<
"rdistz="<<rdistancez2<<
"rdist="<<rdistance2<< //
"\n";
}
}
//return 0; // temporary
if (rdistance2>32) return 3;
if ((rdistancey2>9. || rdistancez2>9.) && cluster->GetType()==0)
return 2; //suspisiouce - will be changed
if ((rdistancey2>6.25 || rdistancez2>6.25) && cluster->GetType()>0)
// strict cut on overlaped cluster
return 2; //suspisiouce - will be changed
if ( (rdistancey2>1. || rdistancez2>6.25 )
&& cluster->GetType()<0){
seed->SetNFoundable(seed->GetNFoundable()-1);
return 2;
}
if (fUseHLTClusters == 3 || fUseHLTClusters == 4) {
if (fIteration==2){
if(!AliTPCReconstructor::GetRecoParam()->GetUseHLTOnePadCluster()) {
if (TMath::Abs(cluster->GetSigmaY2()) < kAlmost0)
return 2;
}
}
}
return 0;
}
//_____________________________________________________________________________
AliTPCtracker::AliTPCtracker(const AliTPCParam *par):
AliTracker(),
fkNIS(par->GetNInnerSector()/2),
fInnerSec(0),
fkNOS(par->GetNOuterSector()/2),
fOuterSec(0),
fN(0),
fSectors(0),
fInput(0),
fOutput(0),
fSeedTree(0),
fTreeDebug(0),
fEvent(0),
fEventHLT(0),
fDebug(0),
fNewIO(0),
fNtracks(0),
fSeeds(0),
fIteration(0),
fkParam(0),
fDebugStreamer(0),
fUseHLTClusters(4),
fClExtraRoadY(0.),
fClExtraRoadZ(0.),
fExtraClErrYZ2(0),
fExtraClErrY2(0),
fExtraClErrZ2(0),
fPrimaryDCAZCut(-1),
fPrimaryDCAYCut(-1),
fDisableSecondaries(kFALSE),
fCrossTalkSignalArray(0),
fClPointersPool(0),
fClPointersPoolPtr(0),
fClPointersPoolSize(0),
fSeedsPool(0),
fHelixPool(0),
fETPPool(0),
fFreeSeedsID(500),
fNFreeSeeds(0),
fLastSeedID(-1),
fAccountDistortions(0)
{
//---------------------------------------------------------------------
// The main TPC tracker constructor
//---------------------------------------------------------------------
fInnerSec=new AliTPCtrackerSector[fkNIS];
fOuterSec=new AliTPCtrackerSector[fkNOS];
Int_t i;
for (i=0; i<fkNIS; i++) fInnerSec[i].Setup(par,0);
for (i=0; i<fkNOS; i++) fOuterSec[i].Setup(par,1);
fkParam = par;
Int_t nrowlow = par->GetNRowLow();
Int_t nrowup = par->GetNRowUp();
for (i=0;i<nrowlow;i++){
fXRow[i] = par->GetPadRowRadiiLow(i);
fPadLength[i]= par->GetPadPitchLength(0,i);
fYMax[i] = fXRow[i]*TMath::Tan(0.5*par->GetInnerAngle());
}
for (i=0;i<nrowup;i++){
fXRow[i+nrowlow] = par->GetPadRowRadiiUp(i);
fPadLength[i+nrowlow] = par->GetPadPitchLength(60,i);
fYMax[i+nrowlow] = fXRow[i+nrowlow]*TMath::Tan(0.5*par->GetOuterAngle());
}
if (AliTPCReconstructor::StreamLevel()>0) {
fDebugStreamer = new TTreeSRedirector("TPCdebug.root","recreate");
AliTPCReconstructor::SetDebugStreamer(fDebugStreamer);
}
//
fSeedsPool = new TClonesArray("AliTPCseed",1000);
fClPointersPool = new AliTPCclusterMI*[kMaxFriendTracks*kMaxRow];
memset(fClPointersPool,0,kMaxFriendTracks*kMaxRow*sizeof(AliTPCclusterMI*));
fClPointersPoolPtr = fClPointersPool;
fClPointersPoolSize = kMaxFriendTracks;
//
// crosstalk array and matrix initialization
Int_t nROCs = 72;
Int_t nTimeBinsAll = AliTPCcalibDB::Instance()->GetMaxTimeBinAllPads() ;
Int_t nWireSegments = 11;
fCrossTalkSignalArray = new TObjArray(nROCs*4); //
fCrossTalkSignalArray->SetOwner(kTRUE);
for (Int_t isector=0; isector<4*nROCs; isector++){
TMatrixD * crossTalkSignal = new TMatrixD(nWireSegments,nTimeBinsAll);
for (Int_t imatrix = 0; imatrix<11; imatrix++)
for (Int_t jmatrix = 0; jmatrix<nTimeBinsAll; jmatrix++){
(*crossTalkSignal)[imatrix][jmatrix]=0.;
}
fCrossTalkSignalArray->AddAt(crossTalkSignal,isector);
}
}
//________________________________________________________________________
AliTPCtracker::AliTPCtracker(const AliTPCtracker &t):
AliTracker(t),
fkNIS(t.fkNIS),
fInnerSec(0),
fkNOS(t.fkNOS),
fOuterSec(0),
fN(0),
fSectors(0),
fInput(0),
fOutput(0),
fSeedTree(0),
fTreeDebug(0),
fEvent(0),
fEventHLT(0),
fDebug(0),
fNewIO(kFALSE),
fNtracks(0),
fSeeds(0),
fIteration(0),
fkParam(0),
fDebugStreamer(0),
fUseHLTClusters(4),
fClExtraRoadY(0.),
fClExtraRoadZ(0.),
fExtraClErrYZ2(0),
fExtraClErrY2(0),
fExtraClErrZ2(0),
fPrimaryDCAZCut(-1),
fPrimaryDCAYCut(-1),
fDisableSecondaries(kFALSE),
fCrossTalkSignalArray(0),
fClPointersPool(0),
fClPointersPoolPtr(0),
fClPointersPoolSize(0),
fSeedsPool(0),
fHelixPool(0),
fETPPool(0),
fFreeSeedsID(500),
fNFreeSeeds(0),
fAccountDistortions(0)
{
//------------------------------------
// dummy copy constructor
//------------------------------------------------------------------
fOutput=t.fOutput;
for (Int_t irow=0; irow<200; irow++){
fXRow[irow]=0;
fYMax[irow]=0;
fPadLength[irow]=0;
}
}
AliTPCtracker & AliTPCtracker::operator=(const AliTPCtracker& /*r*/)
{
//------------------------------
// dummy
//--------------------------------------------------------------
return *this;
}
//_____________________________________________________________________________
AliTPCtracker::~AliTPCtracker() {
//------------------------------------------------------------------
// TPC tracker destructor
//------------------------------------------------------------------
delete[] fInnerSec;
delete[] fOuterSec;
if (fSeeds) {
fSeeds->Clear();
delete fSeeds;
}
delete[] fClPointersPool;
if (fCrossTalkSignalArray) delete fCrossTalkSignalArray;
if (fDebugStreamer) delete fDebugStreamer;
if (fSeedsPool) {
for (int isd=fSeedsPool->GetEntriesFast();isd--;) {
AliTPCseed* seed = (AliTPCseed*)fSeedsPool->At(isd);
if (seed) {
seed->SetClusterOwner(kFALSE);
seed->SetClustersArrayTMP(0);
}
}
delete fSeedsPool;
}
if (fHelixPool) fHelixPool->Delete();
delete fHelixPool;
if (fETPPool) fETPPool->Delete();
delete fETPPool;
}
void AliTPCtracker::FillESD(const TObjArray* arr)
{
//
//
//fill esds using updated tracks
if (!fEvent) return;
AliESDtrack iotrack;
// write tracks to the event
// store index of the track
Int_t nseed=arr->GetEntriesFast();
//FindKinks(arr,fEvent);
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
pt->UpdatePoints();
AddCovariance(pt);
if (AliTPCReconstructor::StreamLevel()&kStreamFillESD) {
(*fDebugStreamer)<<"FillESD"<< // flag: stream track information in FillESD function (after track Iteration 0)
"Tr0.="<<pt<<
"\n";
}
// pt->PropagateTo(fkParam->GetInnerRadiusLow());
if (pt->GetKinkIndex(0)<=0){ //don't propagate daughter tracks
pt->PropagateTo(fkParam->GetInnerRadiusLow());
}
if (( pt->GetPoints()[2]- pt->GetPoints()[0])>5 && pt->GetPoints()[3]>0.8){
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
// iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
MakeESDBitmaps(pt, &iotrack);
fEvent->AddTrack(&iotrack);
continue;
}
if ( (pt->GetNumberOfClusters()>70)&& (Float_t(pt->GetNumberOfClusters())/Float_t(pt->GetNFoundable()))>0.55) {
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
//iotrack.SetTPCindex(i);
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
// iotrack.SetTPCpid(pt->fTPCr);
fEvent->AddTrack(&iotrack);
continue;
}
//
// short tracks - maybe decays
//RS Seed don't keep their cluster pointers, cache cluster usage stat. for fast evaluation
// FillSeedClusterStatCache(pt); // RS use this slow method only if info on shared statistics is needed
if ( (pt->GetNumberOfClusters()>30) && (Float_t(pt->GetNumberOfClusters())/Float_t(pt->GetNFoundable()))>0.70) {
Int_t found,foundable; //,shared;
//GetCachedSeedClusterStatistic(0,60,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//pt->GetClusterStatistic(0,60,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(0,60,found, foundable);
if ( (found>20) && (pt->GetNShared()/float(pt->GetNumberOfClusters())<0.2)){
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
//iotrack.SetTPCindex(i);
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
//iotrack.SetTPCpid(pt->fTPCr);
fEvent->AddTrack(&iotrack);
continue;
}
}
if ( (pt->GetNumberOfClusters()>20) && (Float_t(pt->GetNumberOfClusters())/Float_t(pt->GetNFoundable()))>0.8) {
Int_t found,foundable;//,shared;
//RS GetCachedSeedClusterStatistic(0,60,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//pt->GetClusterStatistic(0,60,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(0,60,found,foundable);
if (found<20) continue;
if (pt->GetNShared()/float(pt->GetNumberOfClusters())>0.2) continue;
//
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
//iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
fEvent->AddTrack(&iotrack);
continue;
}
// short tracks - secondaties
//
if ( (pt->GetNumberOfClusters()>30) ) {
Int_t found,foundable;//,shared;
//GetCachedSeedClusterStatistic(128,158,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//pt->GetClusterStatistic(128,158,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(128,158,found, foundable);
if ( (found>20) && (pt->GetNShared()/float(pt->GetNumberOfClusters())<0.2) &&float(found)/float(foundable)>0.8){
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
//iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
fEvent->AddTrack(&iotrack);
continue;
}
}
if ( (pt->GetNumberOfClusters()>15)) {
Int_t found,foundable,shared;
//GetCachedSeedClusterStatistic(138,158,found, foundable,shared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS pt->GetClusterStatistic(138,158,found, foundable,shared,kFALSE); //RS: avoid this method: seed does not keep clusters
pt->GetClusterStatistic(138,158,found, foundable);
if (found<15) continue;
if (foundable<=0) continue;
if (pt->GetNShared()/float(pt->GetNumberOfClusters())>0.2) continue;
if (float(found)/float(foundable)<0.8) continue;
//
iotrack.~AliESDtrack();
new(&iotrack) AliESDtrack;
iotrack.UpdateTrackParams(pt,AliESDtrack::kTPCin);
iotrack.SetTPCsignal(pt->GetdEdx(), pt->GetSDEDX(0), pt->GetNCDEDX(0));
iotrack.SetTPCPoints(pt->GetPoints());
iotrack.SetKinkIndexes(pt->GetKinkIndexes());
iotrack.SetV0Indexes(pt->GetV0Indexes());
MakeESDBitmaps(pt, &iotrack);
// iotrack.SetTPCpid(pt->fTPCr);
//iotrack.SetTPCindex(i);
fEvent->AddTrack(&iotrack);
continue;
}
}
// >> account for suppressed tracks in the kink indices (RS)
int nESDtracks = fEvent->GetNumberOfTracks();
for (int it=nESDtracks;it--;) {
AliESDtrack* esdTr = fEvent->GetTrack(it);
if (!esdTr || !esdTr->GetKinkIndex(0)) continue;
for (int ik=0;ik<3;ik++) {
int knkId=0;
if (!(knkId=esdTr->GetKinkIndex(ik))) break; // no more kinks for this track
AliESDkink* kink = fEvent->GetKink(TMath::Abs(knkId)-1);
if (!kink) {
AliError(Form("ESDTrack%d refers to non-existing kink %d",it,TMath::Abs(knkId)-1));
continue;
}
kink->SetIndex(it, knkId<0 ? 0:1); // update track index of the kink: mother at 0, daughter at 1
}
}
// << account for suppressed tracks in the kink indices (RS)
AliInfo(Form("Number of filled ESDs-\t%d\n",fEvent->GetNumberOfTracks()));
}
Double_t AliTPCtracker::ErrY2(AliTPCseed* seed, const AliTPCclusterMI * cl){
//
//
// Use calibrated cluster error from OCDB
//
AliTPCClusterParam * clparam = AliTPCcalibDB::Instance()->GetClusterParam();
//
Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
Int_t ctype = cl->GetType();
Int_t type = (cl->GetRow()<63) ? 0: (cl->GetRow()>126) ? 1:2;
Double_t angle = seed->GetSnp()*seed->GetSnp();
angle = TMath::Sqrt(TMath::Abs(angle/(1.-angle)));
Double_t erry2 = clparam->GetError0Par(0,type, z,angle);
if (ctype<0) {
erry2+=0.5; // edge cluster
}
erry2*=erry2;
Double_t addErr=0;
const Double_t *errInner = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInner();
const Double_t *errInnerDeep = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInnerDeepY();
double dr = TMath::Abs(cl->GetX()-85.);
addErr=errInner[0]*TMath::Exp(-dr/errInner[1]);
if (errInnerDeep[0]>0) addErr += errInnerDeep[0]*TMath::Exp(-dr/errInnerDeep[1]);
erry2+=addErr*addErr;
const Double_t *errCluster = (AliTPCReconstructor::GetSystematicErrorCluster()) ? AliTPCReconstructor::GetSystematicErrorCluster() : AliTPCReconstructor::GetRecoParam()->GetSystematicErrorCluster();
erry2+=errCluster[0]*errCluster[0];
seed->SetErrorY2(erry2);
//
return erry2;
//calculate look-up table at the beginning
// static Bool_t ginit = kFALSE;
// static Float_t gnoise1,gnoise2,gnoise3;
// static Float_t ggg1[10000];
// static Float_t ggg2[10000];
// static Float_t ggg3[10000];
// static Float_t glandau1[10000];
// static Float_t glandau2[10000];
// static Float_t glandau3[10000];
// //
// static Float_t gcor01[500];
// static Float_t gcor02[500];
// static Float_t gcorp[500];
// //
// //
// if (ginit==kFALSE){
// for (Int_t i=1;i<500;i++){
// Float_t rsigma = float(i)/100.;
// gcor02[i] = TMath::Max(0.78 +TMath::Exp(7.4*(rsigma-1.2)),0.6);
// gcor01[i] = TMath::Max(0.72 +TMath::Exp(3.36*(rsigma-1.2)),0.6);
// gcorp[i] = TMath::Max(TMath::Power((rsigma+0.5),1.5),1.2);
// }
// //
// for (Int_t i=3;i<10000;i++){
// //
// //
// // inner sector
// Float_t amp = float(i);
// Float_t padlength =0.75;
// gnoise1 = 0.0004/padlength;
// Float_t nel = 0.268*amp;
// Float_t nprim = 0.155*amp;
// ggg1[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.001*nel/(padlength*padlength))/nel;
// glandau1[i] = (2.+0.12*nprim)*0.5* (2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau1[i]>1) glandau1[i]=1;
// glandau1[i]*=padlength*padlength/12.;
// //
// // outer short
// padlength =1.;
// gnoise2 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg2[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau2[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau2[i]>1) glandau2[i]=1;
// glandau2[i]*=padlength*padlength/12.;
// //
// //
// // outer long
// padlength =1.5;
// gnoise3 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg3[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau3[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau3[i]>1) glandau3[i]=1;
// glandau3[i]*=padlength*padlength/12.;
// //
// }
// ginit = kTRUE;
// }
// //
// //
// //
// Int_t amp = int(TMath::Abs(cl->GetQ()));
// if (amp>9999) {
// seed->SetErrorY2(1.);
// return 1.;
// }
// Float_t snoise2;
// Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
// Int_t ctype = cl->GetType();
// Float_t padlength= GetPadPitchLength(seed->GetRow());
// Double_t angle2 = seed->GetSnp()*seed->GetSnp();
// angle2 = angle2/(1-angle2);
// //
// //cluster "quality"
// Int_t rsigmay = int(100.*cl->GetSigmaY2()/(seed->GetCurrentSigmaY2()));
// Float_t res;
// //
// if (fSectors==fInnerSec){
// snoise2 = gnoise1;
// res = ggg1[amp]*z+glandau1[amp]*angle2;
// if (ctype==0) res *= gcor01[rsigmay];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmay];
// }
// }
// else {
// if (padlength<1.1){
// snoise2 = gnoise2;
// res = ggg2[amp]*z+glandau2[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmay];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmay];
// }
// }
// else{
// snoise2 = gnoise3;
// res = ggg3[amp]*z+glandau3[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmay];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmay];
// }
// }
// }
// if (ctype<0){
// res+=0.005;
// res*=2.4; // overestimate error 2 times
// }
// res+= snoise2;
// if (res<2*snoise2)
// res = 2*snoise2;
// seed->SetErrorY2(res);
// return res;
}
Double_t AliTPCtracker::ErrZ2(AliTPCseed* seed, const AliTPCclusterMI * cl){
//
//
// Use calibrated cluster error from OCDB
//
AliTPCClusterParam * clparam = AliTPCcalibDB::Instance()->GetClusterParam();
//
Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
Int_t ctype = cl->GetType();
Int_t type = (cl->GetRow()<63) ? 0: (cl->GetRow()>126) ? 1:2;
//
Double_t angle2 = seed->GetSnp()*seed->GetSnp();
angle2 = seed->GetTgl()*seed->GetTgl()*(1+angle2/(1-angle2));
Double_t angle = TMath::Sqrt(TMath::Abs(angle2));
Double_t errz2 = clparam->GetError0Par(1,type, z,angle);
if (ctype<0) {
errz2+=0.5; // edge cluster
}
errz2*=errz2;
Double_t addErr=0;
const Double_t *errInner = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInner();
const Double_t *errInnerDeepZ = AliTPCReconstructor::GetRecoParam()->GetSystematicErrorClusterInnerDeepZ();
double dr = TMath::Abs(cl->GetX()-85.);
addErr=errInner[0]*TMath::Exp(-dr/errInner[1]);
if (errInnerDeepZ[0]>0) addErr += errInnerDeepZ[0]*TMath::Exp(-dr/errInnerDeepZ[1]);
errz2+=addErr*addErr;
const Double_t *errCluster = (AliTPCReconstructor::GetSystematicErrorCluster()) ? AliTPCReconstructor::GetSystematicErrorCluster() : AliTPCReconstructor::GetRecoParam()->GetSystematicErrorCluster();
errz2+=errCluster[1]*errCluster[1];
seed->SetErrorZ2(errz2);
//
return errz2;
// //seed->SetErrorY2(0.1);
// //return 0.1;
// //calculate look-up table at the beginning
// static Bool_t ginit = kFALSE;
// static Float_t gnoise1,gnoise2,gnoise3;
// static Float_t ggg1[10000];
// static Float_t ggg2[10000];
// static Float_t ggg3[10000];
// static Float_t glandau1[10000];
// static Float_t glandau2[10000];
// static Float_t glandau3[10000];
// //
// static Float_t gcor01[1000];
// static Float_t gcor02[1000];
// static Float_t gcorp[1000];
// //
// //
// if (ginit==kFALSE){
// for (Int_t i=1;i<1000;i++){
// Float_t rsigma = float(i)/100.;
// gcor02[i] = TMath::Max(0.81 +TMath::Exp(6.8*(rsigma-1.2)),0.6);
// gcor01[i] = TMath::Max(0.72 +TMath::Exp(2.04*(rsigma-1.2)),0.6);
// gcorp[i] = TMath::Max(TMath::Power((rsigma+0.5),1.5),1.2);
// }
// //
// for (Int_t i=3;i<10000;i++){
// //
// //
// // inner sector
// Float_t amp = float(i);
// Float_t padlength =0.75;
// gnoise1 = 0.0004/padlength;
// Float_t nel = 0.268*amp;
// Float_t nprim = 0.155*amp;
// ggg1[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.001*nel/(padlength*padlength))/nel;
// glandau1[i] = (2.+0.12*nprim)*0.5* (2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau1[i]>1) glandau1[i]=1;
// glandau1[i]*=padlength*padlength/12.;
// //
// // outer short
// padlength =1.;
// gnoise2 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg2[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau2[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau2[i]>1) glandau2[i]=1;
// glandau2[i]*=padlength*padlength/12.;
// //
// //
// // outer long
// padlength =1.5;
// gnoise3 = 0.0004/padlength;
// nel = 0.3*amp;
// nprim = 0.133*amp;
// ggg3[i] = fkParam->GetDiffT()*fkParam->GetDiffT()*(2+0.0008*nel/(padlength*padlength))/nel;
// glandau3[i] = (2.+0.12*nprim)*0.5*(2.+nprim*nprim*0.001/(padlength*padlength))/nprim;
// if (glandau3[i]>1) glandau3[i]=1;
// glandau3[i]*=padlength*padlength/12.;
// //
// }
// ginit = kTRUE;
// }
// //
// //
// //
// Int_t amp = int(TMath::Abs(cl->GetQ()));
// if (amp>9999) {
// seed->SetErrorY2(1.);
// return 1.;
// }
// Float_t snoise2;
// Float_t z = TMath::Abs(fkParam->GetZLength(0)-TMath::Abs(seed->GetZ()));
// Int_t ctype = cl->GetType();
// Float_t padlength= GetPadPitchLength(seed->GetRow());
// //
// Double_t angle2 = seed->GetSnp()*seed->GetSnp();
// // if (angle2<0.6) angle2 = 0.6;
// angle2 = seed->GetTgl()*seed->GetTgl()*(1+angle2/(1-angle2));
// //
// //cluster "quality"
// Int_t rsigmaz = int(100.*cl->GetSigmaZ2()/(seed->GetCurrentSigmaZ2()));
// Float_t res;
// //
// if (fSectors==fInnerSec){
// snoise2 = gnoise1;
// res = ggg1[amp]*z+glandau1[amp]*angle2;
// if (ctype==0) res *= gcor01[rsigmaz];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmaz];
// }
// }
// else {
// if (padlength<1.1){
// snoise2 = gnoise2;
// res = ggg2[amp]*z+glandau2[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmaz];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmaz];
// }
// }
// else{
// snoise2 = gnoise3;
// res = ggg3[amp]*z+glandau3[amp]*angle2;
// if (ctype==0) res *= gcor02[rsigmaz];
// if ((ctype>0)){
// res+=0.002;
// res*= gcorp[rsigmaz];
// }
// }
// }
// if (ctype<0){
// res+=0.002;
// res*=1.3;
// }
// if ((ctype<0) &&<70){
// res+=0.002;
// res*=1.3;
// }
// res += snoise2;
// if (res<2*snoise2)
// res = 2*snoise2;
// if (res>3) res =3;
// seed->SetErrorZ2(res);
// return res;
}
void AliTPCtracker::RotateToLocal(AliTPCseed *seed)
{
//rotate to track "local coordinata
Float_t x = seed->GetX();
Float_t y = seed->GetY();
Float_t ymax = x*TMath::Tan(0.5*fSectors->GetAlpha());
if (y > ymax) {
seed->SetRelativeSector((seed->GetRelativeSector()+1) % fN);
if (!seed->Rotate(fSectors->GetAlpha()))
return;
} else if (y <-ymax) {
seed->SetRelativeSector((seed->GetRelativeSector()-1+fN) % fN);
if (!seed->Rotate(-fSectors->GetAlpha()))
return;
}
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F1old(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature
//-----------------------------------------------------------------
Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
(y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
(x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
if ( xr*xr+yr*yr<=0.00000000000001) return 100;
return -xr*yr/sqrt(xr*xr+yr*yr);
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F1(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature
//-----------------------------------------------------------------
x3 -=x1;
x2 -=x1;
y3 -=y1;
y2 -=y1;
//
Double_t det = x3*y2-x2*y3;
if (TMath::Abs(det)<1e-10){
return 100;
}
//
Double_t u = 0.5* (x2*(x2-x3)+y2*(y2-y3))/det;
Double_t x0 = x3*0.5-y3*u;
Double_t y0 = y3*0.5+x3*u;
Double_t c2 = 1/TMath::Sqrt(x0*x0+y0*y0);
if (det<0) c2*=-1;
return c2;
}
Double_t AliTPCtracker::F2(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature
//-----------------------------------------------------------------
x3 -=x1;
x2 -=x1;
y3 -=y1;
y2 -=y1;
//
Double_t det = x3*y2-x2*y3;
if (TMath::Abs(det)<1e-10) {
return 100;
}
//
Double_t u = 0.5* (x2*(x2-x3)+y2*(y2-y3))/det;
Double_t x0 = x3*0.5-y3*u;
Double_t y0 = y3*0.5+x3*u;
Double_t c2 = 1/TMath::Sqrt(x0*x0+y0*y0);
if (det<0) c2*=-1;
x0+=x1;
x0*=c2;
return x0;
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F2old(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t x3,Double_t y3) const
{
//-----------------------------------------------------------------
// Initial approximation of the track curvature times center of curvature
//-----------------------------------------------------------------
Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
(y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
(x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
return -a/(d*y1-b)*xr/sqrt(xr*xr+yr*yr);
}
//_____________________________________________________________________________
Double_t AliTPCtracker::F3(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t z1,Double_t z2) const
{
//-----------------------------------------------------------------
// Initial approximation of the tangent of the track dip angle
//-----------------------------------------------------------------
return (z1 - z2)/sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
Double_t AliTPCtracker::F3n(Double_t x1,Double_t y1,
Double_t x2,Double_t y2,
Double_t z1,Double_t z2, Double_t c) const
{
//-----------------------------------------------------------------
// Initial approximation of the tangent of the track dip angle
//-----------------------------------------------------------------
// Double_t angle1;
//angle1 = (z1-z2)*c/(TMath::ASin(c*x1-ni)-TMath::ASin(c*x2-ni));
//
Double_t d = TMath::Sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
if (TMath::Abs(d*c*0.5)>1) return 0;
Double_t angle2 = asinf(d*c*0.5);
angle2 = (z1-z2)*c/(angle2*2.);
return angle2;
}
Bool_t AliTPCtracker::GetProlongation(Double_t x1, Double_t x2, Double_t x[5], Double_t &y, Double_t &z) const
{//-----------------------------------------------------------------
// This function find proloncation of a track to a reference plane x=x2.
//-----------------------------------------------------------------
Double_t dx=x2-x1;
if (TMath::Abs(x[4]*x1 - x[2]) >= 0.999) {
return kFALSE;
}
Double_t c1=x[4]*x1 - x[2], r1=TMath::Sqrt((1.-c1)*(1.+c1));
Double_t c2=x[4]*x2 - x[2], r2=TMath::Sqrt((1.-c2)*(1.+c2));
y = x[0];
z = x[1];
Double_t dy = dx*(c1+c2)/(r1+r2);
Double_t dz = 0;
//
Double_t delta = x[4]*dx*(c1+c2)/(c1*r2 + c2*r1);
dz = x[3]*asinf(delta)/x[4];
y+=dy;
z+=dz;
return kTRUE;
}
Bool_t AliTPCtracker::GetProlongationLine(Double_t x1, Double_t x2, Double_t x[5], Double_t &y, Double_t &z) const
{//-----------------------------------------------------------------
// This function find straight line prolongation of a track to a reference plane x=x2.
//-----------------------------------------------------------------
if (TMath::Abs(x[2]) >= 0.999) return kFALSE;
Double_t c1=- x[2], dx2r = (x2-x1)/TMath::Sqrt((1.-c1)*(1.+c1));
y = x[0] + dx2r*c1;
z = x[1] + dx2r*x[3];
return kTRUE;
}
Int_t AliTPCtracker::LoadClusters (TTree *const tree)
{
// load clusters
//
fInput = tree;
return LoadClusters();
}
Int_t AliTPCtracker::LoadClusters(const TObjArray *arr)
{
//
// load clusters to the memory
AliTPCClustersRow *clrow = 0; //RS: why this new? new AliTPCClustersRow("AliTPCclusterMI");
Int_t lower = arr->LowerBound();
Int_t entries = arr->GetEntriesFast();
AliWarning("Sector Change ins not checked in LoadClusters(const TObjArray *arr)");
for (Int_t i=lower; i<entries; i++) {
clrow = (AliTPCClustersRow*) arr->At(i);
if(!clrow) continue;
TClonesArray* arr = clrow->GetArray();
if(!arr) continue;
int ncl = arr->GetEntriesFast();
if (ncl<1) continue;
//
Int_t sec,row;
fkParam->AdjustSectorRow(clrow->GetID(),sec,row);
for (Int_t icl=ncl; icl--;) {
Transform((AliTPCclusterMI*)(arr->At(icl)));
}
//
// RS: Check for possible sector change due to the distortions: TODO
//
AliTPCtrackerRow * tpcrow=0;
Int_t left=0;
if (sec<fkNIS*2){
tpcrow = &(fInnerSec[sec%fkNIS][row]);
left = sec/fkNIS;
}
else{
tpcrow = &(fOuterSec[(sec-fkNIS*2)%fkNOS][row]);
left = (sec-fkNIS*2)/fkNOS;
}
if (left ==0){
tpcrow->SetN1(ncl);
for (Int_t j=0;j<ncl;++j)
tpcrow->SetCluster1(j, *(AliTPCclusterMI*)(arr->At(j)));
}
if (left ==1){
tpcrow->SetN2(ncl);
for (Int_t j=0;j<ncl;++j)
tpcrow->SetCluster2(j, *(AliTPCclusterMI*)(arr->At(j)));
}
clrow->GetArray()->Clear(); // RS AliTPCclusterMI does not allocate memory
}
//
// delete clrow;
LoadOuterSectors();
LoadInnerSectors();
return 0;
}
Int_t AliTPCtracker::LoadClusters(const TClonesArray *arr)
{
//
// load clusters to the memory from one
// TClonesArray
//
// RS: Check for possible sector change due to the distortions: TODO
AliWarning("Sector Change ins not checked in LoadClusters(const TClonesArray *arr)");
//
//
AliTPCclusterMI *clust=0;
Int_t count[72][96] = { {0} , {0} };
// loop over clusters
for (Int_t icl=0; icl<arr->GetEntriesFast(); icl++) {
clust = (AliTPCclusterMI*)arr->At(icl);
if(!clust) continue;
//printf("cluster: det %d, row %d \n", clust->GetDetector(),clust->GetRow());
// transform clusters
Transform(clust);
// count clusters per pad row
count[clust->GetDetector()][clust->GetRow()]++;
}
// insert clusters to sectors
for (Int_t icl=0; icl<arr->GetEntriesFast(); icl++) {
clust = (AliTPCclusterMI*)arr->At(icl);
if(!clust) continue;
Int_t sec = clust->GetDetector();
Int_t row = clust->GetRow();
// filter overlapping pad rows needed by HLT
if(sec<fkNIS*2) { //IROCs
if(row == 30) continue;
}
else { // OROCs
if(row == 27 || row == 76) continue;
}
// Int_t left=0;
if (sec<fkNIS*2){
// left = sec/fkNIS;
fInnerSec[sec%fkNIS].InsertCluster(clust, count[sec][row], fkParam);
}
else{
// left = (sec-fkNIS*2)/fkNOS;
fOuterSec[(sec-fkNIS*2)%fkNOS].InsertCluster(clust, count[sec][row], fkParam);
}
}
// Load functions must be called behind LoadCluster(TClonesArray*)
// needed by HLT
//LoadOuterSectors();
//LoadInnerSectors();
return 0;
}
Int_t AliTPCtracker::LoadClusters()
{
//
// load clusters to the memory
static AliTPCClustersRow *clrow= new AliTPCClustersRow("AliTPCclusterMI");
//
// TTree * tree = fClustersArray.GetTree();
AliInfo("LoadClusters()\n");
fNClusters = 0;
TTree * tree = fInput;
TBranch * br = tree->GetBranch("Segment");
br->SetAddress(&clrow);
double cutZ2X = AliTPCReconstructor::GetPrimaryZ2XCut();
double cutZOutSector = AliTPCReconstructor::GetZOutSectorCut();
if (cutZOutSector>0 && AliTPCReconstructor::GetExtendedRoads())
cutZOutSector += AliTPCReconstructor::GetExtendedRoads()[1];
//
if (cutZ2X>0 || cutZOutSector>0) {
AliInfoF("Cut on cluster |Z/X| : %s, on cluster Z on wrong CE side: %s",
cutZ2X>0 ? Form("%.3f",cutZ2X) : "N/A",
cutZOutSector>0 ? Form("%.3f",cutZOutSector) : "N/A");
}
Int_t j=Int_t(tree->GetEntries());
for (Int_t i=0; i<j; i++) {
br->GetEntry(i);
//
TClonesArray* clArr = clrow->GetArray();
int nClus = clArr->GetEntriesFast();
Int_t sec,row;
fkParam->AdjustSectorRow(clrow->GetID(),sec,row);
for (Int_t icl=nClus; icl--;) Transform((AliTPCclusterMI*)(clArr->At(icl)));
//
AliTPCtrackerRow * tpcrow=0;
Int_t left=0;
if (sec<fkNIS*2){
tpcrow = &(fInnerSec[sec%fkNIS][row]);
left = sec/fkNIS;
}
else{
tpcrow = &(fOuterSec[(sec-fkNIS*2)%fkNOS][row]);
left = (sec-fkNIS*2)/fkNOS;
}
int nClusAdd = 0;
if (left ==0){ // A side
for (int k=0;k<nClus;k++) {
const AliTPCclusterMI& cl = *((AliTPCclusterMI*)clArr->At(k));
if (cutZOutSector>0 && cl.GetZ()<-cutZOutSector) continue;
if (cutZ2X>0 && cl.GetZ()/cl.GetX() > cutZ2X) continue;
tpcrow->SetCluster1(nClusAdd++, cl);
}
tpcrow->SetN1(nClusAdd);
}
if (left ==1){ // C side
for (int k=0;k<nClus;k++) {
const AliTPCclusterMI& cl = *((AliTPCclusterMI*)clArr->At(k));
if (cutZOutSector>0 && cl.GetZ()>cutZOutSector) continue;
if (cutZ2X>0 && cl.GetZ()/cl.GetX() < -cutZ2X) continue;
tpcrow->SetCluster2(nClusAdd++, cl);
}
tpcrow->SetN2(nClusAdd);
}
fNClusters += nClusAdd;
}
//
//clrow->Clear("C");
clrow->Clear(); // RS AliTPCclusterMI does not allocate memory
LoadOuterSectors();
LoadInnerSectors();
cout << " =================================================================================================================================== " << endl;
cout << " AliTPCReconstructor::GetRecoParam()->GetUseIonTailCorrection() = " << AliTPCReconstructor::GetRecoParam()->GetUseIonTailCorrection() << endl;
cout << " AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection() = " << AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection() << endl;
cout << " =================================================================================================================================== " << endl;
if (AliTPCReconstructor::GetRecoParam()->GetUseIonTailCorrection()) ApplyTailCancellation();
if (AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection()!=0.) CalculateXtalkCorrection();
if (AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrection()!=0.) ApplyXtalkCorrection();
//if (AliTPCReconstructor::GetRecoParam()->GetUseOulierClusterFilter()) FilterOutlierClusters();
/*
static int maxClus[18][2][kMaxRow]={0};
int maxAcc=0,nclEv=0, capacity=0;
for (int isec=0;isec<18;isec++) {
for (int irow=0;irow<kMaxRow;irow++) {
AliTPCtrackerRow * tpcrow = irow>62 ? &(fOuterSec[isec][irow-63]) : &(fInnerSec[isec][irow]);
maxClus[isec][0][irow] = TMath::Max(maxClus[isec][0][irow], tpcrow->GetN1());
maxClus[isec][1][irow] = TMath::Max(maxClus[isec][1][irow], tpcrow->GetN2());
maxAcc += maxClus[isec][0][irow]+maxClus[isec][1][irow];
nclEv += tpcrow->GetN();
capacity += tpcrow->GetClusters1()->Capacity();
capacity += tpcrow->GetClusters2()->Capacity();
}
}
printf("RS:AccumulatedSpace: %d for %d | pointers: %d\n",maxAcc,nclEv,capacity);
*/
return 0;
}
void AliTPCtracker::CalculateXtalkCorrection(){
//
// Calculate crosstalk estimate
//
TStopwatch sw;
sw.Start();
const Int_t nROCs = 72;
const Int_t nIterations=3; //
// 0.) reset crosstalk matrix
//
for (Int_t isector=0; isector<nROCs*4; isector++){ //set all ellemts of crosstalk matrix to 0
TMatrixD * crossTalkMatrix = (TMatrixD*)fCrossTalkSignalArray->At(isector);
if (crossTalkMatrix)(*crossTalkMatrix)*=0;
}
//
// 1.) Filling part -- loop over clusters
//
Double_t missingChargeFactor= AliTPCReconstructor::GetRecoParam()->GetCrosstalkCorrectionMissingCharge();
for (Int_t iter=0; iter<nIterations;iter++){
for (Int_t isector=0; isector<36; isector++){ // loop over sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
Int_t sec=0;
if (isector<18) sec=isector+18*iside;
if (isector>=18) sec=18+isector+18*iside;
for (Int_t row = 0;row<nrows;row++){ // loop over rows
//
//
Int_t wireSegmentID = fkParam->GetWireSegment(sec,row);
Float_t nPadsPerSegment = (Float_t)(fkParam->GetNPadsPerSegment(wireSegmentID));
TMatrixD &crossTalkSignal = *((TMatrixD*)fCrossTalkSignalArray->At(sec));
TMatrixD &crossTalkSignalCache = *((TMatrixD*)fCrossTalkSignalArray->At(sec+nROCs*2)); // this is the cache value of the crosstalk from previous iteration
TMatrixD &crossTalkSignalBelow = *((TMatrixD*)fCrossTalkSignalArray->At(sec+nROCs));
Int_t nCols=crossTalkSignal.GetNcols();
//
AliTPCtrackerRow& tpcrow = sector[row];
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
for (Int_t i=0;i<ncl;i++) { // loop over clusters
AliTPCclusterMI *clXtalk= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
Int_t timeBinXtalk = clXtalk->GetTimeBin();
Double_t rmsPadMin2=0.5*0.5+(fkParam->GetDiffT()*fkParam->GetDiffT())*(TMath::Abs((clXtalk->GetZ()-fkParam->GetZLength())))/(fkParam->GetPadPitchWidth(sec)*fkParam->GetPadPitchWidth(sec)); // minimal PRF width - 0.5 is the PRF in the pad units - we should et it from fkparam getters
Double_t rmsTimeMin2=1+(fkParam->GetDiffL()*fkParam->GetDiffL())*(TMath::Abs((clXtalk->GetZ()-fkParam->GetZLength())))/(fkParam->GetZWidth()*fkParam->GetZWidth()); // minimal PRF width - 1 is the TRF in the time bin units - we should et it from fkParam getters
Double_t rmsTime2 = clXtalk->GetSigmaZ2()/(fkParam->GetZWidth()*fkParam->GetZWidth());
Double_t rmsPad2 = clXtalk->GetSigmaY2()/(fkParam->GetPadPitchWidth(sec)*fkParam->GetPadPitchWidth(sec));
if (rmsPadMin2>rmsPad2){
rmsPad2=rmsPadMin2;
}
if (rmsTimeMin2>rmsTime2){
rmsTime2=rmsTimeMin2;
}
Double_t norm= 2.*TMath::Exp(-1.0/(2.*rmsTime2))+2.*TMath::Exp(-4.0/(2.*rmsTime2))+1.;
Double_t qTotXtalk = 0.;
Double_t qTotXtalkMissing = 0.;
for (Int_t itb=timeBinXtalk-2, idelta=-2; itb<=timeBinXtalk+2; itb++,idelta++) {
if (itb<0 || itb>=nCols) continue;
Double_t missingCharge=0;
Double_t trf= TMath::Exp(-idelta*idelta/(2.*rmsTime2));
if (missingChargeFactor>0) {
for (Int_t dpad=-2; dpad<=2; dpad++){
Double_t qPad = clXtalk->GetMax()*TMath::Exp(-dpad*dpad/(2.*rmsPad2))*trf;
if (TMath::Nint(qPad-crossTalkSignalCache[wireSegmentID][itb])<=fkParam->GetZeroSup()){
missingCharge+=qPad+crossTalkSignalCache[wireSegmentID][itb];
}else{
missingCharge+=crossTalkSignalCache[wireSegmentID][itb];
}
}
}
qTotXtalk = clXtalk->GetQ()*trf/norm+missingCharge*missingChargeFactor;
qTotXtalkMissing = missingCharge;
crossTalkSignal[wireSegmentID][itb]+= qTotXtalk/nPadsPerSegment;
crossTalkSignalBelow[wireSegmentID][itb]+= qTotXtalkMissing/nPadsPerSegment;
} // end of time bin loop
} // end of cluster loop
} // end of rows loop
} // end of side loop
} // end of sector loop
//
// copy crosstalk matrix to cached used for next itteration
//
//
// 2.) dump the crosstalk matrices to tree for further investigation
// a.) to estimate fluctuation of pedestal in indiviula wire segments
// b.) to check correlation between regions
// c.) to check relative conribution of signal below threshold to crosstalk
if (AliTPCReconstructor::StreamLevel()&kStreamCrosstalkMatrix) {
for (Int_t isector=0; isector<nROCs; isector++){ //set all ellemts of crosstalk matrix to 0
TMatrixD * crossTalkMatrix = (TMatrixD*)fCrossTalkSignalArray->At(isector);
TMatrixD * crossTalkMatrixBelow = (TMatrixD*)fCrossTalkSignalArray->At(isector+nROCs);
TMatrixD * crossTalkMatrixCache = (TMatrixD*)fCrossTalkSignalArray->At(isector+nROCs*2);
TVectorD vecAll(crossTalkMatrix->GetNrows());
TVectorD vecBelow(crossTalkMatrix->GetNrows());
TVectorD vecCache(crossTalkMatrixCache->GetNrows());
//
for (Int_t itime=0; itime<crossTalkMatrix->GetNcols(); itime++){
for (Int_t iwire=0; iwire<crossTalkMatrix->GetNrows(); iwire++){
vecAll[iwire]=(*crossTalkMatrix)(iwire,itime);
vecBelow[iwire]=(*crossTalkMatrixBelow)(iwire,itime);
vecCache[iwire]=(*crossTalkMatrixCache)(iwire,itime);
}
(*fDebugStreamer)<<"crosstalkMatrix"<<
"iter="<<iter<< //iteration
"sector="<<isector<< // sector
"itime="<<itime<< // time bin index
"vecAll.="<<&vecAll<< // crosstalk charge + charge below threshold
"vecCache.="<<&vecCache<< // crosstalk charge + charge below threshold
"vecBelow.="<<&vecBelow<< // crosstalk contribution from signal below threshold
"\n";
}
}
}
if (iter<nIterations-1) for (Int_t isector=0; isector<nROCs*2; isector++){ //set all ellemts of crosstalk matrix to 0
TMatrixD * crossTalkMatrix = (TMatrixD*)fCrossTalkSignalArray->At(isector);
TMatrixD * crossTalkMatrixCache = (TMatrixD*)fCrossTalkSignalArray->At(isector+nROCs*2);
if (crossTalkMatrix){
(*crossTalkMatrixCache)*=0;
(*crossTalkMatrixCache)+=(*crossTalkMatrix);
(*crossTalkMatrix)*=0;
}
}
}
sw.Stop();
AliInfoF("timing: %e/%e real/cpu",sw.RealTime(),sw.CpuTime());
//
}
void AliTPCtracker::FilterOutlierClusters(){
//
// filter outlier clusters
//
/*
1.)..... booking part
nSectors=72;
nTimeBins=fParam->Get....
TH2F hisTime("","", sector,0,sector, nTimeBins,0,nTimeBins);
TH2F hisPadRow("","", sector,0,sector, nPadRows,0,nPadRows);
2.) .... filling part
.... cluster loop { hisTime.Fill(cluster->GetDetector(),cluster->GetTimeBin()); }
3.) ...filtering part
sector loop { calculate median,mean80 and rms80 of the nclusters per time bin; calculate median,mean80 and rms80 of the nclusters per par row; .... export values to the debug streamers - to decide which threshold to be used... }
sector loop
{ disable clusters in time bins > mean+ n rms80+ offsetTime disable clusters in padRow > mean+ n rms80+ offsetPadRow // how to dislable clusters? - new bit to introduce }
//
4. Disabling clusters
*/
//
// 1.) booking part
//
// AliTPCcalibDB *db=AliTPCcalibDB::Instance();
Int_t nSectors=AliTPCROC::Instance()->GetNSectors();
Int_t nTimeBins= 1100; // *Bug here - we should get NTimeBins from ALTRO - Parameters not relyable
Int_t nPadRows=(AliTPCROC::Instance()->GetNRows(0) + AliTPCROC::Instance()->GetNRows(36));
// parameters for filtering
const Double_t nSigmaCut=9.; // should be in recoParam ?
const Double_t offsetTime=100; // should be in RecoParam ? -
const Double_t offsetPadRow=300; // should be in RecoParam ?
const Double_t offsetTimeAccept=8; // should be in RecoParam ? - obtained as mean +1 rms in high IR pp
TH2F hisTime("hisSectorTime","hisSectorTime", nSectors,0,nSectors, nTimeBins,0,nTimeBins);
TH2F hisPadRow("hisSectorRow","hisSectorRow", nSectors,0,nSectors, nPadRows,0,nPadRows);
//
// 2.) Filling part -- loop over clusters
//
for (Int_t isector=0; isector<36; isector++){ // loop over sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row];
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
for (Int_t i=0;i<ncl;i++) { // loop over clusters
AliTPCclusterMI *cluster= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
hisTime.Fill(cluster->GetDetector(),cluster->GetTimeBin());
hisPadRow.Fill(cluster->GetDetector(),cluster->GetRow());
}
}
}
}
//
// 3. Filtering part
//
TVectorD vecTime(nTimeBins);
TVectorD vecPadRow(nPadRows);
TVectorD vecMedianSectorTime(nSectors);
TVectorD vecRMSSectorTime(nSectors);
TVectorD vecMedianSectorTimeOut6(nSectors);
TVectorD vecMedianSectorTimeOut9(nSectors);//
TVectorD vecMedianSectorTimeOut(nSectors);//
TVectorD vecMedianSectorPadRow(nSectors);
TVectorD vecRMSSectorPadRow(nSectors);
TVectorD vecMedianSectorPadRowOut6(nSectors);
TVectorD vecMedianSectorPadRowOut9(nSectors);
TVectorD vecMedianSectorPadRowOut(nSectors);
TVectorD vecSectorOut6(nSectors);
TVectorD vecSectorOut9(nSectors);
TMatrixD matSectorCluster(nSectors,2);
//
// 3.a) median, rms calculations for hisTime
//
for (Int_t isec=0; isec<nSectors; isec++){
vecMedianSectorTimeOut6[isec]=0;
vecMedianSectorTimeOut9[isec]=0;
for (Int_t itime=0; itime<nTimeBins; itime++){
vecTime[itime]=hisTime.GetBinContent(isec+1, itime+1);
}
Double_t median= TMath::Mean(nTimeBins,vecTime.GetMatrixArray());
Double_t rms= TMath::RMS(nTimeBins,vecTime.GetMatrixArray());
vecMedianSectorTime[isec]=median;
vecRMSSectorTime[isec]=rms;
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) AliInfo(TString::Format("Sector TimeStat: %d\t%8.0f\t%8.0f",isec,median,rms).Data());
//
// declare outliers
for (Int_t itime=0; itime<nTimeBins; itime++){
Double_t entries= hisTime.GetBinContent(isec+1, itime+1);
if (entries>median+6.*rms+offsetTime) {
vecMedianSectorTimeOut6[isec]+=1;
}
if (entries>median+9.*rms+offsetTime) {
vecMedianSectorTimeOut9[isec]+=1;
}
}
}
//
// 3.b) median, rms calculations for hisPadRow
//
for (Int_t isec=0; isec<nSectors; isec++){
vecMedianSectorPadRowOut6[isec]=0;
vecMedianSectorPadRowOut9[isec]=0;
for (Int_t ipadrow=0; ipadrow<nPadRows; ipadrow++){
vecPadRow[ipadrow]=hisPadRow.GetBinContent(isec+1, ipadrow+1);
}
Int_t nPadRowsSector= AliTPCROC::Instance()->GetNRows(isec);
Double_t median= TMath::Mean(nPadRowsSector,vecPadRow.GetMatrixArray());
Double_t rms= TMath::RMS(nPadRowsSector,vecPadRow.GetMatrixArray());
vecMedianSectorPadRow[isec]=median;
vecRMSSectorPadRow[isec]=rms;
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) AliInfo(TString::Format("Sector PadRowStat: %d\t%8.0f\t%8.0f",isec,median,rms).Data());
//
// declare outliers
for (Int_t ipadrow=0; ipadrow<nPadRows; ipadrow++){
Double_t entries= hisPadRow.GetBinContent(isec+1, ipadrow+1);
if (entries>median+6.*rms+offsetPadRow) {
vecMedianSectorPadRowOut6[isec]+=1;
}
if (entries>median+9.*rms+offsetPadRow) {
vecMedianSectorPadRowOut9[isec]+=1;
}
}
}
//
// 3.c) filter outlier sectors
//
Double_t medianSectorTime = TMath::Median(nSectors, vecTime.GetMatrixArray());
Double_t mean69SectorTime, rms69SectorTime=0;
AliMathBase::EvaluateUni(nSectors, vecTime.GetMatrixArray(), mean69SectorTime,rms69SectorTime,69);
for (Int_t isec=0; isec<nSectors; isec++){
vecSectorOut6[isec]=0;
vecSectorOut9[isec]=0;
matSectorCluster(isec,0)=0;
matSectorCluster(isec,1)=0;
if (TMath::Abs(vecMedianSectorTime[isec])>(mean69SectorTime+6.*(rms69SectorTime+ offsetTimeAccept))) {
vecSectorOut6[isec]=1;
}
if (TMath::Abs(vecMedianSectorTime[isec])>(mean69SectorTime+9.*(rms69SectorTime+ offsetTimeAccept))){
vecSectorOut9[isec]=1;
}
}
// light version of export variable
Int_t filteredSector= vecSectorOut9.Sum(); // light version of export variable
Int_t filteredSectorTime= vecMedianSectorTimeOut9.Sum();
Int_t filteredSectorPadRow= vecMedianSectorPadRowOut9.Sum();
if (fEvent) if (fEvent->GetHeader()){
fEvent->GetHeader()->SetTPCNoiseFilterCounter(0,TMath::Min(filteredSector,255));
fEvent->GetHeader()->SetTPCNoiseFilterCounter(1,TMath::Min(filteredSectorTime,255));
fEvent->GetHeader()->SetTPCNoiseFilterCounter(2,TMath::Min(filteredSectorPadRow,255));
}
//
// 4. Disabling clusters in outlier layers
//
Int_t counterAll=0;
Int_t counterOut=0;
for (Int_t isector=0; isector<36; isector++){ // loop over sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row];
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
for (Int_t i=0;i<ncl;i++) { // loop over clusters
AliTPCclusterMI *cluster= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
Double_t medianTime=vecMedianSectorTime[cluster->GetDetector()];
Double_t medianPadRow=vecMedianSectorPadRow[cluster->GetDetector()];
Double_t rmsTime=vecRMSSectorTime[cluster->GetDetector()];
Double_t rmsPadRow=vecRMSSectorPadRow[cluster->GetDetector()];
Int_t entriesPadRow=hisPadRow.GetBinContent(cluster->GetDetector()+1, cluster->GetRow()+1);
Int_t entriesTime=hisTime.GetBinContent(cluster->GetDetector()+1, cluster->GetTimeBin()+1);
Bool_t isOut=kFALSE;
if (vecSectorOut9[cluster->GetDetector()]>0.5) {
isOut=kTRUE;
}
if (entriesTime>medianTime+nSigmaCut*rmsTime+offsetTime) {
isOut=kTRUE;
vecMedianSectorTimeOut[cluster->GetDetector()]++;
}
if (entriesPadRow>medianPadRow+nSigmaCut*rmsPadRow+offsetPadRow) {
isOut=kTRUE;
vecMedianSectorPadRowOut[cluster->GetDetector()]++;
}
counterAll++;
matSectorCluster(cluster->GetDetector(),0)+=1;
if (isOut){
cluster->Disable();
counterOut++;
matSectorCluster(cluster->GetDetector(),1)+=1;
}
}
}
}
}
for (Int_t isec=0; isec<nSectors; isec++){
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) AliInfo(TString::Format("Sector Stat: %d\t%8.0f\t%8.0f",isec,matSectorCluster(isec,1),matSectorCluster(isec,0)).Data());
}
//
// dump info to streamer - for later tuning of cuts
//
if ((AliTPCReconstructor::StreamLevel()&kStreamFilterClusterInfo)>0) { // stream TPC data ouliers filtering infomation
AliLog::Flush();
AliInfo(TString::Format("Cluster counter: (%d/%d) (Filtered/All)",counterOut,counterAll).Data());
for (Int_t iSec=0; iSec<nSectors; iSec++){
if (vecSectorOut9[iSec]>0 || matSectorCluster(iSec,1)>0) {
AliInfo(TString::Format("Filtered sector\t%d",iSec).Data());
Double_t vecMedTime =TMath::Median(72,vecMedianSectorTime.GetMatrixArray());
Double_t vecMedPadRow =TMath::Median(72,vecMedianSectorPadRow.GetMatrixArray());
Double_t vecMedCluster=(counterAll-counterOut)/72;
AliInfo(TString::Format("VecMedianSectorTime\t(%4.4f/%4.4f/%4.4f)", vecMedianSectorTimeOut[iSec],vecMedianSectorTime[iSec],vecMedTime).Data());
AliInfo(TString::Format("VecMedianSectorPadRow\t(%4.4f/%4.4f/%4.4f)", vecMedianSectorPadRowOut[iSec],vecMedianSectorPadRow[iSec],vecMedPadRow).Data());
AliInfo(TString::Format("MatSectorCluster\t(%4.4f/%4.4f/%4.4f)\n", matSectorCluster(iSec,1), matSectorCluster(iSec,0), vecMedCluster).Data());
AliLog::Flush();
}
}
AliLog::Flush();
Int_t eventNr = fEvent->GetEventNumberInFile();
(*fDebugStreamer)<<"filterClusterInfo"<<
// minimal set variables for the ESDevent
"eventNr="<<eventNr<<
"counterAll="<<counterAll<<
"counterOut="<<counterOut<<
"matSectotCluster.="<<&matSectorCluster<< //
//
"filteredSector="<<filteredSector<< // counter filtered sectors
"filteredSectorTime="<<filteredSectorTime<< // counter filtered time bins
"filteredSectorPadRow="<<filteredSectorPadRow<< // counter filtered pad-rows
// per sector outlier information
"medianSectorTime="<<medianSectorTime<< // median number of clusters per sector/timebin
"mean69SectorTime="<<mean69SectorTime<< // LTM statistic mean of clusters per sector/timebin
"rms69SectorTime="<<rms69SectorTime<< // LTM statistic RMS of clusters per sector/timebin
"vecSectorOut6.="<<&vecSectorOut6<< // flag array sector - 6 sigma +accept margin outlier
"vecSectorOut9.="<<&vecSectorOut9<< // flag array sector - 9 sigma + accept margin outlier
// per sector/timebin outlier detection
"vecMedianSectorTime.="<<&vecMedianSectorTime<<
"vecRMSSectorTime.="<<&vecRMSSectorTime<<
"vecMedianSectorTimeOut6.="<<&vecMedianSectorTimeOut6<<
"vecMedianSectorTimeOut9.="<<&vecMedianSectorTimeOut9<<
"vecMedianSectorTimeOut0.="<<&vecMedianSectorTimeOut<<
// per sector/pad-row outlier detection
"vecMedianSectorPadRow.="<<&vecMedianSectorPadRow<<
"vecRMSSectorPadRow.="<<&vecRMSSectorPadRow<<
"vecMedianSectorPadRowOut6.="<<&vecMedianSectorPadRowOut6<<
"vecMedianSectorPadRowOut9.="<<&vecMedianSectorPadRowOut9<<
"vecMedianSectorPadRowOut9.="<<&vecMedianSectorPadRowOut<<
"\n";
((*fDebugStreamer)<<"filterClusterInfo").GetTree()->Write();
fDebugStreamer->GetFile()->Flush();
}
}
void AliTPCtracker::UnloadClusters()
{
//
// unload clusters from the memory
//
Int_t nrows = fOuterSec->GetNRows();
for (Int_t sec = 0;sec<fkNOS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fOuterSec[sec%fkNOS][row]);
// if (tpcrow){
// if (tpcrow->fClusters1) delete []tpcrow->fClusters1;
// if (tpcrow->fClusters2) delete []tpcrow->fClusters2;
//}
tpcrow->ResetClusters();
}
//
nrows = fInnerSec->GetNRows();
for (Int_t sec = 0;sec<fkNIS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fInnerSec[sec%fkNIS][row]);
//if (tpcrow){
// if (tpcrow->fClusters1) delete []tpcrow->fClusters1;
//if (tpcrow->fClusters2) delete []tpcrow->fClusters2;
//}
tpcrow->ResetClusters();
}
fNClusters = 0;
return ;
}
void AliTPCtracker::FillClusterArray(TObjArray* array) const{
//
// Filling cluster to the array - For visualization purposes
//
Int_t nrows=0;
nrows = fOuterSec->GetNRows();
for (Int_t sec = 0;sec<fkNOS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fOuterSec[sec%fkNOS][row]);
if (!tpcrow) continue;
for (Int_t icl = 0;icl<tpcrow->GetN();icl++){
array->AddLast((TObject*)((*tpcrow)[icl]));
}
}
nrows = fInnerSec->GetNRows();
for (Int_t sec = 0;sec<fkNIS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fInnerSec[sec%fkNIS][row]);
if (!tpcrow) continue;
for (Int_t icl = 0;icl<tpcrow->GetN();icl++){
array->AddLast((TObject*)(*tpcrow)[icl]);
}
}
}
Int_t AliTPCtracker::Transform(AliTPCclusterMI * cluster){
//
// transformation
// RS: return sector in which the cluster appears accounting for eventual distortions
const double kMaxY2X = AliTPCTransform::GetMaxY2X(); // tg of sector angular span
const double kSinSect = TMath::Sin(TMath::Pi()/9), kCosSect = TMath::Cos(TMath::Pi()/9);
//
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform() ;
if (!transform) {
AliFatal("Tranformations not in calibDB");
return -1;
}
if (!transform->GetCurrentRecoParam()) transform->SetCurrentRecoParam((AliTPCRecoParam*)AliTPCReconstructor::GetRecoParam());
Double_t x[3]={static_cast<Double_t>(cluster->GetRow()),static_cast<Double_t>(cluster->GetPad()),static_cast<Double_t>(cluster->GetTimeBin())};
Int_t idROC = cluster->GetDetector();
transform->Transform(x,&idROC,0,1);
// if (cluster->GetDetector()%36>17){
// x[1]*=-1;
//}
//RS: Check if cluster goes outside of sector angular boundaries
float yMax = x[0]*kMaxY2X;
if (x[1]>yMax) {
cluster->SetSectorChanged(kTRUE);
AliTPCTransform::RotateToSectorUp(x,idROC);
}
else if (x[1]<-yMax) {
cluster->SetSectorChanged(kTRUE);
AliTPCTransform::RotateToSectorDown(x,idROC);
}
//
// in debug mode check the transformation
//
if ((AliTPCReconstructor::StreamLevel()&kStreamTransform)>0) {
Float_t gx[3];
cluster->GetGlobalXYZ(gx);
Int_t event = (fEvent==NULL)? 0: fEvent->GetEventNumberInFile();
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Transform"<< // needed for debugging of the cluster transformation, resp. used for later visualization
"event="<<event<<
"x0="<<x[0]<<
"x1="<<x[1]<<
"x2="<<x[2]<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"Cl.="<<cluster<<
"\n";
}
cluster->SetX(x[0]);
cluster->SetY(x[1]);
cluster->SetZ(x[2]);
// The old stuff:
//
//
//
//if (!fkParam->IsGeoRead()) fkParam->ReadGeoMatrices();
if (AliTPCReconstructor::GetRecoParam()->GetUseSectorAlignment() && (!calibDB->HasAlignmentOCDB())){
TGeoHMatrix *mat = fkParam->GetClusterMatrix(cluster->GetDetector());
//TGeoHMatrix mat;
Double_t pos[3]= {cluster->GetX(),cluster->GetY(),cluster->GetZ()};
Double_t posC[3]={cluster->GetX(),cluster->GetY(),cluster->GetZ()};
if (mat) mat->LocalToMaster(pos,posC);
else{
// chack Loading of Geo matrices from GeoManager - TEMPORARY FIX
}
cluster->SetX(posC[0]);
cluster->SetY(posC[1]);
cluster->SetZ(posC[2]);
}
return idROC;
}
void AliTPCtracker::ApplyXtalkCorrection(){
//
// ApplyXtalk correction
// Loop over all clusters
// add to each cluster signal corresponding to common Xtalk mode for given time bin at given wire segment
// cluster loop
TStopwatch sw;
sw.Start();
for (Int_t isector=0; isector<36; isector++){ //loop tracking sectors
for (Int_t iside=0; iside<2; iside++){ // loop over sides A/C
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
Int_t nrows = sector.GetNRows();
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row]; // row object
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
Int_t xSector=0; // sector number in the TPC convention 0-72
if (isector<18){ //if IROC
xSector=isector+(iside>0)*18;
}else{
xSector=isector+18; // isector -18 +36
if (iside>0) xSector+=18;
}
TMatrixD &crossTalkMatrix= *((TMatrixD*)fCrossTalkSignalArray->At(xSector));
Int_t wireSegmentID = fkParam->GetWireSegment(xSector,row);
for (Int_t i=0;i<ncl;i++) {
AliTPCclusterMI *cluster= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
Int_t iTimeBin=TMath::Nint(cluster->GetTimeBin());
Double_t xTalk= crossTalkMatrix[wireSegmentID][iTimeBin];
cluster->SetMax(cluster->GetMax()+xTalk);
const Double_t kDummy=4;
Double_t sumxTalk=xTalk*kDummy; // should be calculated via time response function
cluster->SetQ(cluster->GetQ()+sumxTalk);
if ((AliTPCReconstructor::StreamLevel()&kStreamXtalk)>0) { // flag: stream crosstalk correctio as applied to cluster
TTreeSRedirector &cstream = *fDebugStreamer;
if (gRandom->Rndm() > 0.){
cstream<<"Xtalk"<<
"isector=" << isector << // sector [0,36]
"iside=" << iside << // side A or C
"row=" << row << // padrow
"i=" << i << // index of the cluster
"xSector=" << xSector << // sector [0,72]
"wireSegmentID=" << wireSegmentID << // anode wire segment id [0,10]
"iTimeBin=" << iTimeBin << // timebin of the corrected cluster
"xTalk=" << xTalk << // Xtalk contribution added to Qmax
"sumxTalk=" << sumxTalk << // Xtalk contribution added to Qtot (roughly 3*Xtalk)
"cluster.=" << cluster << // corrected cluster object
"\n";
}
}// dump the results to the debug streamer if in debug mode
}
}
}
}
sw.Stop();
AliInfoF("timing: %e/%e real/cpu",sw.RealTime(),sw.CpuTime());
//
}
void AliTPCtracker::ApplyTailCancellation(){
//
// Correct the cluster charge for the ion tail effect
// The TimeResponse function accessed via AliTPCcalibDB (TPC/Calib/IonTail)
//
TStopwatch sw;
sw.Start();
// Retrieve
TObjArray *ionTailArr = (TObjArray*)AliTPCcalibDB::Instance()->GetIonTailArray();
if (!ionTailArr) {AliFatal("TPC - Missing IonTail OCDB object");}
TObject *rocFactorIROC = ionTailArr->FindObject("factorIROC");
TObject *rocFactorOROC = ionTailArr->FindObject("factorOROC");
Float_t factorIROC = (atof(rocFactorIROC->GetTitle()));
Float_t factorOROC = (atof(rocFactorOROC->GetTitle()));
// find the number of clusters for the whole TPC (nclALL)
Int_t nclALL=0;
for (Int_t isector=0; isector<36; isector++){
AliTPCtrackerSector §or= (isector<18)?fInnerSec[isector%18]:fOuterSec[isector%18];
nclALL += sector.GetNClInSector(0);
nclALL += sector.GetNClInSector(1);
}
//RS changed from heap allocation in the loop to stack allocation
TGraphErrors * graphRes[20];
Float_t indexAmpGraphs[20];
// AliTPCclusterMI* rowClusterArray[kMaxClusterPerRow]; // caches clusters for each row // RS avoid trashing the heap
// start looping over all clusters
for (Int_t iside=0; iside<2; iside++){ // loop over sides
//
//
for (Int_t secType=0; secType<2; secType++){ //loop over inner or outer sector
// cache experimantal tuning factor for the different chamber type
const Float_t ampfactor = (secType==0)?factorIROC:factorOROC;
std::cout << " ampfactor = " << ampfactor << std::endl;
//
for (Int_t sec = 0;sec<fkNOS;sec++){ //loop overs sectors
//
//
// Cache time response functions and their positons to COG of the cluster
// TGraphErrors ** graphRes = new TGraphErrors *[20]; // RS avoid heap allocations if stack can be used
// Float_t * indexAmpGraphs = new Float_t[20]; // RS Moved outside of the loop
memset(graphRes,0,20*sizeof(TGraphErrors*));
memset(indexAmpGraphs,0,20*sizeof(float));
//for (Int_t icache=0; icache<20; icache++) //RS
//{
// graphRes[icache] = NULL;
// indexAmpGraphs[icache] = 0;
// }
///////////////////////////// --> position fo sie loop
if (!AliTPCcalibDB::Instance()->GetTailcancelationGraphs(sec+36*secType+18*iside,graphRes,indexAmpGraphs))
{
continue;
}
AliTPCtrackerSector §or= (secType==0)?fInnerSec[sec]:fOuterSec[sec];
Int_t nrows = sector.GetNRows(); // number of rows
Int_t nclSector = sector.GetNClInSector(iside); // ncl per sector to be used for debugging
for (Int_t row = 0;row<nrows;row++){ // loop over rows
AliTPCtrackerRow& tpcrow = sector[row]; // row object
Int_t ncl = tpcrow.GetN1(); // number of clusters in the row
if (iside>0) ncl=tpcrow.GetN2();
// Order clusters in time for the proper correction of ion tail
Float_t qTotArray[ncl]; // arrays to be filled with modified Qtot and Qmax values in order to avoid float->int conversion
Float_t qMaxArray[ncl];
Int_t sortedClusterIndex[ncl];
Float_t sortedClusterTimeBin[ncl];
//TObjArray *rowClusterArray = new TObjArray(ncl); // cache clusters for each row // RS avoid trashing the heap
AliTPCclusterMI* rowClusterArray[ncl]; // caches clusters for each row // RS avoid trashing the heap
// memset(rowClusterArray,0,sizeof(AliTPCclusterMI*)*ncl); //.Clear();
//if (rowClusterArray.GetSize()<ncl) rowClusterArray.Expand(ncl);
for (Int_t i=0;i<ncl;i++)
{
qTotArray[i]=0;
qMaxArray[i]=0;
sortedClusterIndex[i]=i;
AliTPCclusterMI *rowcl= (iside>0)?(tpcrow.GetCluster2(i)):(tpcrow.GetCluster1(i));
rowClusterArray[i] = rowcl;
//if (rowcl) {
// rowClusterArray.AddAt(rowcl,i);
//} else {
// rowClusterArray.RemoveAt(i);
//}
// Fill the timebin info to the array in order to sort wrt tb
if (!rowcl) {
sortedClusterTimeBin[i]=0.0;
} else {
sortedClusterTimeBin[i] = rowcl->GetTimeBin();
}
}
TMath::Sort(ncl,sortedClusterTimeBin,sortedClusterIndex,kFALSE); // sort clusters in time
// Main cluster correction loops over clusters
for (Int_t icl0=0; icl0<ncl;icl0++){ // first loop over clusters
AliTPCclusterMI *cl0= rowClusterArray[sortedClusterIndex[icl0]]; //RS static_cast<AliTPCclusterMI*>(rowClusterArray.At(sortedClusterIndex[icl0]));
if (!cl0) continue;
Int_t nclPad=0;
//for (Int_t icl1=0; icl1<ncl;icl1++){ // second loop over clusters
// RS: time increases with index since sorted -> cl0->GetTimeBin()>cl1->GetTimeBin() means that icl0>icl1
for (Int_t icl1=0; icl1<icl0;icl1++){ // second loop over clusters
AliTPCclusterMI *cl1= rowClusterArray[sortedClusterIndex[icl1]];//RS static_cast<AliTPCclusterMI*>(rowClusterArray.At(sortedClusterIndex[icl1]));
if (!cl1) continue;
// RS no needed with proper loop organization
//if (cl0->GetTimeBin()<= cl1->GetTimeBin()) continue; // no contibution to the tail if later
int dpad = TMath::Abs(cl0->GetPad()-cl1->GetPad());
if (dpad>4) continue; // no contribution if far away in pad direction
// RS no point in iterating further with sorted clusters once large distance reached
if (cl0->GetTimeBin()-cl1->GetTimeBin()>600) continue; // out of the range of response function
// RS: what about dpad=4?
if (dpad<4) nclPad++; // count ncl for every pad for debugging
// Get the correction values for Qmax and Qtot and find total correction for a given cluster
Double_t ionTailMax=0.;
Double_t ionTailTotal=0.;
GetTailValue(ampfactor,ionTailMax,ionTailTotal,graphRes,indexAmpGraphs,cl0,cl1);
ionTailMax=TMath::Abs(ionTailMax);
ionTailTotal=TMath::Abs(ionTailTotal);
qTotArray[icl0]+=ionTailTotal;
qMaxArray[icl0]+=ionTailMax;
// Dump some info for debugging while clusters are being corrected
if ((AliTPCReconstructor::StreamLevel()&kStreamIonTail)>0) { // flag: stream ion tail correction as applied to cluster
TTreeSRedirector &cstream = *fDebugStreamer;
if (gRandom->Rndm() > 0.999){
cstream<<"IonTail"<<
"cl0.=" <<cl0 << // cluster 0 (to be corrected)
"cl1.=" <<cl1 << // cluster 1 (previous cluster)
"ionTailTotal=" <<ionTailTotal << // ion Tail from cluster 1 contribution to cluster0
"ionTailMax=" <<ionTailMax << // ion Tail from cluster 1 contribution to cluster0
"\n";
}
}// dump the results to the debug streamer if in debug mode
}//end of second loop over clusters
// Set corrected values of the corrected cluster
cl0->SetQ(TMath::Nint(Float_t(cl0->GetQ())+Float_t(qTotArray[icl0])));
cl0->SetMax(TMath::Nint(Float_t(cl0->GetMax())+qMaxArray[icl0]));
// Dump some info for debugging after clusters are corrected
if ((AliTPCReconstructor::StreamLevel()&kStreamIonTail)>0) {
TTreeSRedirector &cstream = *fDebugStreamer;
if (gRandom->Rndm() > 0.999){
cstream<<"IonTailCorrected"<<
"cl0.=" << cl0 << // cluster 0 with huge Qmax
"ionTailTotalPerCluster=" << qTotArray[icl0] <<
"ionTailMaxPerCluster=" << qMaxArray[icl0] <<
"nclALL=" << nclALL <<
"nclSector=" << nclSector <<
"nclRow=" << ncl <<
"nclPad=" << nclPad <<
"row=" << row <<
"sector=" << sec <<
"icl0=" << icl0 <<
"\n";
}
}// dump the results to the debug streamer if in debug mode
}//end of first loop over cluster
// delete rowClusterArray; // RS was moved to stack allocation
}//end of loop over rows
for (int i=0; i<20; i++) delete graphRes[i];
// delete [] graphRes; //RS was changed to stack allocation
// delete [] indexAmpGraphs;
}//end of loop over sectors
}//end of loop over IROC/OROC
}// end of side loop
sw.Stop();
AliInfoF("timing: %e/%e real/cpu",sw.RealTime(),sw.CpuTime());
//
}
//_____________________________________________________________________________
void AliTPCtracker::GetTailValue(Float_t ampfactor,Double_t &ionTailMax, Double_t &ionTailTotal,TGraphErrors **graphRes,Float_t *indexAmpGraphs,AliTPCclusterMI *cl0,AliTPCclusterMI *cl1){
//
// Function in order to calculate the amount of the correction to be added for a given cluster, return values are ionTailTaoltal and ionTailMax
// Parameters:
// cl0 - cluster to be modified
// cl1 - source cluster ion tail of this cluster will be added to the cl0 (accroding time and pad response function)
//
const Double_t kMinPRF = 0.5; // minimal PRF width
ionTailTotal = 0.; // correction value to be added to Qtot of cl0
ionTailMax = 0.; // correction value to be added to Qmax of cl0
Float_t qTot0 = cl0->GetQ(); // cl0 Qtot info
Float_t qTot1 = cl1->GetQ(); // cl1 Qtot info
Int_t sectorPad = cl1->GetDetector(); // sector number
Int_t padcl0 = TMath::Nint(cl0->GetPad()); // pad0
Int_t padcl1 = TMath::Nint(cl1->GetPad()); // pad1
Float_t padWidth = (sectorPad < 36)?0.4:0.6; // pad width in cm
const Int_t deltaTimebin = TMath::Nint(TMath::Abs(cl1->GetTimeBin()-cl0->GetTimeBin()))+12; //distance between pads of cl1 and cl0 increased by 12 bins
Double_t rmsPad1I = (cl1->GetSigmaY2()==0)?0.5/kMinPRF:(0.5*padWidth/TMath::Sqrt(cl1->GetSigmaY2()));
Double_t rmsPad0I = (cl0->GetSigmaY2()==0)?0.5/kMinPRF:(0.5*padWidth/TMath::Sqrt(cl0->GetSigmaY2()));
// RS avoid useless calculations
//Double_t sumAmp1=0.;
//for (Int_t idelta =-2; idelta<=2;idelta++){
// sumAmp1+=TMath::Exp(-idelta*idelta*rmsPad1I);
//}
// Double_t sumAmp0=0.;
//for (Int_t idelta =-2; idelta<=2;idelta++){
// sumAmp0+=TMath::Exp(-idelta*idelta*rmsPad0I));
//}
double tmp = TMath::Exp(-rmsPad1I);
double sumAmp1 = 1.+2.*tmp*(1.+tmp*tmp*tmp);
tmp = TMath::Exp(-rmsPad0I);
double sumAmp0 = 1.+2.*tmp*(1.+tmp*tmp*tmp);
// Apply the correction --> cl1 corrects cl0 (loop over cl1's pads and find which pads of cl0 are going to be corrected)
Int_t padScan=2; // +-2 pad-timebin window will be scanned
for (Int_t ipad1=padcl1-padScan; ipad1<=padcl1+padScan; ipad1++) {
//
//
Float_t deltaPad1 = TMath::Abs(cl1->GetPad()-(Float_t)ipad1);
Double_t amp1 = TMath::Exp(-(deltaPad1*deltaPad1)*rmsPad1I)/sumAmp1; // normalized pad response function
Float_t qTotPad1 = amp1*qTot1; // used as a factor to multipliy the response function
// find closest value of cl1 to COG (among the time response functions' amplitude array --> to select proper t.r.f.)
Int_t ampIndex = 0;
Float_t diffAmp = TMath::Abs(deltaPad1-indexAmpGraphs[0]);
for (Int_t j=0;j<20;j++) {
if (diffAmp > TMath::Abs(deltaPad1-indexAmpGraphs[j]) && indexAmpGraphs[j]!=0)
{
diffAmp = TMath::Abs(deltaPad1-indexAmpGraphs[j]);
ampIndex = j;
}
}
if (!graphRes[ampIndex]) continue;
if (deltaTimebin+2 >= graphRes[ampIndex]->GetN()) continue;
if (graphRes[ampIndex]->GetY()[deltaTimebin+2]>=0) continue;
for (Int_t ipad0=padcl0-padScan; ipad0<=padcl0+padScan; ipad0++) {
//
//
if (ipad1!=ipad0) continue; // check if ipad1 channel sees ipad0 channel, if not no correction to be applied.
Float_t deltaPad0 = TMath::Abs(cl0->GetPad()-(Float_t)ipad0);
Double_t amp0 = TMath::Exp(-(deltaPad0*deltaPad0)*rmsPad0I)/sumAmp0; // normalized pad resp function
Float_t qMaxPad0 = amp0*qTot0;
// Add 5 timebin range contribution around the max peak (-+2 tb window)
for (Int_t itb=deltaTimebin-2; itb<=deltaTimebin+2; itb++) {
if (itb<0) continue;
if (itb>=graphRes[ampIndex]->GetN()) continue;
// calculate contribution to qTot
Float_t tailCorr = TMath::Abs((qTotPad1*ampfactor)*(graphRes[ampIndex])->GetY()[itb]);
if (ipad1!=padcl0) {
ionTailTotal += TMath::Min(qMaxPad0,tailCorr); // for side pad
} else {
ionTailTotal += tailCorr; // for center pad
}
// calculate contribution to qMax
if (itb == deltaTimebin && ipad1 == padcl0) ionTailMax += tailCorr;
} // end of tb correction loop which is applied over 5 tb range
} // end of cl0 loop
} // end of cl1 loop
}
//_____________________________________________________________________________
Int_t AliTPCtracker::LoadOuterSectors() {
//-----------------------------------------------------------------
// This function fills outer TPC sectors with clusters.
//-----------------------------------------------------------------
Int_t nrows = fOuterSec->GetNRows();
UInt_t index=0;
for (Int_t sec = 0;sec<fkNOS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fOuterSec[sec%fkNOS][row]);
Int_t sec2 = sec+2*fkNIS;
//left
Int_t ncl = tpcrow->GetN1();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster1(ncl));
index=(((sec2<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//right
ncl = tpcrow->GetN2();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster2(ncl));
index=((((sec2+fkNOS)<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//
// write indexes for fast acces
//
for (Int_t i=510;i--;) tpcrow->SetFastCluster(i,-1);
for (Int_t i=0;i<tpcrow->GetN();i++){
Int_t zi = Int_t((*tpcrow)[i]->GetZ()+255.);
tpcrow->SetFastCluster(zi,i); // write index
}
Int_t last = 0;
for (Int_t i=0;i<510;i++){
if (tpcrow->GetFastCluster(i)<0)
tpcrow->SetFastCluster(i,last);
else
last = tpcrow->GetFastCluster(i);
}
}
fN=fkNOS;
fSectors=fOuterSec;
return 0;
}
//_____________________________________________________________________________
Int_t AliTPCtracker::LoadInnerSectors() {
//-----------------------------------------------------------------
// This function fills inner TPC sectors with clusters.
//-----------------------------------------------------------------
Int_t nrows = fInnerSec->GetNRows();
UInt_t index=0;
for (Int_t sec = 0;sec<fkNIS;sec++)
for (Int_t row = 0;row<nrows;row++){
AliTPCtrackerRow* tpcrow = &(fInnerSec[sec%fkNIS][row]);
//
//left
Int_t ncl = tpcrow->GetN1();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster1(ncl));
index=(((sec<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//right
ncl = tpcrow->GetN2();
while (ncl--) {
AliTPCclusterMI *c= (tpcrow->GetCluster2(ncl));
index=((((sec+fkNIS)<<8)+row)<<16)+ncl;
tpcrow->InsertCluster(c,index);
}
//
// write indexes for fast acces
//
for (Int_t i=0;i<510;i++)
tpcrow->SetFastCluster(i,-1);
for (Int_t i=0;i<tpcrow->GetN();i++){
Int_t zi = Int_t((*tpcrow)[i]->GetZ()+255.);
tpcrow->SetFastCluster(zi,i); // write index
}
Int_t last = 0;
for (Int_t i=0;i<510;i++){
if (tpcrow->GetFastCluster(i)<0)
tpcrow->SetFastCluster(i,last);
else
last = tpcrow->GetFastCluster(i);
}
}
fN=fkNIS;
fSectors=fInnerSec;
return 0;
}
//_________________________________________________________________________
AliTPCclusterMI *AliTPCtracker::GetClusterMI(Int_t index) const {
//--------------------------------------------------------------------
// Return pointer to a given cluster
//--------------------------------------------------------------------
if (index<0) return 0; // no cluster
Int_t sec=(index&0xff000000)>>24;
Int_t row=(index&0x00ff0000)>>16;
Int_t ncl=(index&0x00007fff)>>00;
const AliTPCtrackerRow * tpcrow=0;
TClonesArray * clrow =0;
if (sec<0 || sec>=fkNIS*4) {
AliWarning(Form("Wrong sector %d",sec));
return 0x0;
}
if (sec<fkNIS*2){
AliTPCtrackerSector& tracksec = fInnerSec[sec%fkNIS];
if (tracksec.GetNRows()<=row) return 0;
tpcrow = &(tracksec[row]);
if (tpcrow==0) return 0;
if (sec<fkNIS) {
if (tpcrow->GetN1()<=ncl) return 0;
clrow = tpcrow->GetClusters1();
}
else {
if (tpcrow->GetN2()<=ncl) return 0;
clrow = tpcrow->GetClusters2();
}
}
else {
AliTPCtrackerSector& tracksec = fOuterSec[(sec-fkNIS*2)%fkNOS];
if (tracksec.GetNRows()<=row) return 0;
tpcrow = &(tracksec[row]);
if (tpcrow==0) return 0;
if (sec-2*fkNIS<fkNOS) {
if (tpcrow->GetN1()<=ncl) return 0;
clrow = tpcrow->GetClusters1();
}
else {
if (tpcrow->GetN2()<=ncl) return 0;
clrow = tpcrow->GetClusters2();
}
}
return (AliTPCclusterMI*)clrow->At(ncl);
}
Int_t AliTPCtracker::FollowToNext(AliTPCseed& t, Int_t nr) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation to next pad row
//-----------------------------------------------------------------
//
const double kRoadY = 1., kRoadZ = 1.;
Double_t x= GetXrow(nr), ymax=GetMaxY(nr);
//
//
AliTPCclusterMI *cl=0;
Int_t tpcindex= t.GetClusterIndex2(nr);
//
// update current shape info every 5 pad-row
// if ( (nr%5==0) || t.GetNumberOfClusters()<2 || (t.fCurrentSigmaY2<0.0001) ){
GetShape(&t,nr);
//}
//
if (fIteration>0 && tpcindex>=-1){ //if we have already clusters
//
if (tpcindex==-1) return 0; //track in dead zone
if (tpcindex >= 0){ //
cl = t.GetClusterPointer(nr); // cluster might not be there during track finding, but is attached in refits
if (cl==0) cl = GetClusterMI(tpcindex);
t.SetCurrentClusterIndex1(tpcindex);
}
if (cl){
Int_t relativesector = ((tpcindex&0xff000000)>>24)%18; // if previously accepted cluster in different sector
Float_t angle = relativesector*fSectors->GetAlpha()+fSectors->GetAlphaShift();
//
if (angle<-TMath::Pi()) angle += 2*TMath::Pi();
if (angle>=TMath::Pi()) angle -= 2*TMath::Pi();
if (TMath::Abs(angle-t.GetAlpha())>0.001){
Double_t rotation = angle-t.GetAlpha();
t.SetRelativeSector(relativesector);
if (!t.Rotate(rotation)) {
t.SetClusterIndex(nr, t.GetClusterIndex(nr) | 0x8000);
return 0;
}
}
if (!t.PropagateTo(cl->GetX())) { // RS: go directly to cluster X
t.SetClusterIndex(nr, t.GetClusterIndex(nr) | 0x8000);
return 0;
}
//
t.SetCurrentCluster(cl);
t.SetRow(nr);
Int_t accept = AcceptCluster(&t,t.GetCurrentCluster());
if ((tpcindex&0x8000)==0) accept =0;
if (accept<3) {
//if founded cluster is acceptible
if (cl->IsUsed(11)) { // id cluster is shared inrease uncertainty
t.SetErrorY2(t.GetErrorY2()+0.03);
t.SetErrorZ2(t.GetErrorZ2()+0.03);
t.SetErrorY2(t.GetErrorY2()*3);
t.SetErrorZ2(t.GetErrorZ2()*3);
}
t.SetNFoundable(t.GetNFoundable()+1);
UpdateTrack(&t,accept);
return 1;
}
else { // Remove old cluster from track
t.SetClusterIndex(nr, -3);
//RS t.SetClusterPointer(nr, 0);
}
}
}
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()) return 0; // cut on angle
if (fIteration>1 && IsFindable(t)){
// not look for new cluster during refitting
t.SetNFoundable(t.GetNFoundable()+1);
return 0;
}
//
UInt_t index=0;
// if (TMath::Abs(t.GetSnp())>0.95 || TMath::Abs(x*t.GetC()-t.GetEta())>0.95) return 0;// patch 28 fev 06
//
if (fAccountDistortions && !DistortX(&t,x,nr)) {
if (fIteration==0) t.SetRemoval(10);
return 0;
}
if (!t.PropagateTo(x)) {
if (fIteration==0) t.SetRemoval(10);
return 0;
}
//
Double_t y = t.GetY();
ymax = x*AliTPCTransform::GetMaxY2X();
if (TMath::Abs(y)>ymax){
if (y > ymax) {
t.SetRelativeSector((t.GetRelativeSector()+1) % fN);
if (!t.Rotate(fSectors->GetAlpha()))
return 0;
} else if (y <-ymax) {
t.SetRelativeSector((t.GetRelativeSector()-1+fN) % fN);
if (!t.Rotate(-fSectors->GetAlpha()))
return 0;
}
x = GetXrow(nr);
if (fAccountDistortions && !DistortX(&t,x,nr)) {
if (fIteration==0) t.SetRemoval(10);
return 0;
}
if (!t.PropagateTo(x)) { //RS:? to check: here we may have back and forth prop. Use PropagateParamOnly?
if (fIteration==0) t.SetRemoval(10);
return 0;
}
y = t.GetY();
ymax = x*AliTPCTransform::GetMaxY2X();
}
//
Double_t z=t.GetZ();
//
if (!IsActive(t.GetRelativeSector(),nr)) { // RS:? How distortions affect this
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
//AliInfo(Form("A - Sector%d phi %f - alpha %f", t.fRelativeSector,y/x, t.GetAlpha()));
Bool_t isActive = IsActive(t.GetRelativeSector(),nr); //RS:? Why do we check this again?
Bool_t isActive2 = (nr>=fInnerSec->GetNRows()) ?
fOuterSec[t.GetRelativeSector()][nr-fInnerSec->GetNRows()].GetN()>0 :
fInnerSec[t.GetRelativeSector()][nr].GetN()>0;
if (!isActive || !isActive2) return 0;
const AliTPCtrackerRow &krow=GetRow(t.GetRelativeSector(),nr);
if ( (t.GetSigmaY2()<0) || t.GetSigmaZ2()<0) return 0;
//
// RS:? This check must be modified: with distortions the dead zone is not well defined
if (TMath::Abs(TMath::Abs(y)-ymax)<krow.GetDeadZone()){
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
else {
if (IsFindable(t))
// if (TMath::Abs(z)<(AliTPCReconstructor::GetCtgRange()*x+10) && TMath::Abs(z)<fkParam->GetZLength(0) && (TMath::Abs(t.GetSnp())<AliTPCReconstructor::GetMaxSnpTracker()))
t.SetNFoundable(t.GetNFoundable()+1);
else
return 0;
}
//calculate
if (krow) {
// cl = krow.FindNearest2(y+10.,z,roady,roadz,index);
cl = krow.FindNearest2(y,z,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,index);
if (cl) t.SetCurrentClusterIndex1(krow.GetIndex(index));
}
if (cl) {
t.SetCurrentCluster(cl);
t.SetRow(nr);
if (fIteration==2&&cl->IsUsed(10)) return 0;
Int_t accept = AcceptCluster(&t,t.GetCurrentCluster());
if (fIteration==2&&cl->IsUsed(11)) {
t.SetErrorY2(t.GetErrorY2()+0.03);
t.SetErrorZ2(t.GetErrorZ2()+0.03);
t.SetErrorY2(t.GetErrorY2()*3);
t.SetErrorZ2(t.GetErrorZ2()*3);
}
/*
if (t.fCurrentCluster->IsUsed(10)){
//
//
t.fNShared++;
if (t.fNShared>0.7*t.GetNumberOfClusters()) {
t.fRemoval =10;
return 0;
}
}
*/
if (accept<3) UpdateTrack(&t,accept);
} else {
if ( fIteration==0 && t.GetNFoundable()*0.5 > t.GetNumberOfClusters()) t.SetRemoval(10);
}
return 1;
}
//_________________________________________________________________________
Bool_t AliTPCtracker::GetTrackPoint(Int_t index, AliTrackPoint &p ) const
{
// Get track space point by index
// return false in case the cluster doesn't exist
AliTPCclusterMI *cl = GetClusterMI(index);
if (!cl) return kFALSE;
Int_t sector = (index&0xff000000)>>24;
// Int_t row = (index&0x00ff0000)>>16;
Float_t xyz[3];
// xyz[0] = fkParam->GetPadRowRadii(sector,row);
xyz[0] = cl->GetX();
xyz[1] = cl->GetY();
xyz[2] = cl->GetZ();
Float_t sin,cos;
fkParam->AdjustCosSin(sector,cos,sin);
Float_t x = cos*xyz[0]-sin*xyz[1];
Float_t y = cos*xyz[1]+sin*xyz[0];
Float_t cov[6];
Float_t sigmaY2 = 0.027*cl->GetSigmaY2();
if (sector < fkParam->GetNInnerSector()) sigmaY2 *= 2.07;
Float_t sigmaZ2 = 0.066*cl->GetSigmaZ2();
if (sector < fkParam->GetNInnerSector()) sigmaZ2 *= 1.77;
cov[0] = sin*sin*sigmaY2;
cov[1] = -sin*cos*sigmaY2;
cov[2] = 0.;
cov[3] = cos*cos*sigmaY2;
cov[4] = 0.;
cov[5] = sigmaZ2;
p.SetXYZ(x,y,xyz[2],cov);
AliGeomManager::ELayerID iLayer;
Int_t idet;
if (sector < fkParam->GetNInnerSector()) {
iLayer = AliGeomManager::kTPC1;
idet = sector;
}
else {
iLayer = AliGeomManager::kTPC2;
idet = sector - fkParam->GetNInnerSector();
}
UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,idet);
p.SetVolumeID(volid);
return kTRUE;
}
Int_t AliTPCtracker::UpdateClusters(AliTPCseed& t, Int_t nr) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation to next pad row
//-----------------------------------------------------------------
t.SetCurrentCluster(0);
t.SetCurrentClusterIndex1(-3);
Double_t xt=t.GetX();
Int_t row = GetRowNumber(xt)-1;
Double_t ymax= GetMaxY(nr);
if (row < nr) return 1; // don't prolongate if not information until now -
// if (TMath::Abs(t.GetSnp())>0.9 && t.GetNumberOfClusters()>40. && fIteration!=2) {
// t.fRemoval =10;
// return 0; // not prolongate strongly inclined tracks
// }
// if (TMath::Abs(t.GetSnp())>0.95) {
// t.fRemoval =10;
// return 0; // not prolongate strongly inclined tracks
// }// patch 28 fev 06
const double kRoadY = 1., kRoadZ = 1.;
Double_t x= GetXrow(nr);
Double_t y,z;
//t.PropagateTo(x+0.02);
//t.PropagateTo(x+0.01);
if (!t.PropagateTo(x)){
return 0;
}
//
y=t.GetY();
z=t.GetZ();
if (TMath::Abs(y)>ymax){
if (y > ymax) {
t.SetRelativeSector((t.GetRelativeSector()+1) % fN);
if (!t.Rotate(fSectors->GetAlpha()))
return 0;
} else if (y <-ymax) {
t.SetRelativeSector((t.GetRelativeSector()-1+fN) % fN);
if (!t.Rotate(-fSectors->GetAlpha()))
return 0;
}
// if (!t.PropagateTo(x)){
// return 0;
//}
return 1;
//y = t.GetY();
}
//
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()) return 0;
if (!IsActive(t.GetRelativeSector(),nr)) {
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
//AliInfo(Form("A - Sector%d phi %f - alpha %f", t.fRelativeSector,y/x, t.GetAlpha()));
AliTPCtrackerRow &krow=GetRow(t.GetRelativeSector(),nr);
if (TMath::Abs(TMath::Abs(y)-ymax)<krow.GetDeadZone()){
t.SetInDead(kTRUE);
t.SetClusterIndex2(nr,-1);
return 0;
}
else
{
// if (TMath::Abs(t.GetZ())<(AliTPCReconstructor::GetCtgRange()*t.GetX()+10) && (TMath::Abs(t.GetSnp())<AliTPCReconstructor::GetMaxSnpTracker()))
if (IsFindable(t)) t.SetNFoundable(t.GetNFoundable()+1);
else
return 0;
}
// update current
if ( (nr%2==0) || t.GetNumberOfClusters()<2){
// t.fCurrentSigmaY = GetSigmaY(&t);
//t.fCurrentSigmaZ = GetSigmaZ(&t);
GetShape(&t,nr);
}
AliTPCclusterMI *cl=0;
Int_t index=0;
//
Double_t roady = 1.;
Double_t roadz = 1.;
//
if (!cl){
index = t.GetClusterIndex2(nr);
if ( (index >= 0) && (index&0x8000)==0){
//RS cl = t.GetClusterPointer(nr);
//RS if ( (cl==0) && (index >= 0)) cl = GetClusterMI(index);
if ( index >= 0 ) cl = GetClusterMI(index);
t.SetCurrentClusterIndex1(index);
if (cl) {
t.SetCurrentCluster(cl);
return 1;
}
}
}
// if (index<0) return 0;
UInt_t uindex = TMath::Abs(index);
if (krow) {
//cl = krow.FindNearest2(y+10,z,roady,roadz,uindex);
cl = krow.FindNearest2(y,z,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,uindex);
}
if (cl) t.SetCurrentClusterIndex1(krow.GetIndex(uindex));
t.SetCurrentCluster(cl);
return 1;
}
Int_t AliTPCtracker::FollowToNextCluster(AliTPCseed & t, Int_t nr) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation to next pad row
//-----------------------------------------------------------------
//update error according neighborhoud
if (t.GetCurrentCluster()) {
t.SetRow(nr);
Int_t accept = AcceptCluster(&t,t.GetCurrentCluster());
if (t.GetCurrentCluster()->IsUsed(10)){
//
//
// t.fErrorZ2*=2;
// t.fErrorY2*=2;
t.SetNShared(t.GetNShared()+1);
if (t.GetNShared()>0.7*t.GetNumberOfClusters()) {
t.SetRemoval(10);
return 0;
}
}
if (fIteration>0) accept = 0;
if (accept<3) UpdateTrack(&t,accept);
} else {
if (fIteration==0){
if ( t.GetNumberOfClusters()>18 && ( (t.GetSigmaY2()+t.GetSigmaZ2())>0.16 + fExtraClErrYZ2 )) t.SetRemoval(10);
if ( t.GetNumberOfClusters()>18 && t.GetChi2()/t.GetNumberOfClusters()>6 ) t.SetRemoval(10);
if (( (t.GetNFoundable()*0.5 > t.GetNumberOfClusters()) || t.GetNoCluster()>15)) t.SetRemoval(10);
}
}
return 1;
}
//_____________________________________________________________________________
Int_t AliTPCtracker::FollowProlongation(AliTPCseed& t, Int_t rf, Int_t step, Bool_t fromSeeds) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation.
//-----------------------------------------------------------------
Double_t xt=t.GetX();
//
Double_t alpha=t.GetAlpha();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
//
t.SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
Int_t first = GetRowNumber(xt);
if (!fromSeeds)
first -= step;
if (first < 0)
first = 0;
for (Int_t nr= first; nr>=rf; nr-=step) {
// update kink info
if (t.GetKinkIndexes()[0]>0){
for (Int_t i=0;i<3;i++){
Int_t index = t.GetKinkIndexes()[i];
if (index==0) break;
if (index<0) continue;
//
AliKink * kink = (AliKink*)fEvent->GetKink(index-1);
if (!kink){
printf("PROBLEM\n");
}
else{
Int_t kinkrow = kink->GetTPCRow0()+2+Int_t(0.5/(0.05+kink->GetAngle(2)));
if (kinkrow==nr){
AliExternalTrackParam paramd(t);
kink->SetDaughter(paramd);
kink->SetStatus(2,5);
kink->Update();
}
}
}
}
if (nr==80) t.UpdateReference();
if (nr<fInnerSec->GetNRows())
fSectors = fInnerSec;
else
fSectors = fOuterSec;
if (FollowToNext(t,nr)==0)
if (!t.IsActive())
return 0;
}
return 1;
}
Int_t AliTPCtracker::FollowBackProlongation(AliTPCseed& t, Int_t rf, Bool_t fromSeeds) {
//-----------------------------------------------------------------
// This function tries to find a track prolongation.
//-----------------------------------------------------------------
//
Double_t xt=t.GetX();
Double_t alpha=t.GetAlpha();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
t.SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
Int_t first = t.GetFirstPoint();
Int_t ri = GetRowNumber(xt);
// if (!fromSeeds) ri += 1;
if (xt<0) ri += 1; // RS
if (first<ri) first = ri;
//
if (first<0) first=0;
for (Int_t nr=first; nr<=rf; nr++) {
// if ( (TMath::Abs(t.GetSnp())>0.95)) break;//patch 28 fev 06
if (t.GetKinkIndexes()[0]<0){
for (Int_t i=0;i<3;i++){
Int_t index = t.GetKinkIndexes()[i];
if (index==0) break;
if (index>0) continue;
index = TMath::Abs(index);
AliKink * kink = (AliKink*)fEvent->GetKink(index-1);
if (!kink){
printf("PROBLEM\n");
}
else{
Int_t kinkrow = kink->GetTPCRow0()-2-Int_t(0.5/(0.05+kink->GetAngle(2)));
if (kinkrow==nr){
AliExternalTrackParam paramm(t);
kink->SetMother(paramm);
kink->SetStatus(2,1);
kink->Update();
}
}
}
}
//
if (nr<fInnerSec->GetNRows())
fSectors = fInnerSec;
else
fSectors = fOuterSec;
FollowToNext(t,nr);
}
return 1;
}
Float_t AliTPCtracker::OverlapFactor(AliTPCseed * s1, AliTPCseed * s2, Int_t &sum1, Int_t & sum2)
{
// overlapping factor
//
sum1=0;
sum2=0;
Int_t sum=0;
//
Float_t dz2 =(s1->GetZ() - s2->GetZ());
dz2*=dz2;
Float_t dy2 =TMath::Abs((s1->GetY() - s2->GetY()));
dy2*=dy2;
Float_t distance = TMath::Sqrt(dz2+dy2);
if (distance>4.) return 0; // if there are far away - not overlap - to reduce combinatorics
// Int_t offset =0;
Int_t firstpoint = TMath::Min(s1->GetFirstPoint(),s2->GetFirstPoint());
Int_t lastpoint = TMath::Max(s1->GetLastPoint(),s2->GetLastPoint());
if (lastpoint>=kMaxRow)
lastpoint = kMaxRow-1;
if (firstpoint<0)
firstpoint = 0;
if (firstpoint>lastpoint) {
firstpoint =lastpoint;
// lastpoint = kMaxRow-1;
}
// for (Int_t i=firstpoint-1;i<lastpoint+1;i++){
// if (s1->GetClusterIndex2(i)>0) sum1++;
// if (s2->GetClusterIndex2(i)>0) sum2++;
// if (s1->GetClusterIndex2(i)==s2->GetClusterIndex2(i) && s1->GetClusterIndex2(i)>0) {
// sum++;
// }
// }
// RS: faster version + fix(?): clusterindex starts from 0
for (Int_t i=firstpoint-1;i<lastpoint+1;i++){
int ind1=s1->GetClusterIndex2(i), ind2=s2->GetClusterIndex2(i);
if (ind1>=0) sum1++;
if (ind2>=0) sum2++;
if (ind1==ind2 && ind1>=0) sum++;
}
if (sum<5) return 0;
Float_t summin = TMath::Min(sum1+1,sum2+1);
Float_t ratio = (sum+1)/Float_t(summin);
return ratio;
}
void AliTPCtracker::SignShared(AliTPCseed * s1, AliTPCseed * s2)
{
// shared clusters
//
Float_t thetaCut = 0.2;//+10.*TMath::Sqrt(s1->GetSigmaTglZ()+ s2->GetSigmaTglZ());
if (TMath::Abs(s1->GetTgl()-s2->GetTgl())>thetaCut) return;
Float_t minCl = TMath::Min(s1->GetNumberOfClusters(),s2->GetNumberOfClusters());
Int_t cutN0 = TMath::Max(5,TMath::Nint(0.1*minCl));
//
Int_t sumshared=0;
//
//Int_t firstpoint = TMath::Max(s1->GetFirstPoint(),s2->GetFirstPoint());
//Int_t lastpoint = TMath::Min(s1->GetLastPoint(),s2->GetLastPoint());
Int_t firstpoint = 0;
Int_t lastpoint = kMaxRow;
//
// if (firstpoint>=lastpoint-5) return;;
for (Int_t i=firstpoint;i<lastpoint;i++){
// if ( (s1->GetClusterIndex2(i)&0xFFFF8FFF)==(s2->GetClusterIndex2(i)&0xFFFF8FFF) && s1->GetClusterIndex2(i)>0) {
if ( (s1->GetClusterIndex2(i))==(s2->GetClusterIndex2(i)) && s1->GetClusterIndex2(i)>=0) {
sumshared++;
}
}
if (sumshared>cutN0){
// sign clusters
//
for (Int_t i=firstpoint;i<lastpoint;i++){
// if ( (s1->GetClusterIndex2(i)&0xFFFF8FFF)==(s2->GetClusterIndex2(i)&0xFFFF8FFF) && s1->GetClusterIndex2(i)>0) {
if ( (s1->GetClusterIndex2(i))==(s2->GetClusterIndex2(i)) && s1->GetClusterIndex2(i)>=0) {
const AliTPCTrackerPoints::Point *p1 = s1->GetTrackPoint(i);
const AliTPCTrackerPoints::Point *p2 = s2->GetTrackPoint(i);;
if (s1->IsActive()&&s2->IsActive()){
s1->SetShared(i);
s2->SetShared(i);
}
}
}
}
//
if (sumshared>cutN0){
for (Int_t i=0;i<4;i++){
if (s1->GetOverlapLabel(3*i)==0){
s1->SetOverlapLabel(3*i, s2->GetLabel());
s1->SetOverlapLabel(3*i+1,sumshared);
s1->SetOverlapLabel(3*i+2,s2->GetUniqueID());
break;
}
}
for (Int_t i=0;i<4;i++){
if (s2->GetOverlapLabel(3*i)==0){
s2->SetOverlapLabel(3*i, s1->GetLabel());
s2->SetOverlapLabel(3*i+1,sumshared);
s2->SetOverlapLabel(3*i+2,s1->GetUniqueID());
break;
}
}
}
}
void AliTPCtracker::SignShared(TObjArray * arr)
{
//
//sort trackss according sectors
//
for (Int_t i=0; i<arr->GetEntriesFast(); i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
//if (pt) RotateToLocal(pt);
pt->SetSort(0);
}
arr->UnSort();
arr->Sort(); // sorting according relative sectors
arr->Expand(arr->GetEntries());
//
//
Int_t nseed=arr->GetEntriesFast();
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
for (Int_t j=0;j<12;j++){
pt->SetOverlapLabel(j,0);
}
}
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
if (pt->GetRemoval()>10) continue;
for (Int_t j=i+1; j<nseed; j++){
AliTPCseed *pt2=(AliTPCseed*)arr->UncheckedAt(j);
if (TMath::Abs(pt->GetRelativeSector()-pt2->GetRelativeSector())>1) continue;
// if (pt2){
if (pt2->GetRemoval()<=10) {
//if ( TMath::Abs(pt->GetRelativeSector()-pt2->GetRelativeSector())>0) break;
SignShared(pt,pt2);
}
}
}
}
void AliTPCtracker::SortTracks(TObjArray * arr, Int_t mode) const
{
//
//sort tracks in array according mode criteria
Int_t nseed = arr->GetEntriesFast();
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
pt->SetSort(mode);
}
arr->UnSort();
arr->Sort();
}
void AliTPCtracker::RemoveUsed2(TObjArray * arr, Float_t factor1, Float_t factor2, Int_t minimal)
{
//
// Loop over all tracks and remove overlaped tracks (with lower quality)
// Algorithm:
// 1. Unsign clusters
// 2. Sort tracks according quality
// Quality is defined by the number of cluster between first and last points
//
// 3. Loop over tracks - decreasing quality order
// a.) remove - If the fraction of shared cluster less than factor (1- n or 2)
// b.) remove - If the minimal number of clusters less than minimal and not ITS
// c.) if track accepted - sign clusters
//
//Called in - AliTPCtracker::Clusters2Tracks()
// - AliTPCtracker::PropagateBack()
// - AliTPCtracker::RefitInward()
//
// Arguments:
// factor1 - factor for constrained
// factor2 - for non constrained tracks
// if (Float_t(shared+1)/Float_t(found+1)>factor) - DELETE
//
UnsignClusters();
//
Int_t nseed = arr->GetEntriesFast();
// Float_t quality = new Float_t[nseed];
// Int_t * indexes = new Int_t[nseed];
Float_t quality[nseed]; //RS Use stack allocations
Int_t indexes[nseed];
Int_t good =0;
//
//
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt){
quality[i]=-1;
continue;
}
pt->UpdatePoints(); //select first last max dens points
Float_t * points = pt->GetPoints();
if (points[3]<0.8) quality[i] =-1;
quality[i] = (points[2]-points[0])+pt->GetNumberOfClusters();
//prefer high momenta tracks if overlaps
quality[i] *= TMath::Sqrt(TMath::Abs(pt->Pt())+0.5);
}
TMath::Sort(nseed,quality,indexes);
//
//
for (Int_t itrack=0; itrack<nseed; itrack++) {
Int_t trackindex = indexes[itrack];
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(trackindex);
if (!pt) continue;
//
if (quality[trackindex]<0){
MarkSeedFree( arr->RemoveAt(trackindex) );
continue;
}
//
//
Int_t first = Int_t(pt->GetPoints()[0]);
Int_t last = Int_t(pt->GetPoints()[2]);
Double_t factor = (pt->GetBConstrain()) ? factor1: factor2;
//
Int_t found,foundable,shared;
GetSeedClusterStatistic(pt, first,last, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
//RS pt->GetClusterStatistic(first,last, found, foundable,shared,kFALSE); // better to get statistic in "high-dens" region do't use full track as in line bellow
//MI pt->GetClusterStatistic(0,kMaxRow, found, foundable,shared,kFALSE);
Bool_t itsgold =kFALSE;
if (pt->GetESD()){
Int_t dummy[12];
if (pt->GetESD()->GetITSclusters(dummy)>4) itsgold= kTRUE;
}
if (!itsgold){
//
if (Float_t(shared+1)/Float_t(found+1)>factor){
if (pt->GetKinkIndexes()[0]!=0) continue; //don't remove tracks - part of the kinks
if( (AliTPCReconstructor::StreamLevel()&kStreamRemoveUsed)>0){ // flag:stream information about TPC tracks which were descarded (double track removal)
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"RemoveUsed"<<
"iter="<<fIteration<<
"pt.="<<pt<<
"\n";
}
MarkSeedFree( arr->RemoveAt(trackindex) );
continue;
}
if (pt->GetNumberOfClusters()<50&&(found-0.5*shared)<minimal){ //remove short tracks
if (pt->GetKinkIndexes()[0]!=0) continue; //don't remove tracks - part of the kinks
if( (AliTPCReconstructor::StreamLevel()&kStreamRemoveShort)>0){ // flag:stream information about TPC tracks which were discarded (short track removal)
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"RemoveShort"<<
"iter="<<fIteration<<
"pt.="<<pt<<
"\n";
}
MarkSeedFree( arr->RemoveAt(trackindex) );
continue;
}
}
good++;
//if (sharedfactor>0.4) continue;
if (pt->GetKinkIndexes()[0]>0) continue;
//Remove tracks with undefined properties - seems
if (pt->GetSigmaY2()<kAlmost0) continue; // ? what is the origin ?
//
for (Int_t i=first; i<last; i++) {
Int_t index=pt->GetClusterIndex2(i);
// if (index<0 || index&0x8000 ) continue;
if (index<0 || index&0x8000 ) continue;
AliTPCclusterMI *c= GetClusterMI(index); //RS pt->GetClusterPointer(i);
if (!c) continue;
c->Use(10);
}
}
fNtracks = good;
if (fDebug>0){
Info("RemoveUsed","\n*****\nNumber of good tracks after shared removal\t%d\n",fNtracks);
}
// delete []quality; // RS was moved to stack allocation
// delete []indexes;
}
void AliTPCtracker::DumpClusters(Int_t iter, TObjArray *trackArray)
{
//
// Dump clusters after reco
// signed and unsigned cluster can be visualized
// 1. Unsign all cluster
// 2. Sign all used clusters
// 3. Dump clusters
UnsignClusters();
Int_t nseed = trackArray->GetEntries();
for (Int_t i=0; i<nseed; i++){
AliTPCseed *pt=(AliTPCseed*)trackArray->UncheckedAt(i);
if (!pt) {
continue;
}
Bool_t isKink=pt->GetKinkIndex(0)!=0;
for (Int_t j=0; j<kMaxRow; ++j) {
Int_t index=pt->GetClusterIndex2(j);
if (index<0) continue;
AliTPCclusterMI *c= GetClusterMI(index); //RS pt->GetClusterPointer(j);
if (!c) continue;
if (isKink) c->Use(100); // kink
c->Use(10); // by default usage 10
}
}
//
Int_t eventNr = fEvent->GetEventNumberInFile();
for (Int_t sec=0;sec<fkNIS;sec++){
for (Int_t row=0;row<fInnerSec->GetNRows();row++){
TClonesArray *cla = fInnerSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN1();icl++){
AliTPCclusterMI* cl = (AliTPCclusterMI*)cla->At(icl);
Float_t gx[3]; cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
cla = fInnerSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN2();icl++){
AliTPCclusterMI* cl = (AliTPCclusterMI*)cla->At(icl);
Float_t gx[3]; cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
}
}
for (Int_t sec=0;sec<fkNOS;sec++){
for (Int_t row=0;row<fOuterSec->GetNRows();row++){
TClonesArray *cla = fOuterSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN1();icl++){
Float_t gx[3];
AliTPCclusterMI* cl = (AliTPCclusterMI*) cla->At(icl);
cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
cla = fOuterSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN2();icl++){
Float_t gx[3];
AliTPCclusterMI* cl = (AliTPCclusterMI*) cla->At(icl);
cl->GetGlobalXYZ(gx);
(*fDebugStreamer)<<"clDump"<<
"eventNr="<<eventNr<<
"iter="<<iter<<
"cl.="<<cl<<
"gx0="<<gx[0]<<
"gx1="<<gx[1]<<
"gx2="<<gx[2]<<
"\n";
}
}
}
}
void AliTPCtracker::UnsignClusters()
{
//
// loop over all clusters and unsign them
//
for (Int_t sec=0;sec<fkNIS;sec++){
for (Int_t row=0;row<fInnerSec->GetNRows();row++){
TClonesArray *cla = fInnerSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN1();icl++)
// if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
cla = fInnerSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fInnerSec[sec][row].GetN2();icl++)
//if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
}
}
for (Int_t sec=0;sec<fkNOS;sec++){
for (Int_t row=0;row<fOuterSec->GetNRows();row++){
TClonesArray *cla = fOuterSec[sec][row].GetClusters1();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN1();icl++)
//if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
cla = fOuterSec[sec][row].GetClusters2();
for (Int_t icl =0;icl< fOuterSec[sec][row].GetN2();icl++)
//if (cl[icl].IsUsed(10))
((AliTPCclusterMI*) cla->At(icl))->Use(-1);
}
}
}
void AliTPCtracker::SignClusters(const TObjArray * arr, Float_t fnumber, Float_t fdensity)
{
//
//sign clusters to be "used"
//
// snumber and sdensity sign number of sigmas - bellow mean value to be accepted
// loop over "primaries"
Float_t sumdens=0;
Float_t sumdens2=0;
Float_t sumn =0;
Float_t sumn2 =0;
Float_t sumchi =0;
Float_t sumchi2 =0;
Float_t sum =0;
TStopwatch timer;
timer.Start();
Int_t nseed = arr->GetEntriesFast();
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
if (!(pt->IsActive())) continue;
Float_t dens = pt->GetNumberOfClusters()/Float_t(pt->GetNFoundable());
if ( (dens>0.7) && (pt->GetNumberOfClusters()>70)){
sumdens += dens;
sumdens2+= dens*dens;
sumn += pt->GetNumberOfClusters();
sumn2 += pt->GetNumberOfClusters()*pt->GetNumberOfClusters();
Float_t chi2 = pt->GetChi2()/pt->GetNumberOfClusters();
if (chi2>5) chi2=5;
sumchi +=chi2;
sumchi2 +=chi2*chi2;
sum++;
}
}
Float_t mdensity = 0.9;
Float_t meann = 130;
Float_t meanchi = 1;
Float_t sdensity = 0.1;
Float_t smeann = 10;
Float_t smeanchi =0.4;
if (sum>20){
mdensity = sumdens/sum;
meann = sumn/sum;
meanchi = sumchi/sum;
//
sdensity = sumdens2/sum-mdensity*mdensity;
if (sdensity >= 0)
sdensity = TMath::Sqrt(sdensity);
else
sdensity = 0.1;
//
smeann = sumn2/sum-meann*meann;
if (smeann >= 0)
smeann = TMath::Sqrt(smeann);
else
smeann = 10;
//
smeanchi = sumchi2/sum - meanchi*meanchi;
if (smeanchi >= 0)
smeanchi = TMath::Sqrt(smeanchi);
else
smeanchi = 0.4;
}
//REMOVE SHORT DELTAS or tracks going out of sensitive volume of TPC
//
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
if (pt->GetBSigned()) continue;
if (pt->GetBConstrain()) continue;
//if (!(pt->IsActive())) continue;
/*
Int_t found,foundable,shared;
pt->GetClusterStatistic(0,kMaxRow,found, foundable,shared);
if (shared/float(found)>0.3) {
if (shared/float(found)>0.9 ){
//MarkSeedFree( arr->RemoveAt(i) );
}
continue;
}
*/
Bool_t isok =kFALSE;
if ( (pt->GetNShared()/pt->GetNumberOfClusters()<0.5) &&pt->GetNumberOfClusters()>60)
isok = kTRUE;
if ((TMath::Abs(1/pt->GetC())<100.) && (pt->GetNShared()/pt->GetNumberOfClusters()<0.7))
isok =kTRUE;
if (TMath::Abs(pt->GetZ()/pt->GetX())>1.1)
isok =kTRUE;
if ( (TMath::Abs(pt->GetSnp()>0.7) && pt->GetD(0,0)>60.))
isok =kTRUE;
if (isok)
for (Int_t j=0; j<kMaxRow; ++j) {
Int_t index=pt->GetClusterIndex2(j);
if (index<0) continue;
AliTPCclusterMI *c= GetClusterMI(index);//pt->GetClusterPointer(j);
if (!c) continue;
//if (!(c->IsUsed(10))) c->Use();
c->Use(10);
}
}
//
Double_t maxchi = meanchi+2.*smeanchi;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) {
continue;
}
//if (!(pt->IsActive())) continue;
if (pt->GetBSigned()) continue;
Double_t chi = pt->GetChi2()/pt->GetNumberOfClusters();
if (chi>maxchi) continue;
Float_t bfactor=1;
Float_t dens = pt->GetNumberOfClusters()/Float_t(pt->GetNFoundable());
//sign only tracks with enoug big density at the beginning
if ((pt->GetDensityFirst(40)<0.75) && pt->GetNumberOfClusters()<meann) continue;
Double_t mindens = TMath::Max(double(mdensity-sdensity*fdensity*bfactor),0.65);
Double_t minn = TMath::Max(Int_t(meann-fnumber*smeann*bfactor),50);
// if (pt->fBConstrain) mindens = TMath::Max(mdensity-sdensity*fdensity*bfactor,0.65);
if ( (pt->GetRemoval()==10) && (pt->GetSnp()>0.8)&&(dens>mindens))
minn=0;
if ((dens>mindens && pt->GetNumberOfClusters()>minn) && chi<maxchi ){
//Int_t noc=pt->GetNumberOfClusters();
pt->SetBSigned(kTRUE);
for (Int_t j=0; j<kMaxRow; ++j) {
Int_t index=pt->GetClusterIndex2(j);
if (index<0) continue;
AliTPCclusterMI *c= GetClusterMI(index); //RS pt->GetClusterPointer(j);
if (!c) continue;
// if (!(c->IsUsed(10))) c->Use();
c->Use(10);
}
}
}
// gLastCheck = nseed;
// arr->Compress();
if (fDebug>0){
timer.Print();
}
}
Int_t AliTPCtracker::RefitInward(AliESDEvent *event)
{
//
// back propagation of ESD tracks
//
//return 0;
if (!event) return 0;
fEvent = event;
fEventHLT = 0;
// extract correction object for multiplicity dependence of dEdx
TObjArray * gainCalibArray = AliTPCcalibDB::Instance()->GetTimeGainSplinesRun(event->GetRunNumber());
AliTPCTransform *transform = AliTPCcalibDB::Instance()->GetTransform() ;
if (!transform) {
AliFatal("Tranformations not in RefitInward");
return 0;
}
transform->SetCurrentRecoParam((AliTPCRecoParam*)AliTPCReconstructor::GetRecoParam());
const AliTPCRecoParam * recoParam = AliTPCcalibDB::Instance()->GetTransform()->GetCurrentRecoParam();
Int_t nContribut = event->GetNumberOfTracks();
TGraphErrors * graphMultDependenceDeDx = 0x0;
if (recoParam && recoParam->GetUseMultiplicityCorrectionDedx() && gainCalibArray) {
if (recoParam->GetUseTotCharge()) {
graphMultDependenceDeDx = (TGraphErrors *) gainCalibArray->FindObject("TGRAPHERRORS_MEANQTOT_MULTIPLICITYDEPENDENCE_BEAM_ALL");
} else {
graphMultDependenceDeDx = (TGraphErrors *) gainCalibArray->FindObject("TGRAPHERRORS_MEANQMAX_MULTIPLICITYDEPENDENCE_BEAM_ALL");
}
}
//
ReadSeeds(event,2);
fIteration=2;
//PrepareForProlongation(fSeeds,1);
PropagateForward2(fSeeds);
RemoveUsed2(fSeeds,0.4,0.4,20);
Int_t entriesSeed=fSeeds->GetEntries();
TObjArray arraySeed(entriesSeed);
for (Int_t i=0;i<entriesSeed;i++) {
arraySeed.AddAt(fSeeds->At(i),i);
}
SignShared(&arraySeed);
// FindCurling(fSeeds, event,2); // find multi found tracks
FindSplitted(fSeeds, event,2); // find multi found tracks
if ((AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC)>0) FindMultiMC(fSeeds, fEvent,2); // flag: stream MC infomation about the multiple find track (ONLY for MC data)
Int_t ntracks=0;
Int_t nseed = fSeeds->GetEntriesFast();
//
// RS: the cluster pointers are not permanently attached to the seed during the tracking, need to attach temporarily
AliTPCclusterMI* seedClusters[kMaxRow];
int seedsInFriends = 0;
int seedsInFriendsNorm = event->GetNTPCFriend2Store();
if (seedsInFriendsNorm>nseed) seedsInFriendsNorm = nseed; // all friends are stored
//
fClPointersPoolPtr = fClPointersPool;
//
for (Int_t i=0;i<nseed;i++) {
AliTPCseed * seed = (AliTPCseed*) fSeeds->UncheckedAt(i);
if (!seed) continue;
if (seed->GetKinkIndex(0)>0) UpdateKinkQualityD(seed); // update quality informations for kinks
AliESDtrack *esd=event->GetTrack(i);
//
//RS: if needed, attach temporary cluster array
const AliTPCclusterMI** seedClustersSave = seed->GetClusters();
if (!seedClustersSave) { //RS: temporary attach clusters
for (int ir=kMaxRow;ir--;) {
int idx = seed->GetClusterIndex2(ir);
seedClusters[ir] = idx<0 ? 0 : GetClusterMI(idx);
}
seed->SetClustersArrayTMP(seedClusters);
}
//
//
if (seed->GetNumberOfClusters()<60 && seed->GetNumberOfClusters()<(esd->GetTPCclusters(0) -5)*0.8) {
AliExternalTrackParam paramIn;
AliExternalTrackParam paramOut;
//
Int_t ncl = seed->RefitTrack(seed,¶mIn,¶mOut);
//
if ((AliTPCReconstructor::StreamLevel() & kStreamRecoverIn)>0) { // flag: stream track information for track failing in RefitInward function and recovered back
(*fDebugStreamer)<<"RecoverIn"<<
"seed.="<<seed<<
"esd.="<<esd<<
"pin.="<<¶mIn<<
"pout.="<<¶mOut<<
"ncl="<<ncl<<
"\n";
}
if (ncl>15) {
seed->Set(paramIn.GetX(),paramIn.GetAlpha(),paramIn.GetParameter(),paramIn.GetCovariance());
seed->SetNumberOfClusters(ncl);
}
}
seed->PropagateTo(fkParam->GetInnerRadiusLow());
seed->UpdatePoints();
AddCovariance(seed);
MakeESDBitmaps(seed, esd);
seed->CookdEdx(0.02,0.6);
CookLabel(seed,0.1); //For comparison only
//
if (((AliTPCReconstructor::StreamLevel()&kStreamRefitInward)>0) && seed!=0) {
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"RefitInward"<< // flag: stream track information in RefitInward function (after tracking Iteration 2)
"Esd.="<<esd<<
"Track.="<<seed<<
"\n";
}
if (seed->GetNumberOfClusters()>15) {
esd->UpdateTrackParams(seed,AliESDtrack::kTPCrefit);
esd->SetTPCPoints(seed->GetPoints());
esd->SetTPCPointsF(seed->GetNFoundable());
Int_t ndedx = seed->GetNCDEDX(0);
Float_t sdedx = seed->GetSDEDX(0);
Float_t dedx = seed->GetdEdx();
// apply mutliplicity dependent dEdx correction if available
if (graphMultDependenceDeDx) {
Double_t corrGain = AliTPCcalibDButil::EvalGraphConst(graphMultDependenceDeDx, nContribut);
dedx += (1 - corrGain)*50.; // MIP is normalized to 50
}
esd->SetTPCsignal(dedx, sdedx, ndedx);
//
// fill new dEdx information
//
Double32_t signal[4];
Double32_t signalMax[4];
Char_t ncl[3];
Char_t nrows[3];
//
for(Int_t iarr=0;iarr<3;iarr++) {
signal[iarr] = seed->GetDEDXregion(iarr+1);
signalMax[iarr] = seed->GetDEDXregion(iarr+5);
ncl[iarr] = seed->GetNCDEDX(iarr+1);
nrows[iarr] = seed->GetNCDEDXInclThres(iarr+1);
}
signal[3] = seed->GetDEDXregion(4);
signalMax[3] = seed->GetDEDXregion(8);
//
AliTPCdEdxInfo * infoTpcPid = new AliTPCdEdxInfo();
infoTpcPid->SetTPCSignalRegionInfo(signal, ncl, nrows);
infoTpcPid->SetTPCSignalsQmax(signalMax);
esd->SetTPCdEdxInfo(infoTpcPid);
//
// add seed to the esd track in Calib level
//
Bool_t storeFriend = seedsInFriendsNorm>0 && (!esd->GetFriendNotStored())
&& seedsInFriends<(kMaxFriendTracks-1)
&& gRandom->Rndm()<(kMaxFriendTracks)/Float_t(seedsInFriendsNorm);
// if (AliTPCReconstructor::StreamLevel()>0 &&storeFriend){
//AliInfoF("Store: %d Stored %d / %d FrOff: %d",storeFriend,seedsInFriends,seedsInFriendsNorm,esd->GetFriendNotStored());
if (storeFriend){ // RS: seed is needed for calibration, regardless on streamlevel
seedsInFriends++;
// RS: this is the only place where the seed is created not in the pool,
// since it should belong to ESDevent
//AliTPCseed * seedCopy = new AliTPCseed(*seed, kTRUE);
//esd->AddCalibObject(seedCopy);
//
//RS to avoid the cloning the seeds and clusters we will declare the seed to own its
// clusters and reattach the clusters pointers from the pool, so they are saved in the friends
seed->SetClusterOwner(kTRUE);
memcpy(fClPointersPoolPtr,seedClusters,kMaxRow*sizeof(AliTPCclusterMI*));
seed->SetClustersArrayTMP(fClPointersPoolPtr);
esd->AddCalibObject(seed);
fClPointersPoolPtr += kMaxRow;
}
else seed->SetClustersArrayTMP((AliTPCclusterMI**)seedClustersSave);
//
ntracks++;
}
else{
//printf("problem\n");
}
//
//RS if seed does not own clusters, then it was not added to friends: detach temporary clusters !!!
if (!seedClustersSave && !seed->GetClusterOwner()) seed->SetClustersArrayTMP(0);
//
}
//FindKinks(fSeeds,event);
if ((AliTPCReconstructor::StreamLevel()&kStreamClDump)>0) DumpClusters(2,fSeeds); // dump clusters at the end of process (signed with useage flags)
Info("RefitInward","Number of refitted tracks %d",ntracks);
AliCosmicTracker::FindCosmic(event, kTRUE);
FillClusterOccupancyInfo();
return 0;
}
Int_t AliTPCtracker::PropagateBack(AliESDEvent *event)
{
//
// back propagation of ESD tracks
//
if (!event) return 0;
fEvent = event;
fEventHLT = 0;
fIteration = 1;
ReadSeeds(event,1);
PropagateBack(fSeeds);
RemoveUsed2(fSeeds,0.4,0.4,20);
//FindCurling(fSeeds, fEvent,1);
FindSplitted(fSeeds, event,1); // find multi found tracks
if ((AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC)>0) FindMultiMC(fSeeds, fEvent,1); // find multi found tracks
//
// RS: the cluster pointers are not permanently attached to the seed during the tracking, need to attach temporarily
AliTPCclusterMI* seedClusters[kMaxRow];
//
Int_t nseed = fSeeds->GetEntriesFast();
Int_t ntracks=0;
for (Int_t i=0;i<nseed;i++){
AliTPCseed * seed = (AliTPCseed*) fSeeds->UncheckedAt(i);
if (!seed) continue;
AliESDtrack *esd=event->GetTrack(i);
if (!esd) continue; //never happen
//
//RS: if needed, attach temporary cluster array
const AliTPCclusterMI** seedClustersSave = seed->GetClusters();
if (!seedClustersSave) { //RS: temporary attach clusters
for (int ir=kMaxRow;ir--;) {
int idx = seed->GetClusterIndex2(ir);
seedClusters[ir] = idx<0 ? 0 : GetClusterMI(idx);
}
seed->SetClustersArrayTMP(seedClusters);
}
//
if (seed->GetKinkIndex(0)<0) UpdateKinkQualityM(seed); // update quality informations for kinks
seed->UpdatePoints();
AddCovariance(seed);
if (seed->GetNumberOfClusters()<60 && seed->GetNumberOfClusters()<(esd->GetTPCclusters(0) -5)*0.8){
AliExternalTrackParam paramIn;
AliExternalTrackParam paramOut;
Int_t ncl = seed->RefitTrack(seed,¶mIn,¶mOut);
if ((AliTPCReconstructor::StreamLevel()&kStreamRecoverBack)>0) { // flag: stream track information for track faling PropagateBack function and recovered back (RefitTrack)
(*fDebugStreamer)<<"RecoverBack"<<
"seed.="<<seed<<
"esd.="<<esd<<
"pin.="<<¶mIn<<
"pout.="<<¶mOut<<
"ncl="<<ncl<<
"\n";
}
if (ncl>15) {
seed->Set(paramOut.GetX(),paramOut.GetAlpha(),paramOut.GetParameter(),paramOut.GetCovariance());
seed->SetNumberOfClusters(ncl);
}
}
seed->CookdEdx(0.02,0.6);
CookLabel(seed,0.1); //For comparison only
if (seed->GetNumberOfClusters()>15){
esd->UpdateTrackParams(seed,AliESDtrack::kTPCout);
esd->SetTPCPoints(seed->GetPoints());
esd->SetTPCPointsF(seed->GetNFoundable());
Int_t ndedx = seed->GetNCDEDX(0);
Float_t sdedx = seed->GetSDEDX(0);
Float_t dedx = seed->GetdEdx();
esd->SetTPCsignal(dedx, sdedx, ndedx);
ntracks++;
Int_t eventnumber = event->GetEventNumberInFile();// patch 28 fev 06
// This is most likely NOT the event number you'd like to use. It has nothing to do with the 'real' event number
if (((AliTPCReconstructor::StreamLevel()&kStreamCPropagateBack)>0) && esd) {
(*fDebugStreamer)<<"PropagateBack"<< // flag: stream track information in PropagateBack function (after tracking Iteration 1)
"Tr0.="<<seed<<
"esd.="<<esd<<
"EventNrInFile="<<eventnumber<<
"\n";
}
}
//
if (!seedClustersSave) seed->SetClustersArrayTMP(0); //RS detach temporary clusters !!!
//
}
if (AliTPCReconstructor::StreamLevel()&kStreamClDump) DumpClusters(1,fSeeds); // flag:stream clusters at the end of process (signed with usage flag)
//FindKinks(fSeeds,event);
Info("PropagateBack","Number of back propagated tracks %d",ntracks);
fEvent =0;
fEventHLT = 0;
return 0;
}
Int_t AliTPCtracker::PostProcess(AliESDEvent *event)
{
//
// Post process events
//
if (!event) return 0;
//
// Set TPC event status
//
// event affected by HV dip
// reset TPC status
if(IsTPCHVDipEvent(event)) {
event->ResetDetectorStatus(AliDAQ::kTPC);
}
//printf("Status %d \n", event->IsDetectorOn(AliDAQ::kTPC));
return 0;
}
void AliTPCtracker::DeleteSeeds()
{
//
fSeeds->Clear();
ResetSeedsPool();
// delete fSeeds; // RS avoid unnecessary deletes
// fSeeds =0;
}
void AliTPCtracker::ReadSeeds(const AliESDEvent *const event, Int_t direction)
{
//
//read seeds from the event
Int_t nentr=event->GetNumberOfTracks();
if (fDebug>0){
Info("ReadSeeds", "Number of ESD tracks: %d\n", nentr);
}
if (fSeeds)
DeleteSeeds();
if (!fSeeds) fSeeds = new TObjArray(nentr);
else if (fSeeds->GetSize()<nentr) fSeeds->Expand(nentr); //RS reuse array
//
UnsignClusters();
// Int_t ntrk=0;
for (Int_t i=0; i<nentr; i++) {
AliESDtrack *esd=event->GetTrack(i);
ULong_t status=esd->GetStatus();
if (!(status&AliESDtrack::kTPCin)) continue;
AliTPCtrack t(*esd);
t.SetNumberOfClusters(0);
// AliTPCseed *seed = new AliTPCseed(t,t.GetAlpha());
AliTPCseed *seed = new( NextFreeSeed() ) AliTPCseed(t/*,t.GetAlpha()*/);
seed->SetPoolID(fLastSeedID);
seed->SetUniqueID(esd->GetID());
AddCovariance(seed); //add systematic ucertainty
for (Int_t ikink=0;ikink<3;ikink++) {
Int_t index = esd->GetKinkIndex(ikink);
seed->GetKinkIndexes()[ikink] = index;
if (index==0) continue;
index = TMath::Abs(index);
AliESDkink * kink = fEvent->GetKink(index-1);
if (kink&&esd->GetKinkIndex(ikink)<0){
if ((status & AliESDtrack::kTRDrefit) != 0) kink->SetStatus(1,2);
if ((status & AliESDtrack::kITSout) != 0) kink->SetStatus(1,0);
}
if (kink&&esd->GetKinkIndex(ikink)>0){
if ((status & AliESDtrack::kTRDrefit) != 0) kink->SetStatus(1,6);
if ((status & AliESDtrack::kITSout) != 0) kink->SetStatus(1,4);
}
}
if (((status&AliESDtrack::kITSout)==0)&&(direction==1)) seed->ResetCovariance(10.);
//RS if ( direction ==2 &&(status & AliESDtrack::kTRDrefit) == 0 ) seed->ResetCovariance(10.);
if ( direction ==2 &&(status & AliESDtrack::kTRDrefit) == 0 ) seed->ResetCovariance(10.);
//if ( direction ==2 && ((status & AliESDtrack::kTPCout) == 0) ) {
// fSeeds->AddAt(0,i);
// MarkSeedFree( seed );
// continue;
//}
//
//
// rotate to the local coordinate system
//
fSectors=fInnerSec; fN=fkNIS;
Double_t alpha=seed->GetAlpha();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
Int_t ns=Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN;
alpha =ns*fSectors->GetAlpha() + fSectors->GetAlphaShift();
alpha-=seed->GetAlpha();
if (alpha<-TMath::Pi()) alpha += 2*TMath::Pi();
if (alpha>=TMath::Pi()) alpha -= 2*TMath::Pi();
if (TMath::Abs(alpha) > 0.001) { // This should not happen normally
AliWarning(Form("Rotating track over %f",alpha));
if (!seed->Rotate(alpha)) {
MarkSeedFree( seed );
continue;
}
}
seed->SetESD(esd);
// sign clusters
if (esd->GetKinkIndex(0)<=0){
for (Int_t irow=0;irow<kMaxRow;irow++){
Int_t index = seed->GetClusterIndex2(irow);
if (index >= 0){
//
AliTPCclusterMI * cl = GetClusterMI(index);
//RS seed->SetClusterPointer(irow,cl);
if (cl){
if ((index & 0x8000)==0){
cl->Use(10); // accepted cluster
}else{
cl->Use(6); // close cluster not accepted
}
}else{
Info("ReadSeeds","Not found cluster");
}
}
}
}
fSeeds->AddAt(seed,i);
}
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds3(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay, Int_t ddsec) {
//-----------------------------------------------------------------
// This function creates track seeds.
// SEEDING WITH VERTEX CONSTRAIN
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
const double kRoadY = 1., kRoadZ = 0.6;
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Double_t x[5], c[15];
// Int_t di = i1-i2;
//
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed();
seed->SetPoolID(fLastSeedID);
Double_t alpha=fSectors->GetAlpha(), shift=fSectors->GetAlphaShift();
Double_t cs=cos(alpha), sn=sin(alpha);
//
// Double_t x1 =fOuterSec->GetX(i1);
//Double_t xx2=fOuterSec->GetX(i2);
Double_t x1 =GetXrow(i1);
Double_t xx2=GetXrow(i2);
Double_t x3=GetX(), y3=GetY(), z3=GetZ();
Int_t imiddle = (i2+i1)/2; //middle pad row index
Double_t xm = GetXrow(imiddle); // radius of middle pad-row
const AliTPCtrackerRow& krm=GetRow(sec,imiddle); //middle pad -row
//
Int_t ns =sec;
const AliTPCtrackerRow& kr1=GetRow(ns,i1);
Double_t ymax = GetMaxY(i1)-kr1.GetDeadZone()-1.5;
Double_t ymaxm = GetMaxY(imiddle)-kr1.GetDeadZone()-1.5;
//
// change cut on curvature if it can't reach this layer
// maximal curvature set to reach it
Double_t dvertexmax = TMath::Sqrt((x1-x3)*(x1-x3)+(ymax+5-y3)*(ymax+5-y3));
if (dvertexmax*0.5*cuts[0]>0.85){
cuts[0] = 0.85/(dvertexmax*0.5+1.);
}
Double_t r2min = 1/(cuts[0]*cuts[0]); //minimal square of radius given by cut
// Int_t ddsec = 1;
if (deltay>0) ddsec = 0;
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
Double_t y1=kr1[is]->GetY(), z1=kr1[is]->GetZ();
//if (TMath::Abs(y1)>ymax) continue;
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y1))> deltay ) continue; // seed only at the edge
// find possible directions
Float_t anglez = (z1-z3)/(x1-x3);
Float_t extraz = z1 - anglez*(x1-xx2); // extrapolated z
//
//
//find rotation angles relative to line given by vertex and point 1
Double_t dvertex2 = (x1-x3)*(x1-x3)+(y1-y3)*(y1-y3);
Double_t dvertex = TMath::Sqrt(dvertex2);
Double_t angle13 = TMath::ATan((y1-y3)/(x1-x3));
Double_t cs13 = cos(-angle13), sn13 = sin(-angle13);
//
// loop over 2 sectors
Int_t dsec1=-ddsec;
Int_t dsec2= ddsec;
if (y1<0) dsec2= 0;
if (y1>0) dsec1= 0;
Double_t dddz1=0; // direction of delta inclination in z axis
Double_t dddz2=0;
if ( (z1-z3)>0)
dddz1 =1;
else
dddz2 =1;
//
for (Int_t dsec = dsec1; dsec<=dsec2;dsec++){
Int_t sec2 = sec + dsec;
//
// AliTPCtrackerRow& kr2 = fOuterSec[(sec2+fkNOS)%fkNOS][i2];
//AliTPCtrackerRow& kr2m = fOuterSec[(sec2+fkNOS)%fkNOS][imiddle];
AliTPCtrackerRow& kr2 = GetRow((sec2+fkNOS)%fkNOS,i2);
AliTPCtrackerRow& kr2m = GetRow((sec2+fkNOS)%fkNOS,imiddle);
Int_t index1 = TMath::Max(kr2.Find(extraz-0.6-dddz1*TMath::Abs(z1)*0.05)-1,0);
Int_t index2 = TMath::Min(kr2.Find(extraz+0.6+dddz2*TMath::Abs(z1)*0.05)+1,kr2);
// rotation angles to p1-p3
Double_t cs13r = cos(-angle13+dsec*alpha)/dvertex, sn13r = sin(-angle13+dsec*alpha)/dvertex;
Double_t x2, y2, z2;
//
// Double_t dymax = maxangle*TMath::Abs(x1-xx2);
//
Double_t dxx0 = (xx2-x3)*cs13r;
Double_t dyy0 = (xx2-x3)*sn13r;
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr2[js];
if (kcl->IsUsed(10)) continue;
if (kcl->IsDisabled()) {
continue;
}
//
//calcutate parameters
//
Double_t yy0 = dyy0 +(kcl->GetY()-y3)*cs13r;
// stright track
if (TMath::Abs(yy0)<0.000001) continue;
Double_t xx0 = dxx0 -(kcl->GetY()-y3)*sn13r;
Double_t y0 = 0.5*(xx0*xx0+yy0*yy0-xx0)/yy0;
Double_t r02 = (0.25+y0*y0)*dvertex2;
//curvature (radius) cut
if (r02<r2min) continue;
nin0++;
//
Double_t c0 = 1/TMath::Sqrt(r02);
if (yy0>0) c0*=-1.;
//Double_t dfi0 = 2.*TMath::ASin(dvertex*c0*0.5);
//Double_t dfi1 = 2.*TMath::ASin(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
Double_t dfi0 = 2.*asinf(dvertex*c0*0.5);
Double_t dfi1 = 2.*asinf(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
//
//
Double_t z0 = kcl->GetZ();
Double_t zzzz2 = z1-(z1-z3)*dfi1/dfi0;
if (TMath::Abs(zzzz2-z0)>0.5) continue;
nin1++;
//
Double_t dip = (z1-z0)*c0/dfi1;
Double_t x0 = (0.5*cs13+y0*sn13)*dvertex*c0;
//
y2 = kcl->GetY();
if (dsec==0){
x2 = xx2;
z2 = kcl->GetZ();
}
else
{
// rotation
z2 = kcl->GetZ();
x2= xx2*cs-y2*sn*dsec;
y2=+xx2*sn*dsec+y2*cs;
}
x[0] = y1;
x[1] = z1;
x[2] = x0;
x[3] = dip;
x[4] = c0;
//
//
// do we have cluster at the middle ?
Double_t ym,zm;
GetProlongation(x1,xm,x,ym,zm);
UInt_t dummy;
AliTPCclusterMI * cm=0;
if (TMath::Abs(ym)-ymaxm<0){
cm = krm.FindNearest2(ym,zm,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
else{
// rotate y1 to system 0
// get state vector in rotated system
Double_t yr1 = (-0.5*sn13+y0*cs13)*dvertex*c0;
Double_t xr2 = x0*cs+yr1*sn*dsec;
Double_t xr[5]={kcl->GetY(),kcl->GetZ(), xr2, dip, c0};
//
GetProlongation(xx2,xm,xr,ym,zm);
if (TMath::Abs(ym)-ymaxm<0){
cm = kr2m.FindNearest2(ym,zm,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
}
// Double_t dym = 0;
// Double_t dzm = 0;
// if (cm){
// dym = ym - cm->GetY();
// dzm = zm - cm->GetZ();
// }
nin2++;
//
//
Double_t sy1=kr1[is]->GetSigmaY2()*2., sz1=kr1[is]->GetSigmaZ2()*2.;
Double_t sy2=kcl->GetSigmaY2()*2., sz2=kcl->GetSigmaZ2()*2.;
//Double_t sy3=400*3./12., sy=0.1, sz=0.1;
Double_t sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
//Double_t sy3=25000*x[4]*x[4]*60+0.5, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
UInt_t index=kr1.GetIndex(is);
if (seed) {MarkSeedFree(seed); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, ns*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
track->SetSeed1(i1);
track->SetSeed2(i2);
track->SetSeedType(3);
//if (dsec==0) {
FollowProlongation(*track, (i1+i2)/2,1);
Int_t foundable,found,shared;
GetSeedClusterStatistic(track,(i1+i2)/2,i1, found, foundable, shared, kTRUE); //RS: seeds don't keep their clusters
//RS track->GetClusterStatistic((i1+i2)/2,i1, found, foundable, shared, kTRUE);
if ((found<0.55*foundable) || shared>0.5*found || (track->GetSigmaY2()+track->GetSigmaZ2())>0.5){
MarkSeedFree(seed); seed = 0;
continue;
}
//}
nin++;
FollowProlongation(*track, i2,1);
//Int_t rc = 1;
track->SetBConstrain(1);
// track->fLastPoint = i1+fInnerSec->GetNRows(); // first cluster in track position
track->SetLastPoint(i1); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters() ) {
MarkSeedFree(seed); seed = 0;
continue;
}
nout1++;
Double_t zv, bz=GetBz();
if ( !track->GetZAt(0.,bz,zv) ) { MarkSeedFree( seed ); seed = 0; continue; }
//
if (fDisableSecondaries) {
if (TMath::Abs(zv)>fPrimaryDCAZCut) { MarkSeedFree( seed ); seed = 0; continue; }
double yv;
if ( !track->GetZAt(0.,bz,yv) ) { MarkSeedFree( seed ); seed = 0; continue; }
if (TMath::Abs(zv)>fPrimaryDCAZCut) { MarkSeedFree( seed ); seed = 0; continue; }
}
//
// Z VERTEX CONDITION
if (TMath::Abs(zv-z3)>cuts[2]) {
FollowProlongation(*track, TMath::Max(i2-20,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2]){
FollowProlongation(*track, TMath::Max(i2-40,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2] &&(track->GetNumberOfClusters() > track->GetNFoundable()*0.7)){
// make seed without constrain
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,1.);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(1);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
continue;
}
else{
MarkSeedFree( seed ); seed = 0;
continue;
}
}
}
track->SetSeedType(0);
arr->AddLast(track); // note, track is seed, don't free the seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
nout2++;
// don't consider other combinations
if (track->GetNumberOfClusters() > track->GetNFoundable()*0.8)
break;
}
}
}
if (fDebug>3){
Info("MakeSeeds3","\nSeeding statistic:\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2);
}
if (seed) MarkSeedFree( seed );
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds3Dist(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay, Int_t ddsec) {
//-----------------------------------------------------------------
// This function creates track seeds, accounting for distortions
// SEEDING WITH VERTEX CONSTRAIN
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Double_t x[5], c[15];
// Int_t di = i1-i2;
//
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed();
seed->SetPoolID(fLastSeedID);
Double_t alpha=fSectors->GetAlpha(), shift=fSectors->GetAlphaShift();
Double_t cs=cos(alpha), sn=sin(alpha);
//
Double_t x1def = GetXrow(i1);
Double_t xx2def = GetXrow(i2);
Double_t x3=GetX(), y3=GetY(), z3=GetZ();
Int_t imiddle = (i2+i1)/2; //middle pad row index
const AliTPCtrackerRow& krm=GetRow(sec,imiddle); //middle pad -row
//
Int_t ns =sec;
const AliTPCtrackerRow& kr1=GetRow(ns,i1);
Double_t ymax = GetMaxY(i1)-kr1.GetDeadZone()-1.5;
Double_t ymaxm = GetMaxY(imiddle)-kr1.GetDeadZone()-1.5; // RS check ymax
//
// change cut on curvature if it can't reach this layer
// maximal curvature set to reach it
Double_t dvertexmax = TMath::Sqrt((x1def-x3)*(x1def-x3)+(ymax+5-y3)*(ymax+5-y3));
if (dvertexmax*0.5*cuts[0]>0.85){
cuts[0] = 0.85/(dvertexmax*0.5+1.);
}
Double_t r2min = 1/(cuts[0]*cuts[0]); //minimal square of radius given by cut
// Int_t ddsec = 1;
if (deltay>0) ddsec = 0;
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
const AliTPCclusterMI* clkr1 = kr1[is];
Double_t x1=clkr1->GetX(), y1=clkr1->GetY(), z1=clkr1->GetZ();
//if (TMath::Abs(y1)>ymax) continue;
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y1))> deltay ) continue; // seed only at the edge
// find possible directions
double dx13 = x1-x3, dy13 = y1-y3, dz13 = z1-z3;
double anglez = dz13/dx13;
double extraz = z1 - anglez*(x1-xx2def); // extrapolated z
//
//
//find rotation angles relative to line given by vertex and point 1
Double_t dvertex2 = dx13*dx13+dy13*dy13;
Double_t dvertex = TMath::Sqrt(dvertex2);
Double_t angle13 = TMath::ATan(dy13/dx13);
Double_t cs13 = cos(-angle13), sn13 = sin(-angle13);
//
// loop over 2 sectors
Int_t dsec1=-ddsec;
Int_t dsec2= ddsec;
if (y1<0) dsec2= 0;
if (y1>0) dsec1= 0;
Double_t dddz1=0; // direction of delta inclination in z axis
Double_t dddz2=0;
if ( dz13>0 ) dddz1 =1;
else dddz2 =1;
//
for (Int_t dsec = dsec1; dsec<=dsec2;dsec++){
Int_t sec2 = sec + dsec;
//
// AliTPCtrackerRow& kr2 = fOuterSec[(sec2+fkNOS)%fkNOS][i2];
//AliTPCtrackerRow& kr2m = fOuterSec[(sec2+fkNOS)%fkNOS][imiddle];
AliTPCtrackerRow& kr2 = GetRow((sec2+fkNOS)%fkNOS,i2);
AliTPCtrackerRow& kr2m = GetRow((sec2+fkNOS)%fkNOS,imiddle);
Int_t index1 = TMath::Max(kr2.Find(extraz-0.6-dddz1*TMath::Abs(z1)*0.05)-1,0);
Int_t index2 = TMath::Min(kr2.Find(extraz+0.6+dddz2*TMath::Abs(z1)*0.05)+1,kr2);
// rotation angles to p1-p3
Double_t cs13r = cos(-angle13+dsec*alpha)/dvertex, sn13r = sin(-angle13+dsec*alpha)/dvertex;
//
// Double_t dymax = maxangle*TMath::Abs(x1-xx2);
//
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr2[js];
if (kcl->IsUsed(10)) continue;
if (kcl->IsDisabled()) {
continue;
}
//
double x2=kcl->GetX(), y2=kcl->GetY(), z2=kcl->GetZ();
double dy23 = y2-y3, dx23 = x2-x3;
//calcutate parameters
Double_t dxx0 = dx23*cs13r;
Double_t dyy0 = dx23*sn13r;
//
Double_t yy0 = dyy0 +dy23*cs13r;
// stright track
if (TMath::Abs(yy0)<0.000001) continue;
Double_t xx0 = dxx0 -dy23*sn13r;
Double_t y0 = 0.5*(xx0*xx0+yy0*yy0-xx0)/yy0;
Double_t r02 = (0.25+y0*y0)*dvertex2;
//curvature (radius) cut
if (r02<r2min) continue;
nin0++;
//
Double_t c0 = 1/TMath::Sqrt(r02);
if (yy0>0) c0*=-1.;
//Double_t dfi0 = 2.*TMath::ASin(dvertex*c0*0.5);
//Double_t dfi1 = 2.*TMath::ASin(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
Double_t dfi0 = 2.*AliTPCFastMath::FastAsin(dvertex*c0*0.5);
Double_t dfi1 = 2.*AliTPCFastMath::FastAsin(TMath::Sqrt(yy0*yy0+(1-xx0)*(1-xx0))*dvertex*c0*0.5);
//
Double_t zzzz2 = z1-dz13*dfi1/dfi0;
if (TMath::Abs(zzzz2-z2)>0.5) continue;
nin1++;
//
Double_t dip = (z1-z2)*c0/dfi1;
Double_t x0 = (0.5*cs13+y0*sn13)*dvertex*c0;
//
if (dsec!=0) {
// rotation
double xt2 = x2;
x2= xt2*cs-y2*sn*dsec;
y2=+xt2*sn*dsec+y2*cs;
}
x[0] = y1;
x[1] = z1;
x[2] = x0;
x[3] = dip;
x[4] = c0;
//
//
// do we have cluster at the middle ?
Double_t xm = GetXrow(imiddle), ym, zm; // radius of middle pad-row
GetProlongation(x1,xm,x,ym,zm);
// account for distortion
double dxDist = GetDistortionX(xm,ym,zm,sec,imiddle);
if (TMath::Abs(dxDist)>0.1) {
GetProlongation(x1,xm+dxDist,x,ym,zm); //RS:? can we use straight line here?
}
UInt_t dummy;
AliTPCclusterMI * cm=0;
if (TMath::Abs(ym)-ymaxm<0){ //RS:? redefine ymax?
cm = krm.FindNearest2(ym,zm,1.0,0.6,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
else{
// rotate y1 to system 0
// get state vector in rotated system
Double_t yr1 = (-0.5*sn13+y0*cs13)*dvertex*c0;
Double_t xr2 = x0*cs+yr1*sn*dsec;
Double_t xr[5]={kcl->GetY(),kcl->GetZ(), xr2, dip, c0};
//
GetProlongation(kcl->GetX(),xm,xr,ym,zm);
double dxDist = GetDistortionX(xm,ym,zm,sec,imiddle);
if (TMath::Abs(dxDist)>0.1) {
GetProlongation(x1,xm+dxDist,x,ym,zm); //RS:? can we use straight line here?
}
//
if (TMath::Abs(ym)-ymaxm<0){
cm = kr2m.FindNearest2(ym,zm,1.0,0.6,dummy);
if ((!cm) || (cm->IsUsed(10))) {
continue;
}
}
}
// Double_t dym = 0;
// Double_t dzm = 0;
// if (cm){
// dym = ym - cm->GetY();
// dzm = zm - cm->GetZ();
// }
nin2++;
//
//
Double_t sy1=kr1[is]->GetSigmaY2()*2., sz1=kr1[is]->GetSigmaZ2()*2.;
Double_t sy2=kcl->GetSigmaY2()*2., sz2=kcl->GetSigmaZ2()*2.;
//Double_t sy3=400*3./12., sy=0.1, sz=0.1;
Double_t sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
//Double_t sy3=25000*x[4]*x[4]*60+0.5, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
UInt_t index=kr1.GetIndex(is);
if (seed) {MarkSeedFree(seed); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, ns*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
track->SetSeed1(i1);
track->SetSeed2(i2);
track->SetSeedType(3);
//if (dsec==0) {
FollowProlongation(*track, (i1+i2)/2,1);
Int_t foundable,found,shared;
track->GetClusterStatistic((i1+i2)/2,i1, found, foundable, shared, kTRUE);
if ((found<0.55*foundable) || shared>0.5*found || (track->GetSigmaY2()+track->GetSigmaZ2())>0.5){
MarkSeedFree(seed); seed = 0;
continue;
}
//}
nin++;
FollowProlongation(*track, i2,1);
//Int_t rc = 1;
track->SetBConstrain(1);
// track->fLastPoint = i1+fInnerSec->GetNRows(); // first cluster in track position
track->SetLastPoint(i1); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters() ) {
MarkSeedFree(seed); seed = 0;
continue;
}
nout1++;
// Z VERTEX CONDITION
Double_t zv, bz=GetBz();
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2]) {
FollowProlongation(*track, TMath::Max(i2-20,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2]){
FollowProlongation(*track, TMath::Max(i2-40,0));
if ( !track->GetZAt(0.,bz,zv) ) continue;
if (TMath::Abs(zv-z3)>cuts[2] &&(track->GetNumberOfClusters() > track->GetNFoundable()*0.7)){
// make seed without constrain
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,1.);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(1);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
continue;
}
else{
MarkSeedFree( seed ); seed = 0;
continue;
}
}
}
track->SetSeedType(0);
arr->AddLast(track); // note, track is seed, don't free the seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
nout2++;
// don't consider other combinations
if (track->GetNumberOfClusters() > track->GetNFoundable()*0.8)
break;
}
}
}
if (fDebug>3){
Info("MakeSeeds3Dist","\nSeeding statistic:\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2);
}
if (seed) MarkSeedFree( seed );
}
void AliTPCtracker::MakeSeeds5(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay) {
//-----------------------------------------------------------------
// This function creates track seeds.
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Int_t nout3 =0;
Double_t x[5], c[15];
//
// make temporary seed
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
//
//
// first 3 padrows
Double_t x1 = GetXrow(i1-1);
const AliTPCtrackerRow& kr1=GetRow(sec,i1-1);
Double_t y1max = GetMaxY(i1-1)-kr1.GetDeadZone()-1.5;
//
Double_t x1p = GetXrow(i1);
const AliTPCtrackerRow& kr1p=GetRow(sec,i1);
//
Double_t x1m = GetXrow(i1-2);
const AliTPCtrackerRow& kr1m=GetRow(sec,i1-2);
//
//last 3 padrow for seeding
AliTPCtrackerRow& kr3 = GetRow((sec+fkNOS)%fkNOS,i1-7);
Double_t x3 = GetXrow(i1-7);
// Double_t y3max= GetMaxY(i1-7)-kr3.fDeadZone-1.5;
//
AliTPCtrackerRow& kr3p = GetRow((sec+fkNOS)%fkNOS,i1-6);
Double_t x3p = GetXrow(i1-6);
//
AliTPCtrackerRow& kr3m = GetRow((sec+fkNOS)%fkNOS,i1-8);
Double_t x3m = GetXrow(i1-8);
//
//
// middle padrow
Int_t im = i1-4; //middle pad row index
Double_t xm = GetXrow(im); // radius of middle pad-row
const AliTPCtrackerRow& krm=GetRow(sec,im); //middle pad -row
// Double_t ymmax = GetMaxY(im)-kr1.fDeadZone-1.5;
//
//
Double_t deltax = x1-x3;
Double_t dymax = deltax*cuts[1];
Double_t dzmax = deltax*cuts[3];
//
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
Double_t y1=kr1[is]->GetY(), z1=kr1[is]->GetZ();
//
if (deltay>0 && TMath::Abs(y1max-TMath::Abs(y1))> deltay ) continue; // seed only at the edge
//
Int_t index1 = TMath::Max(kr3.Find(z1-dzmax)-1,0);
Int_t index2 = TMath::Min(kr3.Find(z1+dzmax)+1,kr3);
//
Double_t y3, z3;
//
//
UInt_t index;
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr3[js];
if (kcl->IsDisabled()) {
continue;
}
if (kcl->IsUsed(10)) continue;
y3 = kcl->GetY();
// apply angular cuts
if (TMath::Abs(y1-y3)>dymax) continue;
//x3 = x3;
z3 = kcl->GetZ();
if (TMath::Abs(z1-z3)>dzmax) continue;
//
Double_t angley = (y1-y3)/(x1-x3);
Double_t anglez = (z1-z3)/(x1-x3);
//
Double_t erry = TMath::Abs(angley)*(x1-x1m)*0.5+0.5;
Double_t errz = TMath::Abs(anglez)*(x1-x1m)*0.5+0.5;
//
Double_t yyym = angley*(xm-x1)+y1;
Double_t zzzm = anglez*(xm-x1)+z1;
const AliTPCclusterMI *kcm = krm.FindNearest2(yyym,zzzm,erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
if (!kcm) continue;
if (kcm->IsUsed(10)) continue;
if (kcm->IsDisabled()) {
continue;
}
erry = TMath::Abs(angley)*(x1-x1m)*0.4+0.5;
errz = TMath::Abs(anglez)*(x1-x1m)*0.4+0.5;
//
//
//
Int_t used =0;
Int_t found =0;
//
// look around first
const AliTPCclusterMI *kc1m = kr1m.FindNearest2(angley*(x1m-x1)+y1,
anglez*(x1m-x1)+z1,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc1m){
found++;
if (kc1m->IsUsed(10)) used++;
}
const AliTPCclusterMI *kc1p = kr1p.FindNearest2(angley*(x1p-x1)+y1,
anglez*(x1p-x1)+z1,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc1p){
found++;
if (kc1p->IsUsed(10)) used++;
}
if (used>1) continue;
if (found<1) continue;
//
// look around last
const AliTPCclusterMI *kc3m = kr3m.FindNearest2(angley*(x3m-x3)+y3,
anglez*(x3m-x3)+z3,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc3m){
found++;
if (kc3m->IsUsed(10)) used++;
}
else
continue;
const AliTPCclusterMI *kc3p = kr3p.FindNearest2(angley*(x3p-x3)+y3,
anglez*(x3p-x3)+z3,
erry+fClExtraRoadY,errz+fClExtraRoadZ,index);
//
if (kc3p){
found++;
if (kc3p->IsUsed(10)) used++;
}
else
continue;
if (used>1) continue;
if (found<3) continue;
//
Double_t x2,y2,z2;
x2 = xm;
y2 = kcm->GetY();
z2 = kcm->GetZ();
//
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]) >= cuts[0]) continue;
nin0++;
//
x[2]=F2(x1,y1,x2,y2,x3,y3);
nin1++;
//
x[3]=F3n(x1,y1,x2,y2,z1,z2,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
nin2++;
//
//
Double_t sy1=0.1, sz1=0.1;
Double_t sy2=0.1, sz2=0.1;
Double_t sy3=0.1, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
index=kr1.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, sec*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
nin++;
FollowProlongation(*track, i1-7,1);
if (track->GetNumberOfClusters() < track->GetNFoundable()*0.75 ||
track->GetNShared()>0.6*track->GetNumberOfClusters() || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.6+fExtraClErrYZ2){
MarkSeedFree( seed ); seed = 0;
continue;
}
nout1++;
nout2++;
//Int_t rc = 1;
FollowProlongation(*track, i2,1);
track->SetBConstrain(0);
track->SetLastPoint(i1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters()<track->GetNFoundable()*0.7 ||
track->GetNShared()>2. || track->GetChi2()/track->GetNumberOfClusters()>6 || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.5+fExtraClErrYZ2) {
MarkSeedFree( seed ); seed = 0;
continue;
}
{
FollowProlongation(*track, TMath::Max(i2-10,0),1);
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,0.9);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(4);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
}
//arr->AddLast(track);
//seed = new AliTPCseed;
nout3++;
}
}
if (fDebug>3){
Info("MakeSeeds5","\nSeeding statiistic:\t%d\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2,nout3);
}
if (seed) MarkSeedFree(seed);
}
void AliTPCtracker::MakeSeeds5Dist(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t cuts[4],
Float_t deltay) {
//-----------------------------------------------------------------
// This function creates track seeds, accounting for distortions
//-----------------------------------------------------------------
// cuts[0] - fP4 cut
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut
// cuts[3] - fP3 cut
Int_t nin0 = 0;
Int_t nin1 = 0;
Int_t nin2 = 0;
Int_t nin = 0;
Int_t nout1 = 0;
Int_t nout2 = 0;
Int_t nout3 =0;
Double_t x[5], c[15];
//
// make temporary seed
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
//
//
// first 3 padrows
Double_t x1Def = GetXrow(i1-1);
const AliTPCtrackerRow& kr1=GetRow(sec,i1-1);
Double_t y1max = GetMaxY(i1-1)-kr1.GetDeadZone()-1.5;
//
Double_t x1pDef = GetXrow(i1);
const AliTPCtrackerRow& kr1p=GetRow(sec,i1);
//
Double_t x1mDef = GetXrow(i1-2);
const AliTPCtrackerRow& kr1m=GetRow(sec,i1-2);
double dx11mDef = x1Def-x1mDef;
double dx11pDef = x1Def-x1pDef;
//
//last 3 padrow for seeding
AliTPCtrackerRow& kr3 = GetRow((sec+fkNOS)%fkNOS,i1-7);
Double_t x3Def = GetXrow(i1-7);
// Double_t y3max= GetMaxY(i1-7)-kr3.fDeadZone-1.5;
//
AliTPCtrackerRow& kr3p = GetRow((sec+fkNOS)%fkNOS,i1-6);
Double_t x3pDef = GetXrow(i1-6);
//
AliTPCtrackerRow& kr3m = GetRow((sec+fkNOS)%fkNOS,i1-8);
Double_t x3mDef = GetXrow(i1-8);
//
double dx33mDef = x3Def-x3mDef;
double dx33pDef = x3Def-x3pDef;
//
// middle padrow
Int_t im = i1-4; //middle pad row index
Double_t xmDef = GetXrow(im); // radius of middle pad-row
const AliTPCtrackerRow& krm=GetRow(sec,im); //middle pad -row
// Double_t ymmax = GetMaxY(im)-kr1.fDeadZone-1.5;
//
//
Double_t deltax = x1Def-x3Def;
Double_t dymax = deltax*cuts[1];
Double_t dzmax = deltax*cuts[3];
//
// loop over clusters
for (Int_t is=0; is < kr1; is++) {
//
if (kr1[is]->IsUsed(10)) continue;
if (kr1[is]->IsDisabled()) {
continue;
}
const AliTPCclusterMI* clkr1 = kr1[is];
Double_t x1=clkr1->GetX(), y1=clkr1->GetY(), z1=clkr1->GetZ();
//
if (deltay>0 && TMath::Abs(y1max-TMath::Abs(y1))> deltay ) continue; // seed only at the edge //RS:? dead zones?
//
Int_t index1 = TMath::Max(kr3.Find(z1-dzmax)-1,0);
Int_t index2 = TMath::Min(kr3.Find(z1+dzmax)+1,kr3);
//
Double_t x3,y3,z3;
//
//
UInt_t index;
for (Int_t js=index1; js < index2; js++) {
const AliTPCclusterMI *kcl = kr3[js];
if (kcl->IsDisabled()) {
continue;
}
if (kcl->IsUsed(10)) continue;
y3 = kcl->GetY();
// apply angular cuts
if (TMath::Abs(y1-y3)>dymax) continue;
//x3 = x3;
z3 = kcl->GetZ();
if (TMath::Abs(z1-z3)>dzmax) continue;
x3 = kcl->GetX();
//
double dx13 = x1-x3;
Double_t angley = (y1-y3)/dx13;
Double_t anglez = (z1-z3)/dx13;
//
Double_t erry = TMath::Abs(angley)*dx11mDef*0.5+0.5; // RS: use ideal X differences assuming
Double_t errz = TMath::Abs(anglez)*dx11mDef*0.5+0.5; // that the distortions are ~same on close rows
//
Double_t yyym = angley*(xmDef-x1Def)+y1; // RS: idem, assume distortions cancels in the difference
Double_t zzzm = anglez*(xmDef-x1Def)+z1;
const AliTPCclusterMI *kcm = krm.FindNearest2(yyym,zzzm,erry,errz,index);
if (!kcm) continue;
if (kcm->IsUsed(10)) continue;
if (kcm->IsDisabled()) {
continue;
}
erry = TMath::Abs(angley)*dx11mDef*0.4+0.5;
errz = TMath::Abs(anglez)*dx11mDef*0.4+0.5;
//
//
//
Int_t used =0;
Int_t found =0;
//
// look around first
const AliTPCclusterMI *kc1m = kr1m.FindNearest2(-angley*dx11mDef+y1, // RS: idem, assume distortions cancels in the difference
-anglez*dx11mDef+z1,
erry,errz,index);
//
if (kc1m){
found++;
if (kc1m->IsUsed(10)) used++;
}
const AliTPCclusterMI *kc1p = kr1p.FindNearest2(-angley*dx11pDef+y1, // RS: idem, assume distortions cancels in the difference
-anglez*dx11pDef+z1,
erry,errz,index);
//
if (kc1p){
found++;
if (kc1p->IsUsed(10)) used++;
}
if (used>1) continue;
if (found<1) continue;
//
// look around last
const AliTPCclusterMI *kc3m = kr3m.FindNearest2(-angley*dx33mDef+y3, // RS: idem, assume distortions cancels in the difference
-anglez*dx33mDef+z3,
erry,errz,index);
//
if (kc3m){
found++;
if (kc3m->IsUsed(10)) used++;
}
else
continue;
const AliTPCclusterMI *kc3p = kr3p.FindNearest2(-angley*dx33pDef+y3, // RS: idem, assume distortions cancels in the difference
-anglez*dx33pDef+z3,
erry,errz,index);
//
if (kc3p){
found++;
if (kc3p->IsUsed(10)) used++;
}
else
continue;
if (used>1) continue;
if (found<3) continue;
//
Double_t x2,y2,z2;
x2 = kcm->GetZ();
y2 = kcm->GetY();
z2 = kcm->GetZ();
//
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]) >= cuts[0]) continue;
nin0++;
//
x[2]=F2(x1,y1,x2,y2,x3,y3);
nin1++;
//
x[3]=F3n(x1,y1,x2,y2,z1,z2,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
nin2++;
//
//
Double_t sy1=0.1, sz1=0.1;
Double_t sy2=0.1, sz2=0.1;
Double_t sy3=0.1, sy=0.1, sz=0.1;
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x2,y2,z1,z2)-x[3])/sy;
Double_t f31=(F3(x1,y1,x2,y2,z1+sz,z2)-x[3])/sz;
Double_t f32=(F3(x1,y1,x2,y2+sy,z1,z2)-x[3])/sy;
Double_t f34=(F3(x1,y1,x2,y2,z1,z2+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// if (!BuildSeed(kr1[is],kcl,0,x1,x2,x3,x,c)) continue;
index=kr1.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1, sec*alpha+shift, x, c, index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
nin++;
FollowProlongation(*track, i1-7,1);
if (track->GetNumberOfClusters() < track->GetNFoundable()*0.75 ||
track->GetNShared()>0.6*track->GetNumberOfClusters() || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.6){
MarkSeedFree( seed ); seed = 0;
continue;
}
nout1++;
nout2++;
//Int_t rc = 1;
FollowProlongation(*track, i2,1);
track->SetBConstrain(0);
track->SetLastPoint(i1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters()<track->GetNFoundable()*0.7 ||
track->GetNShared()>2. || track->GetChi2()/track->GetNumberOfClusters()>6 || ( track->GetSigmaY2()+ track->GetSigmaZ2())>0.5 ) {
MarkSeedFree( seed ); seed = 0;
continue;
}
{
FollowProlongation(*track, TMath::Max(i2-10,0),1);
AliTPCseed * track2 = MakeSeed(track,0.2,0.5,0.9);
FollowProlongation(*track2, i2,1);
track2->SetBConstrain(kFALSE);
track2->SetSeedType(4);
arr->AddLast(track2);
MarkSeedFree( seed ); seed = 0;
}
//arr->AddLast(track);
//seed = new AliTPCseed;
nout3++;
}
}
if (fDebug>3){
Info("MakeSeeds5Dist","\nSeeding statiistic:\t%d\t%d\t%d\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin,nout1,nout2,nout3);
}
if (seed) MarkSeedFree(seed);
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds2(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t */*cuts[4]*/,
Float_t deltay, Bool_t /*bconstrain*/) {
//-----------------------------------------------------------------
// This function creates track seeds - without vertex constraint
//-----------------------------------------------------------------
// cuts[0] - fP4 cut - not applied
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut - not applied
// cuts[3] - fP3 cut
const double kRoadZ = 1.2, kRoadY = 1.2;
Int_t nin0=0;
Int_t nin1=0;
Int_t nin2=0;
Int_t nin3=0;
// Int_t nin4=0;
//Int_t nin5=0;
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
Int_t row0 = (i1+i2)/2;
Int_t drow = (i1-i2)/2;
const AliTPCtrackerRow& kr0=fSectors[sec][row0];
AliTPCtrackerRow * kr=0;
AliTPCpolyTrack polytrack;
Int_t nclusters=fSectors[sec][row0];
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Int_t sumused=0;
Int_t cused=0;
Int_t cnused=0;
for (Int_t is=0; is < nclusters; is++) { //LOOP over clusters
Int_t nfound =0;
Int_t nfoundable =0;
for (Int_t iter =1; iter<2; iter++){ //iterations
const AliTPCtrackerRow& krm=fSectors[sec][row0-iter];
const AliTPCtrackerRow& krp=fSectors[sec][row0+iter];
const AliTPCclusterMI * cl= kr0[is];
if (cl->IsDisabled()) {
continue;
}
if (cl->IsUsed(10)) {
cused++;
}
else{
cnused++;
}
Double_t x = kr0.GetX();
// Initialization of the polytrack
nfound =0;
nfoundable =0;
polytrack.Reset();
//
Double_t y0= cl->GetY();
Double_t z0= cl->GetZ();
Float_t erry = 0;
Float_t errz = 0;
Double_t ymax = fSectors->GetMaxY(row0)-kr0.GetDeadZone()-1.5;
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y0))> deltay ) continue; // seed only at the edge
erry = (0.5)*cl->GetSigmaY2()/TMath::Sqrt(cl->GetQ())*6;
errz = (0.5)*cl->GetSigmaZ2()/TMath::Sqrt(cl->GetQ())*6;
polytrack.AddPoint(x,y0,z0,erry, errz);
sumused=0;
if (cl->IsUsed(10)) sumused++;
Float_t roady = (5*TMath::Sqrt(cl->GetSigmaY2()+0.2)+1.)*iter;
Float_t roadz = (5*TMath::Sqrt(cl->GetSigmaZ2()+0.2)+1.)*iter;
//
x = krm.GetX();
AliTPCclusterMI * cl1 = krm.FindNearest(y0,z0,roady+fClExtraRoadY,roadz+fClExtraRoadZ);
if (cl1 && TMath::Abs(ymax-TMath::Abs(y0))) {
erry = (0.5)*cl1->GetSigmaY2()/TMath::Sqrt(cl1->GetQ())*3;
errz = (0.5)*cl1->GetSigmaZ2()/TMath::Sqrt(cl1->GetQ())*3;
if (cl1->IsUsed(10)) sumused++;
polytrack.AddPoint(x,cl1->GetY(),cl1->GetZ(),erry,errz);
}
//
x = krp.GetX();
AliTPCclusterMI * cl2 = krp.FindNearest(y0,z0,roady+fClExtraRoadY,roadz+fClExtraRoadZ);
if (cl2) {
erry = (0.5)*cl2->GetSigmaY2()/TMath::Sqrt(cl2->GetQ())*3;
errz = (0.5)*cl2->GetSigmaZ2()/TMath::Sqrt(cl2->GetQ())*3;
if (cl2->IsUsed(10)) sumused++;
polytrack.AddPoint(x,cl2->GetY(),cl2->GetZ(),erry,errz);
}
//
if (sumused>0) continue;
nin0++;
polytrack.UpdateParameters();
// follow polytrack
//
Double_t yn,zn;
nfoundable = polytrack.GetN();
nfound = nfoundable;
//
for (Int_t ddrow = iter+1; ddrow<drow;ddrow++){
Float_t maxdist = 0.8*(1.+3./(ddrow));
for (Int_t delta = -1;delta<=1;delta+=2){
Int_t row = row0+ddrow*delta;
kr = &(fSectors[sec][row]);
Double_t xn = kr->GetX();
Double_t ymax1 = fSectors->GetMaxY(row)-kr->GetDeadZone()-1.5;
polytrack.GetFitPoint(xn,yn,zn);
if (TMath::Abs(yn)>ymax1) continue;
nfoundable++;
AliTPCclusterMI * cln = kr->FindNearest(yn,zn,kRoadY+fClExtraRoadY,kRoadZ+fClExtraRoadZ);
if (cln) {
Float_t dist = TMath::Sqrt( (yn-cln->GetY())*(yn-cln->GetY())+(zn-cln->GetZ())*(zn-cln->GetZ()));
if (dist<maxdist){
/*
erry = (dist+0.3)*cln->GetSigmaY2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
errz = (dist+0.3)*cln->GetSigmaZ2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
if (cln->IsUsed(10)) {
// printf("used\n");
sumused++;
erry*=2;
errz*=2;
}
*/
erry=0.1;
errz=0.1;
polytrack.AddPoint(xn,cln->GetY(),cln->GetZ(),erry, errz);
nfound++;
}
}
}
if ( (sumused>3) || (sumused>0.5*nfound) || (nfound<0.6*nfoundable)) break;
polytrack.UpdateParameters();
}
}
if ( (sumused>3) || (sumused>0.5*nfound)) {
//printf("sumused %d\n",sumused);
continue;
}
nin1++;
Double_t dy,dz;
polytrack.GetFitDerivation(kr0.GetX(),dy,dz);
AliTPCpolyTrack track2;
polytrack.Refit(track2,0.5+TMath::Abs(dy)*0.3,0.4+TMath::Abs(dz)*0.3);
if (track2.GetN()<0.5*nfoundable) continue;
nin2++;
if ((nfound>0.6*nfoundable) &&( nfoundable>0.4*(i1-i2))) {
//
// test seed with and without constrain
for (Int_t constrain=0; constrain<=0;constrain++){
// add polytrack candidate
Double_t x[5], c[15];
Double_t x1,x2,x3,y1,y2,y3,z1,z2,z3;
track2.GetBoundaries(x3,x1);
x2 = (x1+x3)/2.;
track2.GetFitPoint(x1,y1,z1);
track2.GetFitPoint(x2,y2,z2);
track2.GetFitPoint(x3,y3,z3);
//
//is track pointing to the vertex ?
Double_t x0,y0,z0;
x0=0;
polytrack.GetFitPoint(x0,y0,z0);
if (constrain) {
x2 = x3;
y2 = y3;
z2 = z3;
x3 = 0;
y3 = 0;
z3 = 0;
}
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
// if (TMath::Abs(x[4]) >= cuts[0]) continue; //
x[2]=F2(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]*x1-x[2]) >= cuts[1]) continue;
//x[3]=F3(x1,y1,x2,y2,z1,z2);
x[3]=F3n(x1,y1,x3,y3,z1,z3,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
Double_t sy =0.1, sz =0.1;
Double_t sy1=0.02, sz1=0.02;
Double_t sy2=0.02, sz2=0.02;
Double_t sy3=0.02;
if (constrain){
sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
}
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x3,y3,z1,z3)-x[3])/sy;
Double_t f31=(F3(x1,y1,x3,y3,z1+sz,z3)-x[3])/sz;
Double_t f32=(F3(x1,y1,x3,y3+sy,z1,z3)-x[3])/sy;
Double_t f34=(F3(x1,y1,x3,y3,z1,z3+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
//Int_t row1 = fSectors->GetRowNumber(x1);
Int_t row1 = GetRowNumber(x1);
UInt_t index=0;
//kr0.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1,sec*alpha+shift,x,c,index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
Int_t rc=FollowProlongation(*track, i2);
if (constrain) track->SetBConstrain(1);
else
track->SetBConstrain(0);
track->SetLastPoint(row1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (rc==0 || track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters()) {
MarkSeedFree( seed ); seed = 0;
}
else {
arr->AddLast(track); // track IS seed, don't free seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
}
nin3++;
}
} // if accepted seed
}
if (fDebug>3){
Info("MakeSeeds2","\nSeeding statiistic:\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin3);
}
if (seed) MarkSeedFree( seed );
}
//_____________________________________________________________________________
void AliTPCtracker::MakeSeeds2Dist(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2, Float_t */*cuts[4]*/,
Float_t deltay, Bool_t /*bconstrain*/) {
//-----------------------------------------------------------------
// This function creates track seeds, accounting for distortions - without vertex constraint
//-----------------------------------------------------------------
// cuts[0] - fP4 cut - not applied
// cuts[1] - tan(phi) cut
// cuts[2] - zvertex cut - not applied
// cuts[3] - fP3 cut
Int_t nin0=0;
Int_t nin1=0;
Int_t nin2=0;
Int_t nin3=0;
// Int_t nin4=0;
//Int_t nin5=0;
Double_t alpha=fOuterSec->GetAlpha(), shift=fOuterSec->GetAlphaShift();
// Double_t cs=cos(alpha), sn=sin(alpha);
Int_t row0 = (i1+i2)/2;
Int_t drow = (i1-i2)/2;
const AliTPCtrackerRow& kr0=fSectors[sec][row0];
AliTPCtrackerRow * kr=0;
AliTPCpolyTrack polytrack;
Int_t nclusters=fSectors[sec][row0];
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
Int_t sumused=0;
Int_t cused=0;
Int_t cnused=0;
Int_t rowMax = -1;
//
for (Int_t is=0; is < nclusters; is++) { //LOOP over clusters
Int_t nfound =0;
Int_t nfoundable =0;
for (Int_t iter =1; iter<2; iter++){ //iterations
const AliTPCtrackerRow& krm=fSectors[sec][row0-iter];
const AliTPCtrackerRow& krp=fSectors[sec][row0+iter];
const AliTPCclusterMI * cl= kr0[is];
if (cl->IsDisabled()) {
continue;
}
if (cl->IsUsed(10)) {
cused++;
}
else{
cnused++;
}
Double_t x = cl->GetX(), xDist = x - kr0.GetX(); // approximate X distortion in proximity of cl
// Initialization of the polytrack
nfound =0;
nfoundable =0;
polytrack.Reset();
//
Double_t y0= cl->GetY();
Double_t z0= cl->GetZ();
Float_t erry = 0;
Float_t errz = 0;
Double_t ymax = fSectors->GetMaxY(row0)-kr0.GetDeadZone()-1.5; // RS: watch dead zones
if (deltay>0 && TMath::Abs(ymax-TMath::Abs(y0))> deltay ) continue; // seed only at the edge
erry = (0.5)*cl->GetSigmaY2()/TMath::Sqrt(cl->GetQ())*6;
errz = (0.5)*cl->GetSigmaZ2()/TMath::Sqrt(cl->GetQ())*6;
polytrack.AddPoint(x,y0,z0,erry, errz);
rowMax = row0;
sumused=0;
if (cl->IsUsed(10)) sumused++;
Float_t roady = (5*TMath::Sqrt(cl->GetSigmaY2()+0.2)+1.)*iter;
Float_t roadz = (5*TMath::Sqrt(cl->GetSigmaZ2()+0.2)+1.)*iter;
//
x = krm.GetX() + xDist; // RS: assume distortion at krm is similar to that at kr
AliTPCclusterMI * cl1 = krm.FindNearest(y0,z0,roady,roadz);
if (cl1 && TMath::Abs(ymax-TMath::Abs(y0))) {
erry = (0.5)*cl1->GetSigmaY2()/TMath::Sqrt(cl1->GetQ())*3;
errz = (0.5)*cl1->GetSigmaZ2()/TMath::Sqrt(cl1->GetQ())*3;
if (cl1->IsUsed(10)) sumused++;
//RS: use real cluster X instead of approximately distorted
polytrack.AddPoint(cl1->GetX(),cl1->GetY(),cl1->GetZ(),erry,errz);
}
//
x = krp.GetX() + xDist; // RS: assume distortion at krp is similar to that at kr
AliTPCclusterMI * cl2 = krp.FindNearest(y0,z0,roady,roadz);
if (cl2) {
erry = (0.5)*cl2->GetSigmaY2()/TMath::Sqrt(cl2->GetQ())*3;
errz = (0.5)*cl2->GetSigmaZ2()/TMath::Sqrt(cl2->GetQ())*3;
if (cl2->IsUsed(10)) sumused++;
//RS: use real cluster X instead of approximately distorted
polytrack.AddPoint(cl2->GetX(),cl2->GetY(),cl2->GetZ(),erry,errz);
rowMax = row0+iter;
}
//
if (sumused>0) continue;
nin0++;
polytrack.UpdateParameters();
// follow polytrack
roadz = 1.2;
roady = 1.2;
//
Double_t yn,zn;
nfoundable = polytrack.GetN();
nfound = nfoundable;
//
for (Int_t ddrow = iter+1; ddrow<drow;ddrow++){
Float_t maxdist = 0.8*(1.+3./(ddrow));
for (Int_t delta = -1;delta<=1;delta+=2){
Int_t row = row0+ddrow*delta;
kr = &(fSectors[sec][row]);
Double_t xn = kr->GetX(); //RS: use row X as a first guess about distorted cluster x
Double_t ymax1 = fSectors->GetMaxY(row)-kr->GetDeadZone()-1.5; // RS: watch dead zones
polytrack.GetFitPoint(xn,yn,zn);
double dxn = GetDistortionX(xn, yn, zn, sec, row);
if (TMath::Abs(dxn)>0.1) { //RS: account for distortion
xn += dxn;
polytrack.GetFitPoint(xn,yn,zn);
}
//
if (TMath::Abs(yn)>ymax1) continue; // RS:? watch dead zones
nfoundable++;
AliTPCclusterMI * cln = kr->FindNearest(yn,zn,roady,roadz);
if (cln) {
Float_t dist = TMath::Sqrt( (yn-cln->GetY())*(yn-cln->GetY())+(zn-cln->GetZ())*(zn-cln->GetZ()));
if (dist<maxdist){
/*
erry = (dist+0.3)*cln->GetSigmaY2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
errz = (dist+0.3)*cln->GetSigmaZ2()/TMath::Sqrt(cln->GetQ())*(1.+1./(ddrow));
if (cln->IsUsed(10)) {
// printf("used\n");
sumused++;
erry*=2;
errz*=2;
}
*/
erry=0.1;
errz=0.1;
polytrack.AddPoint(xn,cln->GetY(),cln->GetZ(),erry, errz);
if (row>rowMax) rowMax = row;
nfound++;
}
}
}
if ( (sumused>3) || (sumused>0.5*nfound) || (nfound<0.6*nfoundable)) break;
polytrack.UpdateParameters();
}
}
if ( (sumused>3) || (sumused>0.5*nfound)) {
//printf("sumused %d\n",sumused);
continue;
}
nin1++;
Double_t dy,dz;
polytrack.GetFitDerivation(kr0.GetX(),dy,dz); // RS: Note: derivative is at ideal row X
AliTPCpolyTrack track2;
polytrack.Refit(track2,0.5+TMath::Abs(dy)*0.3,0.4+TMath::Abs(dz)*0.3);
if (track2.GetN()<0.5*nfoundable) continue;
nin2++;
if ((nfound>0.6*nfoundable) &&( nfoundable>0.4*(i1-i2))) {
//
// test seed with and without constrain
for (Int_t constrain=0; constrain<=0;constrain++){
// add polytrack candidate
Double_t x[5], c[15];
Double_t x1,x2,x3,y1,y2,y3,z1,z2,z3;
track2.GetBoundaries(x3,x1);
x2 = (x1+x3)/2.;
track2.GetFitPoint(x1,y1,z1);
track2.GetFitPoint(x2,y2,z2);
track2.GetFitPoint(x3,y3,z3);
//
//is track pointing to the vertex ?
Double_t x0,y0,z0;
x0=0;
polytrack.GetFitPoint(x0,y0,z0);
if (constrain) {
x2 = x3;
y2 = y3;
z2 = z3;
x3 = 0;
y3 = 0;
z3 = 0;
}
x[0]=y1;
x[1]=z1;
x[4]=F1(x1,y1,x2,y2,x3,y3);
// if (TMath::Abs(x[4]) >= cuts[0]) continue; //
x[2]=F2(x1,y1,x2,y2,x3,y3);
//if (TMath::Abs(x[4]*x1-x[2]) >= cuts[1]) continue;
//x[3]=F3(x1,y1,x2,y2,z1,z2);
x[3]=F3n(x1,y1,x3,y3,z1,z3,x[4]);
//if (TMath::Abs(x[3]) > cuts[3]) continue;
Double_t sy =0.1, sz =0.1;
Double_t sy1=0.02, sz1=0.02;
Double_t sy2=0.02, sz2=0.02;
Double_t sy3=0.02;
if (constrain){
sy3=25000*x[4]*x[4]+0.1, sy=0.1, sz=0.1;
}
Double_t f40=(F1(x1,y1+sy,x2,y2,x3,y3)-x[4])/sy;
Double_t f42=(F1(x1,y1,x2,y2+sy,x3,y3)-x[4])/sy;
Double_t f43=(F1(x1,y1,x2,y2,x3,y3+sy)-x[4])/sy;
Double_t f20=(F2(x1,y1+sy,x2,y2,x3,y3)-x[2])/sy;
Double_t f22=(F2(x1,y1,x2,y2+sy,x3,y3)-x[2])/sy;
Double_t f23=(F2(x1,y1,x2,y2,x3,y3+sy)-x[2])/sy;
Double_t f30=(F3(x1,y1+sy,x3,y3,z1,z3)-x[3])/sy;
Double_t f31=(F3(x1,y1,x3,y3,z1+sz,z3)-x[3])/sz;
Double_t f32=(F3(x1,y1,x3,y3+sy,z1,z3)-x[3])/sy;
Double_t f34=(F3(x1,y1,x3,y3,z1,z3+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
//Int_t row1 = GetRowNumber(x1); // RS: this is now substituted by rowMax
UInt_t index=0;
//kr0.GetIndex(is);
if (seed) {MarkSeedFree( seed ); seed = 0;}
AliTPCseed *track = seed = new( NextFreeSeed() ) AliTPCseed(x1,sec*alpha+shift,x,c,index);
seed->SetPoolID(fLastSeedID);
track->SetIsSeeding(kTRUE);
Int_t rc=FollowProlongation(*track, i2);
if (constrain) track->SetBConstrain(1);
else
track->SetBConstrain(0);
track->SetLastPoint(rowMax); //row1+fInnerSec->GetNRows()); // first cluster in track position
track->SetFirstPoint(track->GetLastPoint());
if (rc==0 || track->GetNumberOfClusters()<(i1-i2)*0.5 ||
track->GetNumberOfClusters() < track->GetNFoundable()*0.6 ||
track->GetNShared()>0.4*track->GetNumberOfClusters()) {
MarkSeedFree( seed ); seed = 0;
}
else {
arr->AddLast(track); // track IS seed, don't free seed
seed = new( NextFreeSeed() ) AliTPCseed;
seed->SetPoolID(fLastSeedID);
}
nin3++;
}
} // if accepted seed
}
if (fDebug>3){
Info("MakeSeeds2","\nSeeding statiistic:\t%d\t%d\t%d\t%d",nin0,nin1,nin2,nin3);
}
if (seed) MarkSeedFree( seed );
}
AliTPCseed *AliTPCtracker::MakeSeed(AliTPCseed *const track, Float_t r0, Float_t r1, Float_t r2)
{
//
//
//reseed using track points
Int_t p0 = int(r0*track->GetNumberOfClusters()); // point 0
Int_t p1 = int(r1*track->GetNumberOfClusters());
Int_t p2 = int(r2*track->GetNumberOfClusters()); // last point
Int_t pp2=0;
Double_t x0[3],x1[3],x2[3];
for (Int_t i=0;i<3;i++){
x0[i]=-1;
x1[i]=-1;
x2[i]=-1;
}
// find track position at given ratio of the length
Int_t sec0=0, sec1=0, sec2=0;
Int_t index=-1;
Int_t clindex;
for (Int_t i=0;i<kMaxRow;i++){
if (track->GetClusterIndex2(i)>=0){
index++;
const AliTPCTrackerPoints::Point *trpoint =track->GetTrackPoint(i);
if ( (index<p0) || x0[0]<0 ){
if (trpoint->GetX()>1){
clindex = track->GetClusterIndex2(i);
if (clindex >= 0){
x0[0] = trpoint->GetX();
x0[1] = trpoint->GetY();
x0[2] = trpoint->GetZ();
sec0 = ((clindex&0xff000000)>>24)%18;
}
}
}
if ( (index<p1) &&(trpoint->GetX()>1)){
clindex = track->GetClusterIndex2(i);
if (clindex >= 0){
x1[0] = trpoint->GetX();
x1[1] = trpoint->GetY();
x1[2] = trpoint->GetZ();
sec1 = ((clindex&0xff000000)>>24)%18;
}
}
if ( (index<p2) &&(trpoint->GetX()>1)){
clindex = track->GetClusterIndex2(i);
if (clindex >= 0){
x2[0] = trpoint->GetX();
x2[1] = trpoint->GetY();
x2[2] = trpoint->GetZ();
sec2 = ((clindex&0xff000000)>>24)%18;
pp2 = i;
}
}
}
}
Double_t alpha, cs,sn, xx2,yy2;
//
alpha = (sec1-sec2)*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= x1[0]*cs-x1[1]*sn;
yy2= x1[0]*sn+x1[1]*cs;
x1[0] = xx2;
x1[1] = yy2;
//
alpha = (sec0-sec2)*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= x0[0]*cs-x0[1]*sn;
yy2= x0[0]*sn+x0[1]*cs;
x0[0] = xx2;
x0[1] = yy2;
//
//
//
Double_t x[5],c[15];
//
x[0]=x2[1];
x[1]=x2[2];
x[4]=F1(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]);
// if (x[4]>1) return 0;
x[2]=F2(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]);
x[3]=F3n(x2[0],x2[1],x0[0],x0[1],x2[2],x0[2],x[4]);
//if (TMath::Abs(x[3]) > 2.2) return 0;
//if (TMath::Abs(x[2]) > 1.99) return 0;
//
Double_t sy =0.1, sz =0.1;
//
Double_t sy1=0.02+track->GetSigmaY2(), sz1=0.02+track->GetSigmaZ2();
Double_t sy2=0.01+track->GetSigmaY2(), sz2=0.01+track->GetSigmaZ2();
Double_t sy3=0.01+track->GetSigmaY2();
//
Double_t f40=(F1(x2[0],x2[1]+sy,x1[0],x1[1],x0[0],x0[1])-x[4])/sy;
Double_t f42=(F1(x2[0],x2[1],x1[0],x1[1]+sy,x0[0],x0[1])-x[4])/sy;
Double_t f43=(F1(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]+sy)-x[4])/sy;
Double_t f20=(F2(x2[0],x2[1]+sy,x1[0],x1[1],x0[0],x0[1])-x[2])/sy;
Double_t f22=(F2(x2[0],x2[1],x1[0],x1[1]+sy,x0[0],x0[1])-x[2])/sy;
Double_t f23=(F2(x2[0],x2[1],x1[0],x1[1],x0[0],x0[1]+sy)-x[2])/sy;
//
Double_t f30=(F3(x2[0],x2[1]+sy,x0[0],x0[1],x2[2],x0[2])-x[3])/sy;
Double_t f31=(F3(x2[0],x2[1],x0[0],x0[1],x2[2]+sz,x0[2])-x[3])/sz;
Double_t f32=(F3(x2[0],x2[1],x0[0],x0[1]+sy,x2[2],x0[2])-x[3])/sy;
Double_t f34=(F3(x2[0],x2[1],x0[0],x0[1],x2[2],x0[2]+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// Int_t row1 = fSectors->GetRowNumber(x2[0]);
AliTPCseed *seed = new( NextFreeSeed() ) AliTPCseed(x2[0], sec2*fSectors->GetAlpha()+fSectors->GetAlphaShift(), x, c, 0);
seed->SetPoolID(fLastSeedID);
// Double_t y0,z0,y1,z1, y2,z2;
//seed->GetProlongation(x0[0],y0,z0);
// seed->GetProlongation(x1[0],y1,z1);
//seed->GetProlongation(x2[0],y2,z2);
// seed =0;
seed->SetLastPoint(pp2);
seed->SetFirstPoint(pp2);
return seed;
}
AliTPCseed *AliTPCtracker::ReSeed(const AliTPCseed *track, Float_t r0, Float_t r1, Float_t r2)
{
//
//
//reseed using founded clusters
//
// Find the number of clusters
Int_t nclusters = 0;
for (Int_t irow=0;irow<kMaxRow;irow++){
if (track->GetClusterIndex(irow)>0) nclusters++;
}
//
Int_t ipos[3];
ipos[0] = TMath::Max(int(r0*nclusters),0); // point 0 cluster
ipos[1] = TMath::Min(int(r1*nclusters),nclusters-1); //
ipos[2] = TMath::Min(int(r2*nclusters),nclusters-1); // last point
//
//
Double_t xyz[3][3]={{0}};
Int_t row[3]={0},sec[3]={0,0,0};
//
// find track row position at given ratio of the length
Int_t index=-1;
for (Int_t irow=0;irow<kMaxRow;irow++){
if (track->GetClusterIndex2(irow)<0) continue;
index++;
for (Int_t ipoint=0;ipoint<3;ipoint++){
if (index<=ipos[ipoint]) row[ipoint] = irow;
}
}
//
//Get cluster and sector position
for (Int_t ipoint=0;ipoint<3;ipoint++){
Int_t clindex = track->GetClusterIndex2(row[ipoint]);
AliTPCclusterMI * cl = clindex<0 ? 0:GetClusterMI(clindex);
if (cl==0) {
//Error("Bug\n");
// AliTPCclusterMI * cl = GetClusterMI(clindex);
return 0;
}
sec[ipoint] = ((clindex&0xff000000)>>24)%18;
xyz[ipoint][0] = GetXrow(row[ipoint]);
xyz[ipoint][1] = cl->GetY();
xyz[ipoint][2] = cl->GetZ();
}
//
//
// Calculate seed state vector and covariance matrix
Double_t alpha, cs,sn, xx2,yy2;
//
alpha = (sec[1]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[1][0]*cs-xyz[1][1]*sn;
yy2= xyz[1][0]*sn+xyz[1][1]*cs;
xyz[1][0] = xx2;
xyz[1][1] = yy2;
//
alpha = (sec[0]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[0][0]*cs-xyz[0][1]*sn;
yy2= xyz[0][0]*sn+xyz[0][1]*cs;
xyz[0][0] = xx2;
xyz[0][1] = yy2;
//
//
//
Double_t x[5],c[15];
//
x[0]=xyz[2][1];
x[1]=xyz[2][2];
x[4]=F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[2]=F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[3]=F3n(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2],x[4]);
//
Double_t sy =0.1, sz =0.1;
//
Double_t sy1=0.2, sz1=0.2;
Double_t sy2=0.2, sz2=0.2;
Double_t sy3=0.2;
//
Double_t f40=(F1(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f42=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f43=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[4])/sy;
Double_t f20=(F2(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f22=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f23=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[2])/sy;
//
Double_t f30=(F3(xyz[2][0],xyz[2][1]+sy,xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f31=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2]+sz,xyz[0][2])-x[3])/sz;
Double_t f32=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1]+sy,xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f34=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2]+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// Int_t row1 = fSectors->GetRowNumber(xyz[2][0]);
AliTPCseed *seed=new( NextFreeSeed() ) AliTPCseed(xyz[2][0], sec[2]*fSectors->GetAlpha()+fSectors->GetAlphaShift(), x, c, 0);
seed->SetPoolID(fLastSeedID);
seed->SetLastPoint(row[2]);
seed->SetFirstPoint(row[2]);
return seed;
}
AliTPCseed *AliTPCtracker::ReSeed(AliTPCseed *track,Int_t r0, Bool_t forward)
{
//
//
//reseed using founded clusters
//
Double_t xyz[3][3];
Int_t row[3]={0,0,0};
Int_t sec[3]={0,0,0};
//
// forward direction
if (forward){
for (Int_t irow=r0;irow<kMaxRow;irow++){
if (track->GetClusterIndex(irow)>0){
row[0] = irow;
break;
}
}
for (Int_t irow=kMaxRow;irow>r0;irow--){
if (track->GetClusterIndex(irow)>0){
row[2] = irow;
break;
}
}
for (Int_t irow=row[2]-15;irow>row[0];irow--){
if (track->GetClusterIndex(irow)>0){
row[1] = irow;
break;
}
}
//
}
if (!forward){
for (Int_t irow=0;irow<r0;irow++){
if (track->GetClusterIndex(irow)>0){
row[0] = irow;
break;
}
}
for (Int_t irow=r0;irow>0;irow--){
if (track->GetClusterIndex(irow)>0){
row[2] = irow;
break;
}
}
for (Int_t irow=row[2]-15;irow>row[0];irow--){
if (track->GetClusterIndex(irow)>0){
row[1] = irow;
break;
}
}
}
//
if ((row[2]-row[0])<20) return 0;
if (row[1]==0) return 0;
//
//
//Get cluster and sector position
for (Int_t ipoint=0;ipoint<3;ipoint++){
Int_t clindex = track->GetClusterIndex2(row[ipoint]);
AliTPCclusterMI * cl = clindex<0 ? 0:GetClusterMI(clindex);
if (cl==0) {
//Error("Bug\n");
// AliTPCclusterMI * cl = GetClusterMI(clindex);
return 0;
}
sec[ipoint] = ((clindex&0xff000000)>>24)%18;
xyz[ipoint][0] = GetXrow(row[ipoint]);
const AliTPCTrackerPoints::Point * point = track->GetTrackPoint(row[ipoint]);
if (point&&ipoint<2){
//
xyz[ipoint][1] = point->GetY();
xyz[ipoint][2] = point->GetZ();
}
else{
xyz[ipoint][1] = cl->GetY();
xyz[ipoint][2] = cl->GetZ();
}
}
//
//
//
//
// Calculate seed state vector and covariance matrix
Double_t alpha, cs,sn, xx2,yy2;
//
alpha = (sec[1]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[1][0]*cs-xyz[1][1]*sn;
yy2= xyz[1][0]*sn+xyz[1][1]*cs;
xyz[1][0] = xx2;
xyz[1][1] = yy2;
//
alpha = (sec[0]-sec[2])*fSectors->GetAlpha();
cs = TMath::Cos(alpha);
sn = TMath::Sin(alpha);
xx2= xyz[0][0]*cs-xyz[0][1]*sn;
yy2= xyz[0][0]*sn+xyz[0][1]*cs;
xyz[0][0] = xx2;
xyz[0][1] = yy2;
//
//
//
Double_t x[5],c[15];
//
x[0]=xyz[2][1];
x[1]=xyz[2][2];
x[4]=F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[2]=F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]);
x[3]=F3n(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2],x[4]);
//
Double_t sy =0.1, sz =0.1;
//
Double_t sy1=0.2, sz1=0.2;
Double_t sy2=0.2, sz2=0.2;
Double_t sy3=0.2;
//
Double_t f40=(F1(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f42=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[4])/sy;
Double_t f43=(F1(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[4])/sy;
Double_t f20=(F2(xyz[2][0],xyz[2][1]+sy,xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f22=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1]+sy,xyz[0][0],xyz[0][1])-x[2])/sy;
Double_t f23=(F2(xyz[2][0],xyz[2][1],xyz[1][0],xyz[1][1],xyz[0][0],xyz[0][1]+sy)-x[2])/sy;
//
Double_t f30=(F3(xyz[2][0],xyz[2][1]+sy,xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f31=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2]+sz,xyz[0][2])-x[3])/sz;
Double_t f32=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1]+sy,xyz[2][2],xyz[0][2])-x[3])/sy;
Double_t f34=(F3(xyz[2][0],xyz[2][1],xyz[0][0],xyz[0][1],xyz[2][2],xyz[0][2]+sz)-x[3])/sz;
c[0]=sy1;
c[1]=0.; c[2]=sz1;
c[3]=f20*sy1; c[4]=0.; c[5]=f20*sy1*f20+f22*sy2*f22+f23*sy3*f23;
c[6]=f30*sy1; c[7]=f31*sz1; c[8]=f30*sy1*f20+f32*sy2*f22;
c[9]=f30*sy1*f30+f31*sz1*f31+f32*sy2*f32+f34*sz2*f34;
c[10]=f40*sy1; c[11]=0.; c[12]=f40*sy1*f20+f42*sy2*f22+f43*sy3*f23;
c[13]=f30*sy1*f40+f32*sy2*f42;
c[14]=f40*sy1*f40+f42*sy2*f42+f43*sy3*f43;
// Int_t row1 = fSectors->GetRowNumber(xyz[2][0]);
AliTPCseed *seed=new( NextFreeSeed() ) AliTPCseed(xyz[2][0], sec[2]*fSectors->GetAlpha()+fSectors->GetAlphaShift(), x, c, 0);
seed->SetPoolID(fLastSeedID);
seed->SetLastPoint(row[2]);
seed->SetFirstPoint(row[2]);
for (Int_t i=row[0];i<row[2];i++){
seed->SetClusterIndex(i, track->GetClusterIndex(i));
}
return seed;
}
void AliTPCtracker::FindMultiMC(const TObjArray * array, AliESDEvent */*esd*/, Int_t iter)
{
//
// find multi tracks - THIS FUNCTION IS ONLY FOR DEBUG PURPOSES
// USES MC LABELS
// Use AliTPCReconstructor::StreamLevel()& kStreamFindMultiMC if you want to tune parameters - cuts
//
// Two reasons to have multiple find tracks
// 1. Curling tracks can be find more than once
// 2. Splitted tracks
// a.) Multiple seeding to increase tracking efficiency - (~ 100% reached)
// b.) Edge effect on the sector boundaries
//
//
// Algorithm done in 2 phases - because of CPU consumption
// it is n^2 algorithm - for lead-lead 20000x20000 combination are investigated
//
// Algorihm for curling tracks sign:
// 1 phase -makes a very rough fast cuts to minimize combinatorics
// a.) opposite sign
// b.) one of the tracks - not pointing to the primary vertex -
// c.) delta tan(theta)
// d.) delta phi
// 2 phase - calculates DCA between tracks - time consument
//
// fast cuts
//
// General cuts - for splitted tracks and for curling tracks
//
const Float_t kMaxdPhi = 0.2; // maximal distance in phi
//
// Curling tracks cuts
//
//
//
//
Int_t nentries = array->GetEntriesFast();
if (!fHelixPool) fHelixPool = new TClonesArray("AliHelix",nentries+50);
fHelixPool->Clear();
TClonesArray& helixes = *fHelixPool;
Float_t xm[nentries];
Float_t dz0[nentries];
Float_t dz1[nentries];
//
//
TStopwatch timer;
timer.Start();
//
// Find track COG in x direction - point with best defined parameters
//
for (Int_t i=0;i<nentries;i++){
AliTPCseed* track = (AliTPCseed*)array->At(i);
if (!track) continue;
track->SetCircular(0);
new (helixes[i]) AliHelix(*track);
Int_t ncl=0;
xm[i]=0;
Float_t dz[2];
track->GetDZ(GetX(),GetY(),GetZ(),GetBz(),dz);
dz0[i]=dz[0];
dz1[i]=dz[1];
for (Int_t icl=0; icl<kMaxRow; icl++){
int tpcindex= track->GetClusterIndex2(icl);
const AliTPCclusterMI * cl = (tpcindex<0) ? 0:GetClusterMI(tpcindex);
//RS AliTPCclusterMI * cl = track->GetClusterPointer(icl);
if (cl) {
xm[i]+=cl->GetX();
ncl++;
}
}
if (ncl>0) xm[i]/=Float_t(ncl);
}
//
for (Int_t i0=0;i0<nentries;i0++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i0);
if (!track0) continue;
AliHelix* hlxi0 = (AliHelix*)helixes[i0];
Float_t xc0 = hlxi0->GetHelix(6);
Float_t yc0 = hlxi0->GetHelix(7);
Float_t r0 = hlxi0->GetHelix(8);
Float_t rc0 = TMath::Sqrt(xc0*xc0+yc0*yc0);
Float_t fi0 = TMath::ATan2(yc0,xc0);
for (Int_t i1=i0+1;i1<nentries;i1++){
AliTPCseed * track1 = (AliTPCseed*)array->At(i1);
if (!track1) continue;
Int_t lab0=track0->GetLabel();
Int_t lab1=track1->GetLabel();
if (TMath::Abs(lab0)!=TMath::Abs(lab1)) continue;
//
AliHelix* hlxi1 = (AliHelix*)helixes[i1];
Float_t xc1 = hlxi1->GetHelix(6);
Float_t yc1 = hlxi1->GetHelix(7);
Float_t r1 = hlxi1->GetHelix(8);
Float_t rc1 = TMath::Sqrt(xc1*xc1+yc1*yc1);
Float_t fi1 = TMath::ATan2(yc1,xc1);
//
Float_t dfi = fi0-fi1;
//
//
if (dfi>1.5*TMath::Pi()) dfi-=TMath::Pi(); // take care about edge effect
if (dfi<-1.5*TMath::Pi()) dfi+=TMath::Pi(); //
if (TMath::Abs(dfi)>kMaxdPhi&&hlxi0->GetHelix(4)*hlxi1->GetHelix(4)<0){
//
// if short tracks with undefined sign
fi1 = -TMath::ATan2(yc1,-xc1);
dfi = fi0-fi1;
}
Float_t dtheta = TMath::Abs(track0->GetTgl()-track1->GetTgl())<TMath::Abs(track0->GetTgl()+track1->GetTgl())? track0->GetTgl()-track1->GetTgl():track0->GetTgl()+track1->GetTgl();
//
// debug stream to tune "fast cuts"
//
Double_t dist[3]; // distance at X
Double_t mdist[3]={0,0,0}; // mean distance X+-40cm
track0->GetDistance(track1,0.5*(xm[i0]+xm[i1])-40.,dist,AliTracker::GetBz());
for (Int_t i=0;i<3;i++) mdist[i]+=TMath::Abs(dist[i]);
track0->GetDistance(track1,0.5*(xm[i0]+xm[i1])+40.,dist,AliTracker::GetBz());
for (Int_t i=0;i<3;i++) mdist[i]+=TMath::Abs(dist[i]);
track0->GetDistance(track1,0.5*(xm[i0]+xm[i1]),dist,AliTracker::GetBz());
for (Int_t i=0;i<3;i++) mdist[i]+=TMath::Abs(dist[i]);
for (Int_t i=0;i<3;i++) mdist[i]*=0.33333;
Float_t sum =0;
Float_t sums=0;
for (Int_t icl=0; icl<kMaxRow; icl++){
Int_t tpcindex0 = track0->GetClusterIndex2(icl);
Int_t tpcindex1 = track1->GetClusterIndex2(icl);
//RS AliTPCclusterMI * cl0 = track0->GetClusterPointer(icl);
//RS AliTPCclusterMI * cl1 = track1->GetClusterPointer(icl);
//RS if (cl0&&cl1) {
if (tpcindex0>=0 && tpcindex1>=0) {
sum++;
if (tpcindex0==tpcindex1) sums++; //RS if (cl0==cl1) sums++;
}
}
//
if ((AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC)>0) { // flag: stream MC infomation about the multiple find track (ONLY for MC data)
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Multi"<<
"iter="<<iter<<
"lab0="<<lab0<<
"lab1="<<lab1<<
"Tr0.="<<track0<< // seed0
"Tr1.="<<track1<< // seed1
"h0.="<<hlxi0<<
"h1.="<<hlxi1<<
//
"sum="<<sum<< //the sum of rows with cl in both
"sums="<<sums<< //the sum of shared clusters
"xm0="<<xm[i0]<< // the center of track
"xm1="<<xm[i1]<< // the x center of track
// General cut variables
"dfi="<<dfi<< // distance in fi angle
"dtheta="<<dtheta<< // distance int theta angle
//
"dz00="<<dz0[i0]<<
"dz01="<<dz0[i1]<<
"dz10="<<dz1[i1]<<
"dz11="<<dz1[i1]<<
"dist0="<<dist[0]<< //distance x
"dist1="<<dist[1]<< //distance y
"dist2="<<dist[2]<< //distance z
"mdist0="<<mdist[0]<< //distance x
"mdist1="<<mdist[1]<< //distance y
"mdist2="<<mdist[2]<< //distance z
//
"r0="<<r0<<
"rc0="<<rc0<<
"fi0="<<fi0<<
"fi1="<<fi1<<
"r1="<<r1<<
"rc1="<<rc1<<
"\n";
}
}
}
if (fHelixPool) fHelixPool->Clear();
// delete [] helixes; // RS moved to stack
// delete [] xm;
// delete [] dz0;
// delete [] dz1;
if (AliTPCReconstructor::StreamLevel()>0) {
AliInfo("Time for curling tracks removal DEBUGGING MC");
timer.Print();
}
}
void AliTPCtracker::FindSplitted(TObjArray * array, AliESDEvent */*esd*/, Int_t /*iter*/){
//
// Find Splitted tracks and remove the one with worst quality
// Corresponding debug streamer to tune selections - "Splitted2"
// Algorithm:
// 0. Sort tracks according quality
// 1. Propagate the tracks to the reference radius
// 2. Double_t loop to select close tracks (only to speed up process)
// 3. Calculate cluster overlap ratio - and remove the track if bigger than a threshold
// 4. Delete temporary parameters
//
const Double_t xref=GetXrow(63); // reference radius -IROC/OROC boundary
// rough cuts
const Double_t kCutP1=10; // delta Z cut 10 cm
const Double_t kCutP2=0.15; // delta snp(fi) cut 0.15
const Double_t kCutP3=0.15; // delta tgl(theta) cut 0.15
const Double_t kCutAlpha=0.15; // delta alpha cut
Int_t firstpoint = 0;
Int_t lastpoint = kMaxRow;
//
Int_t nentries = array->GetEntriesFast();
if (!fETPPool) fETPPool = new TClonesArray("AliExternalTrackParam",nentries+50);
else fETPPool->Clear();
TClonesArray ¶ms = *fETPPool;
//
//
TStopwatch timer;
timer.Start();
//
//0. Sort tracks according quality
//1. Propagate the ext. param to reference radius
Int_t nseed = array->GetEntriesFast();
if (nseed<=0) return;
Float_t quality[nseed];
Int_t indexes[nseed];
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)array->UncheckedAt(i);
if (!pt){
quality[i]=-1;
continue;
}
pt->UpdatePoints(); //select first last max dens points
Float_t * points = pt->GetPoints();
if (points[3]<0.8) quality[i] =-1;
quality[i] = (points[2]-points[0])+pt->GetNumberOfClusters();
//prefer high momenta tracks if overlaps
quality[i] *= TMath::Sqrt(TMath::Abs(pt->Pt())+0.5);
AliExternalTrackParam* parI = new (params[i]) AliExternalTrackParam(*pt);
// params[i]=(*pt);
AliTracker::PropagateTrackParamOnlyToBxByBz(parI,xref,5.,kTRUE);
// AliTracker::PropagateTrackToBxByBz(parI,xref,pt->GetMass(),1.,kTRUE); //RS What is the point of 2nd propagation
}
TMath::Sort(nseed,quality,indexes);
//
// 3. Loop over pair of tracks
//
for (Int_t i0=0; i0<nseed; i0++) {
Int_t index0=indexes[i0];
if (!(array->UncheckedAt(index0))) continue;
AliTPCseed *s1 = (AliTPCseed*)array->UncheckedAt(index0);
if (!s1->IsActive()) continue;
AliExternalTrackParam &par0=*(AliExternalTrackParam*)params[index0];
for (Int_t i1=i0+1; i1<nseed; i1++) {
Int_t index1=indexes[i1];
if (!(array->UncheckedAt(index1))) continue;
AliTPCseed *s2 = (AliTPCseed*)array->UncheckedAt(index1);
if (!s2->IsActive()) continue;
if (s2->GetKinkIndexes()[0]!=0)
if (s2->GetKinkIndexes()[0] == -s1->GetKinkIndexes()[0]) continue;
AliExternalTrackParam &par1=*(AliExternalTrackParam*)params[index1];
if (TMath::Abs(par0.GetParameter()[3]-par1.GetParameter()[3])>kCutP3) continue;
if (TMath::Abs(par0.GetParameter()[1]-par1.GetParameter()[1])>kCutP1) continue;
if (TMath::Abs(par0.GetParameter()[2]-par1.GetParameter()[2])>kCutP2) continue;
Double_t dAlpha= TMath::Abs(par0.GetAlpha()-par1.GetAlpha());
if (dAlpha>TMath::Pi()) dAlpha-=TMath::Pi();
if (TMath::Abs(dAlpha)>kCutAlpha) continue;
//
Int_t sumShared=0;
Int_t nall0=0;
Int_t nall1=0;
Int_t firstShared=lastpoint, lastShared=firstpoint;
Int_t firstRow=lastpoint, lastRow=firstpoint;
//
// for (Int_t i=firstpoint;i<lastpoint;i++){
// if (s1->GetClusterIndex2(i)>0) nall0++;
// if (s2->GetClusterIndex2(i)>0) nall1++;
// if (s1->GetClusterIndex2(i)>0 && s2->GetClusterIndex2(i)>0) {
// if (i<firstRow) firstRow=i;
// if (i>lastRow) lastRow=i;
// }
// if ( (s1->GetClusterIndex2(i))==(s2->GetClusterIndex2(i)) && s1->GetClusterIndex2(i)>0) {
// if (i<firstShared) firstShared=i;
// if (i>lastShared) lastShared=i;
// sumShared++;
// }
// }
//
// RS: faster version + fix(?) ">" -> ">="
for (Int_t i=firstpoint;i<lastpoint;i++){
int ind1=s1->GetClusterIndex2(i),ind2=s2->GetClusterIndex2(i);
if (ind1>=0) nall0++; // RS: ">" -> ">="
if (ind2>=0) nall1++;
if (ind1>=0 && ind2>=0) {
if (i<firstRow) firstRow=i;
if (i>lastRow) lastRow=i;
}
if ( (ind1==ind2) && ind1>=0) {
if (i<firstShared) firstShared=i;
if (i>lastShared) lastShared=i;
sumShared++;
}
}
Double_t ratio0 = Float_t(sumShared)/Float_t(TMath::Min(nall0+1,nall1+1));
Double_t ratio1 = Float_t(sumShared)/Float_t(TMath::Max(nall0+1,nall1+1));
if ((AliTPCReconstructor::StreamLevel()&kStreamSplitted2)>0){ // flag:stream information about discarded TPC tracks pair algorithm
TTreeSRedirector &cstream = *fDebugStreamer;
Int_t n0=s1->GetNumberOfClusters();
Int_t n1=s2->GetNumberOfClusters();
Int_t n0F=s1->GetNFoundable();
Int_t n1F=s2->GetNFoundable();
Int_t lab0=s1->GetLabel();
Int_t lab1=s2->GetLabel();
cstream<<"Splitted2"<< // flag:stream information about discarded TPC tracks pair algorithm
"iter="<<fIteration<<
"lab0="<<lab0<< // MC label if exist
"lab1="<<lab1<< // MC label if exist
"index0="<<index0<<
"index1="<<index1<<
"ratio0="<<ratio0<< // shared ratio
"ratio1="<<ratio1<< // shared ratio
"p0.="<<&par0<< // track parameters
"p1.="<<&par1<<
"s0.="<<s1<< // full seed
"s1.="<<s2<<
"n0="<<n0<< // number of clusters track 0
"n1="<<n1<< // number of clusters track 1
"nall0="<<nall0<< // number of clusters track 0
"nall1="<<nall1<< // number of clusters track 1
"n0F="<<n0F<< // number of findable
"n1F="<<n1F<< // number of findable
"shared="<<sumShared<< // number of shared clusters
"firstS="<<firstShared<< // first and the last shared row
"lastS="<<lastShared<<
"firstRow="<<firstRow<< // first and the last row with cluster
"lastRow="<<lastRow<< //
"\n";
}
//
// remove track with lower quality
//
if (ratio0>AliTPCReconstructor::GetRecoParam()->GetCutSharedClusters(0) ||
ratio1>AliTPCReconstructor::GetRecoParam()->GetCutSharedClusters(1)){
//
//
//
MarkSeedFree( array->RemoveAt(index1) );
}
}
}
//
// 4. Delete temporary array
//
if (fETPPool) fETPPool->Clear();
// delete [] params; // RS moved to stack
// delete [] quality;
// delete [] indexes;
}
void AliTPCtracker::FindCurling(const TObjArray * array, AliESDEvent */*esd*/, Int_t iter)
{
//
// find Curling tracks
// Use AliTPCReconstructor::StreamLevel()&kStreamFindCurling if you want to tune parameters - cuts
//
//
// Algorithm done in 2 phases - because of CPU consumption
// it is n^2 algorithm - for lead-lead 20000x20000 combination are investigated
// see detal in MC part what can be used to cut
//
//
//
const Float_t kMaxC = 400; // maximal curvature to of the track
const Float_t kMaxdTheta = 0.15; // maximal distance in theta
const Float_t kMaxdPhi = 0.15; // maximal distance in phi
const Float_t kPtRatio = 0.3; // ratio between pt
const Float_t kMinDCAR = 2.; // distance to the primary vertex in r - see cpipe cut
//
// Curling tracks cuts
//
//
const Float_t kMaxDeltaRMax = 40; // distance in outer radius
const Float_t kMaxDeltaRMin = 5.; // distance in lower radius - see cpipe cut
const Float_t kMinAngle = 2.9; // angle between tracks
const Float_t kMaxDist = 5; // biggest distance
//
// The cuts can be tuned using the "MC information stored in Multi tree ==> see FindMultiMC
/*
Fast cuts:
TCut csign("csign","Tr0.fP[4]*Tr1.fP[4]<0"); //opposite sign
TCut cmax("cmax","abs(Tr0.GetC())>1/400");
TCut cda("cda","sqrt(dtheta^2+dfi^2)<0.15");
TCut ccratio("ccratio","abs((Tr0.fP[4]+Tr1.fP[4])/(abs(Tr0.fP[4])+abs(Tr1.fP[4])))<0.3");
TCut cpipe("cpipe", "min(abs(r0-rc0),abs(r1-rc1))>5");
//
TCut cdrmax("cdrmax","abs(abs(rc0+r0)-abs(rc1+r1))<40")
TCut cdrmin("cdrmin","abs(abs(rc0+r0)-abs(rc1+r1))<10")
//
Multi->Draw("dfi","iter==0"+csign+cmax+cda+ccratio); ~94% of curling tracks fulfill
Multi->Draw("min(abs(r0-rc0),abs(r1-rc1))","iter==0&&abs(lab1)==abs(lab0)"+csign+cmax+cda+ccratio+cpipe+cdrmin+cdrmax); //80%
//
Curling2->Draw("dfi","iter==0&&abs(lab0)==abs(lab1)"+csign+cmax+cdtheta+cdfi+ccratio)
*/
//
//
//
Int_t nentries = array->GetEntriesFast();
if (!fHelixPool) fHelixPool = new TClonesArray("AliHelix",nentries+100);
fHelixPool->Clear();
TClonesArray& helixes = *fHelixPool;
for (Int_t i=0;i<nentries;i++){
AliTPCseed* track = (AliTPCseed*)array->At(i);
if (!track) continue;
track->SetCircular(0);
new (helixes[i]) AliHelix(*track);
}
//
//
TStopwatch timer;
timer.Start();
Double_t phase[2][2]={{0,0},{0,0}},radius[2]={0,0};
//
// Find tracks
//
//
for (Int_t i0=0;i0<nentries;i0++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i0);
if (!track0) continue;
if (TMath::Abs(track0->GetC())<1/kMaxC) continue;
AliHelix* hlxi0 = (AliHelix*)helixes[i0];
Float_t xc0 = hlxi0->GetHelix(6);
Float_t yc0 = hlxi0->GetHelix(7);
Float_t r0 = hlxi0->GetHelix(8);
Float_t rc0 = TMath::Sqrt(xc0*xc0+yc0*yc0);
Float_t fi0 = TMath::ATan2(yc0,xc0);
for (Int_t i1=i0+1;i1<nentries;i1++){
AliTPCseed * track1 = (AliTPCseed*)array->At(i1);
if (!track1) continue;
if (TMath::Abs(track1->GetC())<1/kMaxC) continue;
AliHelix* hlxi1 = (AliHelix*)helixes[i1];
Float_t xc1 = hlxi1->GetHelix(6);
Float_t yc1 = hlxi1->GetHelix(7);
Float_t r1 = hlxi1->GetHelix(8);
Float_t rc1 = TMath::Sqrt(xc1*xc1+yc1*yc1);
Float_t fi1 = TMath::ATan2(yc1,xc1);
//
Float_t dfi = fi0-fi1;
//
//
if (dfi>1.5*TMath::Pi()) dfi-=TMath::Pi(); // take care about edge effect
if (dfi<-1.5*TMath::Pi()) dfi+=TMath::Pi(); //
Float_t dtheta = TMath::Abs(track0->GetTgl()-track1->GetTgl())<TMath::Abs(track0->GetTgl()+track1->GetTgl())? track0->GetTgl()-track1->GetTgl():track0->GetTgl()+track1->GetTgl();
//
//
// FIRST fast cuts
if (track0->GetBConstrain()&&track1->GetBConstrain()) continue; // not constrained
if (track1->GetSigned1Pt()*track0->GetSigned1Pt()>0) continue; // not the same sign
if ( TMath::Abs(track1->GetTgl()+track0->GetTgl())>kMaxdTheta) continue; //distance in the Theta
if ( TMath::Abs(dfi)>kMaxdPhi) continue; //distance in phi
if ( TMath::Sqrt(dfi*dfi+dtheta*dtheta)>kMaxdPhi) continue; //common angular offset
//
Float_t pt0 = track0->GetSignedPt();
Float_t pt1 = track1->GetSignedPt();
if ((TMath::Abs(pt0+pt1)/(TMath::Abs(pt0)+TMath::Abs(pt1)))>kPtRatio) continue;
if ((iter==1) && TMath::Abs(TMath::Abs(rc0+r0)-TMath::Abs(rc1+r1))>kMaxDeltaRMax) continue;
if ((iter!=1) &&TMath::Abs(TMath::Abs(rc0-r0)-TMath::Abs(rc1-r1))>kMaxDeltaRMin) continue;
if (TMath::Min(TMath::Abs(rc0-r0),TMath::Abs(rc1-r1))<kMinDCAR) continue;
//
//
// Now find closest approach
//
//
//
Int_t npoints = hlxi0->GetRPHIintersections(*hlxi1, phase, radius,10);
if (npoints==0) continue;
hlxi0->GetClosestPhases(*hlxi1, phase);
//
Double_t xyz0[3];
Double_t xyz1[3];
Double_t hangles[3];
hlxi0->Evaluate(phase[0][0],xyz0);
hlxi1->Evaluate(phase[0][1],xyz1);
hlxi0->GetAngle(phase[0][0],*hlxi1,phase[0][1],hangles);
Double_t deltah[2],deltabest;
if (TMath::Abs(hangles[2])<kMinAngle) continue;
if (npoints>0){
Int_t ibest=0;
hlxi0->ParabolicDCA(*hlxi1,phase[0][0],phase[0][1],radius[0],deltah[0],2);
if (npoints==2){
hlxi0->ParabolicDCA(*hlxi1,phase[1][0],phase[1][1],radius[1],deltah[1],2);
if (deltah[1]<deltah[0]) ibest=1;
}
deltabest = TMath::Sqrt(deltah[ibest]);
hlxi0->Evaluate(phase[ibest][0],xyz0);
hlxi1->Evaluate(phase[ibest][1],xyz1);
hlxi0->GetAngle(phase[ibest][0],*hlxi1,phase[ibest][1],hangles);
Double_t radiusbest = TMath::Sqrt(radius[ibest]);
//
if (deltabest>kMaxDist) continue;
// if (mindcar+mindcaz<40 && (TMath::Abs(hangles[2])<kMinAngle ||deltabest>3)) continue;
Bool_t sign =kFALSE;
if (hangles[2]>kMinAngle) sign =kTRUE;
//
if (sign){
// circular[i0] = kTRUE;
// circular[i1] = kTRUE;
if (track0->OneOverPt()<track1->OneOverPt()){
track0->SetCircular(track0->GetCircular()+1);
track1->SetCircular(track1->GetCircular()+2);
}
else{
track1->SetCircular(track1->GetCircular()+1);
track0->SetCircular(track0->GetCircular()+2);
}
}
if ((AliTPCReconstructor::StreamLevel()&kStreamFindCurling)>0){ // flag: stream track infroamtion if the FindCurling tracks method
//
//debug stream to tune "fine" cuts
Int_t lab0=track0->GetLabel();
Int_t lab1=track1->GetLabel();
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Curling2"<<
"iter="<<iter<<
"lab0="<<lab0<<
"lab1="<<lab1<<
"Tr0.="<<track0<<
"Tr1.="<<track1<<
//
"r0="<<r0<<
"rc0="<<rc0<<
"fi0="<<fi0<<
"r1="<<r1<<
"rc1="<<rc1<<
"fi1="<<fi1<<
"dfi="<<dfi<<
"dtheta="<<dtheta<<
//
"npoints="<<npoints<<
"hangles0="<<hangles[0]<<
"hangles1="<<hangles[1]<<
"hangles2="<<hangles[2]<<
"xyz0="<<xyz0[2]<<
"xyzz1="<<xyz1[2]<<
"radius="<<radiusbest<<
"deltabest="<<deltabest<<
"phase0="<<phase[ibest][0]<<
"phase1="<<phase[ibest][1]<<
"\n";
}
}
}
}
if (fHelixPool) fHelixPool->Clear();
// delete [] helixes; //RS moved to stack
if (AliTPCReconstructor::StreamLevel()>1) {
AliInfo("Time for curling tracks removal");
timer.Print();
}
}
void AliTPCtracker::FindKinks(TObjArray * array, AliESDEvent *esd)
{
//
// find kinks
//
//
// RS something is wrong in this routine: not all seeds are assigned to daughters and mothers array, but they all are queried
// to check later
TObjArray kinks(10000);
Int_t nentries = array->GetEntriesFast();
Char_t sign[nentries];
UChar_t nclusters[nentries];
Float_t alpha[nentries];
UChar_t usage[nentries];
Float_t zm[nentries];
Float_t z0[nentries];
Float_t fim[nentries];
Bool_t shared[nentries];
Bool_t circular[nentries];
Float_t dca[nentries];
AliKink *kink = new AliKink();
//
if (!fHelixPool) fHelixPool = new TClonesArray("AliHelix",nentries+100);
fHelixPool->Clear();
TClonesArray& helixes = *fHelixPool;
//const AliESDVertex * primvertex = esd->GetVertex();
//
// nentries = array->GetEntriesFast();
//
//
//
for (Int_t i=0;i<nentries;i++){
sign[i]=0;
usage[i]=0;
AliTPCseed* track = (AliTPCseed*)array->At(i);
if (!track) continue;
track->SetCircular(0);
shared[i] = kFALSE;
track->UpdatePoints();
if (( track->GetPoints()[2]- track->GetPoints()[0])>5 && track->GetPoints()[3]>0.8){
}
nclusters[i]=track->GetNumberOfClusters();
alpha[i] = track->GetAlpha();
AliHelix* hlxi = new (helixes[i]) AliHelix(*track);
Double_t xyz[3];
hlxi->Evaluate(0,xyz);
sign[i] = (track->GetC()>0) ? -1:1;
Double_t x,y,z;
x=160;
if (track->GetProlongation(x,y,z)){
zm[i] = z;
fim[i] = alpha[i]+TMath::ATan2(y,x);
}
else{
zm[i] = track->GetZ();
fim[i] = alpha[i];
}
z0[i]=1000;
circular[i]= kFALSE;
if (track->GetProlongation(0,y,z)) z0[i] = z;
dca[i] = track->GetD(0,0);
}
//
//
TStopwatch timer;
timer.Start();
Int_t ncandidates =0;
Int_t nall =0;
Int_t ntracks=0;
Double_t phase[2][2]={{0,0},{0,0}},radius[2]={0,0};
//
// Find circling track
//
for (Int_t i0=0;i0<nentries;i0++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i0);
if (!track0) continue;
if (track0->GetNumberOfClusters()<40) continue;
if (TMath::Abs(1./track0->GetC())>200) continue;
AliHelix* hlxi0 = (AliHelix*)helixes[i0];
//
for (Int_t i1=i0+1;i1<nentries;i1++){
AliTPCseed * track1 = (AliTPCseed*)array->At(i1);
if (!track1) continue;
if (track1->GetNumberOfClusters()<40) continue;
if ( TMath::Abs(track1->GetTgl()+track0->GetTgl())>0.1) continue;
if (track0->GetBConstrain()&&track1->GetBConstrain()) continue;
if (TMath::Abs(1./track1->GetC())>200) continue;
if (track1->GetSigned1Pt()*track0->GetSigned1Pt()>0) continue;
if (track1->GetTgl()*track0->GetTgl()>0) continue;
if (TMath::Max(TMath::Abs(1./track0->GetC()),TMath::Abs(1./track1->GetC()))>190) continue;
if (track0->GetBConstrain()&&track1->OneOverPt()<track0->OneOverPt()) continue; //returning - lower momenta
if (track1->GetBConstrain()&&track0->OneOverPt()<track1->OneOverPt()) continue; //returning - lower momenta
//
Float_t mindcar = TMath::Min(TMath::Abs(dca[i0]),TMath::Abs(dca[i1]));
if (mindcar<5) continue;
Float_t mindcaz = TMath::Min(TMath::Abs(z0[i0]-GetZ()),TMath::Abs(z0[i1]-GetZ()));
if (mindcaz<5) continue;
if (mindcar+mindcaz<20) continue;
//
AliHelix* hlxi1 = (AliHelix*)helixes[i1];
//
Float_t xc0 = hlxi0->GetHelix(6);
Float_t yc0 = hlxi0->GetHelix(7);
Float_t r0 = hlxi0->GetHelix(8);
Float_t xc1 = hlxi1->GetHelix(6);
Float_t yc1 = hlxi1->GetHelix(7);
Float_t r1 = hlxi1->GetHelix(8);
Float_t rmean = (r0+r1)*0.5;
Float_t delta =TMath::Sqrt((xc1-xc0)*(xc1-xc0)+(yc1-yc0)*(yc1-yc0));
//if (delta>30) continue;
if (delta>rmean*0.25) continue;
if (TMath::Abs(r0-r1)/rmean>0.3) continue;
//
Int_t npoints = hlxi0->GetRPHIintersections(*hlxi1, phase, radius,10);
if (npoints==0) continue;
hlxi0->GetClosestPhases(*hlxi1, phase);
//
Double_t xyz0[3];
Double_t xyz1[3];
Double_t hangles[3];
hlxi0->Evaluate(phase[0][0],xyz0);
hlxi1->Evaluate(phase[0][1],xyz1);
hlxi0->GetAngle(phase[0][0],*hlxi1,phase[0][1],hangles);
Double_t deltah[2],deltabest;
if (hangles[2]<2.8) continue;
if (npoints>0){
Int_t ibest=0;
hlxi0->ParabolicDCA(*hlxi1,phase[0][0],phase[0][1],radius[0],deltah[0],2);
if (npoints==2){
hlxi0->ParabolicDCA(*hlxi1,phase[1][0],phase[1][1],radius[1],deltah[1],2);
if (deltah[1]<deltah[0]) ibest=1;
}
deltabest = TMath::Sqrt(deltah[ibest]);
hlxi0->Evaluate(phase[ibest][0],xyz0);
hlxi1->Evaluate(phase[ibest][1],xyz1);
hlxi0->GetAngle(phase[ibest][0],*hlxi1,phase[ibest][1],hangles);
Double_t radiusbest = TMath::Sqrt(radius[ibest]);
//
if (deltabest>6) continue;
if (mindcar+mindcaz<40 && (hangles[2]<3.12||deltabest>3)) continue;
Bool_t lsign =kFALSE;
if (hangles[2]>3.06) lsign =kTRUE;
//
if (lsign){
circular[i0] = kTRUE;
circular[i1] = kTRUE;
if (track0->OneOverPt()<track1->OneOverPt()){
track0->SetCircular(track0->GetCircular()+1);
track1->SetCircular(track1->GetCircular()+2);
}
else{
track1->SetCircular(track1->GetCircular()+1);
track0->SetCircular(track0->GetCircular()+2);
}
}
if (lsign&&((AliTPCReconstructor::StreamLevel()&kStreamFindCurling)>0)){
//debug stream
Int_t lab0=track0->GetLabel();
Int_t lab1=track1->GetLabel();
TTreeSRedirector &cstream = *fDebugStreamer;
cstream<<"Curling"<<
"lab0="<<lab0<<
"lab1="<<lab1<<
"Tr0.="<<track0<<
"Tr1.="<<track1<<
"dca0="<<dca[i0]<<
"dca1="<<dca[i1]<<
"mindcar="<<mindcar<<
"mindcaz="<<mindcaz<<
"delta="<<delta<<
"rmean="<<rmean<<
"npoints="<<npoints<<
"hangles0="<<hangles[0]<<
"hangles2="<<hangles[2]<<
"xyz0="<<xyz0[2]<<
"xyzz1="<<xyz1[2]<<
"z0="<<z0[i0]<<
"z1="<<z0[i1]<<
"radius="<<radiusbest<<
"deltabest="<<deltabest<<
"phase0="<<phase[ibest][0]<<
"phase1="<<phase[ibest][1]<<
"\n";
}
}
}
}
//
// Finf kinks loop
//
//
for (Int_t i =0;i<nentries;i++){
if (sign[i]==0) continue;
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (track0==0) {
AliInfo("seed==0");
continue;
}
ntracks++;
//
Double_t cradius0 = 40*40;
Double_t cradius1 = 270*270;
Double_t cdist1=8.;
Double_t cdist2=8.;
Double_t cdist3=0.55;
AliHelix* hlxi = (AliHelix*)helixes[i];
for (Int_t j =i+1;j<nentries;j++){
nall++;
if (sign[j]*sign[i]<1) continue;
int ncltot = nclusters[i];
ncltot += nclusters[j];
if ( ncltot>200) continue;
if ( ncltot<80) continue;
if ( TMath::Abs(zm[i]-zm[j])>60.) continue;
if ( TMath::Abs(fim[i]-fim[j])>0.6 && TMath::Abs(fim[i]-fim[j])<5.7 ) continue;
//AliTPCseed * track1 = (AliTPCseed*)array->At(j); Double_t phase[2][2],radius[2];
AliHelix* hlxj = (AliHelix*)helixes[j];
Int_t npoints = hlxi->GetRPHIintersections(*hlxj, phase, radius,20);
if (npoints<1) continue;
// cuts on radius
if (npoints==1){
if (radius[0]<cradius0||radius[0]>cradius1) continue;
}
else{
if ( (radius[0]<cradius0||radius[0]>cradius1) && (radius[1]<cradius0||radius[1]>cradius1) ) continue;
}
//
Double_t delta1=10000,delta2=10000;
// cuts on the intersection radius
hlxi->LinearDCA(*hlxj,phase[0][0],phase[0][1],radius[0],delta1);
if (radius[0]<20&&delta1<1) continue; //intersection at vertex
if (radius[0]<10&&delta1<3) continue; //intersection at vertex
if (npoints==2){
hlxi->LinearDCA(*hlxj,phase[1][0],phase[1][1],radius[1],delta2);
if (radius[1]<20&&delta2<1) continue; //intersection at vertex
if (radius[1]<10&&delta2<3) continue; //intersection at vertex
}
//
Double_t distance1 = TMath::Min(delta1,delta2);
if (distance1>cdist1) continue; // cut on DCA linear approximation
//
npoints = hlxi->GetRPHIintersections(*hlxj, phase, radius,20);
hlxi->ParabolicDCA(*hlxj,phase[0][0],phase[0][1],radius[0],delta1);
if (radius[0]<20&&delta1<1) continue; //intersection at vertex
if (radius[0]<10&&delta1<3) continue; //intersection at vertex
//
if (npoints==2){
hlxi->ParabolicDCA(*hlxj,phase[1][0],phase[1][1],radius[1],delta2);
if (radius[1]<20&&delta2<1) continue; //intersection at vertex
if (radius[1]<10&&delta2<3) continue; //intersection at vertex
}
distance1 = TMath::Min(delta1,delta2);
Float_t rkink =0;
if (delta1<delta2){
rkink = TMath::Sqrt(radius[0]);
}
else{
rkink = TMath::Sqrt(radius[1]);
}
if (distance1>cdist2) continue;
//
//
AliTPCseed * track1 = (AliTPCseed*)array->At(j);
//
//
Int_t row0 = GetRowNumber(rkink);
if (row0<10) continue;
if (row0>150) continue;
//
//
Float_t dens00=-1,dens01=-1;
Float_t dens10=-1,dens11=-1;
//
Int_t found,foundable;//,ishared;
//RS Seed don't keep their cluster pointers, cache cluster usage stat. for fast evaluation
// FillSeedClusterStatCache(track0); // RS: Use this slow method only if sharing stat. is needed and used
//
//GetCachedSeedClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track0->GetClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE);
track0->GetClusterStatistic(0,row0-5, found, foundable);
if (foundable>5) dens00 = Float_t(found)/Float_t(foundable);
//
//GetCachedSeedClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track0->GetClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE);
track0->GetClusterStatistic(row0+5,155, found, foundable);
if (foundable>5) dens01 = Float_t(found)/Float_t(foundable);
//
//
//RS Seed don't keep their cluster pointers, cache cluster usage stat. for fast evaluation
// FillSeedClusterStatCache(track1); // RS: Use this slow method only if sharing stat. is needed and used
//
//GetCachedSeedClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track1->GetClusterStatistic(0,row0-5, found, foundable,ishared,kFALSE);
track1->GetClusterStatistic(0,row0-5, found, foundable);
if (foundable>10) dens10 = Float_t(found)/Float_t(foundable);
//
//GetCachedSeedClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE); // RS make sure FillSeedClusterStatCache is called
//RS track1->GetClusterStatistic(row0+5,155, found, foundable,ishared,kFALSE);
track1->GetClusterStatistic(row0+5,155, found, foundable);
if (foundable>10) dens11 = Float_t(found)/Float_t(foundable);
//
if (dens00<dens10 && dens01<dens11) continue;
if (dens00>dens10 && dens01>dens11) continue;
if (TMath::Max(dens00,dens10)<0.1) continue;
if (TMath::Max(dens01,dens11)<0.3) continue;
//
if (TMath::Min(dens00,dens10)>0.6) continue;
if (TMath::Min(dens01,dens11)>0.6) continue;
//
AliTPCseed * ktrack0, *ktrack1;
if (dens00>dens10){
ktrack0 = track0;
ktrack1 = track1;
}
else{
ktrack0 = track1;
ktrack1 = track0;
}
if (TMath::Abs(ktrack0->GetC())>5) continue; // cut on the curvature for mother particle
AliExternalTrackParam paramm(*ktrack0);
AliExternalTrackParam paramd(*ktrack1);
if (row0>60&&ktrack1->GetReference().GetX()>90.)new (¶md) AliExternalTrackParam(ktrack1->GetReference());
//
//
kink->SetMother(paramm);
kink->SetDaughter(paramd);
kink->Update();
Float_t x[3] = { static_cast<Float_t>(kink->GetPosition()[0]),static_cast<Float_t>(kink->GetPosition()[1]),static_cast<Float_t>(kink->GetPosition()[2])};
Int_t index[4];
fkParam->Transform0to1(x,index);
fkParam->Transform1to2(x,index);
row0 = GetRowNumber(x[0]);
if (kink->GetR()<100) continue;
if (kink->GetR()>240) continue;
if (kink->GetPosition()[2]/kink->GetR()>AliTPCReconstructor::GetCtgRange()) continue; //out of fiducial volume
if (kink->GetDistance()>cdist3) continue;
Float_t dird = kink->GetDaughterP()[0]*kink->GetPosition()[0]+kink->GetDaughterP()[1]*kink->GetPosition()[1]; // rough direction estimate
if (dird<0) continue;
Float_t dirm = kink->GetMotherP()[0]*kink->GetPosition()[0]+kink->GetMotherP()[1]*kink->GetPosition()[1]; // rough direction estimate
if (dirm<0) continue;
Float_t mpt = TMath::Sqrt(kink->GetMotherP()[0]*kink->GetMotherP()[0]+kink->GetMotherP()[1]*kink->GetMotherP()[1]);
if (mpt<0.2) continue;
if (mpt<1){
//for high momenta momentum not defined well in first iteration
Double_t qt = TMath::Sin(kink->GetAngle(2))*ktrack1->GetP();
if (qt>0.35) continue;
}
kink->SetLabel(CookLabel(ktrack0,0.4,0,row0),0);
kink->SetLabel(CookLabel(ktrack1,0.4,row0,kMaxRow),1);
if (dens00>dens10){
kink->SetTPCDensity(dens00,0,0);
kink->SetTPCDensity(dens01,0,1);
kink->SetTPCDensity(dens10,1,0);
kink->SetTPCDensity(dens11,1,1);
kink->SetIndex(i,0);
kink->SetIndex(j,1);
}
else{
kink->SetTPCDensity(dens10,0,0);
kink->SetTPCDensity(dens11,0,1);
kink->SetTPCDensity(dens00,1,0);
kink->SetTPCDensity(dens01,1,1);
kink->SetIndex(j,0);
kink->SetIndex(i,1);
}
if (mpt<1||kink->GetAngle(2)>0.1){
// angle and densities not defined yet
if (kink->GetTPCDensityFactor()<0.8) continue;
if ((2-kink->GetTPCDensityFactor())*kink->GetDistance() >0.25) continue;
if (kink->GetAngle(2)*ktrack0->GetP()<0.003) continue; //too small angle
if (kink->GetAngle(2)>0.2&&kink->GetTPCDensityFactor()<1.15) continue;
if (kink->GetAngle(2)>0.2&&kink->GetTPCDensity(0,1)>0.05) continue;
Float_t criticalangle = track0->GetSigmaSnp2()+track0->GetSigmaTgl2();
criticalangle+= track1->GetSigmaSnp2()+track1->GetSigmaTgl2();
criticalangle= 3*TMath::Sqrt(criticalangle);
if (criticalangle>0.02) criticalangle=0.02;
if (kink->GetAngle(2)<criticalangle) continue;
}
//
Int_t drow = Int_t(2.+0.5/(0.05+kink->GetAngle(2))); // overlap region defined
Float_t shapesum =0;
Float_t sum = 0;
for ( Int_t row = row0-drow; row<row0+drow;row++){
if (row<0) continue;
if (row>155) continue;
//RS if (ktrack0->GetClusterPointer(row)) {
if (ktrack0->GetClusterIndex2(row)>=0) {
const AliTPCTrackerPoints::Point *point = ktrack0->GetTrackPoint(row);
shapesum+=point->GetSigmaY()+point->GetSigmaZ();
sum++;
}
//RS if (ktrack1->GetClusterPointer(row)){
if (ktrack1->GetClusterIndex2(row)>=0) {
const AliTPCTrackerPoints::Point *point =ktrack1->GetTrackPoint(row);
shapesum+=point->GetSigmaY()+point->GetSigmaZ();
sum++;
}
}
if (sum<4){
kink->SetShapeFactor(-1.);
}
else{
kink->SetShapeFactor(shapesum/sum);
}
// esd->AddKink(kink);
//
// kink->SetMother(paramm);
//kink->SetDaughter(paramd);
Double_t chi2P2 = paramm.GetParameter()[2]-paramd.GetParameter()[2];
chi2P2*=chi2P2;
chi2P2/=paramm.GetCovariance()[5]+paramd.GetCovariance()[5];
Double_t chi2P3 = paramm.GetParameter()[3]-paramd.GetParameter()[3];
chi2P3*=chi2P3;
chi2P3/=paramm.GetCovariance()[9]+paramd.GetCovariance()[9];
//
if ((AliTPCReconstructor::StreamLevel()&kStreamFindKinks)>0) { // flag: stream track infroamtion in the FindKinks method
(*fDebugStreamer)<<"kinkLpt"<<
"chi2P2="<<chi2P2<<
"chi2P3="<<chi2P3<<
"p0.="<<¶mm<<
"p1.="<<¶md<<
"k.="<<kink<<
"\n";
}
if ( chi2P2+chi2P3<AliTPCReconstructor::GetRecoParam()->GetKinkAngleCutChi2(0)){
continue;
}
//
kinks.AddLast(kink);
kink = new AliKink;
ncandidates++;
}
}
//
// sort the kinks according quality - and refit them towards vertex
//
Int_t nkinks = kinks.GetEntriesFast();
Float_t quality[nkinks];
Int_t indexes[nkinks];
AliTPCseed *mothers[nkinks];
AliTPCseed *daughters[nkinks];
memset(mothers,0,nkinks*sizeof(AliTPCseed*));
memset(daughters,0,nkinks*sizeof(AliTPCseed*));
//
//
for (Int_t i=0;i<nkinks;i++){
quality[i] =100000;
AliKink *kinkl = (AliKink*)kinks.At(i);
//
// refit kinks towards vertex
//
Int_t index0 = kinkl->GetIndex(0);
Int_t index1 = kinkl->GetIndex(1);
AliTPCseed * ktrack0 = (AliTPCseed*)array->At(index0);
AliTPCseed * ktrack1 = (AliTPCseed*)array->At(index1);
//
Int_t sumn=ktrack0->GetNumberOfClusters()+ktrack1->GetNumberOfClusters();
//
// Refit Kink under if too small angle
//
if (kinkl->GetAngle(2)<0.05){
//
// RS: if possible, remove kink before reseeding
if (kinkl->GetDistance()>0.5 || kinkl->GetR()<110 || kinkl->GetR()>240) {
delete kinks.RemoveAt(i);
continue;
}
//
kinkl->SetTPCRow0(GetRowNumber(kinkl->GetR()));
Int_t row0 = kinkl->GetTPCRow0();
Int_t drow = Int_t(2.+0.5/(0.05+kinkl->GetAngle(2)));
//
Int_t last = row0-drow;
if (last<40) last=40;
if (last<ktrack0->GetFirstPoint()+25) last = ktrack0->GetFirstPoint()+25;
AliTPCseed* seed0 = ReSeed(ktrack0,last,kFALSE);
//
Int_t first = row0+drow;
if (first>130) first=130;
if (first>ktrack1->GetLastPoint()-25) first = TMath::Max(ktrack1->GetLastPoint()-25,30);
AliTPCseed* seed1 = ReSeed(ktrack1,first,kTRUE);
//
if (seed0 && seed1) {
kinkl->SetStatus(1,8);
if (RefitKink(*seed0,*seed1,*kinkl)) kinkl->SetStatus(1,9);
row0 = GetRowNumber(kinkl->GetR());
sumn = seed0->GetNumberOfClusters()+seed1->GetNumberOfClusters();
mothers[i] = seed0;
daughters[i] = seed1;
}
else {
delete kinks.RemoveAt(i);
if (seed0) MarkSeedFree( seed0 );
if (seed1) MarkSeedFree( seed1 );
continue;
}
}
//
if (kinkl) quality[i] = 160*((0.1+kinkl->GetDistance())*(2.-kinkl->GetTPCDensityFactor()))/(sumn+40.); //the longest -clossest will win
}
TMath::Sort(nkinks,quality,indexes,kFALSE);
//
//remove double find kinks
//
for (Int_t ikink0=1;ikink0<nkinks;ikink0++){
AliKink * kink0 = (AliKink*) kinks.At(indexes[ikink0]);
if (!kink0) continue;
//
for (Int_t ikink1=0;ikink1<ikink0;ikink1++){
kink0 = (AliKink*) kinks.At(indexes[ikink0]);
if (!kink0) continue;
AliKink * kink1 = (AliKink*) kinks.At(indexes[ikink1]);
if (!kink1) continue;
// if not close kink continue
if (TMath::Abs(kink1->GetPosition()[2]-kink0->GetPosition()[2])>10) continue;
if (TMath::Abs(kink1->GetPosition()[1]-kink0->GetPosition()[1])>10) continue;
if (TMath::Abs(kink1->GetPosition()[0]-kink0->GetPosition()[0])>10) continue;
//
AliTPCseed &mother0 = mothers[indexes[ikink0]] ? *mothers[indexes[ikink0]] : *((AliTPCseed*)array->At(kink0->GetIndex(0)));
AliTPCseed &daughter0 = daughters[indexes[ikink0]] ? *daughters[indexes[ikink0]] : *((AliTPCseed*)array->At(kink0->GetIndex(1)));
AliTPCseed &mother1 = mothers[indexes[ikink1]] ? *mothers[indexes[ikink1]] : *((AliTPCseed*)array->At(kink1->GetIndex(0)));
AliTPCseed &daughter1 = daughters[indexes[ikink1]] ? *daughters[indexes[ikink1]] : *((AliTPCseed*)array->At(kink1->GetIndex(1)));
Int_t row0 = (kink0->GetTPCRow0()+kink1->GetTPCRow0())/2;
//
Int_t same = 0;
Int_t both = 0;
Int_t samem = 0;
Int_t bothm = 0;
Int_t samed = 0;
Int_t bothd = 0;
//
for (Int_t i=0;i<row0;i++){
if (mother0.GetClusterIndex(i)>0 && mother1.GetClusterIndex(i)>0){
both++;
bothm++;
if (mother0.GetClusterIndex(i)==mother1.GetClusterIndex(i)){
same++;
samem++;
}
}
}
for (Int_t i=row0;i<158;i++){
//if (daughter0.GetClusterIndex(i)>0 && daughter0.GetClusterIndex(i)>0){ // RS: Bug?
if (daughter0.GetClusterIndex(i)>0 && daughter1.GetClusterIndex(i)>0){
both++;
bothd++;
if (mother0.GetClusterIndex(i)==mother1.GetClusterIndex(i)){
same++;
samed++;
}
}
}
Float_t ratio = Float_t(same+1)/Float_t(both+1);
Float_t ratiom = Float_t(samem+1)/Float_t(bothm+1);
Float_t ratiod = Float_t(samed+1)/Float_t(bothd+1);
if (ratio>0.3 && ratiom>0.5 &&ratiod>0.5) {
Int_t sum0 = mother0.GetNumberOfClusters()+daughter0.GetNumberOfClusters();
Int_t sum1 = mother1.GetNumberOfClusters()+daughter1.GetNumberOfClusters();
if (sum1>sum0){
shared[kink0->GetIndex(0)]= kTRUE;
shared[kink0->GetIndex(1)]= kTRUE;
delete kinks.RemoveAt(indexes[ikink0]);
break;
}
else{
shared[kink1->GetIndex(0)]= kTRUE;
shared[kink1->GetIndex(1)]= kTRUE;
delete kinks.RemoveAt(indexes[ikink1]);
}
}
}
}
for (Int_t i=0;i<nkinks;i++){
AliKink * kinkl = (AliKink*) kinks.At(indexes[i]);
if (!kinkl) continue;
kinkl->SetTPCRow0(GetRowNumber(kinkl->GetR()));
Int_t index0 = kinkl->GetIndex(0);
Int_t index1 = kinkl->GetIndex(1);
if (circular[index0]||(circular[index1]&&kinkl->GetDistance()>0.2)) continue;
kinkl->SetMultiple(usage[index0],0);
kinkl->SetMultiple(usage[index1],1);
if (kinkl->GetMultiple()[0]+kinkl->GetMultiple()[1]>2) continue;
if (kinkl->GetMultiple()[0]+kinkl->GetMultiple()[1]>0 && quality[indexes[i]]>0.2) continue;
if (kinkl->GetMultiple()[0]+kinkl->GetMultiple()[1]>0 && kinkl->GetDistance()>0.2) continue;
if (circular[index0]||(circular[index1]&&kinkl->GetDistance()>0.1)) continue;
AliTPCseed * ktrack0 = (AliTPCseed*)array->At(index0);
AliTPCseed * ktrack1 = (AliTPCseed*)array->At(index1);
if (!ktrack0 || !ktrack1) continue;
Int_t index = esd->AddKink(kinkl);
//
//
if ( ktrack0->GetKinkIndex(0)==0 && ktrack1->GetKinkIndex(0)==0) { //best kink
if ( (mothers[indexes[i]]) && daughters[indexes[i]] &&
mothers[indexes[i]]->GetNumberOfClusters()>20 && // where they reseeded?
daughters[indexes[i]]->GetNumberOfClusters()>20 &&
(mothers[indexes[i]]->GetNumberOfClusters()+daughters[indexes[i]]->GetNumberOfClusters())>100){
*ktrack0 = *mothers[indexes[i]];
*ktrack1 = *daughters[indexes[i]];
}
}
//
ktrack0->SetKinkIndex(usage[index0],-(index+1));
ktrack1->SetKinkIndex(usage[index1], (index+1));
usage[index0]++;
usage[index1]++;
}
//
// Remove tracks corresponding to shared kink's
//
for (Int_t i=0;i<nentries;i++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (!track0) continue;
if (track0->GetKinkIndex(0)!=0) continue;
if (shared[i]) MarkSeedFree( array->RemoveAt(i) );
}
//
//
RemoveUsed2(array,0.5,0.4,30);
UnsignClusters();
for (Int_t i=0;i<nentries;i++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (!track0) continue;
track0->CookdEdx(0.02,0.6);
track0->CookPID();
}
//
// RS use stack allocation instead of the heap
AliTPCseed mother,daughter;
AliKink kinkl;
//
for (Int_t i=0;i<nentries;i++){
AliTPCseed * track0 = (AliTPCseed*)array->At(i);
if (!track0) continue;
if (track0->Pt()<1.4) continue;
//remove double high momenta tracks - overlapped with kink candidates
Int_t ishared=0;
Int_t all =0;
for (Int_t icl=track0->GetFirstPoint();icl<track0->GetLastPoint(); icl++){
Int_t tpcindex = track0->GetClusterIndex2(icl);
if (tpcindex<0) continue;
AliTPCclusterMI *cl = GetClusterMI(tpcindex);
all++;
if (cl->IsUsed(10)) ishared++;
}
if (Float_t(ishared+1)/Float_t(all+1)>0.5) {
MarkSeedFree( array->RemoveAt(i) );
continue;
}
//
if (track0->GetKinkIndex(0)!=0) continue;
if (track0->GetNumberOfClusters()<80) continue;
// AliTPCseed *pmother = new AliTPCseed(); // RS use stack allocation
// AliTPCseed *pdaughter = new AliTPCseed();
// AliKink *pkink = new AliKink;
//
if (CheckKinkPoint(track0,mother,daughter, kinkl)){
if (mother.GetNumberOfClusters()<30||daughter.GetNumberOfClusters()<20) {
// delete pmother; // RS used stack allocation
// delete pdaughter;
// delete pkink;
continue; //too short tracks
}
if (mother.Pt()<1.4) {
// delete pmother; // RS used stack allocation
// delete pdaughter;
// delete pkink;
continue;
}
Int_t row0= kinkl.GetTPCRow0();
if (kinkl.GetDistance()>0.5 || kinkl.GetR()<110. || kinkl.GetR()>240.) {
// delete pmother; // RS used stack allocation
// delete pdaughter;
// delete pkink;
continue;
}
//
Int_t index = esd->AddKink(&kinkl);
mother.SetKinkIndex(0,-(index+1));
daughter.SetKinkIndex(0,index+1);
if (mother.GetNumberOfClusters()>50) {
MarkSeedFree( array->RemoveAt(i) );
AliTPCseed* mtc = new( NextFreeSeed() ) AliTPCseed(mother);
mtc->SetPoolID(fLastSeedID);
array->AddAt(mtc,i);
}
else{
AliTPCseed* mtc = new( NextFreeSeed() ) AliTPCseed(mother);
mtc->SetPoolID(fLastSeedID);
array->AddLast(mtc);
}
AliTPCseed* dtc = new( NextFreeSeed() ) AliTPCseed(daughter);
dtc->SetPoolID(fLastSeedID);
array->AddLast(dtc);
for (Int_t icl=0;icl<row0;icl++) {
Int_t tpcindex= mother.GetClusterIndex2(icl);
if (tpcindex<0) continue;
AliTPCclusterMI *cl = GetClusterMI(tpcindex);
if (cl) cl->Use(20);
}
//
for (Int_t icl=row0;icl<158;icl++) {
Int_t tpcindex= mother.GetClusterIndex2(icl);
if (tpcindex<0) continue;
AliTPCclusterMI *cl = GetClusterMI(tpcindex);
if (cl) cl->Use(20);
}
//
}
//delete pmother; // RS used stack allocation
//delete pdaughter;
//delete pkink;
}
for (int i=nkinks;i--;) {
if (mothers[i]) MarkSeedFree( mothers[i] );
if (daughters[i]) MarkSeedFree( daughters[i] );
}
// delete [] daughters;
// delete [] mothers;
//
// RS: most of heap array are converted to stack arrays
// delete [] dca;
// delete []circular;
// delete []shared;
// delete []quality;
// delete []indexes;
//
delete kink;
// delete[]fim;
// delete[] zm;
// delete[] z0;
// delete [] usage;
// delete[] alpha;
// delete[] nclusters;
// delete[] sign;
// delete[] helixes;
if (fHelixPool) fHelixPool->Clear();
kinks.Delete();
//delete kinks;
AliInfo(Form("Ncandidates=\t%d\t%d\t%d\t%d\n",esd->GetNumberOfKinks(),ncandidates,ntracks,nall));
timer.Print();
}
Int_t AliTPCtracker::RefitKink(AliTPCseed &mother, AliTPCseed &daughter, const AliESDkink &knk)
{
//
// refit kink towards to the vertex
//
//
AliKink &kink=(AliKink &)knk;
Int_t row0 = GetRowNumber(kink.GetR());
FollowProlongation(mother,0);
mother.Reset(kFALSE);
//
FollowProlongation(daughter,row0);
daughter.Reset(kFALSE);
FollowBackProlongation(daughter,158);
daughter.Reset(kFALSE);
Int_t first = TMath::Max(row0-20,30);
Int_t last = TMath::Min(row0+20,140);
//
const Int_t kNdiv =5;
AliTPCseed param0[kNdiv]; // parameters along the track
AliTPCseed param1[kNdiv]; // parameters along the track
AliKink kinks[kNdiv]; // corresponding kink parameters
//
Int_t rows[kNdiv];
for (Int_t irow=0; irow<kNdiv;irow++){
rows[irow] = first +((last-first)*irow)/(kNdiv-1);
}
// store parameters along the track
//
for (Int_t irow=0;irow<kNdiv;irow++){
FollowBackProlongation(mother, rows[irow]);
FollowProlongation(daughter,rows[kNdiv-1-irow]);
param0[irow] = mother;
param1[kNdiv-1-irow] = daughter;
}
//
// define kinks
for (Int_t irow=0; irow<kNdiv-1;irow++){
if (param0[irow].GetNumberOfClusters()<kNdiv||param1[irow].GetNumberOfClusters()<kNdiv) continue;
kinks[irow].SetMother(param0[irow]);
kinks[irow].SetDaughter(param1[irow]);
kinks[irow].Update();
}
//
// choose kink with best "quality"
Int_t index =-1;
Double_t mindist = 10000;
for (Int_t irow=0;irow<kNdiv;irow++){
if (param0[irow].GetNumberOfClusters()<20||param1[irow].GetNumberOfClusters()<20) continue;
if (TMath::Abs(kinks[irow].GetR())>240.) continue;
if (TMath::Abs(kinks[irow].GetR())<100.) continue;
//
Float_t normdist = TMath::Abs(param0[irow].GetX()-kinks[irow].GetR())*(0.1+kink.GetDistance());
normdist/= (param0[irow].GetNumberOfClusters()+param1[irow].GetNumberOfClusters()+40.);
if (normdist < mindist){
mindist = normdist;
index = irow;
}
}
//
if (index==-1) return 0;
//
//
param0[index].Reset(kTRUE);
FollowProlongation(param0[index],0);
//
mother = param0[index];
daughter = param1[index]; // daughter in vertex
//
kink.SetMother(mother);
kink.SetDaughter(daughter);
kink.Update();
kink.SetTPCRow0(GetRowNumber(kink.GetR()));
kink.SetTPCncls(param0[index].GetNumberOfClusters(),0);
kink.SetTPCncls(param1[index].GetNumberOfClusters(),1);
kink.SetLabel(CookLabel(&mother,0.4, 0,kink.GetTPCRow0()),0);
kink.SetLabel(CookLabel(&daughter,0.4, kink.GetTPCRow0(),kMaxRow),1);
mother.SetLabel(kink.GetLabel(0));
daughter.SetLabel(kink.GetLabel(1));
return 1;
}
void AliTPCtracker::UpdateKinkQualityM(AliTPCseed * seed){
//
// update Kink quality information for mother after back propagation
//
if (seed->GetKinkIndex(0)>=0) return;
for (Int_t ikink=0;ikink<3;ikink++){
Int_t index = seed->GetKinkIndex(ikink);
if (index>=0) break;
index = TMath::Abs(index)-1;
AliESDkink * kink = fEvent->GetKink(index);
kink->SetTPCDensity(-1,0,0);
kink->SetTPCDensity(1,0,1);
//
Int_t row0 = kink->GetTPCRow0() - 2 - Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row0<15) row0=15;
//
Int_t row1 = kink->GetTPCRow0() + 2 + Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row1>145) row1=145;
//
Int_t found,foundable;//,shared;
//GetSeedClusterStatistic(seed,0,row0, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
//RS seed->GetClusterStatistic(0,row0, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(0,row0, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),0,0);
//
//GetSeedClusterStatistic(seed,row1,155, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
//RS seed->GetClusterStatistic(row1,155, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(row1,155, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),0,1);
}
}
void AliTPCtracker::UpdateKinkQualityD(AliTPCseed * seed){
//
// update Kink quality information for daughter after refit
//
if (seed->GetKinkIndex(0)<=0) return;
for (Int_t ikink=0;ikink<3;ikink++){
Int_t index = seed->GetKinkIndex(ikink);
if (index<=0) break;
index = TMath::Abs(index)-1;
AliESDkink * kink = fEvent->GetKink(index);
kink->SetTPCDensity(-1,1,0);
kink->SetTPCDensity(-1,1,1);
//
Int_t row0 = kink->GetTPCRow0() -2 - Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row0<15) row0=15;
//
Int_t row1 = kink->GetTPCRow0() +2 + Int_t( 0.5/ (0.05+kink->GetAngle(2)));
if (row1>145) row1=145;
//
Int_t found,foundable;//,shared;
//GetSeedClusterStatistic(0,row0, found, foundable,shared,kFALS); //RS: seeds don't keep their clusters
//seed->GetClusterStatistic(0,row0, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(0,row0, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),1,0);
//
//GetSeedClusterStatistic(row1,155, found, foundable,shared,kFALSE); //RS: seeds don't keep their clusters
// seed->GetClusterStatistic(row1,155, found, foundable,shared,kFALSE);
seed->GetClusterStatistic(row1,155, found, foundable);
if (foundable>5) kink->SetTPCDensity(Float_t(found)/Float_t(foundable),1,1);
}
}
Int_t AliTPCtracker::CheckKinkPoint(AliTPCseed*seed,AliTPCseed &mother, AliTPCseed &daughter, const AliESDkink &knk)
{
//
// check kink point for given track
// if return value=0 kink point not found
// otherwise seed0 correspond to mother particle
// seed1 correspond to daughter particle
// kink parameter of kink point
AliKink &kink=(AliKink &)knk;
Int_t middlerow = (seed->GetFirstPoint()+seed->GetLastPoint())/2;
Int_t first = seed->GetFirstPoint();
Int_t last = seed->GetLastPoint();
if (last-first<20) return 0; // shortest length - 2*30 = 60 pad-rows
AliTPCseed *seed1 = ReSeed(seed,middlerow+20, kTRUE); //middle of chamber
if (!seed1) return 0;
FollowProlongation(*seed1,seed->GetLastPoint()-20);
seed1->Reset(kTRUE);
FollowProlongation(*seed1,158);
seed1->Reset(kTRUE);
last = seed1->GetLastPoint();
//
AliTPCseed *seed0 = new( NextFreeSeed() ) AliTPCseed(*seed);
seed0->SetPoolID(fLastSeedID);
seed0->Reset(kFALSE);
seed0->Reset();
//
AliTPCseed param0[20]; // parameters along the track
AliTPCseed param1[20]; // parameters along the track
AliKink kinks[20]; // corresponding kink parameters
Int_t rows[20];
for (Int_t irow=0; irow<20;irow++){
rows[irow] = first +((last-first)*irow)/19;
}
// store parameters along the track
//
for (Int_t irow=0;irow<20;irow++){
FollowBackProlongation(*seed0, rows[irow]);
FollowProlongation(*seed1,rows[19-irow]);
param0[irow] = *seed0;
param1[19-irow] = *seed1;
}
//
// define kinks
for (Int_t irow=0; irow<19;irow++){
kinks[irow].SetMother(param0[irow]);
kinks[irow].SetDaughter(param1[irow]);
kinks[irow].Update();
}
//
// choose kink with biggest change of angle
Int_t index =-1;
Double_t maxchange= 0;
for (Int_t irow=1;irow<19;irow++){
if (TMath::Abs(kinks[irow].GetR())>240.) continue;
if (TMath::Abs(kinks[irow].GetR())<110.) continue;
Float_t quality = TMath::Abs(kinks[irow].GetAngle(2))/(3.+TMath::Abs(kinks[irow].GetR()-param0[irow].GetX()));
if ( quality > maxchange){
maxchange = quality;
index = irow;
//
}
}
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
if (index<0) return 0;
//
Int_t row0 = GetRowNumber(kinks[index].GetR()); //row 0 estimate
seed0 = new( NextFreeSeed() ) AliTPCseed(param0[index]);
seed0->SetPoolID(fLastSeedID);
seed1 = new( NextFreeSeed() ) AliTPCseed(param1[index]);
seed1->SetPoolID(fLastSeedID);
seed0->Reset(kFALSE);
seed1->Reset(kFALSE);
seed0->ResetCovariance(10.);
seed1->ResetCovariance(10.);
FollowProlongation(*seed0,0);
FollowBackProlongation(*seed1,158);
mother = *seed0; // backup mother at position 0
seed0->Reset(kFALSE);
seed1->Reset(kFALSE);
seed0->ResetCovariance(10.);
seed1->ResetCovariance(10.);
//
first = TMath::Max(row0-20,0);
last = TMath::Min(row0+20,158);
//
for (Int_t irow=0; irow<20;irow++){
rows[irow] = first +((last-first)*irow)/19;
}
// store parameters along the track
//
for (Int_t irow=0;irow<20;irow++){
FollowBackProlongation(*seed0, rows[irow]);
FollowProlongation(*seed1,rows[19-irow]);
param0[irow] = *seed0;
param1[19-irow] = *seed1;
}
//
// define kinks
for (Int_t irow=0; irow<19;irow++){
kinks[irow].SetMother(param0[irow]);
kinks[irow].SetDaughter(param1[irow]);
// param0[irow].Dump();
//param1[irow].Dump();
kinks[irow].Update();
}
//
// choose kink with biggest change of angle
index =-1;
maxchange= 0;
for (Int_t irow=0;irow<20;irow++){
if (TMath::Abs(kinks[irow].GetR())>250.) continue;
if (TMath::Abs(kinks[irow].GetR())<90.) continue;
Float_t quality = TMath::Abs(kinks[irow].GetAngle(2))/(3.+TMath::Abs(kinks[irow].GetR()-param0[irow].GetX()));
if ( quality > maxchange){
maxchange = quality;
index = irow;
//
}
}
//
//
if (index==-1 || param0[index].GetNumberOfClusters()+param1[index].GetNumberOfClusters()<100){
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
return 0;
}
// Float_t anglesigma = TMath::Sqrt(param0[index].fC22+param0[index].fC33+param1[index].fC22+param1[index].fC33);
kink.SetMother(param0[index]);
kink.SetDaughter(param1[index]);
kink.Update();
Double_t chi2P2 = param0[index].GetParameter()[2]-param1[index].GetParameter()[2];
chi2P2*=chi2P2;
chi2P2/=param0[index].GetCovariance()[5]+param1[index].GetCovariance()[5];
Double_t chi2P3 = param0[index].GetParameter()[3]-param1[index].GetParameter()[3];
chi2P3*=chi2P3;
chi2P3/=param0[index].GetCovariance()[9]+param1[index].GetCovariance()[9];
//
if (AliTPCReconstructor::StreamLevel()&kStreamFindKinks) { // flag: stream track infroamtion in the FindKinks method
(*fDebugStreamer)<<"kinkHpt"<<
"chi2P2="<<chi2P2<<
"chi2P3="<<chi2P3<<
"p0.="<<¶m0[index]<<
"p1.="<<¶m1[index]<<
"k.="<<&kink<<
"\n";
}
if ( chi2P2+chi2P3<AliTPCReconstructor::GetRecoParam()->GetKinkAngleCutChi2(0)){
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
return 0;
}
row0 = GetRowNumber(kink.GetR());
kink.SetTPCRow0(row0);
kink.SetLabel(CookLabel(seed0,0.5,0,row0),0);
kink.SetLabel(CookLabel(seed1,0.5,row0,158),1);
kink.SetIndex(-10,0);
kink.SetIndex(int(param0[index].GetNumberOfClusters()+param1[index].GetNumberOfClusters()),1);
kink.SetTPCncls(param0[index].GetNumberOfClusters(),0);
kink.SetTPCncls(param1[index].GetNumberOfClusters(),1);
//
//
// new (&mother) AliTPCseed(param0[index]);
daughter = param1[index];
daughter.SetLabel(kink.GetLabel(1));
param0[index].Reset(kTRUE);
FollowProlongation(param0[index],0);
mother = param0[index];
mother.SetLabel(kink.GetLabel(0));
if ( chi2P2+chi2P3<AliTPCReconstructor::GetRecoParam()->GetKinkAngleCutChi2(1)){
mother=*seed;
}
MarkSeedFree( seed0 );
MarkSeedFree( seed1 );
//
return 1;
}
AliTPCseed* AliTPCtracker::ReSeed(AliTPCseed *t)
{
//
// reseed - refit - track
//
Int_t first = 0;
// Int_t last = fSectors->GetNRows()-1;
//
if (fSectors == fOuterSec){
first = TMath::Max(first, t->GetFirstPoint()-fInnerSec->GetNRows());
//last =
}
else
first = t->GetFirstPoint();
//
AliTPCseed * seed = MakeSeed(t,0.1,0.5,0.9);
FollowBackProlongation(*t,fSectors->GetNRows()-1);
t->Reset(kFALSE);
FollowProlongation(*t,first);
return seed;
}
//_____________________________________________________________________________
Int_t AliTPCtracker::ReadSeeds(const TFile *inp) {
//-----------------------------------------------------------------
// This function reades track seeds.
//-----------------------------------------------------------------
TDirectory *savedir=gDirectory;
TFile *in=(TFile*)inp;
if (!in->IsOpen()) {
cerr<<"AliTPCtracker::ReadSeeds(): input file is not open !\n";
return 1;
}
in->cd();
TTree *seedTree=(TTree*)in->Get("Seeds");
if (!seedTree) {
cerr<<"AliTPCtracker::ReadSeeds(): ";
cerr<<"can't get a tree with track seeds !\n";
return 2;
}
AliTPCtrack *seed=new AliTPCtrack;
seedTree->SetBranchAddress("tracks",&seed);
if (fSeeds==0) fSeeds=new TObjArray(15000);
Int_t n=(Int_t)seedTree->GetEntries();
for (Int_t i=0; i<n; i++) {
seedTree->GetEvent(i);
AliTPCseed* sdc = new( NextFreeSeed() ) AliTPCseed(*seed/*,seed->GetAlpha()*/);
sdc->SetPoolID(fLastSeedID);
fSeeds->AddLast(sdc);
}
delete seed; // RS: this seed is not from the pool, delete it !!!
delete seedTree;
savedir->cd();
return 0;
}
Int_t AliTPCtracker::Clusters2TracksHLT (AliESDEvent *const esd, const AliESDEvent *hltEvent)
{
//
// clusters to tracks
if (fSeeds) DeleteSeeds();
else ResetSeedsPool();
fEvent = esd;
fEventHLT = hltEvent;
fAccountDistortions = AliTPCReconstructor::GetRecoParam()->GetAccountDistortions();
if (AliTPCReconstructor::GetRecoParam()->GetUseOulierClusterFilter()) FilterOutlierClusters();
AliTPCTransform *transform = AliTPCcalibDB::Instance()->GetTransform() ;
transform->SetCurrentRecoParam((AliTPCRecoParam*)AliTPCReconstructor::GetRecoParam());
transform->SetCurrentTimeStamp( esd->GetTimeStamp());
transform->SetCurrentRun(esd->GetRunNumber());
//
if (AliTPCReconstructor::GetExtendedRoads()){
fClExtraRoadY = AliTPCReconstructor::GetExtendedRoads()[0];
fClExtraRoadZ = AliTPCReconstructor::GetExtendedRoads()[1];
AliInfoF("Additional errors for roads: Y:%f Z:%f",fClExtraRoadY,fClExtraRoadZ);
}
const Double_t *errCluster = (AliTPCReconstructor::GetSystematicErrorCluster()) ?
AliTPCReconstructor::GetSystematicErrorCluster() :
AliTPCReconstructor::GetRecoParam()->GetSystematicErrorCluster();
//
fExtraClErrY2 = errCluster[0]*errCluster[0];
fExtraClErrZ2 = errCluster[1]*errCluster[1];
fExtraClErrYZ2 = fExtraClErrY2 + fExtraClErrZ2;
AliInfoF("Additional errors for clusters: Y:%f Z:%f",errCluster[0],errCluster[1]);
//
if (AliTPCReconstructor::GetPrimaryDCACut()) {
fPrimaryDCAYCut = AliTPCReconstructor::GetPrimaryDCACut()[0];
fPrimaryDCAZCut = AliTPCReconstructor::GetPrimaryDCACut()[1];
fDisableSecondaries = kTRUE;
AliInfoF("Only primaries will be tracked with DCAY=%f and DCAZ=%f cuts",fPrimaryDCAYCut,fPrimaryDCAZCut);
}
//
Clusters2Tracks();
fEventHLT = 0;
if (!fSeeds) return 1;
FillESD(fSeeds);
if ((AliTPCReconstructor::StreamLevel()&kStreamClDump)>0) DumpClusters(0,fSeeds);
return 0;
//
}
Int_t AliTPCtracker::Clusters2Tracks(AliESDEvent *const esd)
{
//
// clusters to tracks
return Clusters2TracksHLT( esd, 0);
}
//_____________________________________________________________________________
Int_t AliTPCtracker::Clusters2Tracks() {
//-----------------------------------------------------------------
// This is a track finder.
//-----------------------------------------------------------------
TDirectory *savedir=gDirectory;
TStopwatch timer;
fIteration = 0;
fSeeds = Tracking();
if (fDebug>0){
Info("Clusters2Tracks","Time for tracking: \t");timer.Print();timer.Start();
}
//activate again some tracks
for (Int_t i=0; i<fSeeds->GetEntriesFast(); i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<20) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
CookLabel(pt,0.1);
if (pt->GetRemoval()==10) {
if (pt->GetDensityFirst(20)>0.8 || pt->GetDensityFirst(30)>0.8 || pt->GetDensityFirst(40)>0.7)
pt->Desactivate(10); // make track again active // MvL: should be 0 ?
else{
pt->Desactivate(20);
MarkSeedFree( fSeeds->RemoveAt(i) );
}
}
}
//
RemoveUsed2(fSeeds,0.85,0.85,0);
if (AliTPCReconstructor::GetRecoParam()->GetDoKinks()) FindKinks(fSeeds,fEvent);
//FindCurling(fSeeds, fEvent,0);
if (AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC) FindMultiMC(fSeeds, fEvent,-1); // find multi found tracks
RemoveUsed2(fSeeds,0.5,0.4,20);
FindSplitted(fSeeds, fEvent,0); // find multi found tracks
if (AliTPCReconstructor::StreamLevel()&kStreamFindMultiMC) FindMultiMC(fSeeds, fEvent,0); // find multi found tracks
// //
// // refit short tracks
// //
Int_t nseed=fSeeds->GetEntriesFast();
//
Int_t found = 0;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<15) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
CookLabel(pt,0.1); //For comparison only
//if ((pt->IsActive() || (pt->fRemoval==10) )&& nc>50 &&pt->GetNumberOfClusters()>0.4*pt->fNFoundable){
if ((pt->IsActive() || (pt->GetRemoval()==10) )){
found++;
if (fDebug>0) cerr<<found<<'\r';
pt->SetLab2(i);
}
else
MarkSeedFree( fSeeds->RemoveAt(i) );
}
//RemoveOverlap(fSeeds,0.99,7,kTRUE);
SignShared(fSeeds);
//RemoveUsed(fSeeds,0.9,0.9,6);
//
nseed=fSeeds->GetEntriesFast();
found = 0;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<15) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
t.SetUniqueID(i);
t.CookdEdx(0.02,0.6);
// CheckKinkPoint(&t,0.05);
//if ((pt->IsActive() || (pt->fRemoval==10) )&& nc>50 &&pt->GetNumberOfClusters()>0.4*pt->fNFoundable){
if ((pt->IsActive() || (pt->GetRemoval()==10) )){
found++;
if (fDebug>0){
cerr<<found<<'\r';
}
pt->SetLab2(i);
}
else
MarkSeedFree( fSeeds->RemoveAt(i) );
//AliTPCseed * seed1 = ReSeed(pt,0.05,0.5,1);
//if (seed1){
// FollowProlongation(*seed1,0);
// Int_t n = seed1->GetNumberOfClusters();
// printf("fP4\t%f\t%f\n",seed1->GetC(),pt->GetC());
// printf("fN\t%d\t%d\n", seed1->GetNumberOfClusters(),pt->GetNumberOfClusters());
//
//}
//AliTPCseed * seed2 = ReSeed(pt,0.95,0.5,0.05);
}
SortTracks(fSeeds, 1);
/*
fIteration = 1;
PrepareForBackProlongation(fSeeds,5.);
PropagateBack(fSeeds);
printf("Time for back propagation: \t");timer.Print();timer.Start();
fIteration = 2;
PrepareForProlongation(fSeeds,5.);
PropagateForard2(fSeeds);
printf("Time for FORWARD propagation: \t");timer.Print();timer.Start();
// RemoveUsed(fSeeds,0.7,0.7,6);
//RemoveOverlap(fSeeds,0.9,7,kTRUE);
nseed=fSeeds->GetEntriesFast();
found = 0;
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)fSeeds->UncheckedAt(i), &t=*pt;
if (!pt) continue;
Int_t nc=t.GetNumberOfClusters();
if (nc<15) {
MarkSeedFree( fSeeds->RemoveAt(i) );
continue;
}
t.CookdEdx(0.02,0.6);
// CookLabel(pt,0.1); //For comparison only
//if ((pt->IsActive() || (pt->fRemoval==10) )&& nc>50 &&pt->GetNumberOfClusters()>0.4*pt->fNFoundable){
if ((pt->IsActive() || (pt->fRemoval==10) )){
cerr<<found++<<'\r';
}
else
MarkSeedFree( fSeeds->RemoveAt(i) );
pt->fLab2 = i;
}
*/
// fNTracks = found;
if (fDebug>0){
Info("Clusters2Tracks","Time for overlap removal, track writing and dedx cooking: \t"); timer.Print();timer.Start();
}
//
// cerr<<"Number of found tracks : "<<"\t"<<found<<endl;
Info("Clusters2Tracks","Number of found tracks %d",found);
savedir->cd();
// UnloadClusters();
//
return 0;
}
void AliTPCtracker::Tracking(TObjArray * arr)
{
//
// tracking of the seeds
//
fSectors = fOuterSec;
ParallelTracking(arr,150,63);
fSectors = fOuterSec;
ParallelTracking(arr,63,0);
}
TObjArray * AliTPCtracker::Tracking(Int_t seedtype, Int_t i1, Int_t i2, Float_t cuts[4], Float_t dy, Int_t dsec)
{
//
//
//tracking routine
static TObjArray arrTracks;
TObjArray * arr = &arrTracks;
//
fSectors = fOuterSec;
TStopwatch timer;
timer.Start();
for (Int_t sec=0;sec<fkNOS;sec++){
if (fAccountDistortions) {
if (seedtype==3) MakeSeeds3Dist(arr,sec,i1,i2,cuts,dy, dsec);
if (seedtype==4) MakeSeeds5Dist(arr,sec,i1,i2,cuts,dy);
if (seedtype==2) MakeSeeds2Dist(arr,sec,i1,i2,cuts,dy); //RS
}
else {
if (seedtype==3) MakeSeeds3(arr,sec,i1,i2,cuts,dy, dsec);
if (seedtype==4) MakeSeeds5(arr,sec,i1,i2,cuts,dy);
if (seedtype==2) MakeSeeds2(arr,sec,i1,i2,cuts,dy); //RS
}
//
}
if (fDebug>0){
Info("Tracking","\nSeeding - %d\t%d\t%d\t%d\n",seedtype,i1,i2,arr->GetEntriesFast());
timer.Print();
timer.Start();
}
Tracking(arr);
if (fDebug>0){
timer.Print();
}
return arr;
}
TObjArray * AliTPCtracker::Tracking()
{
// tracking
//
if (AliTPCReconstructor::GetRecoParam()->GetSpecialSeeding()) return TrackingSpecial();
TStopwatch timer;
timer.Start();
Int_t nup=fOuterSec->GetNRows()+fInnerSec->GetNRows();
TObjArray * seeds = fSeeds;
if (!seeds) seeds = new TObjArray;
else seeds->Clear();
TObjArray * arr=0;
Int_t fLastSeedRowSec=AliTPCReconstructor::GetRecoParam()->GetLastSeedRowSec();
Int_t gapPrim = AliTPCReconstructor::GetRecoParam()->GetSeedGapPrim();
Int_t gapSec = AliTPCReconstructor::GetRecoParam()->GetSeedGapSec();
Int_t gap =20;
Float_t cuts[4];
cuts[0] = 0.002;
cuts[1] = 1.5;
cuts[2] = 3.;
cuts[3] = 3.;
Float_t fnumber = 3.0;
Float_t fdensity = 3.0;
// make HLT seeds
if (AliTPCReconstructor::GetRecoParam()->GetUseHLTPreSeeding()) {
arr = MakeSeedsHLT( fEventHLT );
if( arr ){
SumTracks(seeds,arr);
delete arr;
arr=0;
//cout<<"HLT tracks left after sorting: "<<seeds->GetEntriesFast()<<endl;
//SignClusters(seeds,fnumber,fdensity);
}
}
//
//find primaries
cuts[0]=0.0066;
for (Int_t delta = 0; delta<18; delta+=gapPrim){
//
cuts[0]=0.0070;
cuts[1] = 1.5;
arr = Tracking(3,nup-1-delta,nup-1-delta-gap,cuts,-1,1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
for (Int_t i=2;i<6;i+=2){
// seed high pt tracks
cuts[0]=0.0022;
cuts[1]=0.3;
arr = Tracking(3,nup-i-delta,nup-i-delta-gap,cuts,-1,0);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
}
fnumber = 4;
fdensity = 4.;
// RemoveUsed(seeds,0.9,0.9,1);
// UnsignClusters();
// SignClusters(seeds,fnumber,fdensity);
//find primaries
cuts[0]=0.0077;
for (Int_t delta = 20; delta<120; delta+=gapPrim){
//
// seed high pt tracks
cuts[0]=0.0060;
cuts[1]=0.3;
cuts[2]=6.;
arr = Tracking(3,nup-delta,nup-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
cuts[0]=0.003;
cuts[1]=0.3;
cuts[2]=6.;
arr = Tracking(3,nup-delta-5,nup-delta-5-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
cuts[0] = 0.01;
cuts[1] = 2.0;
cuts[2] = 3.;
cuts[3] = 2.0;
fnumber = 2.;
fdensity = 2.;
if (fDebug>0){
Info("Tracking()","\n\nPrimary seeding\t%d\n\n",seeds->GetEntriesFast());
timer.Print();
timer.Start();
}
// RemoveUsed(seeds,0.75,0.75,1);
//UnsignClusters();
//SignClusters(seeds,fnumber,fdensity);
if (fDisableSecondaries) return seeds;
// find secondaries
cuts[0] = 0.3;
cuts[1] = 1.5;
cuts[2] = 3.;
cuts[3] = 1.5;
arr = Tracking(4,nup-1,nup-1-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-2,nup-2-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-3,nup-3-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-5,nup-5-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-7,nup-7-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
//
arr = Tracking(4,nup-9,nup-9-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
for (Int_t delta = 9; delta<30; delta+=gapSec){
//
cuts[0] = 0.3;
cuts[1] = 1.5;
cuts[2] = 3.;
cuts[3] = 1.5;
arr = Tracking(4,nup-1-delta,nup-1-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-3-delta,nup-5-delta-gap,cuts,4);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
}
fnumber = 1;
fdensity = 1;
//
// change cuts
fnumber = 2.;
fdensity = 2.;
cuts[0]=0.0080;
// find secondaries
for (Int_t delta = 30; delta<fLastSeedRowSec; delta+=gapSec){
//
cuts[0] = 0.3;
cuts[1] = 3.5;
cuts[2] = 3.;
cuts[3] = 3.5;
arr = Tracking(4,nup-1-delta,nup-1-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
//
arr = Tracking(4,nup-5-delta,nup-5-delta-gap,cuts,5 );
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
if (fDebug>0){
Info("Tracking()","\n\nSecondary seeding\t%d\n\n",seeds->GetEntriesFast());
timer.Print();
timer.Start();
}
return seeds;
//
}
TObjArray * AliTPCtracker::TrackingSpecial()
{
//
// seeding adjusted for laser and cosmic tests - short tracks with big inclination angle
// no primary vertex seeding tried
//
TStopwatch timer;
timer.Start();
Int_t nup=fOuterSec->GetNRows()+fInnerSec->GetNRows();
TObjArray * seeds = fSeeds;
if (!seeds) seeds = new TObjArray;
else seeds->Clear();
TObjArray * arr=0;
Int_t gap = 15;
Float_t cuts[4];
Float_t fnumber = 3.0;
Float_t fdensity = 3.0;
// find secondaries
cuts[0] = AliTPCReconstructor::GetRecoParam()->GetMaxC(); // max curvature
cuts[1] = 3.5; // max tan(phi) angle for seeding
cuts[2] = 3.; // not used (cut on z primary vertex)
cuts[3] = 3.5; // max tan(theta) angle for seeding
for (Int_t delta = 0; nup-delta-gap-1>0; delta+=3){
//
arr = Tracking(4,nup-1-delta,nup-1-delta-gap,cuts,-1);
SumTracks(seeds,arr);
SignClusters(seeds,fnumber,fdensity);
}
if (fDebug>0){
Info("Tracking()","\n\nSecondary seeding\t%d\n\n",seeds->GetEntriesFast());
timer.Print();
timer.Start();
}
return seeds;
//
}
void AliTPCtracker::SumTracks(TObjArray *arr1,TObjArray *&arr2)
{
//
//sum tracks to common container
//remove suspicious tracks
// RS: Attention: supplied tracks come in the static array, don't delete them
Int_t nseed = arr2->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt=(AliTPCseed*)arr2->UncheckedAt(i);
if (pt){
//
// remove tracks with too big curvature
//
if (TMath::Abs(pt->GetC())>AliTPCReconstructor::GetRecoParam()->GetMaxC()){
MarkSeedFree( arr2->RemoveAt(i) );
continue;
}
// REMOVE VERY SHORT TRACKS
if (pt->GetNumberOfClusters()<20){
MarkSeedFree( arr2->RemoveAt(i) );
continue;
}// patch 28 fev06
// NORMAL ACTIVE TRACK
if (pt->IsActive()){
arr1->AddLast(arr2->RemoveAt(i));
continue;
}
//remove not usable tracks
if (pt->GetRemoval()!=10){
MarkSeedFree( arr2->RemoveAt(i) );
continue;
}
// ENABLE ONLY ENOUGH GOOD STOPPED TRACKS
if (pt->GetDensityFirst(20)>0.8 || pt->GetDensityFirst(30)>0.8 || pt->GetDensityFirst(40)>0.7)
arr1->AddLast(arr2->RemoveAt(i));
else{
MarkSeedFree( arr2->RemoveAt(i) );
}
}
}
// delete arr2; arr2 = 0; // RS: this is static array, don't delete it
}
void AliTPCtracker::ParallelTracking(TObjArray *const arr, Int_t rfirst, Int_t rlast)
{
//
// try to track in parralel
Int_t nseed=arr->GetEntriesFast();
//prepare seeds for tracking
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i), &t=*pt;
if (!pt) continue;
if (!t.IsActive()) continue;
// follow prolongation to the first layer
if ( (fSectors ==fInnerSec) || (t.GetFirstPoint()-fkParam->GetNRowLow()>rfirst+1) )
FollowProlongation(t, rfirst+1);
}
//
for (Int_t nr=rfirst; nr>=rlast; nr--){
if (nr<fInnerSec->GetNRows())
fSectors = fInnerSec;
else
fSectors = fOuterSec;
// make indexes with the cluster tracks for given
// find nearest cluster
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i), &t=*pt;
if (!pt) continue;
if (nr==80) pt->UpdateReference();
if (!pt->IsActive()) continue;
// if ( (fSectors ==fOuterSec) && (pt->fFirstPoint-fkParam->GetNRowLow())<nr) continue;
if (pt->GetRelativeSector()>17) {
continue;
}
UpdateClusters(t,nr);
}
// prolonagate to the nearest cluster - if founded
for (Int_t i=0; i<nseed; i++) {
AliTPCseed *pt=(AliTPCseed*)arr->UncheckedAt(i);
if (!pt) continue;
if (!pt->IsActive()) continue;
// if ((fSectors ==fOuterSec) && (pt->fFirstPoint-fkParam->GetNRowLow())<nr) continue;
if (pt->GetRelativeSector()>17) {
continue;
}
FollowToNextCluster(*pt,nr);
}
}
}
void AliTPCtracker::PrepareForBackProlongation(const TObjArray *const arr,Float_t fac) const
{
//
//
// if we use TPC track itself we have to "update" covariance
//
Int_t nseed= arr->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt) {
pt->Modify(fac);
//
//rotate to current local system at first accepted point
Int_t index = pt->GetClusterIndex2(pt->GetFirstPoint());
Int_t sec = (index&0xff000000)>>24;
sec = sec%18;
Float_t angle1 = fInnerSec->GetAlpha()*sec+fInnerSec->GetAlphaShift();
if (angle1>TMath::Pi())
angle1-=2.*TMath::Pi();
Float_t angle2 = pt->GetAlpha();
if (TMath::Abs(angle1-angle2)>0.001){
if (!pt->Rotate(angle1-angle2)) return;
//angle2 = pt->GetAlpha();
//pt->fRelativeSector = pt->GetAlpha()/fInnerSec->GetAlpha();
//if (pt->GetAlpha()<0)
// pt->fRelativeSector+=18;
//sec = pt->fRelativeSector;
}
}
}
}
void AliTPCtracker::PrepareForProlongation(TObjArray *const arr, Float_t fac) const
{
//
//
// if we use TPC track itself we have to "update" covariance
//
Int_t nseed= arr->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt) {
pt->Modify(fac);
pt->SetFirstPoint(pt->GetLastPoint());
}
}
}
Int_t AliTPCtracker::PropagateBack(const TObjArray *const arr)
{
//
// make back propagation
//
Int_t nseed= arr->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt&& pt->GetKinkIndex(0)<=0) {
//AliTPCseed *pt2 = new AliTPCseed(*pt);
fSectors = fInnerSec;
//FollowBackProlongation(*pt,fInnerSec->GetNRows()-1);
//fSectors = fOuterSec;
FollowBackProlongation(*pt,fInnerSec->GetNRows()+fOuterSec->GetNRows()-1,1);
//if (pt->GetNumberOfClusters()<(pt->fEsd->GetTPCclusters(0)) ){
// Error("PropagateBack","Not prolonged track %d",pt->GetLabel());
// FollowBackProlongation(*pt2,fInnerSec->GetNRows()+fOuterSec->GetNRows()-1);
//}
}
if (pt&& pt->GetKinkIndex(0)>0) {
AliESDkink * kink = fEvent->GetKink(pt->GetKinkIndex(0)-1);
pt->SetFirstPoint(kink->GetTPCRow0());
fSectors = fInnerSec;
FollowBackProlongation(*pt,fInnerSec->GetNRows()+fOuterSec->GetNRows()-1,1);
}
CookLabel(pt,0.3);
}
return 0;
}
Int_t AliTPCtracker::PropagateForward2(const TObjArray *const arr)
{
//
// make forward propagation
//
Int_t nseed= arr->GetEntriesFast();
//
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)arr->UncheckedAt(i);
if (pt) {
FollowProlongation(*pt,0,1,1);
CookLabel(pt,0.3);
}
}
return 0;
}
Int_t AliTPCtracker::PropagateForward()
{
//
// propagate track forward
//UnsignClusters();
Int_t nseed = fSeeds->GetEntriesFast();
for (Int_t i=0;i<nseed;i++){
AliTPCseed *pt = (AliTPCseed*)fSeeds->UncheckedAt(i);
if (pt){
AliTPCseed &t = *pt;
Double_t alpha=t.GetAlpha() - fSectors->GetAlphaShift();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
t.SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
}
}
fSectors = fOuterSec;
ParallelTracking(fSeeds,fOuterSec->GetNRows()+fInnerSec->GetNRows()-1,fInnerSec->GetNRows());
fSectors = fInnerSec;
ParallelTracking(fSeeds,fInnerSec->GetNRows()-1,0);
return 1;
}
Int_t AliTPCtracker::PropagateBack(AliTPCseed *const pt, Int_t row0, Int_t row1)
{
//
// make back propagation, in between row0 and row1
//
if (pt) {
fSectors = fInnerSec;
Int_t r1;
//
if (row1<fSectors->GetNRows())
r1 = row1;
else
r1 = fSectors->GetNRows()-1;
if (row0<fSectors->GetNRows()&& r1>0 )
FollowBackProlongation(*pt,r1);
if (row1<=fSectors->GetNRows())
return 0;
//
r1 = row1 - fSectors->GetNRows();
if (r1<=0) return 0;
if (r1>=fOuterSec->GetNRows()) return 0;
fSectors = fOuterSec;
return FollowBackProlongation(*pt,r1);
}
return 0;
}
void AliTPCtracker::GetShape(AliTPCseed * seed, Int_t row)
{
// gets cluster shape
//
AliTPCClusterParam * clparam = AliTPCcalibDB::Instance()->GetClusterParam();
Float_t zdrift = TMath::Abs((fkParam->GetZLength(0)-TMath::Abs(seed->GetZ())));
Int_t type = (seed->GetSector() < fkParam->GetNSector()/2) ? 0: (row>126) ? 1:2;
Double_t angulary = seed->GetSnp();
if (TMath::Abs(angulary)>AliTPCReconstructor::GetMaxSnpTracker()) {
angulary = TMath::Sign(AliTPCReconstructor::GetMaxSnpTracker(),angulary);
}
angulary = angulary*angulary/((1.-angulary)*(1.+angulary));
Double_t angularz = seed->GetTgl()*seed->GetTgl()*(1.+angulary);
Double_t sigmay = clparam->GetRMS0(0,type,zdrift,TMath::Sqrt(TMath::Abs(angulary)));
Double_t sigmaz = clparam->GetRMS0(1,type,zdrift,TMath::Sqrt(TMath::Abs(angularz)));
seed->SetCurrentSigmaY2(sigmay*sigmay);
seed->SetCurrentSigmaZ2(sigmaz*sigmaz);
// Float_t sd2 = TMath::Abs((fkParam->GetZLength(0)-TMath::Abs(seed->GetZ())))*fkParam->GetDiffL()*fkParam->GetDiffL();
// // Float_t padlength = fkParam->GetPadPitchLength(seed->fSector);
// Float_t padlength = GetPadPitchLength(row);
// //
// Float_t sresy = (seed->GetSector() < fkParam->GetNSector()/2) ? 0.2 :0.3;
// seed->SetCurrentSigmaY2(sd2+padlength*padlength*angulary/12.+sresy*sresy);
// //
// Float_t sresz = fkParam->GetZSigma();
// seed->SetCurrentSigmaZ2(sd2+padlength*padlength*angularz*angularz*(1+angulary)/12.+sresz*sresz);
/*
Float_t wy = GetSigmaY(seed);
Float_t wz = GetSigmaZ(seed);
wy*=wy;
wz*=wz;
if (TMath::Abs(wy/seed->fCurrentSigmaY2-1)>0.0001 || TMath::Abs(wz/seed->fCurrentSigmaZ2-1)>0.0001 ){
printf("problem\n");
}
*/
}
//__________________________________________________________________________
void AliTPCtracker::CookLabel(AliKalmanTrack *tk, Float_t wrong) const {
//--------------------------------------------------------------------
//This function "cooks" a track label. If label<0, this track is fake.
//--------------------------------------------------------------------
// AliTPCseed * t = dynamic_cast<AliTPCseed*>(tk);
// if(!t){
// printf("%s:%d wrong type \n",(char*)__FILE__,__LINE__);
// return;
// }
AliTPCseed * t = (AliTPCseed*)tk; // RS avoid slow dynamic cast
Int_t noc=t->GetNumberOfClusters();
if (noc<10){
//printf("\nnot founded prolongation\n\n\n");
//t->Dump();
return ;
}
Int_t lb[kMaxRow];
Int_t mx[kMaxRow];
AliTPCclusterMI *clusters[kMaxRow];
//
for (Int_t i=0;i<kMaxRow;i++) {
clusters[i]=0;
lb[i]=mx[i]=0;
}
Int_t i;
Int_t current=0;
for (i=0; i<kMaxRow && current<noc; i++) {
Int_t index=t->GetClusterIndex2(i);
if (index<=0) continue;
if (index&0x8000) continue;
//
clusters[current++]=GetClusterMI(index);
// if (t->GetClusterPointer(i)){
// clusters[current]=t->GetClusterPointer(i);
// current++;
// }
}
noc = current;
Int_t lab=123456789;
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
lab=TMath::Abs(c->GetLabel(0));
Int_t j;
for (j=0; j<noc; j++) if (lb[j]==lab || mx[j]==0) break;
lb[j]=lab;
(mx[j])++;
}
Int_t max=0;
for (i=0; i<noc; i++) if (mx[i]>max) {max=mx[i]; lab=lb[i];}
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (TMath::Abs(c->GetLabel(1)) == lab ||
TMath::Abs(c->GetLabel(2)) == lab ) max++;
}
if (noc<=0) { lab=-1; return;}
if ((1.- Float_t(max)/(noc)) > wrong) lab=-lab;
else {
Int_t tail=Int_t(0.10*noc);
max=0;
Int_t ind=0;
for (i=1; i<kMaxRow&&ind<tail; i++) {
// AliTPCclusterMI *c=clusters[noc-i];
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (lab == TMath::Abs(c->GetLabel(0)) ||
lab == TMath::Abs(c->GetLabel(1)) ||
lab == TMath::Abs(c->GetLabel(2))) max++;
ind++;
}
if (max < Int_t(0.5*tail)) lab=-lab;
}
t->SetLabel(lab);
// delete[] lb;
//delete[] mx;
//delete[] clusters;
}
//__________________________________________________________________________
Int_t AliTPCtracker::CookLabel(AliTPCseed *const t, Float_t wrong,Int_t first, Int_t last) const {
//--------------------------------------------------------------------
//This function "cooks" a track label. If label<0, this track is fake.
//--------------------------------------------------------------------
Int_t noc=t->GetNumberOfClusters();
if (noc<10){
//printf("\nnot founded prolongation\n\n\n");
//t->Dump();
return -1;
}
Int_t lb[kMaxRow];
Int_t mx[kMaxRow];
AliTPCclusterMI *clusters[kMaxRow];
//
for (Int_t i=0;i<kMaxRow;i++) {
clusters[i]=0;
lb[i]=mx[i]=0;
}
Int_t i;
Int_t current=0;
for (i=0; i<kMaxRow && current<noc; i++) {
if (i<first) continue;
if (i>last) continue;
Int_t index=t->GetClusterIndex2(i);
if (index<=0) continue;
if (index&0x8000) continue;
//
clusters[current++]=GetClusterMI(index);
// if (t->GetClusterPointer(i)){
// clusters[current]=t->GetClusterPointer(i);
// current++;
// }
}
noc = current;
//if (noc<5) return -1;
Int_t lab=123456789;
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
lab=TMath::Abs(c->GetLabel(0));
Int_t j;
for (j=0; j<noc; j++) if (lb[j]==lab || mx[j]==0) break;
lb[j]=lab;
(mx[j])++;
}
Int_t max=0;
for (i=0; i<noc; i++) if (mx[i]>max) {max=mx[i]; lab=lb[i];}
for (i=0; i<noc; i++) {
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (TMath::Abs(c->GetLabel(1)) == lab ||
TMath::Abs(c->GetLabel(2)) == lab ) max++;
}
if (noc<=0) { lab=-1; return -1;}
if ((1.- Float_t(max)/(noc)) > wrong) lab=-lab;
else {
Int_t tail=Int_t(0.10*noc);
max=0;
Int_t ind=0;
for (i=1; i<kMaxRow&&ind<tail; i++) {
// AliTPCclusterMI *c=clusters[noc-i];
AliTPCclusterMI *c=clusters[i];
if (!c) continue;
if (lab == TMath::Abs(c->GetLabel(0)) ||
lab == TMath::Abs(c->GetLabel(1)) ||
lab == TMath::Abs(c->GetLabel(2))) max++;
ind++;
}
if (max < Int_t(0.5*tail)) lab=-lab;
}
// t->SetLabel(lab);
return lab;
// delete[] lb;
//delete[] mx;
//delete[] clusters;
}
Int_t AliTPCtracker::GetRowNumber(Double_t x[3]) const
{
//return pad row number for given x vector
Float_t phi = TMath::ATan2(x[1],x[0]);
if(phi<0) phi=2.*TMath::Pi()+phi;
// Get the local angle in the sector philoc
const Float_t kRaddeg = 180/3.14159265358979312;
Float_t phiangle = (Int_t (phi*kRaddeg/20.) + 0.5)*20./kRaddeg;
Double_t localx = x[0]*TMath::Cos(phiangle)-x[1]*TMath::Sin(phiangle);
return GetRowNumber(localx);
}
void AliTPCtracker::MakeESDBitmaps(AliTPCseed *t, AliESDtrack *esd)
{
//-----------------------------------------------------------------------
// Fill the cluster and sharing bitmaps of the track
//-----------------------------------------------------------------------
Int_t firstpoint = 0;
Int_t lastpoint = kMaxRow;
// AliTPCclusterMI *cluster;
Int_t nclsf = 0;
TBits clusterMap(kMaxRow);
TBits sharedMap(kMaxRow);
TBits fitMap(kMaxRow);
for (int iter=firstpoint; iter<lastpoint; iter++) {
// Change to cluster pointers to see if we have a cluster at given padrow
Int_t tpcindex= t->GetClusterIndex2(iter);
if (tpcindex>=0) {
clusterMap.SetBitNumber(iter, kTRUE);
if (t->IsShared(iter)) sharedMap.SetBitNumber(iter,kTRUE); // RS shared flag moved to seed
//
if ( (tpcindex&0x8000) == 0) {
fitMap.SetBitNumber(iter, kTRUE);
nclsf++;
}
}
// if (t->GetClusterIndex(iter) >= 0 && (t->GetClusterIndex(iter) & 0x8000) == 0) {
// fitMap.SetBitNumber(iter, kTRUE);
// nclsf++;
// }
}
esd->SetTPCClusterMap(clusterMap);
esd->SetTPCSharedMap(sharedMap);
esd->SetTPCFitMap(fitMap);
if (nclsf != t->GetNumberOfClusters())
AliDebug(3,Form("Inconsistency between ncls %d and indices %d (found %d)",t->GetNumberOfClusters(),nclsf,esd->GetTPCClusterMap().CountBits()));
}
Bool_t AliTPCtracker::IsFindable(AliTPCseed & track){
//
// return flag if there is findable cluster at given position
//
Float_t kDeltaZ=10;
Float_t z = track.GetZ();
if (TMath::Abs(z)<(AliTPCReconstructor::GetCtgRange()*track.GetX()+kDeltaZ) &&
TMath::Abs(z)<fkParam->GetZLength(0) &&
(TMath::Abs(track.GetSnp())<AliTPCReconstructor::GetMaxSnpTracker()))
return kTRUE;
return kFALSE;
}
void AliTPCtracker::AddCovariance(AliTPCseed * seed){
//
// Adding systematic error estimate to the covariance matrix
// !!!! the systematic error for element 4 is in 1/GeV
// 03.03.2012 MI changed in respect to the previous versions
// in case systemtic errors defiend statically no correlation added (needed for CPass0)
const Double_t *param = (AliTPCReconstructor::GetSystematicError()!=NULL) ? AliTPCReconstructor::GetSystematicError():AliTPCReconstructor::GetRecoParam()->GetSystematicError();
//
// use only the diagonal part if not specified otherwise
if (!AliTPCReconstructor::GetRecoParam()->GetUseSystematicCorrelation() || AliTPCReconstructor::GetSystematicError()) return AddCovarianceAdd(seed);
//
Double_t *covarS= (Double_t*)seed->GetCovariance();
Double_t factor[5]={1,1,1,1,1};
factor[0]= TMath::Sqrt(TMath::Abs((covarS[0] + param[0]*param[0])/covarS[0]));
factor[1]= TMath::Sqrt(TMath::Abs((covarS[2] + param[1]*param[1])/covarS[2]));
factor[2]= TMath::Sqrt(TMath::Abs((covarS[5] + param[2]*param[2])/covarS[5]));
factor[3]= TMath::Sqrt(TMath::Abs((covarS[9] + param[3]*param[3])/covarS[9]));
factor[4]= TMath::Sqrt(TMath::Abs((covarS[14] +param[4]*param[4])/covarS[14]));
//
factor[0]=factor[2];
factor[4]=factor[2];
// 0
// 1 2
// 3 4 5
// 6 7 8 9
// 10 11 12 13 14
for (Int_t i=0; i<5; i++){
for (Int_t j=i; j<5; j++){
Int_t index=seed->GetIndex(i,j);
covarS[index]*=factor[i]*factor[j];
}
}
}
void AliTPCtracker::AddCovarianceAdd(AliTPCseed * seed){
//
// Adding systematic error - as additive factor without correlation
//
// !!!! the systematic error for element 4 is in 1/GeV
// 03.03.2012 MI changed in respect to the previous versions
const Double_t *param = (AliTPCReconstructor::GetSystematicError()!=NULL) ? AliTPCReconstructor::GetSystematicError():AliTPCReconstructor::GetRecoParam()->GetSystematicError();
Double_t *covarIn= (Double_t*)seed->GetCovariance();
Double_t covar[15];
for (Int_t i=0;i<15;i++) covar[i]=0;
// 0
// 1 2
// 3 4 5
// 6 7 8 9
// 10 11 12 13 14
covar[0] = param[0]*param[0];
covar[2] = param[1]*param[1];
covar[5] = param[2]*param[2];
covar[9] = param[3]*param[3];
covar[14]= param[4]*param[4];
//
covar[1]=TMath::Sqrt((covar[0]*covar[2]))*covarIn[1]/TMath::Sqrt((covarIn[0]*covarIn[2]));
//
covar[3]=TMath::Sqrt((covar[0]*covar[5]))*covarIn[3]/TMath::Sqrt((covarIn[0]*covarIn[5]));
covar[4]=TMath::Sqrt((covar[2]*covar[5]))*covarIn[4]/TMath::Sqrt((covarIn[2]*covarIn[5]));
//
covar[6]=TMath::Sqrt((covar[0]*covar[9]))*covarIn[6]/TMath::Sqrt((covarIn[0]*covarIn[9]));
covar[7]=TMath::Sqrt((covar[2]*covar[9]))*covarIn[7]/TMath::Sqrt((covarIn[2]*covarIn[9]));
covar[8]=TMath::Sqrt((covar[5]*covar[9]))*covarIn[8]/TMath::Sqrt((covarIn[5]*covarIn[9]));
//
covar[10]=TMath::Sqrt((covar[0]*covar[14]))*covarIn[10]/TMath::Sqrt((covarIn[0]*covarIn[14]));
covar[11]=TMath::Sqrt((covar[2]*covar[14]))*covarIn[11]/TMath::Sqrt((covarIn[2]*covarIn[14]));
covar[12]=TMath::Sqrt((covar[5]*covar[14]))*covarIn[12]/TMath::Sqrt((covarIn[5]*covarIn[14]));
covar[13]=TMath::Sqrt((covar[9]*covar[14]))*covarIn[13]/TMath::Sqrt((covarIn[9]*covarIn[14]));
//
seed->AddCovariance(covar);
}
//_____________________________________________________________________________
Bool_t AliTPCtracker::IsTPCHVDipEvent(AliESDEvent const *esdEvent)
{
//
// check events affected by TPC HV dip
//
if(!esdEvent) return kFALSE;
// Init TPC OCDB
AliTPCcalibDB *db=AliTPCcalibDB::Instance();
if(!db) return kFALSE;
db->SetRun(esdEvent->GetRunNumber());
// maximum allowed voltage before an event is identified as a dip event
// and scanning period
const Double_t kTPCHVdip = db->GetParameters()->GetMaxDipVoltage();
const Double_t dipEventScanPeriod = db->GetParameters()->GetVoltageDipScanPeriod();
const Double_t tevSec = esdEvent->GetTimeStamp();
for(Int_t sector=0; sector<72; sector++)
{
// don't use excluded chambers, since the state is not defined at all
if (!db->GetChamberHVStatus(sector)) continue;
// get hv sensor of the chamber
AliDCSSensor *sensor = db->GetChamberHVSensor(sector);
if (!sensor) continue;
TGraph *grSensor=sensor->GetGraph();
if (!grSensor) continue;
if (grSensor->GetN()<1) continue;
// get median
const Double_t median = db->GetChamberHighVoltageMedian(sector);
if(median < 1.) continue;
for (Int_t ipoint=0; ipoint<grSensor->GetN()-1; ++ipoint){
Double_t nextTime=grSensor->GetX()[ipoint+1]*3600+sensor->GetStartTime();
if (tevSec-dipEventScanPeriod>nextTime) continue;
const Float_t deltaV=TMath::Abs(grSensor->GetY()[ipoint]-median);
if (deltaV>kTPCHVdip) {
AliDebug(3,Form("HV dip detected in ROC '%02d' with dV '%.2f' at time stamp '%.0f'",sector,deltaV,tevSec));
return kTRUE;
}
if (nextTime>tevSec+dipEventScanPeriod) break;
}
}
return kFALSE;
}
//________________________________________
void AliTPCtracker::MarkSeedFree(TObject *sd)
{
// account that this seed is "deleted"
// AliTPCseed* seed = dynamic_cast<AliTPCseed*>(sd);
// if (!seed) {
// AliError(Form("Freeing of non-AliTPCseed %p from the pool is requested",sd));
// return;
// }
AliTPCseed* seed = (AliTPCseed*)sd;
int id = seed->GetPoolID();
if (id<0) {
AliError(Form("Freeing of seed %p NOT from the pool is requested",sd));
return;
}
// AliInfo(Form("%d %p",id, seed));
fSeedsPool->RemoveAt(id);
if (fFreeSeedsID.GetSize()<=fNFreeSeeds) fFreeSeedsID.Set( 2*fNFreeSeeds + 100 );
fFreeSeedsID.GetArray()[fNFreeSeeds++] = id;
}
//________________________________________
TObject *&AliTPCtracker::NextFreeSeed()
{
// return next free slot where the seed can be created
fLastSeedID = fNFreeSeeds ? fFreeSeedsID.GetArray()[--fNFreeSeeds] : fSeedsPool->GetEntriesFast();
// AliInfo(Form("%d",fLastSeedID));
return (*fSeedsPool)[ fLastSeedID ];
//
}
//________________________________________
void AliTPCtracker::ResetSeedsPool()
{
// mark all seeds in the pool as unused
AliInfo(Form("CurrentSize: %d, BookedUpTo: %d, free: %d",fSeedsPool->GetSize(),fSeedsPool->GetEntriesFast(),fNFreeSeeds));
fNFreeSeeds = 0;
fSeedsPool->Clear(); // RS: nominally the seeds may allocate memory...
}
Int_t AliTPCtracker::PropagateToRowHLT(AliTPCseed *pt, int nrow)
{
AliTPCseed &t=*pt;
Double_t x= GetXrow(nrow);
Double_t ymax= GetMaxY(nrow);
Int_t rotate = 0;
Int_t nRotations=0;
int ret = 1;
do{
rotate = 0;
if (!t.PropagateTo(x) ){
//cout<<"can't propagate to row "<<nrow<<", x="<<t.GetX()<<" -> "<<x<<endl;
//t.Print();
ret = 0;
break;
}
t.SetRow(nrow);
Double_t y = t.GetY();
if( y > ymax ) {
if( rotate!=-1 ) rotate=1;
} else if (y <-ymax) {
if( rotate!=1 ) rotate = -1;
}
if( rotate==0 ) break;
//cout<<"rotate at row "<<nrow<<": "<<rotate<<endl;
if (!t.Rotate( rotate==1 ?fSectors->GetAlpha() :-fSectors->GetAlpha())) {
//cout<<"can't rotate "<<endl;
ret=0;
break;
}
nRotations+= rotate;
}while(rotate!=0);
if( nRotations!=0 ){
int newSec= t.GetRelativeSector()+nRotations;
if( newSec>=fN ) newSec-=fN;
else if( newSec<0 ) newSec +=fN;
//cout<<"rotate at row "<<nrow<<": "<<nRotations<<" times "<<" sec "
//<< t.GetRelativeSector()<<" -> "<<newSec<<endl;
t.SetRelativeSector(newSec);
}
return ret;
}
void AliTPCtracker::TrackFollowingHLT(TObjArray *const arr )
{
//
// try to track in parralel
AliFatal("RS: This method is not yet aware of cluster pointers no present in the in-memory tracks");
Int_t nRows=fOuterSec->GetNRows()+fInnerSec->GetNRows();
fSectors=fInnerSec;
Int_t nseed=arr->GetEntriesFast();
//cout<<"Parallel tracking My.."<<endl;
double shapeY2[kMaxRow], shapeZ2[kMaxRow];
Int_t clusterIndex[kMaxRow];
for (Int_t iSeed=0; iSeed<nseed; iSeed++) {
//if( iSeed!=1 ) continue;
AliTPCseed *pt=(AliTPCseed*) (arr->UncheckedAt(iSeed));
if (!pt) continue;
AliTPCseed &t=*pt;
//cout <<"Pt "<<t.GetSigned1Pt()<<endl;
// t.Print();
for( int iter=0; iter<3; iter++ ){
t.Reset();
t.SetLastPoint(0); // first cluster in track position
t.SetFirstPoint(nRows-1);
t.ResetCovariance(.1);
t.SetNumberOfClusters(0);
for( int i=0; i<nRows; i++ ){
shapeY2[i]=1.;
shapeZ2[i]=1.;
clusterIndex[i]=-1;
t.SetClusterIndex2(i,-1);
t.SetClusterIndex(i,-1);
}
// pick up the clusters
Double_t roady = 20.;
Double_t roadz = 20.;
double roadr = 5;
AliTPCseed t0(t);
t0.Reset();
int nClusters = 0;
{
t0.SetRelativeSector(t.GetRelativeSector());
t0.SetLastPoint(0); // first cluster in track position
t0.SetFirstPoint(kMaxRow);
for (Int_t nr=0; nr<nRows; nr++){
if( nr<fInnerSec->GetNRows() ) fSectors=fInnerSec;
else fSectors=fOuterSec;
if( !PropagateToRowHLT(&t0, nr ) ){ break; }
if (TMath::Abs(t0.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()){
//cout<<"Snp is too big: "<<t0.GetSnp()<<endl;
continue;
}
if (!IsActive(t0.GetRelativeSector(),nr)) {
continue;
}
if( iter==0 ){
GetShape(&t0,nr);
shapeY2[nr]=t0.GetCurrentSigmaY2();
shapeZ2[nr]=t0.GetCurrentSigmaZ2();
}
AliTPCtrackerRow &krow=GetRow(t0.GetRelativeSector(),nr);
if( !krow ) continue;
t.SetClusterIndex2(nr,-3); // foundable
t.SetClusterIndex(nr,-3);
AliTPCclusterMI *cl=0;
UInt_t uindex = 0;
cl = krow.FindNearest2(t0.GetY(),t0.GetZ(),roady+fClExtraRoadY,roadz+fClExtraRoadZ,uindex);
if (!cl ) continue;
double dy = cl->GetY()-t0.GetY();
double dz = cl->GetZ()-t0.GetZ();
double dr = sqrt(dy*dy+dz*dz);
if( dr>roadr ){
//cout<<"row "<<nr<<", best cluster r= "<<dr<<" y,z = "<<dy<<" "<<dz<<endl;
continue;
}
//cout<<"row "<<nr<<", found cluster r= "<<dr<<" y,z = "<<dy<<" "<<dz<<endl;
t0.SetClusterPointer(nr, cl);
clusterIndex[nr] = krow.GetIndex(uindex);
if( t0.GetFirstPoint()>nr ) t0.SetFirstPoint(nr);
t0.SetLastPoint(nr);
nClusters++;
}
}
if( nClusters <3 ){
//cout<<"NOT ENOUGTH CLUSTERS: "<<nClusters<<endl;
break;
}
Int_t basePoints[3] = {t0.GetFirstPoint(),t0.GetFirstPoint(),t0.GetLastPoint()};
// find midpoint
{
Int_t midRow = (t0.GetLastPoint()-t0.GetFirstPoint())/2;
int dist=200;
for( int nr=t0.GetFirstPoint()+1; nr< t0.GetLastPoint(); nr++){
//if (t0.GetClusterIndex2(nr)<0) continue;
if( !t0.GetClusterPointer(nr) ) continue;
int d = TMath::Abs(nr-midRow);
if( d < dist ){
dist = d;
basePoints[1] = nr;
}
}
}
// first fit 3 base points
if( 1||iter<2 ){
//cout<<"Fit3: "<<endl;
for( int icl=0; icl<3; icl++){
int nr = basePoints[icl];
int lr=nr;
if( nr>=fInnerSec->GetNRows()){
lr = nr - fInnerSec->GetNRows();
fSectors=fOuterSec;
} else fSectors=fInnerSec;
AliTPCclusterMI *cl=t0.GetClusterPointer(nr);
if(!cl){
//cout<<"WRONG!!!!"<<endl;
continue;
}
int iSec = cl->GetDetector() %fkNIS;
int rotate = iSec - t.GetRelativeSector();
if( rotate!=0 ){
//cout<<"Rotate at row"<<nr<<" to "<<rotate<<" sectors"<<endl;
if (!t.Rotate( rotate*fSectors->GetAlpha()) ) {
//cout<<"can't rotate "<<endl;
break;
}
t.SetRelativeSector(iSec);
}
Double_t x= cl->GetX();
if (!t.PropagateTo(x)){
//cout<<"can't propagate to x="<<x<<endl;
break;
}
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()){
//cout<<"Snp is too big: "<<t.GetSnp()<<endl;
break;
}
//cout<<"fit3 : row "<<nr<<" ind = "<<clusterIndex[nr]<<endl;
t.SetCurrentClusterIndex1(clusterIndex[nr]);
t.SetCurrentCluster(cl);
t.SetRow(lr);
t.SetErrorY2(shapeY2[nr]);
t.SetErrorZ2(shapeZ2[nr]);
if( icl==0 ){
double cov[15];
for( int j=0; j<15; j++ ) cov[j]=0;
cov[0]=10;
cov[2]=10;
cov[5]=.5;
cov[9]=.5;
cov[14]=1.;
t.AliExternalTrackParam::AddCovariance(cov);
}
if( !UpdateTrack(&t,0) ){
//cout<<"Can not update"<<endl;
//t.Print();
t.SetClusterIndex2(nr,-1);
t.SetClusterIndex(nr,-1);
t.SetClusterPointer(nr,0);
break;
}
//t.SetClusterPointer(nr, cl);
}
//t.SetLastPoint(t0.GetLastPoint());
//t.SetFirstPoint(t0.GetFirstPoint());
//cout<<"Fit: "<<endl;
for (Int_t nr=t0.GetLastPoint(); nr>=t0.GetFirstPoint(); nr-- ){
int lr=nr;
if( nr>=fInnerSec->GetNRows()){
lr = nr - fInnerSec->GetNRows();
fSectors=fOuterSec;
} else fSectors=fInnerSec;
if(1|| iter<2 ){
if( nr == basePoints[0] ) continue;
if( nr == basePoints[1] ) continue;
if( nr == basePoints[2] ) continue;
}
AliTPCclusterMI *cl=t0.GetClusterPointer(nr);
if(!cl) continue;
int iSec = cl->GetDetector() %fkNIS;
int rotate = iSec - t.GetRelativeSector();
if( rotate!=0 ){
//cout<<"Rotate at row"<<nr<<" to "<<rotate<<" sectors"<<endl;
if (!t.Rotate( rotate*fSectors->GetAlpha()) ) {
//cout<<"can't rotate "<<endl;
break;
}
t.SetRelativeSector(iSec);
}
Double_t x= cl->GetX();
if (!t.PropagateTo(x)){
//cout<<"can't propagate to x="<<x<<endl;
break;
}
if (TMath::Abs(t.GetSnp())>AliTPCReconstructor::GetMaxSnpTracker()){
//cout<<"Snp is too big: "<<t.GetSnp()<<endl;
break;
}
//cout<<"fit: row "<<nr<<" ind = "<<clusterIndex[nr]<<endl;
t.SetCurrentClusterIndex1(clusterIndex[nr]);
t.SetCurrentCluster(cl);
t.SetRow(lr);
t.SetErrorY2(shapeY2[nr]);
t.SetErrorZ2(shapeZ2[nr]);
if( !UpdateTrack(&t,0) ){
//cout<<"Can not update"<<endl;
//t.Print();
t.SetClusterIndex2(nr,-1);
t.SetClusterIndex(nr,-1);
break;
}
//t.SetClusterPointer(nr, cl);
}
}
//cout<<"After iter "<<iter<<": N clusters="<<t.GetNumberOfClusters()<<" : "<<nClusters<<endl;
}
//cout<<"fitted track"<<iSeed<<endl;
//t.Print();
//cout<<"Statistics: "<<endl;
Int_t foundable,found,shared;
//t.GetClusterStatistic(0,nRows, found, foundable, shared, kTRUE);
t.GetClusterStatistic(0,nRows, found, foundable); //RS shared info is not used, use faster method
t.SetNFoundable(foundable);
//cout<<"found "<<found<<" foundable "<<foundable<<" shared "<<shared<<endl;
}
}
TObjArray * AliTPCtracker::MakeSeedsHLT(const AliESDEvent *hltEvent)
{
// tracking
//
AliFatal("RS: This method is not yet aware of cluster pointers no present in the in-memory tracks");
if( !hltEvent ) return 0;
Int_t nentr=hltEvent->GetNumberOfTracks();
AliInfo(Form("Using %d HLT tracks for seeding",nentr));
TObjArray * seeds = new TObjArray(nentr);
Int_t nup=fOuterSec->GetNRows()+fInnerSec->GetNRows();
Int_t index = 0;
Int_t nTr=hltEvent->GetNumberOfTracks();
for( int itr=0; itr<nTr; itr++ ){
//if( itr!=97 ) continue;
const AliExternalTrackParam *param = hltEvent->GetTrack(itr)->GetTPCInnerParam();
if( !param ) continue;
//if( TMath::Abs(esdTr->GetSigned1Pt())>1 ) continue;
//if( TMath::Abs(esdTr->GetTgl())>1. ) continue;
AliTPCtrack tr;
tr.Set(param->GetX(),param->GetAlpha(),param->GetParameter(),param->GetCovariance());
tr.SetNumberOfClusters(0);
AliTPCseed * seed = new( NextFreeSeed() ) AliTPCseed(tr);
Double_t alpha=seed->GetAlpha();// - fSectors->GetAlphaShift();
if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
if (alpha < 0. ) alpha += 2.*TMath::Pi();
//
seed->SetRelativeSector(Int_t(alpha/fSectors->GetAlpha()+0.0001)%fN);
Double_t alphaSec = fSectors->GetAlpha() * seed->GetRelativeSector() + fSectors->GetAlphaShift();
if (alphaSec >= TMath::Pi()) alphaSec -= 2.*TMath::Pi();
if (alphaSec < -TMath::Pi()) alphaSec += 2.*TMath::Pi();
seed->Rotate(alphaSec - alpha);
seed->SetPoolID(fLastSeedID);
seed->SetIsSeeding(kTRUE);
seed->SetSeed1(nup-1);
seed->SetSeed2(nup-2);
seed->SetSeedType(0);
seed->SetFirstPoint(-1);
seed->SetLastPoint(-1);
seeds->AddLast(seed); // note, track is seed, don't free the seed
index++;
//if( index>3 ) break;
}
fSectors = fOuterSec;
TrackFollowingHLT(seeds );
nTr = seeds->GetEntriesFast();
for( int itr=0; itr<nTr; itr++ ){
AliTPCseed * seed = (AliTPCseed*) seeds->UncheckedAt(itr);
if( !seed ) continue;
//FollowBackProlongation(*seed,0);
// cout<<seed->GetNumberOfClusters()<<endl;
Int_t foundable,found;//,shared;
// seed->GetClusterStatistic(0,nup, found, foundable, shared, kTRUE); //RS shared info is not used, use faster method
seed->GetClusterStatistic(0,nup, found, foundable);
seed->SetNFoundable(foundable);
//cout<<"found "<<found<<" foundable "<<foundable<<" shared "<<shared<<endl;
//if ((found<0.55*foundable) || shared>0.5*found ){// || (seed->GetSigmaY2()+seed->GetSigmaZ2())>0.5){
//MarkSeedFree(seeds->RemoveAt(itr));
//continue;
//}
if (seed->GetNumberOfClusters()<30 ||
seed->GetNumberOfClusters() < seed->GetNFoundable()*0.6 ||
seed->GetNShared()>0.4*seed->GetNumberOfClusters() ) {
MarkSeedFree(seeds->RemoveAt(itr));
continue;
}
for( int ir=0; ir<nup; ir++){
AliTPCclusterMI *c = seed->GetClusterPointer(ir);
if( c ) c->Use(10);
}
}
std::cout<<"\n\nHLT tracks left: "<<seeds->GetEntries()<<" out of "<<hltEvent->GetNumberOfTracks()<<endl<<endl;
return seeds;
}
void AliTPCtracker::FillClusterOccupancyInfo()
{
//fill the cluster occupancy info into the ESD friend
AliESDfriend* esdFriend = static_cast<AliESDfriend*>(fEvent->FindListObject("AliESDfriend"));
if (!esdFriend) return;
for (Int_t isector=0; isector<18; isector++){
AliTPCtrackerSector &iroc = fInnerSec[isector];
AliTPCtrackerSector &oroc = fOuterSec[isector];
//all clusters
esdFriend->SetNclustersTPC(isector, iroc.GetNClInSector(0));
esdFriend->SetNclustersTPC(isector+18,iroc.GetNClInSector(1));
esdFriend->SetNclustersTPC(isector+36,oroc.GetNClInSector(0));
esdFriend->SetNclustersTPC(isector+54,oroc.GetNClInSector(1));
//clusters used in tracking
esdFriend->SetNclustersTPCused(isector, iroc.GetNClUsedInSector(0));
esdFriend->SetNclustersTPCused(isector+18, iroc.GetNClUsedInSector(1));
esdFriend->SetNclustersTPCused(isector+36, oroc.GetNClUsedInSector(0));
esdFriend->SetNclustersTPCused(isector+54, oroc.GetNClUsedInSector(1));
}
}
void AliTPCtracker::FillSeedClusterStatCache(const AliTPCseed* seed)
{
//RS fill cache for seed's cluster statistics evaluation buffer
for (int i=kMaxRow;i--;) {
Int_t index = seed->GetClusterIndex2(i);
fClStatFoundable[i] = (index!=-1);
fClStatFound[i] = fClStatShared[i] = kFALSE;
if (index<0 || (index&0x8000)) continue;
const AliTPCclusterMI* cl = GetClusterMI(index);
if (cl->IsUsed(10)) fClStatShared[i] = kTRUE;
}
}
void AliTPCtracker::GetCachedSeedClusterStatistic(Int_t first, Int_t last, Int_t &found, Int_t &foundable, Int_t &shared, Bool_t plus2) const
{
//RS calculation of cached seed statistics
found = 0;
foundable = 0;
shared = 0;
//
for (Int_t i=first;i<last; i++){
if (fClStatFoundable[i]) foundable++;
else continue;
//
if (fClStatFound[i]) found++;
else continue;
//
if (fClStatShared[i]) {
shared++;
continue;
}
if (!plus2) continue; //take also neighborhoud
//
if ( i>0 && fClStatShared[i-1]) {
shared++;
continue;
}
if ( i<(kMaxRow-1) && fClStatShared[i+1]) {
shared++;
continue;
}
}
}
void AliTPCtracker::GetSeedClusterStatistic(const AliTPCseed* seed, Int_t first, Int_t last, Int_t &found, Int_t &foundable, Int_t &shared, Bool_t plus2) const
{
// RS: get cluster stat. on given region, faster for small regions than cachin the whole seed stat.
//
found = 0;
foundable = 0;
shared =0;
for (Int_t i=first;i<last; i++){
Int_t index = seed->GetClusterIndex2(i);
if (index!=-1) foundable++;
if (index&0x8000) continue;
if (index>=0) found++;
else continue;
const AliTPCclusterMI* cl = GetClusterMI(index);
if (cl->IsUsed(10)) {
shared++;
continue;
}
if (!plus2) continue; //take also neighborhoud
//
if (i>0) {
index = seed->GetClusterIndex2(i-1);
cl = index<0 ? 0:GetClusterMI(index);
if (cl && cl->IsUsed(10)) {
shared++;
continue;
}
}
if (i<(kMaxRow-1)) {
index = seed->GetClusterIndex2(i+1);
cl = index<0 ? 0:GetClusterMI(index);
if (cl && cl->IsUsed(10)) {
shared++;
continue;
}
}
}
}
Bool_t AliTPCtracker::DistortX(const AliTPCseed* seed, double& x, int row)
{
// distort X by the distorion at track location on given row
//
//RS:? think to unset fAccountDistortions if no maps are used
if (!AliTPCReconstructor::GetRecoParam()->GetUseCorrectionMap()) return kTRUE;
double xyz[3];
int rowInp = row;//RS
if (!seed->GetYZAt(x,AliTracker::GetBz(),&xyz[1])) return kFALSE; //RS:? Think to cache fBz?
xyz[0] = x;
int roc = seed->GetRelativeSector();
if (seed->GetZ()<0) roc += 18;
if (row>62) {
roc += 36;
row -= 63;
}
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform();
if (!transform) AliFatal("Tranformations not in calibDB");
x += transform->EvalCorrectionMap(roc,row,xyz,0);
return kTRUE;
}
Double_t AliTPCtracker::GetDistortionX(double x, double y, double z, int sec, int row)
{
// get X distortion at location on given row
//
if (!AliTPCReconstructor::GetRecoParam()->GetUseCorrectionMap()) return 0;
double xyz[3] = {x,y,z};
int rowInp = row;
int secInp = sec;
if (z<0) sec += 18;
if (row>62) {
sec += 36;
row -= 63;
}
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform() ;
if (!transform) AliFatal("Tranformations not in calibDB");
return transform->EvalCorrectionMap(sec,row,xyz,0);
}
Double_t AliTPCtracker::GetYSectEdgeDist(int sec, int row, double y, double z)
{
// get the signed shift for maxY of the sector/row accounting for distortion
// Slow way, to speed up
if (!AliTPCReconstructor::GetRecoParam()->GetUseCorrectionMap()) return 0;
double ymax = 0.9*GetMaxY(row); // evaluate distortions at 5% of pad lenght from the edge
if (y<0) ymax = -ymax;
double xyz[3] = {GetXrow(row),ymax,z};
if (z<0) sec += 18;
if (row>62) {
sec += 36;
row -= 63;
}
AliTPCcalibDB * calibDB = AliTPCcalibDB::Instance();
AliTPCTransform *transform = calibDB->GetTransform();
if (!transform) AliFatal("Tranformations not in calibDB");
// change of distance from the edge due to the X shift
double dxtg = transform->EvalCorrectionMap(sec,row,xyz,0)*AliTPCTransform::GetMaxY2X();
double dy = transform->EvalCorrectionMap(sec,row,xyz,1);
return dy + (y>0?dxtg:-dxtg);
//
}
Int_t AliTPCtracker::GetTrackSector(double alpha)
{
//convert alpha to sector
if (alpha<0) alpha += TMath::Pi()*2;
int sec = alpha/(TMath::Pi()/9);
return sec;
}
void AliTPCtracker::CleanESDFriendsObjects(AliESDEvent* esd)
{
// RS: remove seeds stored in friend's calib object contained w/o changing its ownership
//
AliInfo("Removing own seeds from friend tracks");
AliESDfriend* esdF = esd->FindFriend();
int ntr = esd->GetNumberOfTracks();
for (int itr=ntr;itr--;) {
AliESDtrack* trc = esd->GetTrack(itr);
AliESDfriendTrack* trcF = (AliESDfriendTrack*)trc->GetFriendTrack();
if (!trcF) continue;
AliTPCseed* seed = (AliTPCseed*)trcF->GetTPCseed();
if (seed) {
trcF->RemoveCalibObject((TObject*)seed);
seed->SetClusterOwner(kFALSE);
seed->SetClustersArrayTMP(0);
}
}
//
}
//__________________________________________________________________
void AliTPCtracker::CleanESDTracksObjects(TObjArray* trcList)
{
// RS: remove seeds stored in friend's calib object contained w/o changing its ownership
//
int ntr = trcList->GetEntriesFast();
for (int itr=0;itr<ntr;itr++) {
TObject *obj = trcList->At(itr);
AliESDfriendTrack* trcF = (obj->IsA()==AliESDtrack::Class()) ?
(AliESDfriendTrack*)((AliESDtrack*)obj)->GetFriendTrack() : (AliESDfriendTrack*)obj;
if (!trcF) continue;
AliTPCseed* seed = (AliTPCseed*)trcF->GetTPCseed();
if (seed) {
trcF->RemoveCalibObject((TObject*)seed);
seed->SetClusterOwner(kFALSE);
seed->SetClustersArrayTMP(0);
}
}
//
}
|
/*******************************
Copyright (c) 2016-2022 Grégoire Angerand
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 "memory.h"
#include <y/utils/memory.h>
#include <atomic>
#include <cstdlib>
namespace editor {
namespace memory {
std::atomic<usize> live_allocs = 0;
std::atomic<u64> total_allocs= 0;
usize live_allocations() {
return live_allocs;
}
u64 total_allocations() {
return total_allocs;
}
static void* alloc_internal(usize size, usize alignment = max_alignment) {
size = size ? size : 1;
auto try_alloc = [=] {
#ifdef Y_OS_WIN
return _aligned_malloc(size, alignment);
#else
return std::aligned_alloc(alignment, size);
#endif
};
void* ptr = nullptr;
while((ptr = try_alloc()) == nullptr) {
std::new_handler nh = std::get_new_handler();
if(!nh) {
throw std::bad_alloc{};
}
nh();
}
++total_allocs;
++live_allocs;
y_profile_alloc(ptr, size);
return ptr;
}
static void free_internal(void* ptr) {
if(ptr) {
--live_allocs;
}
y_profile_free(ptr);
#ifdef Y_OS_WIN
_aligned_free(ptr);
#else
std::free(ptr);
#endif
}
}
}
void* operator new(std::size_t size) {
return editor::memory::alloc_internal(size);
}
void* operator new(std::size_t size, std::align_val_t al) {
return editor::memory::alloc_internal(size, std::size_t(al));
}
void operator delete(void* ptr) noexcept {
editor::memory::free_internal(ptr);
}
void operator delete(void* ptr, std::align_val_t) noexcept {
editor::memory::free_internal(ptr);
}
debug allocator fix
/*******************************
Copyright (c) 2016-2022 Grégoire Angerand
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 "memory.h"
#include <y/utils/memory.h>
#include <atomic>
#include <cstdlib>
namespace editor {
namespace memory {
std::atomic<usize> live_allocs = 0;
std::atomic<u64> total_allocs= 0;
usize live_allocations() {
return live_allocs;
}
u64 total_allocations() {
return total_allocs;
}
static void* alloc_internal(usize size, usize alignment = max_alignment) {
if(!size) {
return nullptr;
}
auto try_alloc = [=] {
#ifdef Y_OS_WIN
return _aligned_malloc(size, alignment);
#else
return std::aligned_alloc(alignment, size);
#endif
};
void* ptr = nullptr;
while((ptr = try_alloc()) == nullptr) {
std::new_handler nh = std::get_new_handler();
if(!nh) {
throw std::bad_alloc{};
}
nh();
}
++total_allocs;
++live_allocs;
y_profile_alloc(ptr, size);
return ptr;
}
static void free_internal(void* ptr) {
if(ptr) {
--live_allocs;
}
y_profile_free(ptr);
#ifdef Y_OS_WIN
_aligned_free(ptr);
#else
std::free(ptr);
#endif
}
}
}
void* operator new(std::size_t size) {
return editor::memory::alloc_internal(size);
}
void* operator new(std::size_t size, std::align_val_t al) {
return editor::memory::alloc_internal(size, std::size_t(al));
}
void operator delete(void* ptr) noexcept {
editor::memory::free_internal(ptr);
}
void operator delete(void* ptr, std::align_val_t) noexcept {
editor::memory::free_internal(ptr);
}
|
// Copyright (c) 2012 Sirikata Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef _SIRIKATA_CORE_UTIL_INSTANCE_METHOD_NOT_REENTRANT_HPP_
#define _SIRIKATA_CORE_UTIL_INSTANCE_METHOD_NOT_REENTRANT_HPP_
#include <sirikata/core/util/Platform.hpp>
namespace Sirikata {
/** A utility class that lets you specify that a method isn't reentrant and
* validate in debug mode that you're not calling it recursively. It checks
* reentrancy per instance, i.e. it is expected that it is reentrant for
* different instances (e.g. you might have class A and have instance A1::foo
* call instance A2::foo and be fine, but A1::foo eventually hitting A1::foo
* again on the same stack is not ok).
*
* This might seem simple, but in cases where you are using listeners or
* generic callbacks it might be hard to verify statically that you don't
* accidentally have recursion. This lets you just annotate a bit of code to
* make sure it remains true. In release mode all checks are disabled and the
* class uses no space.
*
* Note that you should use one of these *per non-reentrant method*. If you
* have A::foo and A::bar, you need one of these for each one.
*
* To use the class, you want a declaraction like
* InstanceMethodNotReentrant mFooNotRentrant;
* in your class and then create a token in the method, e.g.
* void A::foo() {
* InstanceMethodNotReentrant::Token not_reentrant(mFooNotRentrant);
* }
*
*/
class SIRIKATA_EXPORT InstanceMethodNotReentrant {
public:
InstanceMethodNotReentrant()
: count(0)
{}
class Token {
public:
Token(InstanceMethodNotReentrant& par)
#if SIRIKATA_DEBUG
: parent(par)
#endif
{
#if SIRIKATA_DEBUG
assert(parent.count == 0);
parent.count++;
#endif
}
~Token() {
#if SIRIKATA_DEBUG
parent.count--;
#endif
}
private:
#if SIRIKATA_DEBUG
InstanceMethodNotReentrant& parent;
#endif
};
#if SIRIKATA_DEBUG
char count;
#endif
}; // class InstanceMethodNotReentrant
} // namespace Sirikata
#endif //_SIRIKATA_CORE_UTIL_INSTANCE_METHOD_NOT_REENTRANT_HPP_
Fix missing ifdef in InstanceMethodNotReentrant.
// Copyright (c) 2012 Sirikata Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef _SIRIKATA_CORE_UTIL_INSTANCE_METHOD_NOT_REENTRANT_HPP_
#define _SIRIKATA_CORE_UTIL_INSTANCE_METHOD_NOT_REENTRANT_HPP_
#include <sirikata/core/util/Platform.hpp>
namespace Sirikata {
/** A utility class that lets you specify that a method isn't reentrant and
* validate in debug mode that you're not calling it recursively. It checks
* reentrancy per instance, i.e. it is expected that it is reentrant for
* different instances (e.g. you might have class A and have instance A1::foo
* call instance A2::foo and be fine, but A1::foo eventually hitting A1::foo
* again on the same stack is not ok).
*
* This might seem simple, but in cases where you are using listeners or
* generic callbacks it might be hard to verify statically that you don't
* accidentally have recursion. This lets you just annotate a bit of code to
* make sure it remains true. In release mode all checks are disabled and the
* class uses no space.
*
* Note that you should use one of these *per non-reentrant method*. If you
* have A::foo and A::bar, you need one of these for each one.
*
* To use the class, you want a declaraction like
* InstanceMethodNotReentrant mFooNotRentrant;
* in your class and then create a token in the method, e.g.
* void A::foo() {
* InstanceMethodNotReentrant::Token not_reentrant(mFooNotRentrant);
* }
*
*/
class SIRIKATA_EXPORT InstanceMethodNotReentrant {
public:
InstanceMethodNotReentrant()
#if SIRIKATA_DEBUG
: count(0)
#endif
{}
class Token {
public:
Token(InstanceMethodNotReentrant& par)
#if SIRIKATA_DEBUG
: parent(par)
#endif
{
#if SIRIKATA_DEBUG
assert(parent.count == 0);
parent.count++;
#endif
}
~Token() {
#if SIRIKATA_DEBUG
parent.count--;
#endif
}
private:
#if SIRIKATA_DEBUG
InstanceMethodNotReentrant& parent;
#endif
};
#if SIRIKATA_DEBUG
char count;
#endif
}; // class InstanceMethodNotReentrant
} // namespace Sirikata
#endif //_SIRIKATA_CORE_UTIL_INSTANCE_METHOD_NOT_REENTRANT_HPP_
|
#include "TFile.h"
#include "TH1F.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#ifdef __CINT__
#pragma link C++ class TTreeReaderValue<Float_t>+;
#endif
void TreeReaderSimple() {
TH1F *myHistogram = new TH1F ("h1","ntuple",100,-4,4);
TFile::Open("hsimple.root");
TTreeReader myHSimpleReader ("ntuple");
TTreeReaderValue<Float_t> myPx (myHSimpleReader, "px");
TTreeReaderValue<Float_t> myPy (myHSimpleReader, "py");
for (int i = 0; myHSimpleReader.SetNextEntry(); ++i){
myHistogram->Fill(*myPx + *myPy);
}
myHistogram->Draw();
}
Changed for loop to while loop, as the counter was not used
#include "TFile.h"
#include "TH1F.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#ifdef __CINT__
#pragma link C++ class TTreeReaderValue<Float_t>+;
#endif
void TreeReaderSimple() {
TH1F *myHistogram = new TH1F ("h1","ntuple",100,-4,4);
TFile::Open("hsimple.root");
TTreeReader myHSimpleReader ("ntuple");
TTreeReaderValue<Float_t> myPx (myHSimpleReader, "px");
TTreeReaderValue<Float_t> myPy (myHSimpleReader, "py");
while (myHSimpleReader.SetNextEntry()){
myHistogram->Fill(*myPx + *myPy);
}
myHistogram->Draw();
}
|
//===-- BrainF.cpp - BrainF compiler example ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===--------------------------------------------------------------------===//
//
// This class compiles the BrainF language into LLVM assembly.
//
// The BrainF language has 8 commands:
// Command Equivalent C Action
// ------- ------------ ------
// , *h=getchar(); Read a character from stdin, 255 on EOF
// . putchar(*h); Write a character to stdout
// - --*h; Decrement tape
// + ++*h; Increment tape
// < --h; Move head left
// > ++h; Move head right
// [ while(*h) { Start loop
// ] } End loop
//
//===--------------------------------------------------------------------===//
#include "BrainF.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/ADT/STLExtras.h"
#include <iostream>
using namespace llvm;
//Set the constants for naming
const char *BrainF::tapereg = "tape";
const char *BrainF::headreg = "head";
const char *BrainF::label = "brainf";
const char *BrainF::testreg = "test";
Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf,
LLVMContext& Context) {
in = in1;
memtotal = mem;
comflag = cf;
header(Context);
readloop(0, 0, 0, Context);
delete builder;
return module;
}
void BrainF::header(LLVMContext& C) {
module = new Module("BrainF", C);
//Function prototypes
//declare void @llvm.memset.p0i8.i32(i8 *, i8, i32, i32, i1)
const Type *Tys[] = { Type::getInt8PtrTy(C), Type::getInt32Ty(C) };
Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset,
Tys, 2);
//declare i32 @getchar()
getchar_func = cast<Function>(module->
getOrInsertFunction("getchar", IntegerType::getInt32Ty(C), NULL));
//declare i32 @putchar(i32)
putchar_func = cast<Function>(module->
getOrInsertFunction("putchar", IntegerType::getInt32Ty(C),
IntegerType::getInt32Ty(C), NULL));
//Function header
//define void @brainf()
brainf_func = cast<Function>(module->
getOrInsertFunction("brainf", Type::getVoidTy(C), NULL));
builder = new IRBuilder<>(BasicBlock::Create(C, label, brainf_func));
//%arr = malloc i8, i32 %d
ConstantInt *val_mem = ConstantInt::get(C, APInt(32, memtotal));
BasicBlock* BB = builder->GetInsertBlock();
const Type* IntPtrTy = IntegerType::getInt32Ty(C);
const Type* Int8Ty = IntegerType::getInt8Ty(C);
Constant* allocsize = ConstantExpr::getSizeOf(Int8Ty);
allocsize = ConstantExpr::getTruncOrBitCast(allocsize, IntPtrTy);
ptr_arr = CallInst::CreateMalloc(BB, IntPtrTy, Int8Ty, allocsize, val_mem,
NULL, "arr");
BB->getInstList().push_back(cast<Instruction>(ptr_arr));
//call void @llvm.memset.p0i8.i32(i8 *%arr, i8 0, i32 %d, i32 1, i1 0)
{
Value *memset_params[] = {
ptr_arr,
ConstantInt::get(C, APInt(8, 0)),
val_mem,
ConstantInt::get(C, APInt(32, 1)),
ConstantInt::get(C, APInt(1, 0))
};
CallInst *memset_call = builder->
CreateCall(memset_func, memset_params, array_endof(memset_params));
memset_call->setTailCall(false);
}
//%arrmax = getelementptr i8 *%arr, i32 %d
if (comflag & flag_arraybounds) {
ptr_arrmax = builder->
CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal)), "arrmax");
}
//%head.%d = getelementptr i8 *%arr, i32 %d
curhead = builder->CreateGEP(ptr_arr,
ConstantInt::get(C, APInt(32, memtotal/2)),
headreg);
//Function footer
//brainf.end:
endbb = BasicBlock::Create(C, label, brainf_func);
//call free(i8 *%arr)
endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb));
//ret void
ReturnInst::Create(C, endbb);
//Error block for array out of bounds
if (comflag & flag_arraybounds)
{
//@aberrormsg = internal constant [%d x i8] c"\00"
Constant *msg_0 =
ConstantArray::get(C, "Error: The head has left the tape.", true);
GlobalVariable *aberrormsg = new GlobalVariable(
*module,
msg_0->getType(),
true,
GlobalValue::InternalLinkage,
msg_0,
"aberrormsg");
//declare i32 @puts(i8 *)
Function *puts_func = cast<Function>(module->
getOrInsertFunction("puts", IntegerType::getInt32Ty(C),
PointerType::getUnqual(IntegerType::getInt8Ty(C)), NULL));
//brainf.aberror:
aberrorbb = BasicBlock::Create(C, label, brainf_func);
//call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
{
Constant *zero_32 = Constant::getNullValue(IntegerType::getInt32Ty(C));
Constant *gep_params[] = {
zero_32,
zero_32
};
Constant *msgptr = ConstantExpr::
getGetElementPtr(aberrormsg, gep_params,
array_lengthof(gep_params));
Value *puts_params[] = {
msgptr
};
CallInst *puts_call =
CallInst::Create(puts_func,
puts_params, array_endof(puts_params),
"", aberrorbb);
puts_call->setTailCall(false);
}
//br label %brainf.end
BranchInst::Create(endbb, aberrorbb);
}
}
void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb,
LLVMContext &C) {
Symbol cursym = SYM_NONE;
int curvalue = 0;
Symbol nextsym = SYM_NONE;
int nextvalue = 0;
char c;
int loop;
int direction;
while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) {
// Write out commands
switch(cursym) {
case SYM_NONE:
// Do nothing
break;
case SYM_READ:
{
//%tape.%d = call i32 @getchar()
CallInst *getchar_call = builder->CreateCall(getchar_func, tapereg);
getchar_call->setTailCall(false);
Value *tape_0 = getchar_call;
//%tape.%d = trunc i32 %tape.%d to i8
Value *tape_1 = builder->
CreateTrunc(tape_0, IntegerType::getInt8Ty(C), tapereg);
//store i8 %tape.%d, i8 *%head.%d
builder->CreateStore(tape_1, curhead);
}
break;
case SYM_WRITE:
{
//%tape.%d = load i8 *%head.%d
LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
//%tape.%d = sext i8 %tape.%d to i32
Value *tape_1 = builder->
CreateSExt(tape_0, IntegerType::getInt32Ty(C), tapereg);
//call i32 @putchar(i32 %tape.%d)
Value *putchar_params[] = {
tape_1
};
CallInst *putchar_call = builder->
CreateCall(putchar_func,
putchar_params, array_endof(putchar_params));
putchar_call->setTailCall(false);
}
break;
case SYM_MOVE:
{
//%head.%d = getelementptr i8 *%head.%d, i32 %d
curhead = builder->
CreateGEP(curhead, ConstantInt::get(C, APInt(32, curvalue)),
headreg);
//Error block for array out of bounds
if (comflag & flag_arraybounds)
{
//%test.%d = icmp uge i8 *%head.%d, %arrmax
Value *test_0 = builder->
CreateICmpUGE(curhead, ptr_arrmax, testreg);
//%test.%d = icmp ult i8 *%head.%d, %arr
Value *test_1 = builder->
CreateICmpULT(curhead, ptr_arr, testreg);
//%test.%d = or i1 %test.%d, %test.%d
Value *test_2 = builder->
CreateOr(test_0, test_1, testreg);
//br i1 %test.%d, label %main.%d, label %main.%d
BasicBlock *nextbb = BasicBlock::Create(C, label, brainf_func);
builder->CreateCondBr(test_2, aberrorbb, nextbb);
//main.%d:
builder->SetInsertPoint(nextbb);
}
}
break;
case SYM_CHANGE:
{
//%tape.%d = load i8 *%head.%d
LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
//%tape.%d = add i8 %tape.%d, %d
Value *tape_1 = builder->
CreateAdd(tape_0, ConstantInt::get(C, APInt(8, curvalue)), tapereg);
//store i8 %tape.%d, i8 *%head.%d\n"
builder->CreateStore(tape_1, curhead);
}
break;
case SYM_LOOP:
{
//br label %main.%d
BasicBlock *testbb = BasicBlock::Create(C, label, brainf_func);
builder->CreateBr(testbb);
//main.%d:
BasicBlock *bb_0 = builder->GetInsertBlock();
BasicBlock *bb_1 = BasicBlock::Create(C, label, brainf_func);
builder->SetInsertPoint(bb_1);
// Make part of PHI instruction now, wait until end of loop to finish
PHINode *phi_0 =
PHINode::Create(PointerType::getUnqual(IntegerType::getInt8Ty(C)),
2, headreg, testbb);
phi_0->addIncoming(curhead, bb_0);
curhead = phi_0;
readloop(phi_0, bb_1, testbb, C);
}
break;
default:
std::cerr << "Error: Unknown symbol.\n";
abort();
break;
}
cursym = nextsym;
curvalue = nextvalue;
nextsym = SYM_NONE;
// Reading stdin loop
loop = (cursym == SYM_NONE)
|| (cursym == SYM_MOVE)
|| (cursym == SYM_CHANGE);
while(loop) {
*in>>c;
if (in->eof()) {
if (cursym == SYM_NONE) {
cursym = SYM_EOF;
} else {
nextsym = SYM_EOF;
}
loop = 0;
} else {
direction = 1;
switch(c) {
case '-':
direction = -1;
// Fall through
case '+':
if (cursym == SYM_CHANGE) {
curvalue += direction;
// loop = 1
} else {
if (cursym == SYM_NONE) {
cursym = SYM_CHANGE;
curvalue = direction;
// loop = 1
} else {
nextsym = SYM_CHANGE;
nextvalue = direction;
loop = 0;
}
}
break;
case '<':
direction = -1;
// Fall through
case '>':
if (cursym == SYM_MOVE) {
curvalue += direction;
// loop = 1
} else {
if (cursym == SYM_NONE) {
cursym = SYM_MOVE;
curvalue = direction;
// loop = 1
} else {
nextsym = SYM_MOVE;
nextvalue = direction;
loop = 0;
}
}
break;
case ',':
if (cursym == SYM_NONE) {
cursym = SYM_READ;
} else {
nextsym = SYM_READ;
}
loop = 0;
break;
case '.':
if (cursym == SYM_NONE) {
cursym = SYM_WRITE;
} else {
nextsym = SYM_WRITE;
}
loop = 0;
break;
case '[':
if (cursym == SYM_NONE) {
cursym = SYM_LOOP;
} else {
nextsym = SYM_LOOP;
}
loop = 0;
break;
case ']':
if (cursym == SYM_NONE) {
cursym = SYM_ENDLOOP;
} else {
nextsym = SYM_ENDLOOP;
}
loop = 0;
break;
// Ignore other characters
default:
break;
}
}
}
}
if (cursym == SYM_ENDLOOP) {
if (!phi) {
std::cerr << "Error: Extra ']'\n";
abort();
}
// Write loop test
{
//br label %main.%d
builder->CreateBr(testbb);
//main.%d:
//%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d]
//Finish phi made at beginning of loop
phi->addIncoming(curhead, builder->GetInsertBlock());
Value *head_0 = phi;
//%tape.%d = load i8 *%head.%d
LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb);
//%test.%d = icmp eq i8 %tape.%d, 0
ICmpInst *test_0 = new ICmpInst(*testbb, ICmpInst::ICMP_EQ, tape_0,
ConstantInt::get(C, APInt(8, 0)), testreg);
//br i1 %test.%d, label %main.%d, label %main.%d
BasicBlock *bb_0 = BasicBlock::Create(C, label, brainf_func);
BranchInst::Create(bb_0, oldbb, test_0, testbb);
//main.%d:
builder->SetInsertPoint(bb_0);
//%head.%d = phi i8 *[%head.%d, %main.%d]
PHINode *phi_1 = builder->
CreatePHI(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 1,
headreg);
phi_1->addIncoming(head_0, testbb);
curhead = phi_1;
}
return;
}
//End of the program, so go to return block
builder->CreateBr(endbb);
if (phi) {
std::cerr << "Error: Missing ']'\n";
abort();
}
}
Remove the const from Type after of Jay deconstify work.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@135000 91177308-0d34-0410-b5e6-96231b3b80d8
//===-- BrainF.cpp - BrainF compiler example ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===--------------------------------------------------------------------===//
//
// This class compiles the BrainF language into LLVM assembly.
//
// The BrainF language has 8 commands:
// Command Equivalent C Action
// ------- ------------ ------
// , *h=getchar(); Read a character from stdin, 255 on EOF
// . putchar(*h); Write a character to stdout
// - --*h; Decrement tape
// + ++*h; Increment tape
// < --h; Move head left
// > ++h; Move head right
// [ while(*h) { Start loop
// ] } End loop
//
//===--------------------------------------------------------------------===//
#include "BrainF.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/ADT/STLExtras.h"
#include <iostream>
using namespace llvm;
//Set the constants for naming
const char *BrainF::tapereg = "tape";
const char *BrainF::headreg = "head";
const char *BrainF::label = "brainf";
const char *BrainF::testreg = "test";
Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf,
LLVMContext& Context) {
in = in1;
memtotal = mem;
comflag = cf;
header(Context);
readloop(0, 0, 0, Context);
delete builder;
return module;
}
void BrainF::header(LLVMContext& C) {
module = new Module("BrainF", C);
//Function prototypes
//declare void @llvm.memset.p0i8.i32(i8 *, i8, i32, i32, i1)
Type *Tys[] = { Type::getInt8PtrTy(C), Type::getInt32Ty(C) };
Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset,
Tys, 2);
//declare i32 @getchar()
getchar_func = cast<Function>(module->
getOrInsertFunction("getchar", IntegerType::getInt32Ty(C), NULL));
//declare i32 @putchar(i32)
putchar_func = cast<Function>(module->
getOrInsertFunction("putchar", IntegerType::getInt32Ty(C),
IntegerType::getInt32Ty(C), NULL));
//Function header
//define void @brainf()
brainf_func = cast<Function>(module->
getOrInsertFunction("brainf", Type::getVoidTy(C), NULL));
builder = new IRBuilder<>(BasicBlock::Create(C, label, brainf_func));
//%arr = malloc i8, i32 %d
ConstantInt *val_mem = ConstantInt::get(C, APInt(32, memtotal));
BasicBlock* BB = builder->GetInsertBlock();
const Type* IntPtrTy = IntegerType::getInt32Ty(C);
const Type* Int8Ty = IntegerType::getInt8Ty(C);
Constant* allocsize = ConstantExpr::getSizeOf(Int8Ty);
allocsize = ConstantExpr::getTruncOrBitCast(allocsize, IntPtrTy);
ptr_arr = CallInst::CreateMalloc(BB, IntPtrTy, Int8Ty, allocsize, val_mem,
NULL, "arr");
BB->getInstList().push_back(cast<Instruction>(ptr_arr));
//call void @llvm.memset.p0i8.i32(i8 *%arr, i8 0, i32 %d, i32 1, i1 0)
{
Value *memset_params[] = {
ptr_arr,
ConstantInt::get(C, APInt(8, 0)),
val_mem,
ConstantInt::get(C, APInt(32, 1)),
ConstantInt::get(C, APInt(1, 0))
};
CallInst *memset_call = builder->
CreateCall(memset_func, memset_params, array_endof(memset_params));
memset_call->setTailCall(false);
}
//%arrmax = getelementptr i8 *%arr, i32 %d
if (comflag & flag_arraybounds) {
ptr_arrmax = builder->
CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal)), "arrmax");
}
//%head.%d = getelementptr i8 *%arr, i32 %d
curhead = builder->CreateGEP(ptr_arr,
ConstantInt::get(C, APInt(32, memtotal/2)),
headreg);
//Function footer
//brainf.end:
endbb = BasicBlock::Create(C, label, brainf_func);
//call free(i8 *%arr)
endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb));
//ret void
ReturnInst::Create(C, endbb);
//Error block for array out of bounds
if (comflag & flag_arraybounds)
{
//@aberrormsg = internal constant [%d x i8] c"\00"
Constant *msg_0 =
ConstantArray::get(C, "Error: The head has left the tape.", true);
GlobalVariable *aberrormsg = new GlobalVariable(
*module,
msg_0->getType(),
true,
GlobalValue::InternalLinkage,
msg_0,
"aberrormsg");
//declare i32 @puts(i8 *)
Function *puts_func = cast<Function>(module->
getOrInsertFunction("puts", IntegerType::getInt32Ty(C),
PointerType::getUnqual(IntegerType::getInt8Ty(C)), NULL));
//brainf.aberror:
aberrorbb = BasicBlock::Create(C, label, brainf_func);
//call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
{
Constant *zero_32 = Constant::getNullValue(IntegerType::getInt32Ty(C));
Constant *gep_params[] = {
zero_32,
zero_32
};
Constant *msgptr = ConstantExpr::
getGetElementPtr(aberrormsg, gep_params,
array_lengthof(gep_params));
Value *puts_params[] = {
msgptr
};
CallInst *puts_call =
CallInst::Create(puts_func,
puts_params, array_endof(puts_params),
"", aberrorbb);
puts_call->setTailCall(false);
}
//br label %brainf.end
BranchInst::Create(endbb, aberrorbb);
}
}
void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb,
LLVMContext &C) {
Symbol cursym = SYM_NONE;
int curvalue = 0;
Symbol nextsym = SYM_NONE;
int nextvalue = 0;
char c;
int loop;
int direction;
while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) {
// Write out commands
switch(cursym) {
case SYM_NONE:
// Do nothing
break;
case SYM_READ:
{
//%tape.%d = call i32 @getchar()
CallInst *getchar_call = builder->CreateCall(getchar_func, tapereg);
getchar_call->setTailCall(false);
Value *tape_0 = getchar_call;
//%tape.%d = trunc i32 %tape.%d to i8
Value *tape_1 = builder->
CreateTrunc(tape_0, IntegerType::getInt8Ty(C), tapereg);
//store i8 %tape.%d, i8 *%head.%d
builder->CreateStore(tape_1, curhead);
}
break;
case SYM_WRITE:
{
//%tape.%d = load i8 *%head.%d
LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
//%tape.%d = sext i8 %tape.%d to i32
Value *tape_1 = builder->
CreateSExt(tape_0, IntegerType::getInt32Ty(C), tapereg);
//call i32 @putchar(i32 %tape.%d)
Value *putchar_params[] = {
tape_1
};
CallInst *putchar_call = builder->
CreateCall(putchar_func,
putchar_params, array_endof(putchar_params));
putchar_call->setTailCall(false);
}
break;
case SYM_MOVE:
{
//%head.%d = getelementptr i8 *%head.%d, i32 %d
curhead = builder->
CreateGEP(curhead, ConstantInt::get(C, APInt(32, curvalue)),
headreg);
//Error block for array out of bounds
if (comflag & flag_arraybounds)
{
//%test.%d = icmp uge i8 *%head.%d, %arrmax
Value *test_0 = builder->
CreateICmpUGE(curhead, ptr_arrmax, testreg);
//%test.%d = icmp ult i8 *%head.%d, %arr
Value *test_1 = builder->
CreateICmpULT(curhead, ptr_arr, testreg);
//%test.%d = or i1 %test.%d, %test.%d
Value *test_2 = builder->
CreateOr(test_0, test_1, testreg);
//br i1 %test.%d, label %main.%d, label %main.%d
BasicBlock *nextbb = BasicBlock::Create(C, label, brainf_func);
builder->CreateCondBr(test_2, aberrorbb, nextbb);
//main.%d:
builder->SetInsertPoint(nextbb);
}
}
break;
case SYM_CHANGE:
{
//%tape.%d = load i8 *%head.%d
LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
//%tape.%d = add i8 %tape.%d, %d
Value *tape_1 = builder->
CreateAdd(tape_0, ConstantInt::get(C, APInt(8, curvalue)), tapereg);
//store i8 %tape.%d, i8 *%head.%d\n"
builder->CreateStore(tape_1, curhead);
}
break;
case SYM_LOOP:
{
//br label %main.%d
BasicBlock *testbb = BasicBlock::Create(C, label, brainf_func);
builder->CreateBr(testbb);
//main.%d:
BasicBlock *bb_0 = builder->GetInsertBlock();
BasicBlock *bb_1 = BasicBlock::Create(C, label, brainf_func);
builder->SetInsertPoint(bb_1);
// Make part of PHI instruction now, wait until end of loop to finish
PHINode *phi_0 =
PHINode::Create(PointerType::getUnqual(IntegerType::getInt8Ty(C)),
2, headreg, testbb);
phi_0->addIncoming(curhead, bb_0);
curhead = phi_0;
readloop(phi_0, bb_1, testbb, C);
}
break;
default:
std::cerr << "Error: Unknown symbol.\n";
abort();
break;
}
cursym = nextsym;
curvalue = nextvalue;
nextsym = SYM_NONE;
// Reading stdin loop
loop = (cursym == SYM_NONE)
|| (cursym == SYM_MOVE)
|| (cursym == SYM_CHANGE);
while(loop) {
*in>>c;
if (in->eof()) {
if (cursym == SYM_NONE) {
cursym = SYM_EOF;
} else {
nextsym = SYM_EOF;
}
loop = 0;
} else {
direction = 1;
switch(c) {
case '-':
direction = -1;
// Fall through
case '+':
if (cursym == SYM_CHANGE) {
curvalue += direction;
// loop = 1
} else {
if (cursym == SYM_NONE) {
cursym = SYM_CHANGE;
curvalue = direction;
// loop = 1
} else {
nextsym = SYM_CHANGE;
nextvalue = direction;
loop = 0;
}
}
break;
case '<':
direction = -1;
// Fall through
case '>':
if (cursym == SYM_MOVE) {
curvalue += direction;
// loop = 1
} else {
if (cursym == SYM_NONE) {
cursym = SYM_MOVE;
curvalue = direction;
// loop = 1
} else {
nextsym = SYM_MOVE;
nextvalue = direction;
loop = 0;
}
}
break;
case ',':
if (cursym == SYM_NONE) {
cursym = SYM_READ;
} else {
nextsym = SYM_READ;
}
loop = 0;
break;
case '.':
if (cursym == SYM_NONE) {
cursym = SYM_WRITE;
} else {
nextsym = SYM_WRITE;
}
loop = 0;
break;
case '[':
if (cursym == SYM_NONE) {
cursym = SYM_LOOP;
} else {
nextsym = SYM_LOOP;
}
loop = 0;
break;
case ']':
if (cursym == SYM_NONE) {
cursym = SYM_ENDLOOP;
} else {
nextsym = SYM_ENDLOOP;
}
loop = 0;
break;
// Ignore other characters
default:
break;
}
}
}
}
if (cursym == SYM_ENDLOOP) {
if (!phi) {
std::cerr << "Error: Extra ']'\n";
abort();
}
// Write loop test
{
//br label %main.%d
builder->CreateBr(testbb);
//main.%d:
//%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d]
//Finish phi made at beginning of loop
phi->addIncoming(curhead, builder->GetInsertBlock());
Value *head_0 = phi;
//%tape.%d = load i8 *%head.%d
LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb);
//%test.%d = icmp eq i8 %tape.%d, 0
ICmpInst *test_0 = new ICmpInst(*testbb, ICmpInst::ICMP_EQ, tape_0,
ConstantInt::get(C, APInt(8, 0)), testreg);
//br i1 %test.%d, label %main.%d, label %main.%d
BasicBlock *bb_0 = BasicBlock::Create(C, label, brainf_func);
BranchInst::Create(bb_0, oldbb, test_0, testbb);
//main.%d:
builder->SetInsertPoint(bb_0);
//%head.%d = phi i8 *[%head.%d, %main.%d]
PHINode *phi_1 = builder->
CreatePHI(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 1,
headreg);
phi_1->addIncoming(head_0, testbb);
curhead = phi_1;
}
return;
}
//End of the program, so go to return block
builder->CreateBr(endbb);
if (phi) {
std::cerr << "Error: Missing ']'\n";
abort();
}
}
|
// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o %t
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-1
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-2
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-3
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-4
struct Foo {
int x;
float y;
~Foo() {}
};
struct TestClass {
int x;
TestClass() : x(0) {};
void MemberFunc() {
Foo f;
#pragma clang __debug captured
{
f.y = x;
}
}
};
void test1() {
TestClass c;
c.MemberFunc();
// CHECK-1: %[[Capture:struct\.anon[\.0-9]*]] = type { %struct.Foo*, %struct.TestClass* }
// CHECK-1: define {{.*}} void @_ZN9TestClass10MemberFuncEv
// CHECK-1: alloca %struct.anon
// CHECK-1: getelementptr inbounds %[[Capture]]* %{{[^,]*}}, i32 0, i32 0
// CHECK-1: store %struct.Foo* %f, %struct.Foo**
// CHECK-1: getelementptr inbounds %[[Capture]]* %{{[^,]*}}, i32 0, i32 1
// CHECK-1: call void @[[HelperName:[A-Za-z0-9_]+]](%[[Capture]]*
// CHECK-1: call void @_ZN3FooD1Ev
// CHECK-1: ret
}
// CHECK-1: define internal void @[[HelperName]]
// CHECK-1: getelementptr inbounds %[[Capture]]* {{[^,]*}}, i32 0, i32 1
// CHECK-1: getelementptr inbounds %struct.TestClass* {{[^,]*}}, i32 0, i32 0
// CHECK-1: getelementptr inbounds %[[Capture]]* {{[^,]*}}, i32 0, i32 0
void test2(int x) {
int y = [&]() {
#pragma clang __debug captured
{
x++;
}
return x;
}();
// CHECK-2: define void @_Z5test2i
// CHECK-2: call i32 @[[Lambda:["$\w]+]]
//
// CHECK-2: define internal i32 @[[Lambda]]
// CHECK-2: call void @[[HelperName:["$_A-Za-z0-9]+]](%[[Capture:.*]]*
//
// CHECK-2: define internal void @[[HelperName]]
// CHECK-2: getelementptr inbounds %[[Capture]]*
// CHECK-2: load i32**
// CHECK-2: load i32*
}
void test3(int x) {
#pragma clang __debug captured
{
x = [=]() { return x + 1; } ();
}
// CHECK-3: %[[Capture:struct\.anon[\.0-9]*]] = type { i32* }
// CHECK-3: define void @_Z5test3i(i32 %x)
// CHECK-3: store i32*
// CHECK-3: call void @{{.*}}__captured_stmt
// CHECK-3: ret void
}
void test4() {
#pragma clang __debug captured
{
Foo f;
f.x = 5;
}
// CHECK-4: %[[Capture:struct\.anon[\.0-9]*]] = type { i32* }
// CHECK-4: define void @_Z5test3i(i32 %x)
// CHECK-4: store i32*
// CHECK-4: call void @[[HelperName:["$_A-Za-z0-9]+]](%[[Capture:.*]]*
// CHECK-4: ret void
//
// CHECK-4: define internal void @[[HelperName]]
// CHECK-4: store i32 5, i32*
// CHECK-4: call void @{{.*}}FooD1Ev(%struct.Foo*
}
Fix captured statements codegen test on ARM
The return type of the destructor may vary between platforms, so stop
inadvertently testing it.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@181541 91177308-0d34-0410-b5e6-96231b3b80d8
// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o %t
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-1
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-2
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-3
// RUN: FileCheck %s -input-file=%t -check-prefix=CHECK-4
struct Foo {
int x;
float y;
~Foo() {}
};
struct TestClass {
int x;
TestClass() : x(0) {};
void MemberFunc() {
Foo f;
#pragma clang __debug captured
{
f.y = x;
}
}
};
void test1() {
TestClass c;
c.MemberFunc();
// CHECK-1: %[[Capture:struct\.anon[\.0-9]*]] = type { %struct.Foo*, %struct.TestClass* }
// CHECK-1: define {{.*}} void @_ZN9TestClass10MemberFuncEv
// CHECK-1: alloca %struct.anon
// CHECK-1: getelementptr inbounds %[[Capture]]* %{{[^,]*}}, i32 0, i32 0
// CHECK-1: store %struct.Foo* %f, %struct.Foo**
// CHECK-1: getelementptr inbounds %[[Capture]]* %{{[^,]*}}, i32 0, i32 1
// CHECK-1: call void @[[HelperName:[A-Za-z0-9_]+]](%[[Capture]]*
// CHECK-1: call {{.*}}FooD1Ev
// CHECK-1: ret
}
// CHECK-1: define internal void @[[HelperName]]
// CHECK-1: getelementptr inbounds %[[Capture]]* {{[^,]*}}, i32 0, i32 1
// CHECK-1: getelementptr inbounds %struct.TestClass* {{[^,]*}}, i32 0, i32 0
// CHECK-1: getelementptr inbounds %[[Capture]]* {{[^,]*}}, i32 0, i32 0
void test2(int x) {
int y = [&]() {
#pragma clang __debug captured
{
x++;
}
return x;
}();
// CHECK-2: define void @_Z5test2i
// CHECK-2: call i32 @[[Lambda:["$\w]+]]
//
// CHECK-2: define internal i32 @[[Lambda]]
// CHECK-2: call void @[[HelperName:["$_A-Za-z0-9]+]](%[[Capture:.*]]*
//
// CHECK-2: define internal void @[[HelperName]]
// CHECK-2: getelementptr inbounds %[[Capture]]*
// CHECK-2: load i32**
// CHECK-2: load i32*
}
void test3(int x) {
#pragma clang __debug captured
{
x = [=]() { return x + 1; } ();
}
// CHECK-3: %[[Capture:struct\.anon[\.0-9]*]] = type { i32* }
// CHECK-3: define void @_Z5test3i(i32 %x)
// CHECK-3: store i32*
// CHECK-3: call void @{{.*}}__captured_stmt
// CHECK-3: ret void
}
void test4() {
#pragma clang __debug captured
{
Foo f;
f.x = 5;
}
// CHECK-4: %[[Capture:struct\.anon[\.0-9]*]] = type { i32* }
// CHECK-4: define void @_Z5test3i(i32 %x)
// CHECK-4: store i32*
// CHECK-4: call void @[[HelperName:["$_A-Za-z0-9]+]](%[[Capture:.*]]*
// CHECK-4: ret void
//
// CHECK-4: define internal void @[[HelperName]]
// CHECK-4: store i32 5, i32*
// CHECK-4: call {{.*}}FooD1Ev
}
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia 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.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
/* Video related snippets */
#include "qvideorenderercontrol.h"
#include "qmediaservice.h"
#include "qmediaplayer.h"
#include "qabstractvideosurface.h"
#include "qvideowidgetcontrol.h"
#include "qvideowindowcontrol.h"
#include "qgraphicsvideoitem.h"
#include "qmediaplaylist.h"
#include "qvideosurfaceformat.h"
#include <QFormLayout>
#include <QGraphicsView>
//! [Derived Surface]
class MyVideoSurface : public QAbstractVideoSurface
{
QList<QVideoFrame::PixelFormat> supportedPixelFormats(
QAbstractVideoBuffer::HandleType handleType = QAbstractVideoBuffer::NoHandle) const
{
Q_UNUSED(handleType);
// Return the formats you will support
return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_RGB565;
}
bool present(const QVideoFrame &frame)
{
Q_UNUSED(frame);
// Handle the frame and do your processing
return true;
}
};
//! [Derived Surface]
//! [Video producer]
class MyVideoProducer : public QObject
{
Q_OBJECT
Q_PROPERTY(QAbstractVideoSurface *videoSurface WRITE setVideoSurface)
public:
void setVideoSurface(QAbstractVideoSurface *surface)
{
m_surface = surface;
m_surface->start(m_format);
}
// ...
public slots:
void onNewVideoContentReceived(const QVideoFrame &frame)
{
if (m_surface)
m_surface->present(frame);
}
private:
QAbstractVideoSurface *m_surface;
QVideoSurfaceFormat m_format;
};
//! [Video producer]
class VideoExample : public QObject {
Q_OBJECT
public:
void VideoGraphicsItem();
void VideoRendererControl();
void VideoWidget();
void VideoWindowControl();
void VideoWidgetControl();
private:
// Common naming
QMediaService *mediaService;
QMediaPlaylist *playlist;
QVideoWidget *videoWidget;
QWidget *widget;
QFormLayout *layout;
QAbstractVideoSurface *myVideoSurface;
QMediaPlayer *player;
QMediaContent video;
QGraphicsView *graphicsView;
};
void VideoExample::VideoRendererControl()
{
//! [Video renderer control]
QVideoRendererControl *rendererControl = mediaService->requestControl<QVideoRendererControl *>();
rendererControl->setSurface(myVideoSurface);
//! [Video renderer control]
}
void VideoExample::VideoWidget()
{
//! [Video widget]
player = new QMediaPlayer;
playlist = new QMediaPlaylist(player);
playlist->addMedia(QUrl("http://example.com/myclip1.mp4"));
playlist->addMedia(QUrl("http://example.com/myclip2.mp4"));
videoWidget = new QVideoWidget;
player->setVideoOutput(videoWidget);
videoWidget->show();
playlist->setCurrentIndex(1);
player->play();
//! [Video widget]
player->stop();
//! [Setting surface in player]
player->setVideoOutput(myVideoSurface);
//! [Setting surface in player]
}
void VideoExample::VideoWidgetControl()
{
//! [Video widget control]
QVideoWidgetControl *widgetControl = mediaService->requestControl<QVideoWidgetControl *>();
layout->addWidget(widgetControl->videoWidget());
//! [Video widget control]
}
void VideoExample::VideoWindowControl()
{
//! [Video window control]
QVideoWindowControl *windowControl = mediaService->requestControl<QVideoWindowControl *>();
windowControl->setWinId(widget->winId());
windowControl->setDisplayRect(widget->rect());
windowControl->setAspectRatioMode(Qt::KeepAspectRatio);
//! [Video window control]
}
void VideoExample::VideoGraphicsItem()
{
//! [Video graphics item]
player = new QMediaPlayer(this);
QGraphicsVideoItem *item = new QGraphicsVideoItem;
player->setVideoOutput(item);
graphicsView->scene()->addItem(item);
graphicsView->show();
player->setMedia(QUrl("http://example.com/myclip4.ogv"));
player->play();
//! [Video graphics item]
}
Add a simple accessor to the video provider snippet
Task-number: QTBUG-29383
Change-Id: I744fb997dae6ad1f9b8075791ad463c8fe23a96d
Reviewed-by: Jerome Pasion <c10995d24f6b454503389e8d00d837aef038985d@digia.com>
Reviewed-by: Venugopal Shivashankar <5756f69ec86de98024d1d912258c6908b6f2ee8f@digia.com>
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia 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.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
/* Video related snippets */
#include "qvideorenderercontrol.h"
#include "qmediaservice.h"
#include "qmediaplayer.h"
#include "qabstractvideosurface.h"
#include "qvideowidgetcontrol.h"
#include "qvideowindowcontrol.h"
#include "qgraphicsvideoitem.h"
#include "qmediaplaylist.h"
#include "qvideosurfaceformat.h"
#include <QFormLayout>
#include <QGraphicsView>
//! [Derived Surface]
class MyVideoSurface : public QAbstractVideoSurface
{
QList<QVideoFrame::PixelFormat> supportedPixelFormats(
QAbstractVideoBuffer::HandleType handleType = QAbstractVideoBuffer::NoHandle) const
{
Q_UNUSED(handleType);
// Return the formats you will support
return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_RGB565;
}
bool present(const QVideoFrame &frame)
{
Q_UNUSED(frame);
// Handle the frame and do your processing
return true;
}
};
//! [Derived Surface]
//! [Video producer]
class MyVideoProducer : public QObject
{
Q_OBJECT
Q_PROPERTY(QAbstractVideoSurface *videoSurface READ videoSurface WRITE setVideoSurface)
public:
QAbstractVideoSurface* videoSurface() const { return m_surface; }
void setVideoSurface(QAbstractVideoSurface *surface)
{
m_surface = surface;
m_surface->start(m_format);
}
// ...
public slots:
void onNewVideoContentReceived(const QVideoFrame &frame)
{
if (m_surface)
m_surface->present(frame);
}
private:
QAbstractVideoSurface *m_surface;
QVideoSurfaceFormat m_format;
};
//! [Video producer]
class VideoExample : public QObject {
Q_OBJECT
public:
void VideoGraphicsItem();
void VideoRendererControl();
void VideoWidget();
void VideoWindowControl();
void VideoWidgetControl();
private:
// Common naming
QMediaService *mediaService;
QMediaPlaylist *playlist;
QVideoWidget *videoWidget;
QWidget *widget;
QFormLayout *layout;
QAbstractVideoSurface *myVideoSurface;
QMediaPlayer *player;
QMediaContent video;
QGraphicsView *graphicsView;
};
void VideoExample::VideoRendererControl()
{
//! [Video renderer control]
QVideoRendererControl *rendererControl = mediaService->requestControl<QVideoRendererControl *>();
rendererControl->setSurface(myVideoSurface);
//! [Video renderer control]
}
void VideoExample::VideoWidget()
{
//! [Video widget]
player = new QMediaPlayer;
playlist = new QMediaPlaylist(player);
playlist->addMedia(QUrl("http://example.com/myclip1.mp4"));
playlist->addMedia(QUrl("http://example.com/myclip2.mp4"));
videoWidget = new QVideoWidget;
player->setVideoOutput(videoWidget);
videoWidget->show();
playlist->setCurrentIndex(1);
player->play();
//! [Video widget]
player->stop();
//! [Setting surface in player]
player->setVideoOutput(myVideoSurface);
//! [Setting surface in player]
}
void VideoExample::VideoWidgetControl()
{
//! [Video widget control]
QVideoWidgetControl *widgetControl = mediaService->requestControl<QVideoWidgetControl *>();
layout->addWidget(widgetControl->videoWidget());
//! [Video widget control]
}
void VideoExample::VideoWindowControl()
{
//! [Video window control]
QVideoWindowControl *windowControl = mediaService->requestControl<QVideoWindowControl *>();
windowControl->setWinId(widget->winId());
windowControl->setDisplayRect(widget->rect());
windowControl->setAspectRatioMode(Qt::KeepAspectRatio);
//! [Video window control]
}
void VideoExample::VideoGraphicsItem()
{
//! [Video graphics item]
player = new QMediaPlayer(this);
QGraphicsVideoItem *item = new QGraphicsVideoItem;
player->setVideoOutput(item);
graphicsView->scene()->addItem(item);
graphicsView->show();
player->setMedia(QUrl("http://example.com/myclip4.ogv"));
player->play();
//! [Video graphics item]
}
|
e893/*
* File: UpdateWorker.cpp
* Author: uli
*
* Created on 23. April 2013, 10:35
*/
#include "ReadWorker.hpp"
#include <czmq.h>
#include <string>
#include <iostream>
#include "TableOpenHelper.hpp"
#include "Tablespace.hpp"
#include "protocol.hpp"
#include "zutil.hpp"
#include "endpoints.hpp"
using namespace std;
#define DEBUG_READ
/**
* Read request handler. Shall be called
*
* The original message is modified to contain the response.
*
* Envelope + Read request Header + Table ID[what zmsg_next() must return] + Payload
*/
static void handleCountRequest(Tablespace& tables, zmsg_t* msg, TableOpenHelper& openHelper) {
#ifdef DEBUG_READ
printf("Starting to handle count request of size %d\n", (uint32_t) zmsg_size(msg) - 3);
fflush(stdout);
#endif
//Parse the table id
zframe_t* tableIdFrame = zmsg_next(msg);
assert(zframe_size(tableIdFrame) == sizeof (uint32_t));
uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));
//Parse the start/end frame
zframe_t* rangeStartFrame = zmsg_next(msg);
zframe_t* rangeEndFrame = zmsg_next(msg);
bool haveRangeStart = !(rangeStartFrame == NULL || zframe_size(rangeStartFrame) == 0);
bool haveRangeEnd = !(rangeEndFrame == NULL || zframe_size(rangeEndFrame) == 0);
std::string rangeStart = (haveRangeStart ? string((char*) zframe_data(rangeStartFrame), zframe_size(rangeStartFrame)) : "");
std::string rangeEnd = (haveRangeEnd ? string((char*) zframe_data(rangeEndFrame), zframe_size(rangeEndFrame)) : "");
//Remove the range frames (if any), the reply is shorter
if (rangeStartFrame) {
removeAndDestroyFrame(msg, rangeStartFrame);
}
if (rangeEndFrame) {
removeAndDestroyFrame(msg, rangeEndFrame);
}
//Get the table to read from
leveldb::DB* db = tables.getTable(tableId, openHelper);
//Create the response object
leveldb::ReadOptions readOptions;
string value; //Where the value will be placed
leveldb::Status status;
//Create the iterator
leveldb::Iterator* it = db->NewIterator(leveldb::ReadOwptions());
if (haveRangeStart) {
it->Sekk
} else {
it->SeekToFirst();
}
uint64_t count = 0;
//Iterate over all key-values in the range
for (; it->Valid(); it->Next()) {
count++;
string key = it->key().ToString();
if (haveRangeEnd && key >= rangeEnd) {
break;
}
}
//TODO handle error
assert(it->status().ok()); // Check for any errors found during the scan
//Delete the iterator
delete it;
//Build the response message
zframe_reset(tableIdFrame, &count, sizeof(uint64_t));
}
/**
* Read request handler. Shall be called for Read requests only!
*
* The original message is modified to contain the response.
*
* Envelope + Read request Header + Table ID[what zmsg_next() must return] + Payload
*/
static void handleReadRequest(Tablespace& tables, zmsg_t* msg, TableOpenHelper& openHelper) {
#ifdef DEBUG_READ
printf("Starting to handle read request of size %d\n", (uint32_t) zmsg_size(msg) - 3);
fflush(stdout);
#endif
//Parse the table id
zframe_t* tableIdFrame = zmsg_next(msg);
assert(zframe_size(tableIdFrame) == sizeof (uint32_t));
uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));
//Parse the
//Get the table to read from
leveldb::DB* db = tables.getTable(tableId, openHelper);
//Create the response object
leveldb::ReadOptions readOptions;
leveldb::Status status;
//Read each read request
zframe_t* keyFrame = NULL;
while ((keyFrame = zmsg_next(msg)) != NULL) {
//Build a slice of the key (zero-copy)
string keystr((char*) zframe_data(keyFrame), zframe_size(keyFrame));
leveldb::Slice key((char*) zframe_data(keyFrame), zframe_size(keyFrame));
#ifdef DEBUG_READ
printf("Reading key %s from table %d\n", key.ToString().c_str(), tableId);
#endif
status = db->Get(readOptions, key, &value);
if (status.IsNotFound()) {
#ifdef DEBUG_READ
cout << "Could not find value for key " << key.ToString() << "in table " << tableId << endl;
#endif
//Empty value
zframe_reset(keyFrame, "", 0);
} else {
#ifdef DEBUG_READ
cout << "Read " << value << " (key = " << key.ToString() << ") --> " << value << endl;
#endif
zframe_reset(keyFrame, value.c_str(), value.length());
}
}
//Now we can remove the table ID frame from the message (doing so before would confuse zmsg_next())
zmsg_remove(msg, tableIdFrame);
zframe_destroy(&tableIdFrame);
#ifdef DEBUG_READ
cout << "Final reply msg size: " << zmsg_size(msg) << endl;
#endif
}
/**
* The main function for the update worker thread.
*
* This function parses the header, calls the appropriate handler function
* and sends the response for PARTSYNC requests
*/
static void readWorkerThreadFunction(zctx_t* ctx, Tablespace& tablespace) {
//Create the socket that is used to proxy requests to the external req/rep socket
void* replyProxySocket = zsocket_new(ctx, ZMQ_PUSH);
if (zsocket_connect(replyProxySocket, externalRequestProxyEndpoint)) {
debugZMQError("Connect reply proxy socket", errno);
}
assert(replyProxySocket);
//Create the socket we receive requests from
void* workPullSocket = zsocket_new(ctx, ZMQ_PULL);
zsocket_connect(workPullSocket, readWorkerThreadAddr);
assert(workPullSocket);
//Create the table open helper (creates a socket that sends table open requests)
TableOpenHelper tableOpenHelper(ctx);
//Create the data structure with all info for the poll handler
while (true) {
zmsg_t* msg = zmsg_recv(workPullSocket);
assert(msg);
assert(zmsg_size(msg) >= 1);
//Parse the header
//Contrary to the update message handling, we assume (checked by the request router) that
// the message contains an envelope. Read requests without envelope (--> without return path)
// don't really make sense.
zframe_t* routingFrame = zmsg_first(msg); //Envelope ID
assert(routingFrame);
zframe_t* delimiterFrame = zmsg_next(msg); //Envelope delimiter
assert(delimiterFrame);
zframe_t* headerFrame = zmsg_next(msg);
assert(headerFrame);
assert(isHeaderFrame(headerFrame));
//Get the request type
RequestType requestType = getRequestType(headerFrame);
//Process the rest of the frame
if (requestType == ReadRequest) {
handleReadRequest(tablespace, msg, tableOpenHelper);
} else if (requestType == CountRequest) {
cerr << "Count request TBD - WIP!" << endl;
} else {
cerr << "Internal routing error: request type " << requestType << " routed to update worker thread!" << endl;
}
//Send reply (the handler function rewrote the original message to contain the reply)
assert(msg);
assert(zmsg_size(msg) >= 3); //2 Envelope + 1 Response header (corner case: Nothing to be read)
zmsg_send(&msg, replyProxySocket);
}
printf("Stopping update processor\n");
zsocket_destroy(ctx, workPullSocket);
zsocket_destroy(ctx, replyProxySocket);
}
ReadWorkerController::ReadWorkerController(zctx_t* context, Tablespace& tablespace) : context(context), tablespace(tablespace), numThreads(3) {
//Initialize the push socket
workerPushSocket = zsocket_new(context, ZMQ_PUSH);
zsocket_bind(workerPushSocket, readWorkerThreadAddr);
}
void ReadWorkerController::start() {
threads = new std::thread*[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new std::thread(readWorkerThreadFunction, context, std::ref(tablespace));
}
}
ReadWorkerController::~ReadWorkerController() {
//Send an empty STOP message for each read worker thread (use a temporary socket)
void* tempSocket = zsocket_new(context, ZMQ_PUSH); //Create a temporary socket
zsocket_connect(tempSocket, readWorkerThreadAddr);
for (int i = 0; i < numThreads; i++) {
//Send an empty msg (signals the table open thread to stop)
sendEmptyFrameMessage(tempSocket);
}
//Cleanup
zsocket_destroy(context, &tempSocket);
//Wait for each thread to exit
for (int i = 0; i < numThreads; i++) {
threads[i]->join();
delete threads[i];
}
//Free the array
if (numThreads > 0) {
delete[] threads;
}
}
void ReadWorkerController::send(zmsg_t** msg) {
zmsg_send(msg, workerPushSocket);
}
Added count request handler
e893/*
* File: UpdateWorker.cpp
* Author: uli
*
* Created on 23. April 2013, 10:35
*/
#include "ReadWorker.hpp"
#include <czmq.h>
#include <string>
#include <iostream>
#include "TableOpenHelper.hpp"
#include "Tablespace.hpp"
#include "protocol.hpp"
#include "zutil.hpp"
#include "endpoints.hpp"
using namespace std;
#define DEBUG_READ
/**
* Read request handler. Shall be called
*
* The original message is modified to contain the response.
*
* Envelope + Read request Header + Table ID[what zmsg_next() must return] + Payload
*/
static void handleCountRequest(Tablespace& tables, zmsg_t* msg, TableOpenHelper& openHelper) {
#ifdef DEBUG_READ
printf("Starting to handle count request of size %d\n", (uint32_t) zmsg_size(msg) - 3);
fflush(stdout);
#endif
//Parse the table id
zframe_t* tableIdFrame = zmsg_next(msg);
assert(zframe_size(tableIdFrame) == sizeof (uint32_t));
uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));
//Parse the start/end frame
zframe_t* rangeStartFrame = zmsg_next(msg);
zframe_t* rangeEndFrame = zmsg_next(msg);
bool haveRangeStart = !(rangeStartFrame == NULL || zframe_size(rangeStartFrame) == 0);
bool haveRangeEnd = !(rangeEndFrame == NULL || zframe_size(rangeEndFrame) == 0);
std::string rangeStart = (haveRangeStart ? string((char*) zframe_data(rangeStartFrame), zframe_size(rangeStartFrame)) : "");
std::string rangeEnd = (haveRangeEnd ? string((char*) zframe_data(rangeEndFrame), zframe_size(rangeEndFrame)) : "");
//Remove the range frames (if any), the reply is shorter
if (rangeStartFrame) {
removeAndDestroyFrame(msg, rangeStartFrame);
}
if (rangeEndFrame) {
removeAndDestroyFrame(msg, rangeEndFrame);
}
//Get the table to read from
leveldb::DB* db = tables.getTable(tableId, openHelper);
//Create the response object
leveldb::ReadOptions readOptions;
string value; //Where the value will be placed
leveldb::Status status;
//Create the iterator
leveldb::Iterator* it = db->NewIterator(leveldb::ReadOwptions());
if (haveRangeStart) {
it->Sekk
} else {
it->SeekToFirst();
}
uint64_t count = 0;
//Iterate over all key-values in the range
for (; it->Valid(); it->Next()) {
count++;
string key = it->key().ToString();
if (haveRangeEnd && key >= rangeEnd) {
break;
}
}
//TODO handle error
assert(it->status().ok()); // Check for any errors found during the scan
//Delete the iterator
delete it;
//Build the response message
zframe_reset(tableIdFrame, &count, sizeof (uint64_t));
}
/**
* Read request handler. Shall be called for Read requests only!
*
* The original message is modified to contain the response.
*
* Envelope + Read request Header + Table ID[what zmsg_next() must return] + Payload
*/
static void handleReadRequest(Tablespace& tables, zmsg_t* msg, TableOpenHelper& openHelper) {
#ifdef DEBUG_READ
printf("Starting to handle read request of size %d\n", (uint32_t) zmsg_size(msg) - 3);
fflush(stdout);
#endif
//Parse the table id
zframe_t* tableIdFrame = zmsg_next(msg);
assert(zframe_size(tableIdFrame) == sizeof (uint32_t));
uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));
//Parse the
//Get the table to read from
leveldb::DB* db = tables.getTable(tableId, openHelper);
//Create the response object
leveldb::ReadOptions readOptions;
leveldb::Status status;
//Read each read request
zframe_t* keyFrame = NULL;
while ((keyFrame = zmsg_next(msg)) != NULL) {
//Build a slice of the key (zero-copy)
string keystr((char*) zframe_data(keyFrame), zframe_size(keyFrame));
leveldb::Slice key((char*) zframe_data(keyFrame), zframe_size(keyFrame));
#ifdef DEBUG_READ
printf("Reading key %s from table %d\n", key.ToString().c_str(), tableId);
#endif
status = db->Get(readOptions, key, &value);
if (status.IsNotFound()) {
#ifdef DEBUG_READ
cout << "Could not find value for key " << key.ToString() << "in table " << tableId << endl;
#endif
//Empty value
zframe_reset(keyFrame, "", 0);
} else {
#ifdef DEBUG_READ
cout << "Read " << value << " (key = " << key.ToString() << ") --> " << value << endl;
#endif
zframe_reset(keyFrame, value.c_str(), value.length());
}
}
//Now we can remove the table ID frame from the message (doing so before would confuse zmsg_next())
zmsg_remove(msg, tableIdFrame);
zframe_destroy(&tableIdFrame);
#ifdef DEBUG_READ
cout << "Final reply msg size: " << zmsg_size(msg) << endl;
#endif
}
/**
* The main function for the update worker thread.
*
* This function parses the header, calls the appropriate handler function
* and sends the response for PARTSYNC requests
*/
static void readWorkerThreadFunction(zctx_t* ctx, Tablespace& tablespace) {
//Create the socket that is used to proxy requests to the external req/rep socket
void* replyProxySocket = zsocket_new(ctx, ZMQ_PUSH);
if (zsocket_connect(replyProxySocket, externalRequestProxyEndpoint)) {
debugZMQError("Connect reply proxy socket", errno);
}
assert(replyProxySocket);
//Create the socket we receive requests from
void* workPullSocket = zsocket_new(ctx, ZMQ_PULL);
zsocket_connect(workPullSocket, readWorkerThreadAddr);
assert(workPullSocket);
//Create the table open helper (creates a socket that sends table open requests)
TableOpenHelper tableOpenHelper(ctx);
//Create the data structure with all info for the poll handler
while (true) {
zmsg_t* msg = zmsg_recv(workPullSocket);
assert(msg);
assert(zmsg_size(msg) >= 1);
//Parse the header
//Contrary to the update message handling, we assume (checked by the request router) that
// the message contains an envelope. Read requests without envelope (--> without return path)
// don't really make sense.
zframe_t* routingFrame = zmsg_first(msg); //Envelope ID
assert(routingFrame);
zframe_t* delimiterFrame = zmsg_next(msg); //Envelope delimiter
assert(delimiterFrame);
zframe_t* headerFrame = zmsg_next(msg);
assert(headerFrame);
assert(isHeaderFrame(headerFrame));
//Get the request type
RequestType requestType = getRequestType(headerFrame);
//Process the rest of the frame
if (requestType == ReadRequest) {
handleReadRequest(tablespace, msg, tableOpenHelper);
} else if (requestType == CountRequest) {
handleCountRequest(tablespace, msg, tableOpenHelper);
} else {
cerr << "Internal routing error: request type " << requestType << " routed to update worker thread!" << endl;
}
//Send reply (the handler function rewrote the original message to contain the reply)
assert(msg);
assert(zmsg_size(msg) >= 3); //2 Envelope + 1 Response header (corner case: Nothing to be read)
zmsg_send(&msg, replyProxySocket);
}
printf("Stopping update processor\n");
zsocket_destroy(ctx, workPullSocket);
zsocket_destroy(ctx, replyProxySocket);
}
ReadWorkerController::ReadWorkerController(zctx_t* context, Tablespace& tablespace) : context(context), tablespace(tablespace), numThreads(3) {
//Initialize the push socket
workerPushSocket = zsocket_new(context, ZMQ_PUSH);
zsocket_bind(workerPushSocket, readWorkerThreadAddr);
}
void ReadWorkerController::start() {
threads = new std::thread*[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new std::thread(readWorkerThreadFunction, context, std::ref(tablespace));
}
}
ReadWorkerController::~ReadWorkerController() {
//Send an empty STOP message for each read worker thread (use a temporary socket)
void* tempSocket = zsocket_new(context, ZMQ_PUSH); //Create a temporary socket
zsocket_connect(tempSocket, readWorkerThreadAddr);
for (int i = 0; i < numThreads; i++) {
//Send an empty msg (signals the table open thread to stop)
sendEmptyFrameMessage(tempSocket);
}
//Cleanup
zsocket_destroy(context, &tempSocket);
//Wait for each thread to exit
for (int i = 0; i < numThreads; i++) {
threads[i]->join();
delete threads[i];
}
//Free the array
if (numThreads > 0) {
delete[] threads;
}
}
void ReadWorkerController::send(zmsg_t** msg) {
zmsg_send(msg, workerPushSocket);
}
|
/*************************************************************************
*
* $RCSfile: ToolPanel.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2005-03-18 16:59:43 $
*
* 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 EXPRESSED 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): _______________________________________
*
*
************************************************************************/
#include "ToolPanel.hxx"
#include "TaskPaneFocusManager.hxx"
#include "TitleBar.hxx"
#include "TitledControl.hxx"
#include "ControlContainer.hxx"
#include "TaskPaneViewShell.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
namespace sd { namespace toolpanel {
/** Use WB_DIALOGCONTROL as argument for the Control constructor to
let VCL handle focus traveling. In addition the control
descriptors have to use WB_TABSTOP.
*/
ToolPanel::ToolPanel (
Window* pParentWindow,
TaskPaneViewShell& rViewShell)
: Control (pParentWindow, WB_DIALOGCONTROL),
mrViewShell(rViewShell),
TreeNode (NULL),
mbRearrangeActive(false)
{
SetBackground (Wallpaper ());
SetAccessibleName (String::CreateFromAscii("Task Pane"));
SetAccessibleDescription (String::CreateFromAscii("Impress task pane"));
}
ToolPanel::~ToolPanel (void)
{
}
sal_uInt32 ToolPanel::AddControl (
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
ULONG nHelpId)
{
TitledControl* pTitledControl = new TitledControl (
this,
pControlFactory,
rTitle,
TitleBar::TBT_CONTROL_TITLE);
::std::auto_ptr<TreeNode> pChild (pTitledControl);
// Get the (grand) parent window which is focus-wise our parent.
Window* pParent = GetParent();
if (pParent != NULL)
pParent = pParent->GetParent();
if (pParent != NULL)
{
// Add a down link only for the first control so that when entering
// the sub tool panel the focus is set to the first control.
if (mpControlContainer->GetControlCount() == 1)
FocusManager::Instance().RegisterLink (pParent, pChild->GetWindow());
else
FocusManager::Instance().RegisterUpLink (pChild->GetWindow(), pParent);
}
pTitledControl->GetTitleBar()->SetHelpId(nHelpId);
return mpControlContainer->AddControl (pChild);
}
void ToolPanel::ListHasChanged (void)
{
mpControlContainer->ListHasChanged ();
Rearrange ();
}
void ToolPanel::Resize (void)
{
Control::Resize();
Rearrange ();
}
void ToolPanel::RequestResize (void)
{
Invalidate();
Rearrange ();
}
/** Subtract the space for the title bars from the available space and
give the remaining space to the active control.
*/
void ToolPanel::Rearrange (void)
{
// Prevent recursive calls.
if ( ! mbRearrangeActive && mpControlContainer->GetVisibleControlCount()>0)
{
mbRearrangeActive = true;
SetBackground (Wallpaper ());
// Make the area that is covered by the children a little bit
// smaller so that a frame is visible arround them.
Rectangle aAvailableArea (Point(0,0), GetOutputSizePixel());
int nWidth = aAvailableArea.GetWidth();
sal_uInt32 nControlCount (mpControlContainer->GetControlCount());
sal_uInt32 nActiveControlIndex (
mpControlContainer->GetActiveControlIndex());
// Place title bars of controls above the active control and thereby
// determine the top of the active control.
sal_uInt32 nIndex;
for (nIndex=mpControlContainer->GetFirstIndex();
nIndex<nActiveControlIndex;
nIndex=mpControlContainer->GetNextIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
Size(nWidth, nHeight));
aAvailableArea.Top() += nHeight;
}
}
// Place title bars of controls below the active control and thereby
// determine the bottom of the active control.
for (nIndex=mpControlContainer->GetLastIndex();
nIndex<nControlCount && nIndex!=nActiveControlIndex;
nIndex=mpControlContainer->GetPreviousIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
Point(aAvailableArea.Left(),
aAvailableArea.Bottom()-nHeight+1),
Size(nWidth, nHeight));
aAvailableArea.Bottom() -= nHeight;
}
}
// Finally place the active control.
TreeNode* pChild = mpControlContainer->GetControl(nActiveControlIndex);
if (pChild != NULL)
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
aAvailableArea.GetSize());
mbRearrangeActive = false;
}
else
SetBackground (
Application::GetSettings().GetStyleSettings().GetDialogColor());
}
Size ToolPanel::GetPreferredSize (void)
{
return Size(300,300);
}
sal_Int32 ToolPanel::GetPreferredWidth (sal_Int32 nHeight)
{
return 300;
}
sal_Int32 ToolPanel::GetPreferredHeight (sal_Int32 nWidth)
{
return 300;
}
bool ToolPanel::IsResizable (void)
{
return true;
}
::Window* ToolPanel::GetWindow (void)
{
return this;
}
TaskPaneShellManager* ToolPanel::GetShellManager (void)
{
return &mrViewShell.GetSubShellManager();
}
} } // end of namespace ::sd::toolpanel
INTEGRATION: CWS impress51 (1.6.46); FILE MERGED
2005/06/06 12:18:25 af 1.6.46.3: #i50190# Adaption to changes in TaskPaneFocusManager. Focus is cycled through children on KEY_UP/DOWN.
2005/05/19 09:37:21 af 1.6.46.2: #i48247# Renamed TreeNode::{Get,Create}Accessible() to {Get,Create}AccessibleObject().
2005/05/04 15:02:44 af 1.6.46.1: #i48247# Added CreateAccessible() method.
/*************************************************************************
*
* $RCSfile: ToolPanel.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2005-07-14 10:23:39 $
*
* 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 EXPRESSED 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): _______________________________________
*
*
************************************************************************/
#include "taskpane/ToolPanel.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TitleBar.hxx"
#include "taskpane/TitledControl.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneViewShell.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#include "AccessibleTaskPane.hxx"
#include "strings.hrc"
#include "sdresid.hxx"
#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
namespace sd { namespace toolpanel {
/** Use WB_DIALOGCONTROL as argument for the Control constructor to
let VCL handle focus traveling. In addition the control
descriptors have to use WB_TABSTOP.
*/
ToolPanel::ToolPanel (
Window* pParentWindow,
TaskPaneViewShell& rViewShell)
: Control (pParentWindow, WB_DIALOGCONTROL),
mrViewShell(rViewShell),
TreeNode (NULL),
mbRearrangeActive(false)
{
SetBackground (Wallpaper ());
}
ToolPanel::~ToolPanel (void)
{
}
sal_uInt32 ToolPanel::AddControl (
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
ULONG nHelpId)
{
TitledControl* pTitledControl = new TitledControl (
this,
pControlFactory,
rTitle,
TitleBar::TBT_CONTROL_TITLE);
::std::auto_ptr<TreeNode> pChild (pTitledControl);
// Get the (grand) parent window which is focus-wise our parent.
Window* pParent = GetParent();
if (pParent != NULL)
pParent = pParent->GetParent();
FocusManager& rFocusManager (FocusManager::Instance());
int nControlCount (mpControlContainer->GetControlCount());
// Add a link up from every control to the parent. A down link is added
// only for the first control so that when entering the sub tool panel
// the focus is set to the first control.
if (pParent != NULL)
{
if (nControlCount == 1)
rFocusManager.RegisterDownLink(pParent, pChild->GetWindow());
rFocusManager.RegisterUpLink(pChild->GetWindow(), pParent);
}
// Replace the old links for cycling between first and last child by
// current ones.
if (nControlCount > 0)
{
::Window* pFirst = mpControlContainer->GetControl(0)->GetWindow();
::Window* pLast = mpControlContainer->GetControl(nControlCount-1)->GetWindow();
rFocusManager.RemoveLinks(pFirst,pLast);
rFocusManager.RemoveLinks(pLast,pFirst);
rFocusManager.RegisterLink(pFirst,pChild->GetWindow(), KEY_UP);
rFocusManager.RegisterLink(pChild->GetWindow(),pFirst, KEY_DOWN);
}
pTitledControl->GetTitleBar()->SetHelpId(nHelpId);
return mpControlContainer->AddControl (pChild);
}
void ToolPanel::ListHasChanged (void)
{
mpControlContainer->ListHasChanged ();
Rearrange ();
}
void ToolPanel::Resize (void)
{
Control::Resize();
Rearrange ();
}
void ToolPanel::RequestResize (void)
{
Invalidate();
Rearrange ();
}
/** Subtract the space for the title bars from the available space and
give the remaining space to the active control.
*/
void ToolPanel::Rearrange (void)
{
// Prevent recursive calls.
if ( ! mbRearrangeActive && mpControlContainer->GetVisibleControlCount()>0)
{
mbRearrangeActive = true;
SetBackground (Wallpaper ());
// Make the area that is covered by the children a little bit
// smaller so that a frame is visible arround them.
Rectangle aAvailableArea (Point(0,0), GetOutputSizePixel());
int nWidth = aAvailableArea.GetWidth();
sal_uInt32 nControlCount (mpControlContainer->GetControlCount());
sal_uInt32 nActiveControlIndex (
mpControlContainer->GetActiveControlIndex());
// Place title bars of controls above the active control and thereby
// determine the top of the active control.
sal_uInt32 nIndex;
for (nIndex=mpControlContainer->GetFirstIndex();
nIndex<nActiveControlIndex;
nIndex=mpControlContainer->GetNextIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
Size(nWidth, nHeight));
aAvailableArea.Top() += nHeight;
}
}
// Place title bars of controls below the active control and thereby
// determine the bottom of the active control.
for (nIndex=mpControlContainer->GetLastIndex();
nIndex<nControlCount && nIndex!=nActiveControlIndex;
nIndex=mpControlContainer->GetPreviousIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
Point(aAvailableArea.Left(),
aAvailableArea.Bottom()-nHeight+1),
Size(nWidth, nHeight));
aAvailableArea.Bottom() -= nHeight;
}
}
// Finally place the active control.
TreeNode* pChild = mpControlContainer->GetControl(nActiveControlIndex);
if (pChild != NULL)
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
aAvailableArea.GetSize());
mbRearrangeActive = false;
}
else
SetBackground (
Application::GetSettings().GetStyleSettings().GetDialogColor());
}
Size ToolPanel::GetPreferredSize (void)
{
return Size(300,300);
}
sal_Int32 ToolPanel::GetPreferredWidth (sal_Int32 nHeight)
{
return 300;
}
sal_Int32 ToolPanel::GetPreferredHeight (sal_Int32 nWidth)
{
return 300;
}
bool ToolPanel::IsResizable (void)
{
return true;
}
::Window* ToolPanel::GetWindow (void)
{
return this;
}
TaskPaneShellManager* ToolPanel::GetShellManager (void)
{
return &mrViewShell.GetSubShellManager();
}
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> ToolPanel::CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent)
{
return new ::accessibility::AccessibleTaskPane (
rxParent,
String(SdResId(STR_RIGHT_PANE_TITLE)),
String(SdResId(STR_RIGHT_PANE_TITLE)),
*this);
}
} } // end of namespace ::sd::toolpanel
|
/// \file urbi/umessage.hxx
#include <urbi/uvalue.hh>
namespace urbi
{
template <typename T>
inline
int
getValue(UMessage* m, T& val)
{
int res = 0;
if ((res = (m && m->type == MESSAGE_DATA)))
val = *m->value;
delete m;
return res;
}
template <>
inline
int
getValue<double>(UMessage* m, double& val)
{
int res = 0;
if ((res = (m && m->type == MESSAGE_DATA && m->value->type == DATA_DOUBLE)))
val = (double) *m->value;
delete m;
return res;
}
inline
UMessage::operator urbi::UValue& ()
{
return *value;
}
inline
std::ostream&
operator<<(std::ostream& o, const UMessage& m)
{
return m.print(o);
};
} // namespace urbi
UMessage: improve getValue.
* include/urbi/umessage.hxx: Explictly call the cast towards the
target value to avoid "ambiguities" in the assignment.
/// \file urbi/umessage.hxx
#include <urbi/uvalue.hh>
namespace urbi
{
template <typename T>
inline
int
getValue(UMessage* m, T& val)
{
int res = 0;
if ((res = (m && m->type == MESSAGE_DATA)))
val = (T) *m->value;
delete m;
return res;
}
template <>
inline
int
getValue<double>(UMessage* m, double& val)
{
int res = 0;
if ((res = (m && m->type == MESSAGE_DATA && m->value->type == DATA_DOUBLE)))
val = (double) *m->value;
delete m;
return res;
}
inline
UMessage::operator urbi::UValue& ()
{
return *value;
}
inline
std::ostream&
operator<<(std::ostream& o, const UMessage& m)
{
return m.print(o);
};
} // namespace urbi
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// TRD MCM (Multi Chip Module) simulator //
// which simulated the TRAP processing after the AD-conversion //
// The relevant parameters (i.e. configuration registers of the TRAP //
// configuration are taken from AliTRDtrapConfig. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <fstream> // needed for raw data dump
#include <TCanvas.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TGraph.h>
#include <TLine.h>
#include <TMath.h>
#include <TRandom.h>
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliLoader.h"
#include "AliTRDdigit.h"
#include "AliTRDfeeParam.h"
#include "AliTRDtrapConfig.h"
#include "AliTRDSimParam.h"
#include "AliTRDgeometry.h"
#include "AliTRDcalibDB.h"
#include "AliTRDdigitsManager.h"
#include "AliTRDarrayADC.h"
#include "AliTRDarrayDictionary.h"
#include "AliTRDpadPlane.h"
#include "AliTRDtrackletMCM.h"
#include "AliTRDmcmSim.h"
#include "AliMagF.h"
#include "TGeoGlobalMagField.h"
ClassImp(AliTRDmcmSim)
Bool_t AliTRDmcmSim::fgApplyCut = kTRUE;
Float_t AliTRDmcmSim::fgChargeNorm = 65000.;
Int_t AliTRDmcmSim::fgAddBaseline = 10;
Int_t AliTRDmcmSim::fgPidNBinsQ0 = 40;
Int_t AliTRDmcmSim::fgPidNBinsQ1 = 50;
Bool_t AliTRDmcmSim::fgPidLutDelete = kFALSE;
Int_t AliTRDmcmSim::fgPidLutDefault[40][50] = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 9, 6, 12, 29, 53, 76, 94, 107, 116, 122, 126, 128, 129, 129, 129, 128, 127, 126, 124, 122, 120, 117, 115, 112, 109, 107, 104, 101, 99, 96, 94, 91, 89, 87, 85, 83, 81, 79, 78, 77, 75, 74, 73, 72, 72, 71, 71, 70, 70 },
{ 0, 14, 8, 17, 37, 66, 94, 116, 131, 140, 146, 150, 152, 153, 153, 152, 150, 148, 145, 143, 139, 136, 132, 129, 125, 121, 118, 114, 110, 107, 104, 101, 98, 95, 93, 91, 89, 87, 85, 83, 82, 81, 80, 79, 78, 77, 77, 76, 76, 75 },
{ 0, 33, 19, 34, 69, 112, 145, 167, 181, 189, 194, 196, 197, 197, 196, 194, 191, 188, 184, 180, 175, 170, 165, 159, 154, 148, 143, 137, 132, 127, 123, 118, 114, 111, 107, 104, 101, 99, 96, 94, 92, 91, 89, 88, 87, 86, 85, 85, 84, 84 },
{ 0, 82, 52, 83, 136, 180, 205, 218, 226, 230, 232, 233, 233, 233, 232, 230, 228, 226, 223, 219, 215, 210, 205, 199, 193, 187, 180, 173, 167, 160, 154, 148, 142, 136, 131, 127, 122, 119, 115, 112, 109, 106, 104, 102, 100, 99, 97, 96, 95, 94 },
{ 0, 132, 96, 136, 185, 216, 231, 238, 242, 244, 245, 245, 245, 245, 245, 244, 243, 242, 240, 238, 236, 233, 230, 226, 222, 217, 212, 206, 200, 193, 187, 180, 173, 167, 161, 155, 149, 144, 139, 134, 130, 126, 123, 120, 117, 114, 112, 110, 108, 107 },
{ 0, 153, 120, 160, 203, 227, 238, 243, 246, 247, 248, 249, 249, 249, 248, 248, 247, 246, 245, 244, 243, 241, 239, 237, 234, 231, 228, 224, 219, 215, 209, 204, 198, 192, 186, 180, 174, 168, 163, 157, 152, 147, 143, 139, 135, 131, 128, 125, 123, 120 },
{ 0, 156, 128, 166, 207, 229, 239, 244, 247, 248, 249, 249, 249, 249, 249, 249, 248, 247, 247, 246, 244, 243, 242, 240, 238, 236, 233, 230, 227, 224, 220, 216, 212, 207, 202, 197, 192, 187, 181, 176, 171, 166, 161, 156, 152, 148, 144, 140, 137, 134 },
{ 0, 152, 128, 166, 206, 228, 239, 244, 246, 248, 249, 249, 249, 249, 249, 248, 248, 247, 246, 245, 244, 243, 241, 240, 238, 236, 234, 232, 229, 226, 224, 220, 217, 214, 210, 206, 202, 197, 193, 188, 184, 179, 174, 170, 166, 161, 157, 153, 150, 146 },
{ 0, 146, 126, 164, 203, 226, 237, 243, 246, 247, 248, 248, 248, 248, 248, 247, 247, 246, 245, 244, 242, 241, 239, 238, 236, 234, 232, 230, 227, 225, 223, 220, 217, 215, 212, 209, 205, 202, 199, 195, 191, 187, 183, 179, 175, 171, 168, 164, 160, 156 },
{ 0, 140, 123, 160, 200, 224, 235, 241, 244, 246, 247, 247, 247, 247, 247, 246, 245, 244, 243, 242, 240, 238, 237, 235, 233, 230, 228, 226, 224, 221, 219, 217, 215, 212, 210, 207, 205, 202, 200, 197, 194, 191, 188, 184, 181, 178, 174, 171, 168, 164 },
{ 0, 133, 119, 156, 196, 220, 233, 239, 243, 245, 245, 246, 246, 246, 245, 244, 243, 242, 241, 239, 237, 235, 233, 231, 229, 226, 224, 221, 219, 216, 214, 212, 210, 208, 206, 204, 202, 199, 197, 195, 193, 191, 188, 186, 183, 181, 178, 175, 172, 169 },
{ 0, 127, 115, 152, 192, 217, 230, 237, 241, 243, 244, 244, 244, 244, 243, 242, 241, 240, 238, 236, 234, 232, 229, 227, 224, 221, 218, 216, 213, 210, 208, 206, 203, 201, 200, 198, 196, 194, 193, 191, 190, 188, 186, 185, 183, 181, 179, 177, 174, 172 },
{ 0, 121, 111, 147, 187, 213, 227, 235, 239, 241, 242, 243, 243, 242, 241, 240, 239, 237, 236, 233, 231, 228, 225, 222, 219, 216, 213, 210, 207, 204, 201, 199, 196, 194, 192, 191, 189, 188, 187, 185, 184, 183, 182, 181, 180, 178, 177, 176, 174, 172 },
{ 0, 116, 107, 142, 181, 209, 224, 232, 237, 239, 240, 241, 241, 240, 239, 238, 237, 235, 233, 230, 227, 224, 221, 218, 214, 211, 207, 204, 200, 197, 194, 191, 189, 187, 185, 183, 182, 180, 179, 178, 178, 177, 176, 175, 175, 174, 173, 172, 172, 170 },
{ 0, 112, 103, 136, 176, 204, 220, 229, 234, 237, 238, 239, 239, 238, 237, 236, 234, 232, 230, 227, 224, 221, 217, 213, 209, 205, 201, 198, 194, 190, 187, 184, 181, 179, 177, 175, 174, 172, 171, 171, 170, 169, 169, 169, 168, 168, 168, 168, 167, 167 },
{ 0, 107, 99, 131, 170, 199, 216, 226, 231, 234, 236, 237, 237, 236, 235, 234, 232, 230, 227, 224, 221, 217, 213, 209, 205, 200, 196, 192, 188, 184, 180, 177, 174, 172, 169, 167, 166, 164, 163, 162, 162, 161, 161, 161, 161, 161, 161, 162, 162, 162 },
{ 0, 104, 94, 125, 164, 193, 212, 222, 228, 232, 233, 234, 234, 234, 233, 231, 229, 227, 224, 221, 218, 214, 210, 205, 201, 196, 191, 187, 182, 178, 174, 171, 168, 165, 162, 160, 158, 157, 155, 154, 154, 153, 153, 153, 153, 154, 154, 154, 155, 155 },
{ 0, 100, 90, 119, 157, 188, 207, 219, 225, 229, 231, 232, 232, 231, 230, 229, 227, 224, 222, 218, 215, 211, 206, 202, 197, 192, 187, 182, 178, 173, 169, 165, 162, 158, 156, 153, 151, 149, 148, 147, 146, 146, 145, 145, 145, 146, 146, 147, 148, 148 },
{ 0, 97, 86, 113, 150, 182, 202, 215, 222, 226, 228, 229, 229, 229, 228, 226, 224, 222, 219, 216, 212, 208, 203, 199, 194, 188, 183, 178, 173, 169, 164, 160, 156, 153, 150, 147, 145, 143, 141, 140, 139, 138, 138, 138, 138, 138, 139, 139, 140, 141 },
{ 0, 94, 82, 107, 144, 176, 197, 210, 218, 223, 225, 227, 227, 227, 226, 224, 222, 220, 217, 213, 209, 205, 201, 196, 191, 186, 180, 175, 170, 165, 160, 156, 152, 148, 145, 142, 139, 137, 135, 134, 132, 131, 131, 131, 131, 131, 131, 132, 132, 133 },
{ 0, 92, 78, 102, 137, 169, 192, 206, 215, 220, 223, 224, 224, 224, 223, 222, 220, 217, 215, 211, 207, 203, 199, 194, 188, 183, 178, 172, 167, 162, 157, 152, 148, 144, 140, 137, 134, 132, 130, 128, 127, 125, 125, 124, 124, 124, 124, 125, 125, 126 },
{ 0, 90, 75, 96, 131, 163, 187, 202, 211, 216, 220, 221, 222, 222, 221, 220, 218, 215, 212, 209, 205, 201, 197, 192, 187, 181, 176, 170, 165, 159, 154, 149, 145, 141, 137, 133, 130, 128, 125, 123, 122, 120, 119, 118, 118, 118, 118, 118, 119, 119 },
{ 0, 88, 71, 91, 124, 157, 181, 197, 207, 213, 217, 219, 219, 219, 219, 217, 216, 213, 211, 207, 204, 200, 195, 190, 185, 180, 174, 169, 163, 158, 152, 147, 142, 138, 134, 130, 127, 124, 121, 119, 117, 116, 114, 114, 113, 112, 112, 112, 112, 113 },
{ 0, 87, 68, 86, 118, 151, 176, 192, 203, 210, 214, 216, 217, 217, 217, 215, 214, 212, 209, 206, 202, 198, 194, 189, 184, 179, 173, 167, 162, 156, 151, 146, 141, 136, 132, 128, 124, 121, 118, 116, 114, 112, 110, 109, 108, 108, 107, 107, 107, 107 },
{ 0, 85, 65, 81, 112, 144, 170, 188, 199, 206, 211, 213, 214, 215, 214, 213, 212, 210, 207, 204, 201, 197, 193, 188, 183, 178, 172, 167, 161, 155, 150, 145, 140, 135, 130, 126, 122, 119, 116, 113, 111, 109, 107, 106, 105, 104, 103, 103, 102, 102 },
{ 0, 84, 62, 77, 106, 138, 165, 183, 195, 203, 208, 210, 212, 212, 212, 211, 210, 208, 206, 203, 200, 196, 192, 187, 183, 177, 172, 166, 161, 155, 150, 144, 139, 134, 129, 125, 121, 117, 114, 111, 109, 106, 104, 103, 101, 100, 99, 99, 98, 98 },
{ 0, 84, 60, 73, 101, 133, 159, 178, 191, 199, 204, 208, 209, 210, 210, 209, 208, 206, 204, 202, 199, 195, 191, 187, 182, 177, 172, 166, 161, 155, 150, 144, 139, 134, 129, 124, 120, 116, 113, 110, 107, 104, 102, 100, 99, 98, 96, 96, 95, 95 },
{ 0, 83, 58, 69, 96, 127, 154, 174, 187, 196, 201, 205, 207, 208, 208, 207, 206, 205, 203, 200, 197, 194, 190, 186, 182, 177, 172, 167, 161, 156, 150, 145, 139, 134, 129, 124, 120, 116, 112, 109, 106, 103, 101, 99, 97, 95, 94, 93, 92, 92 },
{ 0, 82, 56, 66, 91, 121, 149, 169, 183, 192, 198, 202, 204, 206, 206, 206, 205, 203, 201, 199, 196, 193, 190, 186, 182, 177, 172, 167, 162, 156, 151, 145, 140, 135, 129, 125, 120, 116, 112, 108, 105, 102, 100, 97, 95, 94, 92, 91, 90, 89 },
{ 0, 82, 54, 62, 86, 116, 144, 165, 179, 189, 195, 199, 202, 203, 204, 204, 203, 202, 200, 198, 196, 193, 189, 186, 182, 177, 173, 168, 163, 157, 152, 146, 141, 136, 130, 125, 121, 116, 112, 108, 105, 102, 99, 96, 94, 92, 91, 89, 88, 87 },
{ 0, 82, 52, 59, 82, 111, 139, 160, 175, 185, 192, 197, 200, 201, 202, 202, 201, 200, 199, 197, 195, 192, 189, 186, 182, 178, 173, 168, 163, 158, 153, 148, 142, 137, 132, 127, 122, 117, 113, 109, 105, 102, 99, 96, 94, 92, 90, 88, 87, 85 },
{ 0, 82, 50, 56, 78, 106, 134, 156, 171, 182, 189, 194, 197, 199, 200, 200, 200, 199, 198, 196, 194, 191, 188, 185, 182, 178, 174, 169, 164, 159, 154, 149, 144, 138, 133, 128, 123, 118, 114, 110, 106, 102, 99, 96, 93, 91, 89, 87, 86, 84 },
{ 0, 82, 49, 54, 74, 102, 129, 151, 167, 179, 186, 191, 195, 197, 198, 198, 198, 197, 196, 195, 193, 191, 188, 185, 182, 178, 174, 170, 165, 161, 156, 151, 145, 140, 135, 130, 125, 120, 115, 111, 107, 103, 100, 97, 94, 91, 89, 87, 85, 83 },
{ 0, 82, 47, 51, 70, 97, 124, 147, 164, 175, 183, 189, 192, 195, 196, 197, 197, 196, 195, 194, 192, 190, 188, 185, 182, 178, 175, 171, 166, 162, 157, 152, 147, 142, 137, 132, 127, 122, 117, 112, 108, 104, 101, 97, 94, 91, 89, 87, 85, 83 },
{ 0, 83, 46, 49, 67, 93, 120, 143, 160, 172, 180, 186, 190, 192, 194, 195, 195, 195, 194, 193, 191, 189, 187, 185, 182, 179, 175, 172, 167, 163, 159, 154, 149, 144, 139, 134, 129, 124, 119, 114, 110, 106, 102, 98, 95, 92, 89, 87, 85, 83 },
{ 0, 83, 45, 47, 64, 89, 116, 139, 156, 169, 177, 184, 188, 190, 192, 193, 193, 193, 193, 192, 190, 189, 187, 184, 182, 179, 176, 172, 168, 164, 160, 156, 151, 146, 141, 136, 131, 126, 121, 116, 112, 108, 104, 100, 96, 93, 90, 88, 85, 83 },
{ 0, 84, 44, 45, 61, 85, 111, 134, 152, 165, 175, 181, 185, 188, 190, 191, 192, 192, 191, 191, 189, 188, 186, 184, 182, 179, 176, 173, 169, 166, 162, 157, 153, 148, 143, 138, 133, 128, 124, 119, 114, 110, 106, 102, 98, 95, 91, 89, 86, 84 },
{ 0, 85, 43, 43, 58, 81, 107, 131, 149, 162, 172, 178, 183, 186, 188, 190, 190, 190, 190, 189, 188, 187, 186, 184, 182, 179, 176, 173, 170, 167, 163, 159, 155, 150, 145, 141, 136, 131, 126, 121, 117, 112, 108, 104, 100, 96, 93, 90, 87, 85 },
{ 0, 85, 42, 41, 55, 78, 103, 127, 145, 159, 169, 176, 181, 184, 186, 188, 189, 189, 189, 188, 188, 186, 185, 183, 181, 179, 177, 174, 171, 168, 164, 160, 156, 152, 148, 143, 138, 134, 129, 124, 119, 115, 110, 106, 102, 98, 95, 91, 88, 86 }
};
Int_t (*AliTRDmcmSim::fgPidLut) = *fgPidLutDefault;
//_____________________________________________________________________________
AliTRDmcmSim::AliTRDmcmSim() : TObject()
,fInitialized(kFALSE)
,fMaxTracklets(-1)
,fDetector(-1)
,fRobPos(-1)
,fMcmPos(-1)
,fRow (-1)
,fNADC(-1)
,fNTimeBin(-1)
,fADCR(NULL)
,fADCF(NULL)
,fMCMT(NULL)
,fTrackletArray(NULL)
,fZSM(NULL)
,fZSM1Dim(NULL)
,fFeeParam(NULL)
,fTrapConfig(NULL)
,fSimParam(NULL)
,fCommonParam(NULL)
,fCal(NULL)
,fGeo(NULL)
,fDigitsManager(NULL)
,fPedAcc(NULL)
,fGainCounterA(NULL)
,fGainCounterB(NULL)
,fTailAmplLong(NULL)
,fTailAmplShort(NULL)
,fNHits(0)
,fFitReg(NULL)
{
//
// AliTRDmcmSim default constructor
// By default, nothing is initialized.
// It is necessary to issue Init before use.
}
AliTRDmcmSim::~AliTRDmcmSim()
{
//
// AliTRDmcmSim destructor
//
if(fInitialized) {
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
delete [] fADCR[iadc];
delete [] fADCF[iadc];
delete [] fZSM [iadc];
}
delete [] fADCR;
delete [] fADCF;
delete [] fZSM;
delete [] fZSM1Dim;
delete [] fMCMT;
delete [] fPedAcc;
delete [] fGainCounterA;
delete [] fGainCounterB;
delete [] fTailAmplLong;
delete [] fTailAmplShort;
delete [] fFitReg;
fTrackletArray->Delete();
delete fTrackletArray;
delete fGeo;
}
}
void AliTRDmcmSim::Init( Int_t det, Int_t robPos, Int_t mcmPos, Bool_t /* newEvent */ )
{
//
// Initialize the class with new geometry information
// fADC array will be reused with filled by zero
//
if (!fInitialized) {
fFeeParam = AliTRDfeeParam::Instance();
fTrapConfig = AliTRDtrapConfig::Instance();
fSimParam = AliTRDSimParam::Instance();
fCommonParam = AliTRDCommonParam::Instance();
fCal = AliTRDcalibDB::Instance();
fGeo = new AliTRDgeometry();
}
fDetector = det;
fRobPos = robPos;
fMcmPos = mcmPos;
fNADC = fFeeParam->GetNadcMcm();
fNTimeBin = fCal->GetNumberOfTimeBins();
fRow = fFeeParam->GetPadRowFromMCM( fRobPos, fMcmPos );
fMaxTracklets = fFeeParam->GetMaxNrOfTracklets();
if (!fInitialized) {
fADCR = new Int_t *[fNADC];
fADCF = new Int_t *[fNADC];
fZSM = new Int_t *[fNADC];
fZSM1Dim = new Int_t [fNADC];
fGainCounterA = new UInt_t[fNADC];
fGainCounterB = new UInt_t[fNADC];
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
fADCR[iadc] = new Int_t[fNTimeBin];
fADCF[iadc] = new Int_t[fNTimeBin];
fZSM [iadc] = new Int_t[fNTimeBin];
}
// filter registers
fPedAcc = new UInt_t[fNADC]; // accumulator for pedestal filter
fTailAmplLong = new UShort_t[fNADC];
fTailAmplShort = new UShort_t[fNADC];
// tracklet calculation
fFitReg = new FitReg_t[fNADC];
fTrackletArray = new TClonesArray("AliTRDtrackletMCM", fMaxTracklets);
fMCMT = new UInt_t[fMaxTracklets];
}
fInitialized = kTRUE;
Reset();
}
void AliTRDmcmSim::Reset()
{
// Resets the data values and internal filter registers
// by re-initialising them
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fADCR[iadc][it] = 0;
fADCF[iadc][it] = 0;
fZSM [iadc][it] = 1; // Default unread = 1
}
fZSM1Dim[iadc] = 1; // Default unread = 1
fGainCounterA[iadc] = 0;
fGainCounterB[iadc] = 0;
}
for(Int_t i = 0; i < fMaxTracklets; i++) {
fMCMT[i] = 0;
}
FilterPedestalInit();
FilterGainInit();
FilterTailInit(fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP)); //??? not really correct if gain filter is active
}
void AliTRDmcmSim::SetNTimebins(Int_t ntimebins)
{
fNTimeBin = ntimebins;
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
delete fADCR[iadc];
delete fADCF[iadc];
delete fZSM[iadc];
fADCR[iadc] = new Int_t[fNTimeBin];
fADCF[iadc] = new Int_t[fNTimeBin];
fZSM [iadc] = new Int_t[fNTimeBin];
}
}
Bool_t AliTRDmcmSim::LoadMCM(AliRunLoader* const runloader, Int_t det, Int_t rob, Int_t mcm)
{
// loads the ADC data as obtained from the digitsManager for the specified MCM
Init(det, rob, mcm);
if (!runloader) {
AliError("No Runloader given");
return kFALSE;
}
AliLoader *trdLoader = runloader->GetLoader("TRDLoader");
if (!trdLoader) {
AliError("Could not get TRDLoader");
return kFALSE;
}
Bool_t retval = kTRUE;
trdLoader->LoadDigits();
fDigitsManager = 0x0;
AliTRDdigitsManager *digMgr = new AliTRDdigitsManager();
digMgr->SetSDigits(0);
digMgr->CreateArrays();
digMgr->ReadDigits(trdLoader->TreeD());
AliTRDarrayADC *digits = (AliTRDarrayADC*) digMgr->GetDigits(det);
if (digits->HasData()) {
digits->Expand();
if (fNTimeBin != digits->GetNtime())
SetNTimebins(digits->GetNtime());
Int_t padrow = fFeeParam->GetPadRowFromMCM(rob, mcm);
Int_t padcol = 0;
for (Int_t ch = 0; ch < fNADC; ch++) {
padcol = GetCol(ch);
fZSM1Dim[ch] = 1;
if (padcol < 0) {
fZSM1Dim[ch] = 0;
for (Int_t tb = 0; tb < fNTimeBin; tb++) {
fADCR[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
}
else {
for (Int_t tb = 0; tb < fNTimeBin; tb++) {
if (digits->GetData(padrow,padcol, tb) < 0) {
fZSM1Dim[ch] = 0;
fADCR[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
else {
fADCR[ch][tb] = digits->GetData(padrow, padcol, tb) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
fADCF[ch][tb] = digits->GetData(padrow, padcol, tb) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
}
}
}
}
}
else
retval = kFALSE;
delete digMgr;
return retval;
}
void AliTRDmcmSim::NoiseTest(Int_t nsamples, Int_t mean, Int_t sigma, Int_t inputGain, Int_t inputTail)
{
// This function can be used to test the filters.
// It feeds nsamples of ADC values with a gaussian distribution specified by mean and sigma.
// The filter chain implemented here consists of:
// Pedestal -> Gain -> Tail
// With inputGain and inputTail the input to the gain and tail filter, respectively,
// can be chosen where
// 0: noise input
// 1: pedestal output
// 2: gain output
// The input has to be chosen from a stage before.
// The filter behaviour is controlled by the TRAP parameters from AliTRDtrapConfig in the
// same way as in normal simulation.
// The functions produces four histograms with the values at the different stages.
TH1F *h = new TH1F("noise", "Gaussian Noise;sample;ADC count",
nsamples, 0, nsamples);
TH1F *hfp = new TH1F("pedf", "Noise #rightarrow Pedestal filter;sample;ADC count", nsamples, 0, nsamples);
TH1F *hfg = new TH1F("pedg", "Pedestal #rightarrow Gain;sample;ADC count", nsamples, 0, nsamples);
TH1F *hft = new TH1F("pedt", "Gain #rightarrow Tail;sample;ADC count", nsamples, 0, nsamples);
h->SetStats(kFALSE);
hfp->SetStats(kFALSE);
hfg->SetStats(kFALSE);
hft->SetStats(kFALSE);
Int_t value; // ADC count with noise (10 bit)
Int_t valuep; // pedestal filter output (12 bit)
Int_t valueg; // gain filter output (12 bit)
Int_t valuet; // tail filter value (12 bit)
for (Int_t i = 0; i < nsamples; i++) {
value = (Int_t) gRandom->Gaus(mean, sigma); // generate noise with gaussian distribution
h->SetBinContent(i, value);
valuep = FilterPedestalNextSample(1, 0, ((Int_t) value) << 2);
if (inputGain == 0)
valueg = FilterGainNextSample(1, ((Int_t) value) << 2);
else
valueg = FilterGainNextSample(1, valuep);
if (inputTail == 0)
valuet = FilterTailNextSample(1, ((Int_t) value) << 2);
else if (inputTail == 1)
valuet = FilterTailNextSample(1, valuep);
else
valuet = FilterTailNextSample(1, valueg);
hfp->SetBinContent(i, valuep >> 2);
hfg->SetBinContent(i, valueg >> 2);
hft->SetBinContent(i, valuet >> 2);
}
TCanvas *c = new TCanvas;
c->Divide(2,2);
c->cd(1);
h->Draw();
c->cd(2);
hfp->Draw();
c->cd(3);
hfg->Draw();
c->cd(4);
hft->Draw();
}
Bool_t AliTRDmcmSim::CheckInitialized()
{
//
// Check whether object is initialized
//
if( ! fInitialized ) {
AliDebug(2, Form ("AliTRDmcmSim is not initialized but function other than Init() is called."));
}
return fInitialized;
}
void AliTRDmcmSim::Print(Option_t* const option) const
{
// Prints the data stored and/or calculated for this MCM.
// The output is controlled by option which can be a sequence of any of
// the following characters:
// R - prints raw ADC data
// F - prints filtered data
// H - prints detected hits
// T - prints found tracklets
// The later stages are only useful when the corresponding calculations
// have been performed.
printf("MCM %i on ROB %i in detector %i\n", fMcmPos, fRobPos, fDetector);
TString opt = option;
if (opt.Contains("R")) {
printf("Raw ADC data (10 bit):\n");
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iChannel = 0; iChannel < fNADC; iChannel++) {
printf("%5i", fADCR[iChannel][iTimeBin] >> fgkAddDigits);
}
printf("\n");
}
}
if (opt.Contains("F")) {
printf("Filtered data (12 bit):\n");
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iChannel = 0; iChannel < fNADC; iChannel++) {
printf("%5i", fADCF[iChannel][iTimeBin]);
}
printf("\n");
}
}
if (opt.Contains("H")) {
printf("Found %i hits:\n", fNHits);
for (Int_t iHit = 0; iHit < fNHits; iHit++) {
printf("Hit %3i in timebin %2i, ADC %2i has charge %3i and position %3i\n",
iHit, fHits[iHit].fTimebin, fHits[iHit].fChannel, fHits[iHit].fQtot, fHits[iHit].fYpos);
}
}
if (opt.Contains("T")) {
printf("Tracklets:\n");
for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntriesFast(); iTrkl++) {
printf("tracklet %i: 0x%08x\n", iTrkl, ((AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl])->GetTrackletWord());
}
}
}
void AliTRDmcmSim::Draw(Option_t* const option)
{
// Plots the data stored in a 2-dim. timebin vs. ADC channel plot.
// The option selects what data is plotted and can be a sequence of
// the following characters:
// R - plot raw data (default)
// F - plot filtered data (meaningless if R is specified)
// In addition to the ADC values:
// H - plot hits
// T - plot tracklets
TString opt = option;
TH2F *hist = new TH2F("mcmdata", Form("Data of MCM %i on ROB %i in detector %i", \
fMcmPos, fRobPos, fDetector), \
fNADC, -0.5, fNADC-.5, fNTimeBin, -.5, fNTimeBin-.5);
hist->GetXaxis()->SetTitle("ADC Channel");
hist->GetYaxis()->SetTitle("Timebin");
hist->SetStats(kFALSE);
if (opt.Contains("R")) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
hist->SetBinContent(iAdc+1, iTimeBin+1, fADCR[iAdc][iTimeBin] >> fgkAddDigits);
}
}
}
else {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
hist->SetBinContent(iAdc+1, iTimeBin+1, fADCF[iAdc][iTimeBin] >> fgkAddDigits);
}
}
}
hist->Draw("colz");
if (opt.Contains("H")) {
TGraph *grHits = new TGraph();
for (Int_t iHit = 0; iHit < fNHits; iHit++) {
grHits->SetPoint(iHit,
fHits[iHit].fChannel + 1 + fHits[iHit].fYpos/256.,
fHits[iHit].fTimebin);
}
grHits->Draw("*");
}
if (opt.Contains("T")) {
TLine *trklLines = new TLine[4];
for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntries(); iTrkl++) {
AliTRDpadPlane *pp = fGeo->GetPadPlane(fDetector);
AliTRDtrackletMCM *trkl = (AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl];
Float_t offset = pp->GetColPos(fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 19)) + 19 * pp->GetWidthIPad();
trklLines[iTrkl].SetX1((offset - trkl->GetY()) / pp->GetWidthIPad());
trklLines[iTrkl].SetY1(0);
trklLines[iTrkl].SetX2((offset - (trkl->GetY() + ((Float_t) trkl->GetdY())*140e-4)) / pp->GetWidthIPad());
trklLines[iTrkl].SetY2(fNTimeBin - 1);
trklLines[iTrkl].SetLineColor(2);
trklLines[iTrkl].SetLineWidth(2);
printf("Tracklet %i: y = %f, dy = %f, offset = %f\n", iTrkl, trkl->GetY(), (trkl->GetdY() * 140e-4), offset);
trklLines[iTrkl].Draw();
}
}
}
void AliTRDmcmSim::SetData( Int_t iadc, Int_t* const adc )
{
//
// Store ADC data into array of raw data
//
if( !CheckInitialized() ) return;
if( iadc < 0 || iadc >= fNADC ) {
//Log (Form ("Error: iadc is out of range (should be 0 to %d).", fNADC-1));
return;
}
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fADCR[iadc][it] = (Int_t) (adc[it]) << fgkAddDigits;
fADCF[iadc][it] = (Int_t) (adc[it]) << fgkAddDigits;
}
}
void AliTRDmcmSim::SetData( Int_t iadc, Int_t it, Int_t adc )
{
//
// Store ADC data into array of raw data
//
if( !CheckInitialized() ) return;
if( iadc < 0 || iadc >= fNADC ) {
//Log (Form ("Error: iadc is out of range (should be 0 to %d).", fNADC-1));
return;
}
fADCR[iadc][it] = adc << fgkAddDigits;
fADCF[iadc][it] = adc << fgkAddDigits;
}
void AliTRDmcmSim::SetData(AliTRDarrayADC* const adcArray, AliTRDdigitsManager *digitsManager)
{
// Set the ADC data from an AliTRDarrayADC
if (!fInitialized) {
AliError("Called uninitialized! Nothing done!");
return;
}
fDigitsManager = digitsManager;
if (fNTimeBin != adcArray->GetNtime())
SetNTimebins(adcArray->GetNtime());
Int_t offset = (fMcmPos % 4) * 21 + (fRobPos % 2) * 84;
// Int_t firstAdc = 0;
// Int_t lastAdc = fNADC-1;
//
// while (GetCol(firstAdc) < 0) {
// for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
// fADCR[firstAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// fADCF[firstAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// }
// firstAdc++;
// }
//
// while (GetCol(lastAdc) < 0) {
// for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
// fADCR[lastAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// fADCF[lastAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// }
// lastAdc--;
// }
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
Int_t value = adcArray->GetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin);
if (value < 0 || (20-iAdc + offset < 1) || (20-iAdc + offset > 165)) {
fADCR[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
else {
fADCR[iAdc][iTimeBin] = adcArray->GetData(GetRow(), GetCol(iAdc), iTimeBin) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
fADCF[iAdc][iTimeBin] = adcArray->GetData(GetRow(), GetCol(iAdc), iTimeBin) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
}
}
}
}
void AliTRDmcmSim::SetDataPedestal( Int_t iadc )
{
//
// Store ADC data into array of raw data
//
if( !CheckInitialized() ) return;
if( iadc < 0 || iadc >= fNADC ) {
return;
}
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fADCR[iadc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[iadc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
}
Int_t AliTRDmcmSim::GetCol( Int_t iadc )
{
//
// Return column id of the pad for the given ADC channel
//
if( !CheckInitialized() )
return -1;
Int_t col = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, iadc);
if (col < 0 || col >= fFeeParam->GetNcol())
return -1;
else
return col;
}
Int_t AliTRDmcmSim::ProduceRawStream( UInt_t *buf, Int_t maxSize, UInt_t iEv)
{
//
// Produce raw data stream from this MCM and put in buf
// Returns number of words filled, or negative value
// with -1 * number of overflowed words
//
UInt_t x;
Int_t nw = 0; // Number of written words
Int_t of = 0; // Number of overflowed words
Int_t rawVer = fFeeParam->GetRAWversion();
Int_t **adc;
Int_t nActiveADC = 0; // number of activated ADC bits in a word
if( !CheckInitialized() ) return 0;
if( fFeeParam->GetRAWstoreRaw() ) {
adc = fADCR;
} else {
adc = fADCF;
}
// Produce MCM header
x = (1<<31) | (fRobPos << 28) | (fMcmPos << 24) | ((iEv % 0x100000) << 4) | 0xC;
if (nw < maxSize) {
buf[nw++] = x;
//printf("\nMCM header: %X ",x);
}
else {
of++;
}
// Produce ADC mask : nncc cccm mmmm mmmm mmmm mmmm mmmm 1100
// n : unused , c : ADC count, m : selected ADCs
if( rawVer >= 3 ) {
x = 0;
for( Int_t iAdc = 0 ; iAdc < fNADC ; iAdc++ ) {
if( fZSM1Dim[iAdc] == 0 ) { // 0 means not suppressed
x = x | (1 << (iAdc+4) ); // last 4 digit reserved for 1100=0xc
nActiveADC++; // number of 1 in mmm....m
}
}
x = x | (1 << 30) | ( ( 0x3FFFFFFC ) & (~(nActiveADC) << 25) ) | 0xC; // nn = 01, ccccc are inverted, 0xc=1100
//printf("nActiveADC=%d=%08X, inverted=%X ",nActiveADC,nActiveADC,x );
if (nw < maxSize) {
buf[nw++] = x;
//printf("ADC mask: %X nMask=%d ADC data: ",x,nActiveADC);
}
else {
of++;
}
}
// Produce ADC data. 3 timebins are packed into one 32 bits word
// In this version, different ADC channel will NOT share the same word
UInt_t aa=0, a1=0, a2=0, a3=0;
for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
if( rawVer>= 3 && fZSM1Dim[iAdc] != 0 ) continue; // Zero Suppression, 0 means not suppressed
aa = !(iAdc & 1) + 2;
for (Int_t iT = 0; iT < fNTimeBin; iT+=3 ) {
a1 = ((iT ) < fNTimeBin ) ? adc[iAdc][iT ] >> fgkAddDigits : 0;
a2 = ((iT + 1) < fNTimeBin ) ? adc[iAdc][iT+1] >> fgkAddDigits : 0;
a3 = ((iT + 2) < fNTimeBin ) ? adc[iAdc][iT+2] >> fgkAddDigits : 0;
x = (a3 << 22) | (a2 << 12) | (a1 << 2) | aa;
if (nw < maxSize) {
buf[nw++] = x;
//printf("%08X ",x);
}
else {
of++;
}
}
}
if( of != 0 ) return -of; else return nw;
}
Int_t AliTRDmcmSim::ProduceTrackletStream( UInt_t *buf, Int_t maxSize )
{
//
// Produce tracklet data stream from this MCM and put in buf
// Returns number of words filled, or negative value
// with -1 * number of overflowed words
//
Int_t nw = 0; // Number of written words
Int_t of = 0; // Number of overflowed words
if( !CheckInitialized() ) return 0;
// Produce tracklet data. A maximum of four 32 Bit words will be written per MCM
// fMCMT is filled continuously until no more tracklet words available
for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) {
if (nw < maxSize)
buf[nw++] = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet])->GetTrackletWord();
else
of++;
}
if( of != 0 ) return -of; else return nw;
}
void AliTRDmcmSim::Filter()
{
//
// Filter the raw ADC values. The active filter stages and their
// parameters are taken from AliTRDtrapConfig.
// The raw data is stored separate from the filtered data. Thus,
// it is possible to run the filters on a set of raw values
// sequentially for parameter tuning.
//
if( !CheckInitialized() ) {
AliError("got called before initialization! Nothing done!");
return;
}
// Apply filters sequentially. Bypass is handled by filters
// since counters and internal registers may be updated even
// if the filter is bypassed.
// The first filter takes the data from fADCR and
// outputs to fADCF.
// Non-linearity filter not implemented.
FilterPedestal();
FilterGain();
FilterTail();
// Crosstalk filter not implemented.
}
void AliTRDmcmSim::FilterPedestalInit()
{
// Initializes the pedestal filter assuming that the input has
// been constant for a long time (compared to the time constant).
// UShort_t fpnp = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); // 0..511 -> 0..127.75, pedestal at the output
UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest
UShort_t shifts[4] = {11, 14, 17, 21}; //??? where to take shifts from?
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++)
fPedAcc[iAdc] = (fSimParam->GetADCbaseline() << 2) * (1<<shifts[fptc]);
}
UShort_t AliTRDmcmSim::FilterPedestalNextSample(Int_t adc, Int_t timebin, UShort_t value)
{
// Returns the output of the pedestal filter given the input value.
// The output depends on the internal registers and, thus, the
// history of the filter.
UShort_t fpnp = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); // 0..511 -> 0..127.75, pedestal at the output
UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest
UShort_t fpby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPBY); // 0..1 the bypass, active low
UShort_t shifts[4] = {11, 14, 17, 21}; //??? where to come from
UShort_t accumulatorShifted;
Int_t correction;
UShort_t inpAdd;
inpAdd = value + fpnp;
if (fpby == 0) //??? before or after update of accumulator
return value;
accumulatorShifted = (fPedAcc[adc] >> shifts[fptc]) & 0x3FF; // 10 bits
if (timebin == 0) // the accumulator is disabled in the drift time
{
correction = (value & 0x3FF) - accumulatorShifted;
fPedAcc[adc] = (fPedAcc[adc] + correction) & 0x7FFFFFFF; // 31 bits
}
if (inpAdd <= accumulatorShifted)
return 0;
else
{
inpAdd = inpAdd - accumulatorShifted;
if (inpAdd > 0xFFF)
return 0xFFF;
else
return inpAdd;
}
}
void AliTRDmcmSim::FilterPedestal()
{
//
// Apply pedestal filter
//
// As the first filter in the chain it reads data from fADCR
// and outputs to fADCF.
// It has only an effect if previous samples have been fed to
// find the pedestal. Currently, the simulation assumes that
// the input has been stable for a sufficiently long time.
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
fADCF[iAdc][iTimeBin] = FilterPedestalNextSample(iAdc, iTimeBin, fADCR[iAdc][iTimeBin]);
}
}
}
void AliTRDmcmSim::FilterGainInit()
{
// Initializes the gain filter. In this case, only threshold
// counters are reset.
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
// these are counters which in hardware continue
// until maximum or reset
fGainCounterA[iAdc] = 0;
fGainCounterB[iAdc] = 0;
}
}
UShort_t AliTRDmcmSim::FilterGainNextSample(Int_t adc, UShort_t value)
{
// Apply the gain filter to the given value.
// BEGIN_LATEX O_{i}(t) = #gamma_{i} * I_{i}(t) + a_{i} END_LATEX
// The output depends on the internal registers and, thus, the
// history of the filter.
UShort_t fgby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGBY); // bypass, active low
UShort_t fgf = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGF0 + adc)); // 0x700 + (0 & 0x1ff);
UShort_t fga = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGA0 + adc)); // 40;
UShort_t fgta = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTA); // 20;
UShort_t fgtb = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTB); // 2060;
UInt_t tmp;
value &= 0xFFF;
tmp = (value * fgf) >> 11;
if (tmp > 0xFFF) tmp = 0xFFF;
if (fgby == 1)
value = AddUintClipping(tmp, fga, 12);
// Update threshold counters
// not really useful as they are cleared with every new event
if ((fGainCounterA[adc] == 0x3FFFFFF) || (fGainCounterB[adc] == 0x3FFFFFF))
{
if (value >= fgtb)
fGainCounterB[adc]++;
else if (value >= fgta)
fGainCounterA[adc]++;
}
return value;
}
void AliTRDmcmSim::FilterGain()
{
// Read data from fADCF and apply gain filter.
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
fADCF[iAdc][iTimeBin] = FilterGainNextSample(iAdc, fADCF[iAdc][iTimeBin]);
}
}
}
void AliTRDmcmSim::FilterTailInit(Int_t baseline)
{
// Initializes the tail filter assuming that the input has
// been at the baseline value (configured by FTFP) for a
// sufficiently long time.
// exponents and weight calculated from configuration
UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component
UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier
UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier
Float_t lambdaL = lambdaLong * 1.0 / (1 << 11);
Float_t lambdaS = lambdaShort * 1.0 / (1 << 11);
Float_t alphaL = alphaLong * 1.0 / (1 << 11);
Float_t qup, qdn;
qup = (1 - lambdaL) * (1 - lambdaS);
qdn = 1 - lambdaS * alphaL - lambdaL * (1 - alphaL);
Float_t kdc = qup/qdn;
Float_t kt, ql, qs;
UShort_t aout;
kt = kdc * baseline;
aout = baseline - (UShort_t) kt;
ql = lambdaL * (1 - lambdaS) * alphaL;
qs = lambdaS * (1 - lambdaL) * (1 - alphaL);
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
fTailAmplLong[iAdc] = (UShort_t) (aout * ql / (ql + qs));
fTailAmplShort[iAdc] = (UShort_t) (aout * qs / (ql + qs));
}
}
UShort_t AliTRDmcmSim::FilterTailNextSample(Int_t adc, UShort_t value)
{
// Returns the output of the tail filter for the given input value.
// The output depends on the internal registers and, thus, the
// history of the filter.
// exponents and weight calculated from configuration
UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component
UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier
UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier
Float_t lambdaL = lambdaLong * 1.0 / (1 << 11);
Float_t lambdaS = lambdaShort * 1.0 / (1 << 11);
Float_t alphaL = alphaLong * 1.0 / (1 << 11);
Float_t qup, qdn;
qup = (1 - lambdaL) * (1 - lambdaS);
qdn = 1 - lambdaS * alphaL - lambdaL * (1 - alphaL);
// Float_t kdc = qup/qdn;
UInt_t aDiff;
UInt_t alInpv;
UShort_t aQ;
UInt_t tmp;
UShort_t inpVolt = value & 0xFFF; // 12 bits
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTBY) == 0) // bypass mode, active low
return value;
else
{
// add the present generator outputs
aQ = AddUintClipping(fTailAmplLong[adc], fTailAmplShort[adc], 12);
// calculate the difference between the input the generated signal
if (inpVolt > aQ)
aDiff = inpVolt - aQ;
else
aDiff = 0;
// the inputs to the two generators, weighted
alInpv = (aDiff * alphaLong) >> 11;
// the new values of the registers, used next time
// long component
tmp = AddUintClipping(fTailAmplLong[adc], alInpv, 12);
tmp = (tmp * lambdaLong) >> 11;
fTailAmplLong[adc] = tmp & 0xFFF;
// short component
tmp = AddUintClipping(fTailAmplShort[adc], aDiff - alInpv, 12);
tmp = (tmp * lambdaShort) >> 11;
fTailAmplShort[adc] = tmp & 0xFFF;
// the output of the filter
return aDiff;
}
}
void AliTRDmcmSim::FilterTail()
{
// Apply tail filter
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
fADCF[iAdc][iTimeBin] = FilterTailNextSample(iAdc, fADCF[iAdc][iTimeBin]);
}
}
}
void AliTRDmcmSim::ZSMapping()
{
//
// Zero Suppression Mapping implemented in TRAP chip
//
// See detail TRAP manual "Data Indication" section:
// http://www.kip.uni-heidelberg.de/ti/TRD/doc/trap/TRAP-UserManual.pdf
//
//??? values should come from TRAPconfig
Int_t eBIS = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIS); // TRAP default = 0x4 (Tis=4)
Int_t eBIT = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIT); // TRAP default = 0x28 (Tit=40)
Int_t eBIL = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIL); // TRAP default = 0xf0
// (lookup table accept (I2,I1,I0)=(111)
// or (110) or (101) or (100))
Int_t eBIN = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIN); // TRAP default = 1 (no neighbor sensitivity)
Int_t ep = 0; // fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); //??? really subtracted here
Int_t **adc = fADCF;
if( !CheckInitialized() ) {
AliError("got called uninitialized! Nothing done!");
return;
}
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
for( Int_t iadc = 1 ; iadc < fNADC-1; iadc++ ) {
// Get ADC data currently in filter buffer
Int_t ap = adc[iadc-1][it] - ep; // previous
Int_t ac = adc[iadc ][it] - ep; // current
Int_t an = adc[iadc+1][it] - ep; // next
// evaluate three conditions
Int_t i0 = ( ac >= ap && ac >= an ) ? 0 : 1; // peak center detection
Int_t i1 = ( ap + ac + an > eBIT ) ? 0 : 1; // cluster
Int_t i2 = ( ac > eBIS ) ? 0 : 1; // absolute large peak
Int_t i = i2 * 4 + i1 * 2 + i0; // Bit position in lookup table
Int_t d = (eBIL >> i) & 1; // Looking up (here d=0 means true
// and d=1 means false according to TRAP manual)
fZSM[iadc][it] &= d;
if( eBIN == 0 ) { // turn on neighboring ADCs
fZSM[iadc-1][it] &= d;
fZSM[iadc+1][it] &= d;
}
}
}
// do 1 dim projection
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fZSM1Dim[iadc] &= fZSM[iadc][it];
}
}
}
void AliTRDmcmSim::DumpData( const char * const f, const char * const target )
{
//
// Dump data stored (for debugging).
// target should contain one or multiple of the following characters
// R for raw data
// F for filtered data
// Z for zero suppression map
// S Raw dat astream
// other characters are simply ignored
//
UInt_t tempbuf[1024];
if( !CheckInitialized() ) return;
std::ofstream of( f, std::ios::out | std::ios::app );
of << Form("AliTRDmcmSim::DumpData det=%03d sm=%02d stack=%d layer=%d rob=%d mcm=%02d\n",
fDetector, fGeo->GetSector(fDetector), fGeo->GetStack(fDetector),
fGeo->GetSector(fDetector), fRobPos, fMcmPos );
for( Int_t t=0 ; target[t] != 0 ; t++ ) {
switch( target[t] ) {
case 'R' :
case 'r' :
of << Form("fADCR (raw ADC data)\n");
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
of << Form(" ADC %02d: ", iadc);
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
of << Form("% 4d", fADCR[iadc][it]);
}
of << Form("\n");
}
break;
case 'F' :
case 'f' :
of << Form("fADCF (filtered ADC data)\n");
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
of << Form(" ADC %02d: ", iadc);
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
of << Form("% 4d", fADCF[iadc][it]);
}
of << Form("\n");
}
break;
case 'Z' :
case 'z' :
of << Form("fZSM and fZSM1Dim (Zero Suppression Map)\n");
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
of << Form(" ADC %02d: ", iadc);
if( fZSM1Dim[iadc] == 0 ) { of << " R " ; } else { of << " . "; } // R:read .:suppressed
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
if( fZSM[iadc][it] == 0 ) { of << " R"; } else { of << " ."; } // R:read .:suppressed
}
of << Form("\n");
}
break;
case 'S' :
case 's' :
Int_t s = ProduceRawStream( tempbuf, 1024 );
of << Form("Stream for Raw Simulation size=%d rawver=%d\n", s, fFeeParam->GetRAWversion());
of << Form(" address data\n");
for( Int_t i = 0 ; i < s ; i++ ) {
of << Form(" %04x %08x\n", i, tempbuf[i]);
}
}
}
}
void AliTRDmcmSim::AddHitToFitreg(Int_t adc, UShort_t timebin, UShort_t qtot, Short_t ypos, Int_t label)
{
// Add the given hit to the fit register which is lateron used for
// the tracklet calculation.
// In addition to the fit sums in the fit register MC information
// is stored.
if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0)) &&
(timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0)))
fFitReg[adc].fQ0 += qtot;
if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1)) &&
(timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1)))
fFitReg[adc].fQ1 += qtot;
if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS) ) &&
(timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE)))
{
fFitReg[adc].fSumX += timebin;
fFitReg[adc].fSumX2 += timebin*timebin;
fFitReg[adc].fNhits++;
fFitReg[adc].fSumY += ypos;
fFitReg[adc].fSumY2 += ypos*ypos;
fFitReg[adc].fSumXY += timebin*ypos;
}
// register hits (MC info)
fHits[fNHits].fChannel = adc;
fHits[fNHits].fQtot = qtot;
fHits[fNHits].fYpos = ypos;
fHits[fNHits].fTimebin = timebin;
fHits[fNHits].fLabel = label;
fNHits++;
}
void AliTRDmcmSim::CalcFitreg()
{
// Preprocessing.
// Detect the hits and fill the fit registers.
// Requires 12-bit data from fADCF which means Filter()
// has to be called before even if all filters are bypassed.
//???
// TRAP parameters:
const UShort_t lutPos[128] = { // move later to some other file
0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15,
16, 16, 16, 17, 17, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 26, 26, 26, 26,
27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 27, 27, 27, 27, 26,
26, 26, 26, 25, 25, 25, 24, 24, 23, 23, 22, 22, 21, 21, 20, 20, 19, 18, 18, 17, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 7};
//??? to be clarified:
UInt_t adcMask = 0xffffffff;
UShort_t timebin, adcch, adcLeft, adcCentral, adcRight, hitQual, timebin1, timebin2, qtotTemp;
Short_t ypos, fromLeft, fromRight, found;
UShort_t qTotal[19]; // the last is dummy
UShort_t marked[6], qMarked[6], worse1, worse2;
timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS);
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0)
< timebin1)
timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0);
timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE);
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1)
> timebin2)
timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1);
// reset the fit registers
fNHits = 0;
for (adcch = 0; adcch < fNADC-2; adcch++) // due to border channels
{
fFitReg[adcch].fNhits = 0;
fFitReg[adcch].fQ0 = 0;
fFitReg[adcch].fQ1 = 0;
fFitReg[adcch].fSumX = 0;
fFitReg[adcch].fSumY = 0;
fFitReg[adcch].fSumX2 = 0;
fFitReg[adcch].fSumY2 = 0;
fFitReg[adcch].fSumXY = 0;
}
for (timebin = timebin1; timebin < timebin2; timebin++)
{
// first find the hit candidates and store the total cluster charge in qTotal array
// in case of not hit store 0 there.
for (adcch = 0; adcch < fNADC-2; adcch++) {
if ( ( (adcMask >> adcch) & 7) == 7) //??? all 3 channels are present in case of ZS
{
adcLeft = fADCF[adcch ][timebin];
adcCentral = fADCF[adcch+1][timebin];
adcRight = fADCF[adcch+2][timebin];
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVBY) == 1)
hitQual = ( (adcLeft * adcRight) <
(fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVT) * adcCentral) );
else
hitQual = 1;
// The accumulated charge is with the pedestal!!!
qtotTemp = adcLeft + adcCentral + adcRight;
if ( (hitQual) &&
(qtotTemp >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT)) &&
(adcLeft <= adcCentral) &&
(adcCentral > adcRight) )
qTotal[adcch] = qtotTemp;
else
qTotal[adcch] = 0;
}
else
qTotal[adcch] = 0; //jkl
AliDebug(10,Form("ch %2d qTotal %5d",adcch, qTotal[adcch]));
}
fromLeft = -1;
adcch = 0;
found = 0;
marked[4] = 19; // invalid channel
marked[5] = 19; // invalid channel
qTotal[19] = 0;
while ((adcch < 16) && (found < 3))
{
if (qTotal[adcch] > 0)
{
fromLeft = adcch;
marked[2*found+1]=adcch;
found++;
}
adcch++;
}
fromRight = -1;
adcch = 18;
found = 0;
while ((adcch > 2) && (found < 3))
{
if (qTotal[adcch] > 0)
{
marked[2*found]=adcch;
found++;
fromRight = adcch;
}
adcch--;
}
AliDebug(10,Form("Fromleft=%d, Fromright=%d",fromLeft, fromRight));
// here mask the hit candidates in the middle, if any
if ((fromLeft >= 0) && (fromRight >= 0) && (fromLeft < fromRight))
for (adcch = fromLeft+1; adcch < fromRight; adcch++)
qTotal[adcch] = 0;
found = 0;
for (adcch = 0; adcch < 19; adcch++)
if (qTotal[adcch] > 0) found++;
// NOT READY
if (found > 4) // sorting like in the TRAP in case of 5 or 6 candidates!
{
if (marked[4] == marked[5]) marked[5] = 19;
for (found=0; found<6; found++)
{
qMarked[found] = qTotal[marked[found]] >> 4;
AliDebug(10,Form("ch_%d qTotal %d qTotals %d",marked[found],qTotal[marked[found]],qMarked[found]));
}
Sort6To2Worst(marked[0], marked[3], marked[4], marked[1], marked[2], marked[5],
qMarked[0],
qMarked[3],
qMarked[4],
qMarked[1],
qMarked[2],
qMarked[5],
&worse1, &worse2);
// Now mask the two channels with the smallest charge
if (worse1 < 19)
{
qTotal[worse1] = 0;
AliDebug(10,Form("Kill ch %d\n",worse1));
}
if (worse2 < 19)
{
qTotal[worse2] = 0;
AliDebug(10,Form("Kill ch %d\n",worse2));
}
}
for (adcch = 0; adcch < 19; adcch++) {
if (qTotal[adcch] > 0) // the channel is marked for processing
{
adcLeft = fADCF[adcch ][timebin];
adcCentral = fADCF[adcch+1][timebin];
adcRight = fADCF[adcch+2][timebin];
// hit detected, in TRAP we have 4 units and a hit-selection, here we proceed all channels!
// subtract the pedestal TPFP, clipping instead of wrapping
Int_t regTPFP = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP);
AliDebug(10, Form("Hit found, time=%d, adcch=%d/%d/%d, adc values=%d/%d/%d, regTPFP=%d, TPHT=%d\n",
timebin, adcch, adcch+1, adcch+2, adcLeft, adcCentral, adcRight, regTPFP,
fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT)));
if (adcLeft < regTPFP) adcLeft = 0; else adcLeft -= regTPFP;
if (adcCentral < regTPFP) adcCentral = 0; else adcCentral -= regTPFP;
if (adcRight < regTPFP) adcRight = 0; else adcRight -= regTPFP;
// Calculate the center of gravity
// checking for adcCentral != 0 (in case of "bad" configuration)
if (adcCentral == 0)
continue;
ypos = 128*(adcLeft - adcRight) / adcCentral;
if (ypos < 0) ypos = -ypos;
// make the correction using the LUT
ypos = ypos + lutPos[ypos & 0x7F];
if (adcLeft > adcRight) ypos = -ypos;
// label calculation
Int_t mcLabel = -1;
if (fDigitsManager) {
Int_t label[9] = { 0 }; // up to 9 different labels possible
Int_t count[9] = { 0 };
Int_t maxIdx = -1;
Int_t maxCount = 0;
Int_t nLabels = 0;
Int_t padcol[3];
padcol[0] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch);
padcol[1] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+1);
padcol[2] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+2);
Int_t padrow = fFeeParam->GetPadRowFromMCM(fRobPos, fMcmPos);
for (Int_t iDict = 0; iDict < 3; iDict++) {
if (!fDigitsManager->UsesDictionaries() || fDigitsManager->GetDictionary(fDetector, iDict) == 0) {
AliError("Cannot get dictionary");
continue;
}
AliTRDarrayDictionary *dict = (AliTRDarrayDictionary*) fDigitsManager->GetDictionary(fDetector, iDict);
if (dict->GetDim() == 0) {
AliError(Form("Dictionary %i of det. %i has dim. 0", fDetector, iDict));
continue;
}
dict->Expand();
for (Int_t iPad = 0; iPad < 3; iPad++) {
if (padcol[iPad] < 0)
continue;
Int_t currLabel = dict->GetData(padrow, padcol[iPad], timebin); //fDigitsManager->GetTrack(iDict, padrow, padcol, timebin, fDetector);
AliDebug(10, Form("Read label: %4i for det: %3i, row: %i, col: %i, tb: %i\n", currLabel, fDetector, padrow, padcol[iPad], timebin));
for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) {
if (currLabel == label[iLabel]) {
count[iLabel]++;
if (count[iLabel] > maxCount) {
maxCount = count[iLabel];
maxIdx = iLabel;
}
currLabel = 0;
break;
}
}
if (currLabel > 0) {
label[nLabels++] = currLabel;
}
}
}
if (maxIdx >= 0)
mcLabel = label[maxIdx];
}
// add the hit to the fitregister
AddHitToFitreg(adcch, timebin, qTotal[adcch], ypos, mcLabel);
}
}
}
}
void AliTRDmcmSim::TrackletSelection()
{
// Select up to 4 tracklet candidates from the fit registers
// and assign them to the CPUs.
UShort_t adcIdx, i, j, ntracks, tmp;
UShort_t trackletCand[18][2]; // store the adcch[0] and number of hits[1] for all tracklet candidates
ntracks = 0;
for (adcIdx = 0; adcIdx < 18; adcIdx++) // ADCs
if ( (fFitReg[adcIdx].fNhits
>= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCL)) &&
(fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits
>= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCT)))
{
trackletCand[ntracks][0] = adcIdx;
trackletCand[ntracks][1] = fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits;
AliDebug(10,Form("%d %2d %4d\n", ntracks, trackletCand[ntracks][0], trackletCand[ntracks][1]));
ntracks++;
};
for (i=0; i<ntracks;i++)
AliDebug(10,Form("%d %d %d\n",i,trackletCand[i][0], trackletCand[i][1]));
if (ntracks > 4)
{
// primitive sorting according to the number of hits
for (j = 0; j < (ntracks-1); j++)
{
for (i = j+1; i < ntracks; i++)
{
if ( (trackletCand[j][1] < trackletCand[i][1]) ||
( (trackletCand[j][1] == trackletCand[i][1]) && (trackletCand[j][0] < trackletCand[i][0]) ) )
{
// swap j & i
tmp = trackletCand[j][1];
trackletCand[j][1] = trackletCand[i][1];
trackletCand[i][1] = tmp;
tmp = trackletCand[j][0];
trackletCand[j][0] = trackletCand[i][0];
trackletCand[i][0] = tmp;
}
}
}
ntracks = 4; // cut the rest, 4 is the max
}
// else is not necessary to sort
// now sort, so that the first tracklet going to CPU0 corresponds to the highest adc channel - as in the TRAP
for (j = 0; j < (ntracks-1); j++)
{
for (i = j+1; i < ntracks; i++)
{
if (trackletCand[j][0] < trackletCand[i][0])
{
// swap j & i
tmp = trackletCand[j][1];
trackletCand[j][1] = trackletCand[i][1];
trackletCand[i][1] = tmp;
tmp = trackletCand[j][0];
trackletCand[j][0] = trackletCand[i][0];
trackletCand[i][0] = tmp;
}
}
}
for (i = 0; i < ntracks; i++) // CPUs with tracklets.
fFitPtr[i] = trackletCand[i][0]; // pointer to the left channel with tracklet for CPU[i]
for (i = ntracks; i < 4; i++) // CPUs without tracklets
fFitPtr[i] = 31; // pointer to the left channel with tracklet for CPU[i] = 31 (invalid)
AliDebug(10,Form("found %i tracklet candidates\n", ntracks));
for (i = 0; i < 4; i++)
AliDebug(10,Form("fitPtr[%i]: %i\n", i, fFitPtr[i]));
}
void AliTRDmcmSim::FitTracklet()
{
// Perform the actual tracklet fit based on the fit sums
// which have been filled in the fit registers.
// parameters in fitred.asm (fit program)
Int_t decPlaces = 5;
Int_t rndAdd = 0;
if (decPlaces > 1)
rndAdd = (1 << (decPlaces-1)) + 1;
else if (decPlaces == 1)
rndAdd = 1;
Int_t ndriftDp = 5; // decimal places for drift time
Long64_t shift = ((Long64_t) 1 << 32);
// calculated in fitred.asm
Int_t padrow = ((fRobPos >> 1) << 2) | (fMcmPos >> 2);
Int_t yoffs = (((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) -
((18*4*2 - 18*2 - 1) << 7);
yoffs = yoffs << decPlaces; // holds position of ADC channel 1
Int_t layer = fDetector % 6;
UInt_t scaleY = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 160.0e-4) * shift);
UInt_t scaleD = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 140.0e-4) * shift);
// previously taken from geometry:
// UInt_t scaleYold = (UInt_t) (shift * (pp->GetWidthIPad() / (256 * 160e-4)));
// UInt_t scaleDold = (UInt_t) (shift * (pp->GetWidthIPad() / (256 * 140e-4)));
// should come from trapConfig (DMEM)
AliTRDpadPlane *pp = fGeo->GetPadPlane(fDetector);
Float_t scaleSlope = (256 / pp->GetWidthIPad()) * (1 << decPlaces); // only used for calculation of corrections and cut
Int_t ndrift = 20 << ndriftDp; //??? value in simulation?
Int_t deflCorr = (Int_t) (TMath::Tan(fCommonParam->GetOmegaTau(fCal->GetVdriftAverage(fDetector))) * fGeo->CdrHght() * scaleSlope); // -370;
Int_t tiltCorr = (Int_t) (pp->GetRowPos(padrow) / fGeo->GetTime0(fDetector % 6) * fGeo->CdrHght() * scaleSlope *
TMath::Tan(pp->GetTiltingAngle() / 180. * TMath::Pi()));
// printf("vdrift av.: %f\n", fCal->GetVdriftAverage(fDetector));
// printf("chamber height: %f\n", fGeo->CdrHght());
// printf("omega tau: %f\n", fCommonParam->GetOmegaTau(fCal->GetVdriftAverage(fDetector)));
// printf("deflection correction: %i\n", deflCorr);
Float_t ptcut = 2.3;
AliMagF* fld = (AliMagF *) TGeoGlobalMagField::Instance()->GetField();
Double_t bz = 0;
if (fld) {
bz = 0.1 * fld->SolenoidField(); // kGauss -> Tesla
}
// printf("Bz: %f\n", bz);
Float_t x0 = fGeo->GetTime0(fDetector % 6);
Float_t y0 = pp->GetColPos(fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 10));
Float_t alphaMax = TMath::ASin( (TMath::Sqrt(TMath::Power(x0/100., 2) + TMath::Power(y0/100., 2)) *
0.3 * TMath::Abs(bz) ) / (2 * ptcut));
// printf("alpha max: %f\n", alphaMax * 180/TMath::Pi());
Int_t minslope = -1 * (Int_t) (fGeo->CdrHght() * TMath::Tan(TMath::ATan(y0/x0) + alphaMax) / 140.e-4);
Int_t maxslope = -1 * (Int_t) (fGeo->CdrHght() * TMath::Tan(TMath::ATan(y0/x0) - alphaMax) / 140.e-4);
// local variables for calculation
Long64_t mult, temp, denom; //???
UInt_t q0, q1, qTotal; // charges in the two windows and total charge
UShort_t nHits; // number of hits
Int_t slope, offset; // slope and offset of the tracklet
Int_t sumX, sumY, sumXY, sumX2; // fit sums from fit registers
//int32_t SumY2; // not used in the current TRAP program
FitReg_t *fit0, *fit1; // pointers to relevant fit registers
// const uint32_t OneDivN[32] = { // 2**31/N : exactly like in the TRAP, the simple division here gives the same result!
// 0x00000000, 0x80000000, 0x40000000, 0x2AAAAAA0, 0x20000000, 0x19999990, 0x15555550, 0x12492490,
// 0x10000000, 0x0E38E380, 0x0CCCCCC0, 0x0BA2E8B0, 0x0AAAAAA0, 0x09D89D80, 0x09249240, 0x08888880,
// 0x08000000, 0x07878780, 0x071C71C0, 0x06BCA1A0, 0x06666660, 0x06186180, 0x05D17450, 0x0590B210,
// 0x05555550, 0x051EB850, 0x04EC4EC0, 0x04BDA120, 0x04924920, 0x0469EE50, 0x04444440, 0x04210840};
for (Int_t cpu = 0; cpu < 4; cpu++) {
if (fFitPtr[cpu] == 31)
{
fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker();
}
else
{
fit0 = &fFitReg[fFitPtr[cpu] ];
fit1 = &fFitReg[fFitPtr[cpu]+1]; // next channel
mult = 1;
mult = mult << (32 + decPlaces);
mult = -mult;
// Merging
nHits = fit0->fNhits + fit1->fNhits; // number of hits
sumX = fit0->fSumX + fit1->fSumX;
sumX2 = fit0->fSumX2 + fit1->fSumX2;
denom = nHits*sumX2 - sumX*sumX;
mult = mult / denom; // exactly like in the TRAP program
q0 = fit0->fQ0 + fit1->fQ0;
q1 = fit0->fQ1 + fit1->fQ1;
sumY = fit0->fSumY + fit1->fSumY + 256*fit1->fNhits;
sumXY = fit0->fSumXY + fit1->fSumXY + 256*fit1->fSumX;
slope = nHits*sumXY - sumX * sumY;
AliDebug(5, Form("slope from fitreg: %i", slope));
offset = sumX2*sumY - sumX * sumXY;
temp = mult * slope;
slope = temp >> 32; // take the upper 32 bits
slope = -slope;
temp = mult * offset;
offset = temp >> 32; // take the upper 32 bits
offset = offset + yoffs;
AliDebug(5, Form("slope: %i, slope * ndrift: %i, deflCorr: %i, tiltCorr: %i", slope, slope * ndrift, deflCorr, tiltCorr));
slope = ((slope * ndrift) >> ndriftDp) + deflCorr + tiltCorr;
offset = offset - (fFitPtr[cpu] << (8 + decPlaces));
AliDebug(5, Form("Det: %3i, ROB: %i, MCM: %2i: deflection: %i, min: %i, max: %i", fDetector, fRobPos, fMcmPos, slope, minslope, maxslope));
temp = slope;
temp = temp * scaleD;
slope = (temp >> 32);
AliDebug(5, Form("slope after scaling: %i", slope));
temp = offset;
temp = temp * scaleY;
offset = (temp >> 32);
// rounding, like in the TRAP
slope = (slope + rndAdd) >> decPlaces;
AliDebug(5, Form("slope after shifting: %i", slope));
offset = (offset + rndAdd) >> decPlaces;
Bool_t rejected = kFALSE;
if ((slope < minslope) || (slope > maxslope))
rejected = kTRUE;
if (rejected && GetApplyCut())
{
fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker();
}
else
{
if (slope > 63 || slope < -64) { // wrapping in TRAP!
AliError(Form("Overflow in slope: %i, tracklet discarded!", slope));
fMCMT[cpu] = 0x10001000;
continue;
}
slope = slope & 0x7F; // 7 bit
if (offset > 0xfff || offset < -0xfff)
AliWarning("Overflow in offset");
offset = offset & 0x1FFF; // 13 bit
Float_t length = TMath::Sqrt(1 + (pp->GetRowPos(padrow) * pp->GetRowPos(padrow) +
(fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 10) * pp->GetWidthIPad() *
fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 10) * pp->GetWidthIPad())) /
(fGeo->GetTime0(fDetector % 6)*fGeo->GetTime0(fDetector % 6)));
// qTotal = (q1 / nHits) >> 1;
qTotal = GetPID(q0/length/fgChargeNorm, q1/length/fgChargeNorm);
if (qTotal > 0xff)
AliWarning("Overflow in charge");
qTotal = qTotal & 0xFF; // 8 bit, exactly like in the TRAP program
// assemble and store the tracklet word
fMCMT[cpu] = (qTotal << 24) | (padrow << 20) | (slope << 13) | offset;
// calculate MC label
Int_t mcLabel = -1;
Int_t nHits0 = 0;
Int_t nHits1 = 0;
if (fDigitsManager) {
Int_t label[30] = {0}; // up to 30 different labels possible
Int_t count[30] = {0};
Int_t maxIdx = -1;
Int_t maxCount = 0;
Int_t nLabels = 0;
for (Int_t iHit = 0; iHit < fNHits; iHit++) {
if ((fHits[iHit].fChannel - fFitPtr[cpu] < 0) ||
(fHits[iHit].fChannel - fFitPtr[cpu] > 1))
continue;
// counting contributing hits
if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0) &&
fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0))
nHits0++;
if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1) &&
fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1))
nHits1++;
Int_t currLabel = fHits[iHit].fLabel;
for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) {
if (currLabel == label[iLabel]) {
count[iLabel]++;
if (count[iLabel] > maxCount) {
maxCount = count[iLabel];
maxIdx = iLabel;
}
currLabel = 0;
break;
}
}
if (currLabel > 0) {
label[nLabels++] = currLabel;
}
}
if (maxIdx >= 0)
mcLabel = label[maxIdx];
}
new ((*fTrackletArray)[fTrackletArray->GetEntriesFast()]) AliTRDtrackletMCM((UInt_t) fMCMT[cpu], fDetector*2 + fRobPos%2, fRobPos, fMcmPos);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetLabel(mcLabel);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits(fit0->fNhits + fit1->fNhits);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits0(nHits0);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits1(nHits1);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ0(q0);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ1(q1);
}
}
}
}
Int_t AliTRDmcmSim::GetPID(Float_t q0, Float_t q1)
{
// get PID from accumulated charges q0 and q1
Int_t binQ0 = (Int_t) (q0 * fgPidNBinsQ0) + 1;
Int_t binQ1 = (Int_t) (q1 * fgPidNBinsQ1) + 1;
binQ0 = binQ0 >= fgPidNBinsQ0 ? fgPidNBinsQ0-1 : binQ0;
binQ1 = binQ1 >= fgPidNBinsQ0 ? fgPidNBinsQ0-1 : binQ1;
return fgPidLut[binQ0*fgPidNBinsQ1+binQ1];
}
void AliTRDmcmSim::SetPIDlut(Int_t *lut, Int_t nbinsq0, Int_t nbinsq1)
{
// set a user-defined PID LUT
if (fgPidLutDelete)
delete [] fgPidLut;
fgPidLutDelete = kFALSE;
fgPidLut = lut;
fgPidNBinsQ0 = nbinsq0;
fgPidNBinsQ1 = nbinsq1;
}
void AliTRDmcmSim::SetPIDlut(TH2F *lut)
{
// set a user-defined PID LUT from a 2D histogram
if (fgPidLutDelete)
delete [] fgPidLut;
fgPidNBinsQ0 = lut->GetNbinsX();
fgPidNBinsQ1 = lut->GetNbinsY();
fgPidLut = new Int_t[fgPidNBinsQ0*fgPidNBinsQ1];
for (Int_t ix = 0; ix < fgPidNBinsQ0; ix++) {
for (Int_t iy = 0; iy < fgPidNBinsQ1; iy++) {
fgPidLut[ix*fgPidNBinsQ1 + iy] = (Int_t) (256. * lut->GetBinContent(ix, iy));
}
}
fgPidLutDelete = kTRUE;
}
void AliTRDmcmSim::SetPIDlutDefault()
{
// use the default PID LUT
if (fgPidLutDelete )
delete [] fgPidLut;
fgPidLutDelete = kFALSE;
fgPidLut = *fgPidLutDefault;
fgPidNBinsQ0 = 40;
fgPidNBinsQ1 = 50;
}
void AliTRDmcmSim::Tracklet()
{
// Run the tracklet calculation by calling sequentially:
// CalcFitreg(); TrackletSelection(); FitTracklet()
// and store the tracklets
if (!fInitialized) {
AliError("Called uninitialized! Nothing done!");
return;
}
fTrackletArray->Delete();
CalcFitreg();
if (fNHits == 0)
return;
TrackletSelection();
FitTracklet();
}
Bool_t AliTRDmcmSim::StoreTracklets()
{
// store the found tracklets via the loader
if (fTrackletArray->GetEntriesFast() == 0)
return kTRUE;
AliRunLoader *rl = AliRunLoader::Instance();
AliDataLoader *dl = 0x0;
if (rl)
dl = rl->GetLoader("TRDLoader")->GetDataLoader("tracklets");
if (!dl) {
AliError("Could not get the tracklets data loader!");
return kFALSE;
}
TTree *trackletTree = dl->Tree();
if (!trackletTree) {
dl->MakeTree();
trackletTree = dl->Tree();
}
AliTRDtrackletMCM *trkl = 0x0;
TBranch *trkbranch = trackletTree->GetBranch("mcmtrklbranch");
if (!trkbranch)
trkbranch = trackletTree->Branch("mcmtrklbranch", "AliTRDtrackletMCM", &trkl, 32000);
for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) {
trkl = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet]);
trkbranch->SetAddress(&trkl);
// printf("filling tracklet 0x%08x\n", trkl->GetTrackletWord());
trkbranch->Fill();
}
dl->WriteData("OVERWRITE");
return kTRUE;
}
void AliTRDmcmSim::WriteData(AliTRDarrayADC *digits)
{
// write back the processed data configured by EBSF
// EBSF = 1: unfiltered data; EBSF = 0: filtered data
// zero-suppressed valued are written as -1 to digits
if (!fInitialized) {
AliError("Called uninitialized! Nothing done!");
return;
}
// Int_t firstAdc = 0;
// Int_t lastAdc = fNADC - 1;
//
// while (GetCol(firstAdc) < 0)
// firstAdc++;
//
// while (GetCol(lastAdc) < 0)
// lastAdc--;
Int_t offset = (fMcmPos % 4) * 21 + (fRobPos % 2) * 84;
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBSF) != 0) // store unfiltered data
{
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
if (fZSM1Dim[iAdc] == 1) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
digits->SetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin, -1);
// printf("suppressed: %i, %i, %i, %i, now: %i\n", fDetector, GetRow(), GetCol(iAdc), iTimeBin,
// digits->GetData(GetRow(), GetCol(iAdc), iTimeBin));
}
}
}
}
else {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
if (fZSM1Dim[iAdc] == 0) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
digits->SetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin, (fADCF[iAdc][iTimeBin] >> fgkAddDigits) - fgAddBaseline);
}
}
else {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
digits->SetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin, -1);
// printf("suppressed: %i, %i, %i, %i\n", fDetector, GetRow(), GetCol(iAdc), iTimeBin);
}
}
}
}
}
// help functions, to be cleaned up
UInt_t AliTRDmcmSim::AddUintClipping(UInt_t a, UInt_t b, UInt_t nbits) const
{
//
// This function adds a and b (unsigned) and clips to
// the specified number of bits.
//
UInt_t sum = a + b;
if (nbits < 32)
{
UInt_t maxv = (1 << nbits) - 1;;
if (sum > maxv)
sum = maxv;
}
else
{
if ((sum < a) || (sum < b))
sum = 0xFFFFFFFF;
}
return sum;
}
void AliTRDmcmSim::Sort2(UShort_t idx1i, UShort_t idx2i, \
UShort_t val1i, UShort_t val2i, \
UShort_t *idx1o, UShort_t *idx2o, \
UShort_t *val1o, UShort_t *val2o) const
{
// sorting for tracklet selection
if (val1i > val2i)
{
*idx1o = idx1i;
*idx2o = idx2i;
*val1o = val1i;
*val2o = val2i;
}
else
{
*idx1o = idx2i;
*idx2o = idx1i;
*val1o = val2i;
*val2o = val1i;
}
}
void AliTRDmcmSim::Sort3(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, \
UShort_t val1i, UShort_t val2i, UShort_t val3i, \
UShort_t *idx1o, UShort_t *idx2o, UShort_t *idx3o, \
UShort_t *val1o, UShort_t *val2o, UShort_t *val3o)
{
// sorting for tracklet selection
Int_t sel;
if (val1i > val2i) sel=4; else sel=0;
if (val2i > val3i) sel=sel + 2;
if (val3i > val1i) sel=sel + 1;
//printf("input channels %d %d %d, charges %d %d %d sel=%d\n",idx1i, idx2i, idx3i, val1i, val2i, val3i, sel);
switch(sel)
{
case 6 : // 1 > 2 > 3 => 1 2 3
case 0 : // 1 = 2 = 3 => 1 2 3 : in this case doesn't matter, but so is in hardware!
*idx1o = idx1i;
*idx2o = idx2i;
*idx3o = idx3i;
*val1o = val1i;
*val2o = val2i;
*val3o = val3i;
break;
case 4 : // 1 > 2, 2 <= 3, 3 <= 1 => 1 3 2
*idx1o = idx1i;
*idx2o = idx3i;
*idx3o = idx2i;
*val1o = val1i;
*val2o = val3i;
*val3o = val2i;
break;
case 2 : // 1 <= 2, 2 > 3, 3 <= 1 => 2 1 3
*idx1o = idx2i;
*idx2o = idx1i;
*idx3o = idx3i;
*val1o = val2i;
*val2o = val1i;
*val3o = val3i;
break;
case 3 : // 1 <= 2, 2 > 3, 3 > 1 => 2 3 1
*idx1o = idx2i;
*idx2o = idx3i;
*idx3o = idx1i;
*val1o = val2i;
*val2o = val3i;
*val3o = val1i;
break;
case 1 : // 1 <= 2, 2 <= 3, 3 > 1 => 3 2 1
*idx1o = idx3i;
*idx2o = idx2i;
*idx3o = idx1i;
*val1o = val3i;
*val2o = val2i;
*val3o = val1i;
break;
case 5 : // 1 > 2, 2 <= 3, 3 > 1 => 3 1 2
*idx1o = idx3i;
*idx2o = idx1i;
*idx3o = idx2i;
*val1o = val3i;
*val2o = val1i;
*val3o = val2i;
break;
default: // the rest should NEVER happen!
AliError("ERROR in Sort3!!!\n");
break;
}
// printf("output channels %d %d %d, charges %d %d %d \n",*idx1o, *idx2o, *idx3o, *val1o, *val2o, *val3o);
}
void AliTRDmcmSim::Sort6To4(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \
UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \
UShort_t *idx1o, UShort_t *idx2o, UShort_t *idx3o, UShort_t *idx4o, \
UShort_t *val1o, UShort_t *val2o, UShort_t *val3o, UShort_t *val4o)
{
// sorting for tracklet selection
UShort_t idx21s, idx22s, idx23s, dummy;
UShort_t val21s, val22s, val23s;
UShort_t idx23as, idx23bs;
UShort_t val23as, val23bs;
Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i,
idx1o, &idx21s, &idx23as,
val1o, &val21s, &val23as);
Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i,
idx2o, &idx22s, &idx23bs,
val2o, &val22s, &val23bs);
Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, &dummy, &val23s, &dummy);
Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s,
idx3o, idx4o, &dummy,
val3o, val4o, &dummy);
}
void AliTRDmcmSim::Sort6To2Worst(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \
UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \
UShort_t *idx5o, UShort_t *idx6o)
{
// sorting for tracklet selection
UShort_t idx21s, idx22s, idx23s, dummy1, dummy2, dummy3, dummy4, dummy5;
UShort_t val21s, val22s, val23s;
UShort_t idx23as, idx23bs;
UShort_t val23as, val23bs;
Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i,
&dummy1, &idx21s, &idx23as,
&dummy2, &val21s, &val23as);
Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i,
&dummy1, &idx22s, &idx23bs,
&dummy2, &val22s, &val23bs);
Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, idx5o, &val23s, &dummy1);
Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s,
&dummy1, &dummy2, idx6o,
&dummy3, &dummy4, &dummy5);
// printf("idx21s=%d, idx23as=%d, idx22s=%d, idx23bs=%d, idx5o=%d, idx6o=%d\n",
// idx21s, idx23as, idx22s, idx23bs, *idx5o, *idx6o);
}
Set baseline to 0.
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// TRD MCM (Multi Chip Module) simulator //
// which simulated the TRAP processing after the AD-conversion //
// The relevant parameters (i.e. configuration registers of the TRAP //
// configuration are taken from AliTRDtrapConfig. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <fstream> // needed for raw data dump
#include <TCanvas.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TGraph.h>
#include <TLine.h>
#include <TMath.h>
#include <TRandom.h>
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliLoader.h"
#include "AliTRDdigit.h"
#include "AliTRDfeeParam.h"
#include "AliTRDtrapConfig.h"
#include "AliTRDSimParam.h"
#include "AliTRDgeometry.h"
#include "AliTRDcalibDB.h"
#include "AliTRDdigitsManager.h"
#include "AliTRDarrayADC.h"
#include "AliTRDarrayDictionary.h"
#include "AliTRDpadPlane.h"
#include "AliTRDtrackletMCM.h"
#include "AliTRDmcmSim.h"
#include "AliMagF.h"
#include "TGeoGlobalMagField.h"
ClassImp(AliTRDmcmSim)
Bool_t AliTRDmcmSim::fgApplyCut = kTRUE;
Float_t AliTRDmcmSim::fgChargeNorm = 65000.;
Int_t AliTRDmcmSim::fgAddBaseline = 0;
Int_t AliTRDmcmSim::fgPidNBinsQ0 = 40;
Int_t AliTRDmcmSim::fgPidNBinsQ1 = 50;
Bool_t AliTRDmcmSim::fgPidLutDelete = kFALSE;
Int_t AliTRDmcmSim::fgPidLutDefault[40][50] = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 9, 6, 12, 29, 53, 76, 94, 107, 116, 122, 126, 128, 129, 129, 129, 128, 127, 126, 124, 122, 120, 117, 115, 112, 109, 107, 104, 101, 99, 96, 94, 91, 89, 87, 85, 83, 81, 79, 78, 77, 75, 74, 73, 72, 72, 71, 71, 70, 70 },
{ 0, 14, 8, 17, 37, 66, 94, 116, 131, 140, 146, 150, 152, 153, 153, 152, 150, 148, 145, 143, 139, 136, 132, 129, 125, 121, 118, 114, 110, 107, 104, 101, 98, 95, 93, 91, 89, 87, 85, 83, 82, 81, 80, 79, 78, 77, 77, 76, 76, 75 },
{ 0, 33, 19, 34, 69, 112, 145, 167, 181, 189, 194, 196, 197, 197, 196, 194, 191, 188, 184, 180, 175, 170, 165, 159, 154, 148, 143, 137, 132, 127, 123, 118, 114, 111, 107, 104, 101, 99, 96, 94, 92, 91, 89, 88, 87, 86, 85, 85, 84, 84 },
{ 0, 82, 52, 83, 136, 180, 205, 218, 226, 230, 232, 233, 233, 233, 232, 230, 228, 226, 223, 219, 215, 210, 205, 199, 193, 187, 180, 173, 167, 160, 154, 148, 142, 136, 131, 127, 122, 119, 115, 112, 109, 106, 104, 102, 100, 99, 97, 96, 95, 94 },
{ 0, 132, 96, 136, 185, 216, 231, 238, 242, 244, 245, 245, 245, 245, 245, 244, 243, 242, 240, 238, 236, 233, 230, 226, 222, 217, 212, 206, 200, 193, 187, 180, 173, 167, 161, 155, 149, 144, 139, 134, 130, 126, 123, 120, 117, 114, 112, 110, 108, 107 },
{ 0, 153, 120, 160, 203, 227, 238, 243, 246, 247, 248, 249, 249, 249, 248, 248, 247, 246, 245, 244, 243, 241, 239, 237, 234, 231, 228, 224, 219, 215, 209, 204, 198, 192, 186, 180, 174, 168, 163, 157, 152, 147, 143, 139, 135, 131, 128, 125, 123, 120 },
{ 0, 156, 128, 166, 207, 229, 239, 244, 247, 248, 249, 249, 249, 249, 249, 249, 248, 247, 247, 246, 244, 243, 242, 240, 238, 236, 233, 230, 227, 224, 220, 216, 212, 207, 202, 197, 192, 187, 181, 176, 171, 166, 161, 156, 152, 148, 144, 140, 137, 134 },
{ 0, 152, 128, 166, 206, 228, 239, 244, 246, 248, 249, 249, 249, 249, 249, 248, 248, 247, 246, 245, 244, 243, 241, 240, 238, 236, 234, 232, 229, 226, 224, 220, 217, 214, 210, 206, 202, 197, 193, 188, 184, 179, 174, 170, 166, 161, 157, 153, 150, 146 },
{ 0, 146, 126, 164, 203, 226, 237, 243, 246, 247, 248, 248, 248, 248, 248, 247, 247, 246, 245, 244, 242, 241, 239, 238, 236, 234, 232, 230, 227, 225, 223, 220, 217, 215, 212, 209, 205, 202, 199, 195, 191, 187, 183, 179, 175, 171, 168, 164, 160, 156 },
{ 0, 140, 123, 160, 200, 224, 235, 241, 244, 246, 247, 247, 247, 247, 247, 246, 245, 244, 243, 242, 240, 238, 237, 235, 233, 230, 228, 226, 224, 221, 219, 217, 215, 212, 210, 207, 205, 202, 200, 197, 194, 191, 188, 184, 181, 178, 174, 171, 168, 164 },
{ 0, 133, 119, 156, 196, 220, 233, 239, 243, 245, 245, 246, 246, 246, 245, 244, 243, 242, 241, 239, 237, 235, 233, 231, 229, 226, 224, 221, 219, 216, 214, 212, 210, 208, 206, 204, 202, 199, 197, 195, 193, 191, 188, 186, 183, 181, 178, 175, 172, 169 },
{ 0, 127, 115, 152, 192, 217, 230, 237, 241, 243, 244, 244, 244, 244, 243, 242, 241, 240, 238, 236, 234, 232, 229, 227, 224, 221, 218, 216, 213, 210, 208, 206, 203, 201, 200, 198, 196, 194, 193, 191, 190, 188, 186, 185, 183, 181, 179, 177, 174, 172 },
{ 0, 121, 111, 147, 187, 213, 227, 235, 239, 241, 242, 243, 243, 242, 241, 240, 239, 237, 236, 233, 231, 228, 225, 222, 219, 216, 213, 210, 207, 204, 201, 199, 196, 194, 192, 191, 189, 188, 187, 185, 184, 183, 182, 181, 180, 178, 177, 176, 174, 172 },
{ 0, 116, 107, 142, 181, 209, 224, 232, 237, 239, 240, 241, 241, 240, 239, 238, 237, 235, 233, 230, 227, 224, 221, 218, 214, 211, 207, 204, 200, 197, 194, 191, 189, 187, 185, 183, 182, 180, 179, 178, 178, 177, 176, 175, 175, 174, 173, 172, 172, 170 },
{ 0, 112, 103, 136, 176, 204, 220, 229, 234, 237, 238, 239, 239, 238, 237, 236, 234, 232, 230, 227, 224, 221, 217, 213, 209, 205, 201, 198, 194, 190, 187, 184, 181, 179, 177, 175, 174, 172, 171, 171, 170, 169, 169, 169, 168, 168, 168, 168, 167, 167 },
{ 0, 107, 99, 131, 170, 199, 216, 226, 231, 234, 236, 237, 237, 236, 235, 234, 232, 230, 227, 224, 221, 217, 213, 209, 205, 200, 196, 192, 188, 184, 180, 177, 174, 172, 169, 167, 166, 164, 163, 162, 162, 161, 161, 161, 161, 161, 161, 162, 162, 162 },
{ 0, 104, 94, 125, 164, 193, 212, 222, 228, 232, 233, 234, 234, 234, 233, 231, 229, 227, 224, 221, 218, 214, 210, 205, 201, 196, 191, 187, 182, 178, 174, 171, 168, 165, 162, 160, 158, 157, 155, 154, 154, 153, 153, 153, 153, 154, 154, 154, 155, 155 },
{ 0, 100, 90, 119, 157, 188, 207, 219, 225, 229, 231, 232, 232, 231, 230, 229, 227, 224, 222, 218, 215, 211, 206, 202, 197, 192, 187, 182, 178, 173, 169, 165, 162, 158, 156, 153, 151, 149, 148, 147, 146, 146, 145, 145, 145, 146, 146, 147, 148, 148 },
{ 0, 97, 86, 113, 150, 182, 202, 215, 222, 226, 228, 229, 229, 229, 228, 226, 224, 222, 219, 216, 212, 208, 203, 199, 194, 188, 183, 178, 173, 169, 164, 160, 156, 153, 150, 147, 145, 143, 141, 140, 139, 138, 138, 138, 138, 138, 139, 139, 140, 141 },
{ 0, 94, 82, 107, 144, 176, 197, 210, 218, 223, 225, 227, 227, 227, 226, 224, 222, 220, 217, 213, 209, 205, 201, 196, 191, 186, 180, 175, 170, 165, 160, 156, 152, 148, 145, 142, 139, 137, 135, 134, 132, 131, 131, 131, 131, 131, 131, 132, 132, 133 },
{ 0, 92, 78, 102, 137, 169, 192, 206, 215, 220, 223, 224, 224, 224, 223, 222, 220, 217, 215, 211, 207, 203, 199, 194, 188, 183, 178, 172, 167, 162, 157, 152, 148, 144, 140, 137, 134, 132, 130, 128, 127, 125, 125, 124, 124, 124, 124, 125, 125, 126 },
{ 0, 90, 75, 96, 131, 163, 187, 202, 211, 216, 220, 221, 222, 222, 221, 220, 218, 215, 212, 209, 205, 201, 197, 192, 187, 181, 176, 170, 165, 159, 154, 149, 145, 141, 137, 133, 130, 128, 125, 123, 122, 120, 119, 118, 118, 118, 118, 118, 119, 119 },
{ 0, 88, 71, 91, 124, 157, 181, 197, 207, 213, 217, 219, 219, 219, 219, 217, 216, 213, 211, 207, 204, 200, 195, 190, 185, 180, 174, 169, 163, 158, 152, 147, 142, 138, 134, 130, 127, 124, 121, 119, 117, 116, 114, 114, 113, 112, 112, 112, 112, 113 },
{ 0, 87, 68, 86, 118, 151, 176, 192, 203, 210, 214, 216, 217, 217, 217, 215, 214, 212, 209, 206, 202, 198, 194, 189, 184, 179, 173, 167, 162, 156, 151, 146, 141, 136, 132, 128, 124, 121, 118, 116, 114, 112, 110, 109, 108, 108, 107, 107, 107, 107 },
{ 0, 85, 65, 81, 112, 144, 170, 188, 199, 206, 211, 213, 214, 215, 214, 213, 212, 210, 207, 204, 201, 197, 193, 188, 183, 178, 172, 167, 161, 155, 150, 145, 140, 135, 130, 126, 122, 119, 116, 113, 111, 109, 107, 106, 105, 104, 103, 103, 102, 102 },
{ 0, 84, 62, 77, 106, 138, 165, 183, 195, 203, 208, 210, 212, 212, 212, 211, 210, 208, 206, 203, 200, 196, 192, 187, 183, 177, 172, 166, 161, 155, 150, 144, 139, 134, 129, 125, 121, 117, 114, 111, 109, 106, 104, 103, 101, 100, 99, 99, 98, 98 },
{ 0, 84, 60, 73, 101, 133, 159, 178, 191, 199, 204, 208, 209, 210, 210, 209, 208, 206, 204, 202, 199, 195, 191, 187, 182, 177, 172, 166, 161, 155, 150, 144, 139, 134, 129, 124, 120, 116, 113, 110, 107, 104, 102, 100, 99, 98, 96, 96, 95, 95 },
{ 0, 83, 58, 69, 96, 127, 154, 174, 187, 196, 201, 205, 207, 208, 208, 207, 206, 205, 203, 200, 197, 194, 190, 186, 182, 177, 172, 167, 161, 156, 150, 145, 139, 134, 129, 124, 120, 116, 112, 109, 106, 103, 101, 99, 97, 95, 94, 93, 92, 92 },
{ 0, 82, 56, 66, 91, 121, 149, 169, 183, 192, 198, 202, 204, 206, 206, 206, 205, 203, 201, 199, 196, 193, 190, 186, 182, 177, 172, 167, 162, 156, 151, 145, 140, 135, 129, 125, 120, 116, 112, 108, 105, 102, 100, 97, 95, 94, 92, 91, 90, 89 },
{ 0, 82, 54, 62, 86, 116, 144, 165, 179, 189, 195, 199, 202, 203, 204, 204, 203, 202, 200, 198, 196, 193, 189, 186, 182, 177, 173, 168, 163, 157, 152, 146, 141, 136, 130, 125, 121, 116, 112, 108, 105, 102, 99, 96, 94, 92, 91, 89, 88, 87 },
{ 0, 82, 52, 59, 82, 111, 139, 160, 175, 185, 192, 197, 200, 201, 202, 202, 201, 200, 199, 197, 195, 192, 189, 186, 182, 178, 173, 168, 163, 158, 153, 148, 142, 137, 132, 127, 122, 117, 113, 109, 105, 102, 99, 96, 94, 92, 90, 88, 87, 85 },
{ 0, 82, 50, 56, 78, 106, 134, 156, 171, 182, 189, 194, 197, 199, 200, 200, 200, 199, 198, 196, 194, 191, 188, 185, 182, 178, 174, 169, 164, 159, 154, 149, 144, 138, 133, 128, 123, 118, 114, 110, 106, 102, 99, 96, 93, 91, 89, 87, 86, 84 },
{ 0, 82, 49, 54, 74, 102, 129, 151, 167, 179, 186, 191, 195, 197, 198, 198, 198, 197, 196, 195, 193, 191, 188, 185, 182, 178, 174, 170, 165, 161, 156, 151, 145, 140, 135, 130, 125, 120, 115, 111, 107, 103, 100, 97, 94, 91, 89, 87, 85, 83 },
{ 0, 82, 47, 51, 70, 97, 124, 147, 164, 175, 183, 189, 192, 195, 196, 197, 197, 196, 195, 194, 192, 190, 188, 185, 182, 178, 175, 171, 166, 162, 157, 152, 147, 142, 137, 132, 127, 122, 117, 112, 108, 104, 101, 97, 94, 91, 89, 87, 85, 83 },
{ 0, 83, 46, 49, 67, 93, 120, 143, 160, 172, 180, 186, 190, 192, 194, 195, 195, 195, 194, 193, 191, 189, 187, 185, 182, 179, 175, 172, 167, 163, 159, 154, 149, 144, 139, 134, 129, 124, 119, 114, 110, 106, 102, 98, 95, 92, 89, 87, 85, 83 },
{ 0, 83, 45, 47, 64, 89, 116, 139, 156, 169, 177, 184, 188, 190, 192, 193, 193, 193, 193, 192, 190, 189, 187, 184, 182, 179, 176, 172, 168, 164, 160, 156, 151, 146, 141, 136, 131, 126, 121, 116, 112, 108, 104, 100, 96, 93, 90, 88, 85, 83 },
{ 0, 84, 44, 45, 61, 85, 111, 134, 152, 165, 175, 181, 185, 188, 190, 191, 192, 192, 191, 191, 189, 188, 186, 184, 182, 179, 176, 173, 169, 166, 162, 157, 153, 148, 143, 138, 133, 128, 124, 119, 114, 110, 106, 102, 98, 95, 91, 89, 86, 84 },
{ 0, 85, 43, 43, 58, 81, 107, 131, 149, 162, 172, 178, 183, 186, 188, 190, 190, 190, 190, 189, 188, 187, 186, 184, 182, 179, 176, 173, 170, 167, 163, 159, 155, 150, 145, 141, 136, 131, 126, 121, 117, 112, 108, 104, 100, 96, 93, 90, 87, 85 },
{ 0, 85, 42, 41, 55, 78, 103, 127, 145, 159, 169, 176, 181, 184, 186, 188, 189, 189, 189, 188, 188, 186, 185, 183, 181, 179, 177, 174, 171, 168, 164, 160, 156, 152, 148, 143, 138, 134, 129, 124, 119, 115, 110, 106, 102, 98, 95, 91, 88, 86 }
};
Int_t (*AliTRDmcmSim::fgPidLut) = *fgPidLutDefault;
//_____________________________________________________________________________
AliTRDmcmSim::AliTRDmcmSim() : TObject()
,fInitialized(kFALSE)
,fMaxTracklets(-1)
,fDetector(-1)
,fRobPos(-1)
,fMcmPos(-1)
,fRow (-1)
,fNADC(-1)
,fNTimeBin(-1)
,fADCR(NULL)
,fADCF(NULL)
,fMCMT(NULL)
,fTrackletArray(NULL)
,fZSM(NULL)
,fZSM1Dim(NULL)
,fFeeParam(NULL)
,fTrapConfig(NULL)
,fSimParam(NULL)
,fCommonParam(NULL)
,fCal(NULL)
,fGeo(NULL)
,fDigitsManager(NULL)
,fPedAcc(NULL)
,fGainCounterA(NULL)
,fGainCounterB(NULL)
,fTailAmplLong(NULL)
,fTailAmplShort(NULL)
,fNHits(0)
,fFitReg(NULL)
{
//
// AliTRDmcmSim default constructor
// By default, nothing is initialized.
// It is necessary to issue Init before use.
}
AliTRDmcmSim::~AliTRDmcmSim()
{
//
// AliTRDmcmSim destructor
//
if(fInitialized) {
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
delete [] fADCR[iadc];
delete [] fADCF[iadc];
delete [] fZSM [iadc];
}
delete [] fADCR;
delete [] fADCF;
delete [] fZSM;
delete [] fZSM1Dim;
delete [] fMCMT;
delete [] fPedAcc;
delete [] fGainCounterA;
delete [] fGainCounterB;
delete [] fTailAmplLong;
delete [] fTailAmplShort;
delete [] fFitReg;
fTrackletArray->Delete();
delete fTrackletArray;
delete fGeo;
}
}
void AliTRDmcmSim::Init( Int_t det, Int_t robPos, Int_t mcmPos, Bool_t /* newEvent */ )
{
//
// Initialize the class with new geometry information
// fADC array will be reused with filled by zero
//
if (!fInitialized) {
fFeeParam = AliTRDfeeParam::Instance();
fTrapConfig = AliTRDtrapConfig::Instance();
fSimParam = AliTRDSimParam::Instance();
fCommonParam = AliTRDCommonParam::Instance();
fCal = AliTRDcalibDB::Instance();
fGeo = new AliTRDgeometry();
}
fDetector = det;
fRobPos = robPos;
fMcmPos = mcmPos;
fNADC = fFeeParam->GetNadcMcm();
fNTimeBin = fCal->GetNumberOfTimeBins();
fRow = fFeeParam->GetPadRowFromMCM( fRobPos, fMcmPos );
fMaxTracklets = fFeeParam->GetMaxNrOfTracklets();
if (!fInitialized) {
fADCR = new Int_t *[fNADC];
fADCF = new Int_t *[fNADC];
fZSM = new Int_t *[fNADC];
fZSM1Dim = new Int_t [fNADC];
fGainCounterA = new UInt_t[fNADC];
fGainCounterB = new UInt_t[fNADC];
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
fADCR[iadc] = new Int_t[fNTimeBin];
fADCF[iadc] = new Int_t[fNTimeBin];
fZSM [iadc] = new Int_t[fNTimeBin];
}
// filter registers
fPedAcc = new UInt_t[fNADC]; // accumulator for pedestal filter
fTailAmplLong = new UShort_t[fNADC];
fTailAmplShort = new UShort_t[fNADC];
// tracklet calculation
fFitReg = new FitReg_t[fNADC];
fTrackletArray = new TClonesArray("AliTRDtrackletMCM", fMaxTracklets);
fMCMT = new UInt_t[fMaxTracklets];
}
fInitialized = kTRUE;
Reset();
}
void AliTRDmcmSim::Reset()
{
// Resets the data values and internal filter registers
// by re-initialising them
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fADCR[iadc][it] = 0;
fADCF[iadc][it] = 0;
fZSM [iadc][it] = 1; // Default unread = 1
}
fZSM1Dim[iadc] = 1; // Default unread = 1
fGainCounterA[iadc] = 0;
fGainCounterB[iadc] = 0;
}
for(Int_t i = 0; i < fMaxTracklets; i++) {
fMCMT[i] = 0;
}
FilterPedestalInit();
FilterGainInit();
FilterTailInit(fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP)); //??? not really correct if gain filter is active
}
void AliTRDmcmSim::SetNTimebins(Int_t ntimebins)
{
fNTimeBin = ntimebins;
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
delete fADCR[iadc];
delete fADCF[iadc];
delete fZSM[iadc];
fADCR[iadc] = new Int_t[fNTimeBin];
fADCF[iadc] = new Int_t[fNTimeBin];
fZSM [iadc] = new Int_t[fNTimeBin];
}
}
Bool_t AliTRDmcmSim::LoadMCM(AliRunLoader* const runloader, Int_t det, Int_t rob, Int_t mcm)
{
// loads the ADC data as obtained from the digitsManager for the specified MCM
Init(det, rob, mcm);
if (!runloader) {
AliError("No Runloader given");
return kFALSE;
}
AliLoader *trdLoader = runloader->GetLoader("TRDLoader");
if (!trdLoader) {
AliError("Could not get TRDLoader");
return kFALSE;
}
Bool_t retval = kTRUE;
trdLoader->LoadDigits();
fDigitsManager = 0x0;
AliTRDdigitsManager *digMgr = new AliTRDdigitsManager();
digMgr->SetSDigits(0);
digMgr->CreateArrays();
digMgr->ReadDigits(trdLoader->TreeD());
AliTRDarrayADC *digits = (AliTRDarrayADC*) digMgr->GetDigits(det);
if (digits->HasData()) {
digits->Expand();
if (fNTimeBin != digits->GetNtime())
SetNTimebins(digits->GetNtime());
Int_t padrow = fFeeParam->GetPadRowFromMCM(rob, mcm);
Int_t padcol = 0;
for (Int_t ch = 0; ch < fNADC; ch++) {
padcol = GetCol(ch);
fZSM1Dim[ch] = 1;
if (padcol < 0) {
fZSM1Dim[ch] = 0;
for (Int_t tb = 0; tb < fNTimeBin; tb++) {
fADCR[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
}
else {
for (Int_t tb = 0; tb < fNTimeBin; tb++) {
if (digits->GetData(padrow,padcol, tb) < 0) {
fZSM1Dim[ch] = 0;
fADCR[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[ch][tb] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
else {
fADCR[ch][tb] = digits->GetData(padrow, padcol, tb) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
fADCF[ch][tb] = digits->GetData(padrow, padcol, tb) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
}
}
}
}
}
else
retval = kFALSE;
delete digMgr;
return retval;
}
void AliTRDmcmSim::NoiseTest(Int_t nsamples, Int_t mean, Int_t sigma, Int_t inputGain, Int_t inputTail)
{
// This function can be used to test the filters.
// It feeds nsamples of ADC values with a gaussian distribution specified by mean and sigma.
// The filter chain implemented here consists of:
// Pedestal -> Gain -> Tail
// With inputGain and inputTail the input to the gain and tail filter, respectively,
// can be chosen where
// 0: noise input
// 1: pedestal output
// 2: gain output
// The input has to be chosen from a stage before.
// The filter behaviour is controlled by the TRAP parameters from AliTRDtrapConfig in the
// same way as in normal simulation.
// The functions produces four histograms with the values at the different stages.
TH1F *h = new TH1F("noise", "Gaussian Noise;sample;ADC count",
nsamples, 0, nsamples);
TH1F *hfp = new TH1F("pedf", "Noise #rightarrow Pedestal filter;sample;ADC count", nsamples, 0, nsamples);
TH1F *hfg = new TH1F("pedg", "Pedestal #rightarrow Gain;sample;ADC count", nsamples, 0, nsamples);
TH1F *hft = new TH1F("pedt", "Gain #rightarrow Tail;sample;ADC count", nsamples, 0, nsamples);
h->SetStats(kFALSE);
hfp->SetStats(kFALSE);
hfg->SetStats(kFALSE);
hft->SetStats(kFALSE);
Int_t value; // ADC count with noise (10 bit)
Int_t valuep; // pedestal filter output (12 bit)
Int_t valueg; // gain filter output (12 bit)
Int_t valuet; // tail filter value (12 bit)
for (Int_t i = 0; i < nsamples; i++) {
value = (Int_t) gRandom->Gaus(mean, sigma); // generate noise with gaussian distribution
h->SetBinContent(i, value);
valuep = FilterPedestalNextSample(1, 0, ((Int_t) value) << 2);
if (inputGain == 0)
valueg = FilterGainNextSample(1, ((Int_t) value) << 2);
else
valueg = FilterGainNextSample(1, valuep);
if (inputTail == 0)
valuet = FilterTailNextSample(1, ((Int_t) value) << 2);
else if (inputTail == 1)
valuet = FilterTailNextSample(1, valuep);
else
valuet = FilterTailNextSample(1, valueg);
hfp->SetBinContent(i, valuep >> 2);
hfg->SetBinContent(i, valueg >> 2);
hft->SetBinContent(i, valuet >> 2);
}
TCanvas *c = new TCanvas;
c->Divide(2,2);
c->cd(1);
h->Draw();
c->cd(2);
hfp->Draw();
c->cd(3);
hfg->Draw();
c->cd(4);
hft->Draw();
}
Bool_t AliTRDmcmSim::CheckInitialized()
{
//
// Check whether object is initialized
//
if( ! fInitialized ) {
AliDebug(2, Form ("AliTRDmcmSim is not initialized but function other than Init() is called."));
}
return fInitialized;
}
void AliTRDmcmSim::Print(Option_t* const option) const
{
// Prints the data stored and/or calculated for this MCM.
// The output is controlled by option which can be a sequence of any of
// the following characters:
// R - prints raw ADC data
// F - prints filtered data
// H - prints detected hits
// T - prints found tracklets
// The later stages are only useful when the corresponding calculations
// have been performed.
printf("MCM %i on ROB %i in detector %i\n", fMcmPos, fRobPos, fDetector);
TString opt = option;
if (opt.Contains("R")) {
printf("Raw ADC data (10 bit):\n");
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iChannel = 0; iChannel < fNADC; iChannel++) {
printf("%5i", fADCR[iChannel][iTimeBin] >> fgkAddDigits);
}
printf("\n");
}
}
if (opt.Contains("F")) {
printf("Filtered data (12 bit):\n");
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iChannel = 0; iChannel < fNADC; iChannel++) {
printf("%5i", fADCF[iChannel][iTimeBin]);
}
printf("\n");
}
}
if (opt.Contains("H")) {
printf("Found %i hits:\n", fNHits);
for (Int_t iHit = 0; iHit < fNHits; iHit++) {
printf("Hit %3i in timebin %2i, ADC %2i has charge %3i and position %3i\n",
iHit, fHits[iHit].fTimebin, fHits[iHit].fChannel, fHits[iHit].fQtot, fHits[iHit].fYpos);
}
}
if (opt.Contains("T")) {
printf("Tracklets:\n");
for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntriesFast(); iTrkl++) {
printf("tracklet %i: 0x%08x\n", iTrkl, ((AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl])->GetTrackletWord());
}
}
}
void AliTRDmcmSim::Draw(Option_t* const option)
{
// Plots the data stored in a 2-dim. timebin vs. ADC channel plot.
// The option selects what data is plotted and can be a sequence of
// the following characters:
// R - plot raw data (default)
// F - plot filtered data (meaningless if R is specified)
// In addition to the ADC values:
// H - plot hits
// T - plot tracklets
TString opt = option;
TH2F *hist = new TH2F("mcmdata", Form("Data of MCM %i on ROB %i in detector %i", \
fMcmPos, fRobPos, fDetector), \
fNADC, -0.5, fNADC-.5, fNTimeBin, -.5, fNTimeBin-.5);
hist->GetXaxis()->SetTitle("ADC Channel");
hist->GetYaxis()->SetTitle("Timebin");
hist->SetStats(kFALSE);
if (opt.Contains("R")) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
hist->SetBinContent(iAdc+1, iTimeBin+1, fADCR[iAdc][iTimeBin] >> fgkAddDigits);
}
}
}
else {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
hist->SetBinContent(iAdc+1, iTimeBin+1, fADCF[iAdc][iTimeBin] >> fgkAddDigits);
}
}
}
hist->Draw("colz");
if (opt.Contains("H")) {
TGraph *grHits = new TGraph();
for (Int_t iHit = 0; iHit < fNHits; iHit++) {
grHits->SetPoint(iHit,
fHits[iHit].fChannel + 1 + fHits[iHit].fYpos/256.,
fHits[iHit].fTimebin);
}
grHits->Draw("*");
}
if (opt.Contains("T")) {
TLine *trklLines = new TLine[4];
for (Int_t iTrkl = 0; iTrkl < fTrackletArray->GetEntries(); iTrkl++) {
AliTRDpadPlane *pp = fGeo->GetPadPlane(fDetector);
AliTRDtrackletMCM *trkl = (AliTRDtrackletMCM*) (*fTrackletArray)[iTrkl];
Float_t offset = pp->GetColPos(fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 19)) + 19 * pp->GetWidthIPad();
trklLines[iTrkl].SetX1((offset - trkl->GetY()) / pp->GetWidthIPad());
trklLines[iTrkl].SetY1(0);
trklLines[iTrkl].SetX2((offset - (trkl->GetY() + ((Float_t) trkl->GetdY())*140e-4)) / pp->GetWidthIPad());
trklLines[iTrkl].SetY2(fNTimeBin - 1);
trklLines[iTrkl].SetLineColor(2);
trklLines[iTrkl].SetLineWidth(2);
printf("Tracklet %i: y = %f, dy = %f, offset = %f\n", iTrkl, trkl->GetY(), (trkl->GetdY() * 140e-4), offset);
trklLines[iTrkl].Draw();
}
}
}
void AliTRDmcmSim::SetData( Int_t iadc, Int_t* const adc )
{
//
// Store ADC data into array of raw data
//
if( !CheckInitialized() ) return;
if( iadc < 0 || iadc >= fNADC ) {
//Log (Form ("Error: iadc is out of range (should be 0 to %d).", fNADC-1));
return;
}
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fADCR[iadc][it] = (Int_t) (adc[it]) << fgkAddDigits;
fADCF[iadc][it] = (Int_t) (adc[it]) << fgkAddDigits;
}
}
void AliTRDmcmSim::SetData( Int_t iadc, Int_t it, Int_t adc )
{
//
// Store ADC data into array of raw data
//
if( !CheckInitialized() ) return;
if( iadc < 0 || iadc >= fNADC ) {
//Log (Form ("Error: iadc is out of range (should be 0 to %d).", fNADC-1));
return;
}
fADCR[iadc][it] = adc << fgkAddDigits;
fADCF[iadc][it] = adc << fgkAddDigits;
}
void AliTRDmcmSim::SetData(AliTRDarrayADC* const adcArray, AliTRDdigitsManager *digitsManager)
{
// Set the ADC data from an AliTRDarrayADC
if (!fInitialized) {
AliError("Called uninitialized! Nothing done!");
return;
}
fDigitsManager = digitsManager;
if (fNTimeBin != adcArray->GetNtime())
SetNTimebins(adcArray->GetNtime());
Int_t offset = (fMcmPos % 4) * 21 + (fRobPos % 2) * 84;
// Int_t firstAdc = 0;
// Int_t lastAdc = fNADC-1;
//
// while (GetCol(firstAdc) < 0) {
// for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
// fADCR[firstAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// fADCF[firstAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// }
// firstAdc++;
// }
//
// while (GetCol(lastAdc) < 0) {
// for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
// fADCR[lastAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// fADCF[lastAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
// }
// lastAdc--;
// }
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
Int_t value = adcArray->GetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin);
if (value < 0 || (20-iAdc + offset < 1) || (20-iAdc + offset > 165)) {
fADCR[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[iAdc][iTimeBin] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
else {
fADCR[iAdc][iTimeBin] = adcArray->GetData(GetRow(), GetCol(iAdc), iTimeBin) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
fADCF[iAdc][iTimeBin] = adcArray->GetData(GetRow(), GetCol(iAdc), iTimeBin) << fgkAddDigits + (fgAddBaseline << fgkAddDigits);
}
}
}
}
void AliTRDmcmSim::SetDataPedestal( Int_t iadc )
{
//
// Store ADC data into array of raw data
//
if( !CheckInitialized() ) return;
if( iadc < 0 || iadc >= fNADC ) {
return;
}
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fADCR[iadc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
fADCF[iadc][it] = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP) + (fgAddBaseline << fgkAddDigits);
}
}
Int_t AliTRDmcmSim::GetCol( Int_t iadc )
{
//
// Return column id of the pad for the given ADC channel
//
if( !CheckInitialized() )
return -1;
Int_t col = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, iadc);
if (col < 0 || col >= fFeeParam->GetNcol())
return -1;
else
return col;
}
Int_t AliTRDmcmSim::ProduceRawStream( UInt_t *buf, Int_t maxSize, UInt_t iEv)
{
//
// Produce raw data stream from this MCM and put in buf
// Returns number of words filled, or negative value
// with -1 * number of overflowed words
//
UInt_t x;
Int_t nw = 0; // Number of written words
Int_t of = 0; // Number of overflowed words
Int_t rawVer = fFeeParam->GetRAWversion();
Int_t **adc;
Int_t nActiveADC = 0; // number of activated ADC bits in a word
if( !CheckInitialized() ) return 0;
if( fFeeParam->GetRAWstoreRaw() ) {
adc = fADCR;
} else {
adc = fADCF;
}
// Produce MCM header
x = (1<<31) | (fRobPos << 28) | (fMcmPos << 24) | ((iEv % 0x100000) << 4) | 0xC;
if (nw < maxSize) {
buf[nw++] = x;
//printf("\nMCM header: %X ",x);
}
else {
of++;
}
// Produce ADC mask : nncc cccm mmmm mmmm mmmm mmmm mmmm 1100
// n : unused , c : ADC count, m : selected ADCs
if( rawVer >= 3 ) {
x = 0;
for( Int_t iAdc = 0 ; iAdc < fNADC ; iAdc++ ) {
if( fZSM1Dim[iAdc] == 0 ) { // 0 means not suppressed
x = x | (1 << (iAdc+4) ); // last 4 digit reserved for 1100=0xc
nActiveADC++; // number of 1 in mmm....m
}
}
x = x | (1 << 30) | ( ( 0x3FFFFFFC ) & (~(nActiveADC) << 25) ) | 0xC; // nn = 01, ccccc are inverted, 0xc=1100
//printf("nActiveADC=%d=%08X, inverted=%X ",nActiveADC,nActiveADC,x );
if (nw < maxSize) {
buf[nw++] = x;
//printf("ADC mask: %X nMask=%d ADC data: ",x,nActiveADC);
}
else {
of++;
}
}
// Produce ADC data. 3 timebins are packed into one 32 bits word
// In this version, different ADC channel will NOT share the same word
UInt_t aa=0, a1=0, a2=0, a3=0;
for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
if( rawVer>= 3 && fZSM1Dim[iAdc] != 0 ) continue; // Zero Suppression, 0 means not suppressed
aa = !(iAdc & 1) + 2;
for (Int_t iT = 0; iT < fNTimeBin; iT+=3 ) {
a1 = ((iT ) < fNTimeBin ) ? adc[iAdc][iT ] >> fgkAddDigits : 0;
a2 = ((iT + 1) < fNTimeBin ) ? adc[iAdc][iT+1] >> fgkAddDigits : 0;
a3 = ((iT + 2) < fNTimeBin ) ? adc[iAdc][iT+2] >> fgkAddDigits : 0;
x = (a3 << 22) | (a2 << 12) | (a1 << 2) | aa;
if (nw < maxSize) {
buf[nw++] = x;
//printf("%08X ",x);
}
else {
of++;
}
}
}
if( of != 0 ) return -of; else return nw;
}
Int_t AliTRDmcmSim::ProduceTrackletStream( UInt_t *buf, Int_t maxSize )
{
//
// Produce tracklet data stream from this MCM and put in buf
// Returns number of words filled, or negative value
// with -1 * number of overflowed words
//
Int_t nw = 0; // Number of written words
Int_t of = 0; // Number of overflowed words
if( !CheckInitialized() ) return 0;
// Produce tracklet data. A maximum of four 32 Bit words will be written per MCM
// fMCMT is filled continuously until no more tracklet words available
for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) {
if (nw < maxSize)
buf[nw++] = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet])->GetTrackletWord();
else
of++;
}
if( of != 0 ) return -of; else return nw;
}
void AliTRDmcmSim::Filter()
{
//
// Filter the raw ADC values. The active filter stages and their
// parameters are taken from AliTRDtrapConfig.
// The raw data is stored separate from the filtered data. Thus,
// it is possible to run the filters on a set of raw values
// sequentially for parameter tuning.
//
if( !CheckInitialized() ) {
AliError("got called before initialization! Nothing done!");
return;
}
// Apply filters sequentially. Bypass is handled by filters
// since counters and internal registers may be updated even
// if the filter is bypassed.
// The first filter takes the data from fADCR and
// outputs to fADCF.
// Non-linearity filter not implemented.
FilterPedestal();
FilterGain();
FilterTail();
// Crosstalk filter not implemented.
}
void AliTRDmcmSim::FilterPedestalInit()
{
// Initializes the pedestal filter assuming that the input has
// been constant for a long time (compared to the time constant).
// UShort_t fpnp = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); // 0..511 -> 0..127.75, pedestal at the output
UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest
UShort_t shifts[4] = {11, 14, 17, 21}; //??? where to take shifts from?
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++)
fPedAcc[iAdc] = (fSimParam->GetADCbaseline() << 2) * (1<<shifts[fptc]);
}
UShort_t AliTRDmcmSim::FilterPedestalNextSample(Int_t adc, Int_t timebin, UShort_t value)
{
// Returns the output of the pedestal filter given the input value.
// The output depends on the internal registers and, thus, the
// history of the filter.
UShort_t fpnp = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); // 0..511 -> 0..127.75, pedestal at the output
UShort_t fptc = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPTC); // 0..3, 0 - fastest, 3 - slowest
UShort_t fpby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPBY); // 0..1 the bypass, active low
UShort_t shifts[4] = {11, 14, 17, 21}; //??? where to come from
UShort_t accumulatorShifted;
Int_t correction;
UShort_t inpAdd;
inpAdd = value + fpnp;
if (fpby == 0) //??? before or after update of accumulator
return value;
accumulatorShifted = (fPedAcc[adc] >> shifts[fptc]) & 0x3FF; // 10 bits
if (timebin == 0) // the accumulator is disabled in the drift time
{
correction = (value & 0x3FF) - accumulatorShifted;
fPedAcc[adc] = (fPedAcc[adc] + correction) & 0x7FFFFFFF; // 31 bits
}
if (inpAdd <= accumulatorShifted)
return 0;
else
{
inpAdd = inpAdd - accumulatorShifted;
if (inpAdd > 0xFFF)
return 0xFFF;
else
return inpAdd;
}
}
void AliTRDmcmSim::FilterPedestal()
{
//
// Apply pedestal filter
//
// As the first filter in the chain it reads data from fADCR
// and outputs to fADCF.
// It has only an effect if previous samples have been fed to
// find the pedestal. Currently, the simulation assumes that
// the input has been stable for a sufficiently long time.
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
fADCF[iAdc][iTimeBin] = FilterPedestalNextSample(iAdc, iTimeBin, fADCR[iAdc][iTimeBin]);
}
}
}
void AliTRDmcmSim::FilterGainInit()
{
// Initializes the gain filter. In this case, only threshold
// counters are reset.
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
// these are counters which in hardware continue
// until maximum or reset
fGainCounterA[iAdc] = 0;
fGainCounterB[iAdc] = 0;
}
}
UShort_t AliTRDmcmSim::FilterGainNextSample(Int_t adc, UShort_t value)
{
// Apply the gain filter to the given value.
// BEGIN_LATEX O_{i}(t) = #gamma_{i} * I_{i}(t) + a_{i} END_LATEX
// The output depends on the internal registers and, thus, the
// history of the filter.
UShort_t fgby = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGBY); // bypass, active low
UShort_t fgf = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGF0 + adc)); // 0x700 + (0 & 0x1ff);
UShort_t fga = fTrapConfig->GetTrapReg(AliTRDtrapConfig::TrapReg_t(AliTRDtrapConfig::kFGA0 + adc)); // 40;
UShort_t fgta = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTA); // 20;
UShort_t fgtb = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFGTB); // 2060;
UInt_t tmp;
value &= 0xFFF;
tmp = (value * fgf) >> 11;
if (tmp > 0xFFF) tmp = 0xFFF;
if (fgby == 1)
value = AddUintClipping(tmp, fga, 12);
// Update threshold counters
// not really useful as they are cleared with every new event
if ((fGainCounterA[adc] == 0x3FFFFFF) || (fGainCounterB[adc] == 0x3FFFFFF))
{
if (value >= fgtb)
fGainCounterB[adc]++;
else if (value >= fgta)
fGainCounterA[adc]++;
}
return value;
}
void AliTRDmcmSim::FilterGain()
{
// Read data from fADCF and apply gain filter.
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
fADCF[iAdc][iTimeBin] = FilterGainNextSample(iAdc, fADCF[iAdc][iTimeBin]);
}
}
}
void AliTRDmcmSim::FilterTailInit(Int_t baseline)
{
// Initializes the tail filter assuming that the input has
// been at the baseline value (configured by FTFP) for a
// sufficiently long time.
// exponents and weight calculated from configuration
UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component
UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier
UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier
Float_t lambdaL = lambdaLong * 1.0 / (1 << 11);
Float_t lambdaS = lambdaShort * 1.0 / (1 << 11);
Float_t alphaL = alphaLong * 1.0 / (1 << 11);
Float_t qup, qdn;
qup = (1 - lambdaL) * (1 - lambdaS);
qdn = 1 - lambdaS * alphaL - lambdaL * (1 - alphaL);
Float_t kdc = qup/qdn;
Float_t kt, ql, qs;
UShort_t aout;
kt = kdc * baseline;
aout = baseline - (UShort_t) kt;
ql = lambdaL * (1 - lambdaS) * alphaL;
qs = lambdaS * (1 - lambdaL) * (1 - alphaL);
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
fTailAmplLong[iAdc] = (UShort_t) (aout * ql / (ql + qs));
fTailAmplShort[iAdc] = (UShort_t) (aout * qs / (ql + qs));
}
}
UShort_t AliTRDmcmSim::FilterTailNextSample(Int_t adc, UShort_t value)
{
// Returns the output of the tail filter for the given input value.
// The output depends on the internal registers and, thus, the
// history of the filter.
// exponents and weight calculated from configuration
UShort_t alphaLong = 0x3ff & fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTAL); // the weight of the long component
UShort_t lambdaLong = (1 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLL) & 0x1FF); // the multiplier
UShort_t lambdaShort = (0 << 10) | (1 << 9) | (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTLS) & 0x1FF); // the multiplier
Float_t lambdaL = lambdaLong * 1.0 / (1 << 11);
Float_t lambdaS = lambdaShort * 1.0 / (1 << 11);
Float_t alphaL = alphaLong * 1.0 / (1 << 11);
Float_t qup, qdn;
qup = (1 - lambdaL) * (1 - lambdaS);
qdn = 1 - lambdaS * alphaL - lambdaL * (1 - alphaL);
// Float_t kdc = qup/qdn;
UInt_t aDiff;
UInt_t alInpv;
UShort_t aQ;
UInt_t tmp;
UShort_t inpVolt = value & 0xFFF; // 12 bits
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFTBY) == 0) // bypass mode, active low
return value;
else
{
// add the present generator outputs
aQ = AddUintClipping(fTailAmplLong[adc], fTailAmplShort[adc], 12);
// calculate the difference between the input the generated signal
if (inpVolt > aQ)
aDiff = inpVolt - aQ;
else
aDiff = 0;
// the inputs to the two generators, weighted
alInpv = (aDiff * alphaLong) >> 11;
// the new values of the registers, used next time
// long component
tmp = AddUintClipping(fTailAmplLong[adc], alInpv, 12);
tmp = (tmp * lambdaLong) >> 11;
fTailAmplLong[adc] = tmp & 0xFFF;
// short component
tmp = AddUintClipping(fTailAmplShort[adc], aDiff - alInpv, 12);
tmp = (tmp * lambdaShort) >> 11;
fTailAmplShort[adc] = tmp & 0xFFF;
// the output of the filter
return aDiff;
}
}
void AliTRDmcmSim::FilterTail()
{
// Apply tail filter
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
fADCF[iAdc][iTimeBin] = FilterTailNextSample(iAdc, fADCF[iAdc][iTimeBin]);
}
}
}
void AliTRDmcmSim::ZSMapping()
{
//
// Zero Suppression Mapping implemented in TRAP chip
//
// See detail TRAP manual "Data Indication" section:
// http://www.kip.uni-heidelberg.de/ti/TRD/doc/trap/TRAP-UserManual.pdf
//
//??? values should come from TRAPconfig
Int_t eBIS = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIS); // TRAP default = 0x4 (Tis=4)
Int_t eBIT = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIT); // TRAP default = 0x28 (Tit=40)
Int_t eBIL = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIL); // TRAP default = 0xf0
// (lookup table accept (I2,I1,I0)=(111)
// or (110) or (101) or (100))
Int_t eBIN = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBIN); // TRAP default = 1 (no neighbor sensitivity)
Int_t ep = 0; // fTrapConfig->GetTrapReg(AliTRDtrapConfig::kFPNP); //??? really subtracted here
Int_t **adc = fADCF;
if( !CheckInitialized() ) {
AliError("got called uninitialized! Nothing done!");
return;
}
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
for( Int_t iadc = 1 ; iadc < fNADC-1; iadc++ ) {
// Get ADC data currently in filter buffer
Int_t ap = adc[iadc-1][it] - ep; // previous
Int_t ac = adc[iadc ][it] - ep; // current
Int_t an = adc[iadc+1][it] - ep; // next
// evaluate three conditions
Int_t i0 = ( ac >= ap && ac >= an ) ? 0 : 1; // peak center detection
Int_t i1 = ( ap + ac + an > eBIT ) ? 0 : 1; // cluster
Int_t i2 = ( ac > eBIS ) ? 0 : 1; // absolute large peak
Int_t i = i2 * 4 + i1 * 2 + i0; // Bit position in lookup table
Int_t d = (eBIL >> i) & 1; // Looking up (here d=0 means true
// and d=1 means false according to TRAP manual)
fZSM[iadc][it] &= d;
if( eBIN == 0 ) { // turn on neighboring ADCs
fZSM[iadc-1][it] &= d;
fZSM[iadc+1][it] &= d;
}
}
}
// do 1 dim projection
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
fZSM1Dim[iadc] &= fZSM[iadc][it];
}
}
}
void AliTRDmcmSim::DumpData( const char * const f, const char * const target )
{
//
// Dump data stored (for debugging).
// target should contain one or multiple of the following characters
// R for raw data
// F for filtered data
// Z for zero suppression map
// S Raw dat astream
// other characters are simply ignored
//
UInt_t tempbuf[1024];
if( !CheckInitialized() ) return;
std::ofstream of( f, std::ios::out | std::ios::app );
of << Form("AliTRDmcmSim::DumpData det=%03d sm=%02d stack=%d layer=%d rob=%d mcm=%02d\n",
fDetector, fGeo->GetSector(fDetector), fGeo->GetStack(fDetector),
fGeo->GetSector(fDetector), fRobPos, fMcmPos );
for( Int_t t=0 ; target[t] != 0 ; t++ ) {
switch( target[t] ) {
case 'R' :
case 'r' :
of << Form("fADCR (raw ADC data)\n");
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
of << Form(" ADC %02d: ", iadc);
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
of << Form("% 4d", fADCR[iadc][it]);
}
of << Form("\n");
}
break;
case 'F' :
case 'f' :
of << Form("fADCF (filtered ADC data)\n");
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
of << Form(" ADC %02d: ", iadc);
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
of << Form("% 4d", fADCF[iadc][it]);
}
of << Form("\n");
}
break;
case 'Z' :
case 'z' :
of << Form("fZSM and fZSM1Dim (Zero Suppression Map)\n");
for( Int_t iadc = 0 ; iadc < fNADC; iadc++ ) {
of << Form(" ADC %02d: ", iadc);
if( fZSM1Dim[iadc] == 0 ) { of << " R " ; } else { of << " . "; } // R:read .:suppressed
for( Int_t it = 0 ; it < fNTimeBin ; it++ ) {
if( fZSM[iadc][it] == 0 ) { of << " R"; } else { of << " ."; } // R:read .:suppressed
}
of << Form("\n");
}
break;
case 'S' :
case 's' :
Int_t s = ProduceRawStream( tempbuf, 1024 );
of << Form("Stream for Raw Simulation size=%d rawver=%d\n", s, fFeeParam->GetRAWversion());
of << Form(" address data\n");
for( Int_t i = 0 ; i < s ; i++ ) {
of << Form(" %04x %08x\n", i, tempbuf[i]);
}
}
}
}
void AliTRDmcmSim::AddHitToFitreg(Int_t adc, UShort_t timebin, UShort_t qtot, Short_t ypos, Int_t label)
{
// Add the given hit to the fit register which is lateron used for
// the tracklet calculation.
// In addition to the fit sums in the fit register MC information
// is stored.
if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0)) &&
(timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0)))
fFitReg[adc].fQ0 += qtot;
if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1)) &&
(timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1)))
fFitReg[adc].fQ1 += qtot;
if ((timebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS) ) &&
(timebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE)))
{
fFitReg[adc].fSumX += timebin;
fFitReg[adc].fSumX2 += timebin*timebin;
fFitReg[adc].fNhits++;
fFitReg[adc].fSumY += ypos;
fFitReg[adc].fSumY2 += ypos*ypos;
fFitReg[adc].fSumXY += timebin*ypos;
}
// register hits (MC info)
fHits[fNHits].fChannel = adc;
fHits[fNHits].fQtot = qtot;
fHits[fNHits].fYpos = ypos;
fHits[fNHits].fTimebin = timebin;
fHits[fNHits].fLabel = label;
fNHits++;
}
void AliTRDmcmSim::CalcFitreg()
{
// Preprocessing.
// Detect the hits and fill the fit registers.
// Requires 12-bit data from fADCF which means Filter()
// has to be called before even if all filters are bypassed.
//???
// TRAP parameters:
const UShort_t lutPos[128] = { // move later to some other file
0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15,
16, 16, 16, 17, 17, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 26, 26, 26, 26,
27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 27, 27, 27, 27, 26,
26, 26, 26, 25, 25, 25, 24, 24, 23, 23, 22, 22, 21, 21, 20, 20, 19, 18, 18, 17, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 7};
//??? to be clarified:
UInt_t adcMask = 0xffffffff;
UShort_t timebin, adcch, adcLeft, adcCentral, adcRight, hitQual, timebin1, timebin2, qtotTemp;
Short_t ypos, fromLeft, fromRight, found;
UShort_t qTotal[19]; // the last is dummy
UShort_t marked[6], qMarked[6], worse1, worse2;
timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFS);
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0)
< timebin1)
timebin1 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0);
timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFE);
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1)
> timebin2)
timebin2 = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1);
// reset the fit registers
fNHits = 0;
for (adcch = 0; adcch < fNADC-2; adcch++) // due to border channels
{
fFitReg[adcch].fNhits = 0;
fFitReg[adcch].fQ0 = 0;
fFitReg[adcch].fQ1 = 0;
fFitReg[adcch].fSumX = 0;
fFitReg[adcch].fSumY = 0;
fFitReg[adcch].fSumX2 = 0;
fFitReg[adcch].fSumY2 = 0;
fFitReg[adcch].fSumXY = 0;
}
for (timebin = timebin1; timebin < timebin2; timebin++)
{
// first find the hit candidates and store the total cluster charge in qTotal array
// in case of not hit store 0 there.
for (adcch = 0; adcch < fNADC-2; adcch++) {
if ( ( (adcMask >> adcch) & 7) == 7) //??? all 3 channels are present in case of ZS
{
adcLeft = fADCF[adcch ][timebin];
adcCentral = fADCF[adcch+1][timebin];
adcRight = fADCF[adcch+2][timebin];
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVBY) == 1)
hitQual = ( (adcLeft * adcRight) <
(fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPVT) * adcCentral) );
else
hitQual = 1;
// The accumulated charge is with the pedestal!!!
qtotTemp = adcLeft + adcCentral + adcRight;
if ( (hitQual) &&
(qtotTemp >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT)) &&
(adcLeft <= adcCentral) &&
(adcCentral > adcRight) )
qTotal[adcch] = qtotTemp;
else
qTotal[adcch] = 0;
}
else
qTotal[adcch] = 0; //jkl
AliDebug(10,Form("ch %2d qTotal %5d",adcch, qTotal[adcch]));
}
fromLeft = -1;
adcch = 0;
found = 0;
marked[4] = 19; // invalid channel
marked[5] = 19; // invalid channel
qTotal[19] = 0;
while ((adcch < 16) && (found < 3))
{
if (qTotal[adcch] > 0)
{
fromLeft = adcch;
marked[2*found+1]=adcch;
found++;
}
adcch++;
}
fromRight = -1;
adcch = 18;
found = 0;
while ((adcch > 2) && (found < 3))
{
if (qTotal[adcch] > 0)
{
marked[2*found]=adcch;
found++;
fromRight = adcch;
}
adcch--;
}
AliDebug(10,Form("Fromleft=%d, Fromright=%d",fromLeft, fromRight));
// here mask the hit candidates in the middle, if any
if ((fromLeft >= 0) && (fromRight >= 0) && (fromLeft < fromRight))
for (adcch = fromLeft+1; adcch < fromRight; adcch++)
qTotal[adcch] = 0;
found = 0;
for (adcch = 0; adcch < 19; adcch++)
if (qTotal[adcch] > 0) found++;
// NOT READY
if (found > 4) // sorting like in the TRAP in case of 5 or 6 candidates!
{
if (marked[4] == marked[5]) marked[5] = 19;
for (found=0; found<6; found++)
{
qMarked[found] = qTotal[marked[found]] >> 4;
AliDebug(10,Form("ch_%d qTotal %d qTotals %d",marked[found],qTotal[marked[found]],qMarked[found]));
}
Sort6To2Worst(marked[0], marked[3], marked[4], marked[1], marked[2], marked[5],
qMarked[0],
qMarked[3],
qMarked[4],
qMarked[1],
qMarked[2],
qMarked[5],
&worse1, &worse2);
// Now mask the two channels with the smallest charge
if (worse1 < 19)
{
qTotal[worse1] = 0;
AliDebug(10,Form("Kill ch %d\n",worse1));
}
if (worse2 < 19)
{
qTotal[worse2] = 0;
AliDebug(10,Form("Kill ch %d\n",worse2));
}
}
for (adcch = 0; adcch < 19; adcch++) {
if (qTotal[adcch] > 0) // the channel is marked for processing
{
adcLeft = fADCF[adcch ][timebin];
adcCentral = fADCF[adcch+1][timebin];
adcRight = fADCF[adcch+2][timebin];
// hit detected, in TRAP we have 4 units and a hit-selection, here we proceed all channels!
// subtract the pedestal TPFP, clipping instead of wrapping
Int_t regTPFP = fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPFP);
AliDebug(10, Form("Hit found, time=%d, adcch=%d/%d/%d, adc values=%d/%d/%d, regTPFP=%d, TPHT=%d\n",
timebin, adcch, adcch+1, adcch+2, adcLeft, adcCentral, adcRight, regTPFP,
fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPHT)));
if (adcLeft < regTPFP) adcLeft = 0; else adcLeft -= regTPFP;
if (adcCentral < regTPFP) adcCentral = 0; else adcCentral -= regTPFP;
if (adcRight < regTPFP) adcRight = 0; else adcRight -= regTPFP;
// Calculate the center of gravity
// checking for adcCentral != 0 (in case of "bad" configuration)
if (adcCentral == 0)
continue;
ypos = 128*(adcLeft - adcRight) / adcCentral;
if (ypos < 0) ypos = -ypos;
// make the correction using the LUT
ypos = ypos + lutPos[ypos & 0x7F];
if (adcLeft > adcRight) ypos = -ypos;
// label calculation
Int_t mcLabel = -1;
if (fDigitsManager) {
Int_t label[9] = { 0 }; // up to 9 different labels possible
Int_t count[9] = { 0 };
Int_t maxIdx = -1;
Int_t maxCount = 0;
Int_t nLabels = 0;
Int_t padcol[3];
padcol[0] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch);
padcol[1] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+1);
padcol[2] = fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, adcch+2);
Int_t padrow = fFeeParam->GetPadRowFromMCM(fRobPos, fMcmPos);
for (Int_t iDict = 0; iDict < 3; iDict++) {
if (!fDigitsManager->UsesDictionaries() || fDigitsManager->GetDictionary(fDetector, iDict) == 0) {
AliError("Cannot get dictionary");
continue;
}
AliTRDarrayDictionary *dict = (AliTRDarrayDictionary*) fDigitsManager->GetDictionary(fDetector, iDict);
if (dict->GetDim() == 0) {
AliError(Form("Dictionary %i of det. %i has dim. 0", fDetector, iDict));
continue;
}
dict->Expand();
for (Int_t iPad = 0; iPad < 3; iPad++) {
if (padcol[iPad] < 0)
continue;
Int_t currLabel = dict->GetData(padrow, padcol[iPad], timebin); //fDigitsManager->GetTrack(iDict, padrow, padcol, timebin, fDetector);
AliDebug(10, Form("Read label: %4i for det: %3i, row: %i, col: %i, tb: %i\n", currLabel, fDetector, padrow, padcol[iPad], timebin));
for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) {
if (currLabel == label[iLabel]) {
count[iLabel]++;
if (count[iLabel] > maxCount) {
maxCount = count[iLabel];
maxIdx = iLabel;
}
currLabel = 0;
break;
}
}
if (currLabel > 0) {
label[nLabels++] = currLabel;
}
}
}
if (maxIdx >= 0)
mcLabel = label[maxIdx];
}
// add the hit to the fitregister
AddHitToFitreg(adcch, timebin, qTotal[adcch], ypos, mcLabel);
}
}
}
}
void AliTRDmcmSim::TrackletSelection()
{
// Select up to 4 tracklet candidates from the fit registers
// and assign them to the CPUs.
UShort_t adcIdx, i, j, ntracks, tmp;
UShort_t trackletCand[18][2]; // store the adcch[0] and number of hits[1] for all tracklet candidates
ntracks = 0;
for (adcIdx = 0; adcIdx < 18; adcIdx++) // ADCs
if ( (fFitReg[adcIdx].fNhits
>= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCL)) &&
(fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits
>= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPCT)))
{
trackletCand[ntracks][0] = adcIdx;
trackletCand[ntracks][1] = fFitReg[adcIdx].fNhits+fFitReg[adcIdx+1].fNhits;
AliDebug(10,Form("%d %2d %4d\n", ntracks, trackletCand[ntracks][0], trackletCand[ntracks][1]));
ntracks++;
};
for (i=0; i<ntracks;i++)
AliDebug(10,Form("%d %d %d\n",i,trackletCand[i][0], trackletCand[i][1]));
if (ntracks > 4)
{
// primitive sorting according to the number of hits
for (j = 0; j < (ntracks-1); j++)
{
for (i = j+1; i < ntracks; i++)
{
if ( (trackletCand[j][1] < trackletCand[i][1]) ||
( (trackletCand[j][1] == trackletCand[i][1]) && (trackletCand[j][0] < trackletCand[i][0]) ) )
{
// swap j & i
tmp = trackletCand[j][1];
trackletCand[j][1] = trackletCand[i][1];
trackletCand[i][1] = tmp;
tmp = trackletCand[j][0];
trackletCand[j][0] = trackletCand[i][0];
trackletCand[i][0] = tmp;
}
}
}
ntracks = 4; // cut the rest, 4 is the max
}
// else is not necessary to sort
// now sort, so that the first tracklet going to CPU0 corresponds to the highest adc channel - as in the TRAP
for (j = 0; j < (ntracks-1); j++)
{
for (i = j+1; i < ntracks; i++)
{
if (trackletCand[j][0] < trackletCand[i][0])
{
// swap j & i
tmp = trackletCand[j][1];
trackletCand[j][1] = trackletCand[i][1];
trackletCand[i][1] = tmp;
tmp = trackletCand[j][0];
trackletCand[j][0] = trackletCand[i][0];
trackletCand[i][0] = tmp;
}
}
}
for (i = 0; i < ntracks; i++) // CPUs with tracklets.
fFitPtr[i] = trackletCand[i][0]; // pointer to the left channel with tracklet for CPU[i]
for (i = ntracks; i < 4; i++) // CPUs without tracklets
fFitPtr[i] = 31; // pointer to the left channel with tracklet for CPU[i] = 31 (invalid)
AliDebug(10,Form("found %i tracklet candidates\n", ntracks));
for (i = 0; i < 4; i++)
AliDebug(10,Form("fitPtr[%i]: %i\n", i, fFitPtr[i]));
}
void AliTRDmcmSim::FitTracklet()
{
// Perform the actual tracklet fit based on the fit sums
// which have been filled in the fit registers.
// parameters in fitred.asm (fit program)
Int_t decPlaces = 5;
Int_t rndAdd = 0;
if (decPlaces > 1)
rndAdd = (1 << (decPlaces-1)) + 1;
else if (decPlaces == 1)
rndAdd = 1;
Int_t ndriftDp = 5; // decimal places for drift time
Long64_t shift = ((Long64_t) 1 << 32);
// calculated in fitred.asm
Int_t padrow = ((fRobPos >> 1) << 2) | (fMcmPos >> 2);
Int_t yoffs = (((((fRobPos & 0x1) << 2) + (fMcmPos & 0x3)) * 18) << 8) -
((18*4*2 - 18*2 - 1) << 7);
yoffs = yoffs << decPlaces; // holds position of ADC channel 1
Int_t layer = fDetector % 6;
UInt_t scaleY = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 160.0e-4) * shift);
UInt_t scaleD = (UInt_t) ((0.635 + 0.03 * layer)/(256.0 * 140.0e-4) * shift);
// previously taken from geometry:
// UInt_t scaleYold = (UInt_t) (shift * (pp->GetWidthIPad() / (256 * 160e-4)));
// UInt_t scaleDold = (UInt_t) (shift * (pp->GetWidthIPad() / (256 * 140e-4)));
// should come from trapConfig (DMEM)
AliTRDpadPlane *pp = fGeo->GetPadPlane(fDetector);
Float_t scaleSlope = (256 / pp->GetWidthIPad()) * (1 << decPlaces); // only used for calculation of corrections and cut
Int_t ndrift = 20 << ndriftDp; //??? value in simulation?
Int_t deflCorr = (Int_t) (TMath::Tan(fCommonParam->GetOmegaTau(fCal->GetVdriftAverage(fDetector))) * fGeo->CdrHght() * scaleSlope); // -370;
Int_t tiltCorr = (Int_t) (pp->GetRowPos(padrow) / fGeo->GetTime0(fDetector % 6) * fGeo->CdrHght() * scaleSlope *
TMath::Tan(pp->GetTiltingAngle() / 180. * TMath::Pi()));
// printf("vdrift av.: %f\n", fCal->GetVdriftAverage(fDetector));
// printf("chamber height: %f\n", fGeo->CdrHght());
// printf("omega tau: %f\n", fCommonParam->GetOmegaTau(fCal->GetVdriftAverage(fDetector)));
// printf("deflection correction: %i\n", deflCorr);
Float_t ptcut = 2.3;
AliMagF* fld = (AliMagF *) TGeoGlobalMagField::Instance()->GetField();
Double_t bz = 0;
if (fld) {
bz = 0.1 * fld->SolenoidField(); // kGauss -> Tesla
}
// printf("Bz: %f\n", bz);
Float_t x0 = fGeo->GetTime0(fDetector % 6);
Float_t y0 = pp->GetColPos(fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 10));
Float_t alphaMax = TMath::ASin( (TMath::Sqrt(TMath::Power(x0/100., 2) + TMath::Power(y0/100., 2)) *
0.3 * TMath::Abs(bz) ) / (2 * ptcut));
// printf("alpha max: %f\n", alphaMax * 180/TMath::Pi());
Int_t minslope = -1 * (Int_t) (fGeo->CdrHght() * TMath::Tan(TMath::ATan(y0/x0) + alphaMax) / 140.e-4);
Int_t maxslope = -1 * (Int_t) (fGeo->CdrHght() * TMath::Tan(TMath::ATan(y0/x0) - alphaMax) / 140.e-4);
// local variables for calculation
Long64_t mult, temp, denom; //???
UInt_t q0, q1, qTotal; // charges in the two windows and total charge
UShort_t nHits; // number of hits
Int_t slope, offset; // slope and offset of the tracklet
Int_t sumX, sumY, sumXY, sumX2; // fit sums from fit registers
//int32_t SumY2; // not used in the current TRAP program
FitReg_t *fit0, *fit1; // pointers to relevant fit registers
// const uint32_t OneDivN[32] = { // 2**31/N : exactly like in the TRAP, the simple division here gives the same result!
// 0x00000000, 0x80000000, 0x40000000, 0x2AAAAAA0, 0x20000000, 0x19999990, 0x15555550, 0x12492490,
// 0x10000000, 0x0E38E380, 0x0CCCCCC0, 0x0BA2E8B0, 0x0AAAAAA0, 0x09D89D80, 0x09249240, 0x08888880,
// 0x08000000, 0x07878780, 0x071C71C0, 0x06BCA1A0, 0x06666660, 0x06186180, 0x05D17450, 0x0590B210,
// 0x05555550, 0x051EB850, 0x04EC4EC0, 0x04BDA120, 0x04924920, 0x0469EE50, 0x04444440, 0x04210840};
for (Int_t cpu = 0; cpu < 4; cpu++) {
if (fFitPtr[cpu] == 31)
{
fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker();
}
else
{
fit0 = &fFitReg[fFitPtr[cpu] ];
fit1 = &fFitReg[fFitPtr[cpu]+1]; // next channel
mult = 1;
mult = mult << (32 + decPlaces);
mult = -mult;
// Merging
nHits = fit0->fNhits + fit1->fNhits; // number of hits
sumX = fit0->fSumX + fit1->fSumX;
sumX2 = fit0->fSumX2 + fit1->fSumX2;
denom = nHits*sumX2 - sumX*sumX;
mult = mult / denom; // exactly like in the TRAP program
q0 = fit0->fQ0 + fit1->fQ0;
q1 = fit0->fQ1 + fit1->fQ1;
sumY = fit0->fSumY + fit1->fSumY + 256*fit1->fNhits;
sumXY = fit0->fSumXY + fit1->fSumXY + 256*fit1->fSumX;
slope = nHits*sumXY - sumX * sumY;
AliDebug(5, Form("slope from fitreg: %i", slope));
offset = sumX2*sumY - sumX * sumXY;
temp = mult * slope;
slope = temp >> 32; // take the upper 32 bits
slope = -slope;
temp = mult * offset;
offset = temp >> 32; // take the upper 32 bits
offset = offset + yoffs;
AliDebug(5, Form("slope: %i, slope * ndrift: %i, deflCorr: %i, tiltCorr: %i", slope, slope * ndrift, deflCorr, tiltCorr));
slope = ((slope * ndrift) >> ndriftDp) + deflCorr + tiltCorr;
offset = offset - (fFitPtr[cpu] << (8 + decPlaces));
AliDebug(5, Form("Det: %3i, ROB: %i, MCM: %2i: deflection: %i, min: %i, max: %i", fDetector, fRobPos, fMcmPos, slope, minslope, maxslope));
temp = slope;
temp = temp * scaleD;
slope = (temp >> 32);
AliDebug(5, Form("slope after scaling: %i", slope));
temp = offset;
temp = temp * scaleY;
offset = (temp >> 32);
// rounding, like in the TRAP
slope = (slope + rndAdd) >> decPlaces;
AliDebug(5, Form("slope after shifting: %i", slope));
offset = (offset + rndAdd) >> decPlaces;
Bool_t rejected = kFALSE;
if ((slope < minslope) || (slope > maxslope))
rejected = kTRUE;
if (rejected && GetApplyCut())
{
fMCMT[cpu] = 0x10001000; //??? AliTRDfeeParam::GetTrackletEndmarker();
}
else
{
if (slope > 63 || slope < -64) { // wrapping in TRAP!
AliError(Form("Overflow in slope: %i, tracklet discarded!", slope));
fMCMT[cpu] = 0x10001000;
continue;
}
slope = slope & 0x7F; // 7 bit
if (offset > 0xfff || offset < -0xfff)
AliWarning("Overflow in offset");
offset = offset & 0x1FFF; // 13 bit
Float_t length = TMath::Sqrt(1 + (pp->GetRowPos(padrow) * pp->GetRowPos(padrow) +
(fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 10) * pp->GetWidthIPad() *
fFeeParam->GetPadColFromADC(fRobPos, fMcmPos, 10) * pp->GetWidthIPad())) /
(fGeo->GetTime0(fDetector % 6)*fGeo->GetTime0(fDetector % 6)));
// qTotal = (q1 / nHits) >> 1;
qTotal = GetPID(q0/length/fgChargeNorm, q1/length/fgChargeNorm);
if (qTotal > 0xff)
AliWarning("Overflow in charge");
qTotal = qTotal & 0xFF; // 8 bit, exactly like in the TRAP program
// assemble and store the tracklet word
fMCMT[cpu] = (qTotal << 24) | (padrow << 20) | (slope << 13) | offset;
// calculate MC label
Int_t mcLabel = -1;
Int_t nHits0 = 0;
Int_t nHits1 = 0;
if (fDigitsManager) {
Int_t label[30] = {0}; // up to 30 different labels possible
Int_t count[30] = {0};
Int_t maxIdx = -1;
Int_t maxCount = 0;
Int_t nLabels = 0;
for (Int_t iHit = 0; iHit < fNHits; iHit++) {
if ((fHits[iHit].fChannel - fFitPtr[cpu] < 0) ||
(fHits[iHit].fChannel - fFitPtr[cpu] > 1))
continue;
// counting contributing hits
if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS0) &&
fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE0))
nHits0++;
if (fHits[iHit].fTimebin >= fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQS1) &&
fHits[iHit].fTimebin < fTrapConfig->GetTrapReg(AliTRDtrapConfig::kTPQE1))
nHits1++;
Int_t currLabel = fHits[iHit].fLabel;
for (Int_t iLabel = 0; iLabel < nLabels; iLabel++) {
if (currLabel == label[iLabel]) {
count[iLabel]++;
if (count[iLabel] > maxCount) {
maxCount = count[iLabel];
maxIdx = iLabel;
}
currLabel = 0;
break;
}
}
if (currLabel > 0) {
label[nLabels++] = currLabel;
}
}
if (maxIdx >= 0)
mcLabel = label[maxIdx];
}
new ((*fTrackletArray)[fTrackletArray->GetEntriesFast()]) AliTRDtrackletMCM((UInt_t) fMCMT[cpu], fDetector*2 + fRobPos%2, fRobPos, fMcmPos);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetLabel(mcLabel);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits(fit0->fNhits + fit1->fNhits);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits0(nHits0);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetNHits1(nHits1);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ0(q0);
((AliTRDtrackletMCM*) (*fTrackletArray)[fTrackletArray->GetEntriesFast()-1])->SetQ1(q1);
}
}
}
}
Int_t AliTRDmcmSim::GetPID(Float_t q0, Float_t q1)
{
// get PID from accumulated charges q0 and q1
Int_t binQ0 = (Int_t) (q0 * fgPidNBinsQ0) + 1;
Int_t binQ1 = (Int_t) (q1 * fgPidNBinsQ1) + 1;
binQ0 = binQ0 >= fgPidNBinsQ0 ? fgPidNBinsQ0-1 : binQ0;
binQ1 = binQ1 >= fgPidNBinsQ0 ? fgPidNBinsQ0-1 : binQ1;
return fgPidLut[binQ0*fgPidNBinsQ1+binQ1];
}
void AliTRDmcmSim::SetPIDlut(Int_t *lut, Int_t nbinsq0, Int_t nbinsq1)
{
// set a user-defined PID LUT
if (fgPidLutDelete)
delete [] fgPidLut;
fgPidLutDelete = kFALSE;
fgPidLut = lut;
fgPidNBinsQ0 = nbinsq0;
fgPidNBinsQ1 = nbinsq1;
}
void AliTRDmcmSim::SetPIDlut(TH2F *lut)
{
// set a user-defined PID LUT from a 2D histogram
if (fgPidLutDelete)
delete [] fgPidLut;
fgPidNBinsQ0 = lut->GetNbinsX();
fgPidNBinsQ1 = lut->GetNbinsY();
fgPidLut = new Int_t[fgPidNBinsQ0*fgPidNBinsQ1];
for (Int_t ix = 0; ix < fgPidNBinsQ0; ix++) {
for (Int_t iy = 0; iy < fgPidNBinsQ1; iy++) {
fgPidLut[ix*fgPidNBinsQ1 + iy] = (Int_t) (256. * lut->GetBinContent(ix, iy));
}
}
fgPidLutDelete = kTRUE;
}
void AliTRDmcmSim::SetPIDlutDefault()
{
// use the default PID LUT
if (fgPidLutDelete )
delete [] fgPidLut;
fgPidLutDelete = kFALSE;
fgPidLut = *fgPidLutDefault;
fgPidNBinsQ0 = 40;
fgPidNBinsQ1 = 50;
}
void AliTRDmcmSim::Tracklet()
{
// Run the tracklet calculation by calling sequentially:
// CalcFitreg(); TrackletSelection(); FitTracklet()
// and store the tracklets
if (!fInitialized) {
AliError("Called uninitialized! Nothing done!");
return;
}
fTrackletArray->Delete();
CalcFitreg();
if (fNHits == 0)
return;
TrackletSelection();
FitTracklet();
}
Bool_t AliTRDmcmSim::StoreTracklets()
{
// store the found tracklets via the loader
if (fTrackletArray->GetEntriesFast() == 0)
return kTRUE;
AliRunLoader *rl = AliRunLoader::Instance();
AliDataLoader *dl = 0x0;
if (rl)
dl = rl->GetLoader("TRDLoader")->GetDataLoader("tracklets");
if (!dl) {
AliError("Could not get the tracklets data loader!");
return kFALSE;
}
TTree *trackletTree = dl->Tree();
if (!trackletTree) {
dl->MakeTree();
trackletTree = dl->Tree();
}
AliTRDtrackletMCM *trkl = 0x0;
TBranch *trkbranch = trackletTree->GetBranch("mcmtrklbranch");
if (!trkbranch)
trkbranch = trackletTree->Branch("mcmtrklbranch", "AliTRDtrackletMCM", &trkl, 32000);
for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) {
trkl = ((AliTRDtrackletMCM*) (*fTrackletArray)[iTracklet]);
trkbranch->SetAddress(&trkl);
// printf("filling tracklet 0x%08x\n", trkl->GetTrackletWord());
trkbranch->Fill();
}
dl->WriteData("OVERWRITE");
return kTRUE;
}
void AliTRDmcmSim::WriteData(AliTRDarrayADC *digits)
{
// write back the processed data configured by EBSF
// EBSF = 1: unfiltered data; EBSF = 0: filtered data
// zero-suppressed valued are written as -1 to digits
if (!fInitialized) {
AliError("Called uninitialized! Nothing done!");
return;
}
// Int_t firstAdc = 0;
// Int_t lastAdc = fNADC - 1;
//
// while (GetCol(firstAdc) < 0)
// firstAdc++;
//
// while (GetCol(lastAdc) < 0)
// lastAdc--;
Int_t offset = (fMcmPos % 4) * 21 + (fRobPos % 2) * 84;
if (fTrapConfig->GetTrapReg(AliTRDtrapConfig::kEBSF) != 0) // store unfiltered data
{
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
if (fZSM1Dim[iAdc] == 1) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
digits->SetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin, -1);
// printf("suppressed: %i, %i, %i, %i, now: %i\n", fDetector, GetRow(), GetCol(iAdc), iTimeBin,
// digits->GetData(GetRow(), GetCol(iAdc), iTimeBin));
}
}
}
}
else {
for (Int_t iAdc = 0; iAdc < fNADC; iAdc++) {
if (fZSM1Dim[iAdc] == 0) {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
digits->SetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin, (fADCF[iAdc][iTimeBin] >> fgkAddDigits) - fgAddBaseline);
}
}
else {
for (Int_t iTimeBin = 0; iTimeBin < fNTimeBin; iTimeBin++) {
digits->SetDataByAdcCol(GetRow(), 20-iAdc + offset, iTimeBin, -1);
// printf("suppressed: %i, %i, %i, %i\n", fDetector, GetRow(), GetCol(iAdc), iTimeBin);
}
}
}
}
}
// help functions, to be cleaned up
UInt_t AliTRDmcmSim::AddUintClipping(UInt_t a, UInt_t b, UInt_t nbits) const
{
//
// This function adds a and b (unsigned) and clips to
// the specified number of bits.
//
UInt_t sum = a + b;
if (nbits < 32)
{
UInt_t maxv = (1 << nbits) - 1;;
if (sum > maxv)
sum = maxv;
}
else
{
if ((sum < a) || (sum < b))
sum = 0xFFFFFFFF;
}
return sum;
}
void AliTRDmcmSim::Sort2(UShort_t idx1i, UShort_t idx2i, \
UShort_t val1i, UShort_t val2i, \
UShort_t *idx1o, UShort_t *idx2o, \
UShort_t *val1o, UShort_t *val2o) const
{
// sorting for tracklet selection
if (val1i > val2i)
{
*idx1o = idx1i;
*idx2o = idx2i;
*val1o = val1i;
*val2o = val2i;
}
else
{
*idx1o = idx2i;
*idx2o = idx1i;
*val1o = val2i;
*val2o = val1i;
}
}
void AliTRDmcmSim::Sort3(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, \
UShort_t val1i, UShort_t val2i, UShort_t val3i, \
UShort_t *idx1o, UShort_t *idx2o, UShort_t *idx3o, \
UShort_t *val1o, UShort_t *val2o, UShort_t *val3o)
{
// sorting for tracklet selection
Int_t sel;
if (val1i > val2i) sel=4; else sel=0;
if (val2i > val3i) sel=sel + 2;
if (val3i > val1i) sel=sel + 1;
//printf("input channels %d %d %d, charges %d %d %d sel=%d\n",idx1i, idx2i, idx3i, val1i, val2i, val3i, sel);
switch(sel)
{
case 6 : // 1 > 2 > 3 => 1 2 3
case 0 : // 1 = 2 = 3 => 1 2 3 : in this case doesn't matter, but so is in hardware!
*idx1o = idx1i;
*idx2o = idx2i;
*idx3o = idx3i;
*val1o = val1i;
*val2o = val2i;
*val3o = val3i;
break;
case 4 : // 1 > 2, 2 <= 3, 3 <= 1 => 1 3 2
*idx1o = idx1i;
*idx2o = idx3i;
*idx3o = idx2i;
*val1o = val1i;
*val2o = val3i;
*val3o = val2i;
break;
case 2 : // 1 <= 2, 2 > 3, 3 <= 1 => 2 1 3
*idx1o = idx2i;
*idx2o = idx1i;
*idx3o = idx3i;
*val1o = val2i;
*val2o = val1i;
*val3o = val3i;
break;
case 3 : // 1 <= 2, 2 > 3, 3 > 1 => 2 3 1
*idx1o = idx2i;
*idx2o = idx3i;
*idx3o = idx1i;
*val1o = val2i;
*val2o = val3i;
*val3o = val1i;
break;
case 1 : // 1 <= 2, 2 <= 3, 3 > 1 => 3 2 1
*idx1o = idx3i;
*idx2o = idx2i;
*idx3o = idx1i;
*val1o = val3i;
*val2o = val2i;
*val3o = val1i;
break;
case 5 : // 1 > 2, 2 <= 3, 3 > 1 => 3 1 2
*idx1o = idx3i;
*idx2o = idx1i;
*idx3o = idx2i;
*val1o = val3i;
*val2o = val1i;
*val3o = val2i;
break;
default: // the rest should NEVER happen!
AliError("ERROR in Sort3!!!\n");
break;
}
// printf("output channels %d %d %d, charges %d %d %d \n",*idx1o, *idx2o, *idx3o, *val1o, *val2o, *val3o);
}
void AliTRDmcmSim::Sort6To4(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \
UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \
UShort_t *idx1o, UShort_t *idx2o, UShort_t *idx3o, UShort_t *idx4o, \
UShort_t *val1o, UShort_t *val2o, UShort_t *val3o, UShort_t *val4o)
{
// sorting for tracklet selection
UShort_t idx21s, idx22s, idx23s, dummy;
UShort_t val21s, val22s, val23s;
UShort_t idx23as, idx23bs;
UShort_t val23as, val23bs;
Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i,
idx1o, &idx21s, &idx23as,
val1o, &val21s, &val23as);
Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i,
idx2o, &idx22s, &idx23bs,
val2o, &val22s, &val23bs);
Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, &dummy, &val23s, &dummy);
Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s,
idx3o, idx4o, &dummy,
val3o, val4o, &dummy);
}
void AliTRDmcmSim::Sort6To2Worst(UShort_t idx1i, UShort_t idx2i, UShort_t idx3i, UShort_t idx4i, UShort_t idx5i, UShort_t idx6i, \
UShort_t val1i, UShort_t val2i, UShort_t val3i, UShort_t val4i, UShort_t val5i, UShort_t val6i, \
UShort_t *idx5o, UShort_t *idx6o)
{
// sorting for tracklet selection
UShort_t idx21s, idx22s, idx23s, dummy1, dummy2, dummy3, dummy4, dummy5;
UShort_t val21s, val22s, val23s;
UShort_t idx23as, idx23bs;
UShort_t val23as, val23bs;
Sort3(idx1i, idx2i, idx3i, val1i, val2i, val3i,
&dummy1, &idx21s, &idx23as,
&dummy2, &val21s, &val23as);
Sort3(idx4i, idx5i, idx6i, val4i, val5i, val6i,
&dummy1, &idx22s, &idx23bs,
&dummy2, &val22s, &val23bs);
Sort2(idx23as, idx23bs, val23as, val23bs, &idx23s, idx5o, &val23s, &dummy1);
Sort3(idx21s, idx22s, idx23s, val21s, val22s, val23s,
&dummy1, &dummy2, idx6o,
&dummy3, &dummy4, &dummy5);
// printf("idx21s=%d, idx23as=%d, idx22s=%d, idx23bs=%d, idx5o=%d, idx6o=%d\n",
// idx21s, idx23as, idx22s, idx23bs, *idx5o, *idx6o);
}
|
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/osr/osr_render_widget_host_view.h"
#include <vector>
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/time/time.h"
#include "cc/output/copy_output_request.h"
#include "cc/scheduler/delay_based_time_source.h"
#include "components/display_compositor/gl_helper.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_frame_subscriber.h"
#include "content/browser/renderer_host/resize_lock.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/context_factory.h"
#include "media/base/video_frame.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_type.h"
#include "ui/events/latency_info.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/skbitmap_operations.h"
namespace atom {
namespace {
const float kDefaultScaleFactor = 1.0;
const int kFrameRetryLimit = 2;
#if !defined(OS_MACOSX)
const int kResizeLockTimeoutMs = 67;
class AtomResizeLock : public content::ResizeLock {
public:
AtomResizeLock(OffScreenRenderWidgetHostView* host,
const gfx::Size new_size,
bool defer_compositor_lock)
: ResizeLock(new_size, defer_compositor_lock),
host_(host),
cancelled_(false),
weak_ptr_factory_(this) {
DCHECK(host_);
host_->HoldResize();
content::BrowserThread::PostDelayedTask(content::BrowserThread::UI,
FROM_HERE, base::Bind(&AtomResizeLock::CancelLock,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kResizeLockTimeoutMs));
}
~AtomResizeLock() override {
CancelLock();
}
bool GrabDeferredLock() override {
return ResizeLock::GrabDeferredLock();
}
void UnlockCompositor() override {
ResizeLock::UnlockCompositor();
compositor_lock_ = NULL;
}
protected:
void LockCompositor() override {
ResizeLock::LockCompositor();
compositor_lock_ = host_->GetCompositor()->GetCompositorLock();
}
void CancelLock() {
if (cancelled_)
return;
cancelled_ = true;
UnlockCompositor();
host_->ReleaseResize();
}
private:
OffScreenRenderWidgetHostView* host_;
scoped_refptr<ui::CompositorLock> compositor_lock_;
bool cancelled_;
base::WeakPtrFactory<AtomResizeLock> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(AtomResizeLock);
};
#endif // !defined(OS_MACOSX)
} // namespace
class AtomCopyFrameGenerator {
public:
AtomCopyFrameGenerator(int frame_rate_threshold_ms,
OffScreenRenderWidgetHostView* view)
: frame_rate_threshold_ms_(frame_rate_threshold_ms),
view_(view),
frame_pending_(false),
frame_in_progress_(false),
frame_retry_count_(0),
weak_ptr_factory_(this) {
last_time_ = base::Time::Now();
}
void GenerateCopyFrame(
bool force_frame,
const gfx::Rect& damage_rect) {
if (force_frame && !frame_pending_)
frame_pending_ = true;
if (!frame_pending_)
return;
if (!damage_rect.IsEmpty())
pending_damage_rect_.Union(damage_rect);
if (frame_in_progress_)
return;
frame_in_progress_ = true;
const int64_t frame_rate_delta =
(base::TimeTicks::Now() - frame_start_time_).InMilliseconds();
if (frame_rate_delta < frame_rate_threshold_ms_) {
content::BrowserThread::PostDelayedTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&AtomCopyFrameGenerator::InternalGenerateCopyFrame,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(
frame_rate_threshold_ms_ - frame_rate_delta));
return;
}
InternalGenerateCopyFrame();
}
bool frame_pending() const { return frame_pending_; }
void set_frame_rate_threshold_ms(int frame_rate_threshold_ms) {
frame_rate_threshold_ms_ = frame_rate_threshold_ms;
}
private:
void InternalGenerateCopyFrame() {
frame_pending_ = false;
frame_start_time_ = base::TimeTicks::Now();
if (!view_->render_widget_host())
return;
const gfx::Rect damage_rect = pending_damage_rect_;
pending_damage_rect_.SetRect(0, 0, 0, 0);
std::unique_ptr<cc::CopyOutputRequest> request =
cc::CopyOutputRequest::CreateRequest(base::Bind(
&AtomCopyFrameGenerator::CopyFromCompositingSurfaceHasResult,
weak_ptr_factory_.GetWeakPtr(),
damage_rect));
request->set_area(gfx::Rect(view_->GetPhysicalBackingSize()));
view_->GetRootLayer()->RequestCopyOfOutput(std::move(request));
}
void CopyFromCompositingSurfaceHasResult(
const gfx::Rect& damage_rect,
std::unique_ptr<cc::CopyOutputResult> result) {
if (result->IsEmpty() || result->size().IsEmpty() ||
!view_->render_widget_host()) {
OnCopyFrameCaptureFailure(damage_rect);
return;
}
if (result->HasTexture()) {
PrepareTextureCopyOutputResult(damage_rect, std::move(result));
return;
}
DCHECK(result->HasBitmap());
PrepareBitmapCopyOutputResult(damage_rect, std::move(result));
}
void PrepareTextureCopyOutputResult(
const gfx::Rect& damage_rect,
std::unique_ptr<cc::CopyOutputResult> result) {
DCHECK(result->HasTexture());
base::ScopedClosureRunner scoped_callback_runner(
base::Bind(&AtomCopyFrameGenerator::OnCopyFrameCaptureFailure,
weak_ptr_factory_.GetWeakPtr(),
damage_rect));
const gfx::Size& result_size = result->size();
SkIRect bitmap_size;
if (bitmap_)
bitmap_->getBounds(&bitmap_size);
if (!bitmap_ ||
bitmap_size.width() != result_size.width() ||
bitmap_size.height() != result_size.height()) {
bitmap_.reset(new SkBitmap);
bitmap_->allocN32Pixels(result_size.width(),
result_size.height(),
true);
if (bitmap_->drawsNothing())
return;
}
content::ImageTransportFactory* factory =
content::ImageTransportFactory::GetInstance();
display_compositor::GLHelper* gl_helper = factory->GetGLHelper();
if (!gl_helper)
return;
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock(
new SkAutoLockPixels(*bitmap_));
uint8_t* pixels = static_cast<uint8_t*>(bitmap_->getPixels());
cc::TextureMailbox texture_mailbox;
std::unique_ptr<cc::SingleReleaseCallback> release_callback;
result->TakeTexture(&texture_mailbox, &release_callback);
DCHECK(texture_mailbox.IsTexture());
if (!texture_mailbox.IsTexture())
return;
ignore_result(scoped_callback_runner.Release());
gl_helper->CropScaleReadbackAndCleanMailbox(
texture_mailbox.mailbox(),
texture_mailbox.sync_token(),
result_size,
gfx::Rect(result_size),
result_size,
pixels,
kN32_SkColorType,
base::Bind(
&AtomCopyFrameGenerator::CopyFromCompositingSurfaceFinishedProxy,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(&release_callback),
damage_rect,
base::Passed(&bitmap_),
base::Passed(&bitmap_pixels_lock)),
display_compositor::GLHelper::SCALER_QUALITY_FAST);
}
static void CopyFromCompositingSurfaceFinishedProxy(
base::WeakPtr<AtomCopyFrameGenerator> generator,
std::unique_ptr<cc::SingleReleaseCallback> release_callback,
const gfx::Rect& damage_rect,
std::unique_ptr<SkBitmap> bitmap,
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock,
bool result) {
gpu::SyncToken sync_token;
if (result) {
display_compositor::GLHelper* gl_helper =
content::ImageTransportFactory::GetInstance()->GetGLHelper();
if (gl_helper)
gl_helper->GenerateSyncToken(&sync_token);
}
const bool lost_resource = !sync_token.HasData();
release_callback->Run(sync_token, lost_resource);
if (generator) {
generator->CopyFromCompositingSurfaceFinished(
damage_rect, std::move(bitmap), std::move(bitmap_pixels_lock),
result);
} else {
bitmap_pixels_lock.reset();
bitmap.reset();
}
}
void CopyFromCompositingSurfaceFinished(
const gfx::Rect& damage_rect,
std::unique_ptr<SkBitmap> bitmap,
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock,
bool result) {
DCHECK(!bitmap_);
bitmap_ = std::move(bitmap);
if (result) {
OnCopyFrameCaptureSuccess(damage_rect, *bitmap_,
std::move(bitmap_pixels_lock));
} else {
bitmap_pixels_lock.reset();
OnCopyFrameCaptureFailure(damage_rect);
}
}
void PrepareBitmapCopyOutputResult(
const gfx::Rect& damage_rect,
std::unique_ptr<cc::CopyOutputResult> result) {
DCHECK(result->HasBitmap());
std::unique_ptr<SkBitmap> source = result->TakeBitmap();
DCHECK(source);
if (source) {
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock(
new SkAutoLockPixels(*source));
OnCopyFrameCaptureSuccess(damage_rect, *source,
std::move(bitmap_pixels_lock));
} else {
OnCopyFrameCaptureFailure(damage_rect);
}
}
void OnCopyFrameCaptureFailure(
const gfx::Rect& damage_rect) {
pending_damage_rect_.Union(damage_rect);
const bool force_frame = (++frame_retry_count_ <= kFrameRetryLimit);
OnCopyFrameCaptureCompletion(force_frame);
}
void OnCopyFrameCaptureSuccess(
const gfx::Rect& damage_rect,
const SkBitmap& bitmap,
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock) {
view_->OnPaint(damage_rect, bitmap);
if (frame_retry_count_ > 0)
frame_retry_count_ = 0;
OnCopyFrameCaptureCompletion(false);
}
void OnCopyFrameCaptureCompletion(bool force_frame) {
frame_in_progress_ = false;
if (frame_pending_) {
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&AtomCopyFrameGenerator::GenerateCopyFrame,
weak_ptr_factory_.GetWeakPtr(),
force_frame,
gfx::Rect()));
}
}
int frame_rate_threshold_ms_;
OffScreenRenderWidgetHostView* view_;
base::Time last_time_;
base::TimeTicks frame_start_time_;
bool frame_pending_;
bool frame_in_progress_;
int frame_retry_count_;
std::unique_ptr<SkBitmap> bitmap_;
gfx::Rect pending_damage_rect_;
base::WeakPtrFactory<AtomCopyFrameGenerator> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(AtomCopyFrameGenerator);
};
class AtomBeginFrameTimer : public cc::DelayBasedTimeSourceClient {
public:
AtomBeginFrameTimer(int frame_rate_threshold_ms,
const base::Closure& callback)
: callback_(callback) {
time_source_.reset(new cc::DelayBasedTimeSource(
content::BrowserThread::GetTaskRunnerForThread(
content::BrowserThread::UI).get()));
time_source_->SetClient(this);
}
void SetActive(bool active) {
time_source_->SetActive(active);
}
bool IsActive() const {
return time_source_->Active();
}
void SetFrameRateThresholdMs(int frame_rate_threshold_ms) {
time_source_->SetTimebaseAndInterval(
base::TimeTicks::Now(),
base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms));
}
private:
void OnTimerTick() override {
callback_.Run();
}
const base::Closure callback_;
std::unique_ptr<cc::DelayBasedTimeSource> time_source_;
DISALLOW_COPY_AND_ASSIGN(AtomBeginFrameTimer);
};
OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView(
bool transparent,
const OnPaintCallback& callback,
content::RenderWidgetHost* host,
OffScreenRenderWidgetHostView* parent_host_view,
NativeWindow* native_window)
: render_widget_host_(content::RenderWidgetHostImpl::From(host)),
parent_host_view_(parent_host_view),
popup_host_view_(nullptr),
child_host_view_(nullptr),
native_window_(native_window),
software_output_device_(nullptr),
transparent_(transparent),
callback_(callback),
parent_callback_(nullptr),
frame_rate_(60),
frame_rate_threshold_ms_(0),
last_time_(base::Time::Now()),
scale_factor_(kDefaultScaleFactor),
size_(native_window->GetSize()),
painting_(true),
is_showing_(!render_widget_host_->is_hidden()),
is_destroyed_(false),
popup_position_(gfx::Rect()),
hold_resize_(false),
pending_resize_(false),
weak_ptr_factory_(this) {
DCHECK(render_widget_host_);
#if !defined(OS_MACOSX)
delegated_frame_host_ = base::MakeUnique<content::DelegatedFrameHost>(
AllocateFrameSinkId(is_guest_view_hack), this);
root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR));
#endif
#if defined(OS_MACOSX)
CreatePlatformWidget(is_guest_view_hack);
#else
// On macOS the ui::Compositor is created/owned by the platform view.
content::ImageTransportFactory* factory =
content::ImageTransportFactory::GetInstance();
ui::ContextFactoryPrivate* context_factory_private =
factory->GetContextFactoryPrivate();
compositor_.reset(
new ui::Compositor(context_factory_private->AllocateFrameSinkId(),
content::GetContextFactory(), context_factory_private,
base::ThreadTaskRunnerHandle::Get()));
compositor_->SetAcceleratedWidget(native_window_->GetAcceleratedWidget());
compositor_->SetRootLayer(root_layer_.get());
#endif
GetCompositor()->SetDelegate(this);
native_window_->AddObserver(this);
ResizeRootLayer();
render_widget_host_->SetView(this);
InstallTransparency();
}
OffScreenRenderWidgetHostView::~OffScreenRenderWidgetHostView() {
if (native_window_)
native_window_->RemoveObserver(this);
#if defined(OS_MACOSX)
if (is_showing_)
browser_compositor_->SetRenderWidgetHostIsHidden(true);
#else
// Marking the DelegatedFrameHost as removed from the window hierarchy is
// necessary to remove all connections to its old ui::Compositor.
if (is_showing_)
delegated_frame_host_->WasHidden();
delegated_frame_host_->ResetCompositor();
#endif
if (copy_frame_generator_.get())
copy_frame_generator_.reset(NULL);
#if defined(OS_MACOSX)
DestroyPlatformWidget();
#else
delegated_frame_host_.reset(NULL);
compositor_.reset(NULL);
root_layer_.reset(NULL);
#endif
}
void OffScreenRenderWidgetHostView::OnWindowResize() {
// In offscreen mode call RenderWidgetHostView's SetSize explicitly
auto size = native_window_->GetSize();
SetSize(size);
}
void OffScreenRenderWidgetHostView::OnWindowClosed() {
native_window_->RemoveObserver(this);
native_window_ = nullptr;
}
void OffScreenRenderWidgetHostView::OnBeginFrameTimerTick() {
const base::TimeTicks frame_time = base::TimeTicks::Now();
const base::TimeDelta vsync_period =
base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms_);
SendBeginFrame(frame_time, vsync_period);
}
void OffScreenRenderWidgetHostView::SendBeginFrame(
base::TimeTicks frame_time, base::TimeDelta vsync_period) {
base::TimeTicks display_time = frame_time + vsync_period;
base::TimeDelta estimated_browser_composite_time =
base::TimeDelta::FromMicroseconds(
(1.0f * base::Time::kMicrosecondsPerSecond) / (3.0f * 60));
base::TimeTicks deadline = display_time - estimated_browser_composite_time;
const cc::BeginFrameArgs& begin_frame_args =
cc::BeginFrameArgs::Create(BEGINFRAME_FROM_HERE,
begin_frame_source_.source_id(),
begin_frame_number_, frame_time, deadline,
vsync_period, cc::BeginFrameArgs::NORMAL);
DCHECK(begin_frame_args.IsValid());
begin_frame_number_++;
render_widget_host_->Send(new ViewMsg_BeginFrame(
render_widget_host_->GetRoutingID(),
begin_frame_args));
}
bool OffScreenRenderWidgetHostView::OnMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(OffScreenRenderWidgetHostView, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames,
SetNeedsBeginFrames)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (!handled)
return content::RenderWidgetHostViewBase::OnMessageReceived(message);
return handled;
}
void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) {
DCHECK(parent_host_view_);
if (parent_host_view_->child_host_view_) {
parent_host_view_->child_host_view_->CancelWidget();
}
parent_host_view_->set_child_host_view(this);
parent_host_view_->Hide();
ResizeRootLayer();
Show();
}
content::RenderWidgetHost* OffScreenRenderWidgetHostView::GetRenderWidgetHost()
const {
return render_widget_host_;
}
void OffScreenRenderWidgetHostView::SetSize(const gfx::Size& size) {
size_ = size;
WasResized();
}
void OffScreenRenderWidgetHostView::SetBounds(const gfx::Rect& new_bounds) {
SetSize(new_bounds.size());
}
gfx::Vector2dF OffScreenRenderWidgetHostView::GetLastScrollOffset() const {
return last_scroll_offset_;
}
gfx::NativeView OffScreenRenderWidgetHostView::GetNativeView() const {
return gfx::NativeView();
}
gfx::NativeViewAccessible
OffScreenRenderWidgetHostView::GetNativeViewAccessible() {
return gfx::NativeViewAccessible();
}
ui::TextInputClient* OffScreenRenderWidgetHostView::GetTextInputClient() {
return nullptr;
}
void OffScreenRenderWidgetHostView::Focus() {
}
bool OffScreenRenderWidgetHostView::HasFocus() const {
return false;
}
bool OffScreenRenderWidgetHostView::IsSurfaceAvailableForCopy() const {
return GetDelegatedFrameHost()->CanCopyFromCompositingSurface();
}
void OffScreenRenderWidgetHostView::Show() {
if (is_showing_)
return;
is_showing_ = true;
#if defined(OS_MACOSX)
browser_compositor_->SetRenderWidgetHostIsHidden(false);
#else
delegated_frame_host_->SetCompositor(compositor_.get());
delegated_frame_host_->WasShown(ui::LatencyInfo());
#endif
if (render_widget_host_)
render_widget_host_->WasShown(ui::LatencyInfo());
}
void OffScreenRenderWidgetHostView::Hide() {
if (!is_showing_)
return;
if (render_widget_host_)
render_widget_host_->WasHidden();
#if defined(OS_MACOSX)
browser_compositor_->SetRenderWidgetHostIsHidden(true);
#else
GetDelegatedFrameHost()->WasHidden();
GetDelegatedFrameHost()->ResetCompositor();
#endif
is_showing_ = false;
}
bool OffScreenRenderWidgetHostView::IsShowing() {
return is_showing_;
}
gfx::Rect OffScreenRenderWidgetHostView::GetViewBounds() const {
if (IsPopupWidget())
return popup_position_;
return gfx::Rect(size_);
}
void OffScreenRenderWidgetHostView::SetBackgroundColor(SkColor color) {
if (transparent_)
color = SkColorSetARGB(SK_AlphaTRANSPARENT, 0, 0, 0);
content::RenderWidgetHostViewBase::SetBackgroundColor(color);
const bool opaque = !transparent_ && GetBackgroundOpaque();
if (render_widget_host_)
render_widget_host_->SetBackgroundOpaque(opaque);
}
gfx::Size OffScreenRenderWidgetHostView::GetVisibleViewportSize() const {
return size_;
}
void OffScreenRenderWidgetHostView::SetInsets(const gfx::Insets& insets) {
}
bool OffScreenRenderWidgetHostView::LockMouse() {
return false;
}
void OffScreenRenderWidgetHostView::UnlockMouse() {
}
void OffScreenRenderWidgetHostView::OnSwapCompositorFrame(
uint32_t output_surface_id,
cc::CompositorFrame frame) {
TRACE_EVENT0("electron",
"OffScreenRenderWidgetHostView::OnSwapCompositorFrame");
if (frame.metadata.root_scroll_offset != last_scroll_offset_) {
last_scroll_offset_ = frame.metadata.root_scroll_offset;
}
if (!frame.render_pass_list.empty()) {
if (software_output_device_) {
if (!begin_frame_timer_.get() || IsPopupWidget()) {
software_output_device_->SetActive(painting_);
}
// The compositor will draw directly to the SoftwareOutputDevice which
// then calls OnPaint.
// We would normally call BrowserCompositorMac::SwapCompositorFrame on
// macOS, however it contains compositor resize logic that we don't want.
// Consequently we instead call the SwapDelegatedFrame method directly.
GetDelegatedFrameHost()->SwapDelegatedFrame(output_surface_id,
std::move(frame));
} else {
if (!copy_frame_generator_.get()) {
copy_frame_generator_.reset(
new AtomCopyFrameGenerator(frame_rate_threshold_ms_, this));
}
// Determine the damage rectangle for the current frame. This is the same
// calculation that SwapDelegatedFrame uses.
cc::RenderPass* root_pass = frame.render_pass_list.back().get();
gfx::Size frame_size = root_pass->output_rect.size();
gfx::Rect damage_rect =
gfx::ToEnclosingRect(gfx::RectF(root_pass->damage_rect));
damage_rect.Intersect(gfx::Rect(frame_size));
// We would normally call BrowserCompositorMac::SwapCompositorFrame on
// macOS, however it contains compositor resize logic that we don't want.
// Consequently we instead call the SwapDelegatedFrame method directly.
GetDelegatedFrameHost()->SwapDelegatedFrame(output_surface_id,
std::move(frame));
// Request a copy of the last compositor frame which will eventually call
// OnPaint asynchronously.
copy_frame_generator_->GenerateCopyFrame(true, damage_rect);
}
}
}
void OffScreenRenderWidgetHostView::ClearCompositorFrame() {
GetDelegatedFrameHost()->ClearDelegatedFrame();
}
void OffScreenRenderWidgetHostView::InitAsPopup(
content::RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
DCHECK_EQ(parent_host_view_, parent_host_view);
if (parent_host_view_->popup_host_view_) {
parent_host_view_->popup_host_view_->CancelWidget();
}
parent_host_view_->set_popup_host_view(this);
parent_host_view_->popup_bitmap_.reset(new SkBitmap);
parent_callback_ = base::Bind(&OffScreenRenderWidgetHostView::OnPopupPaint,
parent_host_view_->weak_ptr_factory_.GetWeakPtr());
popup_position_ = pos;
ResizeRootLayer();
Show();
}
void OffScreenRenderWidgetHostView::InitAsFullscreen(
content::RenderWidgetHostView *) {
}
void OffScreenRenderWidgetHostView::UpdateCursor(const content::WebCursor &) {
}
void OffScreenRenderWidgetHostView::SetIsLoading(bool loading) {
}
void OffScreenRenderWidgetHostView::TextInputStateChanged(
const content::TextInputState& params) {
}
void OffScreenRenderWidgetHostView::ImeCancelComposition() {
}
void OffScreenRenderWidgetHostView::RenderProcessGone(base::TerminationStatus,
int) {
Destroy();
}
void OffScreenRenderWidgetHostView::Destroy() {
if (!is_destroyed_) {
is_destroyed_ = true;
if (parent_host_view_ != NULL) {
CancelWidget();
} else {
if (popup_host_view_)
popup_host_view_->CancelWidget();
popup_bitmap_.reset();
if (child_host_view_)
child_host_view_->CancelWidget();
for (auto guest_host_view : guest_host_views_)
guest_host_view->CancelWidget();
Hide();
}
}
delete this;
}
void OffScreenRenderWidgetHostView::SetTooltipText(const base::string16 &) {
}
void OffScreenRenderWidgetHostView::SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params &) {
}
void OffScreenRenderWidgetHostView::CopyFromSurface(
const gfx::Rect& src_subrect,
const gfx::Size& dst_size,
const content::ReadbackRequestCallback& callback,
const SkColorType preferred_color_type) {
GetDelegatedFrameHost()->CopyFromCompositingSurface(
src_subrect, dst_size, callback, preferred_color_type);
}
void OffScreenRenderWidgetHostView::CopyFromSurfaceToVideoFrame(
const gfx::Rect& src_subrect,
scoped_refptr<media::VideoFrame> target,
const base::Callback<void(const gfx::Rect&, bool)>& callback) {
GetDelegatedFrameHost()->CopyFromCompositingSurfaceToVideoFrame(
src_subrect, target, callback);
}
void OffScreenRenderWidgetHostView::BeginFrameSubscription(
std::unique_ptr<content::RenderWidgetHostViewFrameSubscriber> subscriber) {
GetDelegatedFrameHost()->BeginFrameSubscription(std::move(subscriber));
}
void OffScreenRenderWidgetHostView::EndFrameSubscription() {
GetDelegatedFrameHost()->EndFrameSubscription();
}
void OffScreenRenderWidgetHostView::InitAsGuest(
content::RenderWidgetHostView* parent_host_view,
content::RenderWidgetHostViewGuest* guest_view) {
parent_host_view_->AddGuestHostView(this);
parent_host_view_->RegisterGuestViewFrameSwappedCallback(guest_view);
}
bool OffScreenRenderWidgetHostView::HasAcceleratedSurface(const gfx::Size &) {
return false;
}
gfx::Rect OffScreenRenderWidgetHostView::GetBoundsInRootWindow() {
return gfx::Rect(size_);
}
void OffScreenRenderWidgetHostView::ImeCompositionRangeChanged(
const gfx::Range &, const std::vector<gfx::Rect>&) {
}
gfx::Size OffScreenRenderWidgetHostView::GetPhysicalBackingSize() const {
return gfx::ConvertSizeToPixel(scale_factor_, GetRequestedRendererSize());
}
gfx::Size OffScreenRenderWidgetHostView::GetRequestedRendererSize() const {
return GetDelegatedFrameHost()->GetRequestedRendererSize();
}
content::RenderWidgetHostViewBase*
OffScreenRenderWidgetHostView::CreateViewForWidget(
content::RenderWidgetHost* render_widget_host,
content::RenderWidgetHost* embedder_render_widget_host,
content::WebContentsView* web_contents_view) {
if (render_widget_host->GetView()) {
return static_cast<content::RenderWidgetHostViewBase*>(
render_widget_host->GetView());
}
OffScreenRenderWidgetHostView* embedder_host_view = nullptr;
if (embedder_render_widget_host) {
embedder_host_view = static_cast<OffScreenRenderWidgetHostView*>(
embedder_render_widget_host->GetView());
}
return new OffScreenRenderWidgetHostView(
transparent_,
callback_,
render_widget_host,
embedder_host_view,
native_window_);
}
#if !defined(OS_MACOSX)
ui::Layer* OffScreenRenderWidgetHostView::DelegatedFrameHostGetLayer() const {
return const_cast<ui::Layer*>(root_layer_.get());
}
bool OffScreenRenderWidgetHostView::DelegatedFrameHostIsVisible() const {
return !render_widget_host_->is_hidden();
}
SkColor OffScreenRenderWidgetHostView::DelegatedFrameHostGetGutterColor(
SkColor color) const {
if (render_widget_host_->delegate() &&
render_widget_host_->delegate()->IsFullscreenForCurrentTab()) {
return SK_ColorBLACK;
}
return color;
}
gfx::Size OffScreenRenderWidgetHostView::DelegatedFrameHostDesiredSizeInDIP()
const {
return GetRootLayer()->bounds().size();
}
bool OffScreenRenderWidgetHostView::DelegatedFrameCanCreateResizeLock() const {
return !render_widget_host_->auto_resize_enabled();
}
std::unique_ptr<content::ResizeLock>
OffScreenRenderWidgetHostView::DelegatedFrameHostCreateResizeLock(
bool defer_compositor_lock) {
return std::unique_ptr<content::ResizeLock>(new AtomResizeLock(
this,
DelegatedFrameHostDesiredSizeInDIP(),
defer_compositor_lock));
}
void OffScreenRenderWidgetHostView::DelegatedFrameHostResizeLockWasReleased() {
return render_widget_host_->WasResized();
}
void
OffScreenRenderWidgetHostView::DelegatedFrameHostSendReclaimCompositorResources(
int output_surface_id,
bool is_swap_ack,
const cc::ReturnedResourceArray& resources) {
render_widget_host_->Send(new ViewMsg_ReclaimCompositorResources(
render_widget_host_->GetRoutingID(), output_surface_id, is_swap_ack,
resources));
}
void OffScreenRenderWidgetHostView::SetBeginFrameSource(
cc::BeginFrameSource* source) {
}
#endif // !defined(OS_MACOSX)
bool OffScreenRenderWidgetHostView::TransformPointToLocalCoordSpace(
const gfx::Point& point,
const cc::SurfaceId& original_surface,
gfx::Point* transformed_point) {
// Transformations use physical pixels rather than DIP, so conversion
// is necessary.
gfx::Point point_in_pixels =
gfx::ConvertPointToPixel(scale_factor_, point);
if (!GetDelegatedFrameHost()->TransformPointToLocalCoordSpace(
point_in_pixels, original_surface, transformed_point)) {
return false;
}
*transformed_point =
gfx::ConvertPointToDIP(scale_factor_, *transformed_point);
return true;
}
bool OffScreenRenderWidgetHostView::TransformPointToCoordSpaceForView(
const gfx::Point& point,
RenderWidgetHostViewBase* target_view,
gfx::Point* transformed_point) {
if (target_view == this) {
*transformed_point = point;
return true;
}
// In TransformPointToLocalCoordSpace() there is a Point-to-Pixel conversion,
// but it is not necessary here because the final target view is responsible
// for converting before computing the final transform.
return GetDelegatedFrameHost()->TransformPointToCoordSpaceForView(
point, target_view, transformed_point);
}
void OffScreenRenderWidgetHostView::CancelWidget() {
if (render_widget_host_)
render_widget_host_->LostCapture();
Hide();
if (parent_host_view_) {
if (parent_host_view_->popup_host_view_ == this) {
parent_host_view_->set_popup_host_view(NULL);
parent_host_view_->popup_bitmap_.reset();
} else if (parent_host_view_->child_host_view_ == this) {
parent_host_view_->set_child_host_view(NULL);
parent_host_view_->Show();
} else {
parent_host_view_->RemoveGuestHostView(this);
}
parent_host_view_ = NULL;
}
if (render_widget_host_ && !is_destroyed_) {
is_destroyed_ = true;
// Results in a call to Destroy().
render_widget_host_->ShutdownAndDestroyWidget(true);
}
}
void OffScreenRenderWidgetHostView::AddGuestHostView(
OffScreenRenderWidgetHostView* guest_host) {
guest_host_views_.insert(guest_host);
}
void OffScreenRenderWidgetHostView::RemoveGuestHostView(
OffScreenRenderWidgetHostView* guest_host) {
guest_host_views_.erase(guest_host);
}
void OffScreenRenderWidgetHostView::RegisterGuestViewFrameSwappedCallback(
content::RenderWidgetHostViewGuest* guest_host_view) {
guest_host_view->RegisterFrameSwappedCallback(base::MakeUnique<base::Closure>(
base::Bind(&OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped,
weak_ptr_factory_.GetWeakPtr(),
base::Unretained(guest_host_view))));
}
void OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped(
content::RenderWidgetHostViewGuest* guest_host_view) {
InvalidateBounds(
gfx::ConvertRectToPixel(scale_factor_, guest_host_view->GetViewBounds()));
RegisterGuestViewFrameSwappedCallback(guest_host_view);
}
std::unique_ptr<cc::SoftwareOutputDevice>
OffScreenRenderWidgetHostView::CreateSoftwareOutputDevice(
ui::Compositor* compositor) {
DCHECK_EQ(GetCompositor(), compositor);
DCHECK(!copy_frame_generator_);
DCHECK(!software_output_device_);
software_output_device_ = new OffScreenOutputDevice(
transparent_,
base::Bind(&OffScreenRenderWidgetHostView::OnPaint,
weak_ptr_factory_.GetWeakPtr()));
return base::WrapUnique(software_output_device_);
}
bool OffScreenRenderWidgetHostView::InstallTransparency() {
if (transparent_) {
SetBackgroundColor(SkColor());
#if defined(OS_MACOSX)
browser_compositor_->SetHasTransparentBackground(true);
#else
compositor_->SetHostHasTransparentBackground(true);
#endif
return true;
}
return false;
}
bool OffScreenRenderWidgetHostView::IsAutoResizeEnabled() const {
return render_widget_host_->auto_resize_enabled();
}
void OffScreenRenderWidgetHostView::SetNeedsBeginFrames(
bool needs_begin_frames) {
SetupFrameRate(false);
begin_frame_timer_->SetActive(needs_begin_frames);
if (software_output_device_) {
software_output_device_->SetActive(needs_begin_frames && painting_);
}
}
void CopyBitmapTo(
const SkBitmap& destination,
const SkBitmap& source,
const gfx::Rect& pos) {
SkAutoLockPixels source_pixels_lock(source);
SkAutoLockPixels destination_pixels_lock(destination);
char* src = static_cast<char*>(source.getPixels());
char* dest = static_cast<char*>(destination.getPixels());
int pixelsize = source.bytesPerPixel();
if (pos.x() + pos.width() <= destination.width() &&
pos.y() + pos.height() <= destination.height()) {
for (int i = 0; i < pos.height(); i++) {
memcpy(dest + ((pos.y() + i) * destination.width() + pos.x()) * pixelsize,
src + (i * source.width()) * pixelsize,
source.width() * pixelsize);
}
}
destination.notifyPixelsChanged();
}
void OffScreenRenderWidgetHostView::OnPaint(
const gfx::Rect& damage_rect, const SkBitmap& bitmap) {
TRACE_EVENT0("electron", "OffScreenRenderWidgetHostView::OnPaint");
HoldResize();
if (parent_callback_) {
parent_callback_.Run(damage_rect, bitmap);
} else if (popup_host_view_ && popup_bitmap_.get()) {
gfx::Rect pos = popup_host_view_->popup_position_;
gfx::Rect damage(damage_rect);
damage.Union(pos);
SkBitmap copy = SkBitmapOperations::CreateTiledBitmap(bitmap,
pos.x(), pos.y(), pos.width(), pos.height());
CopyBitmapTo(bitmap, *popup_bitmap_, pos);
callback_.Run(damage, bitmap);
CopyBitmapTo(bitmap, copy, pos);
} else {
callback_.Run(damage_rect, bitmap);
}
ReleaseResize();
}
void OffScreenRenderWidgetHostView::OnPopupPaint(
const gfx::Rect& damage_rect, const SkBitmap& bitmap) {
if (popup_host_view_ && popup_bitmap_.get())
bitmap.deepCopyTo(popup_bitmap_.get());
}
void OffScreenRenderWidgetHostView::HoldResize() {
if (!hold_resize_)
hold_resize_ = true;
}
void OffScreenRenderWidgetHostView::ReleaseResize() {
if (!hold_resize_)
return;
hold_resize_ = false;
if (pending_resize_) {
pending_resize_ = false;
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&OffScreenRenderWidgetHostView::WasResized,
weak_ptr_factory_.GetWeakPtr()));
}
}
void OffScreenRenderWidgetHostView::WasResized() {
if (hold_resize_) {
if (!pending_resize_)
pending_resize_ = true;
return;
}
ResizeRootLayer();
if (render_widget_host_)
render_widget_host_->WasResized();
GetDelegatedFrameHost()->WasResized();
}
void OffScreenRenderWidgetHostView::ProcessKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
if (!render_widget_host_)
return;
render_widget_host_->ForwardKeyboardEvent(event);
}
void OffScreenRenderWidgetHostView::ProcessMouseEvent(
const blink::WebMouseEvent& event,
const ui::LatencyInfo& latency) {
if (!IsPopupWidget()) {
if (popup_host_view_ &&
popup_host_view_->popup_position_.Contains(event.x, event.y)) {
blink::WebMouseEvent popup_event(event);
popup_event.x -= popup_host_view_->popup_position_.x();
popup_event.y -= popup_host_view_->popup_position_.y();
popup_event.windowX = popup_event.x;
popup_event.windowY = popup_event.y;
popup_host_view_->ProcessMouseEvent(popup_event, latency);
return;
}
}
if (!render_widget_host_)
return;
render_widget_host_->ForwardMouseEvent(event);
}
void OffScreenRenderWidgetHostView::ProcessMouseWheelEvent(
const blink::WebMouseWheelEvent& event,
const ui::LatencyInfo& latency) {
if (!IsPopupWidget()) {
if (popup_host_view_) {
if (popup_host_view_->popup_position_.Contains(event.x, event.y)) {
blink::WebMouseWheelEvent popup_event(event);
popup_event.x -= popup_host_view_->popup_position_.x();
popup_event.y -= popup_host_view_->popup_position_.y();
popup_event.windowX = popup_event.x;
popup_event.windowY = popup_event.y;
popup_host_view_->ProcessMouseWheelEvent(popup_event, latency);
return;
} else {
// Scrolling outside of the popup widget so destroy it.
// Execute asynchronously to avoid deleting the widget from inside some
// other callback.
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&OffScreenRenderWidgetHostView::CancelWidget,
popup_host_view_->weak_ptr_factory_.GetWeakPtr()));
}
}
}
if (!render_widget_host_)
return;
render_widget_host_->ForwardWheelEvent(event);
}
void OffScreenRenderWidgetHostView::SetPainting(bool painting) {
painting_ = painting;
if (software_output_device_) {
software_output_device_->SetActive(painting_);
}
}
bool OffScreenRenderWidgetHostView::IsPainting() const {
return painting_;
}
void OffScreenRenderWidgetHostView::SetFrameRate(int frame_rate) {
if (parent_host_view_) {
if (parent_host_view_->GetFrameRate() == GetFrameRate())
return;
frame_rate_ = parent_host_view_->GetFrameRate();
} else {
if (frame_rate <= 0)
frame_rate = 1;
if (frame_rate > 60)
frame_rate = 60;
frame_rate_ = frame_rate;
}
for (auto guest_host_view : guest_host_views_)
guest_host_view->SetFrameRate(frame_rate);
SetupFrameRate(true);
}
int OffScreenRenderWidgetHostView::GetFrameRate() const {
return frame_rate_;
}
#if !defined(OS_MACOSX)
ui::Compositor* OffScreenRenderWidgetHostView::GetCompositor() const {
return compositor_.get();
}
ui::Layer* OffScreenRenderWidgetHostView::GetRootLayer() const {
return root_layer_.get();
}
content::DelegatedFrameHost*
OffScreenRenderWidgetHostView::GetDelegatedFrameHost() const {
return delegated_frame_host_.get();
}
#endif
void OffScreenRenderWidgetHostView::SetupFrameRate(bool force) {
if (!force && frame_rate_threshold_ms_ != 0)
return;
frame_rate_threshold_ms_ = 1000 / frame_rate_;
GetCompositor()->vsync_manager()->SetAuthoritativeVSyncInterval(
base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms_));
if (copy_frame_generator_) {
copy_frame_generator_->set_frame_rate_threshold_ms(
frame_rate_threshold_ms_);
}
if (begin_frame_timer_) {
begin_frame_timer_->SetFrameRateThresholdMs(frame_rate_threshold_ms_);
} else {
begin_frame_timer_.reset(new AtomBeginFrameTimer(
frame_rate_threshold_ms_,
base::Bind(&OffScreenRenderWidgetHostView::OnBeginFrameTimerTick,
weak_ptr_factory_.GetWeakPtr())));
}
}
void OffScreenRenderWidgetHostView::Invalidate() {
InvalidateBounds(GetViewBounds());
}
void OffScreenRenderWidgetHostView::InvalidateBounds(const gfx::Rect& bounds) {
if (software_output_device_) {
software_output_device_->OnPaint(bounds_in_pixels);
} else if (copy_frame_generator_) {
copy_frame_generator_->GenerateCopyFrame(true, bounds_in_pixels);
}
}
void OffScreenRenderWidgetHostView::ResizeRootLayer() {
SetupFrameRate(false);
const float orgScaleFactor = scale_factor_;
const bool scaleFactorDidChange = (orgScaleFactor != scale_factor_);
gfx::Size size;
if (!IsPopupWidget())
size = GetViewBounds().size();
else
size = popup_position_.size();
if (!scaleFactorDidChange && size == GetRootLayer()->bounds().size())
return;
const gfx::Size& size_in_pixels =
gfx::ConvertSizeToPixel(scale_factor_, size);
GetRootLayer()->SetBounds(gfx::Rect(size));
GetCompositor()->SetScaleAndSize(scale_factor_, size_in_pixels);
}
cc::FrameSinkId OffScreenRenderWidgetHostView::AllocateFrameSinkId(
bool is_guest_view_hack) {
// GuestViews have two RenderWidgetHostViews and so we need to make sure
// we don't have FrameSinkId collisions.
// The FrameSinkId generated here must be unique with FrameSinkId allocated
// in ContextFactoryPrivate.
content::ImageTransportFactory* factory =
content::ImageTransportFactory::GetInstance();
return is_guest_view_hack
? factory->GetContextFactoryPrivate()->AllocateFrameSinkId()
: cc::FrameSinkId(base::checked_cast<uint32_t>(
render_widget_host_->GetProcess()->GetID()),
base::checked_cast<uint32_t>(
render_widget_host_->GetRoutingID()));
}
} // namespace atom
call InvalidateBounds when popup updates
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/osr/osr_render_widget_host_view.h"
#include <vector>
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/time/time.h"
#include "cc/output/copy_output_request.h"
#include "cc/scheduler/delay_based_time_source.h"
#include "components/display_compositor/gl_helper.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_frame_subscriber.h"
#include "content/browser/renderer_host/resize_lock.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/context_factory.h"
#include "media/base/video_frame.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_type.h"
#include "ui/events/latency_info.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/skbitmap_operations.h"
namespace atom {
namespace {
const float kDefaultScaleFactor = 1.0;
const int kFrameRetryLimit = 2;
#if !defined(OS_MACOSX)
const int kResizeLockTimeoutMs = 67;
class AtomResizeLock : public content::ResizeLock {
public:
AtomResizeLock(OffScreenRenderWidgetHostView* host,
const gfx::Size new_size,
bool defer_compositor_lock)
: ResizeLock(new_size, defer_compositor_lock),
host_(host),
cancelled_(false),
weak_ptr_factory_(this) {
DCHECK(host_);
host_->HoldResize();
content::BrowserThread::PostDelayedTask(content::BrowserThread::UI,
FROM_HERE, base::Bind(&AtomResizeLock::CancelLock,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kResizeLockTimeoutMs));
}
~AtomResizeLock() override {
CancelLock();
}
bool GrabDeferredLock() override {
return ResizeLock::GrabDeferredLock();
}
void UnlockCompositor() override {
ResizeLock::UnlockCompositor();
compositor_lock_ = NULL;
}
protected:
void LockCompositor() override {
ResizeLock::LockCompositor();
compositor_lock_ = host_->GetCompositor()->GetCompositorLock();
}
void CancelLock() {
if (cancelled_)
return;
cancelled_ = true;
UnlockCompositor();
host_->ReleaseResize();
}
private:
OffScreenRenderWidgetHostView* host_;
scoped_refptr<ui::CompositorLock> compositor_lock_;
bool cancelled_;
base::WeakPtrFactory<AtomResizeLock> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(AtomResizeLock);
};
#endif // !defined(OS_MACOSX)
} // namespace
class AtomCopyFrameGenerator {
public:
AtomCopyFrameGenerator(int frame_rate_threshold_ms,
OffScreenRenderWidgetHostView* view)
: frame_rate_threshold_ms_(frame_rate_threshold_ms),
view_(view),
frame_pending_(false),
frame_in_progress_(false),
frame_retry_count_(0),
weak_ptr_factory_(this) {
last_time_ = base::Time::Now();
}
void GenerateCopyFrame(
bool force_frame,
const gfx::Rect& damage_rect) {
if (force_frame && !frame_pending_)
frame_pending_ = true;
if (!frame_pending_)
return;
if (!damage_rect.IsEmpty())
pending_damage_rect_.Union(damage_rect);
if (frame_in_progress_)
return;
frame_in_progress_ = true;
const int64_t frame_rate_delta =
(base::TimeTicks::Now() - frame_start_time_).InMilliseconds();
if (frame_rate_delta < frame_rate_threshold_ms_) {
content::BrowserThread::PostDelayedTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&AtomCopyFrameGenerator::InternalGenerateCopyFrame,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(
frame_rate_threshold_ms_ - frame_rate_delta));
return;
}
InternalGenerateCopyFrame();
}
bool frame_pending() const { return frame_pending_; }
void set_frame_rate_threshold_ms(int frame_rate_threshold_ms) {
frame_rate_threshold_ms_ = frame_rate_threshold_ms;
}
private:
void InternalGenerateCopyFrame() {
frame_pending_ = false;
frame_start_time_ = base::TimeTicks::Now();
if (!view_->render_widget_host())
return;
const gfx::Rect damage_rect = pending_damage_rect_;
pending_damage_rect_.SetRect(0, 0, 0, 0);
std::unique_ptr<cc::CopyOutputRequest> request =
cc::CopyOutputRequest::CreateRequest(base::Bind(
&AtomCopyFrameGenerator::CopyFromCompositingSurfaceHasResult,
weak_ptr_factory_.GetWeakPtr(),
damage_rect));
request->set_area(gfx::Rect(view_->GetPhysicalBackingSize()));
view_->GetRootLayer()->RequestCopyOfOutput(std::move(request));
}
void CopyFromCompositingSurfaceHasResult(
const gfx::Rect& damage_rect,
std::unique_ptr<cc::CopyOutputResult> result) {
if (result->IsEmpty() || result->size().IsEmpty() ||
!view_->render_widget_host()) {
OnCopyFrameCaptureFailure(damage_rect);
return;
}
if (result->HasTexture()) {
PrepareTextureCopyOutputResult(damage_rect, std::move(result));
return;
}
DCHECK(result->HasBitmap());
PrepareBitmapCopyOutputResult(damage_rect, std::move(result));
}
void PrepareTextureCopyOutputResult(
const gfx::Rect& damage_rect,
std::unique_ptr<cc::CopyOutputResult> result) {
DCHECK(result->HasTexture());
base::ScopedClosureRunner scoped_callback_runner(
base::Bind(&AtomCopyFrameGenerator::OnCopyFrameCaptureFailure,
weak_ptr_factory_.GetWeakPtr(),
damage_rect));
const gfx::Size& result_size = result->size();
SkIRect bitmap_size;
if (bitmap_)
bitmap_->getBounds(&bitmap_size);
if (!bitmap_ ||
bitmap_size.width() != result_size.width() ||
bitmap_size.height() != result_size.height()) {
bitmap_.reset(new SkBitmap);
bitmap_->allocN32Pixels(result_size.width(),
result_size.height(),
true);
if (bitmap_->drawsNothing())
return;
}
content::ImageTransportFactory* factory =
content::ImageTransportFactory::GetInstance();
display_compositor::GLHelper* gl_helper = factory->GetGLHelper();
if (!gl_helper)
return;
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock(
new SkAutoLockPixels(*bitmap_));
uint8_t* pixels = static_cast<uint8_t*>(bitmap_->getPixels());
cc::TextureMailbox texture_mailbox;
std::unique_ptr<cc::SingleReleaseCallback> release_callback;
result->TakeTexture(&texture_mailbox, &release_callback);
DCHECK(texture_mailbox.IsTexture());
if (!texture_mailbox.IsTexture())
return;
ignore_result(scoped_callback_runner.Release());
gl_helper->CropScaleReadbackAndCleanMailbox(
texture_mailbox.mailbox(),
texture_mailbox.sync_token(),
result_size,
gfx::Rect(result_size),
result_size,
pixels,
kN32_SkColorType,
base::Bind(
&AtomCopyFrameGenerator::CopyFromCompositingSurfaceFinishedProxy,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(&release_callback),
damage_rect,
base::Passed(&bitmap_),
base::Passed(&bitmap_pixels_lock)),
display_compositor::GLHelper::SCALER_QUALITY_FAST);
}
static void CopyFromCompositingSurfaceFinishedProxy(
base::WeakPtr<AtomCopyFrameGenerator> generator,
std::unique_ptr<cc::SingleReleaseCallback> release_callback,
const gfx::Rect& damage_rect,
std::unique_ptr<SkBitmap> bitmap,
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock,
bool result) {
gpu::SyncToken sync_token;
if (result) {
display_compositor::GLHelper* gl_helper =
content::ImageTransportFactory::GetInstance()->GetGLHelper();
if (gl_helper)
gl_helper->GenerateSyncToken(&sync_token);
}
const bool lost_resource = !sync_token.HasData();
release_callback->Run(sync_token, lost_resource);
if (generator) {
generator->CopyFromCompositingSurfaceFinished(
damage_rect, std::move(bitmap), std::move(bitmap_pixels_lock),
result);
} else {
bitmap_pixels_lock.reset();
bitmap.reset();
}
}
void CopyFromCompositingSurfaceFinished(
const gfx::Rect& damage_rect,
std::unique_ptr<SkBitmap> bitmap,
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock,
bool result) {
DCHECK(!bitmap_);
bitmap_ = std::move(bitmap);
if (result) {
OnCopyFrameCaptureSuccess(damage_rect, *bitmap_,
std::move(bitmap_pixels_lock));
} else {
bitmap_pixels_lock.reset();
OnCopyFrameCaptureFailure(damage_rect);
}
}
void PrepareBitmapCopyOutputResult(
const gfx::Rect& damage_rect,
std::unique_ptr<cc::CopyOutputResult> result) {
DCHECK(result->HasBitmap());
std::unique_ptr<SkBitmap> source = result->TakeBitmap();
DCHECK(source);
if (source) {
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock(
new SkAutoLockPixels(*source));
OnCopyFrameCaptureSuccess(damage_rect, *source,
std::move(bitmap_pixels_lock));
} else {
OnCopyFrameCaptureFailure(damage_rect);
}
}
void OnCopyFrameCaptureFailure(
const gfx::Rect& damage_rect) {
pending_damage_rect_.Union(damage_rect);
const bool force_frame = (++frame_retry_count_ <= kFrameRetryLimit);
OnCopyFrameCaptureCompletion(force_frame);
}
void OnCopyFrameCaptureSuccess(
const gfx::Rect& damage_rect,
const SkBitmap& bitmap,
std::unique_ptr<SkAutoLockPixels> bitmap_pixels_lock) {
view_->OnPaint(damage_rect, bitmap);
if (frame_retry_count_ > 0)
frame_retry_count_ = 0;
OnCopyFrameCaptureCompletion(false);
}
void OnCopyFrameCaptureCompletion(bool force_frame) {
frame_in_progress_ = false;
if (frame_pending_) {
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&AtomCopyFrameGenerator::GenerateCopyFrame,
weak_ptr_factory_.GetWeakPtr(),
force_frame,
gfx::Rect()));
}
}
int frame_rate_threshold_ms_;
OffScreenRenderWidgetHostView* view_;
base::Time last_time_;
base::TimeTicks frame_start_time_;
bool frame_pending_;
bool frame_in_progress_;
int frame_retry_count_;
std::unique_ptr<SkBitmap> bitmap_;
gfx::Rect pending_damage_rect_;
base::WeakPtrFactory<AtomCopyFrameGenerator> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(AtomCopyFrameGenerator);
};
class AtomBeginFrameTimer : public cc::DelayBasedTimeSourceClient {
public:
AtomBeginFrameTimer(int frame_rate_threshold_ms,
const base::Closure& callback)
: callback_(callback) {
time_source_.reset(new cc::DelayBasedTimeSource(
content::BrowserThread::GetTaskRunnerForThread(
content::BrowserThread::UI).get()));
time_source_->SetClient(this);
}
void SetActive(bool active) {
time_source_->SetActive(active);
}
bool IsActive() const {
return time_source_->Active();
}
void SetFrameRateThresholdMs(int frame_rate_threshold_ms) {
time_source_->SetTimebaseAndInterval(
base::TimeTicks::Now(),
base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms));
}
private:
void OnTimerTick() override {
callback_.Run();
}
const base::Closure callback_;
std::unique_ptr<cc::DelayBasedTimeSource> time_source_;
DISALLOW_COPY_AND_ASSIGN(AtomBeginFrameTimer);
};
OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView(
bool transparent,
const OnPaintCallback& callback,
content::RenderWidgetHost* host,
OffScreenRenderWidgetHostView* parent_host_view,
NativeWindow* native_window)
: render_widget_host_(content::RenderWidgetHostImpl::From(host)),
parent_host_view_(parent_host_view),
popup_host_view_(nullptr),
child_host_view_(nullptr),
native_window_(native_window),
software_output_device_(nullptr),
transparent_(transparent),
callback_(callback),
parent_callback_(nullptr),
frame_rate_(60),
frame_rate_threshold_ms_(0),
last_time_(base::Time::Now()),
scale_factor_(kDefaultScaleFactor),
size_(native_window->GetSize()),
painting_(true),
is_showing_(!render_widget_host_->is_hidden()),
is_destroyed_(false),
popup_position_(gfx::Rect()),
hold_resize_(false),
pending_resize_(false),
weak_ptr_factory_(this) {
DCHECK(render_widget_host_);
#if !defined(OS_MACOSX)
delegated_frame_host_ = base::MakeUnique<content::DelegatedFrameHost>(
AllocateFrameSinkId(is_guest_view_hack), this);
root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR));
#endif
#if defined(OS_MACOSX)
CreatePlatformWidget(is_guest_view_hack);
#else
// On macOS the ui::Compositor is created/owned by the platform view.
content::ImageTransportFactory* factory =
content::ImageTransportFactory::GetInstance();
ui::ContextFactoryPrivate* context_factory_private =
factory->GetContextFactoryPrivate();
compositor_.reset(
new ui::Compositor(context_factory_private->AllocateFrameSinkId(),
content::GetContextFactory(), context_factory_private,
base::ThreadTaskRunnerHandle::Get()));
compositor_->SetAcceleratedWidget(native_window_->GetAcceleratedWidget());
compositor_->SetRootLayer(root_layer_.get());
#endif
GetCompositor()->SetDelegate(this);
native_window_->AddObserver(this);
ResizeRootLayer();
render_widget_host_->SetView(this);
InstallTransparency();
}
OffScreenRenderWidgetHostView::~OffScreenRenderWidgetHostView() {
if (native_window_)
native_window_->RemoveObserver(this);
#if defined(OS_MACOSX)
if (is_showing_)
browser_compositor_->SetRenderWidgetHostIsHidden(true);
#else
// Marking the DelegatedFrameHost as removed from the window hierarchy is
// necessary to remove all connections to its old ui::Compositor.
if (is_showing_)
delegated_frame_host_->WasHidden();
delegated_frame_host_->ResetCompositor();
#endif
if (copy_frame_generator_.get())
copy_frame_generator_.reset(NULL);
#if defined(OS_MACOSX)
DestroyPlatformWidget();
#else
delegated_frame_host_.reset(NULL);
compositor_.reset(NULL);
root_layer_.reset(NULL);
#endif
}
void OffScreenRenderWidgetHostView::OnWindowResize() {
// In offscreen mode call RenderWidgetHostView's SetSize explicitly
auto size = native_window_->GetSize();
SetSize(size);
}
void OffScreenRenderWidgetHostView::OnWindowClosed() {
native_window_->RemoveObserver(this);
native_window_ = nullptr;
}
void OffScreenRenderWidgetHostView::OnBeginFrameTimerTick() {
const base::TimeTicks frame_time = base::TimeTicks::Now();
const base::TimeDelta vsync_period =
base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms_);
SendBeginFrame(frame_time, vsync_period);
}
void OffScreenRenderWidgetHostView::SendBeginFrame(
base::TimeTicks frame_time, base::TimeDelta vsync_period) {
base::TimeTicks display_time = frame_time + vsync_period;
base::TimeDelta estimated_browser_composite_time =
base::TimeDelta::FromMicroseconds(
(1.0f * base::Time::kMicrosecondsPerSecond) / (3.0f * 60));
base::TimeTicks deadline = display_time - estimated_browser_composite_time;
const cc::BeginFrameArgs& begin_frame_args =
cc::BeginFrameArgs::Create(BEGINFRAME_FROM_HERE,
begin_frame_source_.source_id(),
begin_frame_number_, frame_time, deadline,
vsync_period, cc::BeginFrameArgs::NORMAL);
DCHECK(begin_frame_args.IsValid());
begin_frame_number_++;
render_widget_host_->Send(new ViewMsg_BeginFrame(
render_widget_host_->GetRoutingID(),
begin_frame_args));
}
bool OffScreenRenderWidgetHostView::OnMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(OffScreenRenderWidgetHostView, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames,
SetNeedsBeginFrames)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (!handled)
return content::RenderWidgetHostViewBase::OnMessageReceived(message);
return handled;
}
void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) {
DCHECK(parent_host_view_);
if (parent_host_view_->child_host_view_) {
parent_host_view_->child_host_view_->CancelWidget();
}
parent_host_view_->set_child_host_view(this);
parent_host_view_->Hide();
ResizeRootLayer();
Show();
}
content::RenderWidgetHost* OffScreenRenderWidgetHostView::GetRenderWidgetHost()
const {
return render_widget_host_;
}
void OffScreenRenderWidgetHostView::SetSize(const gfx::Size& size) {
size_ = size;
WasResized();
}
void OffScreenRenderWidgetHostView::SetBounds(const gfx::Rect& new_bounds) {
SetSize(new_bounds.size());
}
gfx::Vector2dF OffScreenRenderWidgetHostView::GetLastScrollOffset() const {
return last_scroll_offset_;
}
gfx::NativeView OffScreenRenderWidgetHostView::GetNativeView() const {
return gfx::NativeView();
}
gfx::NativeViewAccessible
OffScreenRenderWidgetHostView::GetNativeViewAccessible() {
return gfx::NativeViewAccessible();
}
ui::TextInputClient* OffScreenRenderWidgetHostView::GetTextInputClient() {
return nullptr;
}
void OffScreenRenderWidgetHostView::Focus() {
}
bool OffScreenRenderWidgetHostView::HasFocus() const {
return false;
}
bool OffScreenRenderWidgetHostView::IsSurfaceAvailableForCopy() const {
return GetDelegatedFrameHost()->CanCopyFromCompositingSurface();
}
void OffScreenRenderWidgetHostView::Show() {
if (is_showing_)
return;
is_showing_ = true;
#if defined(OS_MACOSX)
browser_compositor_->SetRenderWidgetHostIsHidden(false);
#else
delegated_frame_host_->SetCompositor(compositor_.get());
delegated_frame_host_->WasShown(ui::LatencyInfo());
#endif
if (render_widget_host_)
render_widget_host_->WasShown(ui::LatencyInfo());
}
void OffScreenRenderWidgetHostView::Hide() {
if (!is_showing_)
return;
if (render_widget_host_)
render_widget_host_->WasHidden();
#if defined(OS_MACOSX)
browser_compositor_->SetRenderWidgetHostIsHidden(true);
#else
GetDelegatedFrameHost()->WasHidden();
GetDelegatedFrameHost()->ResetCompositor();
#endif
is_showing_ = false;
}
bool OffScreenRenderWidgetHostView::IsShowing() {
return is_showing_;
}
gfx::Rect OffScreenRenderWidgetHostView::GetViewBounds() const {
if (IsPopupWidget())
return popup_position_;
return gfx::Rect(size_);
}
void OffScreenRenderWidgetHostView::SetBackgroundColor(SkColor color) {
if (transparent_)
color = SkColorSetARGB(SK_AlphaTRANSPARENT, 0, 0, 0);
content::RenderWidgetHostViewBase::SetBackgroundColor(color);
const bool opaque = !transparent_ && GetBackgroundOpaque();
if (render_widget_host_)
render_widget_host_->SetBackgroundOpaque(opaque);
}
gfx::Size OffScreenRenderWidgetHostView::GetVisibleViewportSize() const {
return size_;
}
void OffScreenRenderWidgetHostView::SetInsets(const gfx::Insets& insets) {
}
bool OffScreenRenderWidgetHostView::LockMouse() {
return false;
}
void OffScreenRenderWidgetHostView::UnlockMouse() {
}
void OffScreenRenderWidgetHostView::OnSwapCompositorFrame(
uint32_t output_surface_id,
cc::CompositorFrame frame) {
TRACE_EVENT0("electron",
"OffScreenRenderWidgetHostView::OnSwapCompositorFrame");
if (frame.metadata.root_scroll_offset != last_scroll_offset_) {
last_scroll_offset_ = frame.metadata.root_scroll_offset;
}
if (!frame.render_pass_list.empty()) {
if (software_output_device_) {
if (!begin_frame_timer_.get() || IsPopupWidget()) {
software_output_device_->SetActive(painting_);
}
// The compositor will draw directly to the SoftwareOutputDevice which
// then calls OnPaint.
// We would normally call BrowserCompositorMac::SwapCompositorFrame on
// macOS, however it contains compositor resize logic that we don't want.
// Consequently we instead call the SwapDelegatedFrame method directly.
GetDelegatedFrameHost()->SwapDelegatedFrame(output_surface_id,
std::move(frame));
} else {
if (!copy_frame_generator_.get()) {
copy_frame_generator_.reset(
new AtomCopyFrameGenerator(frame_rate_threshold_ms_, this));
}
// Determine the damage rectangle for the current frame. This is the same
// calculation that SwapDelegatedFrame uses.
cc::RenderPass* root_pass = frame.render_pass_list.back().get();
gfx::Size frame_size = root_pass->output_rect.size();
gfx::Rect damage_rect =
gfx::ToEnclosingRect(gfx::RectF(root_pass->damage_rect));
damage_rect.Intersect(gfx::Rect(frame_size));
// We would normally call BrowserCompositorMac::SwapCompositorFrame on
// macOS, however it contains compositor resize logic that we don't want.
// Consequently we instead call the SwapDelegatedFrame method directly.
GetDelegatedFrameHost()->SwapDelegatedFrame(output_surface_id,
std::move(frame));
// Request a copy of the last compositor frame which will eventually call
// OnPaint asynchronously.
copy_frame_generator_->GenerateCopyFrame(true, damage_rect);
}
}
}
void OffScreenRenderWidgetHostView::ClearCompositorFrame() {
GetDelegatedFrameHost()->ClearDelegatedFrame();
}
void OffScreenRenderWidgetHostView::InitAsPopup(
content::RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
DCHECK_EQ(parent_host_view_, parent_host_view);
if (parent_host_view_->popup_host_view_) {
parent_host_view_->popup_host_view_->CancelWidget();
}
parent_host_view_->set_popup_host_view(this);
parent_host_view_->popup_bitmap_.reset(new SkBitmap);
parent_callback_ = base::Bind(&OffScreenRenderWidgetHostView::OnPopupPaint,
parent_host_view_->weak_ptr_factory_.GetWeakPtr());
popup_position_ = pos;
ResizeRootLayer();
Show();
}
void OffScreenRenderWidgetHostView::InitAsFullscreen(
content::RenderWidgetHostView *) {
}
void OffScreenRenderWidgetHostView::UpdateCursor(const content::WebCursor &) {
}
void OffScreenRenderWidgetHostView::SetIsLoading(bool loading) {
}
void OffScreenRenderWidgetHostView::TextInputStateChanged(
const content::TextInputState& params) {
}
void OffScreenRenderWidgetHostView::ImeCancelComposition() {
}
void OffScreenRenderWidgetHostView::RenderProcessGone(base::TerminationStatus,
int) {
Destroy();
}
void OffScreenRenderWidgetHostView::Destroy() {
if (!is_destroyed_) {
is_destroyed_ = true;
if (parent_host_view_ != NULL) {
CancelWidget();
} else {
if (popup_host_view_)
popup_host_view_->CancelWidget();
popup_bitmap_.reset();
if (child_host_view_)
child_host_view_->CancelWidget();
for (auto guest_host_view : guest_host_views_)
guest_host_view->CancelWidget();
Hide();
}
}
delete this;
}
void OffScreenRenderWidgetHostView::SetTooltipText(const base::string16 &) {
}
void OffScreenRenderWidgetHostView::SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params &) {
}
void OffScreenRenderWidgetHostView::CopyFromSurface(
const gfx::Rect& src_subrect,
const gfx::Size& dst_size,
const content::ReadbackRequestCallback& callback,
const SkColorType preferred_color_type) {
GetDelegatedFrameHost()->CopyFromCompositingSurface(
src_subrect, dst_size, callback, preferred_color_type);
}
void OffScreenRenderWidgetHostView::CopyFromSurfaceToVideoFrame(
const gfx::Rect& src_subrect,
scoped_refptr<media::VideoFrame> target,
const base::Callback<void(const gfx::Rect&, bool)>& callback) {
GetDelegatedFrameHost()->CopyFromCompositingSurfaceToVideoFrame(
src_subrect, target, callback);
}
void OffScreenRenderWidgetHostView::BeginFrameSubscription(
std::unique_ptr<content::RenderWidgetHostViewFrameSubscriber> subscriber) {
GetDelegatedFrameHost()->BeginFrameSubscription(std::move(subscriber));
}
void OffScreenRenderWidgetHostView::EndFrameSubscription() {
GetDelegatedFrameHost()->EndFrameSubscription();
}
void OffScreenRenderWidgetHostView::InitAsGuest(
content::RenderWidgetHostView* parent_host_view,
content::RenderWidgetHostViewGuest* guest_view) {
parent_host_view_->AddGuestHostView(this);
parent_host_view_->RegisterGuestViewFrameSwappedCallback(guest_view);
}
bool OffScreenRenderWidgetHostView::HasAcceleratedSurface(const gfx::Size &) {
return false;
}
gfx::Rect OffScreenRenderWidgetHostView::GetBoundsInRootWindow() {
return gfx::Rect(size_);
}
void OffScreenRenderWidgetHostView::ImeCompositionRangeChanged(
const gfx::Range &, const std::vector<gfx::Rect>&) {
}
gfx::Size OffScreenRenderWidgetHostView::GetPhysicalBackingSize() const {
return gfx::ConvertSizeToPixel(scale_factor_, GetRequestedRendererSize());
}
gfx::Size OffScreenRenderWidgetHostView::GetRequestedRendererSize() const {
return GetDelegatedFrameHost()->GetRequestedRendererSize();
}
content::RenderWidgetHostViewBase*
OffScreenRenderWidgetHostView::CreateViewForWidget(
content::RenderWidgetHost* render_widget_host,
content::RenderWidgetHost* embedder_render_widget_host,
content::WebContentsView* web_contents_view) {
if (render_widget_host->GetView()) {
return static_cast<content::RenderWidgetHostViewBase*>(
render_widget_host->GetView());
}
OffScreenRenderWidgetHostView* embedder_host_view = nullptr;
if (embedder_render_widget_host) {
embedder_host_view = static_cast<OffScreenRenderWidgetHostView*>(
embedder_render_widget_host->GetView());
}
return new OffScreenRenderWidgetHostView(
transparent_,
callback_,
render_widget_host,
embedder_host_view,
native_window_);
}
#if !defined(OS_MACOSX)
ui::Layer* OffScreenRenderWidgetHostView::DelegatedFrameHostGetLayer() const {
return const_cast<ui::Layer*>(root_layer_.get());
}
bool OffScreenRenderWidgetHostView::DelegatedFrameHostIsVisible() const {
return !render_widget_host_->is_hidden();
}
SkColor OffScreenRenderWidgetHostView::DelegatedFrameHostGetGutterColor(
SkColor color) const {
if (render_widget_host_->delegate() &&
render_widget_host_->delegate()->IsFullscreenForCurrentTab()) {
return SK_ColorBLACK;
}
return color;
}
gfx::Size OffScreenRenderWidgetHostView::DelegatedFrameHostDesiredSizeInDIP()
const {
return GetRootLayer()->bounds().size();
}
bool OffScreenRenderWidgetHostView::DelegatedFrameCanCreateResizeLock() const {
return !render_widget_host_->auto_resize_enabled();
}
std::unique_ptr<content::ResizeLock>
OffScreenRenderWidgetHostView::DelegatedFrameHostCreateResizeLock(
bool defer_compositor_lock) {
return std::unique_ptr<content::ResizeLock>(new AtomResizeLock(
this,
DelegatedFrameHostDesiredSizeInDIP(),
defer_compositor_lock));
}
void OffScreenRenderWidgetHostView::DelegatedFrameHostResizeLockWasReleased() {
return render_widget_host_->WasResized();
}
void
OffScreenRenderWidgetHostView::DelegatedFrameHostSendReclaimCompositorResources(
int output_surface_id,
bool is_swap_ack,
const cc::ReturnedResourceArray& resources) {
render_widget_host_->Send(new ViewMsg_ReclaimCompositorResources(
render_widget_host_->GetRoutingID(), output_surface_id, is_swap_ack,
resources));
}
void OffScreenRenderWidgetHostView::SetBeginFrameSource(
cc::BeginFrameSource* source) {
}
#endif // !defined(OS_MACOSX)
bool OffScreenRenderWidgetHostView::TransformPointToLocalCoordSpace(
const gfx::Point& point,
const cc::SurfaceId& original_surface,
gfx::Point* transformed_point) {
// Transformations use physical pixels rather than DIP, so conversion
// is necessary.
gfx::Point point_in_pixels =
gfx::ConvertPointToPixel(scale_factor_, point);
if (!GetDelegatedFrameHost()->TransformPointToLocalCoordSpace(
point_in_pixels, original_surface, transformed_point)) {
return false;
}
*transformed_point =
gfx::ConvertPointToDIP(scale_factor_, *transformed_point);
return true;
}
bool OffScreenRenderWidgetHostView::TransformPointToCoordSpaceForView(
const gfx::Point& point,
RenderWidgetHostViewBase* target_view,
gfx::Point* transformed_point) {
if (target_view == this) {
*transformed_point = point;
return true;
}
// In TransformPointToLocalCoordSpace() there is a Point-to-Pixel conversion,
// but it is not necessary here because the final target view is responsible
// for converting before computing the final transform.
return GetDelegatedFrameHost()->TransformPointToCoordSpaceForView(
point, target_view, transformed_point);
}
void OffScreenRenderWidgetHostView::CancelWidget() {
if (render_widget_host_)
render_widget_host_->LostCapture();
Hide();
if (parent_host_view_) {
if (parent_host_view_->popup_host_view_ == this) {
parent_host_view_->set_popup_host_view(NULL);
parent_host_view_->popup_bitmap_.reset();
} else if (parent_host_view_->child_host_view_ == this) {
parent_host_view_->set_child_host_view(NULL);
parent_host_view_->Show();
} else {
parent_host_view_->RemoveGuestHostView(this);
}
parent_host_view_ = NULL;
}
if (render_widget_host_ && !is_destroyed_) {
is_destroyed_ = true;
// Results in a call to Destroy().
render_widget_host_->ShutdownAndDestroyWidget(true);
}
}
void OffScreenRenderWidgetHostView::AddGuestHostView(
OffScreenRenderWidgetHostView* guest_host) {
guest_host_views_.insert(guest_host);
}
void OffScreenRenderWidgetHostView::RemoveGuestHostView(
OffScreenRenderWidgetHostView* guest_host) {
guest_host_views_.erase(guest_host);
}
void OffScreenRenderWidgetHostView::RegisterGuestViewFrameSwappedCallback(
content::RenderWidgetHostViewGuest* guest_host_view) {
guest_host_view->RegisterFrameSwappedCallback(base::MakeUnique<base::Closure>(
base::Bind(&OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped,
weak_ptr_factory_.GetWeakPtr(),
base::Unretained(guest_host_view))));
}
void OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped(
content::RenderWidgetHostViewGuest* guest_host_view) {
InvalidateBounds(
gfx::ConvertRectToPixel(scale_factor_, guest_host_view->GetViewBounds()));
RegisterGuestViewFrameSwappedCallback(guest_host_view);
}
std::unique_ptr<cc::SoftwareOutputDevice>
OffScreenRenderWidgetHostView::CreateSoftwareOutputDevice(
ui::Compositor* compositor) {
DCHECK_EQ(GetCompositor(), compositor);
DCHECK(!copy_frame_generator_);
DCHECK(!software_output_device_);
software_output_device_ = new OffScreenOutputDevice(
transparent_,
base::Bind(&OffScreenRenderWidgetHostView::OnPaint,
weak_ptr_factory_.GetWeakPtr()));
return base::WrapUnique(software_output_device_);
}
bool OffScreenRenderWidgetHostView::InstallTransparency() {
if (transparent_) {
SetBackgroundColor(SkColor());
#if defined(OS_MACOSX)
browser_compositor_->SetHasTransparentBackground(true);
#else
compositor_->SetHostHasTransparentBackground(true);
#endif
return true;
}
return false;
}
bool OffScreenRenderWidgetHostView::IsAutoResizeEnabled() const {
return render_widget_host_->auto_resize_enabled();
}
void OffScreenRenderWidgetHostView::SetNeedsBeginFrames(
bool needs_begin_frames) {
SetupFrameRate(false);
begin_frame_timer_->SetActive(needs_begin_frames);
if (software_output_device_) {
software_output_device_->SetActive(needs_begin_frames && painting_);
}
}
void CopyBitmapTo(
const SkBitmap& destination,
const SkBitmap& source,
const gfx::Rect& pos) {
SkAutoLockPixels source_pixels_lock(source);
SkAutoLockPixels destination_pixels_lock(destination);
char* src = static_cast<char*>(source.getPixels());
char* dest = static_cast<char*>(destination.getPixels());
int pixelsize = source.bytesPerPixel();
if (pos.x() + pos.width() <= destination.width() &&
pos.y() + pos.height() <= destination.height()) {
for (int i = 0; i < pos.height(); i++) {
memcpy(dest + ((pos.y() + i) * destination.width() + pos.x()) * pixelsize,
src + (i * source.width()) * pixelsize,
source.width() * pixelsize);
}
}
destination.notifyPixelsChanged();
}
void OffScreenRenderWidgetHostView::OnPaint(
const gfx::Rect& damage_rect, const SkBitmap& bitmap) {
TRACE_EVENT0("electron", "OffScreenRenderWidgetHostView::OnPaint");
HoldResize();
if (parent_callback_) {
parent_callback_.Run(damage_rect, bitmap);
} else if (popup_host_view_ && popup_bitmap_.get()) {
gfx::Rect pos = popup_host_view_->popup_position_;
gfx::Rect damage(damage_rect);
damage.Union(pos);
SkBitmap copy = SkBitmapOperations::CreateTiledBitmap(bitmap,
pos.x(), pos.y(), pos.width(), pos.height());
CopyBitmapTo(bitmap, *popup_bitmap_, pos);
callback_.Run(damage, bitmap);
CopyBitmapTo(bitmap, copy, pos);
} else {
callback_.Run(damage_rect, bitmap);
}
ReleaseResize();
}
void OffScreenRenderWidgetHostView::OnPopupPaint(
const gfx::Rect& damage_rect, const SkBitmap& bitmap) {
if (popup_host_view_ && popup_bitmap_.get())
bitmap.deepCopyTo(popup_bitmap_.get());
InvalidateBounds(popup_host_view_->popup_position_);
}
void OffScreenRenderWidgetHostView::HoldResize() {
if (!hold_resize_)
hold_resize_ = true;
}
void OffScreenRenderWidgetHostView::ReleaseResize() {
if (!hold_resize_)
return;
hold_resize_ = false;
if (pending_resize_) {
pending_resize_ = false;
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&OffScreenRenderWidgetHostView::WasResized,
weak_ptr_factory_.GetWeakPtr()));
}
}
void OffScreenRenderWidgetHostView::WasResized() {
if (hold_resize_) {
if (!pending_resize_)
pending_resize_ = true;
return;
}
ResizeRootLayer();
if (render_widget_host_)
render_widget_host_->WasResized();
GetDelegatedFrameHost()->WasResized();
}
void OffScreenRenderWidgetHostView::ProcessKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
if (!render_widget_host_)
return;
render_widget_host_->ForwardKeyboardEvent(event);
}
void OffScreenRenderWidgetHostView::ProcessMouseEvent(
const blink::WebMouseEvent& event,
const ui::LatencyInfo& latency) {
if (!IsPopupWidget()) {
if (popup_host_view_ &&
popup_host_view_->popup_position_.Contains(event.x, event.y)) {
blink::WebMouseEvent popup_event(event);
popup_event.x -= popup_host_view_->popup_position_.x();
popup_event.y -= popup_host_view_->popup_position_.y();
popup_event.windowX = popup_event.x;
popup_event.windowY = popup_event.y;
popup_host_view_->ProcessMouseEvent(popup_event, latency);
return;
}
}
if (!render_widget_host_)
return;
render_widget_host_->ForwardMouseEvent(event);
}
void OffScreenRenderWidgetHostView::ProcessMouseWheelEvent(
const blink::WebMouseWheelEvent& event,
const ui::LatencyInfo& latency) {
if (!IsPopupWidget()) {
if (popup_host_view_) {
if (popup_host_view_->popup_position_.Contains(event.x, event.y)) {
blink::WebMouseWheelEvent popup_event(event);
popup_event.x -= popup_host_view_->popup_position_.x();
popup_event.y -= popup_host_view_->popup_position_.y();
popup_event.windowX = popup_event.x;
popup_event.windowY = popup_event.y;
popup_host_view_->ProcessMouseWheelEvent(popup_event, latency);
return;
} else {
// Scrolling outside of the popup widget so destroy it.
// Execute asynchronously to avoid deleting the widget from inside some
// other callback.
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&OffScreenRenderWidgetHostView::CancelWidget,
popup_host_view_->weak_ptr_factory_.GetWeakPtr()));
}
}
}
if (!render_widget_host_)
return;
render_widget_host_->ForwardWheelEvent(event);
}
void OffScreenRenderWidgetHostView::SetPainting(bool painting) {
painting_ = painting;
if (software_output_device_) {
software_output_device_->SetActive(painting_);
}
}
bool OffScreenRenderWidgetHostView::IsPainting() const {
return painting_;
}
void OffScreenRenderWidgetHostView::SetFrameRate(int frame_rate) {
if (parent_host_view_) {
if (parent_host_view_->GetFrameRate() == GetFrameRate())
return;
frame_rate_ = parent_host_view_->GetFrameRate();
} else {
if (frame_rate <= 0)
frame_rate = 1;
if (frame_rate > 60)
frame_rate = 60;
frame_rate_ = frame_rate;
}
for (auto guest_host_view : guest_host_views_)
guest_host_view->SetFrameRate(frame_rate);
SetupFrameRate(true);
}
int OffScreenRenderWidgetHostView::GetFrameRate() const {
return frame_rate_;
}
#if !defined(OS_MACOSX)
ui::Compositor* OffScreenRenderWidgetHostView::GetCompositor() const {
return compositor_.get();
}
ui::Layer* OffScreenRenderWidgetHostView::GetRootLayer() const {
return root_layer_.get();
}
content::DelegatedFrameHost*
OffScreenRenderWidgetHostView::GetDelegatedFrameHost() const {
return delegated_frame_host_.get();
}
#endif
void OffScreenRenderWidgetHostView::SetupFrameRate(bool force) {
if (!force && frame_rate_threshold_ms_ != 0)
return;
frame_rate_threshold_ms_ = 1000 / frame_rate_;
GetCompositor()->vsync_manager()->SetAuthoritativeVSyncInterval(
base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms_));
if (copy_frame_generator_) {
copy_frame_generator_->set_frame_rate_threshold_ms(
frame_rate_threshold_ms_);
}
if (begin_frame_timer_) {
begin_frame_timer_->SetFrameRateThresholdMs(frame_rate_threshold_ms_);
} else {
begin_frame_timer_.reset(new AtomBeginFrameTimer(
frame_rate_threshold_ms_,
base::Bind(&OffScreenRenderWidgetHostView::OnBeginFrameTimerTick,
weak_ptr_factory_.GetWeakPtr())));
}
}
void OffScreenRenderWidgetHostView::Invalidate() {
InvalidateBounds(GetViewBounds());
}
void OffScreenRenderWidgetHostView::InvalidateBounds(const gfx::Rect& bounds) {
if (software_output_device_) {
software_output_device_->OnPaint(bounds_in_pixels);
} else if (copy_frame_generator_) {
copy_frame_generator_->GenerateCopyFrame(true, bounds_in_pixels);
}
}
void OffScreenRenderWidgetHostView::ResizeRootLayer() {
SetupFrameRate(false);
const float orgScaleFactor = scale_factor_;
const bool scaleFactorDidChange = (orgScaleFactor != scale_factor_);
gfx::Size size;
if (!IsPopupWidget())
size = GetViewBounds().size();
else
size = popup_position_.size();
if (!scaleFactorDidChange && size == GetRootLayer()->bounds().size())
return;
const gfx::Size& size_in_pixels =
gfx::ConvertSizeToPixel(scale_factor_, size);
GetRootLayer()->SetBounds(gfx::Rect(size));
GetCompositor()->SetScaleAndSize(scale_factor_, size_in_pixels);
}
cc::FrameSinkId OffScreenRenderWidgetHostView::AllocateFrameSinkId(
bool is_guest_view_hack) {
// GuestViews have two RenderWidgetHostViews and so we need to make sure
// we don't have FrameSinkId collisions.
// The FrameSinkId generated here must be unique with FrameSinkId allocated
// in ContextFactoryPrivate.
content::ImageTransportFactory* factory =
content::ImageTransportFactory::GetInstance();
return is_guest_view_hack
? factory->GetContextFactoryPrivate()->AllocateFrameSinkId()
: cc::FrameSinkId(base::checked_cast<uint32_t>(
render_widget_host_->GetProcess()->GetID()),
base::checked_cast<uint32_t>(
render_widget_host_->GetRoutingID()));
}
} // namespace atom
|
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "ASTNodeEraser.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DependentDiagnostic.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/JIT.h" // For debugging the EE in gdb
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/IPO.h"
using namespace clang;
namespace cling {
///\brief The class does the actual work of removing a declaration and
/// resetting the internal structures of the compiler
///
class DeclReverter : public DeclVisitor<DeclReverter, bool> {
private:
typedef llvm::DenseSet<FileID> FileIDs;
///\brief The Sema object being reverted (contains the AST as well).
///
Sema* m_Sema;
///\brief The execution engine, either JIT or MCJIT, being recovered.
///
llvm::ExecutionEngine* m_EEngine;
///\brief The current transaction being reverted.
///
const Transaction* m_CurTransaction;
///\brief Reverted declaration contains a SourceLocation, representing a
/// place in the file where it was seen. Clang caches that file and even if
/// a declaration is removed and the file is edited we hit the cached entry.
/// This ADT keeps track of the files from which the reverted declarations
/// came from so that in the end they could be removed from clang's cache.
///
FileIDs m_FilesToUncache;
public:
DeclReverter(Sema* S, llvm::ExecutionEngine* EE, const Transaction* T)
: m_Sema(S), m_EEngine(EE), m_CurTransaction(T) { }
~DeclReverter();
///\brief Interface with nice name, forwarding to Visit.
///
///\param[in] D - The declaration to forward.
///\returns true on success.
///
bool RevertDecl(Decl* D) { return Visit(D); }
///\brief If it falls back in the base class just remove the declaration
/// only from the declaration context.
/// @param[in] D - The declaration to be removed.
///
///\returns true on success.
///
bool VisitDecl(Decl* D);
///\brief Removes the declaration from the lookup chains and from the
/// declaration context.
/// @param[in] ND - The declaration to be removed.
///
///\returns true on success.
///
bool VisitNamedDecl(NamedDecl* ND);
///\brief Removes the declaration from the lookup chains and from the
/// declaration context and it rebuilds the redeclaration chain.
/// @param[in] VD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitVarDecl(VarDecl* VD);
///\brief Removes the declaration from the lookup chains and from the
/// declaration context and it rebuilds the redeclaration chain.
/// @param[in] FD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitFunctionDecl(FunctionDecl* FD);
///\brief Specialize the removal of constructors due to the fact the we need
/// the constructor type (aka CXXCtorType). The information is located in
/// the CXXConstructExpr of usually VarDecls.
/// See clang::CodeGen::CodeGenFunction::EmitCXXConstructExpr.
///
/// What we will do instead is to brute-force and try to remove from the
/// llvm::Module all ctors of this class with all the types.
///
///\param[in] CXXCtor - The declaration to be removed.
///
///\returns true on success.
///
bool VisitCXXConstructorDecl(CXXConstructorDecl* CXXCtor);
///\brief Removes the DeclCotnext and its decls.
/// @param[in] DC - The declaration to be removed.
///
///\returns true on success.
///
bool VisitDeclContext(DeclContext* DC);
///\brief Removes the namespace.
/// @param[in] NSD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitNamespaceDecl(NamespaceDecl* NSD);
///\brief Removes a Tag (class/union/struct/enum). Most of the other
/// containers fall back into that case.
/// @param[in] TD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitTagDecl(TagDecl* TD);
///\brief Remove the macro from the Preprocessor.
/// @param[in] MD - The MacroDirectiveInfo containing the IdentifierInfo and
/// MacroDirective to forward.
///
///\returns true on success.
///
bool VisitMacro(const Transaction::MacroDirectiveInfo MD);
///@name Templates
///@{
///\brief Removes template from the redecl chain. Templates are
/// redeclarables also.
/// @param[in] R - The declaration to be removed.
///
///\returns true on success.
///
bool VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl* R);
///@}
void MaybeRemoveDeclFromModule(GlobalDecl& GD) const;
void RemoveStaticInit(llvm::Function& F) const;
/// @name Helpers
/// @{
///\brief Checks whether the declaration was pushed onto the declaration
/// chains.
/// @param[in] ND - The declaration that is being checked.
///
///\returns true if the ND was found in the lookup chain.
///
bool isOnScopeChains(clang::NamedDecl* ND);
///\brief Interface with nice name, forwarding to Visit.
///
///\param[in] MD - The MacroDirectiveInfo containing the IdentifierInfo and
/// MacroDirective to forward.
///\returns true on success.
///
bool RevertMacro(const Transaction::MacroDirectiveInfo MD) { return VisitMacro(MD); }
///\brief Removes given declaration from the chain of redeclarations.
/// Rebuilds the chain and sets properly first and last redeclaration.
/// @param[in] R - The redeclarable, its chain to be rebuilt.
/// @param[in] DC - Remove the redecl's lookup entry from this DeclContext.
///
///\returns the most recent redeclaration in the new chain.
///
template <typename T>
bool VisitRedeclarable(clang::Redeclarable<T>* R, DeclContext* DC) {
llvm::SmallVector<T*, 4> PrevDecls;
T* PrevDecl = R->getMostRecentDecl();
// [0]=>C [1]=>B [2]=>A ...
while (PrevDecl) { // Collect the redeclarations, except the one we remove
if (PrevDecl != R)
PrevDecls.push_back(PrevDecl);
PrevDecl = PrevDecl->getPreviousDecl();
}
if (!PrevDecls.empty()) {
// Make sure we update the lookup maps, because the removed decl might
// be registered in the lookup and again findable.
StoredDeclsMap* Map = DC->getPrimaryContext()->getLookupPtr();
if (Map) {
NamedDecl* ND = (NamedDecl*)((T*)R);
DeclarationName Name = ND->getDeclName();
if (!Name.isEmpty()) {
StoredDeclsMap::iterator Pos = Map->find(Name);
if (Pos != Map->end() && !Pos->second.isNull()) {
DeclContext::lookup_result decls = Pos->second.getLookupResult();
bool isInTheLookup = false;
for(DeclContext::lookup_result::const_iterator I = decls.begin(),
E = decls.end(); I != E; ++I) {
if (*I == ND) { // the decl is registered in the lookup
isInTheLookup = true;
break;
}
}
//
//Pos->second.AddSubsequentDecl(PrevDecls[0]);
// If this is a redeclaration of an existing decl, replace the
// old one with D.
if (isInTheLookup/*!Pos->second.HandleRedeclaration(PrevDecls[0])*/) {
// We are probably in the case where we had overloads and we
// deleted an overload definition but we still have its
// declaration. Say void f(); void f(int); void f(int) {}
// If f(int) was in the lookup table we remove it but we must
// put the declaration of void f(int);
if (Pos->second.getAsDecl() == ND)
Pos->second.setOnlyValue(PrevDecls[0]);
else if (StoredDeclsList::DeclsTy* Vec
= Pos->second.getAsVector()) {
bool wasReplaced = false;
for (StoredDeclsList::DeclsTy::iterator I= Vec->begin(),
E = Vec->end(); I != E; ++I)
if (*I == ND) {
// We need to replace it exactly at the same place where
// the old one was. The reason is cling diff-based
// test suite
assert(*I != PrevDecls[0] && "DAFUQ");
*I = PrevDecls[0];
wasReplaced = true;
break;
}
// This will make the DeclContext::removeDecl happy. It also
// tries to remove the decl from the lookup.
//if (wasReplaced)
// Pos->second.AddSubsequentDecl(ND);
}
}
}
}
}
// Put 0 in the end of the array so that the loop will reset the
// pointer to latest redeclaration in the chain to itself.
//
PrevDecls.push_back(0);
// 0 <- A <- B <- C
for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {
PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);
}
}
return true;
}
/// @}
private:
///\brief Function that collects the files which we must reread from disk.
///
/// For example: We must uncache the cached include, which brought a
/// declaration or a macro diretive definition in the AST.
///\param[in] Loc - The source location of the reverted declaration.
///
void CollectFilesToUncache(SourceLocation Loc);
};
DeclReverter::~DeclReverter() {
SourceManager& SM = m_Sema->getSourceManager();
for (FileIDs::iterator I = m_FilesToUncache.begin(),
E = m_FilesToUncache.end(); I != E; ++I) {
const SrcMgr::FileInfo& fInfo = SM.getSLocEntry(*I).getFile();
// We need to reset the cache
SrcMgr::ContentCache* cache
= const_cast<SrcMgr::ContentCache*>(fInfo.getContentCache());
FileEntry* entry = const_cast<FileEntry*>(cache->ContentsEntry);
// We have to reset the file entry size to keep the cache and the file
// entry in sync.
if (entry) {
cache->replaceBuffer(0,/*free*/true);
FileManager::modifyFileEntry(entry, /*size*/0, 0);
}
}
// Clean up the pending instantiations
m_Sema->PendingInstantiations.clear();
m_Sema->PendingLocalImplicitInstantiations.clear();
}
void DeclReverter::CollectFilesToUncache(SourceLocation Loc) {
const SourceManager& SM = m_Sema->getSourceManager();
FileID FID = SM.getFileID(SM.getSpellingLoc(Loc));
if (!FID.isInvalid() && FID >= m_CurTransaction->getBufferFID()
&& !m_FilesToUncache.count(FID))
m_FilesToUncache.insert(FID);
}
// Gives us access to the protected members that we need.
class DeclContextExt : public DeclContext {
public:
static bool removeIfLast(DeclContext* DC, Decl* D) {
if (!D->getNextDeclInContext()) {
// Either last (remove!), or invalid (nothing to remove)
if (((DeclContextExt*)DC)->LastDecl == D) {
// Valid. Thus remove.
DC->removeDecl(D);
// Force rebuilding of the lookup table.
//DC->setMustBuildLookupTable();
return true;
}
}
else {
// Force rebuilding of the lookup table.
//DC->setMustBuildLookupTable();
DC->removeDecl(D);
return true;
}
return false;
}
};
bool DeclReverter::VisitDecl(Decl* D) {
assert(D && "The Decl is null");
CollectFilesToUncache(D->getLocStart());
DeclContext* DC = D->getLexicalDeclContext();
bool Successful = true;
DeclContextExt::removeIfLast(DC, D);
// With the bump allocator this is nop.
if (Successful)
m_Sema->getASTContext().Deallocate(D);
return Successful;
}
bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {
bool Successful = VisitDecl(ND);
DeclContext* DC = ND->getDeclContext();
while (DC->isTransparentContext())
DC = DC->getLookupParent();
// if the decl was anonymous we are done.
if (!ND->getIdentifier())
return Successful;
// If the decl was removed make sure that we fix the lookup
if (Successful) {
if (Scope* S = m_Sema->getScopeForContext(DC))
S->RemoveDecl(ND);
if (isOnScopeChains(ND))
m_Sema->IdResolver.RemoveDecl(ND);
}
// Cleanup the lookup tables.
StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
if (Map) { // DeclContexts like EnumDecls don't have lookup maps.
// Make sure we the decl doesn't exist in the lookup tables.
StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
if ( Pos != Map->end()) {
// Most decls only have one entry in their list, special case it.
if (Pos->second.getAsDecl() == ND)
Pos->second.remove(ND);
else if (StoredDeclsList::DeclsTy* Vec = Pos->second.getAsVector()) {
// Otherwise iterate over the list with entries with the same name.
// TODO: Walk the redeclaration chain if the entry was a redeclaration
for (StoredDeclsList::DeclsTy::const_iterator I = Vec->begin(),
E = Vec->end(); I != E; ++I)
if (*I == ND)
Pos->second.remove(ND);
}
if (Pos->second.isNull())
Map->erase(Pos);
}
}
#ifndef NDEBUG
if (Map) { // DeclContexts like EnumDecls don't have lookup maps.
// Make sure we the decl doesn't exist in the lookup tables.
StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
if ( Pos != Map->end()) {
// Most decls only have one entry in their list, special case it.
if (NamedDecl *OldD = Pos->second.getAsDecl())
assert(OldD != ND && "Lookup entry still exists.");
else if (StoredDeclsList::DeclsTy* Vec = Pos->second.getAsVector()) {
// Otherwise iterate over the list with entries with the same name.
// TODO: Walk the redeclaration chain if the entry was a redeclaration.
for (StoredDeclsList::DeclsTy::const_iterator I = Vec->begin(),
E = Vec->end(); I != E; ++I)
assert(*I != ND && "Lookup entry still exists.");
}
else
assert(Pos->second.isNull() && "!?");
}
}
#endif
return Successful;
}
bool DeclReverter::VisitVarDecl(VarDecl* VD) {
// Cleanup the module if the transaction was committed and code was
// generated. This has to go first, because it may need the AST information
// which we will remove soon. (Eg. mangleDeclName iterates the redecls)
GlobalDecl GD(VD);
MaybeRemoveDeclFromModule(GD);
// VarDecl : DeclaratiorDecl, Redeclarable
bool Successful = VisitRedeclarable(VD, VD->getDeclContext());
Successful &= VisitDeclaratorDecl(VD);
return Successful;
}
bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {
// The Structors need to be handled differently.
if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD)) {
// Cleanup the module if the transaction was committed and code was
// generated. This has to go first, because it may need the AST info
// which we will remove soon. (Eg. mangleDeclName iterates the redecls)
GlobalDecl GD(FD);
MaybeRemoveDeclFromModule(GD);
}
// FunctionDecl : DeclaratiorDecl, DeclContext, Redeclarable
bool Successful = VisitRedeclarable(FD, FD->getDeclContext());
Successful &= VisitDeclContext(FD);
Successful &= VisitDeclaratorDecl(FD);
// Template instantiation of templated function first creates a canonical
// declaration and after the actual template specialization. For example:
// template<typename T> T TemplatedF(T t);
// template<> int TemplatedF(int i) { return i + 1; } creates:
// 1. Canonical decl: int TemplatedF(int i);
// 2. int TemplatedF(int i){ return i + 1; }
//
// The template specialization is attached to the list of specialization of
// the templated function.
// When TemplatedF is looked up it finds the templated function and the
// lookup is extended by the templated function with its specializations.
// In the end we don't need to remove the canonical decl because, it
// doesn't end up in the lookup table.
//
class FunctionTemplateDeclExt : public FunctionTemplateDecl {
public:
static void removeSpecialization(FunctionTemplateDecl* self,
const FunctionDecl* specialization) {
assert(self && specialization && "Cannot be null!");
assert(specialization == specialization->getCanonicalDecl()
&& "Not the canonical specialization!?");
typedef llvm::SmallVector<FunctionDecl*, 4> Specializations;
typedef llvm::FoldingSetVector< FunctionTemplateSpecializationInfo> Set;
FunctionTemplateDeclExt* This = (FunctionTemplateDeclExt*) self;
Specializations specializations;
const Set& specs = This->getSpecializations();
if (!specs.size()) // nothing to remove
return;
// Collect all the specializations without the one to remove.
for(Set::const_iterator I = specs.begin(),E = specs.end(); I != E; ++I){
assert(I->Function && "Must have a specialization.");
if (I->Function != specialization)
specializations.push_back(I->Function);
}
This->getSpecializations().clear();
//Readd the collected specializations.
void* InsertPos = 0;
FunctionTemplateSpecializationInfo* FTSI = 0;
for (size_t i = 0, e = specializations.size(); i < e; ++i) {
FTSI = specializations[i]->getTemplateSpecializationInfo();
assert(FTSI && "Must not be null.");
// Avoid assertion on add.
FTSI->SetNextInBucket(0);
This->addSpecialization(FTSI, InsertPos);
}
#ifndef NDEBUG
const TemplateArgumentList* args
= specialization->getTemplateSpecializationArgs();
assert(!self->findSpecialization(args->data(), args->size(), InsertPos)
&& "Finds the removed decl again!");
#endif
}
};
if (FD->isFunctionTemplateSpecialization() && FD->isCanonicalDecl()) {
// Only the canonical declarations are registered in the list of the
// specializations.
FunctionTemplateDecl* FTD
= FD->getTemplateSpecializationInfo()->getTemplate();
// The canonical declaration of every specialization is registered with
// the FunctionTemplateDecl.
// Note this might revert too much in the case:
// template<typename T> T f(){ return T();}
// template<> int f();
// template<> int f() { return 0;}
// when the template specialization was forward declared the canonical
// becomes the first forward declaration. If the canonical forward
// declaration was declared outside the set of the decls to revert we have
// to keep it registered as a template specialization.
//
// In order to diagnose mismatches of the specializations, clang 'injects'
// a implicit forward declaration making it very hard distinguish between
// the explicit and the implicit forward declaration. So far the only way
// to distinguish is by source location comparison.
// FIXME: When the misbehavior of clang is fixed we must avoid relying on
// source locations
FunctionTemplateDeclExt::removeSpecialization(FTD, FD);
}
return Successful;
}
bool DeclReverter::VisitCXXConstructorDecl(CXXConstructorDecl* CXXCtor) {
// Cleanup the module if the transaction was committed and code was
// generated. This has to go first, because it may need the AST information
// which we will remove soon. (Eg. mangleDeclName iterates the redecls)
// Brute-force all possibly generated ctors.
// Ctor_Complete Complete object ctor.
// Ctor_Base Base object ctor.
// Ctor_CompleteAllocating Complete object allocating ctor.
GlobalDecl GD(CXXCtor, Ctor_Complete);
MaybeRemoveDeclFromModule(GD);
GD = GlobalDecl(CXXCtor, Ctor_Base);
MaybeRemoveDeclFromModule(GD);
GD = GlobalDecl(CXXCtor, Ctor_CompleteAllocating);
MaybeRemoveDeclFromModule(GD);
bool Successful = VisitCXXMethodDecl(CXXCtor);
return Successful;
}
bool DeclReverter::VisitDeclContext(DeclContext* DC) {
bool Successful = true;
typedef llvm::SmallVector<Decl*, 64> Decls;
Decls declsToErase;
// Removing from single-linked list invalidates the iterators.
for (DeclContext::decl_iterator I = DC->decls_begin();
I != DC->decls_end(); ++I) {
declsToErase.push_back(*I);
}
for(Decls::iterator I = declsToErase.begin(), E = declsToErase.end();
I != E; ++I)
Successful = Visit(*I) && Successful;
return Successful;
}
bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {
bool Successful = VisitDeclContext(NSD);
// If this wasn't the original namespace we need to nominate a new one and
// store it in the lookup tables.
DeclContext* DC = NSD->getDeclContext();
StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
if (!Map)
return false;
StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());
assert(Pos != Map->end() && !Pos->second.isNull()
&& "no lookup entry for decl");
if (NSD != NSD->getOriginalNamespace()) {
NamespaceDecl* NewNSD = NSD->getOriginalNamespace();
Pos->second.setOnlyValue(NewNSD);
if (Scope* S = m_Sema->getScopeForContext(DC))
S->AddDecl(NewNSD);
m_Sema->IdResolver.AddDecl(NewNSD);
}
Successful &= VisitNamedDecl(NSD);
return Successful;
}
bool DeclReverter::VisitTagDecl(TagDecl* TD) {
bool Successful = VisitDeclContext(TD);
Successful &= VisitTypeDecl(TD);
return Successful;
}
void DeclReverter::MaybeRemoveDeclFromModule(GlobalDecl& GD) const {
if (!m_CurTransaction->getModule()) // syntax-only mode exit
return;
using namespace llvm;
// if it was successfully removed from the AST we have to check whether
// code was generated and remove it.
// From llvm's mailing list, explanation of the RAUW'd assert:
//
// The problem isn't with your call to
// replaceAllUsesWith per se, the problem is that somebody (I would guess
// the JIT?) is holding it in a ValueMap.
//
// We used to have a problem that some parts of the code would keep a
// mapping like so:
// std::map<Value *, ...>
// while somebody else would modify the Value* without them noticing,
// leading to a dangling pointer in the map. To fix that, we invented the
// ValueMap which puts a Use that doesn't show up in the use_iterator on
// the Value it holds. When the Value is erased or RAUW'd, the ValueMap is
// notified and in this case decides that's not okay and terminates the
// program.
//
// Probably what's happened here is that the calling function has had its
// code generated by the JIT, but not the callee. Thus the JIT emitted a
// call to a generated stub, and will do the codegen of the callee once
// that stub is reached. Of course, once the JIT is in this state, it holds
// on to the Function with a ValueMap in order to prevent things from
// getting out of sync.
//
if (m_CurTransaction->getState() == Transaction::kCommitted) {
std::string mangledName;
utils::Analyze::maybeMangleDeclName(GD, mangledName);
GlobalValue* GV
= m_CurTransaction->getModule()->getNamedValue(mangledName);
if (GV) { // May be deferred decl and thus 0
GV->removeDeadConstantUsers();
if (!GV->use_empty()) {
// Assert that if there was a use it is not coming from the explicit
// AST node, but from the implicitly generated functions, which ensure
// the initialization order semantics. Such functions are:
// _GLOBAL__I* and __cxx_global_var_init*
//
// We can 'afford' to drop all the references because we know that the
// static init functions must be called only once, and that was
// already done.
SmallVector<User*, 4> uses;
for(llvm::Value::use_iterator I = GV->use_begin(), E = GV->use_end();
I != E; ++I) {
uses.push_back(*I);
}
for(SmallVector<User*, 4>::iterator I = uses.begin(), E = uses.end();
I != E; ++I)
if (llvm::Instruction* instr = dyn_cast<llvm::Instruction>(*I)) {
llvm::Function* F = instr->getParent()->getParent();
if (F->getName().startswith("__cxx_global_var_init"))
RemoveStaticInit(*F);
}
}
// Cleanup the jit mapping of GV->addr.
m_EEngine->updateGlobalMapping(GV, 0);
GV->dropAllReferences();
if (!GV->use_empty()) {
if (Function* F = dyn_cast<Function>(GV)) {
Function* dummy
= Function::Create(F->getFunctionType(), F->getLinkage());
F->replaceAllUsesWith(dummy);
}
else
GV->replaceAllUsesWith(UndefValue::get(GV->getType()));
}
GV->eraseFromParent();
}
}
}
void DeclReverter::RemoveStaticInit(llvm::Function& F) const {
// In our very controlled case the parent of the BasicBlock is the
// static init llvm::Function.
assert(F.getName().startswith("__cxx_global_var_init")
&& "Not a static init");
assert(F.hasInternalLinkage() && "Not a static init");
// The static init functions have the layout:
// declare internal void @__cxx_global_var_init1() section "..."
//
// define internal void @_GLOBAL__I_a2() section "..." {
// entry:
// call void @__cxx_global_var_init1()
// ret void
// }
//
assert(F.hasOneUse() && "Must have only one use");
// erase _GLOBAL__I* first
llvm::BasicBlock* BB = cast<llvm::Instruction>(F.use_back())->getParent();
BB->getParent()->eraseFromParent();
F.eraseFromParent();
}
// See Sema::PushOnScopeChains
bool DeclReverter::isOnScopeChains(NamedDecl* ND) {
// Named decls without name shouldn't be in. Eg: struct {int a};
if (!ND->getDeclName())
return false;
// Out-of-line definitions shouldn't be pushed into scope in C++.
// Out-of-line variable and function definitions shouldn't even in C.
if ((isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) && ND->isOutOfLine() &&
!ND->getDeclContext()->getRedeclContext()->Equals(
ND->getLexicalDeclContext()->getRedeclContext()))
return false;
// Template instantiations should also not be pushed into scope.
if (isa<FunctionDecl>(ND) &&
cast<FunctionDecl>(ND)->isFunctionTemplateSpecialization())
return false;
// Using directives are not registered onto the scope chain
if (isa<UsingDirectiveDecl>(ND))
return false;
IdentifierResolver::iterator
IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),
IDRiEnd = m_Sema->IdResolver.end();
for (; IDRi != IDRiEnd; ++IDRi) {
if (ND == *IDRi)
return true;
}
// Check if the declaration is template instantiation, which is not in
// any DeclContext yet, because it came from
// Sema::PerformPendingInstantiations
// if (isa<FunctionDecl>(D) &&
// cast<FunctionDecl>(D)->getTemplateInstantiationPattern())
// return false;
return false;
}
bool DeclReverter::VisitMacro(const Transaction::MacroDirectiveInfo MacroD) {
assert(MacroD.m_MD && "The MacroDirective is null");
assert(MacroD.m_II && "The IdentifierInfo is null");
CollectFilesToUncache(MacroD.m_MD->getLocation());
Preprocessor& PP = m_Sema->getPreprocessor();
#ifndef NDEBUG
bool ExistsInPP = false;
// Make sure the macro is in the Preprocessor. Not sure if not redundant
// because removeMacro looks for the macro anyway in the DenseMap Macros[]
for (Preprocessor::macro_iterator
I = PP.macro_begin(/*IncludeExternalMacros*/false),
E = PP.macro_end(/*IncludeExternalMacros*/false); E !=I; ++I) {
if ((*I).first == MacroD.m_II) {
// FIXME:check whether we have the concrete directive on the macro chain
// && (*I).second == MacroD.m_MD
ExistsInPP = true;
break;
}
}
assert(ExistsInPP && "Not in the Preprocessor?!");
#endif
const MacroDirective* MD = MacroD.m_MD;
// Undef the definition
const MacroInfo* MI = MD->getMacroInfo();
// If the macro is not defined, this is a noop undef, just return.
if (MI == 0)
return false;
// Remove the pair from the macros
PP.removeMacro(MacroD.m_II, const_cast<MacroDirective*>(MacroD.m_MD));
return true;
}
bool DeclReverter::VisitFunctionTemplateDecl(FunctionTemplateDecl* FTD) {
bool Successful = false;
// Remove specializations:
for (FunctionTemplateDecl::spec_iterator I = FTD->spec_begin(),
E = FTD->spec_end(); I != E; ++I)
Successful = Visit(*I);
Successful &= VisitFunctionDecl(FTD->getTemplatedDecl());
return Successful;
}
ASTNodeEraser::ASTNodeEraser(Sema* S, llvm::ExecutionEngine* EE)
: m_Sema(S), m_EEngine(EE) {
}
ASTNodeEraser::~ASTNodeEraser() {
}
bool ASTNodeEraser::RevertTransaction(Transaction* T) {
DeclReverter DeclRev(m_Sema, m_EEngine, T);
bool Successful = true;
for (Transaction::const_reverse_iterator I = T->rdecls_begin(),
E = T->rdecls_end(); I != E; ++I) {
if ((*I).m_Call != Transaction::kCCIHandleTopLevelDecl)
continue;
const DeclGroupRef& DGR = (*I).m_DGR;
for (DeclGroupRef::const_iterator
Di = DGR.end() - 1, E = DGR.begin() - 1; Di != E; --Di) {
// Get rid of the declaration. If the declaration has name we should
// heal the lookup tables as well
Successful = DeclRev.RevertDecl(*Di) && Successful;
}
}
#ifndef NDEBUG
assert(Successful && "Cannot handle that yet!");
#endif
m_Sema->getDiagnostics().Reset();
m_Sema->getDiagnostics().getClient()->clear();
// Cleanup the module from unused global values.
//llvm::ModulePass* globalDCE = llvm::createGlobalDCEPass();
//globalDCE->runOnModule(*T->getModule());
if (Successful)
T->setState(Transaction::kRolledBack);
else
T->setState(Transaction::kRolledBackWithErrors);
return Successful;
}
} // end namespace cling
Simplify the update of the lookup tables when visiting a redeclarable.
The key idea is that the decl that is being detached from the redecl chain can
be in registered in the lookup tables. In this case we need to check if there
is another decl in the chain and update the lookup table so that the existing
decls in the chain could be accessible.
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "ASTNodeEraser.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DependentDiagnostic.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/JIT.h" // For debugging the EE in gdb
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/IPO.h"
using namespace clang;
namespace cling {
///\brief The class does the actual work of removing a declaration and
/// resetting the internal structures of the compiler
///
class DeclReverter : public DeclVisitor<DeclReverter, bool> {
private:
typedef llvm::DenseSet<FileID> FileIDs;
///\brief The Sema object being reverted (contains the AST as well).
///
Sema* m_Sema;
///\brief The execution engine, either JIT or MCJIT, being recovered.
///
llvm::ExecutionEngine* m_EEngine;
///\brief The current transaction being reverted.
///
const Transaction* m_CurTransaction;
///\brief Reverted declaration contains a SourceLocation, representing a
/// place in the file where it was seen. Clang caches that file and even if
/// a declaration is removed and the file is edited we hit the cached entry.
/// This ADT keeps track of the files from which the reverted declarations
/// came from so that in the end they could be removed from clang's cache.
///
FileIDs m_FilesToUncache;
public:
DeclReverter(Sema* S, llvm::ExecutionEngine* EE, const Transaction* T)
: m_Sema(S), m_EEngine(EE), m_CurTransaction(T) { }
~DeclReverter();
///\brief Interface with nice name, forwarding to Visit.
///
///\param[in] D - The declaration to forward.
///\returns true on success.
///
bool RevertDecl(Decl* D) { return Visit(D); }
///\brief If it falls back in the base class just remove the declaration
/// only from the declaration context.
/// @param[in] D - The declaration to be removed.
///
///\returns true on success.
///
bool VisitDecl(Decl* D);
///\brief Removes the declaration from the lookup chains and from the
/// declaration context.
/// @param[in] ND - The declaration to be removed.
///
///\returns true on success.
///
bool VisitNamedDecl(NamedDecl* ND);
///\brief Removes the declaration from the lookup chains and from the
/// declaration context and it rebuilds the redeclaration chain.
/// @param[in] VD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitVarDecl(VarDecl* VD);
///\brief Removes the declaration from the lookup chains and from the
/// declaration context and it rebuilds the redeclaration chain.
/// @param[in] FD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitFunctionDecl(FunctionDecl* FD);
///\brief Specialize the removal of constructors due to the fact the we need
/// the constructor type (aka CXXCtorType). The information is located in
/// the CXXConstructExpr of usually VarDecls.
/// See clang::CodeGen::CodeGenFunction::EmitCXXConstructExpr.
///
/// What we will do instead is to brute-force and try to remove from the
/// llvm::Module all ctors of this class with all the types.
///
///\param[in] CXXCtor - The declaration to be removed.
///
///\returns true on success.
///
bool VisitCXXConstructorDecl(CXXConstructorDecl* CXXCtor);
///\brief Removes the DeclCotnext and its decls.
/// @param[in] DC - The declaration to be removed.
///
///\returns true on success.
///
bool VisitDeclContext(DeclContext* DC);
///\brief Removes the namespace.
/// @param[in] NSD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitNamespaceDecl(NamespaceDecl* NSD);
///\brief Removes a Tag (class/union/struct/enum). Most of the other
/// containers fall back into that case.
/// @param[in] TD - The declaration to be removed.
///
///\returns true on success.
///
bool VisitTagDecl(TagDecl* TD);
///\brief Remove the macro from the Preprocessor.
/// @param[in] MD - The MacroDirectiveInfo containing the IdentifierInfo and
/// MacroDirective to forward.
///
///\returns true on success.
///
bool VisitMacro(const Transaction::MacroDirectiveInfo MD);
///@name Templates
///@{
///\brief Removes template from the redecl chain. Templates are
/// redeclarables also.
/// @param[in] R - The declaration to be removed.
///
///\returns true on success.
///
bool VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl* R);
///@}
void MaybeRemoveDeclFromModule(GlobalDecl& GD) const;
void RemoveStaticInit(llvm::Function& F) const;
/// @name Helpers
/// @{
///\brief Checks whether the declaration was pushed onto the declaration
/// chains.
/// @param[in] ND - The declaration that is being checked.
///
///\returns true if the ND was found in the lookup chain.
///
bool isOnScopeChains(clang::NamedDecl* ND);
///\brief Interface with nice name, forwarding to Visit.
///
///\param[in] MD - The MacroDirectiveInfo containing the IdentifierInfo and
/// MacroDirective to forward.
///\returns true on success.
///
bool RevertMacro(const Transaction::MacroDirectiveInfo MD) { return VisitMacro(MD); }
///\brief Removes given declaration from the chain of redeclarations.
/// Rebuilds the chain and sets properly first and last redeclaration.
/// @param[in] R - The redeclarable, its chain to be rebuilt.
/// @param[in] DC - Remove the redecl's lookup entry from this DeclContext.
///
///\returns the most recent redeclaration in the new chain.
///
template <typename T>
bool VisitRedeclarable(clang::Redeclarable<T>* R, DeclContext* DC) {
llvm::SmallVector<T*, 4> PrevDecls;
T* PrevDecl = R->getMostRecentDecl();
// [0]=>C [1]=>B [2]=>A ...
while (PrevDecl) { // Collect the redeclarations, except the one we remove
if (PrevDecl != R)
PrevDecls.push_back(PrevDecl);
PrevDecl = PrevDecl->getPreviousDecl();
}
if (!PrevDecls.empty()) {
// Make sure we update the lookup maps, because the removed decl might
// be registered in the lookup and again findable.
StoredDeclsMap* Map = DC->getPrimaryContext()->getLookupPtr();
if (Map) {
NamedDecl* ND = (NamedDecl*)((T*)R);
DeclarationName Name = ND->getDeclName();
if (!Name.isEmpty()) {
StoredDeclsMap::iterator Pos = Map->find(Name);
if (Pos != Map->end() && !Pos->second.isNull()) {
DeclContext::lookup_result decls = Pos->second.getLookupResult();
for(DeclContext::lookup_result::iterator I = decls.begin(),
E = decls.end(); I != E; ++I) {
if (*I == ND) { // the decl is registered in the lookup
*I = PrevDecls[0];
break;
}
}
}
}
}
// Put 0 in the end of the array so that the loop will reset the
// pointer to latest redeclaration in the chain to itself.
//
PrevDecls.push_back(0);
// 0 <- A <- B <- C
for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {
PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);
}
}
return true;
}
/// @}
private:
///\brief Function that collects the files which we must reread from disk.
///
/// For example: We must uncache the cached include, which brought a
/// declaration or a macro diretive definition in the AST.
///\param[in] Loc - The source location of the reverted declaration.
///
void CollectFilesToUncache(SourceLocation Loc);
};
DeclReverter::~DeclReverter() {
SourceManager& SM = m_Sema->getSourceManager();
for (FileIDs::iterator I = m_FilesToUncache.begin(),
E = m_FilesToUncache.end(); I != E; ++I) {
const SrcMgr::FileInfo& fInfo = SM.getSLocEntry(*I).getFile();
// We need to reset the cache
SrcMgr::ContentCache* cache
= const_cast<SrcMgr::ContentCache*>(fInfo.getContentCache());
FileEntry* entry = const_cast<FileEntry*>(cache->ContentsEntry);
// We have to reset the file entry size to keep the cache and the file
// entry in sync.
if (entry) {
cache->replaceBuffer(0,/*free*/true);
FileManager::modifyFileEntry(entry, /*size*/0, 0);
}
}
// Clean up the pending instantiations
m_Sema->PendingInstantiations.clear();
m_Sema->PendingLocalImplicitInstantiations.clear();
}
void DeclReverter::CollectFilesToUncache(SourceLocation Loc) {
const SourceManager& SM = m_Sema->getSourceManager();
FileID FID = SM.getFileID(SM.getSpellingLoc(Loc));
if (!FID.isInvalid() && FID >= m_CurTransaction->getBufferFID()
&& !m_FilesToUncache.count(FID))
m_FilesToUncache.insert(FID);
}
// Gives us access to the protected members that we need.
class DeclContextExt : public DeclContext {
public:
static bool removeIfLast(DeclContext* DC, Decl* D) {
if (!D->getNextDeclInContext()) {
// Either last (remove!), or invalid (nothing to remove)
if (((DeclContextExt*)DC)->LastDecl == D) {
// Valid. Thus remove.
DC->removeDecl(D);
// Force rebuilding of the lookup table.
//DC->setMustBuildLookupTable();
return true;
}
}
else {
// Force rebuilding of the lookup table.
//DC->setMustBuildLookupTable();
DC->removeDecl(D);
return true;
}
return false;
}
};
bool DeclReverter::VisitDecl(Decl* D) {
assert(D && "The Decl is null");
CollectFilesToUncache(D->getLocStart());
DeclContext* DC = D->getLexicalDeclContext();
bool Successful = true;
DeclContextExt::removeIfLast(DC, D);
// With the bump allocator this is nop.
if (Successful)
m_Sema->getASTContext().Deallocate(D);
return Successful;
}
bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {
bool Successful = VisitDecl(ND);
DeclContext* DC = ND->getDeclContext();
while (DC->isTransparentContext())
DC = DC->getLookupParent();
// if the decl was anonymous we are done.
if (!ND->getIdentifier())
return Successful;
// If the decl was removed make sure that we fix the lookup
if (Successful) {
if (Scope* S = m_Sema->getScopeForContext(DC))
S->RemoveDecl(ND);
if (isOnScopeChains(ND))
m_Sema->IdResolver.RemoveDecl(ND);
}
// Cleanup the lookup tables.
StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
if (Map) { // DeclContexts like EnumDecls don't have lookup maps.
// Make sure we the decl doesn't exist in the lookup tables.
StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
if ( Pos != Map->end()) {
// Most decls only have one entry in their list, special case it.
if (Pos->second.getAsDecl() == ND)
Pos->second.remove(ND);
else if (StoredDeclsList::DeclsTy* Vec = Pos->second.getAsVector()) {
// Otherwise iterate over the list with entries with the same name.
// TODO: Walk the redeclaration chain if the entry was a redeclaration
for (StoredDeclsList::DeclsTy::const_iterator I = Vec->begin(),
E = Vec->end(); I != E; ++I)
if (*I == ND)
Pos->second.remove(ND);
}
if (Pos->second.isNull())
Map->erase(Pos);
}
}
#ifndef NDEBUG
if (Map) { // DeclContexts like EnumDecls don't have lookup maps.
// Make sure we the decl doesn't exist in the lookup tables.
StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
if ( Pos != Map->end()) {
// Most decls only have one entry in their list, special case it.
if (NamedDecl *OldD = Pos->second.getAsDecl())
assert(OldD != ND && "Lookup entry still exists.");
else if (StoredDeclsList::DeclsTy* Vec = Pos->second.getAsVector()) {
// Otherwise iterate over the list with entries with the same name.
// TODO: Walk the redeclaration chain if the entry was a redeclaration.
for (StoredDeclsList::DeclsTy::const_iterator I = Vec->begin(),
E = Vec->end(); I != E; ++I)
assert(*I != ND && "Lookup entry still exists.");
}
else
assert(Pos->second.isNull() && "!?");
}
}
#endif
return Successful;
}
bool DeclReverter::VisitVarDecl(VarDecl* VD) {
// Cleanup the module if the transaction was committed and code was
// generated. This has to go first, because it may need the AST information
// which we will remove soon. (Eg. mangleDeclName iterates the redecls)
GlobalDecl GD(VD);
MaybeRemoveDeclFromModule(GD);
// VarDecl : DeclaratiorDecl, Redeclarable
bool Successful = VisitRedeclarable(VD, VD->getDeclContext());
Successful &= VisitDeclaratorDecl(VD);
return Successful;
}
bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {
// The Structors need to be handled differently.
if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD)) {
// Cleanup the module if the transaction was committed and code was
// generated. This has to go first, because it may need the AST info
// which we will remove soon. (Eg. mangleDeclName iterates the redecls)
GlobalDecl GD(FD);
MaybeRemoveDeclFromModule(GD);
}
// FunctionDecl : DeclaratiorDecl, DeclContext, Redeclarable
bool Successful = VisitRedeclarable(FD, FD->getDeclContext());
Successful &= VisitDeclContext(FD);
Successful &= VisitDeclaratorDecl(FD);
// Template instantiation of templated function first creates a canonical
// declaration and after the actual template specialization. For example:
// template<typename T> T TemplatedF(T t);
// template<> int TemplatedF(int i) { return i + 1; } creates:
// 1. Canonical decl: int TemplatedF(int i);
// 2. int TemplatedF(int i){ return i + 1; }
//
// The template specialization is attached to the list of specialization of
// the templated function.
// When TemplatedF is looked up it finds the templated function and the
// lookup is extended by the templated function with its specializations.
// In the end we don't need to remove the canonical decl because, it
// doesn't end up in the lookup table.
//
class FunctionTemplateDeclExt : public FunctionTemplateDecl {
public:
static void removeSpecialization(FunctionTemplateDecl* self,
const FunctionDecl* specialization) {
assert(self && specialization && "Cannot be null!");
assert(specialization == specialization->getCanonicalDecl()
&& "Not the canonical specialization!?");
typedef llvm::SmallVector<FunctionDecl*, 4> Specializations;
typedef llvm::FoldingSetVector< FunctionTemplateSpecializationInfo> Set;
FunctionTemplateDeclExt* This = (FunctionTemplateDeclExt*) self;
Specializations specializations;
const Set& specs = This->getSpecializations();
if (!specs.size()) // nothing to remove
return;
// Collect all the specializations without the one to remove.
for(Set::const_iterator I = specs.begin(),E = specs.end(); I != E; ++I){
assert(I->Function && "Must have a specialization.");
if (I->Function != specialization)
specializations.push_back(I->Function);
}
This->getSpecializations().clear();
//Readd the collected specializations.
void* InsertPos = 0;
FunctionTemplateSpecializationInfo* FTSI = 0;
for (size_t i = 0, e = specializations.size(); i < e; ++i) {
FTSI = specializations[i]->getTemplateSpecializationInfo();
assert(FTSI && "Must not be null.");
// Avoid assertion on add.
FTSI->SetNextInBucket(0);
This->addSpecialization(FTSI, InsertPos);
}
#ifndef NDEBUG
const TemplateArgumentList* args
= specialization->getTemplateSpecializationArgs();
assert(!self->findSpecialization(args->data(), args->size(), InsertPos)
&& "Finds the removed decl again!");
#endif
}
};
if (FD->isFunctionTemplateSpecialization() && FD->isCanonicalDecl()) {
// Only the canonical declarations are registered in the list of the
// specializations.
FunctionTemplateDecl* FTD
= FD->getTemplateSpecializationInfo()->getTemplate();
// The canonical declaration of every specialization is registered with
// the FunctionTemplateDecl.
// Note this might revert too much in the case:
// template<typename T> T f(){ return T();}
// template<> int f();
// template<> int f() { return 0;}
// when the template specialization was forward declared the canonical
// becomes the first forward declaration. If the canonical forward
// declaration was declared outside the set of the decls to revert we have
// to keep it registered as a template specialization.
//
// In order to diagnose mismatches of the specializations, clang 'injects'
// a implicit forward declaration making it very hard distinguish between
// the explicit and the implicit forward declaration. So far the only way
// to distinguish is by source location comparison.
// FIXME: When the misbehavior of clang is fixed we must avoid relying on
// source locations
FunctionTemplateDeclExt::removeSpecialization(FTD, FD);
}
return Successful;
}
bool DeclReverter::VisitCXXConstructorDecl(CXXConstructorDecl* CXXCtor) {
// Cleanup the module if the transaction was committed and code was
// generated. This has to go first, because it may need the AST information
// which we will remove soon. (Eg. mangleDeclName iterates the redecls)
// Brute-force all possibly generated ctors.
// Ctor_Complete Complete object ctor.
// Ctor_Base Base object ctor.
// Ctor_CompleteAllocating Complete object allocating ctor.
GlobalDecl GD(CXXCtor, Ctor_Complete);
MaybeRemoveDeclFromModule(GD);
GD = GlobalDecl(CXXCtor, Ctor_Base);
MaybeRemoveDeclFromModule(GD);
GD = GlobalDecl(CXXCtor, Ctor_CompleteAllocating);
MaybeRemoveDeclFromModule(GD);
bool Successful = VisitCXXMethodDecl(CXXCtor);
return Successful;
}
bool DeclReverter::VisitDeclContext(DeclContext* DC) {
bool Successful = true;
typedef llvm::SmallVector<Decl*, 64> Decls;
Decls declsToErase;
// Removing from single-linked list invalidates the iterators.
for (DeclContext::decl_iterator I = DC->decls_begin();
I != DC->decls_end(); ++I) {
declsToErase.push_back(*I);
}
for(Decls::iterator I = declsToErase.begin(), E = declsToErase.end();
I != E; ++I)
Successful = Visit(*I) && Successful;
return Successful;
}
bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {
bool Successful = VisitDeclContext(NSD);
// If this wasn't the original namespace we need to nominate a new one and
// store it in the lookup tables.
DeclContext* DC = NSD->getDeclContext();
StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
if (!Map)
return false;
StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());
assert(Pos != Map->end() && !Pos->second.isNull()
&& "no lookup entry for decl");
if (NSD != NSD->getOriginalNamespace()) {
NamespaceDecl* NewNSD = NSD->getOriginalNamespace();
Pos->second.setOnlyValue(NewNSD);
if (Scope* S = m_Sema->getScopeForContext(DC))
S->AddDecl(NewNSD);
m_Sema->IdResolver.AddDecl(NewNSD);
}
Successful &= VisitNamedDecl(NSD);
return Successful;
}
bool DeclReverter::VisitTagDecl(TagDecl* TD) {
bool Successful = VisitDeclContext(TD);
Successful &= VisitTypeDecl(TD);
return Successful;
}
void DeclReverter::MaybeRemoveDeclFromModule(GlobalDecl& GD) const {
if (!m_CurTransaction->getModule()) // syntax-only mode exit
return;
using namespace llvm;
// if it was successfully removed from the AST we have to check whether
// code was generated and remove it.
// From llvm's mailing list, explanation of the RAUW'd assert:
//
// The problem isn't with your call to
// replaceAllUsesWith per se, the problem is that somebody (I would guess
// the JIT?) is holding it in a ValueMap.
//
// We used to have a problem that some parts of the code would keep a
// mapping like so:
// std::map<Value *, ...>
// while somebody else would modify the Value* without them noticing,
// leading to a dangling pointer in the map. To fix that, we invented the
// ValueMap which puts a Use that doesn't show up in the use_iterator on
// the Value it holds. When the Value is erased or RAUW'd, the ValueMap is
// notified and in this case decides that's not okay and terminates the
// program.
//
// Probably what's happened here is that the calling function has had its
// code generated by the JIT, but not the callee. Thus the JIT emitted a
// call to a generated stub, and will do the codegen of the callee once
// that stub is reached. Of course, once the JIT is in this state, it holds
// on to the Function with a ValueMap in order to prevent things from
// getting out of sync.
//
if (m_CurTransaction->getState() == Transaction::kCommitted) {
std::string mangledName;
utils::Analyze::maybeMangleDeclName(GD, mangledName);
GlobalValue* GV
= m_CurTransaction->getModule()->getNamedValue(mangledName);
if (GV) { // May be deferred decl and thus 0
GV->removeDeadConstantUsers();
if (!GV->use_empty()) {
// Assert that if there was a use it is not coming from the explicit
// AST node, but from the implicitly generated functions, which ensure
// the initialization order semantics. Such functions are:
// _GLOBAL__I* and __cxx_global_var_init*
//
// We can 'afford' to drop all the references because we know that the
// static init functions must be called only once, and that was
// already done.
SmallVector<User*, 4> uses;
for(llvm::Value::use_iterator I = GV->use_begin(), E = GV->use_end();
I != E; ++I) {
uses.push_back(*I);
}
for(SmallVector<User*, 4>::iterator I = uses.begin(), E = uses.end();
I != E; ++I)
if (llvm::Instruction* instr = dyn_cast<llvm::Instruction>(*I)) {
llvm::Function* F = instr->getParent()->getParent();
if (F->getName().startswith("__cxx_global_var_init"))
RemoveStaticInit(*F);
}
}
// Cleanup the jit mapping of GV->addr.
m_EEngine->updateGlobalMapping(GV, 0);
GV->dropAllReferences();
if (!GV->use_empty()) {
if (Function* F = dyn_cast<Function>(GV)) {
Function* dummy
= Function::Create(F->getFunctionType(), F->getLinkage());
F->replaceAllUsesWith(dummy);
}
else
GV->replaceAllUsesWith(UndefValue::get(GV->getType()));
}
GV->eraseFromParent();
}
}
}
void DeclReverter::RemoveStaticInit(llvm::Function& F) const {
// In our very controlled case the parent of the BasicBlock is the
// static init llvm::Function.
assert(F.getName().startswith("__cxx_global_var_init")
&& "Not a static init");
assert(F.hasInternalLinkage() && "Not a static init");
// The static init functions have the layout:
// declare internal void @__cxx_global_var_init1() section "..."
//
// define internal void @_GLOBAL__I_a2() section "..." {
// entry:
// call void @__cxx_global_var_init1()
// ret void
// }
//
assert(F.hasOneUse() && "Must have only one use");
// erase _GLOBAL__I* first
llvm::BasicBlock* BB = cast<llvm::Instruction>(F.use_back())->getParent();
BB->getParent()->eraseFromParent();
F.eraseFromParent();
}
// See Sema::PushOnScopeChains
bool DeclReverter::isOnScopeChains(NamedDecl* ND) {
// Named decls without name shouldn't be in. Eg: struct {int a};
if (!ND->getDeclName())
return false;
// Out-of-line definitions shouldn't be pushed into scope in C++.
// Out-of-line variable and function definitions shouldn't even in C.
if ((isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) && ND->isOutOfLine() &&
!ND->getDeclContext()->getRedeclContext()->Equals(
ND->getLexicalDeclContext()->getRedeclContext()))
return false;
// Template instantiations should also not be pushed into scope.
if (isa<FunctionDecl>(ND) &&
cast<FunctionDecl>(ND)->isFunctionTemplateSpecialization())
return false;
// Using directives are not registered onto the scope chain
if (isa<UsingDirectiveDecl>(ND))
return false;
IdentifierResolver::iterator
IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),
IDRiEnd = m_Sema->IdResolver.end();
for (; IDRi != IDRiEnd; ++IDRi) {
if (ND == *IDRi)
return true;
}
// Check if the declaration is template instantiation, which is not in
// any DeclContext yet, because it came from
// Sema::PerformPendingInstantiations
// if (isa<FunctionDecl>(D) &&
// cast<FunctionDecl>(D)->getTemplateInstantiationPattern())
// return false;
return false;
}
bool DeclReverter::VisitMacro(const Transaction::MacroDirectiveInfo MacroD) {
assert(MacroD.m_MD && "The MacroDirective is null");
assert(MacroD.m_II && "The IdentifierInfo is null");
CollectFilesToUncache(MacroD.m_MD->getLocation());
Preprocessor& PP = m_Sema->getPreprocessor();
#ifndef NDEBUG
bool ExistsInPP = false;
// Make sure the macro is in the Preprocessor. Not sure if not redundant
// because removeMacro looks for the macro anyway in the DenseMap Macros[]
for (Preprocessor::macro_iterator
I = PP.macro_begin(/*IncludeExternalMacros*/false),
E = PP.macro_end(/*IncludeExternalMacros*/false); E !=I; ++I) {
if ((*I).first == MacroD.m_II) {
// FIXME:check whether we have the concrete directive on the macro chain
// && (*I).second == MacroD.m_MD
ExistsInPP = true;
break;
}
}
assert(ExistsInPP && "Not in the Preprocessor?!");
#endif
const MacroDirective* MD = MacroD.m_MD;
// Undef the definition
const MacroInfo* MI = MD->getMacroInfo();
// If the macro is not defined, this is a noop undef, just return.
if (MI == 0)
return false;
// Remove the pair from the macros
PP.removeMacro(MacroD.m_II, const_cast<MacroDirective*>(MacroD.m_MD));
return true;
}
bool DeclReverter::VisitFunctionTemplateDecl(FunctionTemplateDecl* FTD) {
bool Successful = false;
// Remove specializations:
for (FunctionTemplateDecl::spec_iterator I = FTD->spec_begin(),
E = FTD->spec_end(); I != E; ++I)
Successful = Visit(*I);
Successful &= VisitFunctionDecl(FTD->getTemplatedDecl());
return Successful;
}
ASTNodeEraser::ASTNodeEraser(Sema* S, llvm::ExecutionEngine* EE)
: m_Sema(S), m_EEngine(EE) {
}
ASTNodeEraser::~ASTNodeEraser() {
}
bool ASTNodeEraser::RevertTransaction(Transaction* T) {
DeclReverter DeclRev(m_Sema, m_EEngine, T);
bool Successful = true;
for (Transaction::const_reverse_iterator I = T->rdecls_begin(),
E = T->rdecls_end(); I != E; ++I) {
if ((*I).m_Call != Transaction::kCCIHandleTopLevelDecl)
continue;
const DeclGroupRef& DGR = (*I).m_DGR;
for (DeclGroupRef::const_iterator
Di = DGR.end() - 1, E = DGR.begin() - 1; Di != E; --Di) {
// Get rid of the declaration. If the declaration has name we should
// heal the lookup tables as well
Successful = DeclRev.RevertDecl(*Di) && Successful;
}
}
#ifndef NDEBUG
assert(Successful && "Cannot handle that yet!");
#endif
m_Sema->getDiagnostics().Reset();
m_Sema->getDiagnostics().getClient()->clear();
// Cleanup the module from unused global values.
//llvm::ModulePass* globalDCE = llvm::createGlobalDCEPass();
//globalDCE->runOnModule(*T->getModule());
if (Successful)
T->setState(Transaction::kRolledBack);
else
T->setState(Transaction::kRolledBackWithErrors);
return Successful;
}
} // end namespace cling
|
#include "manipulatetoolview.h"
#include "manipulatetoolcontroller.h"
#include <QMouseEvent>
#include "terrainview.h"
#include "session.h"
#include "terrain.h"
#include "terrainedit.h"
ManipulateToolView::ManipulateToolView(ManipulateMode mode, Session *session, TerrainView *view) :
session(session),
view(view),
mode(mode),
hover(false),
otherActive(false),
active(false),
cursor(Qt::SizeVerCursor)
{
connect(view, SIGNAL(clientMousePressed(QMouseEvent*)), SLOT(clientMousePressed(QMouseEvent*)));
connect(view, SIGNAL(clientMouseReleased(QMouseEvent*)), SLOT(clientMouseReleased(QMouseEvent*)));
connect(view, SIGNAL(clientMouseMoved(QMouseEvent*)), SLOT(clientMouseMoved(QMouseEvent*)));
connect(view, SIGNAL(terrainPaint(TerrainViewDrawingContext*)), SLOT(terrainPaint(TerrainViewDrawingContext*)));
highlightImage = QImage(8, 8, QImage::Format_RGB32);
std::memset(highlightImage.bits(), 0, 8 * 8 * 4);
for (int i = 0; i < 8; ++i) {
uint col = 0xff00;
highlightImage.setPixel(i, 0, col);
highlightImage.setPixel(i, highlightImage.height() - 1, col);
highlightImage.setPixel(0, i, col);
highlightImage.setPixel(highlightImage.width() - 1, i, col);
}
}
ManipulateToolView::~ManipulateToolView()
{
}
void ManipulateToolView::clientMousePressed(QMouseEvent *e)
{
if (e->isAccepted()) {
otherActive = true;
return;
}
if (e->button() == Qt::LeftButton && hover) {
edit = session->beginEdit();
if (edit) {
active = true;
dragStartY = e->y();
dragStartHeight = session->terrain()->landform(pos.x(), pos.y());
if (mode == ManipulateMode::Landform)
view->addCursorOverride(&cursor);
}
e->accept();
}
}
void ManipulateToolView::clientMouseReleased(QMouseEvent *e)
{
if (active && e->button() == Qt::LeftButton) {
active = false;
session->endEdit();
e->accept();
if (mode == ManipulateMode::Landform)
view->removeCursorOverride(&cursor);
}
if (e->buttons() == 0) {
otherActive = false;
}
clientMouseMoved(e);
}
void ManipulateToolView::clientMouseMoved(QMouseEvent *e)
{
if (active && mode == ManipulateMode::Landform) {
float height = dragStartHeight + (e->y() - dragStartY) * .07f;
height = Terrain::quantizeOne(height);
edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
session->terrain()->landform(pos.x(), pos.y()) = height;
edit->endEdit(session->terrain().data());
} else {
hover = false;
if (e->x() >= 0 && e->y() >= 0 && e->x() < view->width() && e->y() < view->height()) {
pos = view->rayCast(e->pos());
auto t = session->terrain();
if (pos.x() >= 0 && pos.y() >= 0 && pos.x() < t->size().width() && pos.y() < t->size().height())
hover = true;
}
if (active && mode == ManipulateMode::Color) {
// set color
if (hover) {
edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
session->terrain()->color(pos.x(), pos.y()) = session->primaryColor();
edit->endEdit(session->terrain().data());
}
}
}
view->update();
}
void ManipulateToolView::terrainPaint(TerrainViewDrawingContext *ctx)
{
if (hover) {
ctx->projectBitmap(highlightImage, QPointF(pos.x() + .05f, pos.y() + .05f), QSizeF(.9f, .9f), true);
}
}
Made "paint" tool better
#include "manipulatetoolview.h"
#include "manipulatetoolcontroller.h"
#include <QMouseEvent>
#include "terrainview.h"
#include "session.h"
#include "terrain.h"
#include "terrainedit.h"
ManipulateToolView::ManipulateToolView(ManipulateMode mode, Session *session, TerrainView *view) :
session(session),
view(view),
mode(mode),
hover(false),
otherActive(false),
active(false),
cursor(Qt::SizeVerCursor)
{
connect(view, SIGNAL(clientMousePressed(QMouseEvent*)), SLOT(clientMousePressed(QMouseEvent*)));
connect(view, SIGNAL(clientMouseReleased(QMouseEvent*)), SLOT(clientMouseReleased(QMouseEvent*)));
connect(view, SIGNAL(clientMouseMoved(QMouseEvent*)), SLOT(clientMouseMoved(QMouseEvent*)));
connect(view, SIGNAL(terrainPaint(TerrainViewDrawingContext*)), SLOT(terrainPaint(TerrainViewDrawingContext*)));
highlightImage = QImage(8, 8, QImage::Format_RGB32);
std::memset(highlightImage.bits(), 0, 8 * 8 * 4);
for (int i = 0; i < 8; ++i) {
uint col = 0xff00;
highlightImage.setPixel(i, 0, col);
highlightImage.setPixel(i, highlightImage.height() - 1, col);
highlightImage.setPixel(0, i, col);
highlightImage.setPixel(highlightImage.width() - 1, i, col);
}
}
ManipulateToolView::~ManipulateToolView()
{
}
void ManipulateToolView::clientMousePressed(QMouseEvent *e)
{
if (e->isAccepted()) {
otherActive = true;
return;
}
if (e->button() == Qt::LeftButton && hover) {
edit = session->beginEdit();
if (edit) {
active = true;
dragStartY = e->y();
dragStartHeight = session->terrain()->landform(pos.x(), pos.y());
if (mode == ManipulateMode::Landform)
view->addCursorOverride(&cursor);
clientMouseMoved(e);
}
e->accept();
}
}
void ManipulateToolView::clientMouseReleased(QMouseEvent *e)
{
if (active && e->button() == Qt::LeftButton) {
active = false;
session->endEdit();
e->accept();
if (mode == ManipulateMode::Landform)
view->removeCursorOverride(&cursor);
}
if (e->buttons() == 0) {
otherActive = false;
}
clientMouseMoved(e);
}
void ManipulateToolView::clientMouseMoved(QMouseEvent *e)
{
if (active && mode == ManipulateMode::Landform) {
float height = dragStartHeight + (e->y() - dragStartY) * .07f;
height = Terrain::quantizeOne(height);
edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
session->terrain()->landform(pos.x(), pos.y()) = height;
edit->endEdit(session->terrain().data());
} else {
hover = false;
if (e->x() >= 0 && e->y() >= 0 && e->x() < view->width() && e->y() < view->height()) {
pos = view->rayCast(e->pos());
auto t = session->terrain();
if (pos.x() >= 0 && pos.y() >= 0 && pos.x() < t->size().width() && pos.y() < t->size().height())
hover = true;
}
if (active && mode == ManipulateMode::Color) {
// set color
if (hover) {
edit->beginEdit(QRect(pos.x(), pos.y(), 1, 1), session->terrain().data());
session->terrain()->color(pos.x(), pos.y()) = session->primaryColor();
edit->endEdit(session->terrain().data());
}
}
}
view->update();
}
void ManipulateToolView::terrainPaint(TerrainViewDrawingContext *ctx)
{
if (hover) {
ctx->projectBitmap(highlightImage, QPointF(pos.x() + .05f, pos.y() + .05f), QSizeF(.9f, .9f), true);
}
}
|
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <functional>
#include <initializer_list>
#include <vector>
#include "DMGpuSupport.h"
#include "SkAutoPixmapStorage.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkData.h"
#include "SkImageEncoder.h"
#include "SkImageGenerator.h"
#include "SkImage_Base.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkPixelSerializer.h"
#include "SkRRect.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkUtils.h"
#include "Test.h"
using namespace sk_gpu_test;
static void assert_equal(skiatest::Reporter* reporter, SkImage* a, const SkIRect* subsetA,
SkImage* b) {
const int widthA = subsetA ? subsetA->width() : a->width();
const int heightA = subsetA ? subsetA->height() : a->height();
REPORTER_ASSERT(reporter, widthA == b->width());
REPORTER_ASSERT(reporter, heightA == b->height());
// see https://bug.skia.org/3965
//REPORTER_ASSERT(reporter, a->isOpaque() == b->isOpaque());
SkImageInfo info = SkImageInfo::MakeN32(widthA, heightA,
a->isOpaque() ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
SkAutoPixmapStorage pmapA, pmapB;
pmapA.alloc(info);
pmapB.alloc(info);
const int srcX = subsetA ? subsetA->x() : 0;
const int srcY = subsetA ? subsetA->y() : 0;
REPORTER_ASSERT(reporter, a->readPixels(pmapA, srcX, srcY));
REPORTER_ASSERT(reporter, b->readPixels(pmapB, 0, 0));
const size_t widthBytes = widthA * info.bytesPerPixel();
for (int y = 0; y < heightA; ++y) {
REPORTER_ASSERT(reporter, !memcmp(pmapA.addr32(0, y), pmapB.addr32(0, y), widthBytes));
}
}
static void draw_image_test_pattern(SkCanvas* canvas) {
canvas->clear(SK_ColorWHITE);
SkPaint paint;
paint.setColor(SK_ColorBLACK);
canvas->drawRect(SkRect::MakeXYWH(5, 5, 10, 10), paint);
}
static sk_sp<SkImage> create_image() {
const SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRaster(info));
draw_image_test_pattern(surface->getCanvas());
return surface->makeImageSnapshot();
}
static SkData* create_image_data(SkImageInfo* info) {
*info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
const size_t rowBytes = info->minRowBytes();
SkAutoTUnref<SkData> data(SkData::NewUninitialized(rowBytes * info->height()));
{
SkBitmap bm;
bm.installPixels(*info, data->writable_data(), rowBytes);
SkCanvas canvas(bm);
draw_image_test_pattern(&canvas);
}
return data.release();
}
static sk_sp<SkImage> create_data_image() {
SkImageInfo info;
sk_sp<SkData> data(create_image_data(&info));
return SkImage::MakeRasterData(info, data, info.minRowBytes());
}
#if SK_SUPPORT_GPU // not gpu-specific but currently only used in GPU tests
static sk_sp<SkImage> create_image_565() {
const SkImageInfo info = SkImageInfo::Make(20, 20, kRGB_565_SkColorType, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRaster(info));
draw_image_test_pattern(surface->getCanvas());
return surface->makeImageSnapshot();
}
static sk_sp<SkImage> create_image_large() {
const SkImageInfo info = SkImageInfo::MakeN32(32000, 32, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRaster(info));
surface->getCanvas()->clear(SK_ColorWHITE);
SkPaint paint;
paint.setColor(SK_ColorBLACK);
surface->getCanvas()->drawRect(SkRect::MakeXYWH(4000, 2, 28000, 30), paint);
return surface->makeImageSnapshot();
}
static sk_sp<SkImage> create_image_ct() {
SkPMColor colors[] = {
SkPreMultiplyARGB(0xFF, 0xFF, 0xFF, 0x00),
SkPreMultiplyARGB(0x80, 0x00, 0xA0, 0xFF),
SkPreMultiplyARGB(0xFF, 0xBB, 0x00, 0xBB)
};
SkAutoTUnref<SkColorTable> colorTable(new SkColorTable(colors, SK_ARRAY_COUNT(colors)));
uint8_t data[] = {
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 1, 2, 1, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0
};
SkImageInfo info = SkImageInfo::Make(5, 5, kIndex_8_SkColorType, kPremul_SkAlphaType);
return SkImage::MakeRasterCopy(SkPixmap(info, data, 5, colorTable));
}
static sk_sp<SkImage> create_picture_image() {
SkPictureRecorder recorder;
SkCanvas* canvas = recorder.beginRecording(10, 10);
canvas->clear(SK_ColorCYAN);
return SkImage::MakeFromPicture(recorder.finishRecordingAsPicture(), SkISize::Make(10, 10),
nullptr, nullptr);
};
#endif
// Want to ensure that our Release is called when the owning image is destroyed
struct RasterDataHolder {
RasterDataHolder() : fReleaseCount(0) {}
SkAutoTUnref<SkData> fData;
int fReleaseCount;
static void Release(const void* pixels, void* context) {
RasterDataHolder* self = static_cast<RasterDataHolder*>(context);
self->fReleaseCount++;
self->fData.reset();
}
};
static sk_sp<SkImage> create_rasterproc_image(RasterDataHolder* dataHolder) {
SkASSERT(dataHolder);
SkImageInfo info;
SkAutoTUnref<SkData> data(create_image_data(&info));
dataHolder->fData.reset(SkRef(data.get()));
return SkImage::MakeFromRaster(SkPixmap(info, data->data(), info.minRowBytes()),
RasterDataHolder::Release, dataHolder);
}
static sk_sp<SkImage> create_codec_image() {
SkImageInfo info;
SkAutoTUnref<SkData> data(create_image_data(&info));
SkBitmap bitmap;
bitmap.installPixels(info, data->writable_data(), info.minRowBytes());
sk_sp<SkData> src(
SkImageEncoder::EncodeData(bitmap, SkImageEncoder::kPNG_Type, 100));
return SkImage::MakeFromEncoded(src);
}
#if SK_SUPPORT_GPU
static sk_sp<SkImage> create_gpu_image(GrContext* context) {
const SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info));
draw_image_test_pattern(surface->getCanvas());
return surface->makeImageSnapshot();
}
#endif
static void test_encode(skiatest::Reporter* reporter, SkImage* image) {
const SkIRect ir = SkIRect::MakeXYWH(5, 5, 10, 10);
sk_sp<SkData> origEncoded(image->encode());
REPORTER_ASSERT(reporter, origEncoded);
REPORTER_ASSERT(reporter, origEncoded->size() > 0);
sk_sp<SkImage> decoded(SkImage::MakeFromEncoded(origEncoded));
REPORTER_ASSERT(reporter, decoded);
assert_equal(reporter, image, nullptr, decoded.get());
// Now see if we can instantiate an image from a subset of the surface/origEncoded
decoded = SkImage::MakeFromEncoded(origEncoded, &ir);
REPORTER_ASSERT(reporter, decoded);
assert_equal(reporter, image, &ir, decoded.get());
}
DEF_TEST(ImageEncode, reporter) {
test_encode(reporter, create_image().get());
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageEncode_Gpu, reporter, ctxInfo) {
test_encode(reporter, create_gpu_image(ctxInfo.grContext()).get());
}
#endif
namespace {
const char* kSerializedData = "serialized";
class MockSerializer : public SkPixelSerializer {
public:
MockSerializer(SkData* (*func)()) : fFunc(func), fDidEncode(false) { }
bool didEncode() const { return fDidEncode; }
protected:
bool onUseEncodedData(const void*, size_t) override {
return false;
}
SkData* onEncode(const SkPixmap&) override {
fDidEncode = true;
return fFunc();
}
private:
SkData* (*fFunc)();
bool fDidEncode;
typedef SkPixelSerializer INHERITED;
};
} // anonymous namespace
// Test that SkImage encoding observes custom pixel serializers.
DEF_TEST(Image_Encode_Serializer, reporter) {
MockSerializer serializer([]() -> SkData* { return SkData::NewWithCString(kSerializedData); });
sk_sp<SkImage> image(create_image());
SkAutoTUnref<SkData> encoded(image->encode(&serializer));
SkAutoTUnref<SkData> reference(SkData::NewWithCString(kSerializedData));
REPORTER_ASSERT(reporter, serializer.didEncode());
REPORTER_ASSERT(reporter, encoded);
REPORTER_ASSERT(reporter, encoded->size() > 0);
REPORTER_ASSERT(reporter, encoded->equals(reference));
}
// Test that image encoding failures do not break picture serialization/deserialization.
DEF_TEST(Image_Serialize_Encoding_Failure, reporter) {
auto surface(SkSurface::MakeRasterN32Premul(100, 100));
surface->getCanvas()->clear(SK_ColorGREEN);
sk_sp<SkImage> image(surface->makeImageSnapshot());
REPORTER_ASSERT(reporter, image);
SkPictureRecorder recorder;
SkCanvas* canvas = recorder.beginRecording(100, 100);
canvas->drawImage(image, 0, 0);
sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
REPORTER_ASSERT(reporter, picture);
REPORTER_ASSERT(reporter, picture->approximateOpCount() > 0);
MockSerializer emptySerializer([]() -> SkData* { return SkData::NewEmpty(); });
MockSerializer nullSerializer([]() -> SkData* { return nullptr; });
MockSerializer* serializers[] = { &emptySerializer, &nullSerializer };
for (size_t i = 0; i < SK_ARRAY_COUNT(serializers); ++i) {
SkDynamicMemoryWStream wstream;
REPORTER_ASSERT(reporter, !serializers[i]->didEncode());
picture->serialize(&wstream, serializers[i]);
REPORTER_ASSERT(reporter, serializers[i]->didEncode());
SkAutoTDelete<SkStream> rstream(wstream.detachAsStream());
sk_sp<SkPicture> deserialized(SkPicture::MakeFromStream(rstream));
REPORTER_ASSERT(reporter, deserialized);
REPORTER_ASSERT(reporter, deserialized->approximateOpCount() > 0);
}
}
DEF_TEST(Image_NewRasterCopy, reporter) {
const SkPMColor red = SkPackARGB32(0xFF, 0xFF, 0, 0);
const SkPMColor green = SkPackARGB32(0xFF, 0, 0xFF, 0);
const SkPMColor blue = SkPackARGB32(0xFF, 0, 0, 0xFF);
SkPMColor colors[] = { red, green, blue, 0 };
SkAutoTUnref<SkColorTable> ctable(new SkColorTable(colors, SK_ARRAY_COUNT(colors)));
// The colortable made a copy, so we can trash the original colors
memset(colors, 0xFF, sizeof(colors));
const SkImageInfo srcInfo = SkImageInfo::Make(2, 2, kIndex_8_SkColorType, kPremul_SkAlphaType);
const size_t srcRowBytes = 2 * sizeof(uint8_t);
uint8_t indices[] = { 0, 1, 2, 3 };
sk_sp<SkImage> image(SkImage::MakeRasterCopy(SkPixmap(srcInfo, indices, srcRowBytes, ctable)));
// The image made a copy, so we can trash the original indices
memset(indices, 0xFF, sizeof(indices));
const SkImageInfo dstInfo = SkImageInfo::MakeN32Premul(2, 2);
const size_t dstRowBytes = 2 * sizeof(SkPMColor);
SkPMColor pixels[4];
memset(pixels, 0xFF, sizeof(pixels)); // init with values we don't expect
image->readPixels(dstInfo, pixels, dstRowBytes, 0, 0);
REPORTER_ASSERT(reporter, red == pixels[0]);
REPORTER_ASSERT(reporter, green == pixels[1]);
REPORTER_ASSERT(reporter, blue == pixels[2]);
REPORTER_ASSERT(reporter, 0 == pixels[3]);
}
// Test that a draw that only partially covers the drawing surface isn't
// interpreted as covering the entire drawing surface (i.e., exercise one of the
// conditions of SkCanvas::wouldOverwriteEntireSurface()).
DEF_TEST(Image_RetainSnapshot, reporter) {
const SkPMColor red = SkPackARGB32(0xFF, 0xFF, 0, 0);
const SkPMColor green = SkPackARGB32(0xFF, 0, 0xFF, 0);
SkImageInfo info = SkImageInfo::MakeN32Premul(2, 2);
auto surface(SkSurface::MakeRaster(info));
surface->getCanvas()->clear(0xFF00FF00);
SkPMColor pixels[4];
memset(pixels, 0xFF, sizeof(pixels)); // init with values we don't expect
const SkImageInfo dstInfo = SkImageInfo::MakeN32Premul(2, 2);
const size_t dstRowBytes = 2 * sizeof(SkPMColor);
sk_sp<SkImage> image1(surface->makeImageSnapshot());
REPORTER_ASSERT(reporter, image1->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
for (size_t i = 0; i < SK_ARRAY_COUNT(pixels); ++i) {
REPORTER_ASSERT(reporter, pixels[i] == green);
}
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kSrc_Mode);
paint.setColor(SK_ColorRED);
surface->getCanvas()->drawRect(SkRect::MakeXYWH(1, 1, 1, 1), paint);
sk_sp<SkImage> image2(surface->makeImageSnapshot());
REPORTER_ASSERT(reporter, image2->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
REPORTER_ASSERT(reporter, pixels[0] == green);
REPORTER_ASSERT(reporter, pixels[1] == green);
REPORTER_ASSERT(reporter, pixels[2] == green);
REPORTER_ASSERT(reporter, pixels[3] == red);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
static void make_bitmap_mutable(SkBitmap* bm) {
bm->allocN32Pixels(10, 10);
}
static void make_bitmap_immutable(SkBitmap* bm) {
bm->allocN32Pixels(10, 10);
bm->setImmutable();
}
DEF_TEST(image_newfrombitmap, reporter) {
const struct {
void (*fMakeProc)(SkBitmap*);
bool fExpectPeekSuccess;
bool fExpectSharedID;
bool fExpectLazy;
} rec[] = {
{ make_bitmap_mutable, true, false, false },
{ make_bitmap_immutable, true, true, false },
};
for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
SkBitmap bm;
rec[i].fMakeProc(&bm);
sk_sp<SkImage> image(SkImage::MakeFromBitmap(bm));
SkPixmap pmap;
const bool sharedID = (image->uniqueID() == bm.getGenerationID());
REPORTER_ASSERT(reporter, sharedID == rec[i].fExpectSharedID);
const bool peekSuccess = image->peekPixels(&pmap);
REPORTER_ASSERT(reporter, peekSuccess == rec[i].fExpectPeekSuccess);
const bool lazy = image->isLazyGenerated();
REPORTER_ASSERT(reporter, lazy == rec[i].fExpectLazy);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "SkBitmapCache.h"
/*
* This tests the caching (and preemptive purge) of the raster equivalent of a gpu-image.
* We cache it for performance when drawing into a raster surface.
*
* A cleaner test would know if each drawImage call triggered a read-back from the gpu,
* but we don't have that facility (at the moment) so we use a little internal knowledge
* of *how* the raster version is cached, and look for that.
*/
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(c, reporter, ctxInfo) {
SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
const uint32_t uniqueID = image->uniqueID();
auto surface(SkSurface::MakeRaster(info));
// now we can test drawing a gpu-backed image into a cpu-backed surface
{
SkBitmap cachedBitmap;
REPORTER_ASSERT(reporter, !SkBitmapCache::Find(uniqueID, &cachedBitmap));
}
surface->getCanvas()->drawImage(image, 0, 0);
{
SkBitmap cachedBitmap;
if (SkBitmapCache::Find(uniqueID, &cachedBitmap)) {
REPORTER_ASSERT(reporter, cachedBitmap.getGenerationID() == uniqueID);
REPORTER_ASSERT(reporter, cachedBitmap.isImmutable());
REPORTER_ASSERT(reporter, cachedBitmap.getPixels());
} else {
// unexpected, but not really a bug, since the cache is global and this test may be
// run w/ other threads competing for its budget.
SkDebugf("SkImage_Gpu2Cpu : cachedBitmap was already purged\n");
}
}
image.reset(nullptr);
{
SkBitmap cachedBitmap;
REPORTER_ASSERT(reporter, !SkBitmapCache::Find(uniqueID, &cachedBitmap));
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_newTextureImage, reporter, contextInfo) {
GrContext* context = contextInfo.grContext();
sk_gpu_test::TestContext* testContext = contextInfo.testContext();
GrContextFactory otherFactory;
GrContextFactory::ContextType otherContextType =
GrContextFactory::NativeContextTypeForBackend(testContext->backend());
ContextInfo otherContextInfo = otherFactory.getContextInfo(otherContextType);
testContext->makeCurrent();
std::function<sk_sp<SkImage>()> imageFactories[] = {
create_image,
create_codec_image,
create_data_image,
// Create an image from a picture.
create_picture_image,
// Create a texture image.
[context] { return create_gpu_image(context); },
// Create a texture image in a another GrContext.
[testContext, otherContextInfo] {
otherContextInfo.testContext()->makeCurrent();
sk_sp<SkImage> otherContextImage = create_gpu_image(otherContextInfo.grContext());
testContext->makeCurrent();
return otherContextImage;
}
};
for (auto factory : imageFactories) {
sk_sp<SkImage> image(factory());
if (!image) {
ERRORF(reporter, "Error creating image.");
continue;
}
GrTexture* origTexture = as_IB(image)->peekTexture();
sk_sp<SkImage> texImage(image->makeTextureImage(context));
if (!texImage) {
// We execpt to fail if image comes from a different GrContext.
if (!origTexture || origTexture->getContext() == context) {
ERRORF(reporter, "newTextureImage failed.");
}
continue;
}
GrTexture* copyTexture = as_IB(texImage)->peekTexture();
if (!copyTexture) {
ERRORF(reporter, "newTextureImage returned non-texture image.");
continue;
}
if (origTexture) {
if (origTexture != copyTexture) {
ERRORF(reporter, "newTextureImage made unnecessary texture copy.");
}
}
if (image->width() != texImage->width() || image->height() != texImage->height()) {
ERRORF(reporter, "newTextureImage changed the image size.");
}
if (image->isOpaque() != texImage->isOpaque()) {
ERRORF(reporter, "newTextureImage changed image opaqueness.");
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_drawAbandonedGpuImage, reporter, contextInfo) {
auto context = contextInfo.grContext();
auto image = create_gpu_image(context);
auto info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info));
as_IB(image)->peekTexture()->abandon();
surface->getCanvas()->drawImage(image, 0, 0);
}
#endif
// https://bug.skia.org/4390
DEF_TEST(ImageFromIndex8Bitmap, r) {
SkPMColor pmColors[1] = {SkPreMultiplyColor(SK_ColorWHITE)};
SkBitmap bm;
SkAutoTUnref<SkColorTable> ctable(
new SkColorTable(pmColors, SK_ARRAY_COUNT(pmColors)));
SkImageInfo info =
SkImageInfo::Make(1, 1, kIndex_8_SkColorType, kPremul_SkAlphaType);
bm.allocPixels(info, nullptr, ctable);
SkAutoLockPixels autoLockPixels(bm);
*bm.getAddr8(0, 0) = 0;
sk_sp<SkImage> img(SkImage::MakeFromBitmap(bm));
REPORTER_ASSERT(r, img != nullptr);
}
class EmptyGenerator : public SkImageGenerator {
public:
EmptyGenerator() : SkImageGenerator(SkImageInfo::MakeN32Premul(0, 0)) {}
};
DEF_TEST(ImageEmpty, reporter) {
const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
SkPixmap pmap(info, nullptr, 0);
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeRasterCopy(pmap));
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeRasterData(info, nullptr, 0));
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeFromRaster(pmap, nullptr, nullptr));
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeFromGenerator(new EmptyGenerator));
}
DEF_TEST(ImageDataRef, reporter) {
SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
size_t rowBytes = info.minRowBytes();
size_t size = info.getSafeSize(rowBytes);
sk_sp<SkData> data = SkData::MakeUninitialized(size);
REPORTER_ASSERT(reporter, data->unique());
sk_sp<SkImage> image = SkImage::MakeRasterData(info, data, rowBytes);
REPORTER_ASSERT(reporter, !data->unique());
image.reset();
REPORTER_ASSERT(reporter, data->unique());
}
static bool has_pixels(const SkPMColor pixels[], int count, SkPMColor expected) {
for (int i = 0; i < count; ++i) {
if (pixels[i] != expected) {
return false;
}
}
return true;
}
static void test_read_pixels(skiatest::Reporter* reporter, SkImage* image) {
const SkPMColor expected = SkPreMultiplyColor(SK_ColorWHITE);
const SkPMColor notExpected = ~expected;
const int w = 2, h = 2;
const size_t rowBytes = w * sizeof(SkPMColor);
SkPMColor pixels[w*h];
SkImageInfo info;
info = SkImageInfo::MakeUnknown(w, h);
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, 0));
// out-of-bounds should fail
info = SkImageInfo::MakeN32Premul(w, h);
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, -w, 0));
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, -h));
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, image->width(), 0));
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, image->height()));
// top-left should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, 0, 0));
REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
// bottom-right should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
image->width() - w, image->height() - h));
REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
// partial top-left should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, -1, -1));
REPORTER_ASSERT(reporter, pixels[3] == expected);
REPORTER_ASSERT(reporter, has_pixels(pixels, w*h - 1, notExpected));
// partial bottom-right should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
image->width() - 1, image->height() - 1));
REPORTER_ASSERT(reporter, pixels[0] == expected);
REPORTER_ASSERT(reporter, has_pixels(&pixels[1], w*h - 1, notExpected));
}
DEF_TEST(ImageReadPixels, reporter) {
sk_sp<SkImage> image(create_image());
test_read_pixels(reporter, image.get());
image = create_data_image();
test_read_pixels(reporter, image.get());
RasterDataHolder dataHolder;
image = create_rasterproc_image(&dataHolder);
test_read_pixels(reporter, image.get());
image.reset();
REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
image = create_codec_image();
test_read_pixels(reporter, image.get());
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ImageReadPixels_Gpu, reporter, ctxInfo) {
test_read_pixels(reporter, create_gpu_image(ctxInfo.grContext()).get());
}
#endif
static void check_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image,
const SkBitmap& bitmap, SkImage::LegacyBitmapMode mode) {
REPORTER_ASSERT(reporter, image->width() == bitmap.width());
REPORTER_ASSERT(reporter, image->height() == bitmap.height());
REPORTER_ASSERT(reporter, image->isOpaque() == bitmap.isOpaque());
if (SkImage::kRO_LegacyBitmapMode == mode) {
REPORTER_ASSERT(reporter, bitmap.isImmutable());
}
SkAutoLockPixels alp(bitmap);
REPORTER_ASSERT(reporter, bitmap.getPixels());
const SkImageInfo info = SkImageInfo::MakeN32(1, 1, bitmap.alphaType());
SkPMColor imageColor;
REPORTER_ASSERT(reporter, image->readPixels(info, &imageColor, sizeof(SkPMColor), 0, 0));
REPORTER_ASSERT(reporter, imageColor == *bitmap.getAddr32(0, 0));
}
static void test_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image, SkImage::LegacyBitmapMode mode) {
SkBitmap bitmap;
REPORTER_ASSERT(reporter, image->asLegacyBitmap(&bitmap, mode));
check_legacy_bitmap(reporter, image, bitmap, mode);
// Test subsetting to exercise the rowBytes logic.
SkBitmap tmp;
REPORTER_ASSERT(reporter, bitmap.extractSubset(&tmp, SkIRect::MakeWH(image->width() / 2,
image->height() / 2)));
sk_sp<SkImage> subsetImage(SkImage::MakeFromBitmap(tmp));
REPORTER_ASSERT(reporter, subsetImage.get());
SkBitmap subsetBitmap;
REPORTER_ASSERT(reporter, subsetImage->asLegacyBitmap(&subsetBitmap, mode));
check_legacy_bitmap(reporter, subsetImage.get(), subsetBitmap, mode);
}
DEF_TEST(ImageLegacyBitmap, reporter) {
const SkImage::LegacyBitmapMode modes[] = {
SkImage::kRO_LegacyBitmapMode,
SkImage::kRW_LegacyBitmapMode,
};
for (auto& mode : modes) {
sk_sp<SkImage> image(create_image());
test_legacy_bitmap(reporter, image.get(), mode);
image = create_data_image();
test_legacy_bitmap(reporter, image.get(), mode);
RasterDataHolder dataHolder;
image = create_rasterproc_image(&dataHolder);
test_legacy_bitmap(reporter, image.get(), mode);
image.reset();
REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
image = create_codec_image();
test_legacy_bitmap(reporter, image.get(), mode);
}
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageLegacyBitmap_Gpu, reporter, ctxInfo) {
const SkImage::LegacyBitmapMode modes[] = {
SkImage::kRO_LegacyBitmapMode,
SkImage::kRW_LegacyBitmapMode,
};
for (auto& mode : modes) {
sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
test_legacy_bitmap(reporter, image.get(), mode);
}
}
#endif
static void test_peek(skiatest::Reporter* reporter, SkImage* image, bool expectPeekSuccess) {
SkPixmap pm;
bool success = image->peekPixels(&pm);
REPORTER_ASSERT(reporter, expectPeekSuccess == success);
if (success) {
const SkImageInfo& info = pm.info();
REPORTER_ASSERT(reporter, 20 == info.width());
REPORTER_ASSERT(reporter, 20 == info.height());
REPORTER_ASSERT(reporter, kN32_SkColorType == info.colorType());
REPORTER_ASSERT(reporter, kPremul_SkAlphaType == info.alphaType() ||
kOpaque_SkAlphaType == info.alphaType());
REPORTER_ASSERT(reporter, info.minRowBytes() <= pm.rowBytes());
REPORTER_ASSERT(reporter, SkPreMultiplyColor(SK_ColorWHITE) == *pm.addr32(0, 0));
}
}
DEF_TEST(ImagePeek, reporter) {
sk_sp<SkImage> image(create_image());
test_peek(reporter, image.get(), true);
image = create_data_image();
test_peek(reporter, image.get(), true);
RasterDataHolder dataHolder;
image = create_rasterproc_image(&dataHolder);
test_peek(reporter, image.get(), true);
image.reset();
REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
image = create_codec_image();
test_peek(reporter, image.get(), false);
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ImagePeek_Gpu, reporter, ctxInfo) {
sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
test_peek(reporter, image.get(), false);
}
#endif
#if SK_SUPPORT_GPU
struct TextureReleaseChecker {
TextureReleaseChecker() : fReleaseCount(0) {}
int fReleaseCount;
static void Release(void* self) {
static_cast<TextureReleaseChecker*>(self)->fReleaseCount++;
}
};
static void check_image_color(skiatest::Reporter* reporter, SkImage* image, SkPMColor expected) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
SkPMColor pixel;
REPORTER_ASSERT(reporter, image->readPixels(info, &pixel, sizeof(pixel), 0, 0));
REPORTER_ASSERT(reporter, pixel == expected);
}
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_NewFromTexture, reporter, ctxInfo) {
GrTextureProvider* provider = ctxInfo.grContext()->textureProvider();
const int w = 10;
const int h = 10;
SkPMColor storage[w * h];
const SkPMColor expected0 = SkPreMultiplyColor(SK_ColorRED);
sk_memset32(storage, expected0, w * h);
GrSurfaceDesc desc;
desc.fFlags = kRenderTarget_GrSurfaceFlag; // needs to be a rendertarget for readpixels();
desc.fOrigin = kDefault_GrSurfaceOrigin;
desc.fWidth = w;
desc.fHeight = h;
desc.fConfig = kSkia8888_GrPixelConfig;
desc.fSampleCnt = 0;
SkAutoTUnref<GrTexture> tex(provider->createTexture(desc, SkBudgeted::kNo, storage, w * 4));
if (!tex) {
REPORTER_ASSERT(reporter, false);
return;
}
GrBackendTextureDesc backendDesc;
backendDesc.fConfig = kSkia8888_GrPixelConfig;
backendDesc.fFlags = kRenderTarget_GrBackendTextureFlag;
backendDesc.fWidth = w;
backendDesc.fHeight = h;
backendDesc.fSampleCnt = 0;
backendDesc.fTextureHandle = tex->getTextureHandle();
TextureReleaseChecker releaseChecker;
sk_sp<SkImage> refImg(
SkImage::MakeFromTexture(ctxInfo.grContext(), backendDesc, kPremul_SkAlphaType,
TextureReleaseChecker::Release, &releaseChecker));
sk_sp<SkImage> cpyImg(SkImage::MakeFromTextureCopy(ctxInfo.grContext(), backendDesc,
kPremul_SkAlphaType));
check_image_color(reporter, refImg.get(), expected0);
check_image_color(reporter, cpyImg.get(), expected0);
// Now lets jam new colors into our "external" texture, and see if the images notice
const SkPMColor expected1 = SkPreMultiplyColor(SK_ColorBLUE);
sk_memset32(storage, expected1, w * h);
tex->writePixels(0, 0, w, h, kSkia8888_GrPixelConfig, storage, GrContext::kFlushWrites_PixelOp);
// The cpy'd one should still see the old color
#if 0
// There is no guarantee that refImg sees the new color. We are free to have made a copy. Our
// write pixels call violated the contract with refImg and refImg is now undefined.
check_image_color(reporter, refImg, expected1);
#endif
check_image_color(reporter, cpyImg.get(), expected0);
// Now exercise the release proc
REPORTER_ASSERT(reporter, 0 == releaseChecker.fReleaseCount);
refImg.reset(nullptr); // force a release of the image
REPORTER_ASSERT(reporter, 1 == releaseChecker.fReleaseCount);
}
static void check_images_same(skiatest::Reporter* reporter, const SkImage* a, const SkImage* b) {
if (a->width() != b->width() || a->height() != b->height()) {
ERRORF(reporter, "Images must have the same size");
return;
}
if (a->isOpaque() != b->isOpaque()) {
ERRORF(reporter, "Images must have the same opaquness");
return;
}
SkImageInfo info = SkImageInfo::MakeN32Premul(a->width(), a->height());
SkAutoPixmapStorage apm;
SkAutoPixmapStorage bpm;
apm.alloc(info);
bpm.alloc(info);
if (!a->readPixels(apm, 0, 0)) {
ERRORF(reporter, "Could not read image a's pixels");
return;
}
if (!b->readPixels(bpm, 0, 0)) {
ERRORF(reporter, "Could not read image b's pixels");
return;
}
for (auto y = 0; y < info.height(); ++y) {
for (auto x = 0; x < info.width(); ++x) {
uint32_t pixelA = *apm.addr32(x, y);
uint32_t pixelB = *bpm.addr32(x, y);
if (pixelA != pixelB) {
ERRORF(reporter, "Expected image pixels to be the same. At %d,%d 0x%08x != 0x%08x",
x, y, pixelA, pixelB);
return;
}
}
}
}
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(NewTextureFromPixmap, reporter, ctxInfo) {
for (auto create : {&create_image,
&create_image_565,
&create_image_ct}) {
sk_sp<SkImage> image((*create)());
if (!image) {
ERRORF(reporter, "Could not create image");
return;
}
SkPixmap pixmap;
if (!image->peekPixels(&pixmap)) {
ERRORF(reporter, "peek failed");
} else {
sk_sp<SkImage> texImage(SkImage::MakeTextureFromPixmap(ctxInfo.grContext(), pixmap,
SkBudgeted::kNo));
if (!texImage) {
ERRORF(reporter, "NewTextureFromPixmap failed.");
} else {
check_images_same(reporter, image.get(), texImage.get());
}
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(DeferredTextureImage, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
sk_gpu_test::TestContext* testContext = ctxInfo.testContext();
SkAutoTUnref<GrContextThreadSafeProxy> proxy(context->threadSafeProxy());
GrContextFactory otherFactory;
ContextInfo otherContextInfo =
otherFactory.getContextInfo(GrContextFactory::kNativeGL_ContextType);
testContext->makeCurrent();
REPORTER_ASSERT(reporter, proxy);
struct {
std::function<sk_sp<SkImage> ()> fImageFactory;
std::vector<SkImage::DeferredTextureImageUsageParams> fParams;
SkFilterQuality fExpectedQuality;
int fExpectedScaleFactor;
bool fExpectation;
} testCases[] = {
{ create_image, {{}}, kNone_SkFilterQuality, 1, true },
{ create_codec_image, {{}}, kNone_SkFilterQuality, 1, true },
{ create_data_image, {{}}, kNone_SkFilterQuality, 1, true },
{ create_picture_image, {{}}, kNone_SkFilterQuality, 1, false },
{ [context] { return create_gpu_image(context); }, {{}}, kNone_SkFilterQuality, 1, false },
// Create a texture image in a another GrContext.
{ [testContext, otherContextInfo] {
otherContextInfo.testContext()->makeCurrent();
sk_sp<SkImage> otherContextImage = create_gpu_image(otherContextInfo.grContext());
testContext->makeCurrent();
return otherContextImage;
}, {{}}, kNone_SkFilterQuality, 1, false },
// Create an image that is too large to upload.
{ create_image_large, {{}}, kNone_SkFilterQuality, 1, false },
// Create an image that is too large, but is scaled to an acceptable size.
{ create_image_large, {{SkMatrix::I(), kMedium_SkFilterQuality, 4}},
kMedium_SkFilterQuality, 16, true},
// Create an image with multiple low filter qualities, make sure we round up.
{ create_image_large, {{SkMatrix::I(), kNone_SkFilterQuality, 4},
{SkMatrix::I(), kMedium_SkFilterQuality, 4}},
kMedium_SkFilterQuality, 16, true},
// Create an image with multiple prescale levels, make sure we chose the minimum scale.
{ create_image_large, {{SkMatrix::I(), kMedium_SkFilterQuality, 5},
{SkMatrix::I(), kMedium_SkFilterQuality, 4}},
kMedium_SkFilterQuality, 16, true},
};
for (auto testCase : testCases) {
sk_sp<SkImage> image(testCase.fImageFactory());
size_t size = image->getDeferredTextureImageData(*proxy, testCase.fParams.data(),
static_cast<int>(testCase.fParams.size()),
nullptr);
static const char *const kFS[] = { "fail", "succeed" };
if (SkToBool(size) != testCase.fExpectation) {
ERRORF(reporter, "This image was expected to %s but did not.",
kFS[testCase.fExpectation]);
}
if (size) {
void* buffer = sk_malloc_throw(size);
void* misaligned = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(buffer) + 3);
if (image->getDeferredTextureImageData(*proxy, testCase.fParams.data(),
static_cast<int>(testCase.fParams.size()),
misaligned)) {
ERRORF(reporter, "Should fail when buffer is misaligned.");
}
if (!image->getDeferredTextureImageData(*proxy, testCase.fParams.data(),
static_cast<int>(testCase.fParams.size()),
buffer)) {
ERRORF(reporter, "deferred image size succeeded but creation failed.");
} else {
for (auto budgeted : { SkBudgeted::kNo, SkBudgeted::kYes }) {
sk_sp<SkImage> newImage(
SkImage::MakeFromDeferredTextureImageData(context, buffer, budgeted));
REPORTER_ASSERT(reporter, newImage != nullptr);
if (newImage) {
// Scale the image in software for comparison.
SkImageInfo scaled_info = SkImageInfo::MakeN32(
image->width() / testCase.fExpectedScaleFactor,
image->height() / testCase.fExpectedScaleFactor,
image->isOpaque() ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
SkAutoPixmapStorage scaled;
scaled.alloc(scaled_info);
image->scalePixels(scaled, testCase.fExpectedQuality);
sk_sp<SkImage> scaledImage = SkImage::MakeRasterCopy(scaled);
check_images_same(reporter, scaledImage.get(), newImage.get());
}
// The other context should not be able to create images from texture data
// created by the original context.
sk_sp<SkImage> newImage2(SkImage::MakeFromDeferredTextureImageData(
otherContextInfo.grContext(), buffer, budgeted));
REPORTER_ASSERT(reporter, !newImage2);
testContext->makeCurrent();
}
}
sk_free(buffer);
}
}
}
#endif
Disable SkImage_drawAbandonedGpuImage on Vulkan.
It crashes issuing a clear batch.
GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2060263005
TBR=brianosman@google.com
Review-Url: https://codereview.chromium.org/2060263005
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <functional>
#include <initializer_list>
#include <vector>
#include "DMGpuSupport.h"
#include "SkAutoPixmapStorage.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkData.h"
#include "SkImageEncoder.h"
#include "SkImageGenerator.h"
#include "SkImage_Base.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkPixelSerializer.h"
#include "SkRRect.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkUtils.h"
#include "Test.h"
using namespace sk_gpu_test;
static void assert_equal(skiatest::Reporter* reporter, SkImage* a, const SkIRect* subsetA,
SkImage* b) {
const int widthA = subsetA ? subsetA->width() : a->width();
const int heightA = subsetA ? subsetA->height() : a->height();
REPORTER_ASSERT(reporter, widthA == b->width());
REPORTER_ASSERT(reporter, heightA == b->height());
// see https://bug.skia.org/3965
//REPORTER_ASSERT(reporter, a->isOpaque() == b->isOpaque());
SkImageInfo info = SkImageInfo::MakeN32(widthA, heightA,
a->isOpaque() ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
SkAutoPixmapStorage pmapA, pmapB;
pmapA.alloc(info);
pmapB.alloc(info);
const int srcX = subsetA ? subsetA->x() : 0;
const int srcY = subsetA ? subsetA->y() : 0;
REPORTER_ASSERT(reporter, a->readPixels(pmapA, srcX, srcY));
REPORTER_ASSERT(reporter, b->readPixels(pmapB, 0, 0));
const size_t widthBytes = widthA * info.bytesPerPixel();
for (int y = 0; y < heightA; ++y) {
REPORTER_ASSERT(reporter, !memcmp(pmapA.addr32(0, y), pmapB.addr32(0, y), widthBytes));
}
}
static void draw_image_test_pattern(SkCanvas* canvas) {
canvas->clear(SK_ColorWHITE);
SkPaint paint;
paint.setColor(SK_ColorBLACK);
canvas->drawRect(SkRect::MakeXYWH(5, 5, 10, 10), paint);
}
static sk_sp<SkImage> create_image() {
const SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRaster(info));
draw_image_test_pattern(surface->getCanvas());
return surface->makeImageSnapshot();
}
static SkData* create_image_data(SkImageInfo* info) {
*info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
const size_t rowBytes = info->minRowBytes();
SkAutoTUnref<SkData> data(SkData::NewUninitialized(rowBytes * info->height()));
{
SkBitmap bm;
bm.installPixels(*info, data->writable_data(), rowBytes);
SkCanvas canvas(bm);
draw_image_test_pattern(&canvas);
}
return data.release();
}
static sk_sp<SkImage> create_data_image() {
SkImageInfo info;
sk_sp<SkData> data(create_image_data(&info));
return SkImage::MakeRasterData(info, data, info.minRowBytes());
}
#if SK_SUPPORT_GPU // not gpu-specific but currently only used in GPU tests
static sk_sp<SkImage> create_image_565() {
const SkImageInfo info = SkImageInfo::Make(20, 20, kRGB_565_SkColorType, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRaster(info));
draw_image_test_pattern(surface->getCanvas());
return surface->makeImageSnapshot();
}
static sk_sp<SkImage> create_image_large() {
const SkImageInfo info = SkImageInfo::MakeN32(32000, 32, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRaster(info));
surface->getCanvas()->clear(SK_ColorWHITE);
SkPaint paint;
paint.setColor(SK_ColorBLACK);
surface->getCanvas()->drawRect(SkRect::MakeXYWH(4000, 2, 28000, 30), paint);
return surface->makeImageSnapshot();
}
static sk_sp<SkImage> create_image_ct() {
SkPMColor colors[] = {
SkPreMultiplyARGB(0xFF, 0xFF, 0xFF, 0x00),
SkPreMultiplyARGB(0x80, 0x00, 0xA0, 0xFF),
SkPreMultiplyARGB(0xFF, 0xBB, 0x00, 0xBB)
};
SkAutoTUnref<SkColorTable> colorTable(new SkColorTable(colors, SK_ARRAY_COUNT(colors)));
uint8_t data[] = {
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 1, 2, 1, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0
};
SkImageInfo info = SkImageInfo::Make(5, 5, kIndex_8_SkColorType, kPremul_SkAlphaType);
return SkImage::MakeRasterCopy(SkPixmap(info, data, 5, colorTable));
}
static sk_sp<SkImage> create_picture_image() {
SkPictureRecorder recorder;
SkCanvas* canvas = recorder.beginRecording(10, 10);
canvas->clear(SK_ColorCYAN);
return SkImage::MakeFromPicture(recorder.finishRecordingAsPicture(), SkISize::Make(10, 10),
nullptr, nullptr);
};
#endif
// Want to ensure that our Release is called when the owning image is destroyed
struct RasterDataHolder {
RasterDataHolder() : fReleaseCount(0) {}
SkAutoTUnref<SkData> fData;
int fReleaseCount;
static void Release(const void* pixels, void* context) {
RasterDataHolder* self = static_cast<RasterDataHolder*>(context);
self->fReleaseCount++;
self->fData.reset();
}
};
static sk_sp<SkImage> create_rasterproc_image(RasterDataHolder* dataHolder) {
SkASSERT(dataHolder);
SkImageInfo info;
SkAutoTUnref<SkData> data(create_image_data(&info));
dataHolder->fData.reset(SkRef(data.get()));
return SkImage::MakeFromRaster(SkPixmap(info, data->data(), info.minRowBytes()),
RasterDataHolder::Release, dataHolder);
}
static sk_sp<SkImage> create_codec_image() {
SkImageInfo info;
SkAutoTUnref<SkData> data(create_image_data(&info));
SkBitmap bitmap;
bitmap.installPixels(info, data->writable_data(), info.minRowBytes());
sk_sp<SkData> src(
SkImageEncoder::EncodeData(bitmap, SkImageEncoder::kPNG_Type, 100));
return SkImage::MakeFromEncoded(src);
}
#if SK_SUPPORT_GPU
static sk_sp<SkImage> create_gpu_image(GrContext* context) {
const SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info));
draw_image_test_pattern(surface->getCanvas());
return surface->makeImageSnapshot();
}
#endif
static void test_encode(skiatest::Reporter* reporter, SkImage* image) {
const SkIRect ir = SkIRect::MakeXYWH(5, 5, 10, 10);
sk_sp<SkData> origEncoded(image->encode());
REPORTER_ASSERT(reporter, origEncoded);
REPORTER_ASSERT(reporter, origEncoded->size() > 0);
sk_sp<SkImage> decoded(SkImage::MakeFromEncoded(origEncoded));
REPORTER_ASSERT(reporter, decoded);
assert_equal(reporter, image, nullptr, decoded.get());
// Now see if we can instantiate an image from a subset of the surface/origEncoded
decoded = SkImage::MakeFromEncoded(origEncoded, &ir);
REPORTER_ASSERT(reporter, decoded);
assert_equal(reporter, image, &ir, decoded.get());
}
DEF_TEST(ImageEncode, reporter) {
test_encode(reporter, create_image().get());
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageEncode_Gpu, reporter, ctxInfo) {
test_encode(reporter, create_gpu_image(ctxInfo.grContext()).get());
}
#endif
namespace {
const char* kSerializedData = "serialized";
class MockSerializer : public SkPixelSerializer {
public:
MockSerializer(SkData* (*func)()) : fFunc(func), fDidEncode(false) { }
bool didEncode() const { return fDidEncode; }
protected:
bool onUseEncodedData(const void*, size_t) override {
return false;
}
SkData* onEncode(const SkPixmap&) override {
fDidEncode = true;
return fFunc();
}
private:
SkData* (*fFunc)();
bool fDidEncode;
typedef SkPixelSerializer INHERITED;
};
} // anonymous namespace
// Test that SkImage encoding observes custom pixel serializers.
DEF_TEST(Image_Encode_Serializer, reporter) {
MockSerializer serializer([]() -> SkData* { return SkData::NewWithCString(kSerializedData); });
sk_sp<SkImage> image(create_image());
SkAutoTUnref<SkData> encoded(image->encode(&serializer));
SkAutoTUnref<SkData> reference(SkData::NewWithCString(kSerializedData));
REPORTER_ASSERT(reporter, serializer.didEncode());
REPORTER_ASSERT(reporter, encoded);
REPORTER_ASSERT(reporter, encoded->size() > 0);
REPORTER_ASSERT(reporter, encoded->equals(reference));
}
// Test that image encoding failures do not break picture serialization/deserialization.
DEF_TEST(Image_Serialize_Encoding_Failure, reporter) {
auto surface(SkSurface::MakeRasterN32Premul(100, 100));
surface->getCanvas()->clear(SK_ColorGREEN);
sk_sp<SkImage> image(surface->makeImageSnapshot());
REPORTER_ASSERT(reporter, image);
SkPictureRecorder recorder;
SkCanvas* canvas = recorder.beginRecording(100, 100);
canvas->drawImage(image, 0, 0);
sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
REPORTER_ASSERT(reporter, picture);
REPORTER_ASSERT(reporter, picture->approximateOpCount() > 0);
MockSerializer emptySerializer([]() -> SkData* { return SkData::NewEmpty(); });
MockSerializer nullSerializer([]() -> SkData* { return nullptr; });
MockSerializer* serializers[] = { &emptySerializer, &nullSerializer };
for (size_t i = 0; i < SK_ARRAY_COUNT(serializers); ++i) {
SkDynamicMemoryWStream wstream;
REPORTER_ASSERT(reporter, !serializers[i]->didEncode());
picture->serialize(&wstream, serializers[i]);
REPORTER_ASSERT(reporter, serializers[i]->didEncode());
SkAutoTDelete<SkStream> rstream(wstream.detachAsStream());
sk_sp<SkPicture> deserialized(SkPicture::MakeFromStream(rstream));
REPORTER_ASSERT(reporter, deserialized);
REPORTER_ASSERT(reporter, deserialized->approximateOpCount() > 0);
}
}
DEF_TEST(Image_NewRasterCopy, reporter) {
const SkPMColor red = SkPackARGB32(0xFF, 0xFF, 0, 0);
const SkPMColor green = SkPackARGB32(0xFF, 0, 0xFF, 0);
const SkPMColor blue = SkPackARGB32(0xFF, 0, 0, 0xFF);
SkPMColor colors[] = { red, green, blue, 0 };
SkAutoTUnref<SkColorTable> ctable(new SkColorTable(colors, SK_ARRAY_COUNT(colors)));
// The colortable made a copy, so we can trash the original colors
memset(colors, 0xFF, sizeof(colors));
const SkImageInfo srcInfo = SkImageInfo::Make(2, 2, kIndex_8_SkColorType, kPremul_SkAlphaType);
const size_t srcRowBytes = 2 * sizeof(uint8_t);
uint8_t indices[] = { 0, 1, 2, 3 };
sk_sp<SkImage> image(SkImage::MakeRasterCopy(SkPixmap(srcInfo, indices, srcRowBytes, ctable)));
// The image made a copy, so we can trash the original indices
memset(indices, 0xFF, sizeof(indices));
const SkImageInfo dstInfo = SkImageInfo::MakeN32Premul(2, 2);
const size_t dstRowBytes = 2 * sizeof(SkPMColor);
SkPMColor pixels[4];
memset(pixels, 0xFF, sizeof(pixels)); // init with values we don't expect
image->readPixels(dstInfo, pixels, dstRowBytes, 0, 0);
REPORTER_ASSERT(reporter, red == pixels[0]);
REPORTER_ASSERT(reporter, green == pixels[1]);
REPORTER_ASSERT(reporter, blue == pixels[2]);
REPORTER_ASSERT(reporter, 0 == pixels[3]);
}
// Test that a draw that only partially covers the drawing surface isn't
// interpreted as covering the entire drawing surface (i.e., exercise one of the
// conditions of SkCanvas::wouldOverwriteEntireSurface()).
DEF_TEST(Image_RetainSnapshot, reporter) {
const SkPMColor red = SkPackARGB32(0xFF, 0xFF, 0, 0);
const SkPMColor green = SkPackARGB32(0xFF, 0, 0xFF, 0);
SkImageInfo info = SkImageInfo::MakeN32Premul(2, 2);
auto surface(SkSurface::MakeRaster(info));
surface->getCanvas()->clear(0xFF00FF00);
SkPMColor pixels[4];
memset(pixels, 0xFF, sizeof(pixels)); // init with values we don't expect
const SkImageInfo dstInfo = SkImageInfo::MakeN32Premul(2, 2);
const size_t dstRowBytes = 2 * sizeof(SkPMColor);
sk_sp<SkImage> image1(surface->makeImageSnapshot());
REPORTER_ASSERT(reporter, image1->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
for (size_t i = 0; i < SK_ARRAY_COUNT(pixels); ++i) {
REPORTER_ASSERT(reporter, pixels[i] == green);
}
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kSrc_Mode);
paint.setColor(SK_ColorRED);
surface->getCanvas()->drawRect(SkRect::MakeXYWH(1, 1, 1, 1), paint);
sk_sp<SkImage> image2(surface->makeImageSnapshot());
REPORTER_ASSERT(reporter, image2->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
REPORTER_ASSERT(reporter, pixels[0] == green);
REPORTER_ASSERT(reporter, pixels[1] == green);
REPORTER_ASSERT(reporter, pixels[2] == green);
REPORTER_ASSERT(reporter, pixels[3] == red);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
static void make_bitmap_mutable(SkBitmap* bm) {
bm->allocN32Pixels(10, 10);
}
static void make_bitmap_immutable(SkBitmap* bm) {
bm->allocN32Pixels(10, 10);
bm->setImmutable();
}
DEF_TEST(image_newfrombitmap, reporter) {
const struct {
void (*fMakeProc)(SkBitmap*);
bool fExpectPeekSuccess;
bool fExpectSharedID;
bool fExpectLazy;
} rec[] = {
{ make_bitmap_mutable, true, false, false },
{ make_bitmap_immutable, true, true, false },
};
for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
SkBitmap bm;
rec[i].fMakeProc(&bm);
sk_sp<SkImage> image(SkImage::MakeFromBitmap(bm));
SkPixmap pmap;
const bool sharedID = (image->uniqueID() == bm.getGenerationID());
REPORTER_ASSERT(reporter, sharedID == rec[i].fExpectSharedID);
const bool peekSuccess = image->peekPixels(&pmap);
REPORTER_ASSERT(reporter, peekSuccess == rec[i].fExpectPeekSuccess);
const bool lazy = image->isLazyGenerated();
REPORTER_ASSERT(reporter, lazy == rec[i].fExpectLazy);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "SkBitmapCache.h"
/*
* This tests the caching (and preemptive purge) of the raster equivalent of a gpu-image.
* We cache it for performance when drawing into a raster surface.
*
* A cleaner test would know if each drawImage call triggered a read-back from the gpu,
* but we don't have that facility (at the moment) so we use a little internal knowledge
* of *how* the raster version is cached, and look for that.
*/
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(c, reporter, ctxInfo) {
SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
const uint32_t uniqueID = image->uniqueID();
auto surface(SkSurface::MakeRaster(info));
// now we can test drawing a gpu-backed image into a cpu-backed surface
{
SkBitmap cachedBitmap;
REPORTER_ASSERT(reporter, !SkBitmapCache::Find(uniqueID, &cachedBitmap));
}
surface->getCanvas()->drawImage(image, 0, 0);
{
SkBitmap cachedBitmap;
if (SkBitmapCache::Find(uniqueID, &cachedBitmap)) {
REPORTER_ASSERT(reporter, cachedBitmap.getGenerationID() == uniqueID);
REPORTER_ASSERT(reporter, cachedBitmap.isImmutable());
REPORTER_ASSERT(reporter, cachedBitmap.getPixels());
} else {
// unexpected, but not really a bug, since the cache is global and this test may be
// run w/ other threads competing for its budget.
SkDebugf("SkImage_Gpu2Cpu : cachedBitmap was already purged\n");
}
}
image.reset(nullptr);
{
SkBitmap cachedBitmap;
REPORTER_ASSERT(reporter, !SkBitmapCache::Find(uniqueID, &cachedBitmap));
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_newTextureImage, reporter, contextInfo) {
GrContext* context = contextInfo.grContext();
sk_gpu_test::TestContext* testContext = contextInfo.testContext();
GrContextFactory otherFactory;
GrContextFactory::ContextType otherContextType =
GrContextFactory::NativeContextTypeForBackend(testContext->backend());
ContextInfo otherContextInfo = otherFactory.getContextInfo(otherContextType);
testContext->makeCurrent();
std::function<sk_sp<SkImage>()> imageFactories[] = {
create_image,
create_codec_image,
create_data_image,
// Create an image from a picture.
create_picture_image,
// Create a texture image.
[context] { return create_gpu_image(context); },
// Create a texture image in a another GrContext.
[testContext, otherContextInfo] {
otherContextInfo.testContext()->makeCurrent();
sk_sp<SkImage> otherContextImage = create_gpu_image(otherContextInfo.grContext());
testContext->makeCurrent();
return otherContextImage;
}
};
for (auto factory : imageFactories) {
sk_sp<SkImage> image(factory());
if (!image) {
ERRORF(reporter, "Error creating image.");
continue;
}
GrTexture* origTexture = as_IB(image)->peekTexture();
sk_sp<SkImage> texImage(image->makeTextureImage(context));
if (!texImage) {
// We execpt to fail if image comes from a different GrContext.
if (!origTexture || origTexture->getContext() == context) {
ERRORF(reporter, "newTextureImage failed.");
}
continue;
}
GrTexture* copyTexture = as_IB(texImage)->peekTexture();
if (!copyTexture) {
ERRORF(reporter, "newTextureImage returned non-texture image.");
continue;
}
if (origTexture) {
if (origTexture != copyTexture) {
ERRORF(reporter, "newTextureImage made unnecessary texture copy.");
}
}
if (image->width() != texImage->width() || image->height() != texImage->height()) {
ERRORF(reporter, "newTextureImage changed the image size.");
}
if (image->isOpaque() != texImage->isOpaque()) {
ERRORF(reporter, "newTextureImage changed image opaqueness.");
}
}
}
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_drawAbandonedGpuImage, reporter, contextInfo) {
auto context = contextInfo.grContext();
auto image = create_gpu_image(context);
auto info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
auto surface(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info));
as_IB(image)->peekTexture()->abandon();
surface->getCanvas()->drawImage(image, 0, 0);
}
#endif
// https://bug.skia.org/4390
DEF_TEST(ImageFromIndex8Bitmap, r) {
SkPMColor pmColors[1] = {SkPreMultiplyColor(SK_ColorWHITE)};
SkBitmap bm;
SkAutoTUnref<SkColorTable> ctable(
new SkColorTable(pmColors, SK_ARRAY_COUNT(pmColors)));
SkImageInfo info =
SkImageInfo::Make(1, 1, kIndex_8_SkColorType, kPremul_SkAlphaType);
bm.allocPixels(info, nullptr, ctable);
SkAutoLockPixels autoLockPixels(bm);
*bm.getAddr8(0, 0) = 0;
sk_sp<SkImage> img(SkImage::MakeFromBitmap(bm));
REPORTER_ASSERT(r, img != nullptr);
}
class EmptyGenerator : public SkImageGenerator {
public:
EmptyGenerator() : SkImageGenerator(SkImageInfo::MakeN32Premul(0, 0)) {}
};
DEF_TEST(ImageEmpty, reporter) {
const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
SkPixmap pmap(info, nullptr, 0);
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeRasterCopy(pmap));
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeRasterData(info, nullptr, 0));
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeFromRaster(pmap, nullptr, nullptr));
REPORTER_ASSERT(reporter, nullptr == SkImage::MakeFromGenerator(new EmptyGenerator));
}
DEF_TEST(ImageDataRef, reporter) {
SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
size_t rowBytes = info.minRowBytes();
size_t size = info.getSafeSize(rowBytes);
sk_sp<SkData> data = SkData::MakeUninitialized(size);
REPORTER_ASSERT(reporter, data->unique());
sk_sp<SkImage> image = SkImage::MakeRasterData(info, data, rowBytes);
REPORTER_ASSERT(reporter, !data->unique());
image.reset();
REPORTER_ASSERT(reporter, data->unique());
}
static bool has_pixels(const SkPMColor pixels[], int count, SkPMColor expected) {
for (int i = 0; i < count; ++i) {
if (pixels[i] != expected) {
return false;
}
}
return true;
}
static void test_read_pixels(skiatest::Reporter* reporter, SkImage* image) {
const SkPMColor expected = SkPreMultiplyColor(SK_ColorWHITE);
const SkPMColor notExpected = ~expected;
const int w = 2, h = 2;
const size_t rowBytes = w * sizeof(SkPMColor);
SkPMColor pixels[w*h];
SkImageInfo info;
info = SkImageInfo::MakeUnknown(w, h);
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, 0));
// out-of-bounds should fail
info = SkImageInfo::MakeN32Premul(w, h);
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, -w, 0));
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, -h));
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, image->width(), 0));
REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, image->height()));
// top-left should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, 0, 0));
REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
// bottom-right should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
image->width() - w, image->height() - h));
REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
// partial top-left should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, -1, -1));
REPORTER_ASSERT(reporter, pixels[3] == expected);
REPORTER_ASSERT(reporter, has_pixels(pixels, w*h - 1, notExpected));
// partial bottom-right should succeed
sk_memset32(pixels, notExpected, w*h);
REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
image->width() - 1, image->height() - 1));
REPORTER_ASSERT(reporter, pixels[0] == expected);
REPORTER_ASSERT(reporter, has_pixels(&pixels[1], w*h - 1, notExpected));
}
DEF_TEST(ImageReadPixels, reporter) {
sk_sp<SkImage> image(create_image());
test_read_pixels(reporter, image.get());
image = create_data_image();
test_read_pixels(reporter, image.get());
RasterDataHolder dataHolder;
image = create_rasterproc_image(&dataHolder);
test_read_pixels(reporter, image.get());
image.reset();
REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
image = create_codec_image();
test_read_pixels(reporter, image.get());
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ImageReadPixels_Gpu, reporter, ctxInfo) {
test_read_pixels(reporter, create_gpu_image(ctxInfo.grContext()).get());
}
#endif
static void check_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image,
const SkBitmap& bitmap, SkImage::LegacyBitmapMode mode) {
REPORTER_ASSERT(reporter, image->width() == bitmap.width());
REPORTER_ASSERT(reporter, image->height() == bitmap.height());
REPORTER_ASSERT(reporter, image->isOpaque() == bitmap.isOpaque());
if (SkImage::kRO_LegacyBitmapMode == mode) {
REPORTER_ASSERT(reporter, bitmap.isImmutable());
}
SkAutoLockPixels alp(bitmap);
REPORTER_ASSERT(reporter, bitmap.getPixels());
const SkImageInfo info = SkImageInfo::MakeN32(1, 1, bitmap.alphaType());
SkPMColor imageColor;
REPORTER_ASSERT(reporter, image->readPixels(info, &imageColor, sizeof(SkPMColor), 0, 0));
REPORTER_ASSERT(reporter, imageColor == *bitmap.getAddr32(0, 0));
}
static void test_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image, SkImage::LegacyBitmapMode mode) {
SkBitmap bitmap;
REPORTER_ASSERT(reporter, image->asLegacyBitmap(&bitmap, mode));
check_legacy_bitmap(reporter, image, bitmap, mode);
// Test subsetting to exercise the rowBytes logic.
SkBitmap tmp;
REPORTER_ASSERT(reporter, bitmap.extractSubset(&tmp, SkIRect::MakeWH(image->width() / 2,
image->height() / 2)));
sk_sp<SkImage> subsetImage(SkImage::MakeFromBitmap(tmp));
REPORTER_ASSERT(reporter, subsetImage.get());
SkBitmap subsetBitmap;
REPORTER_ASSERT(reporter, subsetImage->asLegacyBitmap(&subsetBitmap, mode));
check_legacy_bitmap(reporter, subsetImage.get(), subsetBitmap, mode);
}
DEF_TEST(ImageLegacyBitmap, reporter) {
const SkImage::LegacyBitmapMode modes[] = {
SkImage::kRO_LegacyBitmapMode,
SkImage::kRW_LegacyBitmapMode,
};
for (auto& mode : modes) {
sk_sp<SkImage> image(create_image());
test_legacy_bitmap(reporter, image.get(), mode);
image = create_data_image();
test_legacy_bitmap(reporter, image.get(), mode);
RasterDataHolder dataHolder;
image = create_rasterproc_image(&dataHolder);
test_legacy_bitmap(reporter, image.get(), mode);
image.reset();
REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
image = create_codec_image();
test_legacy_bitmap(reporter, image.get(), mode);
}
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageLegacyBitmap_Gpu, reporter, ctxInfo) {
const SkImage::LegacyBitmapMode modes[] = {
SkImage::kRO_LegacyBitmapMode,
SkImage::kRW_LegacyBitmapMode,
};
for (auto& mode : modes) {
sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
test_legacy_bitmap(reporter, image.get(), mode);
}
}
#endif
static void test_peek(skiatest::Reporter* reporter, SkImage* image, bool expectPeekSuccess) {
SkPixmap pm;
bool success = image->peekPixels(&pm);
REPORTER_ASSERT(reporter, expectPeekSuccess == success);
if (success) {
const SkImageInfo& info = pm.info();
REPORTER_ASSERT(reporter, 20 == info.width());
REPORTER_ASSERT(reporter, 20 == info.height());
REPORTER_ASSERT(reporter, kN32_SkColorType == info.colorType());
REPORTER_ASSERT(reporter, kPremul_SkAlphaType == info.alphaType() ||
kOpaque_SkAlphaType == info.alphaType());
REPORTER_ASSERT(reporter, info.minRowBytes() <= pm.rowBytes());
REPORTER_ASSERT(reporter, SkPreMultiplyColor(SK_ColorWHITE) == *pm.addr32(0, 0));
}
}
DEF_TEST(ImagePeek, reporter) {
sk_sp<SkImage> image(create_image());
test_peek(reporter, image.get(), true);
image = create_data_image();
test_peek(reporter, image.get(), true);
RasterDataHolder dataHolder;
image = create_rasterproc_image(&dataHolder);
test_peek(reporter, image.get(), true);
image.reset();
REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
image = create_codec_image();
test_peek(reporter, image.get(), false);
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ImagePeek_Gpu, reporter, ctxInfo) {
sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
test_peek(reporter, image.get(), false);
}
#endif
#if SK_SUPPORT_GPU
struct TextureReleaseChecker {
TextureReleaseChecker() : fReleaseCount(0) {}
int fReleaseCount;
static void Release(void* self) {
static_cast<TextureReleaseChecker*>(self)->fReleaseCount++;
}
};
static void check_image_color(skiatest::Reporter* reporter, SkImage* image, SkPMColor expected) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
SkPMColor pixel;
REPORTER_ASSERT(reporter, image->readPixels(info, &pixel, sizeof(pixel), 0, 0));
REPORTER_ASSERT(reporter, pixel == expected);
}
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_NewFromTexture, reporter, ctxInfo) {
GrTextureProvider* provider = ctxInfo.grContext()->textureProvider();
const int w = 10;
const int h = 10;
SkPMColor storage[w * h];
const SkPMColor expected0 = SkPreMultiplyColor(SK_ColorRED);
sk_memset32(storage, expected0, w * h);
GrSurfaceDesc desc;
desc.fFlags = kRenderTarget_GrSurfaceFlag; // needs to be a rendertarget for readpixels();
desc.fOrigin = kDefault_GrSurfaceOrigin;
desc.fWidth = w;
desc.fHeight = h;
desc.fConfig = kSkia8888_GrPixelConfig;
desc.fSampleCnt = 0;
SkAutoTUnref<GrTexture> tex(provider->createTexture(desc, SkBudgeted::kNo, storage, w * 4));
if (!tex) {
REPORTER_ASSERT(reporter, false);
return;
}
GrBackendTextureDesc backendDesc;
backendDesc.fConfig = kSkia8888_GrPixelConfig;
backendDesc.fFlags = kRenderTarget_GrBackendTextureFlag;
backendDesc.fWidth = w;
backendDesc.fHeight = h;
backendDesc.fSampleCnt = 0;
backendDesc.fTextureHandle = tex->getTextureHandle();
TextureReleaseChecker releaseChecker;
sk_sp<SkImage> refImg(
SkImage::MakeFromTexture(ctxInfo.grContext(), backendDesc, kPremul_SkAlphaType,
TextureReleaseChecker::Release, &releaseChecker));
sk_sp<SkImage> cpyImg(SkImage::MakeFromTextureCopy(ctxInfo.grContext(), backendDesc,
kPremul_SkAlphaType));
check_image_color(reporter, refImg.get(), expected0);
check_image_color(reporter, cpyImg.get(), expected0);
// Now lets jam new colors into our "external" texture, and see if the images notice
const SkPMColor expected1 = SkPreMultiplyColor(SK_ColorBLUE);
sk_memset32(storage, expected1, w * h);
tex->writePixels(0, 0, w, h, kSkia8888_GrPixelConfig, storage, GrContext::kFlushWrites_PixelOp);
// The cpy'd one should still see the old color
#if 0
// There is no guarantee that refImg sees the new color. We are free to have made a copy. Our
// write pixels call violated the contract with refImg and refImg is now undefined.
check_image_color(reporter, refImg, expected1);
#endif
check_image_color(reporter, cpyImg.get(), expected0);
// Now exercise the release proc
REPORTER_ASSERT(reporter, 0 == releaseChecker.fReleaseCount);
refImg.reset(nullptr); // force a release of the image
REPORTER_ASSERT(reporter, 1 == releaseChecker.fReleaseCount);
}
static void check_images_same(skiatest::Reporter* reporter, const SkImage* a, const SkImage* b) {
if (a->width() != b->width() || a->height() != b->height()) {
ERRORF(reporter, "Images must have the same size");
return;
}
if (a->isOpaque() != b->isOpaque()) {
ERRORF(reporter, "Images must have the same opaquness");
return;
}
SkImageInfo info = SkImageInfo::MakeN32Premul(a->width(), a->height());
SkAutoPixmapStorage apm;
SkAutoPixmapStorage bpm;
apm.alloc(info);
bpm.alloc(info);
if (!a->readPixels(apm, 0, 0)) {
ERRORF(reporter, "Could not read image a's pixels");
return;
}
if (!b->readPixels(bpm, 0, 0)) {
ERRORF(reporter, "Could not read image b's pixels");
return;
}
for (auto y = 0; y < info.height(); ++y) {
for (auto x = 0; x < info.width(); ++x) {
uint32_t pixelA = *apm.addr32(x, y);
uint32_t pixelB = *bpm.addr32(x, y);
if (pixelA != pixelB) {
ERRORF(reporter, "Expected image pixels to be the same. At %d,%d 0x%08x != 0x%08x",
x, y, pixelA, pixelB);
return;
}
}
}
}
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(NewTextureFromPixmap, reporter, ctxInfo) {
for (auto create : {&create_image,
&create_image_565,
&create_image_ct}) {
sk_sp<SkImage> image((*create)());
if (!image) {
ERRORF(reporter, "Could not create image");
return;
}
SkPixmap pixmap;
if (!image->peekPixels(&pixmap)) {
ERRORF(reporter, "peek failed");
} else {
sk_sp<SkImage> texImage(SkImage::MakeTextureFromPixmap(ctxInfo.grContext(), pixmap,
SkBudgeted::kNo));
if (!texImage) {
ERRORF(reporter, "NewTextureFromPixmap failed.");
} else {
check_images_same(reporter, image.get(), texImage.get());
}
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(DeferredTextureImage, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
sk_gpu_test::TestContext* testContext = ctxInfo.testContext();
SkAutoTUnref<GrContextThreadSafeProxy> proxy(context->threadSafeProxy());
GrContextFactory otherFactory;
ContextInfo otherContextInfo =
otherFactory.getContextInfo(GrContextFactory::kNativeGL_ContextType);
testContext->makeCurrent();
REPORTER_ASSERT(reporter, proxy);
struct {
std::function<sk_sp<SkImage> ()> fImageFactory;
std::vector<SkImage::DeferredTextureImageUsageParams> fParams;
SkFilterQuality fExpectedQuality;
int fExpectedScaleFactor;
bool fExpectation;
} testCases[] = {
{ create_image, {{}}, kNone_SkFilterQuality, 1, true },
{ create_codec_image, {{}}, kNone_SkFilterQuality, 1, true },
{ create_data_image, {{}}, kNone_SkFilterQuality, 1, true },
{ create_picture_image, {{}}, kNone_SkFilterQuality, 1, false },
{ [context] { return create_gpu_image(context); }, {{}}, kNone_SkFilterQuality, 1, false },
// Create a texture image in a another GrContext.
{ [testContext, otherContextInfo] {
otherContextInfo.testContext()->makeCurrent();
sk_sp<SkImage> otherContextImage = create_gpu_image(otherContextInfo.grContext());
testContext->makeCurrent();
return otherContextImage;
}, {{}}, kNone_SkFilterQuality, 1, false },
// Create an image that is too large to upload.
{ create_image_large, {{}}, kNone_SkFilterQuality, 1, false },
// Create an image that is too large, but is scaled to an acceptable size.
{ create_image_large, {{SkMatrix::I(), kMedium_SkFilterQuality, 4}},
kMedium_SkFilterQuality, 16, true},
// Create an image with multiple low filter qualities, make sure we round up.
{ create_image_large, {{SkMatrix::I(), kNone_SkFilterQuality, 4},
{SkMatrix::I(), kMedium_SkFilterQuality, 4}},
kMedium_SkFilterQuality, 16, true},
// Create an image with multiple prescale levels, make sure we chose the minimum scale.
{ create_image_large, {{SkMatrix::I(), kMedium_SkFilterQuality, 5},
{SkMatrix::I(), kMedium_SkFilterQuality, 4}},
kMedium_SkFilterQuality, 16, true},
};
for (auto testCase : testCases) {
sk_sp<SkImage> image(testCase.fImageFactory());
size_t size = image->getDeferredTextureImageData(*proxy, testCase.fParams.data(),
static_cast<int>(testCase.fParams.size()),
nullptr);
static const char *const kFS[] = { "fail", "succeed" };
if (SkToBool(size) != testCase.fExpectation) {
ERRORF(reporter, "This image was expected to %s but did not.",
kFS[testCase.fExpectation]);
}
if (size) {
void* buffer = sk_malloc_throw(size);
void* misaligned = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(buffer) + 3);
if (image->getDeferredTextureImageData(*proxy, testCase.fParams.data(),
static_cast<int>(testCase.fParams.size()),
misaligned)) {
ERRORF(reporter, "Should fail when buffer is misaligned.");
}
if (!image->getDeferredTextureImageData(*proxy, testCase.fParams.data(),
static_cast<int>(testCase.fParams.size()),
buffer)) {
ERRORF(reporter, "deferred image size succeeded but creation failed.");
} else {
for (auto budgeted : { SkBudgeted::kNo, SkBudgeted::kYes }) {
sk_sp<SkImage> newImage(
SkImage::MakeFromDeferredTextureImageData(context, buffer, budgeted));
REPORTER_ASSERT(reporter, newImage != nullptr);
if (newImage) {
// Scale the image in software for comparison.
SkImageInfo scaled_info = SkImageInfo::MakeN32(
image->width() / testCase.fExpectedScaleFactor,
image->height() / testCase.fExpectedScaleFactor,
image->isOpaque() ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
SkAutoPixmapStorage scaled;
scaled.alloc(scaled_info);
image->scalePixels(scaled, testCase.fExpectedQuality);
sk_sp<SkImage> scaledImage = SkImage::MakeRasterCopy(scaled);
check_images_same(reporter, scaledImage.get(), newImage.get());
}
// The other context should not be able to create images from texture data
// created by the original context.
sk_sp<SkImage> newImage2(SkImage::MakeFromDeferredTextureImageData(
otherContextInfo.grContext(), buffer, budgeted));
REPORTER_ASSERT(reporter, !newImage2);
testContext->makeCurrent();
}
}
sk_free(buffer);
}
}
}
#endif
|
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2015 Imperial College London
* Copyright 2013-2015 Andreas Schuh
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/PointSetIO.h"
#include "mirtk/PointSetUtils.h"
#include "vtkSmartPointer.h"
#include "vtkPointSet.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkFloatArray.h"
#include "vtkDataSetAttributes.h"
#include "vtkPointDataToCellData.h"
#include "vtkCellDataToPointData.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
cout << endl;
cout << "Usage: " << name << " <source> <target> [<output>] [options]" << endl;
cout << endl;
cout << "Description:" << endl;
cout << " Copies point and/or cell data from a source point set to a target point set" << endl;
cout << " and writes the resulting amended point set to the specified output file." << endl;
cout << " When no separate output file is specified, the target point set is overwritten." << endl;
cout << " This command can also convert from point data to cell data and vice versa." << endl;
cout << endl;
cout << " If the point sets have differing number of points or cells, respectively," << endl;
cout << " zero entries are either added to the target arrays or only the first n tuples" << endl;
cout << " of the source arrays are copied. In case of the -points option, the remaining" << endl;
cout << " target points are kept unchanged." << endl;
cout << endl;
cout << " If the <attr> argument is given to any of the option below, the copied data" << endl;
cout << " array is set as the new \"scalars\", \"vectors\", \"tcoords\", or \"normals\"" << endl;
cout << " attribute, respectively, of the output point set." << endl;
cout << endl;
cout << " When no options are given, the :option:`-scalars` are copied over." << endl;
cout << endl;
cout << "Arguments:" << endl;
cout << " source Point set from which to copy the point/cell data." << endl;
#if MIRTK_IO_WITH_GIFTI
cout << " Can also be a GIFTI file with only point data arrays." << endl;
cout << " In this case, the coordinates and topology of the target" << endl;
cout << " surface are used to define the source surface." << endl;
#endif
cout << " target Point set to which to add the point/cell data." << endl;
cout << " output Output point set with copied point/cell data." << endl;
cout << " If not specified, the target file is overwritten." << endl;
cout << endl;
cout << "Optional arguments:" << endl;
cout << " -scalars" << endl;
cout << " Copy \"scalars\" data set attribute. (default)" << endl;
cout << endl;
cout << " -vectors" << endl;
cout << " Copy \"vectors\" data set attribute." << endl;
cout << endl;
cout << " -vectors-as-points" << endl;
cout << " Set points of target to \"vectors\" data set attribute of source." << endl;
cout << endl;
cout << " -normals" << endl;
cout << " Copy \"normals\" data set attribute." << endl;
cout << endl;
cout << " -tcoords" << endl;
cout << " Copy \"tcoords\" data set attribute." << endl;
cout << endl;
cout << " -tcoords-as-points" << endl;
cout << " Set points of target to \"tcoords\" data set attribute of source." << endl;
cout << endl;
cout << " -points [<target_name> [<attr>]]" << endl;
cout << " Add points of source as point data of target." << endl;
cout << " When no <target_name> (and <attr>) specified, the points of the" << endl;
cout << " target point set are replaced by those of the source point set." << endl;
cout << " If the target point set has more points than the source point set," << endl;
cout << " the remaining points of the target point set are unchanged." << endl;
cout << endl;
cout << " -pointdata <name|index> [<target_name> [<attr>]]" << endl;
cout << " Name or index of source point data to copy." << endl;
cout << endl;
cout << " -pointdata-as-points <name|index>" << endl;
cout << " Replaces the points of the target point set by the first three" << endl;
cout << " components of the specified source point data array." << endl;
cout << endl;
cout << " -pointdata-as-celldata <name|index>" << endl;
cout << " Converts the specified point data array of the source point set to cell" << endl;
cout << " data and adds a corresponding cell data array to the target point set." << endl;
cout << endl;
cout << " -pointmask <name>" << endl;
cout << " Add point data array which indicates copied point data." << endl;
cout << endl;
cout << " -celldata <name|index> [<target_name> [<attr>]]" << endl;
cout << " Name or index of source cell data to copy." << endl;
cout << endl;
cout << " -celldata-as-pointdata <name|index>" << endl;
cout << " Converts the specified cell data array of the source point set to point" << endl;
cout << " data and adds a corresponding point data array to the target point set." << endl;
cout << endl;
cout << " -cellmask <name>" << endl;
cout << " Add cell data array which indicates copied cell data." << endl;
cout << endl;
cout << " -case-[in]sensitive" << endl;
cout << " Lookup source arrays by case [in]sensitive name. (default: insensitive)" << endl;
PrintCommonOptions(cout);
cout << endl;
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
using AttributeType = vtkDataSetAttributes::AttributeTypes;
const AttributeType NUM_ATTRIBUTES = vtkDataSetAttributes::NUM_ATTRIBUTES;
// -----------------------------------------------------------------------------
struct ArrayInfo
{
int _SourceIndex;
const char *_SourceName;
AttributeType _SourceAttribute;
int _TargetIndex;
const char *_TargetName;
AttributeType _TargetAttribute;
bool _PointCellConversion;
ArrayInfo()
:
_SourceIndex(-1),
_SourceName(nullptr),
_SourceAttribute(NUM_ATTRIBUTES),
_TargetIndex(-1),
_TargetName(nullptr),
_TargetAttribute(NUM_ATTRIBUTES),
_PointCellConversion(false)
{}
};
// -----------------------------------------------------------------------------
/// Get source point data array
vtkDataArray *GetSourceArray(const char *type, vtkDataSetAttributes *attr, const ArrayInfo &info, bool case_sensitive)
{
vtkDataArray *array;
if (info._SourceAttribute < NUM_ATTRIBUTES) {
array = attr->GetAttribute(info._SourceAttribute);
} else if (info._SourceName) {
if (case_sensitive) {
array = attr->GetArray(info._SourceName);
} else {
array = GetArrayByCaseInsensitiveName(attr, info._SourceName);
}
if (array == nullptr) {
FatalError("Source has no " << type << " data array named " << info._SourceName);
}
} else {
if (info._SourceIndex < 0 || info._SourceIndex >= attr->GetNumberOfArrays()) {
FatalError("Source has no " << type << " data array with index " << info._SourceIndex);
}
array = attr->GetArray(info._SourceIndex);
}
return array;
}
// -----------------------------------------------------------------------------
/// Convert point data labels to cell data
vtkSmartPointer<vtkDataArray> ConvertPointToCellLabels(vtkPointSet *pset, vtkDataArray *labels)
{
vtkSmartPointer<vtkDataArray> output;
output.TakeReference(labels->NewInstance());
output->SetName(labels->GetName());
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
output->SetComponentName(j, labels->GetComponentName(j));
}
output->SetNumberOfComponents(labels->GetNumberOfComponents());
output->SetNumberOfTuples(pset->GetNumberOfCells());
OrderedMap<double, int> label_count;
vtkSmartPointer<vtkIdList> ptIds = vtkSmartPointer<vtkIdList>::New();
for (vtkIdType cellId = 0; cellId < pset->GetNumberOfCells(); ++cellId) {
pset->GetCellPoints(cellId, ptIds);
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
label_count.clear();
for (vtkIdType i = 0; i < ptIds->GetNumberOfIds(); ++i) {
++label_count[labels->GetComponent(ptIds->GetId(i), j)];
}
int max_cnt = 0;
double max_label = 0.;
for (const auto &cnt : label_count) {
if (cnt.second > max_cnt) {
max_label = cnt.first;
max_cnt = cnt.second;
}
}
output->SetComponent(cellId, j, max_label);
}
}
return output;
}
// -----------------------------------------------------------------------------
/// Convert cell data labels to point data
vtkSmartPointer<vtkDataArray> ConvertCellToPointLabels(vtkPointSet *pset, vtkDataArray *labels)
{
vtkSmartPointer<vtkDataArray> output;
output.TakeReference(labels->NewInstance());
output->SetName(labels->GetName());
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
output->SetComponentName(j, labels->GetComponentName(j));
}
output->SetNumberOfComponents(labels->GetNumberOfComponents());
output->SetNumberOfTuples(pset->GetNumberOfPoints());
OrderedMap<double, int> label_count;
vtkSmartPointer<vtkIdList> cellIds = vtkSmartPointer<vtkIdList>::New();
for (vtkIdType ptId = 0; ptId < pset->GetNumberOfPoints(); ++ptId) {
pset->GetPointCells(ptId, cellIds);
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
label_count.clear();
for (vtkIdType i = 0; i < cellIds->GetNumberOfIds(); ++i) {
++label_count[labels->GetComponent(cellIds->GetId(i), j)];
}
int max_cnt = 0;
double max_label = 0.;
for (const auto &cnt : label_count) {
if (cnt.second > max_cnt) {
max_label = cnt.first;
max_cnt = cnt.second;
}
}
output->SetComponent(ptId, j, max_label);
}
}
return output;
}
// -----------------------------------------------------------------------------
/// Copy tuples from the input data array
vtkSmartPointer<vtkDataArray> Copy(vtkDataArray *array, vtkIdType n)
{
vtkSmartPointer<vtkDataArray> copy;
copy.TakeReference(array->NewInstance());
copy->SetName(array->GetName());
copy->SetNumberOfComponents(array->GetNumberOfComponents());
copy->SetNumberOfTuples(n);
for (int j = 0; j < array->GetNumberOfComponents(); ++j) {
copy->SetComponentName(j, array->GetComponentName(j));
}
vtkIdType ptId = 0;
while (ptId < n && ptId < array->GetNumberOfTuples()) {
copy->SetTuple(ptId, array->GetTuple(ptId));
++ptId;
}
while (ptId < n) {
for (int j = 0; j < copy->GetNumberOfComponents(); ++j) {
copy->SetComponent(ptId, j, .0);
}
++ptId;
}
return copy;
}
// -----------------------------------------------------------------------------
/// Add data array to data set attributes
void AddArray(vtkDataSetAttributes *data, vtkDataArray *array, AttributeType type)
{
switch (type) {
case AttributeType::SCALARS: data->SetScalars(array); break;
case AttributeType::VECTORS: data->SetVectors(array); break;
case AttributeType::NORMALS: data->SetNormals(array); break;
case AttributeType::TCOORDS: data->SetTCoords(array); break;
case AttributeType::TENSORS: data->SetTensors(array); break;
case AttributeType::GLOBALIDS: data->SetGlobalIds(array); break;
case AttributeType::PEDIGREEIDS: data->SetPedigreeIds(array); break;
default: data->AddArray(array); break;
}
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
vtkSmartPointer<vtkDataArray> array;
vtkSmartPointer<vtkDataArray> copy;
vtkDataSetAttributes *sourceAttr, *targetAttr;
vtkIdType ntuples;
// Positional arguments
REQUIRES_POSARGS(2);
if (NUM_POSARGS > 3) {
PrintHelp(EXECNAME);
exit(1);
}
const char *source_name = POSARG(1);
const char *target_name = POSARG(2);
const char *output_name = (NUM_POSARGS == 3 ? POSARG(3) : target_name);
// Optional arguments
Array<ArrayInfo> pd, cd;
const char *point_mask_name = nullptr;
const char *cell_mask_name = nullptr;
bool case_sensitive = false;
for (ALL_OPTIONS) {
if (OPTION("-points")) {
ArrayInfo info;
info._SourceIndex = -2;
if (HAS_ARGUMENT) info._TargetName = ARGUMENT;
else info._TargetName = NULL;
if (HAS_ARGUMENT) PARSE_ARGUMENT(info._TargetAttribute);
pd.push_back(info);
}
else if (OPTION("-scalars") || OPTION("-vectors") || OPTION("-normals") || OPTION("-tcoords")) {
ArrayInfo info;
FromString(OPTNAME + 1, info._SourceAttribute);
pd.push_back(info);
cd.push_back(info);
}
else if (OPTION("-vectors-as-points") || OPTION("-tcoords-as-points")) {
ArrayInfo info;
FromString(OPTNAME + 1, info._SourceAttribute);
info._TargetIndex = -2;
pd.push_back(info);
}
else if (OPTION("-pointdata") || OPTION("-pointdata-as-celldata") ||
OPTION("-celldata") || OPTION("-celldata-as-pointdata")) {
ArrayInfo info;
if (strcmp(OPTNAME, "-pointdata-as-celldata") == 0 ||
strcmp(OPTNAME, "-celldata-as-pointdata") == 0) {
info._PointCellConversion = true;
} else {
info._PointCellConversion = false;
}
info._SourceName = ARGUMENT;
if (FromString(info._SourceName, info._SourceIndex)) {
info._SourceName = NULL;
} else {
info._SourceIndex = -1;
}
if (HAS_ARGUMENT) {
info._TargetName = ARGUMENT;
}
if (HAS_ARGUMENT) PARSE_ARGUMENT(info._TargetAttribute);
if (strncmp(OPTNAME, "-pointdata", 10) == 0) pd.push_back(info);
else cd.push_back(info);
}
else if (OPTION("-pointdata-as-points")) {
ArrayInfo info;
info._SourceName = ARGUMENT;
if (FromString(info._SourceName, info._SourceIndex)) {
info._SourceName = NULL;
} else {
info._SourceIndex = -1;
}
info._TargetIndex = -2;
pd.push_back(info);
}
else if (OPTION("-pointmask")) point_mask_name = ARGUMENT;
else if (OPTION("-cellmask")) cell_mask_name = ARGUMENT;
else if (OPTION("-case-sensitive")) case_sensitive = true;
else if (OPTION("-case-insensitive")) case_sensitive = false;
else HANDLE_COMMON_OR_UNKNOWN_OPTION();
}
// Read input data sets
vtkSmartPointer<vtkPointSet> source, target;
target = ReadPointSet(target_name);
#if MIRTK_IO_WITH_GIFTI
if (Extension(source_name, EXT_Last) == ".gii") {
source = ReadGIFTI(source_name, vtkPolyData::SafeDownCast(target));
}
#endif
if (source == nullptr) {
source = ReadPointSet(source_name);
}
const vtkIdType npoints = target->GetNumberOfPoints();
const vtkIdType ncells = target->GetNumberOfCells();
vtkPointData * const sourcePD = source->GetPointData();
vtkCellData * const sourceCD = source->GetCellData();
vtkPointData * const targetPD = target->GetPointData();
vtkCellData * const targetCD = target->GetCellData();
// Copy all point set attributes by default
if (pd.empty() && cd.empty()) {
int attr;
for (int i = 0; i < sourcePD->GetNumberOfArrays(); ++i) {
attr = sourcePD->IsArrayAnAttribute(i);
if (attr < 0) attr = NUM_ATTRIBUTES;
ArrayInfo info;
info._SourceIndex = i;
info._TargetAttribute = static_cast<AttributeType>(attr);
pd.push_back(info);
}
for (int i = 0; i < sourceCD->GetNumberOfArrays(); ++i) {
attr = sourceCD->IsArrayAnAttribute(i);
if (attr < 0) attr = NUM_ATTRIBUTES;
ArrayInfo info;
info._SourceIndex = i;
info._TargetAttribute = static_cast<AttributeType>(attr);
cd.push_back(info);
}
}
// Convert point data to cell data if necessary
vtkSmartPointer<vtkCellData> pd_as_cd;
for (size_t i = 0; i < pd.size(); ++i) {
if (pd[i]._PointCellConversion) {
vtkNew<vtkPointDataToCellData> pd_to_cd;
SetVTKInput(pd_to_cd, source);
pd_to_cd->PassPointDataOff();
pd_to_cd->Update();
pd_as_cd = pd_to_cd->GetOutput()->GetCellData();
break;
}
}
// Convert cell data to point data if necessary
vtkSmartPointer<vtkPointData> cd_as_pd;
for (size_t i = 0; i < cd.size(); ++i) {
if (cd[i]._PointCellConversion) {
vtkNew<vtkCellDataToPointData> cd_to_pd;
SetVTKInput(cd_to_pd, source);
cd_to_pd->PassCellDataOff();
cd_to_pd->Update();
cd_as_pd = cd_to_pd->GetOutput()->GetPointData();
break;
}
}
// Add point data
for (size_t i = 0; i < pd.size(); ++i) {
if (pd[i]._SourceIndex == -2) {
vtkIdType end = min(npoints, source->GetNumberOfPoints());
if (pd[i]._TargetName) {
copy = vtkSmartPointer<vtkFloatArray>::New();
copy->SetNumberOfComponents(3);
copy->SetNumberOfTuples(npoints);
for (vtkIdType ptId = 0; ptId < end; ++ptId) {
copy->SetTuple(ptId, source->GetPoint(ptId));
}
const double zero[3] = {.0, .0, .0};
for (vtkIdType ptId = end; ptId < npoints; ++ptId) {
copy->SetTuple(ptId, zero);
}
} else {
vtkPoints *points = target->GetPoints();
for (vtkIdType ptId = 0; ptId < end; ++ptId) {
points->SetPoint(ptId, source->GetPoint(ptId));
}
copy = nullptr;
}
} else {
if (pd[i]._PointCellConversion && pd[i]._TargetIndex != -2) {
sourceAttr = pd_as_cd;
targetAttr = targetCD;
ntuples = ncells;
} else {
sourceAttr = sourcePD;
targetAttr = targetPD;
ntuples = npoints;
}
array = GetSourceArray("point", sourceAttr, pd[i], case_sensitive);
if (pd[i]._TargetIndex == -2) {
double p[3] = {.0};
vtkPoints *points = target->GetPoints();
vtkIdType end = min(npoints, source->GetNumberOfPoints());
int dim = min(3, array->GetNumberOfComponents());
for (vtkIdType ptId = 0; ptId < end; ++ptId) {
for (int i = 0; i < dim; ++i) p[i] = array->GetComponent(ptId, i);
points->SetPoint(ptId, p);
}
copy = nullptr;
} else {
if (sourceAttr == pd_as_cd.Get()) {
if ((array->GetName() && ToLower(array->GetName()) .find("label") != string::npos) ||
(pd[i]._TargetName && ToLower(pd[i]._TargetName).find("label") != string::npos)) {
vtkDataArray *labels = GetSourceArray("point", sourcePD, pd[i], case_sensitive);
array = ConvertPointToCellLabels(source, labels);
}
}
copy = Copy(array, ntuples);
}
}
if (copy) {
if (pd[i]._TargetName) copy->SetName(pd[i]._TargetName);
AddArray(targetAttr, copy, pd[i]._TargetAttribute);
}
}
if (point_mask_name) {
vtkSmartPointer<vtkDataArray> mask = NewVTKDataArray(VTK_UNSIGNED_CHAR);
mask->SetName(point_mask_name);
mask->SetNumberOfComponents(1);
mask->SetNumberOfTuples(npoints);
mask->FillComponent(0, .0);
for (vtkIdType ptId = 0; ptId < npoints && ptId < source->GetNumberOfPoints(); ++ptId) {
mask->SetComponent(ptId, 0, 1.0);
}
targetPD->AddArray(mask);
}
// Add cell data
for (size_t i = 0; i < cd.size(); ++i) {
if (cd[i]._PointCellConversion) {
sourceAttr = cd_as_pd;
targetAttr = targetPD;
ntuples = npoints;
} else {
sourceAttr = sourceCD;
targetAttr = targetCD;
ntuples = ncells;
}
array = GetSourceArray("cell", sourceAttr, cd[i], case_sensitive);
if (sourceAttr == cd_as_pd.Get()) {
if ((array->GetName() && ToLower(array->GetName()) .find("label") != string::npos) ||
(cd[i]._TargetName && ToLower(cd[i]._TargetName).find("label") != string::npos)) {
vtkDataArray *labels = GetSourceArray("cell", sourceCD, cd[i], case_sensitive);
array = ConvertCellToPointLabels(source, labels);
}
}
copy = Copy(array, ntuples);
if (cd[i]._TargetName) copy->SetName(cd[i]._TargetName);
AddArray(targetAttr, copy, cd[i]._TargetAttribute);
}
if (cell_mask_name) {
vtkSmartPointer<vtkDataArray> mask = NewVTKDataArray(VTK_UNSIGNED_CHAR);
mask->SetName(cell_mask_name);
mask->SetNumberOfComponents(1);
mask->SetNumberOfTuples(ncells);
mask->FillComponent(0, .0);
for (vtkIdType cellId = 0; cellId < ncells && cellId < source->GetNumberOfCells(); ++cellId) {
mask->SetComponent(cellId, 0, 1.0);
}
targetCD->AddArray(mask);
}
// Write resulting data set
WritePointSet(output_name, target);
}
fix: Use vtkSmartPointer::GetPointer instead of newer Get() [Applications]
The vtkSmartPointer::Get function was added in VTK 6.1.
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2015 Imperial College London
* Copyright 2013-2015 Andreas Schuh
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/PointSetIO.h"
#include "mirtk/PointSetUtils.h"
#include "vtkSmartPointer.h"
#include "vtkPointSet.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkFloatArray.h"
#include "vtkDataSetAttributes.h"
#include "vtkPointDataToCellData.h"
#include "vtkCellDataToPointData.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
cout << endl;
cout << "Usage: " << name << " <source> <target> [<output>] [options]" << endl;
cout << endl;
cout << "Description:" << endl;
cout << " Copies point and/or cell data from a source point set to a target point set" << endl;
cout << " and writes the resulting amended point set to the specified output file." << endl;
cout << " When no separate output file is specified, the target point set is overwritten." << endl;
cout << " This command can also convert from point data to cell data and vice versa." << endl;
cout << endl;
cout << " If the point sets have differing number of points or cells, respectively," << endl;
cout << " zero entries are either added to the target arrays or only the first n tuples" << endl;
cout << " of the source arrays are copied. In case of the -points option, the remaining" << endl;
cout << " target points are kept unchanged." << endl;
cout << endl;
cout << " If the <attr> argument is given to any of the option below, the copied data" << endl;
cout << " array is set as the new \"scalars\", \"vectors\", \"tcoords\", or \"normals\"" << endl;
cout << " attribute, respectively, of the output point set." << endl;
cout << endl;
cout << " When no options are given, the :option:`-scalars` are copied over." << endl;
cout << endl;
cout << "Arguments:" << endl;
cout << " source Point set from which to copy the point/cell data." << endl;
#if MIRTK_IO_WITH_GIFTI
cout << " Can also be a GIFTI file with only point data arrays." << endl;
cout << " In this case, the coordinates and topology of the target" << endl;
cout << " surface are used to define the source surface." << endl;
#endif
cout << " target Point set to which to add the point/cell data." << endl;
cout << " output Output point set with copied point/cell data." << endl;
cout << " If not specified, the target file is overwritten." << endl;
cout << endl;
cout << "Optional arguments:" << endl;
cout << " -scalars" << endl;
cout << " Copy \"scalars\" data set attribute. (default)" << endl;
cout << endl;
cout << " -vectors" << endl;
cout << " Copy \"vectors\" data set attribute." << endl;
cout << endl;
cout << " -vectors-as-points" << endl;
cout << " Set points of target to \"vectors\" data set attribute of source." << endl;
cout << endl;
cout << " -normals" << endl;
cout << " Copy \"normals\" data set attribute." << endl;
cout << endl;
cout << " -tcoords" << endl;
cout << " Copy \"tcoords\" data set attribute." << endl;
cout << endl;
cout << " -tcoords-as-points" << endl;
cout << " Set points of target to \"tcoords\" data set attribute of source." << endl;
cout << endl;
cout << " -points [<target_name> [<attr>]]" << endl;
cout << " Add points of source as point data of target." << endl;
cout << " When no <target_name> (and <attr>) specified, the points of the" << endl;
cout << " target point set are replaced by those of the source point set." << endl;
cout << " If the target point set has more points than the source point set," << endl;
cout << " the remaining points of the target point set are unchanged." << endl;
cout << endl;
cout << " -pointdata <name|index> [<target_name> [<attr>]]" << endl;
cout << " Name or index of source point data to copy." << endl;
cout << endl;
cout << " -pointdata-as-points <name|index>" << endl;
cout << " Replaces the points of the target point set by the first three" << endl;
cout << " components of the specified source point data array." << endl;
cout << endl;
cout << " -pointdata-as-celldata <name|index>" << endl;
cout << " Converts the specified point data array of the source point set to cell" << endl;
cout << " data and adds a corresponding cell data array to the target point set." << endl;
cout << endl;
cout << " -pointmask <name>" << endl;
cout << " Add point data array which indicates copied point data." << endl;
cout << endl;
cout << " -celldata <name|index> [<target_name> [<attr>]]" << endl;
cout << " Name or index of source cell data to copy." << endl;
cout << endl;
cout << " -celldata-as-pointdata <name|index>" << endl;
cout << " Converts the specified cell data array of the source point set to point" << endl;
cout << " data and adds a corresponding point data array to the target point set." << endl;
cout << endl;
cout << " -cellmask <name>" << endl;
cout << " Add cell data array which indicates copied cell data." << endl;
cout << endl;
cout << " -case-[in]sensitive" << endl;
cout << " Lookup source arrays by case [in]sensitive name. (default: insensitive)" << endl;
PrintCommonOptions(cout);
cout << endl;
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
using AttributeType = vtkDataSetAttributes::AttributeTypes;
const AttributeType NUM_ATTRIBUTES = vtkDataSetAttributes::NUM_ATTRIBUTES;
// -----------------------------------------------------------------------------
struct ArrayInfo
{
int _SourceIndex;
const char *_SourceName;
AttributeType _SourceAttribute;
int _TargetIndex;
const char *_TargetName;
AttributeType _TargetAttribute;
bool _PointCellConversion;
ArrayInfo()
:
_SourceIndex(-1),
_SourceName(nullptr),
_SourceAttribute(NUM_ATTRIBUTES),
_TargetIndex(-1),
_TargetName(nullptr),
_TargetAttribute(NUM_ATTRIBUTES),
_PointCellConversion(false)
{}
};
// -----------------------------------------------------------------------------
/// Get source point data array
vtkDataArray *GetSourceArray(const char *type, vtkDataSetAttributes *attr, const ArrayInfo &info, bool case_sensitive)
{
vtkDataArray *array;
if (info._SourceAttribute < NUM_ATTRIBUTES) {
array = attr->GetAttribute(info._SourceAttribute);
} else if (info._SourceName) {
if (case_sensitive) {
array = attr->GetArray(info._SourceName);
} else {
array = GetArrayByCaseInsensitiveName(attr, info._SourceName);
}
if (array == nullptr) {
FatalError("Source has no " << type << " data array named " << info._SourceName);
}
} else {
if (info._SourceIndex < 0 || info._SourceIndex >= attr->GetNumberOfArrays()) {
FatalError("Source has no " << type << " data array with index " << info._SourceIndex);
}
array = attr->GetArray(info._SourceIndex);
}
return array;
}
// -----------------------------------------------------------------------------
/// Convert point data labels to cell data
vtkSmartPointer<vtkDataArray> ConvertPointToCellLabels(vtkPointSet *pset, vtkDataArray *labels)
{
vtkSmartPointer<vtkDataArray> output;
output.TakeReference(labels->NewInstance());
output->SetName(labels->GetName());
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
output->SetComponentName(j, labels->GetComponentName(j));
}
output->SetNumberOfComponents(labels->GetNumberOfComponents());
output->SetNumberOfTuples(pset->GetNumberOfCells());
OrderedMap<double, int> label_count;
vtkSmartPointer<vtkIdList> ptIds = vtkSmartPointer<vtkIdList>::New();
for (vtkIdType cellId = 0; cellId < pset->GetNumberOfCells(); ++cellId) {
pset->GetCellPoints(cellId, ptIds);
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
label_count.clear();
for (vtkIdType i = 0; i < ptIds->GetNumberOfIds(); ++i) {
++label_count[labels->GetComponent(ptIds->GetId(i), j)];
}
int max_cnt = 0;
double max_label = 0.;
for (const auto &cnt : label_count) {
if (cnt.second > max_cnt) {
max_label = cnt.first;
max_cnt = cnt.second;
}
}
output->SetComponent(cellId, j, max_label);
}
}
return output;
}
// -----------------------------------------------------------------------------
/// Convert cell data labels to point data
vtkSmartPointer<vtkDataArray> ConvertCellToPointLabels(vtkPointSet *pset, vtkDataArray *labels)
{
vtkSmartPointer<vtkDataArray> output;
output.TakeReference(labels->NewInstance());
output->SetName(labels->GetName());
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
output->SetComponentName(j, labels->GetComponentName(j));
}
output->SetNumberOfComponents(labels->GetNumberOfComponents());
output->SetNumberOfTuples(pset->GetNumberOfPoints());
OrderedMap<double, int> label_count;
vtkSmartPointer<vtkIdList> cellIds = vtkSmartPointer<vtkIdList>::New();
for (vtkIdType ptId = 0; ptId < pset->GetNumberOfPoints(); ++ptId) {
pset->GetPointCells(ptId, cellIds);
for (int j = 0; j < labels->GetNumberOfComponents(); ++j) {
label_count.clear();
for (vtkIdType i = 0; i < cellIds->GetNumberOfIds(); ++i) {
++label_count[labels->GetComponent(cellIds->GetId(i), j)];
}
int max_cnt = 0;
double max_label = 0.;
for (const auto &cnt : label_count) {
if (cnt.second > max_cnt) {
max_label = cnt.first;
max_cnt = cnt.second;
}
}
output->SetComponent(ptId, j, max_label);
}
}
return output;
}
// -----------------------------------------------------------------------------
/// Copy tuples from the input data array
vtkSmartPointer<vtkDataArray> Copy(vtkDataArray *array, vtkIdType n)
{
vtkSmartPointer<vtkDataArray> copy;
copy.TakeReference(array->NewInstance());
copy->SetName(array->GetName());
copy->SetNumberOfComponents(array->GetNumberOfComponents());
copy->SetNumberOfTuples(n);
for (int j = 0; j < array->GetNumberOfComponents(); ++j) {
copy->SetComponentName(j, array->GetComponentName(j));
}
vtkIdType ptId = 0;
while (ptId < n && ptId < array->GetNumberOfTuples()) {
copy->SetTuple(ptId, array->GetTuple(ptId));
++ptId;
}
while (ptId < n) {
for (int j = 0; j < copy->GetNumberOfComponents(); ++j) {
copy->SetComponent(ptId, j, .0);
}
++ptId;
}
return copy;
}
// -----------------------------------------------------------------------------
/// Add data array to data set attributes
void AddArray(vtkDataSetAttributes *data, vtkDataArray *array, AttributeType type)
{
switch (type) {
case AttributeType::SCALARS: data->SetScalars(array); break;
case AttributeType::VECTORS: data->SetVectors(array); break;
case AttributeType::NORMALS: data->SetNormals(array); break;
case AttributeType::TCOORDS: data->SetTCoords(array); break;
case AttributeType::TENSORS: data->SetTensors(array); break;
case AttributeType::GLOBALIDS: data->SetGlobalIds(array); break;
case AttributeType::PEDIGREEIDS: data->SetPedigreeIds(array); break;
default: data->AddArray(array); break;
}
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
vtkSmartPointer<vtkDataArray> array;
vtkSmartPointer<vtkDataArray> copy;
vtkDataSetAttributes *sourceAttr, *targetAttr;
vtkIdType ntuples;
// Positional arguments
REQUIRES_POSARGS(2);
if (NUM_POSARGS > 3) {
PrintHelp(EXECNAME);
exit(1);
}
const char *source_name = POSARG(1);
const char *target_name = POSARG(2);
const char *output_name = (NUM_POSARGS == 3 ? POSARG(3) : target_name);
// Optional arguments
Array<ArrayInfo> pd, cd;
const char *point_mask_name = nullptr;
const char *cell_mask_name = nullptr;
bool case_sensitive = false;
for (ALL_OPTIONS) {
if (OPTION("-points")) {
ArrayInfo info;
info._SourceIndex = -2;
if (HAS_ARGUMENT) info._TargetName = ARGUMENT;
else info._TargetName = NULL;
if (HAS_ARGUMENT) PARSE_ARGUMENT(info._TargetAttribute);
pd.push_back(info);
}
else if (OPTION("-scalars") || OPTION("-vectors") || OPTION("-normals") || OPTION("-tcoords")) {
ArrayInfo info;
FromString(OPTNAME + 1, info._SourceAttribute);
pd.push_back(info);
cd.push_back(info);
}
else if (OPTION("-vectors-as-points") || OPTION("-tcoords-as-points")) {
ArrayInfo info;
FromString(OPTNAME + 1, info._SourceAttribute);
info._TargetIndex = -2;
pd.push_back(info);
}
else if (OPTION("-pointdata") || OPTION("-pointdata-as-celldata") ||
OPTION("-celldata") || OPTION("-celldata-as-pointdata")) {
ArrayInfo info;
if (strcmp(OPTNAME, "-pointdata-as-celldata") == 0 ||
strcmp(OPTNAME, "-celldata-as-pointdata") == 0) {
info._PointCellConversion = true;
} else {
info._PointCellConversion = false;
}
info._SourceName = ARGUMENT;
if (FromString(info._SourceName, info._SourceIndex)) {
info._SourceName = NULL;
} else {
info._SourceIndex = -1;
}
if (HAS_ARGUMENT) {
info._TargetName = ARGUMENT;
}
if (HAS_ARGUMENT) PARSE_ARGUMENT(info._TargetAttribute);
if (strncmp(OPTNAME, "-pointdata", 10) == 0) pd.push_back(info);
else cd.push_back(info);
}
else if (OPTION("-pointdata-as-points")) {
ArrayInfo info;
info._SourceName = ARGUMENT;
if (FromString(info._SourceName, info._SourceIndex)) {
info._SourceName = NULL;
} else {
info._SourceIndex = -1;
}
info._TargetIndex = -2;
pd.push_back(info);
}
else if (OPTION("-pointmask")) point_mask_name = ARGUMENT;
else if (OPTION("-cellmask")) cell_mask_name = ARGUMENT;
else if (OPTION("-case-sensitive")) case_sensitive = true;
else if (OPTION("-case-insensitive")) case_sensitive = false;
else HANDLE_COMMON_OR_UNKNOWN_OPTION();
}
// Read input data sets
vtkSmartPointer<vtkPointSet> source, target;
target = ReadPointSet(target_name);
#if MIRTK_IO_WITH_GIFTI
if (Extension(source_name, EXT_Last) == ".gii") {
source = ReadGIFTI(source_name, vtkPolyData::SafeDownCast(target));
}
#endif
if (source == nullptr) {
source = ReadPointSet(source_name);
}
const vtkIdType npoints = target->GetNumberOfPoints();
const vtkIdType ncells = target->GetNumberOfCells();
vtkPointData * const sourcePD = source->GetPointData();
vtkCellData * const sourceCD = source->GetCellData();
vtkPointData * const targetPD = target->GetPointData();
vtkCellData * const targetCD = target->GetCellData();
// Copy all point set attributes by default
if (pd.empty() && cd.empty()) {
int attr;
for (int i = 0; i < sourcePD->GetNumberOfArrays(); ++i) {
attr = sourcePD->IsArrayAnAttribute(i);
if (attr < 0) attr = NUM_ATTRIBUTES;
ArrayInfo info;
info._SourceIndex = i;
info._TargetAttribute = static_cast<AttributeType>(attr);
pd.push_back(info);
}
for (int i = 0; i < sourceCD->GetNumberOfArrays(); ++i) {
attr = sourceCD->IsArrayAnAttribute(i);
if (attr < 0) attr = NUM_ATTRIBUTES;
ArrayInfo info;
info._SourceIndex = i;
info._TargetAttribute = static_cast<AttributeType>(attr);
cd.push_back(info);
}
}
// Convert point data to cell data if necessary
vtkSmartPointer<vtkCellData> pd_as_cd;
for (size_t i = 0; i < pd.size(); ++i) {
if (pd[i]._PointCellConversion) {
vtkNew<vtkPointDataToCellData> pd_to_cd;
SetVTKInput(pd_to_cd, source);
pd_to_cd->PassPointDataOff();
pd_to_cd->Update();
pd_as_cd = pd_to_cd->GetOutput()->GetCellData();
break;
}
}
// Convert cell data to point data if necessary
vtkSmartPointer<vtkPointData> cd_as_pd;
for (size_t i = 0; i < cd.size(); ++i) {
if (cd[i]._PointCellConversion) {
vtkNew<vtkCellDataToPointData> cd_to_pd;
SetVTKInput(cd_to_pd, source);
cd_to_pd->PassCellDataOff();
cd_to_pd->Update();
cd_as_pd = cd_to_pd->GetOutput()->GetPointData();
break;
}
}
// Add point data
for (size_t i = 0; i < pd.size(); ++i) {
if (pd[i]._SourceIndex == -2) {
vtkIdType end = min(npoints, source->GetNumberOfPoints());
if (pd[i]._TargetName) {
copy = vtkSmartPointer<vtkFloatArray>::New();
copy->SetNumberOfComponents(3);
copy->SetNumberOfTuples(npoints);
for (vtkIdType ptId = 0; ptId < end; ++ptId) {
copy->SetTuple(ptId, source->GetPoint(ptId));
}
const double zero[3] = {.0, .0, .0};
for (vtkIdType ptId = end; ptId < npoints; ++ptId) {
copy->SetTuple(ptId, zero);
}
} else {
vtkPoints *points = target->GetPoints();
for (vtkIdType ptId = 0; ptId < end; ++ptId) {
points->SetPoint(ptId, source->GetPoint(ptId));
}
copy = nullptr;
}
} else {
if (pd[i]._PointCellConversion && pd[i]._TargetIndex != -2) {
sourceAttr = pd_as_cd;
targetAttr = targetCD;
ntuples = ncells;
} else {
sourceAttr = sourcePD;
targetAttr = targetPD;
ntuples = npoints;
}
array = GetSourceArray("point", sourceAttr, pd[i], case_sensitive);
if (pd[i]._TargetIndex == -2) {
double p[3] = {.0};
vtkPoints *points = target->GetPoints();
vtkIdType end = min(npoints, source->GetNumberOfPoints());
int dim = min(3, array->GetNumberOfComponents());
for (vtkIdType ptId = 0; ptId < end; ++ptId) {
for (int i = 0; i < dim; ++i) p[i] = array->GetComponent(ptId, i);
points->SetPoint(ptId, p);
}
copy = nullptr;
} else {
if (sourceAttr == pd_as_cd.GetPointer()) {
if ((array->GetName() && ToLower(array->GetName()) .find("label") != string::npos) ||
(pd[i]._TargetName && ToLower(pd[i]._TargetName).find("label") != string::npos)) {
vtkDataArray *labels = GetSourceArray("point", sourcePD, pd[i], case_sensitive);
array = ConvertPointToCellLabels(source, labels);
}
}
copy = Copy(array, ntuples);
}
}
if (copy) {
if (pd[i]._TargetName) copy->SetName(pd[i]._TargetName);
AddArray(targetAttr, copy, pd[i]._TargetAttribute);
}
}
if (point_mask_name) {
vtkSmartPointer<vtkDataArray> mask = NewVTKDataArray(VTK_UNSIGNED_CHAR);
mask->SetName(point_mask_name);
mask->SetNumberOfComponents(1);
mask->SetNumberOfTuples(npoints);
mask->FillComponent(0, .0);
for (vtkIdType ptId = 0; ptId < npoints && ptId < source->GetNumberOfPoints(); ++ptId) {
mask->SetComponent(ptId, 0, 1.0);
}
targetPD->AddArray(mask);
}
// Add cell data
for (size_t i = 0; i < cd.size(); ++i) {
if (cd[i]._PointCellConversion) {
sourceAttr = cd_as_pd;
targetAttr = targetPD;
ntuples = npoints;
} else {
sourceAttr = sourceCD;
targetAttr = targetCD;
ntuples = ncells;
}
array = GetSourceArray("cell", sourceAttr, cd[i], case_sensitive);
if (sourceAttr == cd_as_pd.GetPointer()) {
if ((array->GetName() && ToLower(array->GetName()) .find("label") != string::npos) ||
(cd[i]._TargetName && ToLower(cd[i]._TargetName).find("label") != string::npos)) {
vtkDataArray *labels = GetSourceArray("cell", sourceCD, cd[i], case_sensitive);
array = ConvertCellToPointLabels(source, labels);
}
}
copy = Copy(array, ntuples);
if (cd[i]._TargetName) copy->SetName(cd[i]._TargetName);
AddArray(targetAttr, copy, cd[i]._TargetAttribute);
}
if (cell_mask_name) {
vtkSmartPointer<vtkDataArray> mask = NewVTKDataArray(VTK_UNSIGNED_CHAR);
mask->SetName(cell_mask_name);
mask->SetNumberOfComponents(1);
mask->SetNumberOfTuples(ncells);
mask->FillComponent(0, .0);
for (vtkIdType cellId = 0; cellId < ncells && cellId < source->GetNumberOfCells(); ++cellId) {
mask->SetComponent(cellId, 0, 1.0);
}
targetCD->AddArray(mask);
}
// Write resulting data set
WritePointSet(output_name, target);
}
|
// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "rdb_protocol/btree.hpp"
#include <string>
#include <vector>
#include "btree/backfill.hpp"
#include "btree/concurrent_traversal.hpp"
#include "btree/erase_range.hpp"
#include "btree/get_distribution.hpp"
#include "btree/operations.hpp"
#include "btree/parallel_traversal.hpp"
#include "buffer_cache/alt/alt_serialize_onto_blob.hpp"
#include "containers/archive/boost_types.hpp"
#include "containers/archive/buffer_group_stream.hpp"
#include "containers/archive/vector_stream.hpp"
#include "containers/scoped.hpp"
#include "rdb_protocol/blob_wrapper.hpp"
#include "rdb_protocol/func.hpp"
#include "rdb_protocol/lazy_json.hpp"
#include "rdb_protocol/transform_visitors.hpp"
value_sizer_t<rdb_value_t>::value_sizer_t(block_size_t bs) : block_size_(bs) { }
const rdb_value_t *value_sizer_t<rdb_value_t>::as_rdb(const void *p) {
return reinterpret_cast<const rdb_value_t *>(p);
}
int value_sizer_t<rdb_value_t>::size(const void *value) const {
return as_rdb(value)->inline_size(block_size_);
}
bool value_sizer_t<rdb_value_t>::fits(const void *value, int length_available) const {
return btree_value_fits(block_size_, length_available, as_rdb(value));
}
int value_sizer_t<rdb_value_t>::max_possible_size() const {
return blob::btree_maxreflen;
}
block_magic_t value_sizer_t<rdb_value_t>::leaf_magic() {
block_magic_t magic = { { 'r', 'd', 'b', 'l' } };
return magic;
}
block_magic_t value_sizer_t<rdb_value_t>::btree_leaf_magic() const {
return leaf_magic();
}
block_size_t value_sizer_t<rdb_value_t>::block_size() const { return block_size_; }
bool btree_value_fits(block_size_t bs, int data_length, const rdb_value_t *value) {
return blob::ref_fits(bs, data_length, value->value_ref(),
blob::btree_maxreflen);
}
void rdb_get(const store_key_t &store_key, btree_slice_t *slice,
superblock_t *superblock, point_read_response_t *response,
profile::trace_t *trace) {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_read(superblock, store_key.btree_key(), &kv_location,
&slice->stats, trace);
if (!kv_location.value.has()) {
response->data.reset(new ql::datum_t(ql::datum_t::R_NULL));
} else {
response->data = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
}
}
void kv_location_delete(keyvalue_location_t<rdb_value_t> *kv_location,
const store_key_t &key,
repli_timestamp_t timestamp,
rdb_modification_info_t *mod_info_out) {
// Notice this also implies that buf is valid.
guarantee(kv_location->value.has());
if (mod_info_out != NULL) {
guarantee(mod_info_out->deleted.second.empty());
// As noted above, we can be sure that buf is valid.
block_size_t block_size = kv_location->buf.cache()->get_block_size();
{
// RSI: Why do we detach a value only when mod_info_out is not NULL? I
// mistakenly had us detach a value whenever we say it's "deleted" -- but
// I guess we only say it's deleted when there's a mod_info_out -- we
// should probably put this outside the conditional.
blob_t blob(block_size, kv_location->value->value_ref(),
blob::btree_maxreflen);
blob.detach_subtree(&kv_location->buf);
}
mod_info_out->deleted.second.assign(kv_location->value->value_ref(),
kv_location->value->value_ref() +
kv_location->value->inline_size(block_size));
}
kv_location->value.reset();
null_key_modification_callback_t<rdb_value_t> null_cb;
apply_keyvalue_change(kv_location, key.btree_key(), timestamp,
expired_t::NO, &null_cb);
}
void kv_location_set(keyvalue_location_t<rdb_value_t> *kv_location,
const store_key_t &key,
counted_t<const ql::datum_t> data,
repli_timestamp_t timestamp,
rdb_modification_info_t *mod_info_out) {
scoped_malloc_t<rdb_value_t> new_value(blob::btree_maxreflen);
memset(new_value.get(), 0, blob::btree_maxreflen);
const block_size_t block_size = kv_location->buf.cache()->get_block_size();
{
blob_t blob(block_size, new_value->value_ref(), blob::btree_maxreflen);
serialize_onto_blob(buf_parent_t(&kv_location->buf), &blob, data);
}
if (mod_info_out) {
guarantee(mod_info_out->added.second.empty());
mod_info_out->added.second.assign(new_value->value_ref(),
new_value->value_ref() + new_value->inline_size(block_size));
}
if (kv_location->value.has() && mod_info_out) {
guarantee(mod_info_out->deleted.second.empty());
{
// RSI: Wait -- do we call detach_subtree in all the right places? For
// example, why does our detaching a value depend on whether mod_info_out
// is NULL or not?
blob_t blob(block_size, kv_location->value->value_ref(),
blob::btree_maxreflen);
blob.detach_subtree(&kv_location->buf);
}
mod_info_out->deleted.second.assign(
kv_location->value->value_ref(),
kv_location->value->value_ref()
+ kv_location->value->inline_size(block_size));
}
// Actually update the leaf, if needed.
kv_location->value = std::move(new_value);
null_key_modification_callback_t<rdb_value_t> null_cb;
apply_keyvalue_change(kv_location, key.btree_key(), timestamp,
expired_t::NO, &null_cb);
}
void kv_location_set(keyvalue_location_t<rdb_value_t> *kv_location,
const store_key_t &key,
const std::vector<char> &value_ref,
repli_timestamp_t timestamp) {
scoped_malloc_t<rdb_value_t> new_value(
value_ref.data(), value_ref.data() + value_ref.size());
// Update the leaf, if needed.
kv_location->value = std::move(new_value);
null_key_modification_callback_t<rdb_value_t> null_cb;
apply_keyvalue_change(kv_location, key.btree_key(), timestamp,
expired_t::NO, &null_cb);
}
batched_replace_response_t rdb_replace_and_return_superblock(
const btree_loc_info_t &info,
const btree_point_replacer_t *replacer,
promise_t<superblock_t *> *superblock_promise,
rdb_modification_info_t *mod_info_out,
profile::trace_t *trace)
{
bool return_vals = replacer->should_return_vals();
const std::string &primary_key = *info.btree->primary_key;
const store_key_t &key = *info.key;
ql::datum_ptr_t resp(ql::datum_t::R_OBJECT);
try {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(info.superblock, info.key->btree_key(),
&kv_location,
&info.btree->slice->stats,
trace,
superblock_promise);
bool started_empty, ended_empty;
counted_t<const ql::datum_t> old_val;
if (!kv_location.value.has()) {
// If there's no entry with this key, pass NULL to the function.
started_empty = true;
old_val = make_counted<ql::datum_t>(ql::datum_t::R_NULL);
} else {
// Otherwise pass the entry with this key to the function.
started_empty = false;
old_val = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
guarantee(old_val->get(primary_key, ql::NOTHROW).has());
}
guarantee(old_val.has());
if (return_vals == RETURN_VALS) {
bool conflict = resp.add("old_val", old_val)
|| resp.add("new_val", old_val); // changed below
guarantee(!conflict);
}
counted_t<const ql::datum_t> new_val = replacer->replace(old_val);
if (return_vals == RETURN_VALS) {
bool conflict = resp.add("new_val", new_val, ql::CLOBBER);
guarantee(conflict); // We set it to `old_val` previously.
}
if (new_val->get_type() == ql::datum_t::R_NULL) {
ended_empty = true;
} else if (new_val->get_type() == ql::datum_t::R_OBJECT) {
ended_empty = false;
new_val->rcheck_valid_replace(
old_val, counted_t<const ql::datum_t>(), primary_key);
counted_t<const ql::datum_t> pk = new_val->get(primary_key, ql::NOTHROW);
rcheck_target(
new_val, ql::base_exc_t::GENERIC,
key.compare(store_key_t(pk->print_primary())) == 0,
(started_empty
? strprintf("Primary key `%s` cannot be changed (null -> %s)",
primary_key.c_str(), new_val->print().c_str())
: strprintf("Primary key `%s` cannot be changed (%s -> %s)",
primary_key.c_str(),
old_val->print().c_str(), new_val->print().c_str())));
} else {
rfail_typed_target(
new_val, "Inserted value must be an OBJECT (got %s):\n%s",
new_val->get_type_name().c_str(), new_val->print().c_str());
}
// We use `conflict` below to store whether or not there was a key
// conflict when constructing the stats object. It defaults to `true`
// so that we fail an assertion if we never update the stats object.
bool conflict = true;
// Figure out what operation we're doing (based on started_empty,
// ended_empty, and the result of the function call) and then do it.
if (started_empty) {
if (ended_empty) {
conflict = resp.add("skipped", make_counted<ql::datum_t>(1.0));
} else {
conflict = resp.add("inserted", make_counted<ql::datum_t>(1.0));
r_sanity_check(new_val->get(primary_key, ql::NOTHROW).has());
kv_location_set(&kv_location, *info.key, new_val, info.btree->timestamp,
mod_info_out);
guarantee(mod_info_out->deleted.second.empty());
guarantee(!mod_info_out->added.second.empty());
mod_info_out->added.first = new_val;
}
} else {
if (ended_empty) {
conflict = resp.add("deleted", make_counted<ql::datum_t>(1.0));
kv_location_delete(&kv_location, *info.key, info.btree->timestamp,
mod_info_out);
guarantee(!mod_info_out->deleted.second.empty());
guarantee(mod_info_out->added.second.empty());
mod_info_out->deleted.first = old_val;
} else {
r_sanity_check(
*old_val->get(primary_key) == *new_val->get(primary_key));
if (*old_val == *new_val) {
conflict = resp.add("unchanged",
make_counted<ql::datum_t>(1.0));
} else {
conflict = resp.add("replaced", make_counted<ql::datum_t>(1.0));
r_sanity_check(new_val->get(primary_key, ql::NOTHROW).has());
kv_location_set(&kv_location, *info.key, new_val,
info.btree->timestamp,
mod_info_out);
guarantee(!mod_info_out->deleted.second.empty());
guarantee(!mod_info_out->added.second.empty());
mod_info_out->added.first = new_val;
mod_info_out->deleted.first = old_val;
}
}
}
guarantee(!conflict); // message never added twice
} catch (const ql::base_exc_t &e) {
resp.add_error(e.what());
} catch (const interrupted_exc_t &e) {
std::string msg = strprintf("interrupted (%s:%d)", __FILE__, __LINE__);
resp.add_error(msg.c_str());
// We don't rethrow because we're in a coroutine. Theoretically the
// above message should never make it back to a user because the calling
// function will also be interrupted, but we document where it comes
// from to aid in future debugging if that invariant becomes violated.
}
return resp.to_counted();
}
class one_replace_t : public btree_point_replacer_t {
public:
one_replace_t(const btree_batched_replacer_t *_replacer, size_t _index)
: replacer(_replacer), index(_index) { }
counted_t<const ql::datum_t> replace(const counted_t<const ql::datum_t> &d) const {
return replacer->replace(d, index);
}
bool should_return_vals() const { return replacer->should_return_vals(); }
private:
const btree_batched_replacer_t *const replacer;
const size_t index;
};
void do_a_replace_from_batched_replace(
auto_drainer_t::lock_t,
fifo_enforcer_sink_t *batched_replaces_fifo_sink,
const fifo_enforcer_write_token_t &batched_replaces_fifo_token,
const btree_loc_info_t &info,
const one_replace_t one_replace,
promise_t<superblock_t *> *superblock_promise,
rdb_modification_report_cb_t *sindex_cb,
batched_replace_response_t *stats_out,
profile::trace_t *trace)
{
fifo_enforcer_sink_t::exit_write_t exiter(
batched_replaces_fifo_sink, batched_replaces_fifo_token);
rdb_modification_report_t mod_report(*info.key);
counted_t<const ql::datum_t> res = rdb_replace_and_return_superblock(
info, &one_replace, superblock_promise, &mod_report.info, trace);
*stats_out = (*stats_out)->merge(res, ql::stats_merge);
// RSI: What is this for? are we waiting to get in line to call on_mod_report? I guess so.
// JD: Looks like this is a do_a_replace_from_batched_replace specific thing.
exiter.wait();
sindex_cb->on_mod_report(mod_report);
}
batched_replace_response_t rdb_batched_replace(
const btree_info_t &info,
scoped_ptr_t<superblock_t> *superblock,
const std::vector<store_key_t> &keys,
const btree_batched_replacer_t *replacer,
rdb_modification_report_cb_t *sindex_cb,
profile::trace_t *trace) {
fifo_enforcer_source_t batched_replaces_fifo_source;
fifo_enforcer_sink_t batched_replaces_fifo_sink;
counted_t<const ql::datum_t> stats(new ql::datum_t(ql::datum_t::R_OBJECT));
// We have to drain write operations before destructing everything above us,
// because the coroutines being drained use them.
{
auto_drainer_t drainer;
// Note the destructor ordering: We release the superblock before draining
// on all the write operations.
scoped_ptr_t<superblock_t> current_superblock(superblock->release());
for (size_t i = 0; i < keys.size(); ++i) {
// Pass out the point_replace_response_t.
promise_t<superblock_t *> superblock_promise;
coro_t::spawn_sometime(
std::bind(
&do_a_replace_from_batched_replace,
auto_drainer_t::lock_t(&drainer),
&batched_replaces_fifo_sink,
batched_replaces_fifo_source.enter_write(),
btree_loc_info_t(&info, current_superblock.release(), &keys[i]),
one_replace_t(replacer, i),
&superblock_promise,
sindex_cb,
&stats,
trace));
current_superblock.init(superblock_promise.wait());
}
} // Make sure the drainer is destructed before the return statement.
return stats;
}
void rdb_set(const store_key_t &key,
counted_t<const ql::datum_t> data,
bool overwrite,
btree_slice_t *slice,
repli_timestamp_t timestamp,
superblock_t *superblock,
point_write_response_t *response_out,
rdb_modification_info_t *mod_info,
profile::trace_t *trace) {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(superblock, key.btree_key(), &kv_location,
&slice->stats, trace);
const bool had_value = kv_location.value.has();
/* update the modification report */
if (kv_location.value.has()) {
mod_info->deleted.first = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
}
mod_info->added.first = data;
if (overwrite || !had_value) {
kv_location_set(&kv_location, key, data, timestamp, mod_info);
guarantee(mod_info->deleted.second.empty() == !had_value &&
!mod_info->added.second.empty());
}
response_out->result =
(had_value ? point_write_result_t::DUPLICATE : point_write_result_t::STORED);
}
class agnostic_rdb_backfill_callback_t : public agnostic_backfill_callback_t {
public:
agnostic_rdb_backfill_callback_t(rdb_backfill_callback_t *cb,
const key_range_t &kr,
btree_slice_t *slice) :
cb_(cb), kr_(kr), slice_(slice) { }
void on_delete_range(const key_range_t &range, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
rassert(kr_.is_superset(range));
cb_->on_delete_range(range, interruptor);
}
void on_deletion(const btree_key_t *key, repli_timestamp_t recency, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
rassert(kr_.contains_key(key->contents, key->size));
cb_->on_deletion(key, recency, interruptor);
}
void on_pair(buf_parent_t leaf_node, repli_timestamp_t recency,
const btree_key_t *key, const void *val,
signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
rassert(kr_.contains_key(key->contents, key->size));
const rdb_value_t *value = static_cast<const rdb_value_t *>(val);
slice_->stats.pm_keys_read.record();
rdb_protocol_details::backfill_atom_t atom;
atom.key.assign(key->size, key->contents);
atom.value = get_data(value, leaf_node);
atom.recency = recency;
cb_->on_keyvalue(atom, interruptor);
}
void on_sindexes(const std::map<std::string, secondary_index_t> &sindexes, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
cb_->on_sindexes(sindexes, interruptor);
}
rdb_backfill_callback_t *cb_;
key_range_t kr_;
btree_slice_t *slice_;
};
void rdb_backfill(btree_slice_t *slice, const key_range_t& key_range,
repli_timestamp_t since_when, rdb_backfill_callback_t *callback,
superblock_t *superblock,
buf_lock_t *sindex_block,
parallel_traversal_progress_t *p, signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t) {
agnostic_rdb_backfill_callback_t agnostic_cb(callback, key_range, slice);
value_sizer_t<rdb_value_t> sizer(slice->cache()->get_block_size());
do_agnostic_btree_backfill(&sizer, slice, key_range, since_when, &agnostic_cb,
superblock, sindex_block, p, interruptor);
}
void rdb_delete(const store_key_t &key, btree_slice_t *slice,
repli_timestamp_t timestamp,
superblock_t *superblock, point_delete_response_t *response,
rdb_modification_info_t *mod_info,
profile::trace_t *trace) {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(superblock, key.btree_key(),
&kv_location, &slice->stats, trace);
bool exists = kv_location.value.has();
/* Update the modification report. */
if (exists) {
mod_info->deleted.first = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
kv_location_delete(&kv_location, key, timestamp, mod_info);
}
guarantee(!mod_info->deleted.second.empty() && mod_info->added.second.empty());
response->result = (exists ? point_delete_result_t::DELETED : point_delete_result_t::MISSING);
}
// Remember that secondary indexes and the main btree both point to the same rdb
// value -- you don't want to double-delete that value!
void actually_delete_rdb_value(buf_parent_t parent, void *value) {
blob_t blob(parent.cache()->get_block_size(),
static_cast<rdb_value_t *>(value)->value_ref(),
blob::btree_maxreflen);
blob.clear(parent);
}
void rdb_value_deleter_t::delete_value(buf_parent_t parent, void *value) {
actually_delete_rdb_value(parent, value);
}
void rdb_value_non_deleter_t::delete_value(buf_parent_t, void *) {
//RSI should we be detaching blobs in here?
}
class sindex_key_range_tester_t : public key_tester_t {
public:
explicit sindex_key_range_tester_t(const key_range_t &key_range)
: key_range_(key_range) { }
bool key_should_be_erased(const btree_key_t *key) {
std::string pk = ql::datum_t::extract_primary(
key_to_unescaped_str(store_key_t(key)));
return key_range_.contains_key(store_key_t(pk));
}
private:
key_range_t key_range_;
};
typedef btree_store_t<rdb_protocol_t>::sindex_access_t sindex_access_t;
typedef btree_store_t<rdb_protocol_t>::sindex_access_vector_t sindex_access_vector_t;
void sindex_erase_range(const key_range_t &key_range,
const sindex_access_t *sindex_access, auto_drainer_t::lock_t,
signal_t *interruptor, bool release_superblock) THROWS_NOTHING {
value_sizer_t<rdb_value_t> rdb_sizer(sindex_access->btree->cache()->get_block_size());
value_sizer_t<void> *sizer = &rdb_sizer;
rdb_value_non_deleter_t deleter;
sindex_key_range_tester_t tester(key_range);
try {
btree_erase_range_generic(sizer, sindex_access->btree, &tester,
&deleter, NULL, NULL,
sindex_access->super_block.get(), interruptor,
release_superblock);
} catch (const interrupted_exc_t &) {
// We were interrupted. That's fine nothing to be done about it.
}
}
/* Spawns a coro to carry out the erase range for each sindex. */
void spawn_sindex_erase_ranges(
const sindex_access_vector_t *sindex_access,
const key_range_t &key_range,
auto_drainer_t *drainer,
auto_drainer_t::lock_t,
bool release_superblock,
signal_t *interruptor) {
for (auto it = sindex_access->begin(); it != sindex_access->end(); ++it) {
coro_t::spawn_sometime(std::bind(
&sindex_erase_range, key_range, &*it,
auto_drainer_t::lock_t(drainer), interruptor,
release_superblock));
}
}
void rdb_erase_range(btree_slice_t *slice, key_tester_t *tester,
const key_range_t &key_range,
buf_lock_t *sindex_block,
superblock_t *superblock,
btree_store_t<rdb_protocol_t> *store,
signal_t *interruptor) {
/* This is guaranteed because the way the keys are calculated below would
* lead to a single key being deleted even if the range was empty. */
guarantee(!key_range.is_empty());
/* Dispatch the erase range to the sindexes. */
sindex_access_vector_t sindex_superblocks;
{
store->acquire_post_constructed_sindex_superblocks_for_write(
sindex_block, &sindex_superblocks);
mutex_t::acq_t acq;
store->lock_sindex_queue(sindex_block, &acq);
write_message_t wm;
wm << rdb_sindex_change_t(rdb_erase_range_report_t(key_range));
store->sindex_queue_push(wm, &acq);
}
{
auto_drainer_t sindex_erase_drainer;
spawn_sindex_erase_ranges(&sindex_superblocks, key_range,
&sindex_erase_drainer, auto_drainer_t::lock_t(&sindex_erase_drainer),
true /* release the superblock */, interruptor);
/* Notice, when we exit this block we destruct the sindex_erase_drainer
* which means we'll wait until all of the sindex_erase_ranges finish
* executing. This is an important detail because the sindexes only
* store references to their data. They don't actually store a full
* copy of the data themselves. The call to btree_erase_range_generic
* is the one that will actually erase the data and if we were to make
* that call before the indexes were finished erasing we would have
* reference to data which didn't actually exist and another process
* could read that data. */
/* TL;DR it's very important that we make sure all of the coros spawned
* by spawn_sindex_erase_ranges complete before we proceed past this
* point. */
}
/* Twiddle some keys to get the in the form we want. Notice these are keys
* which will be made exclusive and inclusive as their names suggest
* below. At the point of construction they aren't. */
store_key_t left_key_exclusive(key_range.left);
store_key_t right_key_inclusive(key_range.right.key);
bool left_key_supplied = left_key_exclusive.decrement();
bool right_key_supplied = !key_range.right.unbounded;
if (right_key_supplied) {
right_key_inclusive.decrement();
}
/* Now left_key_exclusive and right_key_inclusive accurately reflect their
* names. */
/* We need these structures to perform the erase range. */
value_sizer_t<rdb_value_t> rdb_sizer(slice->cache()->get_block_size());
value_sizer_t<void> *sizer = &rdb_sizer;
rdb_value_deleter_t deleter;
btree_erase_range_generic(sizer, slice, tester, &deleter,
left_key_supplied ? left_key_exclusive.btree_key() : NULL,
right_key_supplied ? right_key_inclusive.btree_key() : NULL,
superblock, interruptor);
// RSI: this comment about auto_drainer_t is false.
// auto_drainer_t is destructed here so this waits for other coros to finish.
}
// This is actually a kind of misleading name. This function estimates the size of a datum,
// not a whole rget, though it is used for that purpose (by summing up these responses).
size_t estimate_rget_response_size(const counted_t<const ql::datum_t> &datum) {
return serialized_size(datum);
}
class rdb_rget_depth_first_traversal_callback_t
: public concurrent_traversal_callback_t {
public:
/* This constructor does a traversal on the primary btree, it's not to be
* used with sindexes. The constructor below is for use with sindexes. */
rdb_rget_depth_first_traversal_callback_t(
ql::env_t *_ql_env,
const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &_transform,
boost::optional<rdb_protocol_details::terminal_t> _terminal,
const key_range_t &range,
sorting_t _sorting,
rget_read_response_t *_response,
btree_slice_t *_slice)
: bad_init(false),
response(_response),
ql_env(_ql_env),
batcher(batchspec.to_batcher()),
transform(_transform),
terminal(_terminal),
sorting(_sorting),
slice(_slice)
{
init(range);
}
/* This constructor is used if you're doing a secondary index get, it takes
* an extra key_range_t (_primary_key_range) which is used to filter out
* unwanted results. The reason you can get unwanted results is is
* oversharding. When we overshard multiple logical shards are stored in
* the same physical btree_store_t, this is transparent with all other
* operations but their sindex values get mixed together and you wind up
* with multiple copies of each. This constructor will filter out the
* duplicates. This was issue #606. */
rdb_rget_depth_first_traversal_callback_t(
ql::env_t *_ql_env,
const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &_transform,
boost::optional<rdb_protocol_details::terminal_t> _terminal,
const key_range_t &range,
const key_range_t &_primary_key_range,
sorting_t _sorting,
ql::map_wire_func_t _sindex_function,
sindex_multi_bool_t _sindex_multi,
datum_range_t _sindex_range,
rget_read_response_t *_response,
btree_slice_t *_slice)
: bad_init(false),
response(_response),
ql_env(_ql_env),
batcher(batchspec.to_batcher()),
transform(_transform),
terminal(_terminal),
sorting(_sorting),
primary_key_range(_primary_key_range),
sindex_range(_sindex_range),
sindex_multi(_sindex_multi),
slice(_slice)
{
sindex_function = _sindex_function.compile_wire_func();
init(range);
}
void init(const key_range_t &range) {
try {
if (!reversed(sorting)) {
response->last_considered_key = range.left;
} else {
if (!range.right.unbounded) {
response->last_considered_key = range.right.key;
} else {
response->last_considered_key = store_key_t::max();
}
}
if (terminal) {
query_language::terminal_initialize(&*terminal, &response->result);
}
disabler.init(new profile::disabler_t(ql_env->trace));
sampler.init(new profile::sampler_t("Range traversal doc evaluation.", ql_env->trace));
} catch (const ql::exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any more requests. */
response->result = e2;
bad_init = true;
} catch (const ql::datum_exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any more requests. */
terminal_exception(e2, *terminal, &response->result);
bad_init = true;
}
}
virtual bool handle_pair(scoped_key_value_t &&keyvalue,
concurrent_traversal_fifo_enforcer_signal_t waiter)
THROWS_ONLY(interrupted_exc_t) {
sampler->new_sample();
store_key_t store_key(keyvalue.key());
if (bad_init) {
return false;
}
if (primary_key_range) {
std::string pk = ql::datum_t::extract_primary(
key_to_unescaped_str(store_key));
if (!primary_key_range->contains_key(store_key_t(pk))) {
return true;
}
}
try {
lazy_json_t first_value(static_cast<const rdb_value_t *>(keyvalue.value()),
keyvalue.expose_buf());
// When doing "count" queries, we don't want to actually load the json
// value. Here we detect up-front whether we will need to load the value.
// If nothing uses the value, we load it here. Otherwise we never load
// it. The main problem with this code is that we still need a time to
// exclusively process each row, in between the call to
// waiter.wait_interruptible() and the end of this function. If we fixed
// the design that makes us need to _process_ each row one at a time, we
// wouldn't have to guess up front whether the lazy_json_t actually needs
// to be loaded, and the code would be safer (and algorithmically more
// parallelized).
if (sindex_function.has() || !transform.empty() || !terminal
|| query_language::terminal_uses_value(*terminal)) {
// Force the value to be loaded.
first_value.get();
// Increment reads here since the btree doesn't know if we actually do a read
slice->stats.pm_keys_read.record();
} else {
// We _must_ load the value before calling keyvalue.reset(), and
// before calling waiter.wait_interruptible(). So we call
// first_value.reset() to make any later call to .get() fail.
first_value.reset();
}
rassert(!first_value.references_parent());
keyvalue.reset();
waiter.wait_interruptible();
if ((response->last_considered_key < store_key && !reversed(sorting)) ||
(response->last_considered_key > store_key && reversed(sorting))) {
response->last_considered_key = store_key;
}
std::vector<lazy_json_t> data;
data.push_back(first_value);
counted_t<const ql::datum_t> sindex_value;
if (sindex_function) {
sindex_value =
sindex_function->call(ql_env, first_value.get())->as_datum();
guarantee(sindex_range);
guarantee(sindex_multi);
if (sindex_multi == sindex_multi_bool_t::MULTI &&
sindex_value->get_type() == ql::datum_t::R_ARRAY) {
boost::optional<uint64_t> tag =
ql::datum_t::extract_tag(key_to_unescaped_str(store_key));
guarantee(tag);
guarantee(sindex_value->size() > *tag);
sindex_value = sindex_value->get(*tag);
}
if (!sindex_range->contains(sindex_value)) {
return true;
}
}
// Apply transforms to the data
{
rdb_protocol_details::transform_t::iterator it;
for (it = transform.begin(); it != transform.end(); ++it) {
try {
std::vector<counted_t<const ql::datum_t> > tmp;
for (auto jt = data.begin(); jt != data.end(); ++jt) {
query_language::transform_apply(
ql_env, jt->get(), &*it, &tmp);
}
data.clear();
for (auto jt = tmp.begin(); jt != tmp.end(); ++jt) {
data.push_back(lazy_json_t(*jt));
}
} catch (const ql::datum_exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any
more requests. */
transform_exception(e2, *it, &response->result);
return false;
}
}
}
if (!terminal) {
typedef rget_read_response_t::stream_t stream_t;
stream_t *stream = boost::get<stream_t>(&response->result);
guarantee(stream);
for (auto it = data.begin(); it != data.end(); ++it) {
counted_t<const ql::datum_t> datum = it->get();
if (sorting != sorting_t::UNORDERED && sindex_value) {
stream->push_back(rdb_protocol_details::rget_item_t(
store_key, sindex_value, datum));
} else {
stream->push_back(rdb_protocol_details::rget_item_t(
store_key, datum));
}
batcher.note_el(datum);
}
return !batcher.should_send_batch();
} else {
try {
for (auto jt = data.begin(); jt != data.end(); ++jt) {
query_language::terminal_apply(
ql_env, *jt, &*terminal, &response->result);
}
return true;
} catch (const ql::datum_exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any
more requests. */
terminal_exception(e2, *terminal, &response->result);
return false;
}
}
} catch (const ql::exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any more requests. */
response->result = e2;
return false;
}
}
virtual profile::trace_t *get_trace() THROWS_NOTHING {
return ql_env->trace.get_or_null();
}
bool bad_init;
rget_read_response_t *response;
ql::env_t *ql_env;
ql::batcher_t batcher;
rdb_protocol_details::transform_t transform;
boost::optional<rdb_protocol_details::terminal_t> terminal;
sorting_t sorting;
/* Only present if we're doing a sindex read.*/
boost::optional<key_range_t> primary_key_range;
boost::optional<datum_range_t> sindex_range;
counted_t<ql::func_t> sindex_function;
boost::optional<sindex_multi_bool_t> sindex_multi;
scoped_ptr_t<profile::disabler_t> disabler;
scoped_ptr_t<profile::sampler_t> sampler;
btree_slice_t *slice;
};
class result_finalizer_visitor_t : public boost::static_visitor<void> {
public:
void operator()(const rget_read_response_t::stream_t &) const { }
void operator()(const ql::exc_t &) const { }
void operator()(const ql::datum_exc_t &) const { }
void operator()(const std::vector<ql::wire_datum_map_t> &) const { }
void operator()(const rget_read_response_t::empty_t &) const { }
void operator()(const counted_t<const ql::datum_t> &) const { }
void operator()(ql::wire_datum_map_t &dm) const { // NOLINT(runtime/references)
dm.finalize();
}
};
void rdb_rget_slice(btree_slice_t *slice, const key_range_t &range,
superblock_t *superblock,
ql::env_t *ql_env, const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &transform,
const boost::optional<rdb_protocol_details::terminal_t> &terminal,
sorting_t sorting,
rget_read_response_t *response) {
profile::starter_t starter("Do range scan on primary index.", ql_env->trace);
rdb_rget_depth_first_traversal_callback_t callback(
ql_env, batchspec, transform, terminal, range, sorting, response, slice);
btree_concurrent_traversal(slice, superblock, range, &callback,
(!reversed(sorting) ? FORWARD : BACKWARD));
response->truncated = callback.batcher.should_send_batch();
boost::apply_visitor(result_finalizer_visitor_t(), response->result);
}
void rdb_rget_secondary_slice(
btree_slice_t *slice,
const datum_range_t &sindex_range,
const rdb_protocol_t::region_t &sindex_region,
superblock_t *superblock,
ql::env_t *ql_env,
const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &transform,
const boost::optional<rdb_protocol_details::terminal_t> &terminal,
const key_range_t &pk_range,
sorting_t sorting,
const ql::map_wire_func_t &sindex_func,
sindex_multi_bool_t sindex_multi,
rget_read_response_t *response) {
profile::starter_t starter("Do range scan on secondary index.", ql_env->trace);
rdb_rget_depth_first_traversal_callback_t callback(
ql_env, batchspec, transform, terminal, sindex_region.inner, pk_range,
sorting, sindex_func, sindex_multi, sindex_range, response, slice);
btree_concurrent_traversal(
slice, superblock, sindex_region.inner, &callback,
(!reversed(sorting) ? FORWARD : BACKWARD));
response->truncated = callback.batcher.should_send_batch();
boost::apply_visitor(result_finalizer_visitor_t(), response->result);
}
void rdb_distribution_get(btree_slice_t *slice, int max_depth,
const store_key_t &left_key,
superblock_t *superblock,
distribution_read_response_t *response) {
int64_t key_count_out;
std::vector<store_key_t> key_splits;
get_btree_key_distribution(slice, superblock, max_depth,
&key_count_out, &key_splits);
int64_t keys_per_bucket;
if (key_splits.size() == 0) {
keys_per_bucket = key_count_out;
} else {
keys_per_bucket = std::max<int64_t>(key_count_out / key_splits.size(), 1);
}
response->key_counts[left_key] = keys_per_bucket;
for (std::vector<store_key_t>::iterator it = key_splits.begin();
it != key_splits.end();
++it) {
response->key_counts[*it] = keys_per_bucket;
}
}
static const int8_t HAS_VALUE = 0;
static const int8_t HAS_NO_VALUE = 1;
void rdb_modification_info_t::rdb_serialize(write_message_t &msg) const { // NOLINT(runtime/references)
if (!deleted.first.get()) {
guarantee(deleted.second.empty());
msg << HAS_NO_VALUE;
} else {
msg << HAS_VALUE;
msg << deleted;
}
if (!added.first.get()) {
guarantee(added.second.empty());
msg << HAS_NO_VALUE;
} else {
msg << HAS_VALUE;
msg << added;
}
}
archive_result_t rdb_modification_info_t::rdb_deserialize(read_stream_t *s) {
archive_result_t res;
int8_t has_value;
res = deserialize(s, &has_value);
if (res) { return res; }
if (has_value == HAS_VALUE) {
res = deserialize(s, &deleted);
if (res) { return res; }
}
res = deserialize(s, &has_value);
if (res) { return res; }
if (has_value == HAS_VALUE) {
res = deserialize(s, &added);
if (res) { return res; }
}
return ARCHIVE_SUCCESS;
}
RDB_IMPL_ME_SERIALIZABLE_2(rdb_modification_report_t, primary_key, info);
RDB_IMPL_ME_SERIALIZABLE_1(rdb_erase_range_report_t, range_to_erase);
rdb_modification_report_cb_t::rdb_modification_report_cb_t(
btree_store_t<rdb_protocol_t> *store,
buf_lock_t *sindex_block,
auto_drainer_t::lock_t lock)
: lock_(lock), store_(store),
sindex_block_(sindex_block) {
store_->acquire_post_constructed_sindex_superblocks_for_write(
sindex_block_, &sindexes_);
}
rdb_modification_report_cb_t::~rdb_modification_report_cb_t() { }
void rdb_modification_report_cb_t::on_mod_report(
const rdb_modification_report_t &mod_report) {
mutex_t::acq_t acq;
store_->lock_sindex_queue(sindex_block_, &acq);
write_message_t wm;
wm << rdb_sindex_change_t(mod_report);
store_->sindex_queue_push(wm, &acq);
rdb_update_sindexes(sindexes_, &mod_report, sindex_block_->txn());
}
typedef btree_store_t<rdb_protocol_t>::sindex_access_vector_t sindex_access_vector_t;
void compute_keys(const store_key_t &primary_key, counted_t<const ql::datum_t> doc,
ql::map_wire_func_t *mapping, sindex_multi_bool_t multi, ql::env_t *env,
std::vector<store_key_t> *keys_out) {
guarantee(keys_out->empty());
counted_t<const ql::datum_t> index =
mapping->compile_wire_func()->call(env, doc)->as_datum();
if (multi == sindex_multi_bool_t::MULTI && index->get_type() == ql::datum_t::R_ARRAY) {
for (uint64_t i = 0; i < index->size(); ++i) {
keys_out->push_back(
store_key_t(index->get(i, ql::THROW)->print_secondary(primary_key, i)));
}
} else {
keys_out->push_back(store_key_t(index->print_secondary(primary_key)));
}
}
/* Used below by rdb_update_sindexes. */
void rdb_update_single_sindex(
const btree_store_t<rdb_protocol_t>::sindex_access_t *sindex,
const rdb_modification_report_t *modification,
auto_drainer_t::lock_t) {
// Note if you get this error it's likely that you've passed in a default
// constructed mod_report. Don't do that. Mod reports should always be passed
// to a function as an output parameter before they're passed to this
// function.
guarantee(modification->primary_key.size() != 0);
ql::map_wire_func_t mapping;
sindex_multi_bool_t multi = sindex_multi_bool_t::MULTI;
vector_read_stream_t read_stream(&sindex->sindex.opaque_definition);
archive_result_t success = deserialize(&read_stream, &mapping);
guarantee_deserialization(success, "sindex deserialize");
success = deserialize(&read_stream, &multi);
guarantee_deserialization(success, "sindex deserialize");
// TODO we just use a NULL environment here. People should not be able
// to do anything that requires an environment like gets from other
// tables etc. but we don't have a nice way to disallow those things so
// for now we pass null and it will segfault if an illegal sindex
// mapping is passed.
cond_t non_interruptor;
ql::env_t env(&non_interruptor);
superblock_t *super_block = sindex->super_block.get();
if (modification->info.deleted.first) {
guarantee(!modification->info.deleted.second.empty());
try {
counted_t<const ql::datum_t> deleted = modification->info.deleted.first;
std::vector<store_key_t> keys;
compute_keys(modification->primary_key, deleted, &mapping, multi, &env, &keys);
for (auto it = keys.begin(); it != keys.end(); ++it) {
promise_t<superblock_t *> return_superblock_local;
{
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(super_block,
it->btree_key(),
&kv_location,
&sindex->btree->stats,
env.trace.get_or_null(),
&return_superblock_local);
if (kv_location.value.has()) {
kv_location_delete(&kv_location, *it,
repli_timestamp_t::distant_past, NULL);
}
// The keyvalue location gets destroyed here.
}
super_block = return_superblock_local.wait();
}
} catch (const ql::base_exc_t &) {
// Do nothing (it wasn't actually in the index).
}
}
if (modification->info.added.first) {
try {
counted_t<const ql::datum_t> added = modification->info.added.first;
std::vector<store_key_t> keys;
compute_keys(modification->primary_key, added, &mapping, multi, &env, &keys);
for (auto it = keys.begin(); it != keys.end(); ++it) {
promise_t<superblock_t *> return_superblock_local;
{
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(super_block,
it->btree_key(),
&kv_location,
&sindex->btree->stats,
env.trace.get_or_null(),
&return_superblock_local);
kv_location_set(&kv_location, *it,
modification->info.added.second,
repli_timestamp_t::distant_past);
// The keyvalue location gets destroyed here.
}
super_block = return_superblock_local.wait();
}
} catch (const ql::base_exc_t &) {
// Do nothing (we just drop the row from the index).
}
}
}
void rdb_update_sindexes(const sindex_access_vector_t &sindexes,
const rdb_modification_report_t *modification,
txn_t *txn) {
{
auto_drainer_t drainer;
for (sindex_access_vector_t::const_iterator it = sindexes.begin();
it != sindexes.end();
++it) {
coro_t::spawn_sometime(std::bind(
&rdb_update_single_sindex, &*it,
modification, auto_drainer_t::lock_t(&drainer)));
}
}
/* All of the sindex have been updated now it's time to actually clear the
* deleted blob if it exists. */
if (modification->info.deleted.first) {
// Deleting the value unfortunately updates the ref in-place as it operates, so
// we need to make a copy of the blob reference that is extended to the
// appropriate width.
std::vector<char> ref_cpy(modification->info.deleted.second);
ref_cpy.insert(ref_cpy.end(), blob::btree_maxreflen - ref_cpy.size(), 0);
guarantee(ref_cpy.size() == static_cast<size_t>(blob::btree_maxreflen));
actually_delete_rdb_value(buf_parent_t(txn), ref_cpy.data());
}
}
void rdb_erase_range_sindexes(const sindex_access_vector_t &sindexes,
const rdb_erase_range_report_t *erase_range,
signal_t *interruptor) {
auto_drainer_t drainer;
spawn_sindex_erase_ranges(&sindexes, erase_range->range_to_erase,
&drainer, auto_drainer_t::lock_t(&drainer),
false /* don't release the superblock */, interruptor);
}
class post_construct_traversal_helper_t : public btree_traversal_helper_t {
public:
post_construct_traversal_helper_t(
btree_store_t<rdb_protocol_t> *store,
const std::set<uuid_u> &sindexes_to_post_construct,
cond_t *interrupt_myself,
signal_t *interruptor
)
: store_(store),
sindexes_to_post_construct_(sindexes_to_post_construct),
interrupt_myself_(interrupt_myself), interruptor_(interruptor)
{ }
void process_a_leaf(buf_lock_t *leaf_node_buf,
const btree_key_t *, const btree_key_t *,
signal_t *, int *) THROWS_ONLY(interrupted_exc_t) {
write_token_pair_t token_pair;
store_->new_write_token_pair(&token_pair);
// KSI: FML
scoped_ptr_t<txn_t> wtxn;
btree_store_t<rdb_protocol_t>::sindex_access_vector_t sindexes;
try {
scoped_ptr_t<real_superblock_t> superblock;
// We want soft durability because having a partially constructed secondary index is
// okay -- we wipe it and rebuild it, if it has not been marked completely
// constructed.
store_->acquire_superblock_for_write(
repli_timestamp_t::distant_past,
2, // KSI: This is not the right value.
write_durability_t::SOFT,
&token_pair,
&wtxn,
&superblock,
interruptor_);
// RSI: We used to have this comment. We no longer do that (and we no
// longer want to do that). How is performance affected? We shouldn't
// have stuff blocking on the superblock (generally) anyway, right?
// While we need wtxn to be a write transaction (thus calling
// `acquire_superblock_for_write`), we only need a read lock
// on the superblock (which is why we pass in `rwi_read`).
// Usually in btree code, we are supposed to acquire the superblock
// in write mode if we are going to do writes further down the tree,
// in order to guarantee that no other read can bypass the write on
// the way down. However in this special case this is already
// guaranteed by the token_pair that all secondary index operations
// use, so we can safely acquire it with `rwi_read` instead.
// RSI: ^^ remove the above outdated comment left for reference for the
// previous RSI comment.
// Synchronization is guaranteed through the token_pair.
// Let's get the information we need from the superblock and then
// release it immediately.
block_id_t sindex_block_id = superblock->get_sindex_block_id();
buf_lock_t sindex_block
= store_->acquire_sindex_block_for_write(superblock->expose_buf(),
sindex_block_id);
superblock.reset();
store_->acquire_sindex_superblocks_for_write(
sindexes_to_post_construct_,
&sindex_block,
&sindexes);
if (sindexes.empty()) {
interrupt_myself_->pulse_if_not_already_pulsed();
return;
}
} catch (const interrupted_exc_t &e) {
return;
}
buf_read_t leaf_read(leaf_node_buf);
const leaf_node_t *leaf_node
= static_cast<const leaf_node_t *>(leaf_read.get_data_read());
for (auto it = leaf::begin(*leaf_node); it != leaf::end(*leaf_node); ++it) {
store_->btree->stats.pm_keys_read.record();
/* Grab relevant values from the leaf node. */
const btree_key_t *key = (*it).first;
const void *value = (*it).second;
guarantee(key);
store_key_t pk(key);
rdb_modification_report_t mod_report(pk);
const rdb_value_t *rdb_value = static_cast<const rdb_value_t *>(value);
const block_size_t block_size = leaf_node_buf->cache()->get_block_size();
mod_report.info.added
= std::make_pair(
get_data(rdb_value, buf_parent_t(leaf_node_buf)),
std::vector<char>(rdb_value->value_ref(),
rdb_value->value_ref() + rdb_value->inline_size(block_size)));
rdb_update_sindexes(sindexes, &mod_report, wtxn.get());
coro_t::yield();
}
}
void postprocess_internal_node(buf_lock_t *) { }
void filter_interesting_children(buf_parent_t,
ranged_block_ids_t *ids_source,
interesting_children_callback_t *cb) {
for (int i = 0, e = ids_source->num_block_ids(); i < e; ++i) {
cb->receive_interesting_child(i);
}
cb->no_more_interesting_children();
}
// RSI: Parallel traversal should release the superblock, right? That way we can
// get at the sindexes.
// RSI: Instead of wtxn we should just have one (write) transaction, pre-visit
// the sindex block, traverse the main subtree (snapshottedly) without releasing
// the superblock, instead of this two-transaction business. We could get
// everything done in one write transaction? But having big write transactions
// is bad for some reason (if it actually touches the superblock). Think about
// that, make sindexes better, and talk to other people about known sindex
// problems.
access_t btree_superblock_mode() { return access_t::read; }
access_t btree_node_mode() { return access_t::read; }
btree_store_t<rdb_protocol_t> *store_;
const std::set<uuid_u> &sindexes_to_post_construct_;
cond_t *interrupt_myself_;
signal_t *interruptor_;
};
void post_construct_secondary_indexes(
btree_store_t<rdb_protocol_t> *store,
const std::set<uuid_u> &sindexes_to_post_construct,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t) {
cond_t local_interruptor;
wait_any_t wait_any(&local_interruptor, interruptor);
post_construct_traversal_helper_t helper(store,
sindexes_to_post_construct, &local_interruptor, interruptor);
/* Notice the ordering of progress_tracker and insertion_sentries matters.
* insertion_sentries puts pointers in the progress tracker map. Once
* insertion_sentries is destructed nothing has a reference to
* progress_tracker so we know it's safe to destruct it. */
parallel_traversal_progress_t progress_tracker;
helper.progress = &progress_tracker;
std::vector<map_insertion_sentry_t<uuid_u, const parallel_traversal_progress_t *> >
insertion_sentries(sindexes_to_post_construct.size());
auto sentry = insertion_sentries.begin();
for (auto it = sindexes_to_post_construct.begin();
it != sindexes_to_post_construct.end(); ++it) {
store->add_progress_tracker(&*sentry, *it, &progress_tracker);
}
object_buffer_t<fifo_enforcer_sink_t::exit_read_t> read_token;
store->new_read_token(&read_token);
// Mind the destructor ordering.
// The superblock must be released before txn (`btree_parallel_traversal`
// usually already takes care of that).
// The txn must be destructed before the cache_account.
scoped_ptr_t<alt_cache_account_t> cache_account;
scoped_ptr_t<txn_t> txn;
scoped_ptr_t<real_superblock_t> superblock;
store->acquire_superblock_for_read(
&read_token,
&txn,
&superblock,
interruptor,
true /* USE_SNAPSHOT */);
// KSI: Is this high(?) priority why making an sindex slows stuff down a lot?
txn->cache()->create_cache_account(SINDEX_POST_CONSTRUCTION_CACHE_PRIORITY,
&cache_account);
txn->set_account(cache_account.get());
btree_parallel_traversal(superblock.get(),
store->btree.get(), &helper, &wait_any);
}
Made kv_location_delete detach the blob subtree in all cases, not just when mod_info_out is not null.
// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "rdb_protocol/btree.hpp"
#include <string>
#include <vector>
#include "btree/backfill.hpp"
#include "btree/concurrent_traversal.hpp"
#include "btree/erase_range.hpp"
#include "btree/get_distribution.hpp"
#include "btree/operations.hpp"
#include "btree/parallel_traversal.hpp"
#include "buffer_cache/alt/alt_serialize_onto_blob.hpp"
#include "containers/archive/boost_types.hpp"
#include "containers/archive/buffer_group_stream.hpp"
#include "containers/archive/vector_stream.hpp"
#include "containers/scoped.hpp"
#include "rdb_protocol/blob_wrapper.hpp"
#include "rdb_protocol/func.hpp"
#include "rdb_protocol/lazy_json.hpp"
#include "rdb_protocol/transform_visitors.hpp"
value_sizer_t<rdb_value_t>::value_sizer_t(block_size_t bs) : block_size_(bs) { }
const rdb_value_t *value_sizer_t<rdb_value_t>::as_rdb(const void *p) {
return reinterpret_cast<const rdb_value_t *>(p);
}
int value_sizer_t<rdb_value_t>::size(const void *value) const {
return as_rdb(value)->inline_size(block_size_);
}
bool value_sizer_t<rdb_value_t>::fits(const void *value, int length_available) const {
return btree_value_fits(block_size_, length_available, as_rdb(value));
}
int value_sizer_t<rdb_value_t>::max_possible_size() const {
return blob::btree_maxreflen;
}
block_magic_t value_sizer_t<rdb_value_t>::leaf_magic() {
block_magic_t magic = { { 'r', 'd', 'b', 'l' } };
return magic;
}
block_magic_t value_sizer_t<rdb_value_t>::btree_leaf_magic() const {
return leaf_magic();
}
block_size_t value_sizer_t<rdb_value_t>::block_size() const { return block_size_; }
bool btree_value_fits(block_size_t bs, int data_length, const rdb_value_t *value) {
return blob::ref_fits(bs, data_length, value->value_ref(),
blob::btree_maxreflen);
}
void rdb_get(const store_key_t &store_key, btree_slice_t *slice,
superblock_t *superblock, point_read_response_t *response,
profile::trace_t *trace) {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_read(superblock, store_key.btree_key(), &kv_location,
&slice->stats, trace);
if (!kv_location.value.has()) {
response->data.reset(new ql::datum_t(ql::datum_t::R_NULL));
} else {
response->data = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
}
}
void kv_location_delete(keyvalue_location_t<rdb_value_t> *kv_location,
const store_key_t &key,
repli_timestamp_t timestamp,
rdb_modification_info_t *mod_info_out) {
// Notice this also implies that buf is valid.
guarantee(kv_location->value.has());
// As noted above, we can be sure that buf is valid.
const block_size_t block_size = kv_location->buf.cache()->get_block_size();
// Detach the blob subtree.
{
blob_t blob(block_size, kv_location->value->value_ref(),
blob::btree_maxreflen);
blob.detach_subtree(&kv_location->buf);
}
if (mod_info_out != NULL) {
guarantee(mod_info_out->deleted.second.empty());
mod_info_out->deleted.second.assign(
kv_location->value->value_ref(),
kv_location->value->value_ref()
+ kv_location->value->inline_size(block_size));
}
kv_location->value.reset();
null_key_modification_callback_t<rdb_value_t> null_cb;
apply_keyvalue_change(kv_location, key.btree_key(), timestamp,
expired_t::NO, &null_cb);
}
void kv_location_set(keyvalue_location_t<rdb_value_t> *kv_location,
const store_key_t &key,
counted_t<const ql::datum_t> data,
repli_timestamp_t timestamp,
rdb_modification_info_t *mod_info_out) {
scoped_malloc_t<rdb_value_t> new_value(blob::btree_maxreflen);
memset(new_value.get(), 0, blob::btree_maxreflen);
const block_size_t block_size = kv_location->buf.cache()->get_block_size();
{
blob_t blob(block_size, new_value->value_ref(), blob::btree_maxreflen);
serialize_onto_blob(buf_parent_t(&kv_location->buf), &blob, data);
}
if (mod_info_out) {
guarantee(mod_info_out->added.second.empty());
mod_info_out->added.second.assign(new_value->value_ref(),
new_value->value_ref() + new_value->inline_size(block_size));
}
if (kv_location->value.has() && mod_info_out) {
guarantee(mod_info_out->deleted.second.empty());
{
// RSI: Wait -- do we call detach_subtree in all the right places? For
// example, why does our detaching a value depend on whether mod_info_out
// is NULL or not?
blob_t blob(block_size, kv_location->value->value_ref(),
blob::btree_maxreflen);
blob.detach_subtree(&kv_location->buf);
}
mod_info_out->deleted.second.assign(
kv_location->value->value_ref(),
kv_location->value->value_ref()
+ kv_location->value->inline_size(block_size));
}
// Actually update the leaf, if needed.
kv_location->value = std::move(new_value);
null_key_modification_callback_t<rdb_value_t> null_cb;
apply_keyvalue_change(kv_location, key.btree_key(), timestamp,
expired_t::NO, &null_cb);
}
void kv_location_set(keyvalue_location_t<rdb_value_t> *kv_location,
const store_key_t &key,
const std::vector<char> &value_ref,
repli_timestamp_t timestamp) {
scoped_malloc_t<rdb_value_t> new_value(
value_ref.data(), value_ref.data() + value_ref.size());
// Update the leaf, if needed.
kv_location->value = std::move(new_value);
null_key_modification_callback_t<rdb_value_t> null_cb;
apply_keyvalue_change(kv_location, key.btree_key(), timestamp,
expired_t::NO, &null_cb);
}
batched_replace_response_t rdb_replace_and_return_superblock(
const btree_loc_info_t &info,
const btree_point_replacer_t *replacer,
promise_t<superblock_t *> *superblock_promise,
rdb_modification_info_t *mod_info_out,
profile::trace_t *trace)
{
bool return_vals = replacer->should_return_vals();
const std::string &primary_key = *info.btree->primary_key;
const store_key_t &key = *info.key;
ql::datum_ptr_t resp(ql::datum_t::R_OBJECT);
try {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(info.superblock, info.key->btree_key(),
&kv_location,
&info.btree->slice->stats,
trace,
superblock_promise);
bool started_empty, ended_empty;
counted_t<const ql::datum_t> old_val;
if (!kv_location.value.has()) {
// If there's no entry with this key, pass NULL to the function.
started_empty = true;
old_val = make_counted<ql::datum_t>(ql::datum_t::R_NULL);
} else {
// Otherwise pass the entry with this key to the function.
started_empty = false;
old_val = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
guarantee(old_val->get(primary_key, ql::NOTHROW).has());
}
guarantee(old_val.has());
if (return_vals == RETURN_VALS) {
bool conflict = resp.add("old_val", old_val)
|| resp.add("new_val", old_val); // changed below
guarantee(!conflict);
}
counted_t<const ql::datum_t> new_val = replacer->replace(old_val);
if (return_vals == RETURN_VALS) {
bool conflict = resp.add("new_val", new_val, ql::CLOBBER);
guarantee(conflict); // We set it to `old_val` previously.
}
if (new_val->get_type() == ql::datum_t::R_NULL) {
ended_empty = true;
} else if (new_val->get_type() == ql::datum_t::R_OBJECT) {
ended_empty = false;
new_val->rcheck_valid_replace(
old_val, counted_t<const ql::datum_t>(), primary_key);
counted_t<const ql::datum_t> pk = new_val->get(primary_key, ql::NOTHROW);
rcheck_target(
new_val, ql::base_exc_t::GENERIC,
key.compare(store_key_t(pk->print_primary())) == 0,
(started_empty
? strprintf("Primary key `%s` cannot be changed (null -> %s)",
primary_key.c_str(), new_val->print().c_str())
: strprintf("Primary key `%s` cannot be changed (%s -> %s)",
primary_key.c_str(),
old_val->print().c_str(), new_val->print().c_str())));
} else {
rfail_typed_target(
new_val, "Inserted value must be an OBJECT (got %s):\n%s",
new_val->get_type_name().c_str(), new_val->print().c_str());
}
// We use `conflict` below to store whether or not there was a key
// conflict when constructing the stats object. It defaults to `true`
// so that we fail an assertion if we never update the stats object.
bool conflict = true;
// Figure out what operation we're doing (based on started_empty,
// ended_empty, and the result of the function call) and then do it.
if (started_empty) {
if (ended_empty) {
conflict = resp.add("skipped", make_counted<ql::datum_t>(1.0));
} else {
conflict = resp.add("inserted", make_counted<ql::datum_t>(1.0));
r_sanity_check(new_val->get(primary_key, ql::NOTHROW).has());
kv_location_set(&kv_location, *info.key, new_val, info.btree->timestamp,
mod_info_out);
guarantee(mod_info_out->deleted.second.empty());
guarantee(!mod_info_out->added.second.empty());
mod_info_out->added.first = new_val;
}
} else {
if (ended_empty) {
conflict = resp.add("deleted", make_counted<ql::datum_t>(1.0));
kv_location_delete(&kv_location, *info.key, info.btree->timestamp,
mod_info_out);
guarantee(!mod_info_out->deleted.second.empty());
guarantee(mod_info_out->added.second.empty());
mod_info_out->deleted.first = old_val;
} else {
r_sanity_check(
*old_val->get(primary_key) == *new_val->get(primary_key));
if (*old_val == *new_val) {
conflict = resp.add("unchanged",
make_counted<ql::datum_t>(1.0));
} else {
conflict = resp.add("replaced", make_counted<ql::datum_t>(1.0));
r_sanity_check(new_val->get(primary_key, ql::NOTHROW).has());
kv_location_set(&kv_location, *info.key, new_val,
info.btree->timestamp,
mod_info_out);
guarantee(!mod_info_out->deleted.second.empty());
guarantee(!mod_info_out->added.second.empty());
mod_info_out->added.first = new_val;
mod_info_out->deleted.first = old_val;
}
}
}
guarantee(!conflict); // message never added twice
} catch (const ql::base_exc_t &e) {
resp.add_error(e.what());
} catch (const interrupted_exc_t &e) {
std::string msg = strprintf("interrupted (%s:%d)", __FILE__, __LINE__);
resp.add_error(msg.c_str());
// We don't rethrow because we're in a coroutine. Theoretically the
// above message should never make it back to a user because the calling
// function will also be interrupted, but we document where it comes
// from to aid in future debugging if that invariant becomes violated.
}
return resp.to_counted();
}
class one_replace_t : public btree_point_replacer_t {
public:
one_replace_t(const btree_batched_replacer_t *_replacer, size_t _index)
: replacer(_replacer), index(_index) { }
counted_t<const ql::datum_t> replace(const counted_t<const ql::datum_t> &d) const {
return replacer->replace(d, index);
}
bool should_return_vals() const { return replacer->should_return_vals(); }
private:
const btree_batched_replacer_t *const replacer;
const size_t index;
};
void do_a_replace_from_batched_replace(
auto_drainer_t::lock_t,
fifo_enforcer_sink_t *batched_replaces_fifo_sink,
const fifo_enforcer_write_token_t &batched_replaces_fifo_token,
const btree_loc_info_t &info,
const one_replace_t one_replace,
promise_t<superblock_t *> *superblock_promise,
rdb_modification_report_cb_t *sindex_cb,
batched_replace_response_t *stats_out,
profile::trace_t *trace)
{
fifo_enforcer_sink_t::exit_write_t exiter(
batched_replaces_fifo_sink, batched_replaces_fifo_token);
rdb_modification_report_t mod_report(*info.key);
counted_t<const ql::datum_t> res = rdb_replace_and_return_superblock(
info, &one_replace, superblock_promise, &mod_report.info, trace);
*stats_out = (*stats_out)->merge(res, ql::stats_merge);
// RSI: What is this for? are we waiting to get in line to call on_mod_report? I guess so.
// JD: Looks like this is a do_a_replace_from_batched_replace specific thing.
exiter.wait();
sindex_cb->on_mod_report(mod_report);
}
batched_replace_response_t rdb_batched_replace(
const btree_info_t &info,
scoped_ptr_t<superblock_t> *superblock,
const std::vector<store_key_t> &keys,
const btree_batched_replacer_t *replacer,
rdb_modification_report_cb_t *sindex_cb,
profile::trace_t *trace) {
fifo_enforcer_source_t batched_replaces_fifo_source;
fifo_enforcer_sink_t batched_replaces_fifo_sink;
counted_t<const ql::datum_t> stats(new ql::datum_t(ql::datum_t::R_OBJECT));
// We have to drain write operations before destructing everything above us,
// because the coroutines being drained use them.
{
auto_drainer_t drainer;
// Note the destructor ordering: We release the superblock before draining
// on all the write operations.
scoped_ptr_t<superblock_t> current_superblock(superblock->release());
for (size_t i = 0; i < keys.size(); ++i) {
// Pass out the point_replace_response_t.
promise_t<superblock_t *> superblock_promise;
coro_t::spawn_sometime(
std::bind(
&do_a_replace_from_batched_replace,
auto_drainer_t::lock_t(&drainer),
&batched_replaces_fifo_sink,
batched_replaces_fifo_source.enter_write(),
btree_loc_info_t(&info, current_superblock.release(), &keys[i]),
one_replace_t(replacer, i),
&superblock_promise,
sindex_cb,
&stats,
trace));
current_superblock.init(superblock_promise.wait());
}
} // Make sure the drainer is destructed before the return statement.
return stats;
}
void rdb_set(const store_key_t &key,
counted_t<const ql::datum_t> data,
bool overwrite,
btree_slice_t *slice,
repli_timestamp_t timestamp,
superblock_t *superblock,
point_write_response_t *response_out,
rdb_modification_info_t *mod_info,
profile::trace_t *trace) {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(superblock, key.btree_key(), &kv_location,
&slice->stats, trace);
const bool had_value = kv_location.value.has();
/* update the modification report */
if (kv_location.value.has()) {
mod_info->deleted.first = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
}
mod_info->added.first = data;
if (overwrite || !had_value) {
kv_location_set(&kv_location, key, data, timestamp, mod_info);
guarantee(mod_info->deleted.second.empty() == !had_value &&
!mod_info->added.second.empty());
}
response_out->result =
(had_value ? point_write_result_t::DUPLICATE : point_write_result_t::STORED);
}
class agnostic_rdb_backfill_callback_t : public agnostic_backfill_callback_t {
public:
agnostic_rdb_backfill_callback_t(rdb_backfill_callback_t *cb,
const key_range_t &kr,
btree_slice_t *slice) :
cb_(cb), kr_(kr), slice_(slice) { }
void on_delete_range(const key_range_t &range, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
rassert(kr_.is_superset(range));
cb_->on_delete_range(range, interruptor);
}
void on_deletion(const btree_key_t *key, repli_timestamp_t recency, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
rassert(kr_.contains_key(key->contents, key->size));
cb_->on_deletion(key, recency, interruptor);
}
void on_pair(buf_parent_t leaf_node, repli_timestamp_t recency,
const btree_key_t *key, const void *val,
signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
rassert(kr_.contains_key(key->contents, key->size));
const rdb_value_t *value = static_cast<const rdb_value_t *>(val);
slice_->stats.pm_keys_read.record();
rdb_protocol_details::backfill_atom_t atom;
atom.key.assign(key->size, key->contents);
atom.value = get_data(value, leaf_node);
atom.recency = recency;
cb_->on_keyvalue(atom, interruptor);
}
void on_sindexes(const std::map<std::string, secondary_index_t> &sindexes, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t) {
cb_->on_sindexes(sindexes, interruptor);
}
rdb_backfill_callback_t *cb_;
key_range_t kr_;
btree_slice_t *slice_;
};
void rdb_backfill(btree_slice_t *slice, const key_range_t& key_range,
repli_timestamp_t since_when, rdb_backfill_callback_t *callback,
superblock_t *superblock,
buf_lock_t *sindex_block,
parallel_traversal_progress_t *p, signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t) {
agnostic_rdb_backfill_callback_t agnostic_cb(callback, key_range, slice);
value_sizer_t<rdb_value_t> sizer(slice->cache()->get_block_size());
do_agnostic_btree_backfill(&sizer, slice, key_range, since_when, &agnostic_cb,
superblock, sindex_block, p, interruptor);
}
void rdb_delete(const store_key_t &key, btree_slice_t *slice,
repli_timestamp_t timestamp,
superblock_t *superblock, point_delete_response_t *response,
rdb_modification_info_t *mod_info,
profile::trace_t *trace) {
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(superblock, key.btree_key(),
&kv_location, &slice->stats, trace);
bool exists = kv_location.value.has();
/* Update the modification report. */
if (exists) {
mod_info->deleted.first = get_data(kv_location.value.get(),
buf_parent_t(&kv_location.buf));
kv_location_delete(&kv_location, key, timestamp, mod_info);
}
guarantee(!mod_info->deleted.second.empty() && mod_info->added.second.empty());
response->result = (exists ? point_delete_result_t::DELETED : point_delete_result_t::MISSING);
}
// Remember that secondary indexes and the main btree both point to the same rdb
// value -- you don't want to double-delete that value!
void actually_delete_rdb_value(buf_parent_t parent, void *value) {
blob_t blob(parent.cache()->get_block_size(),
static_cast<rdb_value_t *>(value)->value_ref(),
blob::btree_maxreflen);
blob.clear(parent);
}
void rdb_value_deleter_t::delete_value(buf_parent_t parent, void *value) {
actually_delete_rdb_value(parent, value);
}
void rdb_value_non_deleter_t::delete_value(buf_parent_t, void *) {
//RSI should we be detaching blobs in here?
}
class sindex_key_range_tester_t : public key_tester_t {
public:
explicit sindex_key_range_tester_t(const key_range_t &key_range)
: key_range_(key_range) { }
bool key_should_be_erased(const btree_key_t *key) {
std::string pk = ql::datum_t::extract_primary(
key_to_unescaped_str(store_key_t(key)));
return key_range_.contains_key(store_key_t(pk));
}
private:
key_range_t key_range_;
};
typedef btree_store_t<rdb_protocol_t>::sindex_access_t sindex_access_t;
typedef btree_store_t<rdb_protocol_t>::sindex_access_vector_t sindex_access_vector_t;
void sindex_erase_range(const key_range_t &key_range,
const sindex_access_t *sindex_access, auto_drainer_t::lock_t,
signal_t *interruptor, bool release_superblock) THROWS_NOTHING {
value_sizer_t<rdb_value_t> rdb_sizer(sindex_access->btree->cache()->get_block_size());
value_sizer_t<void> *sizer = &rdb_sizer;
rdb_value_non_deleter_t deleter;
sindex_key_range_tester_t tester(key_range);
try {
btree_erase_range_generic(sizer, sindex_access->btree, &tester,
&deleter, NULL, NULL,
sindex_access->super_block.get(), interruptor,
release_superblock);
} catch (const interrupted_exc_t &) {
// We were interrupted. That's fine nothing to be done about it.
}
}
/* Spawns a coro to carry out the erase range for each sindex. */
void spawn_sindex_erase_ranges(
const sindex_access_vector_t *sindex_access,
const key_range_t &key_range,
auto_drainer_t *drainer,
auto_drainer_t::lock_t,
bool release_superblock,
signal_t *interruptor) {
for (auto it = sindex_access->begin(); it != sindex_access->end(); ++it) {
coro_t::spawn_sometime(std::bind(
&sindex_erase_range, key_range, &*it,
auto_drainer_t::lock_t(drainer), interruptor,
release_superblock));
}
}
void rdb_erase_range(btree_slice_t *slice, key_tester_t *tester,
const key_range_t &key_range,
buf_lock_t *sindex_block,
superblock_t *superblock,
btree_store_t<rdb_protocol_t> *store,
signal_t *interruptor) {
/* This is guaranteed because the way the keys are calculated below would
* lead to a single key being deleted even if the range was empty. */
guarantee(!key_range.is_empty());
/* Dispatch the erase range to the sindexes. */
sindex_access_vector_t sindex_superblocks;
{
store->acquire_post_constructed_sindex_superblocks_for_write(
sindex_block, &sindex_superblocks);
mutex_t::acq_t acq;
store->lock_sindex_queue(sindex_block, &acq);
write_message_t wm;
wm << rdb_sindex_change_t(rdb_erase_range_report_t(key_range));
store->sindex_queue_push(wm, &acq);
}
{
auto_drainer_t sindex_erase_drainer;
spawn_sindex_erase_ranges(&sindex_superblocks, key_range,
&sindex_erase_drainer, auto_drainer_t::lock_t(&sindex_erase_drainer),
true /* release the superblock */, interruptor);
/* Notice, when we exit this block we destruct the sindex_erase_drainer
* which means we'll wait until all of the sindex_erase_ranges finish
* executing. This is an important detail because the sindexes only
* store references to their data. They don't actually store a full
* copy of the data themselves. The call to btree_erase_range_generic
* is the one that will actually erase the data and if we were to make
* that call before the indexes were finished erasing we would have
* reference to data which didn't actually exist and another process
* could read that data. */
/* TL;DR it's very important that we make sure all of the coros spawned
* by spawn_sindex_erase_ranges complete before we proceed past this
* point. */
}
/* Twiddle some keys to get the in the form we want. Notice these are keys
* which will be made exclusive and inclusive as their names suggest
* below. At the point of construction they aren't. */
store_key_t left_key_exclusive(key_range.left);
store_key_t right_key_inclusive(key_range.right.key);
bool left_key_supplied = left_key_exclusive.decrement();
bool right_key_supplied = !key_range.right.unbounded;
if (right_key_supplied) {
right_key_inclusive.decrement();
}
/* Now left_key_exclusive and right_key_inclusive accurately reflect their
* names. */
/* We need these structures to perform the erase range. */
value_sizer_t<rdb_value_t> rdb_sizer(slice->cache()->get_block_size());
value_sizer_t<void> *sizer = &rdb_sizer;
rdb_value_deleter_t deleter;
btree_erase_range_generic(sizer, slice, tester, &deleter,
left_key_supplied ? left_key_exclusive.btree_key() : NULL,
right_key_supplied ? right_key_inclusive.btree_key() : NULL,
superblock, interruptor);
// RSI: this comment about auto_drainer_t is false.
// auto_drainer_t is destructed here so this waits for other coros to finish.
}
// This is actually a kind of misleading name. This function estimates the size of a datum,
// not a whole rget, though it is used for that purpose (by summing up these responses).
size_t estimate_rget_response_size(const counted_t<const ql::datum_t> &datum) {
return serialized_size(datum);
}
class rdb_rget_depth_first_traversal_callback_t
: public concurrent_traversal_callback_t {
public:
/* This constructor does a traversal on the primary btree, it's not to be
* used with sindexes. The constructor below is for use with sindexes. */
rdb_rget_depth_first_traversal_callback_t(
ql::env_t *_ql_env,
const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &_transform,
boost::optional<rdb_protocol_details::terminal_t> _terminal,
const key_range_t &range,
sorting_t _sorting,
rget_read_response_t *_response,
btree_slice_t *_slice)
: bad_init(false),
response(_response),
ql_env(_ql_env),
batcher(batchspec.to_batcher()),
transform(_transform),
terminal(_terminal),
sorting(_sorting),
slice(_slice)
{
init(range);
}
/* This constructor is used if you're doing a secondary index get, it takes
* an extra key_range_t (_primary_key_range) which is used to filter out
* unwanted results. The reason you can get unwanted results is is
* oversharding. When we overshard multiple logical shards are stored in
* the same physical btree_store_t, this is transparent with all other
* operations but their sindex values get mixed together and you wind up
* with multiple copies of each. This constructor will filter out the
* duplicates. This was issue #606. */
rdb_rget_depth_first_traversal_callback_t(
ql::env_t *_ql_env,
const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &_transform,
boost::optional<rdb_protocol_details::terminal_t> _terminal,
const key_range_t &range,
const key_range_t &_primary_key_range,
sorting_t _sorting,
ql::map_wire_func_t _sindex_function,
sindex_multi_bool_t _sindex_multi,
datum_range_t _sindex_range,
rget_read_response_t *_response,
btree_slice_t *_slice)
: bad_init(false),
response(_response),
ql_env(_ql_env),
batcher(batchspec.to_batcher()),
transform(_transform),
terminal(_terminal),
sorting(_sorting),
primary_key_range(_primary_key_range),
sindex_range(_sindex_range),
sindex_multi(_sindex_multi),
slice(_slice)
{
sindex_function = _sindex_function.compile_wire_func();
init(range);
}
void init(const key_range_t &range) {
try {
if (!reversed(sorting)) {
response->last_considered_key = range.left;
} else {
if (!range.right.unbounded) {
response->last_considered_key = range.right.key;
} else {
response->last_considered_key = store_key_t::max();
}
}
if (terminal) {
query_language::terminal_initialize(&*terminal, &response->result);
}
disabler.init(new profile::disabler_t(ql_env->trace));
sampler.init(new profile::sampler_t("Range traversal doc evaluation.", ql_env->trace));
} catch (const ql::exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any more requests. */
response->result = e2;
bad_init = true;
} catch (const ql::datum_exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any more requests. */
terminal_exception(e2, *terminal, &response->result);
bad_init = true;
}
}
virtual bool handle_pair(scoped_key_value_t &&keyvalue,
concurrent_traversal_fifo_enforcer_signal_t waiter)
THROWS_ONLY(interrupted_exc_t) {
sampler->new_sample();
store_key_t store_key(keyvalue.key());
if (bad_init) {
return false;
}
if (primary_key_range) {
std::string pk = ql::datum_t::extract_primary(
key_to_unescaped_str(store_key));
if (!primary_key_range->contains_key(store_key_t(pk))) {
return true;
}
}
try {
lazy_json_t first_value(static_cast<const rdb_value_t *>(keyvalue.value()),
keyvalue.expose_buf());
// When doing "count" queries, we don't want to actually load the json
// value. Here we detect up-front whether we will need to load the value.
// If nothing uses the value, we load it here. Otherwise we never load
// it. The main problem with this code is that we still need a time to
// exclusively process each row, in between the call to
// waiter.wait_interruptible() and the end of this function. If we fixed
// the design that makes us need to _process_ each row one at a time, we
// wouldn't have to guess up front whether the lazy_json_t actually needs
// to be loaded, and the code would be safer (and algorithmically more
// parallelized).
if (sindex_function.has() || !transform.empty() || !terminal
|| query_language::terminal_uses_value(*terminal)) {
// Force the value to be loaded.
first_value.get();
// Increment reads here since the btree doesn't know if we actually do a read
slice->stats.pm_keys_read.record();
} else {
// We _must_ load the value before calling keyvalue.reset(), and
// before calling waiter.wait_interruptible(). So we call
// first_value.reset() to make any later call to .get() fail.
first_value.reset();
}
rassert(!first_value.references_parent());
keyvalue.reset();
waiter.wait_interruptible();
if ((response->last_considered_key < store_key && !reversed(sorting)) ||
(response->last_considered_key > store_key && reversed(sorting))) {
response->last_considered_key = store_key;
}
std::vector<lazy_json_t> data;
data.push_back(first_value);
counted_t<const ql::datum_t> sindex_value;
if (sindex_function) {
sindex_value =
sindex_function->call(ql_env, first_value.get())->as_datum();
guarantee(sindex_range);
guarantee(sindex_multi);
if (sindex_multi == sindex_multi_bool_t::MULTI &&
sindex_value->get_type() == ql::datum_t::R_ARRAY) {
boost::optional<uint64_t> tag =
ql::datum_t::extract_tag(key_to_unescaped_str(store_key));
guarantee(tag);
guarantee(sindex_value->size() > *tag);
sindex_value = sindex_value->get(*tag);
}
if (!sindex_range->contains(sindex_value)) {
return true;
}
}
// Apply transforms to the data
{
rdb_protocol_details::transform_t::iterator it;
for (it = transform.begin(); it != transform.end(); ++it) {
try {
std::vector<counted_t<const ql::datum_t> > tmp;
for (auto jt = data.begin(); jt != data.end(); ++jt) {
query_language::transform_apply(
ql_env, jt->get(), &*it, &tmp);
}
data.clear();
for (auto jt = tmp.begin(); jt != tmp.end(); ++jt) {
data.push_back(lazy_json_t(*jt));
}
} catch (const ql::datum_exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any
more requests. */
transform_exception(e2, *it, &response->result);
return false;
}
}
}
if (!terminal) {
typedef rget_read_response_t::stream_t stream_t;
stream_t *stream = boost::get<stream_t>(&response->result);
guarantee(stream);
for (auto it = data.begin(); it != data.end(); ++it) {
counted_t<const ql::datum_t> datum = it->get();
if (sorting != sorting_t::UNORDERED && sindex_value) {
stream->push_back(rdb_protocol_details::rget_item_t(
store_key, sindex_value, datum));
} else {
stream->push_back(rdb_protocol_details::rget_item_t(
store_key, datum));
}
batcher.note_el(datum);
}
return !batcher.should_send_batch();
} else {
try {
for (auto jt = data.begin(); jt != data.end(); ++jt) {
query_language::terminal_apply(
ql_env, *jt, &*terminal, &response->result);
}
return true;
} catch (const ql::datum_exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any
more requests. */
terminal_exception(e2, *terminal, &response->result);
return false;
}
}
} catch (const ql::exc_t &e2) {
/* Evaluation threw so we're not going to be accepting any more requests. */
response->result = e2;
return false;
}
}
virtual profile::trace_t *get_trace() THROWS_NOTHING {
return ql_env->trace.get_or_null();
}
bool bad_init;
rget_read_response_t *response;
ql::env_t *ql_env;
ql::batcher_t batcher;
rdb_protocol_details::transform_t transform;
boost::optional<rdb_protocol_details::terminal_t> terminal;
sorting_t sorting;
/* Only present if we're doing a sindex read.*/
boost::optional<key_range_t> primary_key_range;
boost::optional<datum_range_t> sindex_range;
counted_t<ql::func_t> sindex_function;
boost::optional<sindex_multi_bool_t> sindex_multi;
scoped_ptr_t<profile::disabler_t> disabler;
scoped_ptr_t<profile::sampler_t> sampler;
btree_slice_t *slice;
};
class result_finalizer_visitor_t : public boost::static_visitor<void> {
public:
void operator()(const rget_read_response_t::stream_t &) const { }
void operator()(const ql::exc_t &) const { }
void operator()(const ql::datum_exc_t &) const { }
void operator()(const std::vector<ql::wire_datum_map_t> &) const { }
void operator()(const rget_read_response_t::empty_t &) const { }
void operator()(const counted_t<const ql::datum_t> &) const { }
void operator()(ql::wire_datum_map_t &dm) const { // NOLINT(runtime/references)
dm.finalize();
}
};
void rdb_rget_slice(btree_slice_t *slice, const key_range_t &range,
superblock_t *superblock,
ql::env_t *ql_env, const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &transform,
const boost::optional<rdb_protocol_details::terminal_t> &terminal,
sorting_t sorting,
rget_read_response_t *response) {
profile::starter_t starter("Do range scan on primary index.", ql_env->trace);
rdb_rget_depth_first_traversal_callback_t callback(
ql_env, batchspec, transform, terminal, range, sorting, response, slice);
btree_concurrent_traversal(slice, superblock, range, &callback,
(!reversed(sorting) ? FORWARD : BACKWARD));
response->truncated = callback.batcher.should_send_batch();
boost::apply_visitor(result_finalizer_visitor_t(), response->result);
}
void rdb_rget_secondary_slice(
btree_slice_t *slice,
const datum_range_t &sindex_range,
const rdb_protocol_t::region_t &sindex_region,
superblock_t *superblock,
ql::env_t *ql_env,
const ql::batchspec_t &batchspec,
const rdb_protocol_details::transform_t &transform,
const boost::optional<rdb_protocol_details::terminal_t> &terminal,
const key_range_t &pk_range,
sorting_t sorting,
const ql::map_wire_func_t &sindex_func,
sindex_multi_bool_t sindex_multi,
rget_read_response_t *response) {
profile::starter_t starter("Do range scan on secondary index.", ql_env->trace);
rdb_rget_depth_first_traversal_callback_t callback(
ql_env, batchspec, transform, terminal, sindex_region.inner, pk_range,
sorting, sindex_func, sindex_multi, sindex_range, response, slice);
btree_concurrent_traversal(
slice, superblock, sindex_region.inner, &callback,
(!reversed(sorting) ? FORWARD : BACKWARD));
response->truncated = callback.batcher.should_send_batch();
boost::apply_visitor(result_finalizer_visitor_t(), response->result);
}
void rdb_distribution_get(btree_slice_t *slice, int max_depth,
const store_key_t &left_key,
superblock_t *superblock,
distribution_read_response_t *response) {
int64_t key_count_out;
std::vector<store_key_t> key_splits;
get_btree_key_distribution(slice, superblock, max_depth,
&key_count_out, &key_splits);
int64_t keys_per_bucket;
if (key_splits.size() == 0) {
keys_per_bucket = key_count_out;
} else {
keys_per_bucket = std::max<int64_t>(key_count_out / key_splits.size(), 1);
}
response->key_counts[left_key] = keys_per_bucket;
for (std::vector<store_key_t>::iterator it = key_splits.begin();
it != key_splits.end();
++it) {
response->key_counts[*it] = keys_per_bucket;
}
}
static const int8_t HAS_VALUE = 0;
static const int8_t HAS_NO_VALUE = 1;
void rdb_modification_info_t::rdb_serialize(write_message_t &msg) const { // NOLINT(runtime/references)
if (!deleted.first.get()) {
guarantee(deleted.second.empty());
msg << HAS_NO_VALUE;
} else {
msg << HAS_VALUE;
msg << deleted;
}
if (!added.first.get()) {
guarantee(added.second.empty());
msg << HAS_NO_VALUE;
} else {
msg << HAS_VALUE;
msg << added;
}
}
archive_result_t rdb_modification_info_t::rdb_deserialize(read_stream_t *s) {
archive_result_t res;
int8_t has_value;
res = deserialize(s, &has_value);
if (res) { return res; }
if (has_value == HAS_VALUE) {
res = deserialize(s, &deleted);
if (res) { return res; }
}
res = deserialize(s, &has_value);
if (res) { return res; }
if (has_value == HAS_VALUE) {
res = deserialize(s, &added);
if (res) { return res; }
}
return ARCHIVE_SUCCESS;
}
RDB_IMPL_ME_SERIALIZABLE_2(rdb_modification_report_t, primary_key, info);
RDB_IMPL_ME_SERIALIZABLE_1(rdb_erase_range_report_t, range_to_erase);
rdb_modification_report_cb_t::rdb_modification_report_cb_t(
btree_store_t<rdb_protocol_t> *store,
buf_lock_t *sindex_block,
auto_drainer_t::lock_t lock)
: lock_(lock), store_(store),
sindex_block_(sindex_block) {
store_->acquire_post_constructed_sindex_superblocks_for_write(
sindex_block_, &sindexes_);
}
rdb_modification_report_cb_t::~rdb_modification_report_cb_t() { }
void rdb_modification_report_cb_t::on_mod_report(
const rdb_modification_report_t &mod_report) {
mutex_t::acq_t acq;
store_->lock_sindex_queue(sindex_block_, &acq);
write_message_t wm;
wm << rdb_sindex_change_t(mod_report);
store_->sindex_queue_push(wm, &acq);
rdb_update_sindexes(sindexes_, &mod_report, sindex_block_->txn());
}
typedef btree_store_t<rdb_protocol_t>::sindex_access_vector_t sindex_access_vector_t;
void compute_keys(const store_key_t &primary_key, counted_t<const ql::datum_t> doc,
ql::map_wire_func_t *mapping, sindex_multi_bool_t multi, ql::env_t *env,
std::vector<store_key_t> *keys_out) {
guarantee(keys_out->empty());
counted_t<const ql::datum_t> index =
mapping->compile_wire_func()->call(env, doc)->as_datum();
if (multi == sindex_multi_bool_t::MULTI && index->get_type() == ql::datum_t::R_ARRAY) {
for (uint64_t i = 0; i < index->size(); ++i) {
keys_out->push_back(
store_key_t(index->get(i, ql::THROW)->print_secondary(primary_key, i)));
}
} else {
keys_out->push_back(store_key_t(index->print_secondary(primary_key)));
}
}
/* Used below by rdb_update_sindexes. */
void rdb_update_single_sindex(
const btree_store_t<rdb_protocol_t>::sindex_access_t *sindex,
const rdb_modification_report_t *modification,
auto_drainer_t::lock_t) {
// Note if you get this error it's likely that you've passed in a default
// constructed mod_report. Don't do that. Mod reports should always be passed
// to a function as an output parameter before they're passed to this
// function.
guarantee(modification->primary_key.size() != 0);
ql::map_wire_func_t mapping;
sindex_multi_bool_t multi = sindex_multi_bool_t::MULTI;
vector_read_stream_t read_stream(&sindex->sindex.opaque_definition);
archive_result_t success = deserialize(&read_stream, &mapping);
guarantee_deserialization(success, "sindex deserialize");
success = deserialize(&read_stream, &multi);
guarantee_deserialization(success, "sindex deserialize");
// TODO we just use a NULL environment here. People should not be able
// to do anything that requires an environment like gets from other
// tables etc. but we don't have a nice way to disallow those things so
// for now we pass null and it will segfault if an illegal sindex
// mapping is passed.
cond_t non_interruptor;
ql::env_t env(&non_interruptor);
superblock_t *super_block = sindex->super_block.get();
if (modification->info.deleted.first) {
guarantee(!modification->info.deleted.second.empty());
try {
counted_t<const ql::datum_t> deleted = modification->info.deleted.first;
std::vector<store_key_t> keys;
compute_keys(modification->primary_key, deleted, &mapping, multi, &env, &keys);
for (auto it = keys.begin(); it != keys.end(); ++it) {
promise_t<superblock_t *> return_superblock_local;
{
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(super_block,
it->btree_key(),
&kv_location,
&sindex->btree->stats,
env.trace.get_or_null(),
&return_superblock_local);
if (kv_location.value.has()) {
kv_location_delete(&kv_location, *it,
repli_timestamp_t::distant_past, NULL);
}
// The keyvalue location gets destroyed here.
}
super_block = return_superblock_local.wait();
}
} catch (const ql::base_exc_t &) {
// Do nothing (it wasn't actually in the index).
}
}
if (modification->info.added.first) {
try {
counted_t<const ql::datum_t> added = modification->info.added.first;
std::vector<store_key_t> keys;
compute_keys(modification->primary_key, added, &mapping, multi, &env, &keys);
for (auto it = keys.begin(); it != keys.end(); ++it) {
promise_t<superblock_t *> return_superblock_local;
{
keyvalue_location_t<rdb_value_t> kv_location;
find_keyvalue_location_for_write(super_block,
it->btree_key(),
&kv_location,
&sindex->btree->stats,
env.trace.get_or_null(),
&return_superblock_local);
kv_location_set(&kv_location, *it,
modification->info.added.second,
repli_timestamp_t::distant_past);
// The keyvalue location gets destroyed here.
}
super_block = return_superblock_local.wait();
}
} catch (const ql::base_exc_t &) {
// Do nothing (we just drop the row from the index).
}
}
}
void rdb_update_sindexes(const sindex_access_vector_t &sindexes,
const rdb_modification_report_t *modification,
txn_t *txn) {
{
auto_drainer_t drainer;
for (sindex_access_vector_t::const_iterator it = sindexes.begin();
it != sindexes.end();
++it) {
coro_t::spawn_sometime(std::bind(
&rdb_update_single_sindex, &*it,
modification, auto_drainer_t::lock_t(&drainer)));
}
}
/* All of the sindex have been updated now it's time to actually clear the
* deleted blob if it exists. */
if (modification->info.deleted.first) {
// Deleting the value unfortunately updates the ref in-place as it operates, so
// we need to make a copy of the blob reference that is extended to the
// appropriate width.
std::vector<char> ref_cpy(modification->info.deleted.second);
ref_cpy.insert(ref_cpy.end(), blob::btree_maxreflen - ref_cpy.size(), 0);
guarantee(ref_cpy.size() == static_cast<size_t>(blob::btree_maxreflen));
actually_delete_rdb_value(buf_parent_t(txn), ref_cpy.data());
}
}
void rdb_erase_range_sindexes(const sindex_access_vector_t &sindexes,
const rdb_erase_range_report_t *erase_range,
signal_t *interruptor) {
auto_drainer_t drainer;
spawn_sindex_erase_ranges(&sindexes, erase_range->range_to_erase,
&drainer, auto_drainer_t::lock_t(&drainer),
false /* don't release the superblock */, interruptor);
}
class post_construct_traversal_helper_t : public btree_traversal_helper_t {
public:
post_construct_traversal_helper_t(
btree_store_t<rdb_protocol_t> *store,
const std::set<uuid_u> &sindexes_to_post_construct,
cond_t *interrupt_myself,
signal_t *interruptor
)
: store_(store),
sindexes_to_post_construct_(sindexes_to_post_construct),
interrupt_myself_(interrupt_myself), interruptor_(interruptor)
{ }
void process_a_leaf(buf_lock_t *leaf_node_buf,
const btree_key_t *, const btree_key_t *,
signal_t *, int *) THROWS_ONLY(interrupted_exc_t) {
write_token_pair_t token_pair;
store_->new_write_token_pair(&token_pair);
// KSI: FML
scoped_ptr_t<txn_t> wtxn;
btree_store_t<rdb_protocol_t>::sindex_access_vector_t sindexes;
try {
scoped_ptr_t<real_superblock_t> superblock;
// We want soft durability because having a partially constructed secondary index is
// okay -- we wipe it and rebuild it, if it has not been marked completely
// constructed.
store_->acquire_superblock_for_write(
repli_timestamp_t::distant_past,
2, // KSI: This is not the right value.
write_durability_t::SOFT,
&token_pair,
&wtxn,
&superblock,
interruptor_);
// RSI: We used to have this comment. We no longer do that (and we no
// longer want to do that). How is performance affected? We shouldn't
// have stuff blocking on the superblock (generally) anyway, right?
// While we need wtxn to be a write transaction (thus calling
// `acquire_superblock_for_write`), we only need a read lock
// on the superblock (which is why we pass in `rwi_read`).
// Usually in btree code, we are supposed to acquire the superblock
// in write mode if we are going to do writes further down the tree,
// in order to guarantee that no other read can bypass the write on
// the way down. However in this special case this is already
// guaranteed by the token_pair that all secondary index operations
// use, so we can safely acquire it with `rwi_read` instead.
// RSI: ^^ remove the above outdated comment left for reference for the
// previous RSI comment.
// Synchronization is guaranteed through the token_pair.
// Let's get the information we need from the superblock and then
// release it immediately.
block_id_t sindex_block_id = superblock->get_sindex_block_id();
buf_lock_t sindex_block
= store_->acquire_sindex_block_for_write(superblock->expose_buf(),
sindex_block_id);
superblock.reset();
store_->acquire_sindex_superblocks_for_write(
sindexes_to_post_construct_,
&sindex_block,
&sindexes);
if (sindexes.empty()) {
interrupt_myself_->pulse_if_not_already_pulsed();
return;
}
} catch (const interrupted_exc_t &e) {
return;
}
buf_read_t leaf_read(leaf_node_buf);
const leaf_node_t *leaf_node
= static_cast<const leaf_node_t *>(leaf_read.get_data_read());
for (auto it = leaf::begin(*leaf_node); it != leaf::end(*leaf_node); ++it) {
store_->btree->stats.pm_keys_read.record();
/* Grab relevant values from the leaf node. */
const btree_key_t *key = (*it).first;
const void *value = (*it).second;
guarantee(key);
store_key_t pk(key);
rdb_modification_report_t mod_report(pk);
const rdb_value_t *rdb_value = static_cast<const rdb_value_t *>(value);
const block_size_t block_size = leaf_node_buf->cache()->get_block_size();
mod_report.info.added
= std::make_pair(
get_data(rdb_value, buf_parent_t(leaf_node_buf)),
std::vector<char>(rdb_value->value_ref(),
rdb_value->value_ref() + rdb_value->inline_size(block_size)));
rdb_update_sindexes(sindexes, &mod_report, wtxn.get());
coro_t::yield();
}
}
void postprocess_internal_node(buf_lock_t *) { }
void filter_interesting_children(buf_parent_t,
ranged_block_ids_t *ids_source,
interesting_children_callback_t *cb) {
for (int i = 0, e = ids_source->num_block_ids(); i < e; ++i) {
cb->receive_interesting_child(i);
}
cb->no_more_interesting_children();
}
// RSI: Parallel traversal should release the superblock, right? That way we can
// get at the sindexes.
// RSI: Instead of wtxn we should just have one (write) transaction, pre-visit
// the sindex block, traverse the main subtree (snapshottedly) without releasing
// the superblock, instead of this two-transaction business. We could get
// everything done in one write transaction? But having big write transactions
// is bad for some reason (if it actually touches the superblock). Think about
// that, make sindexes better, and talk to other people about known sindex
// problems.
access_t btree_superblock_mode() { return access_t::read; }
access_t btree_node_mode() { return access_t::read; }
btree_store_t<rdb_protocol_t> *store_;
const std::set<uuid_u> &sindexes_to_post_construct_;
cond_t *interrupt_myself_;
signal_t *interruptor_;
};
void post_construct_secondary_indexes(
btree_store_t<rdb_protocol_t> *store,
const std::set<uuid_u> &sindexes_to_post_construct,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t) {
cond_t local_interruptor;
wait_any_t wait_any(&local_interruptor, interruptor);
post_construct_traversal_helper_t helper(store,
sindexes_to_post_construct, &local_interruptor, interruptor);
/* Notice the ordering of progress_tracker and insertion_sentries matters.
* insertion_sentries puts pointers in the progress tracker map. Once
* insertion_sentries is destructed nothing has a reference to
* progress_tracker so we know it's safe to destruct it. */
parallel_traversal_progress_t progress_tracker;
helper.progress = &progress_tracker;
std::vector<map_insertion_sentry_t<uuid_u, const parallel_traversal_progress_t *> >
insertion_sentries(sindexes_to_post_construct.size());
auto sentry = insertion_sentries.begin();
for (auto it = sindexes_to_post_construct.begin();
it != sindexes_to_post_construct.end(); ++it) {
store->add_progress_tracker(&*sentry, *it, &progress_tracker);
}
object_buffer_t<fifo_enforcer_sink_t::exit_read_t> read_token;
store->new_read_token(&read_token);
// Mind the destructor ordering.
// The superblock must be released before txn (`btree_parallel_traversal`
// usually already takes care of that).
// The txn must be destructed before the cache_account.
scoped_ptr_t<alt_cache_account_t> cache_account;
scoped_ptr_t<txn_t> txn;
scoped_ptr_t<real_superblock_t> superblock;
store->acquire_superblock_for_read(
&read_token,
&txn,
&superblock,
interruptor,
true /* USE_SNAPSHOT */);
// KSI: Is this high(?) priority why making an sindex slows stuff down a lot?
txn->cache()->create_cache_account(SINDEX_POST_CONSTRUCTION_CACHE_PRIORITY,
&cache_account);
txn->set_account(cache_account.get());
btree_parallel_traversal(superblock.get(),
store->btree.get(), &helper, &wait_any);
}
|
#include "objectives/noisy/fitness-noise/FitnessNoiseSource.hpp"
#include <vector>
FitnessNoiseSource::FitnessNoiseSource() {}
Fitness FitnessNoiseSource::noisify(
Fitness cleanFitness,
std::function<double(double)> noisemaker
) {
std::vector<double> components = cleanFitness.getComponents();
for (unsigned int i = 0; i < components.size(); i++)
components[i] = noisemaker(components[i]);
return Fitness(components);
}
[FitnessNoiseSource]: Updated to use FitnessSource
#include "objectives/noisy/fitness-noise/FitnessNoiseSource.hpp"
#include <vector>
FitnessNoiseSource::FitnessNoiseSource() {}
Fitness FitnessNoiseSource::noisify(
Fitness cleanFitness,
std::function<double(double)> noisemaker
) {
std::vector<FitnessPair> components = cleanFitness.getComponents();
for (unsigned int i = 0; i < components.size(); i++)
components[i] = std::make_tuple(
noisemaker(std::get<0>(components[i])),
std::get<1>(components[i])
);
return Fitness(components);
}
|
// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "../include/embree2/rtcore.h"
#include "../include/embree2/rtcore_ray.h"
#include "../kernels/common/default.h"
#include "../kernels/algorithms/parallel_for.h"
#include <vector>
#if defined(RTCORE_RAY_PACKETS) && !defined(__MIC__)
# define HAS_INTERSECT4 1
#else
# define HAS_INTERSECT4 0
#endif
#if defined(RTCORE_RAY_PACKETS) && (defined(__TARGET_AVX__) || defined(__TARGET_AVX2__))
# define HAS_INTERSECT8 1
#else
# define HAS_INTERSECT8 0
#endif
#if defined(RTCORE_RAY_PACKETS) && (defined(__MIC__) || defined(__TARGET_AVX512KNL__))
# define HAS_INTERSECT16 1
#else
# define HAS_INTERSECT16 0
#endif
namespace embree
{
bool hasISA(const int isa)
{
int cpu_features = getCPUFeatures();
return (cpu_features & isa) == isa;
}
/* error reporting function */
void error_handler(const RTCError code, const char* str = nullptr)
{
if (code == RTC_NO_ERROR)
return;
printf("Embree: ");
switch (code) {
case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break;
case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break;
case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break;
case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break;
case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break;
case RTC_CANCELLED : printf("RTC_CANCELLED"); break;
default : printf("invalid error code"); break;
}
if (str) {
printf(" (");
while (*str) putchar(*str++);
printf(")\n");
}
exit(1);
}
RTCAlgorithmFlags aflags = (RTCAlgorithmFlags) (RTC_INTERSECT1 | RTC_INTERSECT4 | RTC_INTERSECT8 | RTC_INTERSECT16);
/* configuration */
static std::string g_rtcore = "";
static size_t g_plot_min = 0;
static size_t g_plot_max = 0;
static size_t g_plot_step= 0;
static std::string g_plot_test = "";
static bool executed_benchmarks = false;
/* vertex and triangle layout */
struct Vertex { float x,y,z,a; };
struct Triangle { int v0, v1, v2; };
#define AssertNoError() \
if (rtcGetError() != RTC_NO_ERROR) return false;
#define AssertAnyError() \
if (rtcGetError() == RTC_NO_ERROR) return false;
#define AssertError(code) \
if (rtcGetError() != code) return false;
std::vector<thread_t> g_threads;
MutexSys g_mutex;
BarrierSys g_barrier;
LinearBarrierActive g_barrier_active;
size_t g_num_mutex_locks = 100000;
size_t g_num_threads = 0;
ssize_t g_num_threads_init = -1;
atomic_t g_atomic_cntr = 0;
class Benchmark
{
public:
const std::string name;
const std::string unit;
Benchmark (const std::string& name, const std::string& unit)
: name(name), unit(unit) {}
virtual double run(size_t numThreads) = 0;
void print(size_t numThreads, size_t N)
{
double pmin = inf, pmax = -float(inf), pavg = 0.0f;
for (size_t j=0; j<N; j++) {
double p = run(numThreads);
pmin = min(pmin,p);
pmax = max(pmax,p);
pavg = pavg + p/double(N);
}
printf("%40s ... [%f / %f / %f] %s\n",name.c_str(),pmin,pavg,pmax,unit.c_str());
fflush(stdout);
}
};
class benchmark_mutex_sys : public Benchmark
{
public:
benchmark_mutex_sys ()
: Benchmark("mutex_sys","ms") {}
static void benchmark_mutex_sys_thread(void* ptr)
{
g_barrier.wait();
while (true)
{
if (atomic_add(&g_atomic_cntr,-1) < 0) break;
g_mutex.lock();
g_mutex.unlock();
}
}
double run (size_t numThreads)
{
g_barrier.init(numThreads);
g_atomic_cntr = g_num_mutex_locks;
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_mutex_sys_thread,nullptr,1000000,i));
//setAffinity(0);
double t0 = getSeconds();
benchmark_mutex_sys_thread(nullptr);
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
//printf("%40s ... %f ms (%f k/s)\n","mutex_sys",1000.0f*(t1-t0)/double(g_num_mutex_locks),1E-3*g_num_mutex_locks/(t1-t0));
//fflush(stdout);
return 1000.0f*(t1-t0)/double(g_num_mutex_locks);
}
};
class benchmark_barrier_sys : public Benchmark
{
public:
enum { N = 100 };
benchmark_barrier_sys ()
: Benchmark("barrier_sys","ms") {}
static void benchmark_barrier_sys_thread(void* ptr)
{
g_barrier.wait();
for (size_t i=0; i<N; i++)
g_barrier.wait();
}
double run (size_t numThreads)
{
g_barrier.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_barrier_sys_thread,(void*)i,1000000,i));
//setAffinity(0);
g_barrier.wait();
double t0 = getSeconds();
for (size_t i=0; i<N; i++) g_barrier.wait();
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
//printf("%40s ... %f ms (%f k/s)\n","barrier_sys",1000.0f*(t1-t0)/double(N),1E-3*N/(t1-t0));
//fflush(stdout);
return 1000.0f*(t1-t0)/double(N);
}
};
class benchmark_barrier_active : public Benchmark
{
enum { N = 1000 };
public:
benchmark_barrier_active ()
: Benchmark("barrier_active","ns") {}
static void benchmark_barrier_active_thread(void* ptr)
{
size_t threadIndex = (size_t) ptr;
size_t threadCount = g_num_threads;
g_barrier_active.wait(threadIndex);
for (size_t i=0; i<N; i++)
g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_barrier_active_thread,(void*)i,1000000,i));
setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
for (size_t i=0; i<N; i++)
g_barrier_active.wait(0);
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++)
join(g_threads[i]);
g_threads.clear();
//printf("%40s ... %f ms (%f k/s)\n","barrier_active",1000.0f*(t1-t0)/double(N),1E-3*N/(t1-t0));
//fflush(stdout);
return 1E9*(t1-t0)/double(N);
}
};
class benchmark_atomic_inc : public Benchmark
{
public:
enum { N = 10000000 };
benchmark_atomic_inc ()
: Benchmark("atomic_inc","ns") {}
static void benchmark_atomic_inc_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
__memory_barrier();
while (atomic_add(&g_atomic_cntr,-1) > 0);
__memory_barrier();
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
g_atomic_cntr = N;
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_atomic_inc_thread,(void*)i,1000000,i));
setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
//size_t c0 = rdtsc();
benchmark_atomic_inc_thread(nullptr);
//size_t c1 = rdtsc();
double t1 = getSeconds();
g_barrier_active.wait(0);
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
//PRINT(double(c1-c0)/N);
//printf("%40s ... %f ms (%f k/s)\n","mutex_sys",1000.0f*(t1-t0)/double(g_num_mutex_locks),1E-3*g_num_mutex_locks/(t1-t0));
//fflush(stdout);
return 1E9*(t1-t0)/double(N);
}
};
class benchmark_pagefaults : public Benchmark
{
public:
enum { N = 1024*1024*1024 };
static char* ptr;
benchmark_pagefaults ()
: Benchmark("pagefaults","GB/s") {}
static void benchmark_pagefaults_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
size_t start = (threadIndex+0)*N/threadCount;
size_t end = (threadIndex+1)*N/threadCount;
for (size_t i=start; i<end; i+=64)
ptr[i] = 0;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
#if !defined(__WIN32__)
ptr = (char*) os_reserve(N);
#else
ptr = (char*)os_malloc(N);
#endif
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_pagefaults_thread,(void*)i,1000000,i));
//setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
benchmark_pagefaults_thread(0);
double t1 = getSeconds();
g_barrier_active.wait(0);
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
os_free(ptr,N);
return 1E-9*double(N)/(t1-t0);
}
};
char* benchmark_pagefaults::ptr = nullptr;
#if defined(__UNIX__)
#include <sys/mman.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#endif
class benchmark_osmalloc_with_page_commit : public Benchmark
{
public:
enum { N = 1024*1024*1024 };
static char* ptr;
benchmark_osmalloc_with_page_commit ()
: Benchmark("osmalloc_with_page_commit","GB/s") {}
static void benchmark_osmalloc_with_page_commit_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
size_t start = (threadIndex+0)*N/threadCount;
size_t end = (threadIndex+1)*N/threadCount;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
int flags = 0;
#if defined(__UNIX__) && !defined(__APPLE__)
flags |= MAP_POPULATE;
#endif
size_t startN = 1024*1024*16;
double t = 0.0f;
size_t iterations = 0;
for (size_t i=startN;i<=N;i*=2,iterations++)
{
double t0 = getSeconds();
char *ptr = (char*) os_malloc(i,flags);
double t1 = getSeconds();
os_free(ptr,i);
t += 1E-9*double(i)/(t1-t0);
}
return t / (double)iterations;
}
};
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
class benchmark_bandwidth : public Benchmark
{
public:
enum { N = 300000000 };
static char* ptr;
benchmark_bandwidth ()
: Benchmark("bandwidth","GB/s") {}
static void benchmark_bandwidth_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
size_t start = (threadIndex+0)*N/threadCount;
size_t end = (threadIndex+1)*N/threadCount;
char p = 0;
for (size_t i=start; i<end; i+=64)
p += ptr[i];
volatile char out = p;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
ptr = (char*) os_malloc(N);
for (size_t i=0; i<N; i+=4096) ptr[i] = 0;
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_bandwidth_thread,(void*)i,1000000,i));
//setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
benchmark_bandwidth_thread(0);
double t1 = getSeconds();
g_barrier_active.wait(0);
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
os_free(ptr,N);
return 1E-9*double(N)/(t1-t0);
}
};
char* benchmark_bandwidth::ptr = nullptr;
RTCRay makeRay(Vec3f org, Vec3f dir)
{
RTCRay ray;
ray.org[0] = org.x; ray.org[1] = org.y; ray.org[2] = org.z;
ray.dir[0] = dir.x; ray.dir[1] = dir.y; ray.dir[2] = dir.z;
ray.tnear = 0.0f; ray.tfar = inf;
ray.time = 0; ray.mask = -1;
ray.geomID = ray.primID = ray.instID = -1;
return ray;
}
RTCRay makeRay(Vec3f org, Vec3f dir, float tnear, float tfar)
{
RTCRay ray;
ray.org[0] = org.x; ray.org[1] = org.y; ray.org[2] = org.z;
ray.dir[0] = dir.x; ray.dir[1] = dir.y; ray.dir[2] = dir.z;
ray.tnear = tnear; ray.tfar = tfar;
ray.time = 0; ray.mask = -1;
ray.geomID = ray.primID = ray.instID = -1;
return ray;
}
void setRay(RTCRay4& ray_o, int i, const RTCRay& ray_i)
{
ray_o.orgx[i] = ray_i.org[0];
ray_o.orgy[i] = ray_i.org[1];
ray_o.orgz[i] = ray_i.org[2];
ray_o.dirx[i] = ray_i.dir[0];
ray_o.diry[i] = ray_i.dir[1];
ray_o.dirz[i] = ray_i.dir[2];
ray_o.tnear[i] = ray_i.tnear;
ray_o.tfar[i] = ray_i.tfar;
ray_o.time[i] = ray_i.time;
ray_o.mask[i] = ray_i.mask;
ray_o.geomID[i] = ray_i.geomID;
ray_o.primID[i] = ray_i.primID;
ray_o.instID[i] = ray_i.instID;
}
void setRay(RTCRay8& ray_o, int i, const RTCRay& ray_i)
{
ray_o.orgx[i] = ray_i.org[0];
ray_o.orgy[i] = ray_i.org[1];
ray_o.orgz[i] = ray_i.org[2];
ray_o.dirx[i] = ray_i.dir[0];
ray_o.diry[i] = ray_i.dir[1];
ray_o.dirz[i] = ray_i.dir[2];
ray_o.tnear[i] = ray_i.tnear;
ray_o.tfar[i] = ray_i.tfar;
ray_o.time[i] = ray_i.time;
ray_o.mask[i] = ray_i.mask;
ray_o.geomID[i] = ray_i.geomID;
ray_o.primID[i] = ray_i.primID;
ray_o.instID[i] = ray_i.instID;
}
void setRay(RTCRay16& ray_o, int i, const RTCRay& ray_i)
{
ray_o.orgx[i] = ray_i.org[0];
ray_o.orgy[i] = ray_i.org[1];
ray_o.orgz[i] = ray_i.org[2];
ray_o.dirx[i] = ray_i.dir[0];
ray_o.diry[i] = ray_i.dir[1];
ray_o.dirz[i] = ray_i.dir[2];
ray_o.tnear[i] = ray_i.tnear;
ray_o.tfar[i] = ray_i.tfar;
ray_o.time[i] = ray_i.time;
ray_o.mask[i] = ray_i.mask;
ray_o.geomID[i] = ray_i.geomID;
ray_o.primID[i] = ray_i.primID;
ray_o.instID[i] = ray_i.instID;
}
struct Mesh {
std::vector<Vertex> vertices;
std::vector<Triangle> triangles;
};
void createSphereMesh (const Vec3f pos, const float r, size_t numPhi, Mesh& mesh_o)
{
/* create a triangulated sphere */
size_t numTheta = 2*numPhi;
mesh_o.vertices.resize(numTheta*(numPhi+1));
mesh_o.triangles.resize(2*numTheta*(numPhi-1));
/* map triangle and vertex buffer */
Vertex* vertices = (Vertex* ) &mesh_o.vertices[0];
Triangle* triangles = (Triangle*) &mesh_o.triangles[0];
/* create sphere geometry */
int tri = 0;
const float rcpNumTheta = 1.0f/float(numTheta);
const float rcpNumPhi = 1.0f/float(numPhi);
for (size_t phi=0; phi<=numPhi; phi++)
{
for (size_t theta=0; theta<numTheta; theta++)
{
const float phif = phi*float(pi)*rcpNumPhi;
const float thetaf = theta*2.0f*float(pi)*rcpNumTheta;
Vertex& v = vertices[phi*numTheta+theta];
v.x = pos.x + r*sin(phif)*sin(thetaf);
v.y = pos.y + r*cos(phif);
v.z = pos.z + r*sin(phif)*cos(thetaf);
}
if (phi == 0) continue;
for (size_t theta=1; theta<=numTheta; theta++)
{
int p00 = (phi-1)*numTheta+theta-1;
int p01 = (phi-1)*numTheta+theta%numTheta;
int p10 = phi*numTheta+theta-1;
int p11 = phi*numTheta+theta%numTheta;
if (phi > 1) {
triangles[tri].v0 = p10;
triangles[tri].v1 = p00;
triangles[tri].v2 = p01;
tri++;
}
if (phi < numPhi) {
triangles[tri].v0 = p11;
triangles[tri].v1 = p10;
triangles[tri].v2 = p01;
tri++;
}
}
}
}
unsigned addSphere (RTCScene scene, RTCGeometryFlags flag, const Vec3f pos, const float r, size_t numPhi)
{
Mesh mesh; createSphereMesh (pos, r, numPhi, mesh);
unsigned geom = rtcNewTriangleMesh (scene, flag, mesh.triangles.size(), mesh.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
return geom;
}
struct LineSegments {
avector<Vec3fa> vertices;
avector<int> lines;
};
Vec3fa uniformSampleSphere(const float& u, const float& v)
{
const float phi = float(two_pi) * u;
const float cosTheta = 1.0f - 2.0f * v, sinTheta = 2.0f * sqrt(v * (1.0f - v));
return Vec3fa(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);
}
inline unsigned int rngInt(unsigned int& state)
{
const unsigned int m = 1664525;
const unsigned int n = 1013904223;
state = state * m + n;
return state;
}
inline float rngFloat(unsigned int& state)
{
rngInt(state);
return (float)(int)(state >> 1) * 4.656612873077392578125e-10f;
}
void createHairball(const Vec3fa& pos, const float r, size_t numLines, LineSegments& hairset_o)
{
const float thickness = 0.001f*r;
unsigned int state = 1;
for (size_t t=0; t<numLines/3; t++)
{
Vec3fa dp = uniformSampleSphere(rngFloat(state), rngFloat(state));
Vec3fa l0 = pos + r*(dp + 0.00f*dp); l0.w = thickness;
Vec3fa l1 = pos + r*(dp + 0.25f*dp); l1.w = thickness;
Vec3fa l2 = pos + r*(dp + 0.50f*dp); l2.w = thickness;
Vec3fa l3 = pos + r*(dp + 0.75f*dp); l3.w = thickness;
const unsigned int v_index = hairset_o.vertices.size();
hairset_o.vertices.push_back(l0);
hairset_o.vertices.push_back(l1);
hairset_o.vertices.push_back(l2);
hairset_o.vertices.push_back(l3);
hairset_o.lines.push_back(v_index);
hairset_o.lines.push_back(v_index+1);
hairset_o.lines.push_back(v_index+2);
}
}
class create_geometry : public Benchmark
{
public:
RTCSceneFlags sflags; RTCGeometryFlags gflags; size_t numPhi; size_t numMeshes;
create_geometry (const std::string& name, RTCSceneFlags sflags, RTCGeometryFlags gflags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), sflags(sflags), gflags(gflags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh; createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
const size_t sizeVertexData = mesh.vertices.size()*sizeof(Vertex);
Vertex** vertices = new Vertex*[numMeshes];
for (size_t i=0; i<numMeshes; i++)
{
vertices[i] = (Vertex*)os_malloc(sizeVertexData);
assert(vertices[i]);
for (size_t j=0;j<mesh.vertices.size();j++)
{
Vertex &v = vertices[i][j];
v.x = mesh.vertices[j].x * (float)i;
v.y = mesh.vertices[j].y * (float)i;
v.z = mesh.vertices[j].z * (float)i;
v.a = 0.0f;
}
}
double t0 = getSeconds();
RTCScene scene = rtcDeviceNewScene(device,sflags,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewTriangleMesh (scene, gflags, mesh.triangles.size(), mesh.vertices.size());
#if 1
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,&vertices[i][0] ,0,sizeof(Vertex));
rtcSetBuffer(scene,geom,RTC_INDEX_BUFFER ,&mesh.triangles[0],0,sizeof(Triangle));
#else
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<mesh.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
#endif
}
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
for (size_t i=0; i<numMeshes; i++)
os_free(vertices[i],sizeVertexData);
delete[] vertices;
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)/(t1-t0);
}
};
class create_geometry_line : public Benchmark
{
public:
RTCSceneFlags sflags; RTCGeometryFlags gflags; size_t numLines; size_t numMeshes;
create_geometry_line (const std::string& name, RTCSceneFlags sflags, RTCGeometryFlags gflags, size_t numLines, size_t numMeshes)
: Benchmark(name,"Mlines/s"), sflags(sflags), gflags(gflags), numLines(numLines), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
LineSegments hairset; createHairball (Vec3f(0,0,0), 1, numLines, hairset);
const size_t sizeVertexData = hairset.vertices.size()*sizeof(Vec3fa);
Vec3fa** vertices = new Vec3fa*[numMeshes];
for (size_t i=0; i<numMeshes; i++)
{
vertices[i] = (Vec3fa*)os_malloc(sizeVertexData);
assert(vertices[i]);
for (size_t j=0;j<hairset.vertices.size();j++)
{
Vec3fa &v = vertices[i][j];
v.x = hairset.vertices[j].x * (float)i;
v.y = hairset.vertices[j].y * (float)i;
v.z = hairset.vertices[j].z * (float)i;
v.a = hairset.vertices[j].a;
}
}
double t0 = getSeconds();
RTCScene scene = rtcDeviceNewScene(device,sflags,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewLineSegments (scene, gflags, hairset.lines.size(), hairset.vertices.size());
#if 1
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,&vertices[i][0],0,sizeof(Vec3fa));
rtcSetBuffer(scene,geom,RTC_INDEX_BUFFER ,&hairset.lines[0],0,sizeof(int));
#else
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &hairset.vertices[0], hairset.vertices.size()*sizeof(Vec3fa));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &hairset.lines[0], hairset.lines.size()*sizeof(int));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<hairset.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
#endif
}
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
for (size_t i=0; i<numMeshes; i++)
os_free(vertices[i],sizeVertexData);
delete[] vertices;
size_t numLines = hairset.lines.size() * numMeshes;
return 1E-6*double(numLines)/(t1-t0);
}
};
class update_geometry : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numPhi; size_t numMeshes;
update_geometry(const std::string& name, RTCGeometryFlags flags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), flags(flags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh; createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewTriangleMesh (scene, flags, mesh.triangles.size(), mesh.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<mesh.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
}
rtcCommit (scene);
double t0 = getSeconds();
for (size_t i=0; i<numMeshes; i++) rtcUpdate(scene,i);
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
//return 1000.0f*(t1-t0);
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)/(t1-t0);
}
};
class update_geometry_line : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numLines; size_t numMeshes;
update_geometry_line(const std::string& name, RTCGeometryFlags flags, size_t numLines, size_t numMeshes)
: Benchmark(name,"Mlines/s"), flags(flags), numLines(numLines), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
LineSegments hairset; createHairball (Vec3f(0,0,0), 1, numLines, hairset);
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewLineSegments (scene, flags, hairset.lines.size(), hairset.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &hairset.vertices[0], hairset.vertices.size()*sizeof(Vec3fa));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &hairset.lines[0], hairset.lines.size()*sizeof(int));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<hairset.vertices.size(); i++) {
hairset.vertices[i].x += 1.0f;
hairset.vertices[i].y += 1.0f;
hairset.vertices[i].z += 1.0f;
}
}
rtcCommit (scene);
double t0 = getSeconds();
for (size_t i=0; i<numMeshes; i++) rtcUpdate(scene,i);
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
//return 1000.0f*(t1-t0);
size_t numLines = hairset.lines.size() * numMeshes;
return 1E-6*double(numLines)/(t1-t0);
}
};
class update_scenes : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numPhi; size_t numMeshes;
update_scenes(const std::string& name, RTCGeometryFlags flags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), flags(flags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh; createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
std::vector<RTCScene> scenes;
for (size_t i=0; i<numMeshes; i++)
{
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
unsigned geom = rtcNewTriangleMesh (scene, flags, mesh.triangles.size(), mesh.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<mesh.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
scenes.push_back(scene);
rtcCommit (scene);
}
double t0 = getSeconds();
#if defined(__MIC__)
for (size_t i=0; i<scenes.size(); i++) {
rtcUpdate(scenes[i],0);
rtcCommit (scenes[i]);
}
#else
parallel_for( scenes.size(), [&](size_t i) {
rtcUpdate(scenes[i],0);
rtcCommit (scenes[i]);
});
#endif
double t1 = getSeconds();
for (size_t i=0; i<scenes.size(); i++)
rtcDeleteScene(scenes[i]);
rtcDeleteDevice(device);
//return 1000.0f*(t1-t0);
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)/(t1-t0);
}
};
class update_keyframe_scenes : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numPhi; size_t numMeshes;
update_keyframe_scenes(const std::string& name, RTCGeometryFlags flags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), flags(flags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh;
createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
std::vector<RTCScene> scenes;
const size_t sizeVertexData = mesh.vertices.size()*sizeof(Vertex);
Vertex *key_frame_vertices[2];
key_frame_vertices[0] = (Vertex*)os_malloc(sizeVertexData);
key_frame_vertices[1] = (Vertex*)os_malloc(sizeVertexData);
memcpy(key_frame_vertices[0],&mesh.vertices[0],sizeVertexData);
memcpy(key_frame_vertices[1],&mesh.vertices[0],sizeVertexData);
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
unsigned geom = rtcNewTriangleMesh (scene, flags, mesh.triangles.size(), mesh.vertices.size());
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,key_frame_vertices[1],0,sizeof(Vec3fa));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
rtcCommit (scene);
static const size_t anim_runs = 4;
//static const size_t anim_runs = 4000000;
double t0 = getSeconds();
for (size_t i=0;i<anim_runs;i++)
{
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,key_frame_vertices[i%2],0,sizeof(Vec3fa));
rtcUpdate(scene,0);
rtcCommit(scene);
}
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
os_free(key_frame_vertices[0],sizeVertexData);
os_free(key_frame_vertices[1],sizeVertexData);
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)*anim_runs/((t1-t0));;
}
};
template<bool intersect>
class benchmark_rtcore_intersect1_throughput : public Benchmark
{
public:
enum { N = 1024*128 };
static RTCScene scene;
benchmark_rtcore_intersect1_throughput ()
: Benchmark(intersect ? "incoherent_intersect1_throughput" : "incoherent_occluded1_throughput","MRays/s (all HW threads)") {}
virtual void trace(Vec3f* numbers)
{
}
static double benchmark_rtcore_intersect1_throughput_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
srand48(threadIndex*334124);
Vec3f* numbers = new Vec3f[N];
#if 1
for (size_t i=0; i<N; i++) {
float x = 2.0f*drand48()-1.0f;
float y = 2.0f*drand48()-1.0f;
float z = 2.0f*drand48()-1.0f;
numbers[i] = Vec3f(x,y,z);
}
#else
#define NUM 512
float rx[NUM];
float ry[NUM];
float rz[NUM];
for (size_t i=0; i<NUM; i++) {
rx[i] = drand48();
ry[i] = drand48();
rz[i] = drand48();
}
for (size_t i=0; i<N; i++) {
float x = 2.0f*rx[i%NUM]-1.0f;
float y = 2.0f*ry[i%NUM]-1.0f;
float z = 2.0f*rz[i%NUM]-1.0f;
numbers[i] = Vec3f(x,y,z);
}
#endif
g_barrier_active.wait(threadIndex);
double t0 = getSeconds();
for (size_t i=0; i<N; i++) {
RTCRay ray = makeRay(zero,numbers[i]);
if (intersect)
rtcIntersect(scene,ray);
else
rtcOccluded(scene,ray);
}
g_barrier_active.wait(threadIndex);
double t1 = getSeconds();
delete [] numbers;
return t1-t0;
}
double run (size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
int numPhi = 501;
//int numPhi = 61;
//int numPhi = 1601;
RTCSceneFlags flags = RTC_SCENE_STATIC;
scene = rtcDeviceNewScene(device,flags,aflags);
addSphere (scene, RTC_GEOMETRY_STATIC, zero, 1, numPhi);
rtcCommit (scene);
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread((thread_func)benchmark_rtcore_intersect1_throughput_thread,(void*)i,1000000,i));
setAffinity(0);
//g_barrier_active.wait(0);
//double t0 = getSeconds();
double delta = benchmark_rtcore_intersect1_throughput_thread(0);
//g_barrier_active.wait(0);
//double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
return 1E-6*double(N)/(delta)*double(numThreads);
}
};
template<> RTCScene benchmark_rtcore_intersect1_throughput<true>::scene = nullptr;
template<> RTCScene benchmark_rtcore_intersect1_throughput<false>::scene = nullptr;
#if HAS_INTERSECT16
template<bool intersect>
class benchmark_rtcore_intersect16_throughput : public Benchmark
{
public:
enum { N = 1024*128 };
static RTCScene scene;
benchmark_rtcore_intersect16_throughput ()
: Benchmark(intersect ? "incoherent_intersect16_throughput" : "incoherent_occluded16_throughput","MRays/s (all HW threads)") {}
static double benchmark_rtcore_intersect16_throughput_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
srand48(threadIndex*334124);
Vec3f* numbers = new Vec3f[N];
#if 0
assert(N % 16 == 0);
for (size_t i=0; i<N; i++) {
size_t j = i >> 4;
float tx = (j & 1) ? 1.0f : -1.0f;
float ty = (j & 2) ? 1.0f : -1.0f;
float tz = (j & 4) ? 1.0f : -1.0f;
float x = drand48()*tx;
float y = drand48()*ty;
float z = drand48()*tz;
numbers[i] = Vec3f(x,y,z);
}
#else
for (size_t i=0; i<N; i++) {
float x = 2.0f*drand48()-1.0f;
float y = 2.0f*drand48()-1.0f;
float z = 2.0f*drand48()-1.0f;
numbers[i] = Vec3f(x,y,z);
}
#endif
__aligned(16) int valid16[16] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 };
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
double t0 = getSeconds();
//while(1)
for (size_t i=0; i<N; i+=16) {
RTCRay16 ray16;
for (size_t j=0;j<16;j++)
setRay(ray16,j,makeRay(zero,numbers[i+j]));
if (intersect)
rtcIntersect16(valid16,scene,ray16);
else
rtcOccluded16(valid16,scene,ray16);
}
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
double t1 = getSeconds();
delete [] numbers;
return t1-t0;
}
double run (size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
int numPhi = 501;
RTCSceneFlags flags = RTC_SCENE_STATIC;
scene = rtcDeviceNewScene(device,flags,aflags);
addSphere (scene, RTC_GEOMETRY_STATIC, zero, 1, numPhi);
rtcCommit (scene);
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread((thread_func)benchmark_rtcore_intersect16_throughput_thread,(void*)i,1000000,i));
setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
double delta = benchmark_rtcore_intersect16_throughput_thread(0);
g_barrier_active.wait(0);
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
return 1E-6*double(N)/(delta)*double(numThreads);
}
};
template<> RTCScene benchmark_rtcore_intersect16_throughput<true>::scene = nullptr;
template<> RTCScene benchmark_rtcore_intersect16_throughput<false>::scene = nullptr;
#endif
void rtcore_coherent_intersect1(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y++) {
for (size_t x=0; x<width; x++) {
RTCRay ray = makeRay(zero,Vec3f(float(x)*rcpWidth,1,float(y)*rcpHeight));
rtcIntersect(scene,ray);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect1",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#if HAS_INTERSECT4
void rtcore_coherent_intersect4(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y+=2) {
for (size_t x=0; x<width; x+=2) {
RTCRay4 ray4;
for (size_t dy=0; dy<2; dy++) {
for (size_t dx=0; dx<2; dx++) {
setRay(ray4,2*dy+dx,makeRay(zero,Vec3f(float(x+dx)*rcpWidth,1,float(y+dy)*rcpHeight)));
}
}
__aligned(16) int valid4[4] = { -1,-1,-1,-1 };
rtcIntersect4(valid4,scene,ray4);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect4",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT8
void rtcore_coherent_intersect8(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y+=4) {
for (size_t x=0; x<width; x+=2) {
RTCRay8 ray8;
for (size_t dy=0; dy<4; dy++) {
for (size_t dx=0; dx<2; dx++) {
setRay(ray8,2*dy+dx,makeRay(zero,Vec3f(float(x+dx)*rcpWidth,1,float(y+dy)*rcpHeight)));
}
}
__aligned(32) int valid8[8] = { -1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect8(valid8,scene,ray8);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect8",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT16
void rtcore_coherent_intersect16(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y+=4) {
for (size_t x=0; x<width; x+=4) {
RTCRay16 ray16;
for (size_t dy=0; dy<4; dy++) {
for (size_t dx=0; dx<4; dx++) {
setRay(ray16,4*dy+dx,makeRay(zero,Vec3f(float(x+dx)*rcpWidth,1,float(y+dy)*rcpHeight)));
}
}
__aligned(64) int valid16[16] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect16(valid16,scene,ray16);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect16",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#endif
void rtcore_incoherent_intersect1(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i++) {
RTCRay ray = makeRay(zero,numbers[i]);
rtcIntersect(scene,ray);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect1",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#if HAS_INTERSECT4
void rtcore_incoherent_intersect4(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i+=4) {
RTCRay4 ray4;
for (size_t j=0; j<4; j++) {
setRay(ray4,j,makeRay(zero,numbers[i+j]));
}
__aligned(16) int valid4[4] = { -1,-1,-1,-1 };
rtcIntersect4(valid4,scene,ray4);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect4",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT8
void rtcore_incoherent_intersect8(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i+=8) {
RTCRay8 ray8;
for (size_t j=0; j<8; j++) {
setRay(ray8,j,makeRay(zero,numbers[i+j]));
}
__aligned(32) int valid8[8] = { -1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect8(valid8,scene,ray8);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect8",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT16
void rtcore_incoherent_intersect16(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i+=16) {
RTCRay16 ray16;
for (size_t j=0; j<16; j++) {
setRay(ray16,j,makeRay(zero,numbers[i+j]));
}
__aligned(64) int valid16[16] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect16(valid16,scene,ray16);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect16",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#endif
void rtcore_intersect_benchmark(RTCSceneFlags flags, size_t numPhi)
{
RTCDevice device = rtcNewDevice(g_rtcore.c_str());
error_handler(rtcDeviceGetError(device));
RTCScene scene = rtcDeviceNewScene(device,flags,aflags);
addSphere (scene, RTC_GEOMETRY_STATIC, zero, 1, numPhi);
rtcCommit (scene);
rtcore_coherent_intersect1(scene);
#if HAS_INTERSECT4
rtcore_coherent_intersect4(scene);
#endif
#if HAS_INTERSECT8
if (hasISA(AVX)) {
rtcore_coherent_intersect8(scene);
}
#endif
#if HAS_INTERSECT16
if (hasISA(AVX512KNL) || hasISA(KNC)) {
rtcore_coherent_intersect16(scene);
}
#endif
size_t N = 1024*1024;
Vec3f* numbers = new Vec3f[N];
for (size_t i=0; i<N; i++) {
float x = 2.0f*drand48()-1.0f;
float y = 2.0f*drand48()-1.0f;
float z = 2.0f*drand48()-1.0f;
numbers[i] = Vec3f(x,y,z);
}
rtcore_incoherent_intersect1(scene,numbers,N);
#if HAS_INTERSECT4
rtcore_incoherent_intersect4(scene,numbers,N);
#endif
#if HAS_INTERSECT8
if (hasISA(AVX)) {
rtcore_incoherent_intersect8(scene,numbers,N);
}
#endif
#if HAS_INTERSECT16
if (hasISA(AVX512KNL) || hasISA(KNC)) {
rtcore_incoherent_intersect16(scene,numbers,N);
}
#endif
delete[] numbers;
rtcDeleteScene(scene);
rtcDeleteDevice(device);
}
std::vector<Benchmark*> benchmarks;
void create_benchmarks()
{
#if 1
benchmarks.push_back(new benchmark_rtcore_intersect1_throughput<true>());
benchmarks.push_back(new benchmark_rtcore_intersect1_throughput<false>());
#if HAS_INTERSECT16
if (hasISA(AVX512KNL) || hasISA(KNC)) {
benchmarks.push_back(new benchmark_rtcore_intersect16_throughput<true>());
//benchmarks.push_back(new benchmark_rtcore_intersect16_throughput<false>());
}
#endif
benchmarks.push_back(new benchmark_mutex_sys());
benchmarks.push_back(new benchmark_barrier_sys());
benchmarks.push_back(new benchmark_barrier_active());
benchmarks.push_back(new benchmark_atomic_inc());
#if defined(__X86_64__)
benchmarks.push_back(new benchmark_osmalloc_with_page_commit());
benchmarks.push_back(new benchmark_pagefaults());
benchmarks.push_back(new benchmark_bandwidth());
#endif
benchmarks.push_back(new create_geometry ("create_static_geometry_120", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,6,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_1k" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,17,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_10k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,51,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_100k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,159,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_1000k_1", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,501,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_100k_10", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,159,10));
benchmarks.push_back(new create_geometry ("create_static_geometry_10k_100", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,51,100));
benchmarks.push_back(new create_geometry ("create_static_geometry_1k_1000" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new create_geometry ("create_static_geometry_120_10000",RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,6,8334));
#endif
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_120", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,6,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_1k" , RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,17,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_10k", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,51,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_100k", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,159,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_1000k_1", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,501,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_100k_10", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,159,10));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_10k_100", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,51,100));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_1k_1000" , RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_120_10000",RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,6,8334));
#endif
#endif
benchmarks.push_back(new update_geometry ("refit_geometry_120", RTC_GEOMETRY_DEFORMABLE,6,1));
benchmarks.push_back(new update_geometry ("refit_geometry_1k" , RTC_GEOMETRY_DEFORMABLE,17,1));
benchmarks.push_back(new update_geometry ("refit_geometry_10k", RTC_GEOMETRY_DEFORMABLE,51,1));
benchmarks.push_back(new update_geometry ("refit_geometry_100k", RTC_GEOMETRY_DEFORMABLE,159,1));
benchmarks.push_back(new update_geometry ("refit_geometry_1000k_1", RTC_GEOMETRY_DEFORMABLE,501,1));
benchmarks.push_back(new update_geometry ("refit_geometry_100k_10", RTC_GEOMETRY_DEFORMABLE,159,10));
benchmarks.push_back(new update_geometry ("refit_geometry_10k_100", RTC_GEOMETRY_DEFORMABLE,51,100));
benchmarks.push_back(new update_geometry ("refit_geometry_1k_1000" , RTC_GEOMETRY_DEFORMABLE,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_geometry ("refit_geometry_120_10000",RTC_GEOMETRY_DEFORMABLE,6,8334));
#endif
#if 1
benchmarks.push_back(new update_geometry ("update_geometry_120", RTC_GEOMETRY_DYNAMIC,6,1));
benchmarks.push_back(new update_geometry ("update_geometry_1k" , RTC_GEOMETRY_DYNAMIC,17,1));
benchmarks.push_back(new update_geometry ("update_geometry_10k", RTC_GEOMETRY_DYNAMIC,51,1));
benchmarks.push_back(new update_geometry ("update_geometry_100k", RTC_GEOMETRY_DYNAMIC,159,1));
benchmarks.push_back(new update_geometry ("update_geometry_1000k_1", RTC_GEOMETRY_DYNAMIC,501,1));
benchmarks.push_back(new update_geometry ("update_geometry_100k_10", RTC_GEOMETRY_DYNAMIC,159,10));
benchmarks.push_back(new update_geometry ("update_geometry_10k_100", RTC_GEOMETRY_DYNAMIC,51,100));
benchmarks.push_back(new update_geometry ("update_geometry_1k_1000" , RTC_GEOMETRY_DYNAMIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_geometry ("update_geometry_120_10000",RTC_GEOMETRY_DYNAMIC,6,8334));
#endif
benchmarks.push_back(new update_scenes ("refit_scenes_120", RTC_GEOMETRY_DEFORMABLE,6,1));
benchmarks.push_back(new update_scenes ("refit_scenes_1k" , RTC_GEOMETRY_DEFORMABLE,17,1));
benchmarks.push_back(new update_scenes ("refit_scenes_10k", RTC_GEOMETRY_DEFORMABLE,51,1));
benchmarks.push_back(new update_scenes ("refit_scenes_100k", RTC_GEOMETRY_DEFORMABLE,159,1));
benchmarks.push_back(new update_scenes ("refit_scenes_1000k_1", RTC_GEOMETRY_DEFORMABLE,501,1));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("refit_scenes_8000k_1", RTC_GEOMETRY_DEFORMABLE,1420,1));
#endif
benchmarks.push_back(new update_scenes ("refit_scenes_100k_10", RTC_GEOMETRY_DEFORMABLE,159,10));
#if !defined(__MIC__)
benchmarks.push_back(new update_scenes ("refit_scenes_10k_100", RTC_GEOMETRY_DEFORMABLE,51,100));
benchmarks.push_back(new update_scenes ("refit_scenes_1k_1000" , RTC_GEOMETRY_DEFORMABLE,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("refit_scenes_120_10000",RTC_GEOMETRY_DEFORMABLE,6,8334));
#endif
#endif
#if defined(__X86_64__)
benchmarks.push_back(new update_keyframe_scenes ("refit_keyframe_scenes_1000k_1", RTC_GEOMETRY_DEFORMABLE,501,1));
benchmarks.push_back(new update_keyframe_scenes ("refit_keyframe_scenes_8000k_1", RTC_GEOMETRY_DEFORMABLE,1420,1));
#endif
benchmarks.push_back(new update_scenes ("update_scenes_120", RTC_GEOMETRY_DYNAMIC,6,1));
benchmarks.push_back(new update_scenes ("update_scenes_1k" , RTC_GEOMETRY_DYNAMIC,17,1));
benchmarks.push_back(new update_scenes ("update_scenes_10k", RTC_GEOMETRY_DYNAMIC,51,1));
benchmarks.push_back(new update_scenes ("update_scenes_100k", RTC_GEOMETRY_DYNAMIC,159,1));
benchmarks.push_back(new update_scenes ("update_scenes_1000k_1", RTC_GEOMETRY_DYNAMIC,501,1));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("update_scenes_8000k_1", RTC_GEOMETRY_DYNAMIC,1420,1));
#endif
benchmarks.push_back(new update_scenes ("update_scenes_100k_10", RTC_GEOMETRY_DYNAMIC,159,10));
#if !defined(__MIC__)
benchmarks.push_back(new update_scenes ("update_scenes_10k_100", RTC_GEOMETRY_DYNAMIC,51,100));
benchmarks.push_back(new update_scenes ("update_scenes_1k_1000" , RTC_GEOMETRY_DYNAMIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("update_scenes_120_10000",RTC_GEOMETRY_DYNAMIC,6,8334));
#endif
#if defined(__X86_64__)
benchmarks.push_back(new update_keyframe_scenes ("update_keyframe_scenes_1000k_1", RTC_GEOMETRY_DYNAMIC,501,1));
benchmarks.push_back(new update_keyframe_scenes ("update_keyframe_scenes_8000k_1", RTC_GEOMETRY_DYNAMIC,1420,1));
#endif
#endif
#endif
//benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_120", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,120,1));
//benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_1k" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,1*1000,1));
//benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_10k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,10*1000,1));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_100k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,100*1000,1));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_1000k_1", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,1000*1000,1));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_100k_10", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,100*1000,10));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_10k_100", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,10*1000,100));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_1k_1000" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,1*1000,1000));
#if defined(__X86_64__)
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_120_10000",RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,120,10000));
#endif
//benchmarks.push_back(new update_geometry_line ("refit_geometry_line_120", RTC_GEOMETRY_DEFORMABLE,120,1));
//benchmarks.push_back(new update_geometry_line ("refit_geometry_line_1k" , RTC_GEOMETRY_DEFORMABLE,1*1000,1));
//benchmarks.push_back(new update_geometry_line ("refit_geometry_line_10k", RTC_GEOMETRY_DEFORMABLE,10*1000,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_100k", RTC_GEOMETRY_DEFORMABLE,100*1000,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_1000k_1", RTC_GEOMETRY_DEFORMABLE,1000*1000,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_8000k_1", RTC_GEOMETRY_DEFORMABLE,1000*1000*8,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_100k_10", RTC_GEOMETRY_DEFORMABLE,100*1000,10));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_10k_100", RTC_GEOMETRY_DEFORMABLE,10*1000,100));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_1k_1000" , RTC_GEOMETRY_DEFORMABLE,1*1000,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_120_10000",RTC_GEOMETRY_DEFORMABLE,120,10000));
#endif
}
Benchmark* getBenchmark(const std::string& str)
{
for (size_t i=0; i<benchmarks.size(); i++)
if (benchmarks[i]->name == str)
return benchmarks[i];
std::cout << "unknown benchmark: " << str << std::endl;
exit(1);
}
void plot_scalability()
{
Benchmark* benchmark = getBenchmark(g_plot_test);
//std::cout << "set terminal gif" << std::endl;
//std::cout << "set output\"" << benchmark->name << "\"" << std::endl;
std::cout << "set key inside right top vertical Right noreverse enhanced autotitles box linetype -1 linewidth 1.000" << std::endl;
std::cout << "set samples 50, 50" << std::endl;
std::cout << "set title \"" << benchmark->name << "\"" << std::endl;
std::cout << "set xlabel \"threads\"" << std::endl;
std::cout << "set ylabel \"" << benchmark->unit << "\"" << std::endl;
std::cout << "plot \"-\" using 0:2 title \"" << benchmark->name << "\" with lines" << std::endl;
for (size_t i=g_plot_min; i<=g_plot_max; i+= g_plot_step)
{
double pmin = inf, pmax = -float(inf), pavg = 0.0f;
size_t N = 8;
for (size_t j=0; j<N; j++) {
double p = benchmark->run(i);
pmin = min(pmin,p);
pmax = max(pmax,p);
pavg = pavg + p/double(N);
}
//std::cout << "threads = " << i << ": [" << pmin << " / " << pavg << " / " << pmax << "] " << benchmark->unit << std::endl;
std::cout << " " << i << " " << pmin << " " << pavg << " " << pmax << std::endl;
}
std::cout << "EOF" << std::endl;
}
static void parseCommandLine(int argc, char** argv)
{
for (int i=1; i<argc; i++)
{
std::string tag = argv[i];
if (tag == "") return;
/* rtcore configuration */
else if (tag == "-rtcore" && i+1<argc) {
g_rtcore = argv[++i];
}
/* plots scalability graph */
else if (tag == "-plot" && i+4<argc) {
g_plot_min = atoi(argv[++i]);
g_plot_max = atoi(argv[++i]);
g_plot_step= atoi(argv[++i]);
g_plot_test= argv[++i];
plot_scalability();
}
/* run single benchmark */
else if (tag == "-run" && i+2<argc)
{
size_t numThreads = atoi(argv[++i]);
std::string name = argv[++i];
Benchmark* benchmark = getBenchmark(name);
benchmark->print(numThreads,16);
executed_benchmarks = true;
}
else if (tag == "-threads" && i+1<argc)
{
g_num_threads_init = atoi(argv[++i]);
}
/* skip unknown command line parameter */
else {
std::cerr << "unknown command line parameter: " << tag << " ";
std::cerr << std::endl;
}
}
}
/* main function in embree namespace */
int main(int argc, char** argv)
{
/* for best performance set FTZ and DAZ flags in MXCSR control and status register */
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
create_benchmarks();
/* parse command line */
parseCommandLine(argc,argv);
if (!executed_benchmarks)
{
size_t numThreads = getNumberOfLogicalThreads();
printf("%40s ... %d \n","#HW threads ",(int)getNumberOfLogicalThreads());
#if defined (__MIC__)
numThreads -= 4;
#endif
if (g_num_threads_init != -1)
{
numThreads = g_num_threads_init;
PRINT(numThreads);
}
rtcore_intersect_benchmark(RTC_SCENE_STATIC, 501);
for (size_t i=0; i<benchmarks.size(); i++) benchmarks[i]->print(numThreads,4);
}
return 0;
}
}
int main(int argc, char** argv)
{
try {
return embree::main(argc, argv);
}
catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "Error: unknown exception caught." << std::endl;
return 1;
}
}
added stream micro benchmarks to benchmark tool
// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "../include/embree2/rtcore.h"
#include "../include/embree2/rtcore_ray.h"
#include "../kernels/common/default.h"
#include "../kernels/algorithms/parallel_for.h"
#include <vector>
#if defined(RTCORE_RAY_PACKETS) && !defined(__MIC__)
# define HAS_INTERSECT4 1
#else
# define HAS_INTERSECT4 0
#endif
#if defined(RTCORE_RAY_PACKETS) && (defined(__TARGET_AVX__) || defined(__TARGET_AVX2__))
# define HAS_INTERSECT8 1
#else
# define HAS_INTERSECT8 0
#endif
#if defined(RTCORE_RAY_PACKETS) && (defined(__MIC__) || defined(__TARGET_AVX512KNL__))
# define HAS_INTERSECT16 1
#else
# define HAS_INTERSECT16 0
#endif
namespace embree
{
bool hasISA(const int isa)
{
int cpu_features = getCPUFeatures();
return (cpu_features & isa) == isa;
}
/* error reporting function */
void error_handler(const RTCError code, const char* str = nullptr)
{
if (code == RTC_NO_ERROR)
return;
printf("Embree: ");
switch (code) {
case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break;
case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break;
case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break;
case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break;
case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break;
case RTC_CANCELLED : printf("RTC_CANCELLED"); break;
default : printf("invalid error code"); break;
}
if (str) {
printf(" (");
while (*str) putchar(*str++);
printf(")\n");
}
exit(1);
}
RTCAlgorithmFlags aflags = (RTCAlgorithmFlags) (RTC_INTERSECT1 | RTC_INTERSECT4 | RTC_INTERSECT8 | RTC_INTERSECT16 | RTC_INTERSECTN);
/* configuration */
static std::string g_rtcore = "";
static size_t g_plot_min = 0;
static size_t g_plot_max = 0;
static size_t g_plot_step= 0;
static std::string g_plot_test = "";
static bool executed_benchmarks = false;
/* vertex and triangle layout */
struct Vertex { float x,y,z,a; };
struct Triangle { int v0, v1, v2; };
#define AssertNoError() \
if (rtcGetError() != RTC_NO_ERROR) return false;
#define AssertAnyError() \
if (rtcGetError() == RTC_NO_ERROR) return false;
#define AssertError(code) \
if (rtcGetError() != code) return false;
std::vector<thread_t> g_threads;
MutexSys g_mutex;
BarrierSys g_barrier;
LinearBarrierActive g_barrier_active;
size_t g_num_mutex_locks = 100000;
size_t g_num_threads = 0;
ssize_t g_num_threads_init = -1;
atomic_t g_atomic_cntr = 0;
class Benchmark
{
public:
const std::string name;
const std::string unit;
Benchmark (const std::string& name, const std::string& unit)
: name(name), unit(unit) {}
virtual double run(size_t numThreads) = 0;
void print(size_t numThreads, size_t N)
{
double pmin = inf, pmax = -float(inf), pavg = 0.0f;
for (size_t j=0; j<N; j++) {
double p = run(numThreads);
pmin = min(pmin,p);
pmax = max(pmax,p);
pavg = pavg + p/double(N);
}
printf("%40s ... [%f / %f / %f] %s\n",name.c_str(),pmin,pavg,pmax,unit.c_str());
fflush(stdout);
}
};
class benchmark_mutex_sys : public Benchmark
{
public:
benchmark_mutex_sys ()
: Benchmark("mutex_sys","ms") {}
static void benchmark_mutex_sys_thread(void* ptr)
{
g_barrier.wait();
while (true)
{
if (atomic_add(&g_atomic_cntr,-1) < 0) break;
g_mutex.lock();
g_mutex.unlock();
}
}
double run (size_t numThreads)
{
g_barrier.init(numThreads);
g_atomic_cntr = g_num_mutex_locks;
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_mutex_sys_thread,nullptr,1000000,i));
//setAffinity(0);
double t0 = getSeconds();
benchmark_mutex_sys_thread(nullptr);
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
//printf("%40s ... %f ms (%f k/s)\n","mutex_sys",1000.0f*(t1-t0)/double(g_num_mutex_locks),1E-3*g_num_mutex_locks/(t1-t0));
//fflush(stdout);
return 1000.0f*(t1-t0)/double(g_num_mutex_locks);
}
};
class benchmark_barrier_sys : public Benchmark
{
public:
enum { N = 100 };
benchmark_barrier_sys ()
: Benchmark("barrier_sys","ms") {}
static void benchmark_barrier_sys_thread(void* ptr)
{
g_barrier.wait();
for (size_t i=0; i<N; i++)
g_barrier.wait();
}
double run (size_t numThreads)
{
g_barrier.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_barrier_sys_thread,(void*)i,1000000,i));
//setAffinity(0);
g_barrier.wait();
double t0 = getSeconds();
for (size_t i=0; i<N; i++) g_barrier.wait();
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
//printf("%40s ... %f ms (%f k/s)\n","barrier_sys",1000.0f*(t1-t0)/double(N),1E-3*N/(t1-t0));
//fflush(stdout);
return 1000.0f*(t1-t0)/double(N);
}
};
class benchmark_barrier_active : public Benchmark
{
enum { N = 1000 };
public:
benchmark_barrier_active ()
: Benchmark("barrier_active","ns") {}
static void benchmark_barrier_active_thread(void* ptr)
{
size_t threadIndex = (size_t) ptr;
size_t threadCount = g_num_threads;
g_barrier_active.wait(threadIndex);
for (size_t i=0; i<N; i++)
g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_barrier_active_thread,(void*)i,1000000,i));
setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
for (size_t i=0; i<N; i++)
g_barrier_active.wait(0);
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++)
join(g_threads[i]);
g_threads.clear();
//printf("%40s ... %f ms (%f k/s)\n","barrier_active",1000.0f*(t1-t0)/double(N),1E-3*N/(t1-t0));
//fflush(stdout);
return 1E9*(t1-t0)/double(N);
}
};
class benchmark_atomic_inc : public Benchmark
{
public:
enum { N = 10000000 };
benchmark_atomic_inc ()
: Benchmark("atomic_inc","ns") {}
static void benchmark_atomic_inc_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
__memory_barrier();
while (atomic_add(&g_atomic_cntr,-1) > 0);
__memory_barrier();
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
g_atomic_cntr = N;
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_atomic_inc_thread,(void*)i,1000000,i));
setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
//size_t c0 = rdtsc();
benchmark_atomic_inc_thread(nullptr);
//size_t c1 = rdtsc();
double t1 = getSeconds();
g_barrier_active.wait(0);
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
//PRINT(double(c1-c0)/N);
//printf("%40s ... %f ms (%f k/s)\n","mutex_sys",1000.0f*(t1-t0)/double(g_num_mutex_locks),1E-3*g_num_mutex_locks/(t1-t0));
//fflush(stdout);
return 1E9*(t1-t0)/double(N);
}
};
class benchmark_pagefaults : public Benchmark
{
public:
enum { N = 1024*1024*1024 };
static char* ptr;
benchmark_pagefaults ()
: Benchmark("pagefaults","GB/s") {}
static void benchmark_pagefaults_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
size_t start = (threadIndex+0)*N/threadCount;
size_t end = (threadIndex+1)*N/threadCount;
for (size_t i=start; i<end; i+=64)
ptr[i] = 0;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
#if !defined(__WIN32__)
ptr = (char*) os_reserve(N);
#else
ptr = (char*)os_malloc(N);
#endif
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_pagefaults_thread,(void*)i,1000000,i));
//setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
benchmark_pagefaults_thread(0);
double t1 = getSeconds();
g_barrier_active.wait(0);
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
os_free(ptr,N);
return 1E-9*double(N)/(t1-t0);
}
};
char* benchmark_pagefaults::ptr = nullptr;
#if defined(__UNIX__)
#include <sys/mman.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#endif
class benchmark_osmalloc_with_page_commit : public Benchmark
{
public:
enum { N = 1024*1024*1024 };
static char* ptr;
benchmark_osmalloc_with_page_commit ()
: Benchmark("osmalloc_with_page_commit","GB/s") {}
static void benchmark_osmalloc_with_page_commit_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
size_t start = (threadIndex+0)*N/threadCount;
size_t end = (threadIndex+1)*N/threadCount;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
int flags = 0;
#if defined(__UNIX__) && !defined(__APPLE__)
flags |= MAP_POPULATE;
#endif
size_t startN = 1024*1024*16;
double t = 0.0f;
size_t iterations = 0;
for (size_t i=startN;i<=N;i*=2,iterations++)
{
double t0 = getSeconds();
char *ptr = (char*) os_malloc(i,flags);
double t1 = getSeconds();
os_free(ptr,i);
t += 1E-9*double(i)/(t1-t0);
}
return t / (double)iterations;
}
};
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
class benchmark_bandwidth : public Benchmark
{
public:
enum { N = 300000000 };
static char* ptr;
benchmark_bandwidth ()
: Benchmark("bandwidth","GB/s") {}
static void benchmark_bandwidth_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
size_t start = (threadIndex+0)*N/threadCount;
size_t end = (threadIndex+1)*N/threadCount;
char p = 0;
for (size_t i=start; i<end; i+=64)
p += ptr[i];
volatile char out = p;
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
}
double run (size_t numThreads)
{
ptr = (char*) os_malloc(N);
for (size_t i=0; i<N; i+=4096) ptr[i] = 0;
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread(benchmark_bandwidth_thread,(void*)i,1000000,i));
//setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
benchmark_bandwidth_thread(0);
double t1 = getSeconds();
g_barrier_active.wait(0);
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
os_free(ptr,N);
return 1E-9*double(N)/(t1-t0);
}
};
char* benchmark_bandwidth::ptr = nullptr;
RTCRay makeRay(Vec3f org, Vec3f dir)
{
RTCRay ray;
ray.org[0] = org.x; ray.org[1] = org.y; ray.org[2] = org.z;
ray.dir[0] = dir.x; ray.dir[1] = dir.y; ray.dir[2] = dir.z;
ray.tnear = 0.0f; ray.tfar = inf;
ray.time = 0; ray.mask = -1;
ray.geomID = ray.primID = ray.instID = -1;
return ray;
}
RTCRay makeRay(Vec3f org, Vec3f dir, float tnear, float tfar)
{
RTCRay ray;
ray.org[0] = org.x; ray.org[1] = org.y; ray.org[2] = org.z;
ray.dir[0] = dir.x; ray.dir[1] = dir.y; ray.dir[2] = dir.z;
ray.tnear = tnear; ray.tfar = tfar;
ray.time = 0; ray.mask = -1;
ray.geomID = ray.primID = ray.instID = -1;
return ray;
}
void setRay(RTCRay4& ray_o, int i, const RTCRay& ray_i)
{
ray_o.orgx[i] = ray_i.org[0];
ray_o.orgy[i] = ray_i.org[1];
ray_o.orgz[i] = ray_i.org[2];
ray_o.dirx[i] = ray_i.dir[0];
ray_o.diry[i] = ray_i.dir[1];
ray_o.dirz[i] = ray_i.dir[2];
ray_o.tnear[i] = ray_i.tnear;
ray_o.tfar[i] = ray_i.tfar;
ray_o.time[i] = ray_i.time;
ray_o.mask[i] = ray_i.mask;
ray_o.geomID[i] = ray_i.geomID;
ray_o.primID[i] = ray_i.primID;
ray_o.instID[i] = ray_i.instID;
}
void setRay(RTCRay8& ray_o, int i, const RTCRay& ray_i)
{
ray_o.orgx[i] = ray_i.org[0];
ray_o.orgy[i] = ray_i.org[1];
ray_o.orgz[i] = ray_i.org[2];
ray_o.dirx[i] = ray_i.dir[0];
ray_o.diry[i] = ray_i.dir[1];
ray_o.dirz[i] = ray_i.dir[2];
ray_o.tnear[i] = ray_i.tnear;
ray_o.tfar[i] = ray_i.tfar;
ray_o.time[i] = ray_i.time;
ray_o.mask[i] = ray_i.mask;
ray_o.geomID[i] = ray_i.geomID;
ray_o.primID[i] = ray_i.primID;
ray_o.instID[i] = ray_i.instID;
}
void setRay(RTCRay16& ray_o, int i, const RTCRay& ray_i)
{
ray_o.orgx[i] = ray_i.org[0];
ray_o.orgy[i] = ray_i.org[1];
ray_o.orgz[i] = ray_i.org[2];
ray_o.dirx[i] = ray_i.dir[0];
ray_o.diry[i] = ray_i.dir[1];
ray_o.dirz[i] = ray_i.dir[2];
ray_o.tnear[i] = ray_i.tnear;
ray_o.tfar[i] = ray_i.tfar;
ray_o.time[i] = ray_i.time;
ray_o.mask[i] = ray_i.mask;
ray_o.geomID[i] = ray_i.geomID;
ray_o.primID[i] = ray_i.primID;
ray_o.instID[i] = ray_i.instID;
}
struct Mesh {
std::vector<Vertex> vertices;
std::vector<Triangle> triangles;
};
void createSphereMesh (const Vec3f pos, const float r, size_t numPhi, Mesh& mesh_o)
{
/* create a triangulated sphere */
size_t numTheta = 2*numPhi;
mesh_o.vertices.resize(numTheta*(numPhi+1));
mesh_o.triangles.resize(2*numTheta*(numPhi-1));
/* map triangle and vertex buffer */
Vertex* vertices = (Vertex* ) &mesh_o.vertices[0];
Triangle* triangles = (Triangle*) &mesh_o.triangles[0];
/* create sphere geometry */
int tri = 0;
const float rcpNumTheta = 1.0f/float(numTheta);
const float rcpNumPhi = 1.0f/float(numPhi);
for (size_t phi=0; phi<=numPhi; phi++)
{
for (size_t theta=0; theta<numTheta; theta++)
{
const float phif = phi*float(pi)*rcpNumPhi;
const float thetaf = theta*2.0f*float(pi)*rcpNumTheta;
Vertex& v = vertices[phi*numTheta+theta];
v.x = pos.x + r*sin(phif)*sin(thetaf);
v.y = pos.y + r*cos(phif);
v.z = pos.z + r*sin(phif)*cos(thetaf);
}
if (phi == 0) continue;
for (size_t theta=1; theta<=numTheta; theta++)
{
int p00 = (phi-1)*numTheta+theta-1;
int p01 = (phi-1)*numTheta+theta%numTheta;
int p10 = phi*numTheta+theta-1;
int p11 = phi*numTheta+theta%numTheta;
if (phi > 1) {
triangles[tri].v0 = p10;
triangles[tri].v1 = p00;
triangles[tri].v2 = p01;
tri++;
}
if (phi < numPhi) {
triangles[tri].v0 = p11;
triangles[tri].v1 = p10;
triangles[tri].v2 = p01;
tri++;
}
}
}
}
unsigned addSphere (RTCScene scene, RTCGeometryFlags flag, const Vec3f pos, const float r, size_t numPhi)
{
Mesh mesh; createSphereMesh (pos, r, numPhi, mesh);
unsigned geom = rtcNewTriangleMesh (scene, flag, mesh.triangles.size(), mesh.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
return geom;
}
struct LineSegments {
avector<Vec3fa> vertices;
avector<int> lines;
};
Vec3fa uniformSampleSphere(const float& u, const float& v)
{
const float phi = float(two_pi) * u;
const float cosTheta = 1.0f - 2.0f * v, sinTheta = 2.0f * sqrt(v * (1.0f - v));
return Vec3fa(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);
}
inline unsigned int rngInt(unsigned int& state)
{
const unsigned int m = 1664525;
const unsigned int n = 1013904223;
state = state * m + n;
return state;
}
inline float rngFloat(unsigned int& state)
{
rngInt(state);
return (float)(int)(state >> 1) * 4.656612873077392578125e-10f;
}
void createHairball(const Vec3fa& pos, const float r, size_t numLines, LineSegments& hairset_o)
{
const float thickness = 0.001f*r;
unsigned int state = 1;
for (size_t t=0; t<numLines/3; t++)
{
Vec3fa dp = uniformSampleSphere(rngFloat(state), rngFloat(state));
Vec3fa l0 = pos + r*(dp + 0.00f*dp); l0.w = thickness;
Vec3fa l1 = pos + r*(dp + 0.25f*dp); l1.w = thickness;
Vec3fa l2 = pos + r*(dp + 0.50f*dp); l2.w = thickness;
Vec3fa l3 = pos + r*(dp + 0.75f*dp); l3.w = thickness;
const unsigned int v_index = hairset_o.vertices.size();
hairset_o.vertices.push_back(l0);
hairset_o.vertices.push_back(l1);
hairset_o.vertices.push_back(l2);
hairset_o.vertices.push_back(l3);
hairset_o.lines.push_back(v_index);
hairset_o.lines.push_back(v_index+1);
hairset_o.lines.push_back(v_index+2);
}
}
class create_geometry : public Benchmark
{
public:
RTCSceneFlags sflags; RTCGeometryFlags gflags; size_t numPhi; size_t numMeshes;
create_geometry (const std::string& name, RTCSceneFlags sflags, RTCGeometryFlags gflags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), sflags(sflags), gflags(gflags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh; createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
const size_t sizeVertexData = mesh.vertices.size()*sizeof(Vertex);
Vertex** vertices = new Vertex*[numMeshes];
for (size_t i=0; i<numMeshes; i++)
{
vertices[i] = (Vertex*)os_malloc(sizeVertexData);
assert(vertices[i]);
for (size_t j=0;j<mesh.vertices.size();j++)
{
Vertex &v = vertices[i][j];
v.x = mesh.vertices[j].x * (float)i;
v.y = mesh.vertices[j].y * (float)i;
v.z = mesh.vertices[j].z * (float)i;
v.a = 0.0f;
}
}
double t0 = getSeconds();
RTCScene scene = rtcDeviceNewScene(device,sflags,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewTriangleMesh (scene, gflags, mesh.triangles.size(), mesh.vertices.size());
#if 1
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,&vertices[i][0] ,0,sizeof(Vertex));
rtcSetBuffer(scene,geom,RTC_INDEX_BUFFER ,&mesh.triangles[0],0,sizeof(Triangle));
#else
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<mesh.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
#endif
}
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
for (size_t i=0; i<numMeshes; i++)
os_free(vertices[i],sizeVertexData);
delete[] vertices;
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)/(t1-t0);
}
};
class create_geometry_line : public Benchmark
{
public:
RTCSceneFlags sflags; RTCGeometryFlags gflags; size_t numLines; size_t numMeshes;
create_geometry_line (const std::string& name, RTCSceneFlags sflags, RTCGeometryFlags gflags, size_t numLines, size_t numMeshes)
: Benchmark(name,"Mlines/s"), sflags(sflags), gflags(gflags), numLines(numLines), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
LineSegments hairset; createHairball (Vec3f(0,0,0), 1, numLines, hairset);
const size_t sizeVertexData = hairset.vertices.size()*sizeof(Vec3fa);
Vec3fa** vertices = new Vec3fa*[numMeshes];
for (size_t i=0; i<numMeshes; i++)
{
vertices[i] = (Vec3fa*)os_malloc(sizeVertexData);
assert(vertices[i]);
for (size_t j=0;j<hairset.vertices.size();j++)
{
Vec3fa &v = vertices[i][j];
v.x = hairset.vertices[j].x * (float)i;
v.y = hairset.vertices[j].y * (float)i;
v.z = hairset.vertices[j].z * (float)i;
v.a = hairset.vertices[j].a;
}
}
double t0 = getSeconds();
RTCScene scene = rtcDeviceNewScene(device,sflags,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewLineSegments (scene, gflags, hairset.lines.size(), hairset.vertices.size());
#if 1
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,&vertices[i][0],0,sizeof(Vec3fa));
rtcSetBuffer(scene,geom,RTC_INDEX_BUFFER ,&hairset.lines[0],0,sizeof(int));
#else
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &hairset.vertices[0], hairset.vertices.size()*sizeof(Vec3fa));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &hairset.lines[0], hairset.lines.size()*sizeof(int));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<hairset.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
#endif
}
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
for (size_t i=0; i<numMeshes; i++)
os_free(vertices[i],sizeVertexData);
delete[] vertices;
size_t numLines = hairset.lines.size() * numMeshes;
return 1E-6*double(numLines)/(t1-t0);
}
};
class update_geometry : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numPhi; size_t numMeshes;
update_geometry(const std::string& name, RTCGeometryFlags flags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), flags(flags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh; createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewTriangleMesh (scene, flags, mesh.triangles.size(), mesh.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<mesh.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
}
rtcCommit (scene);
double t0 = getSeconds();
for (size_t i=0; i<numMeshes; i++) rtcUpdate(scene,i);
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
//return 1000.0f*(t1-t0);
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)/(t1-t0);
}
};
class update_geometry_line : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numLines; size_t numMeshes;
update_geometry_line(const std::string& name, RTCGeometryFlags flags, size_t numLines, size_t numMeshes)
: Benchmark(name,"Mlines/s"), flags(flags), numLines(numLines), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
LineSegments hairset; createHairball (Vec3f(0,0,0), 1, numLines, hairset);
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
for (size_t i=0; i<numMeshes; i++)
{
unsigned geom = rtcNewLineSegments (scene, flags, hairset.lines.size(), hairset.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &hairset.vertices[0], hairset.vertices.size()*sizeof(Vec3fa));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &hairset.lines[0], hairset.lines.size()*sizeof(int));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<hairset.vertices.size(); i++) {
hairset.vertices[i].x += 1.0f;
hairset.vertices[i].y += 1.0f;
hairset.vertices[i].z += 1.0f;
}
}
rtcCommit (scene);
double t0 = getSeconds();
for (size_t i=0; i<numMeshes; i++) rtcUpdate(scene,i);
rtcCommit (scene);
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
//return 1000.0f*(t1-t0);
size_t numLines = hairset.lines.size() * numMeshes;
return 1E-6*double(numLines)/(t1-t0);
}
};
class update_scenes : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numPhi; size_t numMeshes;
update_scenes(const std::string& name, RTCGeometryFlags flags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), flags(flags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh; createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
std::vector<RTCScene> scenes;
for (size_t i=0; i<numMeshes; i++)
{
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
unsigned geom = rtcNewTriangleMesh (scene, flags, mesh.triangles.size(), mesh.vertices.size());
memcpy(rtcMapBuffer(scene,geom,RTC_VERTEX_BUFFER), &mesh.vertices[0], mesh.vertices.size()*sizeof(Vertex));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_VERTEX_BUFFER);
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
for (size_t i=0; i<mesh.vertices.size(); i++) {
mesh.vertices[i].x += 1.0f;
mesh.vertices[i].y += 1.0f;
mesh.vertices[i].z += 1.0f;
}
scenes.push_back(scene);
rtcCommit (scene);
}
double t0 = getSeconds();
#if defined(__MIC__)
for (size_t i=0; i<scenes.size(); i++) {
rtcUpdate(scenes[i],0);
rtcCommit (scenes[i]);
}
#else
parallel_for( scenes.size(), [&](size_t i) {
rtcUpdate(scenes[i],0);
rtcCommit (scenes[i]);
});
#endif
double t1 = getSeconds();
for (size_t i=0; i<scenes.size(); i++)
rtcDeleteScene(scenes[i]);
rtcDeleteDevice(device);
//return 1000.0f*(t1-t0);
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)/(t1-t0);
}
};
class update_keyframe_scenes : public Benchmark
{
public:
RTCGeometryFlags flags; size_t numPhi; size_t numMeshes;
update_keyframe_scenes(const std::string& name, RTCGeometryFlags flags, size_t numPhi, size_t numMeshes)
: Benchmark(name,"Mtris/s"), flags(flags), numPhi(numPhi), numMeshes(numMeshes) {}
double run(size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
Mesh mesh;
createSphereMesh (Vec3f(0,0,0), 1, numPhi, mesh);
std::vector<RTCScene> scenes;
const size_t sizeVertexData = mesh.vertices.size()*sizeof(Vertex);
Vertex *key_frame_vertices[2];
key_frame_vertices[0] = (Vertex*)os_malloc(sizeVertexData);
key_frame_vertices[1] = (Vertex*)os_malloc(sizeVertexData);
memcpy(key_frame_vertices[0],&mesh.vertices[0],sizeVertexData);
memcpy(key_frame_vertices[1],&mesh.vertices[0],sizeVertexData);
RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_DYNAMIC,aflags);
unsigned geom = rtcNewTriangleMesh (scene, flags, mesh.triangles.size(), mesh.vertices.size());
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,key_frame_vertices[1],0,sizeof(Vec3fa));
memcpy(rtcMapBuffer(scene,geom,RTC_INDEX_BUFFER ), &mesh.triangles[0], mesh.triangles.size()*sizeof(Triangle));
rtcUnmapBuffer(scene,geom,RTC_INDEX_BUFFER);
rtcCommit (scene);
static const size_t anim_runs = 4;
//static const size_t anim_runs = 4000000;
double t0 = getSeconds();
for (size_t i=0;i<anim_runs;i++)
{
rtcSetBuffer(scene,geom,RTC_VERTEX_BUFFER,key_frame_vertices[i%2],0,sizeof(Vec3fa));
rtcUpdate(scene,0);
rtcCommit(scene);
}
double t1 = getSeconds();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
os_free(key_frame_vertices[0],sizeVertexData);
os_free(key_frame_vertices[1],sizeVertexData);
size_t numTriangles = mesh.triangles.size() * numMeshes;
return 1E-6*double(numTriangles)*anim_runs/((t1-t0));;
}
};
template<bool intersect>
class benchmark_rtcore_intersect1_throughput : public Benchmark
{
public:
enum { N = 1024*128 };
static RTCScene scene;
benchmark_rtcore_intersect1_throughput ()
: Benchmark(intersect ? "incoherent_intersect1_throughput" : "incoherent_occluded1_throughput","MRays/s (all HW threads)") {}
virtual void trace(Vec3f* numbers)
{
}
static double benchmark_rtcore_intersect1_throughput_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
srand48(threadIndex*334124);
Vec3f* numbers = new Vec3f[N];
#if 1
for (size_t i=0; i<N; i++) {
float x = 2.0f*drand48()-1.0f;
float y = 2.0f*drand48()-1.0f;
float z = 2.0f*drand48()-1.0f;
numbers[i] = Vec3f(x,y,z);
}
#else
#define NUM 512
float rx[NUM];
float ry[NUM];
float rz[NUM];
for (size_t i=0; i<NUM; i++) {
rx[i] = drand48();
ry[i] = drand48();
rz[i] = drand48();
}
for (size_t i=0; i<N; i++) {
float x = 2.0f*rx[i%NUM]-1.0f;
float y = 2.0f*ry[i%NUM]-1.0f;
float z = 2.0f*rz[i%NUM]-1.0f;
numbers[i] = Vec3f(x,y,z);
}
#endif
g_barrier_active.wait(threadIndex);
double t0 = getSeconds();
for (size_t i=0; i<N; i++) {
RTCRay ray = makeRay(zero,numbers[i]);
if (intersect)
rtcIntersect(scene,ray);
else
rtcOccluded(scene,ray);
}
g_barrier_active.wait(threadIndex);
double t1 = getSeconds();
delete [] numbers;
return t1-t0;
}
double run (size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
int numPhi = 501;
//int numPhi = 61;
//int numPhi = 1601;
RTCSceneFlags flags = RTC_SCENE_STATIC;
scene = rtcDeviceNewScene(device,flags,aflags);
addSphere (scene, RTC_GEOMETRY_STATIC, zero, 1, numPhi);
rtcCommit (scene);
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread((thread_func)benchmark_rtcore_intersect1_throughput_thread,(void*)i,1000000,i));
setAffinity(0);
//g_barrier_active.wait(0);
//double t0 = getSeconds();
double delta = benchmark_rtcore_intersect1_throughput_thread(0);
//g_barrier_active.wait(0);
//double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
return 1E-6*double(N)/(delta)*double(numThreads);
}
};
template<> RTCScene benchmark_rtcore_intersect1_throughput<true>::scene = nullptr;
template<> RTCScene benchmark_rtcore_intersect1_throughput<false>::scene = nullptr;
#if HAS_INTERSECT16
template<bool intersect>
class benchmark_rtcore_intersect16_throughput : public Benchmark
{
public:
enum { N = 1024*128 };
static RTCScene scene;
benchmark_rtcore_intersect16_throughput ()
: Benchmark(intersect ? "incoherent_intersect16_throughput" : "incoherent_occluded16_throughput","MRays/s (all HW threads)") {}
static double benchmark_rtcore_intersect16_throughput_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
srand48(threadIndex*334124);
Vec3f* numbers = new Vec3f[N];
#if 0
assert(N % 16 == 0);
for (size_t i=0; i<N; i++) {
size_t j = i >> 4;
float tx = (j & 1) ? 1.0f : -1.0f;
float ty = (j & 2) ? 1.0f : -1.0f;
float tz = (j & 4) ? 1.0f : -1.0f;
float x = drand48()*tx;
float y = drand48()*ty;
float z = drand48()*tz;
numbers[i] = Vec3f(x,y,z);
}
#else
for (size_t i=0; i<N; i++) {
float x = 2.0f*drand48()-1.0f;
float y = 2.0f*drand48()-1.0f;
float z = 2.0f*drand48()-1.0f;
numbers[i] = Vec3f(x,y,z);
}
#endif
__aligned(16) int valid16[16] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 };
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
double t0 = getSeconds();
//while(1)
for (size_t i=0; i<N; i+=16) {
RTCRay16 ray16;
for (size_t j=0;j<16;j++)
setRay(ray16,j,makeRay(zero,numbers[i+j]));
if (intersect)
rtcIntersect16(valid16,scene,ray16);
else
rtcOccluded16(valid16,scene,ray16);
}
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
double t1 = getSeconds();
delete [] numbers;
return t1-t0;
}
double run (size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
int numPhi = 501;
RTCSceneFlags flags = RTC_SCENE_STATIC;
scene = rtcDeviceNewScene(device,flags,aflags);
addSphere (scene, RTC_GEOMETRY_STATIC, zero, 1, numPhi);
rtcCommit (scene);
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread((thread_func)benchmark_rtcore_intersect16_throughput_thread,(void*)i,1000000,i));
setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
double delta = benchmark_rtcore_intersect16_throughput_thread(0);
g_barrier_active.wait(0);
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
return 1E-6*double(N)/(delta)*double(numThreads);
}
};
template<> RTCScene benchmark_rtcore_intersect16_throughput<true>::scene = nullptr;
template<> RTCScene benchmark_rtcore_intersect16_throughput<false>::scene = nullptr;
#endif
#if HAS_INTERSECT8
template<bool intersect>
class benchmark_rtcore_intersect_stream_throughput : public Benchmark
{
public:
enum { N = 1024*128 };
static RTCScene scene;
benchmark_rtcore_intersect_stream_throughput ()
: Benchmark(intersect ? "incoherent_intersect_stream_throughput" : "incoherent_occluded_stream_throughput","MRays/s (all HW threads)") {}
static double benchmark_rtcore_intersect_stream_throughput_thread(void* arg)
{
size_t threadIndex = (size_t) arg;
size_t threadCount = g_num_threads;
srand48(threadIndex*334124);
Vec3f* numbers = new Vec3f[N];
for (size_t i=0; i<N; i++) {
float x = 2.0f*drand48()-1.0f;
float y = 2.0f*drand48()-1.0f;
float z = 2.0f*drand48()-1.0f;
numbers[i] = Vec3f(x,y,z);
}
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
double t0 = getSeconds();
#define STREAM_SIZE 256
for (size_t i=0; i<N; i+=STREAM_SIZE) {
RTCRay rays[STREAM_SIZE];
for (size_t j=0;j<STREAM_SIZE;j++)
{
rays[j] = makeRay(zero,numbers[i+j]);
}
if (intersect)
rtcIntersectN(scene,rays,STREAM_SIZE,sizeof(RTCRay),RTC_RAYN_AOS);
else
rtcOccludedN(scene,rays,STREAM_SIZE,sizeof(RTCRay),RTC_RAYN_AOS);
}
if (threadIndex != 0) g_barrier_active.wait(threadIndex);
double t1 = getSeconds();
delete [] numbers;
return t1-t0;
}
double run (size_t numThreads)
{
RTCDevice device = rtcNewDevice((g_rtcore+",threads="+toString(numThreads)).c_str());
error_handler(rtcDeviceGetError(device));
int numPhi = 501;
RTCSceneFlags flags = RTC_SCENE_STATIC;
scene = rtcDeviceNewScene(device,flags,aflags);
addSphere (scene, RTC_GEOMETRY_STATIC, zero, 1, numPhi);
rtcCommit (scene);
g_num_threads = numThreads;
g_barrier_active.init(numThreads);
for (size_t i=1; i<numThreads; i++)
g_threads.push_back(createThread((thread_func)benchmark_rtcore_intersect_stream_throughput_thread,(void*)i,1000000,i));
setAffinity(0);
g_barrier_active.wait(0);
double t0 = getSeconds();
double delta = benchmark_rtcore_intersect_stream_throughput_thread(0);
g_barrier_active.wait(0);
double t1 = getSeconds();
for (size_t i=0; i<g_threads.size(); i++) join(g_threads[i]);
g_threads.clear();
rtcDeleteScene(scene);
rtcDeleteDevice(device);
return 1E-6*double(N)/(delta)*double(numThreads);
}
};
template<> RTCScene benchmark_rtcore_intersect_stream_throughput<true>::scene = nullptr;
template<> RTCScene benchmark_rtcore_intersect_stream_throughput<false>::scene = nullptr;
#endif
void rtcore_coherent_intersect1(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y++) {
for (size_t x=0; x<width; x++) {
RTCRay ray = makeRay(zero,Vec3f(float(x)*rcpWidth,1,float(y)*rcpHeight));
rtcIntersect(scene,ray);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect1",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#if HAS_INTERSECT4
void rtcore_coherent_intersect4(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y+=2) {
for (size_t x=0; x<width; x+=2) {
RTCRay4 ray4;
for (size_t dy=0; dy<2; dy++) {
for (size_t dx=0; dx<2; dx++) {
setRay(ray4,2*dy+dx,makeRay(zero,Vec3f(float(x+dx)*rcpWidth,1,float(y+dy)*rcpHeight)));
}
}
__aligned(16) int valid4[4] = { -1,-1,-1,-1 };
rtcIntersect4(valid4,scene,ray4);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect4",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT8
void rtcore_coherent_intersect8(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y+=4) {
for (size_t x=0; x<width; x+=2) {
RTCRay8 ray8;
for (size_t dy=0; dy<4; dy++) {
for (size_t dx=0; dx<2; dx++) {
setRay(ray8,2*dy+dx,makeRay(zero,Vec3f(float(x+dx)*rcpWidth,1,float(y+dy)*rcpHeight)));
}
}
__aligned(32) int valid8[8] = { -1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect8(valid8,scene,ray8);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect8",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT16
void rtcore_coherent_intersect16(RTCScene scene)
{
size_t width = 1024;
size_t height = 1024;
float rcpWidth = 1.0f/1024.0f;
float rcpHeight = 1.0f/1024.0f;
double t0 = getSeconds();
for (size_t y=0; y<height; y+=4) {
for (size_t x=0; x<width; x+=4) {
RTCRay16 ray16;
for (size_t dy=0; dy<4; dy++) {
for (size_t dx=0; dx<4; dx++) {
setRay(ray16,4*dy+dx,makeRay(zero,Vec3f(float(x+dx)*rcpWidth,1,float(y+dy)*rcpHeight)));
}
}
__aligned(64) int valid16[16] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect16(valid16,scene,ray16);
}
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","coherent_intersect16",1E-6*(double)(width*height)/(t1-t0));
fflush(stdout);
}
#endif
void rtcore_incoherent_intersect1(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i++) {
RTCRay ray = makeRay(zero,numbers[i]);
rtcIntersect(scene,ray);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect1",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#if HAS_INTERSECT4
void rtcore_incoherent_intersect4(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i+=4) {
RTCRay4 ray4;
for (size_t j=0; j<4; j++) {
setRay(ray4,j,makeRay(zero,numbers[i+j]));
}
__aligned(16) int valid4[4] = { -1,-1,-1,-1 };
rtcIntersect4(valid4,scene,ray4);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect4",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT8
void rtcore_incoherent_intersect8(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i+=8) {
RTCRay8 ray8;
for (size_t j=0; j<8; j++) {
setRay(ray8,j,makeRay(zero,numbers[i+j]));
}
__aligned(32) int valid8[8] = { -1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect8(valid8,scene,ray8);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect8",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#endif
#if HAS_INTERSECT16
void rtcore_incoherent_intersect16(RTCScene scene, Vec3f* numbers, size_t N)
{
double t0 = getSeconds();
for (size_t i=0; i<N; i+=16) {
RTCRay16 ray16;
for (size_t j=0; j<16; j++) {
setRay(ray16,j,makeRay(zero,numbers[i+j]));
}
__aligned(64) int valid16[16] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 };
rtcIntersect16(valid16,scene,ray16);
}
double t1 = getSeconds();
printf("%40s ... %f Mrps\n","incoherent_intersect16",1E-6*(double)N/(t1-t0));
fflush(stdout);
}
#endif
void rtcore_intersect_benchmark(RTCSceneFlags flags, size_t numPhi)
{
RTCDevice device = rtcNewDevice(g_rtcore.c_str());
error_handler(rtcDeviceGetError(device));
RTCScene scene = rtcDeviceNewScene(device,flags,aflags);
addSphere (scene, RTC_GEOMETRY_STATIC, zero, 1, numPhi);
rtcCommit (scene);
rtcore_coherent_intersect1(scene);
#if HAS_INTERSECT4
rtcore_coherent_intersect4(scene);
#endif
#if HAS_INTERSECT8
if (hasISA(AVX)) {
rtcore_coherent_intersect8(scene);
}
#endif
#if HAS_INTERSECT16
if (hasISA(AVX512KNL) || hasISA(KNC)) {
rtcore_coherent_intersect16(scene);
}
#endif
size_t N = 1024*1024;
Vec3f* numbers = new Vec3f[N];
for (size_t i=0; i<N; i++) {
float x = 2.0f*drand48()-1.0f;
float y = 2.0f*drand48()-1.0f;
float z = 2.0f*drand48()-1.0f;
numbers[i] = Vec3f(x,y,z);
}
rtcore_incoherent_intersect1(scene,numbers,N);
#if HAS_INTERSECT4
rtcore_incoherent_intersect4(scene,numbers,N);
#endif
#if HAS_INTERSECT8
if (hasISA(AVX)) {
rtcore_incoherent_intersect8(scene,numbers,N);
}
#endif
#if HAS_INTERSECT16
if (hasISA(AVX512KNL) || hasISA(KNC)) {
rtcore_incoherent_intersect16(scene,numbers,N);
}
#endif
delete[] numbers;
rtcDeleteScene(scene);
rtcDeleteDevice(device);
}
std::vector<Benchmark*> benchmarks;
void create_benchmarks()
{
#if 1
benchmarks.push_back(new benchmark_rtcore_intersect1_throughput<true>());
benchmarks.push_back(new benchmark_rtcore_intersect1_throughput<false>());
#if HAS_INTERSECT16
if (hasISA(AVX512KNL) || hasISA(KNC)) {
benchmarks.push_back(new benchmark_rtcore_intersect16_throughput<true>());
benchmarks.push_back(new benchmark_rtcore_intersect16_throughput<false>());
}
#endif
#if HAS_INTERSECT8
if (hasISA(AVX)) {
benchmarks.push_back(new benchmark_rtcore_intersect_stream_throughput<true>());
benchmarks.push_back(new benchmark_rtcore_intersect_stream_throughput<false>());
}
#endif
benchmarks.push_back(new benchmark_mutex_sys());
benchmarks.push_back(new benchmark_barrier_sys());
benchmarks.push_back(new benchmark_barrier_active());
benchmarks.push_back(new benchmark_atomic_inc());
#if defined(__X86_64__)
benchmarks.push_back(new benchmark_osmalloc_with_page_commit());
benchmarks.push_back(new benchmark_pagefaults());
benchmarks.push_back(new benchmark_bandwidth());
#endif
benchmarks.push_back(new create_geometry ("create_static_geometry_120", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,6,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_1k" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,17,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_10k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,51,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_100k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,159,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_1000k_1", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,501,1));
benchmarks.push_back(new create_geometry ("create_static_geometry_100k_10", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,159,10));
benchmarks.push_back(new create_geometry ("create_static_geometry_10k_100", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,51,100));
benchmarks.push_back(new create_geometry ("create_static_geometry_1k_1000" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new create_geometry ("create_static_geometry_120_10000",RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,6,8334));
#endif
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_120", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,6,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_1k" , RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,17,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_10k", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,51,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_100k", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,159,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_1000k_1", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,501,1));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_100k_10", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,159,10));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_10k_100", RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,51,100));
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_1k_1000" , RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new create_geometry ("create_dynamic_geometry_120_10000",RTC_SCENE_DYNAMIC,RTC_GEOMETRY_STATIC,6,8334));
#endif
#endif
benchmarks.push_back(new update_geometry ("refit_geometry_120", RTC_GEOMETRY_DEFORMABLE,6,1));
benchmarks.push_back(new update_geometry ("refit_geometry_1k" , RTC_GEOMETRY_DEFORMABLE,17,1));
benchmarks.push_back(new update_geometry ("refit_geometry_10k", RTC_GEOMETRY_DEFORMABLE,51,1));
benchmarks.push_back(new update_geometry ("refit_geometry_100k", RTC_GEOMETRY_DEFORMABLE,159,1));
benchmarks.push_back(new update_geometry ("refit_geometry_1000k_1", RTC_GEOMETRY_DEFORMABLE,501,1));
benchmarks.push_back(new update_geometry ("refit_geometry_100k_10", RTC_GEOMETRY_DEFORMABLE,159,10));
benchmarks.push_back(new update_geometry ("refit_geometry_10k_100", RTC_GEOMETRY_DEFORMABLE,51,100));
benchmarks.push_back(new update_geometry ("refit_geometry_1k_1000" , RTC_GEOMETRY_DEFORMABLE,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_geometry ("refit_geometry_120_10000",RTC_GEOMETRY_DEFORMABLE,6,8334));
#endif
#if 1
benchmarks.push_back(new update_geometry ("update_geometry_120", RTC_GEOMETRY_DYNAMIC,6,1));
benchmarks.push_back(new update_geometry ("update_geometry_1k" , RTC_GEOMETRY_DYNAMIC,17,1));
benchmarks.push_back(new update_geometry ("update_geometry_10k", RTC_GEOMETRY_DYNAMIC,51,1));
benchmarks.push_back(new update_geometry ("update_geometry_100k", RTC_GEOMETRY_DYNAMIC,159,1));
benchmarks.push_back(new update_geometry ("update_geometry_1000k_1", RTC_GEOMETRY_DYNAMIC,501,1));
benchmarks.push_back(new update_geometry ("update_geometry_100k_10", RTC_GEOMETRY_DYNAMIC,159,10));
benchmarks.push_back(new update_geometry ("update_geometry_10k_100", RTC_GEOMETRY_DYNAMIC,51,100));
benchmarks.push_back(new update_geometry ("update_geometry_1k_1000" , RTC_GEOMETRY_DYNAMIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_geometry ("update_geometry_120_10000",RTC_GEOMETRY_DYNAMIC,6,8334));
#endif
benchmarks.push_back(new update_scenes ("refit_scenes_120", RTC_GEOMETRY_DEFORMABLE,6,1));
benchmarks.push_back(new update_scenes ("refit_scenes_1k" , RTC_GEOMETRY_DEFORMABLE,17,1));
benchmarks.push_back(new update_scenes ("refit_scenes_10k", RTC_GEOMETRY_DEFORMABLE,51,1));
benchmarks.push_back(new update_scenes ("refit_scenes_100k", RTC_GEOMETRY_DEFORMABLE,159,1));
benchmarks.push_back(new update_scenes ("refit_scenes_1000k_1", RTC_GEOMETRY_DEFORMABLE,501,1));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("refit_scenes_8000k_1", RTC_GEOMETRY_DEFORMABLE,1420,1));
#endif
benchmarks.push_back(new update_scenes ("refit_scenes_100k_10", RTC_GEOMETRY_DEFORMABLE,159,10));
#if !defined(__MIC__)
benchmarks.push_back(new update_scenes ("refit_scenes_10k_100", RTC_GEOMETRY_DEFORMABLE,51,100));
benchmarks.push_back(new update_scenes ("refit_scenes_1k_1000" , RTC_GEOMETRY_DEFORMABLE,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("refit_scenes_120_10000",RTC_GEOMETRY_DEFORMABLE,6,8334));
#endif
#endif
#if defined(__X86_64__)
benchmarks.push_back(new update_keyframe_scenes ("refit_keyframe_scenes_1000k_1", RTC_GEOMETRY_DEFORMABLE,501,1));
benchmarks.push_back(new update_keyframe_scenes ("refit_keyframe_scenes_8000k_1", RTC_GEOMETRY_DEFORMABLE,1420,1));
#endif
benchmarks.push_back(new update_scenes ("update_scenes_120", RTC_GEOMETRY_DYNAMIC,6,1));
benchmarks.push_back(new update_scenes ("update_scenes_1k" , RTC_GEOMETRY_DYNAMIC,17,1));
benchmarks.push_back(new update_scenes ("update_scenes_10k", RTC_GEOMETRY_DYNAMIC,51,1));
benchmarks.push_back(new update_scenes ("update_scenes_100k", RTC_GEOMETRY_DYNAMIC,159,1));
benchmarks.push_back(new update_scenes ("update_scenes_1000k_1", RTC_GEOMETRY_DYNAMIC,501,1));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("update_scenes_8000k_1", RTC_GEOMETRY_DYNAMIC,1420,1));
#endif
benchmarks.push_back(new update_scenes ("update_scenes_100k_10", RTC_GEOMETRY_DYNAMIC,159,10));
#if !defined(__MIC__)
benchmarks.push_back(new update_scenes ("update_scenes_10k_100", RTC_GEOMETRY_DYNAMIC,51,100));
benchmarks.push_back(new update_scenes ("update_scenes_1k_1000" , RTC_GEOMETRY_DYNAMIC,17,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_scenes ("update_scenes_120_10000",RTC_GEOMETRY_DYNAMIC,6,8334));
#endif
#if defined(__X86_64__)
benchmarks.push_back(new update_keyframe_scenes ("update_keyframe_scenes_1000k_1", RTC_GEOMETRY_DYNAMIC,501,1));
benchmarks.push_back(new update_keyframe_scenes ("update_keyframe_scenes_8000k_1", RTC_GEOMETRY_DYNAMIC,1420,1));
#endif
#endif
#endif
//benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_120", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,120,1));
//benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_1k" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,1*1000,1));
//benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_10k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,10*1000,1));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_100k", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,100*1000,1));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_1000k_1", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,1000*1000,1));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_100k_10", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,100*1000,10));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_10k_100", RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,10*1000,100));
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_1k_1000" , RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,1*1000,1000));
#if defined(__X86_64__)
benchmarks.push_back(new create_geometry_line ("create_static_geometry_line_120_10000",RTC_SCENE_STATIC,RTC_GEOMETRY_STATIC,120,10000));
#endif
//benchmarks.push_back(new update_geometry_line ("refit_geometry_line_120", RTC_GEOMETRY_DEFORMABLE,120,1));
//benchmarks.push_back(new update_geometry_line ("refit_geometry_line_1k" , RTC_GEOMETRY_DEFORMABLE,1*1000,1));
//benchmarks.push_back(new update_geometry_line ("refit_geometry_line_10k", RTC_GEOMETRY_DEFORMABLE,10*1000,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_100k", RTC_GEOMETRY_DEFORMABLE,100*1000,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_1000k_1", RTC_GEOMETRY_DEFORMABLE,1000*1000,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_8000k_1", RTC_GEOMETRY_DEFORMABLE,1000*1000*8,1));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_100k_10", RTC_GEOMETRY_DEFORMABLE,100*1000,10));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_10k_100", RTC_GEOMETRY_DEFORMABLE,10*1000,100));
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_1k_1000" , RTC_GEOMETRY_DEFORMABLE,1*1000,1000));
#if defined(__X86_64__)
benchmarks.push_back(new update_geometry_line ("refit_geometry_line_120_10000",RTC_GEOMETRY_DEFORMABLE,120,10000));
#endif
}
Benchmark* getBenchmark(const std::string& str)
{
for (size_t i=0; i<benchmarks.size(); i++)
if (benchmarks[i]->name == str)
return benchmarks[i];
std::cout << "unknown benchmark: " << str << std::endl;
exit(1);
}
void plot_scalability()
{
Benchmark* benchmark = getBenchmark(g_plot_test);
//std::cout << "set terminal gif" << std::endl;
//std::cout << "set output\"" << benchmark->name << "\"" << std::endl;
std::cout << "set key inside right top vertical Right noreverse enhanced autotitles box linetype -1 linewidth 1.000" << std::endl;
std::cout << "set samples 50, 50" << std::endl;
std::cout << "set title \"" << benchmark->name << "\"" << std::endl;
std::cout << "set xlabel \"threads\"" << std::endl;
std::cout << "set ylabel \"" << benchmark->unit << "\"" << std::endl;
std::cout << "plot \"-\" using 0:2 title \"" << benchmark->name << "\" with lines" << std::endl;
for (size_t i=g_plot_min; i<=g_plot_max; i+= g_plot_step)
{
double pmin = inf, pmax = -float(inf), pavg = 0.0f;
size_t N = 8;
for (size_t j=0; j<N; j++) {
double p = benchmark->run(i);
pmin = min(pmin,p);
pmax = max(pmax,p);
pavg = pavg + p/double(N);
}
//std::cout << "threads = " << i << ": [" << pmin << " / " << pavg << " / " << pmax << "] " << benchmark->unit << std::endl;
std::cout << " " << i << " " << pmin << " " << pavg << " " << pmax << std::endl;
}
std::cout << "EOF" << std::endl;
}
static void parseCommandLine(int argc, char** argv)
{
for (int i=1; i<argc; i++)
{
std::string tag = argv[i];
if (tag == "") return;
/* rtcore configuration */
else if (tag == "-rtcore" && i+1<argc) {
g_rtcore = argv[++i];
}
/* plots scalability graph */
else if (tag == "-plot" && i+4<argc) {
g_plot_min = atoi(argv[++i]);
g_plot_max = atoi(argv[++i]);
g_plot_step= atoi(argv[++i]);
g_plot_test= argv[++i];
plot_scalability();
}
/* run single benchmark */
else if (tag == "-run" && i+2<argc)
{
size_t numThreads = atoi(argv[++i]);
std::string name = argv[++i];
Benchmark* benchmark = getBenchmark(name);
benchmark->print(numThreads,16);
executed_benchmarks = true;
}
else if (tag == "-threads" && i+1<argc)
{
g_num_threads_init = atoi(argv[++i]);
}
/* skip unknown command line parameter */
else {
std::cerr << "unknown command line parameter: " << tag << " ";
std::cerr << std::endl;
}
}
}
/* main function in embree namespace */
int main(int argc, char** argv)
{
/* for best performance set FTZ and DAZ flags in MXCSR control and status register */
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
create_benchmarks();
/* parse command line */
parseCommandLine(argc,argv);
if (!executed_benchmarks)
{
size_t numThreads = getNumberOfLogicalThreads();
printf("%40s ... %d \n","#HW threads ",(int)getNumberOfLogicalThreads());
#if defined (__MIC__)
numThreads -= 4;
#endif
if (g_num_threads_init != -1)
{
numThreads = g_num_threads_init;
PRINT(numThreads);
}
rtcore_intersect_benchmark(RTC_SCENE_STATIC, 501);
for (size_t i=0; i<benchmarks.size(); i++) benchmarks[i]->print(numThreads,4);
}
return 0;
}
}
int main(int argc, char** argv)
{
try {
return embree::main(argc, argv);
}
catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "Error: unknown exception caught." << std::endl;
return 1;
}
}
|
// Copyright 2013 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 "ui/app_list/app_list_folder_item.h"
#include "base/guid.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_item_list.h"
#include "ui/app_list/folder_image_source.h"
#include "ui/gfx/geometry/rect.h"
namespace app_list {
AppListFolderItem::AppListFolderItem(const std::string& id,
FolderType folder_type)
: AppListItem(id),
folder_type_(folder_type),
item_list_(new AppListItemList) {
item_list_->AddObserver(this);
}
AppListFolderItem::~AppListFolderItem() {
for (size_t i = 0; i < top_items_.size(); ++i)
top_items_[i]->RemoveObserver(this);
item_list_->RemoveObserver(this);
}
void AppListFolderItem::UpdateIcon() {
FolderImageSource::Icons top_icons;
for (size_t i = 0; i < top_items_.size(); ++i)
top_icons.push_back(top_items_[i]->icon());
const gfx::Size icon_size = gfx::Size(kGridIconDimension, kGridIconDimension);
gfx::ImageSkia icon = gfx::ImageSkia(
new FolderImageSource(top_icons, icon_size),
icon_size);
SetIcon(icon, false);
}
const gfx::ImageSkia& AppListFolderItem::GetTopIcon(size_t item_index) {
DCHECK(item_index <= top_items_.size());
return top_items_[item_index]->icon();
}
gfx::Rect AppListFolderItem::GetTargetIconRectInFolderForItem(
AppListItem* item,
const gfx::Rect& folder_icon_bounds) {
for (size_t i = 0; i < top_items_.size(); ++i) {
if (item->id() == top_items_[i]->id()) {
std::vector<gfx::Rect> rects =
FolderImageSource::GetTopIconsBounds(folder_icon_bounds);
return rects[i];
}
}
gfx::Rect target_rect(folder_icon_bounds);
target_rect.ClampToCenteredSize(FolderImageSource::ItemIconSize());
return target_rect;
}
void AppListFolderItem::Activate(int event_flags) {
// Folder handling is implemented by the View, so do nothing.
}
// static
const char AppListFolderItem::kItemType[] = "FolderItem";
const char* AppListFolderItem::GetItemType() const {
return AppListFolderItem::kItemType;
}
ui::MenuModel* AppListFolderItem::GetContextMenuModel() {
// TODO(stevenjb/jennyz): Implement.
return NULL;
}
AppListItem* AppListFolderItem::FindChildItem(const std::string& id) {
return item_list_->FindItem(id);
}
size_t AppListFolderItem::ChildItemCount() const {
return item_list_->item_count();
}
void AppListFolderItem::OnExtensionPreferenceChanged() {
for (size_t i = 0; i < item_list_->item_count(); ++i)
item_list_->item_at(i)->OnExtensionPreferenceChanged();
}
bool AppListFolderItem::CompareForTest(const AppListItem* other) const {
if (!AppListItem::CompareForTest(other))
return false;
const AppListFolderItem* other_folder =
static_cast<const AppListFolderItem*>(other);
if (other_folder->item_list()->item_count() != item_list_->item_count())
return false;
for (size_t i = 0; i < item_list_->item_count(); ++i) {
if (!item_list()->item_at(i)->CompareForTest(
other_folder->item_list()->item_at(i)))
return false;
}
return true;
}
std::string AppListFolderItem::GenerateId() {
return base::GenerateGUID();
}
void AppListFolderItem::ItemIconChanged() {
UpdateIcon();
}
void AppListFolderItem::OnListItemAdded(size_t index,
AppListItem* item) {
if (index <= kNumFolderTopItems)
UpdateTopItems();
}
void AppListFolderItem::OnListItemRemoved(size_t index,
AppListItem* item) {
if (index <= kNumFolderTopItems)
UpdateTopItems();
}
void AppListFolderItem::OnListItemMoved(size_t from_index,
size_t to_index,
AppListItem* item) {
if (from_index <= kNumFolderTopItems || to_index <= kNumFolderTopItems)
UpdateTopItems();
}
void AppListFolderItem::UpdateTopItems() {
for (size_t i = 0; i < top_items_.size(); ++i)
top_items_[i]->RemoveObserver(this);
top_items_.clear();
for (size_t i = 0;
i < kNumFolderTopItems && i < item_list_->item_count(); ++i) {
AppListItem* item = item_list_->item_at(i);
item->AddObserver(this);
top_items_.push_back(item);
}
UpdateIcon();
}
} // namespace app_list
App list folder icons: Fixed off-by-one error.
Not actually visible to the user. It is not supposed to regenerate the
icon if the fifth or greater item changed. Due to an off-by-one error,
it would still regenerate the icon if the fifth item changed (which is
unnecessary).
NB: Tests are incoming (which would have caught this error).
Also harden a DCHECK (fixing a similar off-by-one error, and making it
into a CHECK because it would be a security issue if it failed).
BUG=425444
Review URL: https://codereview.chromium.org/681373004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#302030}
// Copyright 2013 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 "ui/app_list/app_list_folder_item.h"
#include "base/guid.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_item_list.h"
#include "ui/app_list/folder_image_source.h"
#include "ui/gfx/geometry/rect.h"
namespace app_list {
AppListFolderItem::AppListFolderItem(const std::string& id,
FolderType folder_type)
: AppListItem(id),
folder_type_(folder_type),
item_list_(new AppListItemList) {
item_list_->AddObserver(this);
}
AppListFolderItem::~AppListFolderItem() {
for (size_t i = 0; i < top_items_.size(); ++i)
top_items_[i]->RemoveObserver(this);
item_list_->RemoveObserver(this);
}
void AppListFolderItem::UpdateIcon() {
FolderImageSource::Icons top_icons;
for (size_t i = 0; i < top_items_.size(); ++i)
top_icons.push_back(top_items_[i]->icon());
const gfx::Size icon_size = gfx::Size(kGridIconDimension, kGridIconDimension);
gfx::ImageSkia icon = gfx::ImageSkia(
new FolderImageSource(top_icons, icon_size),
icon_size);
SetIcon(icon, false);
}
const gfx::ImageSkia& AppListFolderItem::GetTopIcon(size_t item_index) {
CHECK_LT(item_index, top_items_.size());
return top_items_[item_index]->icon();
}
gfx::Rect AppListFolderItem::GetTargetIconRectInFolderForItem(
AppListItem* item,
const gfx::Rect& folder_icon_bounds) {
for (size_t i = 0; i < top_items_.size(); ++i) {
if (item->id() == top_items_[i]->id()) {
std::vector<gfx::Rect> rects =
FolderImageSource::GetTopIconsBounds(folder_icon_bounds);
return rects[i];
}
}
gfx::Rect target_rect(folder_icon_bounds);
target_rect.ClampToCenteredSize(FolderImageSource::ItemIconSize());
return target_rect;
}
void AppListFolderItem::Activate(int event_flags) {
// Folder handling is implemented by the View, so do nothing.
}
// static
const char AppListFolderItem::kItemType[] = "FolderItem";
const char* AppListFolderItem::GetItemType() const {
return AppListFolderItem::kItemType;
}
ui::MenuModel* AppListFolderItem::GetContextMenuModel() {
// TODO(stevenjb/jennyz): Implement.
return NULL;
}
AppListItem* AppListFolderItem::FindChildItem(const std::string& id) {
return item_list_->FindItem(id);
}
size_t AppListFolderItem::ChildItemCount() const {
return item_list_->item_count();
}
void AppListFolderItem::OnExtensionPreferenceChanged() {
for (size_t i = 0; i < item_list_->item_count(); ++i)
item_list_->item_at(i)->OnExtensionPreferenceChanged();
}
bool AppListFolderItem::CompareForTest(const AppListItem* other) const {
if (!AppListItem::CompareForTest(other))
return false;
const AppListFolderItem* other_folder =
static_cast<const AppListFolderItem*>(other);
if (other_folder->item_list()->item_count() != item_list_->item_count())
return false;
for (size_t i = 0; i < item_list_->item_count(); ++i) {
if (!item_list()->item_at(i)->CompareForTest(
other_folder->item_list()->item_at(i)))
return false;
}
return true;
}
std::string AppListFolderItem::GenerateId() {
return base::GenerateGUID();
}
void AppListFolderItem::ItemIconChanged() {
UpdateIcon();
}
void AppListFolderItem::OnListItemAdded(size_t index,
AppListItem* item) {
if (index < kNumFolderTopItems)
UpdateTopItems();
}
void AppListFolderItem::OnListItemRemoved(size_t index,
AppListItem* item) {
if (index < kNumFolderTopItems)
UpdateTopItems();
}
void AppListFolderItem::OnListItemMoved(size_t from_index,
size_t to_index,
AppListItem* item) {
if (from_index < kNumFolderTopItems || to_index < kNumFolderTopItems)
UpdateTopItems();
}
void AppListFolderItem::UpdateTopItems() {
for (size_t i = 0; i < top_items_.size(); ++i)
top_items_[i]->RemoveObserver(this);
top_items_.clear();
for (size_t i = 0;
i < kNumFolderTopItems && i < item_list_->item_count(); ++i) {
AppListItem* item = item_list_->item_at(i);
item->AddObserver(this);
top_items_.push_back(item);
}
UpdateIcon();
}
} // namespace app_list
|
// 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 "ui/app_list/views/apps_grid_view.h"
#include <algorithm>
#include <set>
#include <string>
#include "base/guid.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_folder_item.h"
#include "ui/app_list/app_list_item.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/pagination_controller.h"
#include "ui/app_list/views/app_list_drag_and_drop_host.h"
#include "ui/app_list/views/app_list_folder_view.h"
#include "ui/app_list/views/app_list_item_view.h"
#include "ui/app_list/views/apps_grid_view_delegate.h"
#include "ui/app_list/views/page_switcher.h"
#include "ui/app_list/views/pulsing_block_view.h"
#include "ui/app_list/views/top_icon_animation_view.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/events/event.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
#include "ui/views/border.h"
#include "ui/views/view_model_utils.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#if defined(OS_WIN)
#include "ui/views/win/hwnd_util.h"
#endif // defined(OS_WIN)
#endif // defined(USE_AURA)
#if defined(OS_WIN)
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/win/shortcut.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/drop_target_win.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#include "ui/gfx/win/dpi.h"
#endif
namespace app_list {
namespace {
// Distance a drag needs to be from the app grid to be considered 'outside', at
// which point we rearrange the apps to their pre-drag configuration, as a drop
// then would be canceled. We have a buffer to make it easier to drag apps to
// other pages.
const int kDragBufferPx = 20;
// Padding space in pixels for fixed layout.
const int kLeftRightPadding = 20;
const int kTopPadding = 1;
const int kBottomPadding = 24;
// Padding space in pixels between pages.
const int kPagePadding = 40;
// Preferred tile size when showing in fixed layout.
const int kPreferredTileWidth = 88;
const int kPreferredTileHeight = 98;
// Width in pixels of the area on the sides that triggers a page flip.
const int kPageFlipZoneSize = 40;
// Delay in milliseconds to do the page flip.
const int kPageFlipDelayInMs = 1000;
// How many pages on either side of the selected one we prerender.
const int kPrerenderPages = 1;
// The drag and drop proxy should get scaled by this factor.
const float kDragAndDropProxyScale = 1.5f;
// Delays in milliseconds to show folder dropping preview circle.
const int kFolderDroppingDelay = 150;
// Delays in milliseconds to show re-order preview.
const int kReorderDelay = 120;
// Delays in milliseconds to show folder item reparent UI.
const int kFolderItemReparentDelay = 50;
// Radius of the circle, in which if entered, show folder dropping preview
// UI.
const int kFolderDroppingCircleRadius = 15;
// RowMoveAnimationDelegate is used when moving an item into a different row.
// Before running the animation, the item's layer is re-created and kept in
// the original position, then the item is moved to just before its target
// position and opacity set to 0. When the animation runs, this delegate moves
// the layer and fades it out while fading in the item at the same time.
class RowMoveAnimationDelegate : public gfx::AnimationDelegate {
public:
RowMoveAnimationDelegate(views::View* view,
ui::Layer* layer,
const gfx::Rect& layer_target)
: view_(view),
layer_(layer),
layer_start_(layer ? layer->bounds() : gfx::Rect()),
layer_target_(layer_target) {
}
virtual ~RowMoveAnimationDelegate() {}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
if (layer_) {
layer_->SetOpacity(1 - animation->GetCurrentValue());
layer_->SetBounds(animation->CurrentValueBetween(layer_start_,
layer_target_));
layer_->ScheduleDraw();
}
}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->SchedulePaint();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->SchedulePaint();
}
private:
// The view that needs to be wrapped. Owned by views hierarchy.
views::View* view_;
scoped_ptr<ui::Layer> layer_;
const gfx::Rect layer_start_;
const gfx::Rect layer_target_;
DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate);
};
// ItemRemoveAnimationDelegate is used to show animation for removing an item.
// This happens when user drags an item into a folder. The dragged item will
// be removed from the original list after it is dropped into the folder.
class ItemRemoveAnimationDelegate : public gfx::AnimationDelegate {
public:
explicit ItemRemoveAnimationDelegate(views::View* view)
: view_(view) {
}
virtual ~ItemRemoveAnimationDelegate() {
}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
}
private:
scoped_ptr<views::View> view_;
DISALLOW_COPY_AND_ASSIGN(ItemRemoveAnimationDelegate);
};
// ItemMoveAnimationDelegate observes when an item finishes animating when it is
// not moving between rows. This is to ensure an item is repainted for the
// "zoom out" case when releasing an item being dragged.
class ItemMoveAnimationDelegate : public gfx::AnimationDelegate {
public:
ItemMoveAnimationDelegate(views::View* view) : view_(view) {}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->SchedulePaint();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->SchedulePaint();
}
private:
views::View* view_;
DISALLOW_COPY_AND_ASSIGN(ItemMoveAnimationDelegate);
};
// Gets the distance between the centers of the |rect_1| and |rect_2|.
int GetDistanceBetweenRects(gfx::Rect rect_1,
gfx::Rect rect_2) {
return (rect_1.CenterPoint() - rect_2.CenterPoint()).Length();
}
// Returns true if the |item| is an folder item.
bool IsFolderItem(AppListItem* item) {
return (item->GetItemType() == AppListFolderItem::kItemType);
}
bool IsOEMFolderItem(AppListItem* item) {
return IsFolderItem(item) &&
(static_cast<AppListFolderItem*>(item))->folder_type() ==
AppListFolderItem::FOLDER_TYPE_OEM;
}
} // namespace
#if defined(OS_WIN)
// Interprets drag events sent from Windows via the drag/drop API and forwards
// them to AppsGridView.
// On Windows, in order to have the OS perform the drag properly we need to
// provide it with a shortcut file which may or may not exist at the time the
// drag is started. Therefore while waiting for that shortcut to be located we
// just do a regular "internal" drag and transition into the synchronous drag
// when the shortcut is found/created. Hence a synchronous drag is an optional
// phase of a regular drag and non-Windows platforms drags are equivalent to a
// Windows drag that never enters the synchronous drag phase.
class SynchronousDrag : public ui::DragSourceWin {
public:
SynchronousDrag(AppsGridView* grid_view,
AppListItemView* drag_view,
const gfx::Point& drag_view_offset)
: grid_view_(grid_view),
drag_view_(drag_view),
drag_view_offset_(drag_view_offset),
has_shortcut_path_(false),
running_(false),
canceled_(false) {}
void set_shortcut_path(const base::FilePath& shortcut_path) {
has_shortcut_path_ = true;
shortcut_path_ = shortcut_path;
}
bool running() { return running_; }
bool CanRun() {
return has_shortcut_path_ && !running_;
}
void Run() {
DCHECK(CanRun());
// Prevent the synchronous dragger being destroyed while the drag is
// running.
scoped_refptr<SynchronousDrag> this_ref = this;
running_ = true;
ui::OSExchangeData data;
SetupExchangeData(&data);
// Hide the dragged view because the OS is going to create its own.
drag_view_->SetVisible(false);
// Blocks until the drag is finished. Calls into the ui::DragSourceWin
// methods.
DWORD effects;
DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects);
// If |drag_view_| is NULL the drag was ended by some reentrant code.
if (drag_view_) {
// Make the drag view visible again.
drag_view_->SetVisible(true);
drag_view_->OnSyncDragEnd();
grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView());
}
}
void EndDragExternally() {
CancelDrag();
DCHECK(drag_view_);
drag_view_->SetVisible(true);
drag_view_ = NULL;
}
private:
// Overridden from ui::DragSourceWin.
virtual void OnDragSourceCancel() OVERRIDE {
canceled_ = true;
}
virtual void OnDragSourceDrop() OVERRIDE {
}
virtual void OnDragSourceMove() OVERRIDE {
grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords());
}
void SetupExchangeData(ui::OSExchangeData* data) {
data->SetFilename(shortcut_path_);
gfx::ImageSkia image(drag_view_->GetDragImage());
gfx::Size image_size(image.size());
drag_utils::SetDragImageOnDataObject(
image,
drag_view_offset_ - drag_view_->GetDragImageOffset(),
data);
}
HWND GetGridViewHWND() {
return views::HWNDForView(grid_view_);
}
bool IsCursorWithinGridView() {
POINT p;
GetCursorPos(&p);
return GetGridViewHWND() == WindowFromPoint(p);
}
gfx::Point GetCursorInGridViewCoords() {
POINT p;
GetCursorPos(&p);
ScreenToClient(GetGridViewHWND(), &p);
gfx::Point grid_view_pt(p.x, p.y);
grid_view_pt = gfx::win::ScreenToDIPPoint(grid_view_pt);
views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt);
return grid_view_pt;
}
AppsGridView* grid_view_;
AppListItemView* drag_view_;
gfx::Point drag_view_offset_;
bool has_shortcut_path_;
base::FilePath shortcut_path_;
bool running_;
bool canceled_;
DISALLOW_COPY_AND_ASSIGN(SynchronousDrag);
};
#endif // defined(OS_WIN)
AppsGridView::AppsGridView(AppsGridViewDelegate* delegate)
: model_(NULL),
item_list_(NULL),
delegate_(delegate),
folder_delegate_(NULL),
page_switcher_view_(NULL),
cols_(0),
rows_per_page_(0),
selected_view_(NULL),
drag_view_(NULL),
drag_start_page_(-1),
#if defined(OS_WIN)
use_synchronous_drag_(true),
#endif
drag_pointer_(NONE),
drop_attempt_(DROP_FOR_NONE),
drag_and_drop_host_(NULL),
forward_events_to_drag_and_drop_host_(false),
page_flip_target_(-1),
page_flip_delay_in_ms_(kPageFlipDelayInMs),
bounds_animator_(this),
activated_folder_item_view_(NULL),
dragging_for_reparent_item_(false) {
SetPaintToLayer(true);
// Clip any icons that are outside the grid view's bounds. These icons would
// otherwise be visible to the user when the grid view is off screen.
layer()->SetMasksToBounds(true);
SetFillsBoundsOpaquely(false);
pagination_model_.SetTransitionDurations(kPageTransitionDurationInMs,
kOverscrollPageTransitionDurationMs);
pagination_model_.AddObserver(this);
// The experimental app list transitions vertically.
PaginationController::ScrollAxis scroll_axis =
app_list::switches::IsExperimentalAppListEnabled()
? PaginationController::SCROLL_AXIS_VERTICAL
: PaginationController::SCROLL_AXIS_HORIZONTAL;
pagination_controller_.reset(
new PaginationController(&pagination_model_, scroll_axis));
if (!switches::IsExperimentalAppListEnabled()) {
page_switcher_view_ = new PageSwitcher(&pagination_model_);
AddChildView(page_switcher_view_);
}
}
AppsGridView::~AppsGridView() {
// Coming here |drag_view_| should already be canceled since otherwise the
// drag would disappear after the app list got animated away and closed,
// which would look odd.
DCHECK(!drag_view_);
if (drag_view_)
EndDrag(true);
if (model_)
model_->RemoveObserver(this);
pagination_model_.RemoveObserver(this);
if (item_list_)
item_list_->RemoveObserver(this);
// Make sure |page_switcher_view_| is deleted before |pagination_model_|.
view_model_.Clear();
RemoveAllChildViews(true);
}
void AppsGridView::SetLayout(int cols, int rows_per_page) {
cols_ = cols;
rows_per_page_ = rows_per_page;
SetBorder(views::Border::CreateEmptyBorder(
kTopPadding, kLeftRightPadding, 0, kLeftRightPadding));
}
void AppsGridView::ResetForShowApps() {
activated_folder_item_view_ = NULL;
ClearDragState();
layer()->SetOpacity(1.0f);
SetVisible(true);
// Set all views to visible in case they weren't made visible again by an
// incomplete animation.
for (int i = 0; i < view_model_.view_size(); ++i) {
view_model_.view_at(i)->SetVisible(true);
}
CHECK_EQ(item_list_->item_count(),
static_cast<size_t>(view_model_.view_size()));
}
void AppsGridView::SetModel(AppListModel* model) {
if (model_)
model_->RemoveObserver(this);
model_ = model;
if (model_)
model_->AddObserver(this);
Update();
}
void AppsGridView::SetItemList(AppListItemList* item_list) {
if (item_list_)
item_list_->RemoveObserver(this);
item_list_ = item_list;
if (item_list_)
item_list_->AddObserver(this);
Update();
}
void AppsGridView::SetSelectedView(views::View* view) {
if (IsSelectedView(view) || IsDraggedView(view))
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
SetSelectedItemByIndex(index);
}
void AppsGridView::ClearSelectedView(views::View* view) {
if (view && IsSelectedView(view)) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
void AppsGridView::ClearAnySelectedView() {
if (selected_view_) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
bool AppsGridView::IsSelectedView(const views::View* view) const {
return selected_view_ == view;
}
void AppsGridView::EnsureViewVisible(const views::View* view) {
if (pagination_model_.has_transition())
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
pagination_model_.SelectPage(index.page, false);
}
void AppsGridView::InitiateDrag(AppListItemView* view,
Pointer pointer,
const ui::LocatedEvent& event) {
DCHECK(view);
if (drag_view_ || pulsing_blocks_model_.view_size())
return;
drag_view_ = view;
drag_view_init_index_ = GetIndexOfView(drag_view_);
drag_view_offset_ = event.location();
drag_start_page_ = pagination_model_.selected_page();
ExtractDragLocation(event, &drag_start_grid_view_);
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
}
void AppsGridView::StartSettingUpSynchronousDrag() {
#if defined(OS_WIN)
if (!delegate_ || !use_synchronous_drag_)
return;
// Folders and downloading items can't be integrated with the OS.
if (IsFolderItem(drag_view_->item()) || drag_view_->item()->is_installing())
return;
// Favor the drag and drop host over native win32 drag. For the Win8/ash
// launcher we want to have ashes drag and drop over win32's.
if (drag_and_drop_host_)
return;
// Never create a second synchronous drag if the drag started in a folder.
if (IsDraggingForReparentInRootLevelGridView())
return;
synchronous_drag_ = new SynchronousDrag(this, drag_view_, drag_view_offset_);
delegate_->GetShortcutPathForApp(drag_view_->item()->id(),
base::Bind(&AppsGridView::OnGotShortcutPath,
base::Unretained(this),
synchronous_drag_));
#endif
}
bool AppsGridView::RunSynchronousDrag() {
#if defined(OS_WIN)
if (!synchronous_drag_)
return false;
if (synchronous_drag_->CanRun()) {
if (IsDraggingForReparentInHiddenGridView())
folder_delegate_->SetRootLevelDragViewVisible(false);
synchronous_drag_->Run();
synchronous_drag_ = NULL;
return true;
} else if (!synchronous_drag_->running()) {
// The OS drag is not ready yet. If the root grid has a drag view because
// a reparent has started, ensure it is visible.
if (IsDraggingForReparentInHiddenGridView())
folder_delegate_->SetRootLevelDragViewVisible(true);
}
#endif
return false;
}
void AppsGridView::CleanUpSynchronousDrag() {
#if defined(OS_WIN)
if (synchronous_drag_)
synchronous_drag_->EndDragExternally();
synchronous_drag_ = NULL;
#endif
}
#if defined(OS_WIN)
void AppsGridView::OnGotShortcutPath(
scoped_refptr<SynchronousDrag> synchronous_drag,
const base::FilePath& path) {
// Drag may have ended before we get the shortcut path or a new drag may have
// begun.
if (synchronous_drag_ != synchronous_drag)
return;
// Setting the shortcut path here means the next time we hit UpdateDrag()
// we'll enter the synchronous drag.
// NOTE we don't Run() the drag here because that causes animations not to
// update for some reason.
synchronous_drag_->set_shortcut_path(path);
DCHECK(synchronous_drag_->CanRun());
}
#endif
bool AppsGridView::UpdateDragFromItem(Pointer pointer,
const ui::LocatedEvent& event) {
if (!drag_view_)
return false; // Drag canceled.
gfx::Point drag_point_in_grid_view;
ExtractDragLocation(event, &drag_point_in_grid_view);
UpdateDrag(pointer, drag_point_in_grid_view);
if (!dragging())
return false;
// If a drag and drop host is provided, see if the drag operation needs to be
// forwarded.
gfx::Point location_in_screen = drag_point_in_grid_view;
views::View::ConvertPointToScreen(this, &location_in_screen);
DispatchDragEventToDragAndDropHost(location_in_screen);
if (drag_and_drop_host_)
drag_and_drop_host_->UpdateDragIconProxy(location_in_screen);
return true;
}
void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) {
if (folder_delegate_)
UpdateDragStateInsideFolder(pointer, point);
if (!drag_view_)
return; // Drag canceled.
if (RunSynchronousDrag())
return;
gfx::Vector2d drag_vector(point - drag_start_grid_view_);
if (!dragging() && ExceededDragThreshold(drag_vector)) {
drag_pointer_ = pointer;
// Move the view to the front so that it appears on top of other views.
ReorderChildView(drag_view_, -1);
bounds_animator_.StopAnimatingView(drag_view_);
// Stopping the animation may have invalidated our drag view due to the
// view hierarchy changing.
if (!drag_view_)
return;
StartSettingUpSynchronousDrag();
if (!dragging_for_reparent_item_)
StartDragAndDropHostDrag(point);
}
if (drag_pointer_ != pointer)
return;
last_drag_point_ = point;
const Index last_drop_target = drop_target_;
DropAttempt last_drop_attempt = drop_attempt_;
CalculateDropTarget(last_drag_point_, false);
if (IsPointWithinDragBuffer(last_drag_point_))
MaybeStartPageFlipTimer(last_drag_point_);
else
StopPageFlipTimer();
if (page_switcher_view_) {
gfx::Point page_switcher_point(last_drag_point_);
views::View::ConvertPointToTarget(
this, page_switcher_view_, &page_switcher_point);
page_switcher_view_->UpdateUIForDragPoint(page_switcher_point);
}
if (!EnableFolderDragDropUI()) {
if (last_drop_target != drop_target_)
AnimateToIdealBounds();
drag_view_->SetPosition(drag_view_start_ + drag_vector);
return;
}
// Update drag with folder UI enabled.
if (last_drop_target != drop_target_ ||
last_drop_attempt != drop_attempt_) {
if (drop_attempt_ == DROP_FOR_REORDER) {
folder_dropping_timer_.Stop();
reorder_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kReorderDelay),
this, &AppsGridView::OnReorderTimer);
} else if (drop_attempt_ == DROP_FOR_FOLDER) {
reorder_timer_.Stop();
folder_dropping_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kFolderDroppingDelay),
this, &AppsGridView::OnFolderDroppingTimer);
}
// Reset the previous drop target.
SetAsFolderDroppingTarget(last_drop_target, false);
}
drag_view_->SetPosition(drag_view_start_ + drag_vector);
}
void AppsGridView::EndDrag(bool cancel) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
// Coming here a drag and drop was in progress.
bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_;
if (forward_events_to_drag_and_drop_host_) {
DCHECK(!IsDraggingForReparentInRootLevelGridView());
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(cancel);
if (IsDraggingForReparentInHiddenGridView()) {
folder_delegate_->DispatchEndDragEventForReparent(
true /* events_forwarded_to_drag_drop_host */,
cancel /* cancel_drag */);
}
} else {
if (IsDraggingForReparentInHiddenGridView()) {
// Forward the EndDrag event to the root level grid view.
folder_delegate_->DispatchEndDragEventForReparent(
false /* events_forwarded_to_drag_drop_host */,
cancel /* cancel_drag */);
EndDragForReparentInHiddenFolderGridView();
return;
}
if (IsDraggingForReparentInRootLevelGridView()) {
// An EndDrag can be received during a reparent via a model change. This
// is always a cancel and needs to be forwarded to the folder.
DCHECK(cancel);
delegate_->CancelDragInActiveFolder();
return;
}
if (!cancel && dragging()) {
// Regular drag ending path, ie, not for reparenting.
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_)) {
if (!EnableFolderDragDropUI()) {
MoveItemInModel(drag_view_, drop_target_);
} else {
if (drop_attempt_ == DROP_FOR_REORDER)
MoveItemInModel(drag_view_, drop_target_);
else if (drop_attempt_ == DROP_FOR_FOLDER)
MoveItemToFolder(drag_view_, drop_target_);
}
}
}
}
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
if (landed_in_drag_and_drop_host) {
// Move the item directly to the target location, avoiding the "zip back"
// animation if the user was pinning it to the shelf.
int i = drop_target_.slot;
gfx::Rect bounds = view_model_.ideal_bounds(i);
drag_view_->SetBoundsRect(bounds);
}
// Fade in slowly if it landed in the shelf.
SetViewHidden(drag_view_,
false /* show */,
!landed_in_drag_and_drop_host /* animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
ClearDragState();
AnimateToIdealBounds();
StopPageFlipTimer();
// If user releases mouse inside a folder's grid view, burst the folder
// container ink bubble.
if (folder_delegate_ && !IsDraggingForReparentInHiddenGridView())
folder_delegate_->UpdateFolderViewBackground(false);
}
void AppsGridView::StopPageFlipTimer() {
page_flip_timer_.Stop();
page_flip_target_ = -1;
}
AppListItemView* AppsGridView::GetItemViewAt(int index) const {
DCHECK(index >= 0 && index < view_model_.view_size());
return static_cast<AppListItemView*>(view_model_.view_at(index));
}
void AppsGridView::SetTopItemViewsVisible(bool visible) {
int top_item_count = std::min(static_cast<int>(kNumFolderTopItems),
view_model_.view_size());
for (int i = 0; i < top_item_count; ++i)
GetItemViewAt(i)->icon()->SetVisible(visible);
}
void AppsGridView::ScheduleShowHideAnimation(bool show) {
// Stop any previous animation.
layer()->GetAnimator()->StopAnimating();
// Set initial state.
SetVisible(true);
layer()->SetOpacity(show ? 0.0f : 1.0f);
ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator());
animation.AddObserver(this);
animation.SetTweenType(
show ? kFolderFadeInTweenType : kFolderFadeOutTweenType);
animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
show ? kFolderTransitionInDurationMs : kFolderTransitionOutDurationMs));
layer()->SetOpacity(show ? 1.0f : 0.0f);
}
void AppsGridView::InitiateDragFromReparentItemInRootLevelGridView(
AppListItemView* original_drag_view,
const gfx::Rect& drag_view_rect,
const gfx::Point& drag_point) {
DCHECK(original_drag_view && !drag_view_);
DCHECK(!dragging_for_reparent_item_);
// Create a new AppListItemView to duplicate the original_drag_view in the
// folder's grid view.
AppListItemView* view = new AppListItemView(this, original_drag_view->item());
AddChildView(view);
drag_view_ = view;
drag_view_->SetPaintToLayer(true);
// Note: For testing purpose, SetFillsBoundsOpaquely can be set to true to
// show the gray background.
drag_view_->SetFillsBoundsOpaquely(false);
drag_view_->SetBoundsRect(drag_view_rect);
drag_view_->SetDragUIState(); // Hide the title of the drag_view_.
// Hide the drag_view_ for drag icon proxy.
SetViewHidden(drag_view_,
true /* hide */,
true /* no animate */);
// Add drag_view_ to the end of the view_model_.
view_model_.Add(drag_view_, view_model_.view_size());
drag_start_page_ = pagination_model_.selected_page();
drag_start_grid_view_ = drag_point;
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
// Set the flag in root level grid view.
dragging_for_reparent_item_ = true;
}
void AppsGridView::UpdateDragFromReparentItem(Pointer pointer,
const gfx::Point& drag_point) {
// Note that if a cancel ocurrs while reparenting, the |drag_view_| in both
// root and folder grid views is cleared, so the check in UpdateDragFromItem()
// for |drag_view_| being NULL (in the folder grid) is sufficient.
DCHECK(drag_view_);
DCHECK(IsDraggingForReparentInRootLevelGridView());
UpdateDrag(pointer, drag_point);
}
bool AppsGridView::IsDraggedView(const views::View* view) const {
return drag_view_ == view;
}
void AppsGridView::ClearDragState() {
drop_attempt_ = DROP_FOR_NONE;
drag_pointer_ = NONE;
drop_target_ = Index();
drag_start_grid_view_ = gfx::Point();
drag_start_page_ = -1;
drag_view_offset_ = gfx::Point();
if (drag_view_) {
drag_view_->OnDragEnded();
if (IsDraggingForReparentInRootLevelGridView()) {
const int drag_view_index = view_model_.GetIndexOfView(drag_view_);
CHECK_EQ(view_model_.view_size() - 1, drag_view_index);
DeleteItemViewAtIndex(drag_view_index);
}
}
drag_view_ = NULL;
dragging_for_reparent_item_ = false;
}
void AppsGridView::SetDragViewVisible(bool visible) {
DCHECK(drag_view_);
SetViewHidden(drag_view_, !visible, true);
}
void AppsGridView::SetDragAndDropHostOfCurrentAppList(
ApplicationDragAndDropHost* drag_and_drop_host) {
drag_and_drop_host_ = drag_and_drop_host;
}
void AppsGridView::Prerender() {
Layout();
int selected_page = std::max(0, pagination_model_.selected_page());
int start = std::max(0, (selected_page - kPrerenderPages) * tiles_per_page());
int end = std::min(view_model_.view_size(),
(selected_page + 1 + kPrerenderPages) * tiles_per_page());
for (int i = start; i < end; i++) {
AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i));
v->Prerender();
}
}
bool AppsGridView::IsAnimatingView(views::View* view) {
return bounds_animator_.IsAnimating(view);
}
gfx::Size AppsGridView::GetPreferredSize() const {
const gfx::Insets insets(GetInsets());
const gfx::Size tile_size = gfx::Size(kPreferredTileWidth,
kPreferredTileHeight);
int page_switcher_height = kBottomPadding;
if (page_switcher_view_)
page_switcher_height = page_switcher_view_->GetPreferredSize().height();
return gfx::Size(
tile_size.width() * cols_ + insets.width(),
tile_size.height() * rows_per_page_ +
page_switcher_height + insets.height());
}
bool AppsGridView::GetDropFormats(
int* formats,
std::set<OSExchangeData::CustomFormat>* custom_formats) {
// TODO(koz): Only accept a specific drag type for app shortcuts.
*formats = OSExchangeData::FILE_NAME;
return true;
}
bool AppsGridView::CanDrop(const OSExchangeData& data) {
return true;
}
int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_MOVE;
}
void AppsGridView::Layout() {
if (bounds_animator_.IsAnimating())
bounds_animator_.Cancel();
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view != drag_view_)
view->SetBoundsRect(view_model_.ideal_bounds(i));
}
views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_);
if (page_switcher_view_) {
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
gfx::Rect rect(GetContentsBounds());
rect.set_y(rect.bottom() - page_switcher_height);
rect.set_height(page_switcher_height);
page_switcher_view_->SetBoundsRect(rect);
}
}
bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyPressed(event);
if (!handled) {
const int forward_dir = base::i18n::IsRTL() ? -1 : 1;
switch (event.key_code()) {
case ui::VKEY_LEFT:
MoveSelected(0, -forward_dir, 0);
return true;
case ui::VKEY_RIGHT:
MoveSelected(0, forward_dir, 0);
return true;
case ui::VKEY_UP:
MoveSelected(0, 0, -1);
return true;
case ui::VKEY_DOWN:
MoveSelected(0, 0, 1);
return true;
case ui::VKEY_PRIOR: {
MoveSelected(-1, 0, 0);
return true;
}
case ui::VKEY_NEXT: {
MoveSelected(1, 0, 0);
return true;
}
default:
break;
}
}
return handled;
}
bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyReleased(event);
return handled;
}
bool AppsGridView::OnMouseWheel(const ui::MouseWheelEvent& event) {
return pagination_controller_->OnScroll(
gfx::Vector2d(event.x_offset(), event.y_offset()));
}
void AppsGridView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (!details.is_add && details.parent == this) {
// The view being delete should not have reference in |view_model_|.
CHECK_EQ(-1, view_model_.GetIndexOfView(details.child));
if (selected_view_ == details.child)
selected_view_ = NULL;
if (activated_folder_item_view_ == details.child)
activated_folder_item_view_ = NULL;
if (drag_view_ == details.child)
EndDrag(true);
bounds_animator_.StopAnimatingView(details.child);
}
}
void AppsGridView::OnGestureEvent(ui::GestureEvent* event) {
if (pagination_controller_->OnGestureEvent(*event, GetContentsBounds()))
event->SetHandled();
}
void AppsGridView::OnScrollEvent(ui::ScrollEvent* event) {
if (event->type() == ui::ET_SCROLL_FLING_CANCEL)
return;
gfx::Vector2dF offset(event->x_offset(), event->y_offset());
if (pagination_controller_->OnScroll(gfx::ToFlooredVector2d(offset))) {
event->SetHandled();
event->StopPropagation();
}
}
void AppsGridView::Update() {
DCHECK(!selected_view_ && !drag_view_);
view_model_.Clear();
if (!item_list_ || !item_list_->item_count())
return;
for (size_t i = 0; i < item_list_->item_count(); ++i) {
views::View* view = CreateViewForItemAtIndex(i);
view_model_.Add(view, i);
AddChildView(view);
}
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::UpdatePaging() {
int total_page = view_model_.view_size() && tiles_per_page()
? (view_model_.view_size() - 1) / tiles_per_page() + 1
: 0;
pagination_model_.SetTotalPages(total_page);
}
void AppsGridView::UpdatePulsingBlockViews() {
const int existing_items = item_list_ ? item_list_->item_count() : 0;
const int available_slots =
tiles_per_page() - existing_items % tiles_per_page();
const int desired = model_->status() == AppListModel::STATUS_SYNCING ?
available_slots : 0;
if (pulsing_blocks_model_.view_size() == desired)
return;
while (pulsing_blocks_model_.view_size() > desired) {
views::View* view = pulsing_blocks_model_.view_at(0);
pulsing_blocks_model_.Remove(0);
delete view;
}
while (pulsing_blocks_model_.view_size() < desired) {
views::View* view = new PulsingBlockView(
gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true);
pulsing_blocks_model_.Add(view, 0);
AddChildView(view);
}
}
views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) {
// The drag_view_ might be pending for deletion, therefore view_model_
// may have one more item than item_list_.
DCHECK_LE(index, item_list_->item_count());
AppListItemView* view = new AppListItemView(this,
item_list_->item_at(index));
view->SetPaintToLayer(true);
view->SetFillsBoundsOpaquely(false);
return view;
}
AppsGridView::Index AppsGridView::GetIndexFromModelIndex(
int model_index) const {
return Index(model_index / tiles_per_page(), model_index % tiles_per_page());
}
int AppsGridView::GetModelIndexFromIndex(const Index& index) const {
return index.page * tiles_per_page() + index.slot;
}
void AppsGridView::SetSelectedItemByIndex(const Index& index) {
if (GetIndexOfView(selected_view_) == index)
return;
views::View* new_selection = GetViewAtIndex(index);
if (!new_selection)
return; // Keep current selection.
if (selected_view_)
selected_view_->SchedulePaint();
EnsureViewVisible(new_selection);
selected_view_ = new_selection;
selected_view_->SchedulePaint();
selected_view_->NotifyAccessibilityEvent(
ui::AX_EVENT_FOCUS, true);
}
bool AppsGridView::IsValidIndex(const Index& index) const {
return index.page >= 0 && index.page < pagination_model_.total_pages() &&
index.slot >= 0 && index.slot < tiles_per_page() &&
GetModelIndexFromIndex(index) < view_model_.view_size();
}
AppsGridView::Index AppsGridView::GetIndexOfView(
const views::View* view) const {
const int model_index = view_model_.GetIndexOfView(view);
if (model_index == -1)
return Index();
return GetIndexFromModelIndex(model_index);
}
views::View* AppsGridView::GetViewAtIndex(const Index& index) const {
if (!IsValidIndex(index))
return NULL;
const int model_index = GetModelIndexFromIndex(index);
return view_model_.view_at(model_index);
}
void AppsGridView::MoveSelected(int page_delta,
int slot_x_delta,
int slot_y_delta) {
if (!selected_view_)
return SetSelectedItemByIndex(Index(pagination_model_.selected_page(), 0));
const Index& selected = GetIndexOfView(selected_view_);
int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_;
if (selected.slot % cols_ == 0 && slot_x_delta == -1) {
if (selected.page > 0) {
page_delta = -1;
target_slot = selected.slot + cols_ - 1;
} else {
target_slot = selected.slot;
}
}
if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) {
if (selected.page < pagination_model_.total_pages() - 1) {
page_delta = 1;
target_slot = selected.slot - cols_ + 1;
} else {
target_slot = selected.slot;
}
}
// Clamp the target slot to the last item if we are moving to the last page
// but our target slot is past the end of the item list.
if (page_delta &&
selected.page + page_delta == pagination_model_.total_pages() - 1) {
int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page();
if (last_item_slot < target_slot) {
target_slot = last_item_slot;
}
}
int target_page = std::min(pagination_model_.total_pages() - 1,
std::max(selected.page + page_delta, 0));
SetSelectedItemByIndex(Index(target_page, target_slot));
}
void AppsGridView::CalculateIdealBounds() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(rect);
// Page size including padding pixels. A tile.x + page_width means the same
// tile slot in the next page; similarly for tile.y + page_height.
const int page_width = grid_rect.width() + kPagePadding;
const int page_height = grid_rect.height() + kPagePadding;
// If there is a transition, calculates offset for current and target page.
const int current_page = pagination_model_.selected_page();
const PaginationModel::Transition& transition =
pagination_model_.transition();
const bool is_valid = pagination_model_.is_valid_page(transition.target_page);
// Transition to previous page means negative offset.
const int dir = transition.target_page > current_page ? -1 : 1;
const int total_views =
view_model_.view_size() + pulsing_blocks_model_.view_size();
int slot_index = 0;
for (int i = 0; i < total_views; ++i) {
if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_) {
if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER)
++slot_index;
continue;
}
Index view_index = GetIndexFromModelIndex(slot_index);
if (drop_target_ == view_index) {
if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER) {
view_index = GetIndexFromModelIndex(slot_index);
} else if (!EnableFolderDragDropUI() ||
drop_attempt_ == DROP_FOR_REORDER) {
++slot_index;
view_index = GetIndexFromModelIndex(slot_index);
}
}
// Decide the x or y offset for current item.
int x_offset = 0;
int y_offset = 0;
if (pagination_controller_->scroll_axis() ==
PaginationController::SCROLL_AXIS_HORIZONTAL) {
if (view_index.page < current_page)
x_offset = -page_width;
else if (view_index.page > current_page)
x_offset = page_width;
if (is_valid) {
if (view_index.page == current_page ||
view_index.page == transition.target_page) {
x_offset += transition.progress * page_width * dir;
}
}
} else {
if (view_index.page < current_page)
y_offset = -page_height;
else if (view_index.page > current_page)
y_offset = page_height;
if (is_valid) {
if (view_index.page == current_page ||
view_index.page == transition.target_page) {
y_offset += transition.progress * page_height * dir;
}
}
}
const int row = view_index.slot / cols_;
const int col = view_index.slot % cols_;
gfx::Rect tile_slot(
gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset,
grid_rect.y() + row * tile_size.height() + y_offset),
tile_size);
if (i < view_model_.view_size()) {
view_model_.set_ideal_bounds(i, tile_slot);
} else {
pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(),
tile_slot);
}
++slot_index;
}
}
void AppsGridView::AnimateToIdealBounds() {
const gfx::Rect visible_bounds(GetVisibleBounds());
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view == drag_view_)
continue;
const gfx::Rect& target = view_model_.ideal_bounds(i);
if (bounds_animator_.GetTargetBounds(view) == target)
continue;
const gfx::Rect& current = view->bounds();
const bool current_visible = visible_bounds.Intersects(current);
const bool target_visible = visible_bounds.Intersects(target);
const bool visible = current_visible || target_visible;
const int y_diff = target.y() - current.y();
if (visible && y_diff && y_diff % kPreferredTileHeight == 0) {
AnimationBetweenRows(view,
current_visible,
current,
target_visible,
target);
} else if (visible || bounds_animator_.IsAnimating(view)) {
bounds_animator_.AnimateViewTo(view, target);
bounds_animator_.SetAnimationDelegate(
view,
scoped_ptr<gfx::AnimationDelegate>(
new ItemMoveAnimationDelegate(view)));
} else {
view->SetBoundsRect(target);
}
}
}
void AppsGridView::AnimationBetweenRows(views::View* view,
bool animate_current,
const gfx::Rect& current,
bool animate_target,
const gfx::Rect& target) {
// Determine page of |current| and |target|. -1 means in the left invisible
// page, 0 is the center visible page and 1 means in the right invisible page.
const int current_page = current.x() < 0 ? -1 :
current.x() >= width() ? 1 : 0;
const int target_page = target.x() < 0 ? -1 :
target.x() >= width() ? 1 : 0;
const int dir = current_page < target_page ||
(current_page == target_page && current.y() < target.y()) ? 1 : -1;
scoped_ptr<ui::Layer> layer;
if (animate_current) {
layer = view->RecreateLayer();
layer->SuppressPaint();
view->SetFillsBoundsOpaquely(false);
view->layer()->SetOpacity(0.f);
}
gfx::Rect current_out(current);
current_out.Offset(dir * kPreferredTileWidth, 0);
gfx::Rect target_in(target);
if (animate_target)
target_in.Offset(-dir * kPreferredTileWidth, 0);
view->SetBoundsRect(target_in);
bounds_animator_.AnimateViewTo(view, target);
bounds_animator_.SetAnimationDelegate(
view,
scoped_ptr<gfx::AnimationDelegate>(
new RowMoveAnimationDelegate(view, layer.release(), current_out)));
}
void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event,
gfx::Point* drag_point) {
#if defined(USE_AURA) && !defined(OS_WIN)
// Use root location of |event| instead of location in |drag_view_|'s
// coordinates because |drag_view_| has a scale transform and location
// could have integer round error and causes jitter.
*drag_point = event.root_location();
// GetWidget() could be NULL for tests.
if (GetWidget()) {
aura::Window::ConvertPointToTarget(
GetWidget()->GetNativeWindow()->GetRootWindow(),
GetWidget()->GetNativeWindow(),
drag_point);
}
views::View::ConvertPointFromWidget(this, drag_point);
#else
// For non-aura, root location is not clearly defined but |drag_view_| does
// not have the scale transform. So no round error would be introduced and
// it's okay to use View::ConvertPointToTarget.
*drag_point = event.location();
views::View::ConvertPointToTarget(drag_view_, this, drag_point);
#endif
}
void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point,
bool use_page_button_hovering) {
if (EnableFolderDragDropUI()) {
CalculateDropTargetWithFolderEnabled(drag_point, use_page_button_hovering);
return;
}
int current_page = pagination_model_.selected_page();
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
current_page = drag_start_page_;
}
if (use_page_button_hovering && page_switcher_view_ &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_.is_valid_page(page)) {
drop_target_.page = page;
drop_target_.slot = tiles_per_page() - 1;
}
} else {
gfx::Rect bounds(GetContentsBounds());
const int drop_row = (point.y() - bounds.y()) / kPreferredTileHeight;
const int drop_col = std::min(cols_ - 1,
(point.x() - bounds.x()) / kPreferredTileWidth);
drop_target_.page = current_page;
drop_target_.slot = std::max(0, std::min(
tiles_per_page() - 1,
drop_row * cols_ + drop_col));
}
// Limits to the last possible slot on last page.
if (drop_target_.page == pagination_model_.total_pages() - 1) {
drop_target_.slot = std::min(
(view_model_.view_size() - 1) % tiles_per_page(),
drop_target_.slot);
}
}
void AppsGridView::CalculateDropTargetWithFolderEnabled(
const gfx::Point& drag_point,
bool use_page_button_hovering) {
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
}
if (use_page_button_hovering && page_switcher_view_ &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_.is_valid_page(page))
drop_attempt_ = DROP_FOR_NONE;
} else {
DCHECK(drag_view_);
// Try to find the nearest target for folder dropping or re-ordering.
drop_target_ = GetNearestTileForDragView();
}
}
void AppsGridView::OnReorderTimer() {
if (drop_attempt_ == DROP_FOR_REORDER)
AnimateToIdealBounds();
}
void AppsGridView::OnFolderItemReparentTimer() {
DCHECK(folder_delegate_);
if (drag_out_of_folder_container_ && drag_view_) {
folder_delegate_->ReparentItem(drag_view_, last_drag_point_);
// Set the flag in the folder's grid view.
dragging_for_reparent_item_ = true;
// Do not observe any data change since it is going to be hidden.
item_list_->RemoveObserver(this);
item_list_ = NULL;
}
}
void AppsGridView::OnFolderDroppingTimer() {
if (drop_attempt_ == DROP_FOR_FOLDER)
SetAsFolderDroppingTarget(drop_target_, true);
}
void AppsGridView::UpdateDragStateInsideFolder(Pointer pointer,
const gfx::Point& drag_point) {
if (IsUnderOEMFolder())
return;
if (IsDraggingForReparentInHiddenGridView()) {
// Dispatch drag event to root level grid view for re-parenting folder
// folder item purpose.
DispatchDragEventForReparent(pointer, drag_point);
return;
}
// Regular drag and drop in a folder's grid view.
folder_delegate_->UpdateFolderViewBackground(true);
// Calculate if the drag_view_ is dragged out of the folder's container
// ink bubble.
gfx::Rect bounds_to_folder_view = ConvertRectToParent(drag_view_->bounds());
gfx::Point pt = bounds_to_folder_view.CenterPoint();
bool is_item_dragged_out_of_folder =
folder_delegate_->IsPointOutsideOfFolderBoundary(pt);
if (is_item_dragged_out_of_folder) {
if (!drag_out_of_folder_container_) {
folder_item_reparent_timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kFolderItemReparentDelay),
this,
&AppsGridView::OnFolderItemReparentTimer);
drag_out_of_folder_container_ = true;
}
} else {
folder_item_reparent_timer_.Stop();
drag_out_of_folder_container_ = false;
}
}
bool AppsGridView::IsDraggingForReparentInRootLevelGridView() const {
return (!folder_delegate_ && dragging_for_reparent_item_);
}
bool AppsGridView::IsDraggingForReparentInHiddenGridView() const {
return (folder_delegate_ && dragging_for_reparent_item_);
}
gfx::Rect AppsGridView::GetTargetIconRectInFolder(
AppListItemView* drag_item_view,
AppListItemView* folder_item_view) {
gfx::Rect view_ideal_bounds = view_model_.ideal_bounds(
view_model_.GetIndexOfView(folder_item_view));
gfx::Rect icon_ideal_bounds =
folder_item_view->GetIconBoundsForTargetViewBounds(view_ideal_bounds);
AppListFolderItem* folder_item =
static_cast<AppListFolderItem*>(folder_item_view->item());
return folder_item->GetTargetIconRectInFolderForItem(
drag_item_view->item(), icon_ideal_bounds);
}
bool AppsGridView::IsUnderOEMFolder() {
if (!folder_delegate_)
return false;
return folder_delegate_->IsOEMFolder();
}
void AppsGridView::DispatchDragEventForReparent(Pointer pointer,
const gfx::Point& drag_point) {
folder_delegate_->DispatchDragEventForReparent(pointer, drag_point);
}
void AppsGridView::EndDragFromReparentItemInRootLevel(
bool events_forwarded_to_drag_drop_host,
bool cancel_drag) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
DCHECK(IsDraggingForReparentInRootLevelGridView());
bool cancel_reparent = cancel_drag || drop_attempt_ == DROP_FOR_NONE;
if (!events_forwarded_to_drag_drop_host && !cancel_reparent) {
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_)) {
if (drop_attempt_ == DROP_FOR_REORDER) {
ReparentItemForReorder(drag_view_, drop_target_);
} else if (drop_attempt_ == DROP_FOR_FOLDER) {
ReparentItemToAnotherFolder(drag_view_, drop_target_);
}
}
SetViewHidden(drag_view_, false /* show */, true /* no animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
if (cancel_reparent) {
CancelFolderItemReparent(drag_view_);
} else {
// By setting |drag_view_| to NULL here, we prevent ClearDragState() from
// cleaning up the newly created AppListItemView, effectively claiming
// ownership of the newly created drag view.
drag_view_->OnDragEnded();
drag_view_ = NULL;
}
ClearDragState();
AnimateToIdealBounds();
StopPageFlipTimer();
}
void AppsGridView::EndDragForReparentInHiddenFolderGridView() {
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
ClearDragState();
}
void AppsGridView::OnFolderItemRemoved() {
DCHECK(folder_delegate_);
item_list_ = NULL;
}
void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) {
// When a drag and drop host is given, the item can be dragged out of the app
// list window. In that case a proxy widget needs to be used.
// Note: This code has very likely to be changed for Windows (non metro mode)
// when a |drag_and_drop_host_| gets implemented.
if (!drag_view_ || !drag_and_drop_host_)
return;
gfx::Point screen_location = grid_location;
views::View::ConvertPointToScreen(this, &screen_location);
// Determine the mouse offset to the center of the icon so that the drag and
// drop host follows this layer.
gfx::Vector2d delta = drag_view_offset_ -
drag_view_->GetLocalBounds().CenterPoint();
delta.set_y(delta.y() + drag_view_->title()->size().height() / 2);
// We have to hide the original item since the drag and drop host will do
// the OS dependent code to "lift off the dragged item".
DCHECK(!IsDraggingForReparentInRootLevelGridView());
drag_and_drop_host_->CreateDragIconProxy(screen_location,
drag_view_->item()->icon(),
drag_view_,
delta,
kDragAndDropProxyScale);
SetViewHidden(drag_view_,
true /* hide */,
true /* no animation */);
}
void AppsGridView::DispatchDragEventToDragAndDropHost(
const gfx::Point& location_in_screen_coordinates) {
if (!drag_view_ || !drag_and_drop_host_)
return;
if (GetLocalBounds().Contains(last_drag_point_)) {
// The event was issued inside the app menu and we should get all events.
if (forward_events_to_drag_and_drop_host_) {
// The DnD host was previously called and needs to be informed that the
// session returns to the owner.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (IsFolderItem(drag_view_->item()))
return;
// The event happened outside our app menu and we might need to dispatch.
if (forward_events_to_drag_and_drop_host_) {
// Dispatch since we have already started.
if (!drag_and_drop_host_->Drag(location_in_screen_coordinates)) {
// The host is not active any longer and we cancel the operation.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (drag_and_drop_host_->StartDrag(drag_view_->item()->id(),
location_in_screen_coordinates)) {
// From now on we forward the drag events.
forward_events_to_drag_and_drop_host_ = true;
// Any flip operations are stopped.
StopPageFlipTimer();
}
}
}
}
void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) {
if (!IsPointWithinDragBuffer(drag_point))
StopPageFlipTimer();
int new_page_flip_target = -1;
if (page_switcher_view_ &&
page_switcher_view_->bounds().Contains(drag_point)) {
gfx::Point page_switcher_point(drag_point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
new_page_flip_target =
page_switcher_view_->GetPageForPoint(page_switcher_point);
}
// TODO(xiyuan): Fix this for RTL.
if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize)
new_page_flip_target = pagination_model_.selected_page() - 1;
if (new_page_flip_target == -1 &&
drag_point.x() > width() - kPageFlipZoneSize) {
new_page_flip_target = pagination_model_.selected_page() + 1;
}
if (new_page_flip_target == page_flip_target_)
return;
StopPageFlipTimer();
if (pagination_model_.is_valid_page(new_page_flip_target)) {
page_flip_target_ = new_page_flip_target;
if (page_flip_target_ != pagination_model_.selected_page()) {
page_flip_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_),
this, &AppsGridView::OnPageFlipTimer);
}
}
}
void AppsGridView::OnPageFlipTimer() {
DCHECK(pagination_model_.is_valid_page(page_flip_target_));
pagination_model_.SelectPage(page_flip_target_, true);
}
void AppsGridView::MoveItemInModel(views::View* item_view,
const Index& target) {
int current_model_index = view_model_.GetIndexOfView(item_view);
DCHECK_GE(current_model_index, 0);
int target_model_index = GetModelIndexFromIndex(target);
if (target_model_index == current_model_index)
return;
item_list_->RemoveObserver(this);
item_list_->MoveItem(current_model_index, target_model_index);
view_model_.Move(current_model_index, target_model_index);
item_list_->AddObserver(this);
if (pagination_model_.selected_page() != target.page)
pagination_model_.SelectPage(target.page, false);
}
void AppsGridView::MoveItemToFolder(views::View* item_view,
const Index& target) {
const std::string& source_item_id =
static_cast<AppListItemView*>(item_view)->item()->id();
AppListItemView* target_view =
static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot));
const std::string& target_view_item_id = target_view->item()->id();
// Make change to data model.
item_list_->RemoveObserver(this);
std::string folder_item_id =
model_->MergeItems(target_view_item_id, source_item_id);
item_list_->AddObserver(this);
if (folder_item_id.empty()) {
LOG(ERROR) << "Unable to merge into item id: " << target_view_item_id;
return;
}
if (folder_item_id != target_view_item_id) {
// New folder was created, change the view model to replace the old target
// view with the new folder item view.
size_t folder_item_index;
if (item_list_->FindItemIndex(folder_item_id, &folder_item_index)) {
int target_view_index = view_model_.GetIndexOfView(target_view);
gfx::Rect target_view_bounds = target_view->bounds();
DeleteItemViewAtIndex(target_view_index);
views::View* target_folder_view =
CreateViewForItemAtIndex(folder_item_index);
target_folder_view->SetBoundsRect(target_view_bounds);
view_model_.Add(target_folder_view, target_view_index);
AddChildView(target_folder_view);
} else {
LOG(ERROR) << "Folder no longer in item_list: " << folder_item_id;
}
}
// Fade out the drag_view_ and delete it when animation ends.
int drag_view_index = view_model_.GetIndexOfView(drag_view_);
view_model_.Remove(drag_view_index);
bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
bounds_animator_.SetAnimationDelegate(
drag_view_,
scoped_ptr<gfx::AnimationDelegate>(
new ItemRemoveAnimationDelegate(drag_view_)));
UpdatePaging();
}
void AppsGridView::ReparentItemForReorder(views::View* item_view,
const Index& target) {
item_list_->RemoveObserver(this);
model_->RemoveObserver(this);
AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item();
DCHECK(reparent_item->IsInFolder());
const std::string source_folder_id = reparent_item->folder_id();
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
int target_model_index = GetModelIndexFromIndex(target);
// Remove the source folder view if there is only 1 item in it, since the
// source folder will be deleted after its only child item removed from it.
if (source_folder->ChildItemCount() == 1u) {
const int deleted_folder_index =
view_model_.GetIndexOfView(activated_folder_item_view());
DeleteItemViewAtIndex(deleted_folder_index);
// Adjust |target_model_index| if it is beyond the deleted folder index.
if (target_model_index > deleted_folder_index)
--target_model_index;
}
// Move the item from its parent folder to top level item list.
// Must move to target_model_index, the location we expect the target item
// to be, not the item location we want to insert before.
int current_model_index = view_model_.GetIndexOfView(item_view);
syncer::StringOrdinal target_position;
if (target_model_index < static_cast<int>(item_list_->item_count()))
target_position = item_list_->item_at(target_model_index)->position();
model_->MoveItemToFolderAt(reparent_item, "", target_position);
view_model_.Move(current_model_index, target_model_index);
RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
item_list_->AddObserver(this);
model_->AddObserver(this);
UpdatePaging();
}
void AppsGridView::ReparentItemToAnotherFolder(views::View* item_view,
const Index& target) {
DCHECK(IsDraggingForReparentInRootLevelGridView());
AppListItemView* target_view =
static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot));
if (!target_view)
return;
// Make change to data model.
item_list_->RemoveObserver(this);
AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item();
DCHECK(reparent_item->IsInFolder());
const std::string source_folder_id = reparent_item->folder_id();
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
// Remove the source folder view if there is only 1 item in it, since the
// source folder will be deleted after its only child item merged into the
// target item.
if (source_folder->ChildItemCount() == 1u)
DeleteItemViewAtIndex(
view_model_.GetIndexOfView(activated_folder_item_view()));
AppListItem* target_item = target_view->item();
// Move item to the target folder.
std::string target_id_after_merge =
model_->MergeItems(target_item->id(), reparent_item->id());
if (target_id_after_merge.empty()) {
LOG(ERROR) << "Unable to reparent to item id: " << target_item->id();
item_list_->AddObserver(this);
return;
}
if (target_id_after_merge != target_item->id()) {
// New folder was created, change the view model to replace the old target
// view with the new folder item view.
const std::string& new_folder_id = reparent_item->folder_id();
size_t new_folder_index;
if (item_list_->FindItemIndex(new_folder_id, &new_folder_index)) {
int target_view_index = view_model_.GetIndexOfView(target_view);
DeleteItemViewAtIndex(target_view_index);
views::View* new_folder_view =
CreateViewForItemAtIndex(new_folder_index);
view_model_.Add(new_folder_view, target_view_index);
AddChildView(new_folder_view);
} else {
LOG(ERROR) << "Folder no longer in item_list: " << new_folder_id;
}
}
RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
item_list_->AddObserver(this);
// Fade out the drag_view_ and delete it when animation ends.
int drag_view_index = view_model_.GetIndexOfView(drag_view_);
view_model_.Remove(drag_view_index);
bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
bounds_animator_.SetAnimationDelegate(
drag_view_,
scoped_ptr<gfx::AnimationDelegate>(
new ItemRemoveAnimationDelegate(drag_view_)));
UpdatePaging();
}
// After moving the re-parenting item out of the folder, if there is only 1 item
// left, remove the last item out of the folder, delete the folder and insert it
// to the data model at the same position. Make the same change to view_model_
// accordingly.
void AppsGridView::RemoveLastItemFromReparentItemFolderIfNecessary(
const std::string& source_folder_id) {
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
if (!source_folder || source_folder->ChildItemCount() != 1u)
return;
// Delete view associated with the folder item to be removed.
DeleteItemViewAtIndex(
view_model_.GetIndexOfView(activated_folder_item_view()));
// Now make the data change to remove the folder item in model.
AppListItem* last_item = source_folder->item_list()->item_at(0);
model_->MoveItemToFolderAt(last_item, "", source_folder->position());
// Create a new item view for the last item in folder.
size_t last_item_index;
if (!item_list_->FindItemIndex(last_item->id(), &last_item_index) ||
last_item_index > static_cast<size_t>(view_model_.view_size())) {
NOTREACHED();
return;
}
views::View* last_item_view = CreateViewForItemAtIndex(last_item_index);
view_model_.Add(last_item_view, last_item_index);
AddChildView(last_item_view);
}
void AppsGridView::CancelFolderItemReparent(AppListItemView* drag_item_view) {
// The icon of the dragged item must target to its final ideal bounds after
// the animation completes.
CalculateIdealBounds();
gfx::Rect target_icon_rect =
GetTargetIconRectInFolder(drag_item_view, activated_folder_item_view_);
gfx::Rect drag_view_icon_to_grid =
drag_item_view->ConvertRectToParent(drag_item_view->GetIconBounds());
drag_view_icon_to_grid.ClampToCenteredSize(
gfx::Size(kGridIconDimension, kGridIconDimension));
TopIconAnimationView* icon_view = new TopIconAnimationView(
drag_item_view->item()->icon(),
target_icon_rect,
false); /* animate like closing folder */
AddChildView(icon_view);
icon_view->SetBoundsRect(drag_view_icon_to_grid);
icon_view->TransformView();
}
void AppsGridView::CancelContextMenusOnCurrentPage() {
int start = pagination_model_.selected_page() * tiles_per_page();
int end = std::min(view_model_.view_size(), start + tiles_per_page());
for (int i = start; i < end; ++i) {
AppListItemView* view =
static_cast<AppListItemView*>(view_model_.view_at(i));
view->CancelContextMenu();
}
}
void AppsGridView::DeleteItemViewAtIndex(int index) {
views::View* item_view = view_model_.view_at(index);
view_model_.Remove(index);
if (item_view == drag_view_)
drag_view_ = NULL;
delete item_view;
}
bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const {
gfx::Rect rect(GetLocalBounds());
rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx);
return rect.Contains(point);
}
void AppsGridView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (dragging())
return;
if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName))
return;
if (delegate_) {
// Always set the previous activated_folder_item_view_ to be visible. This
// prevents a case where the item would remain hidden due the
// |activated_folder_item_view_| changing during the animation. We only
// need to track |activated_folder_item_view_| in the root level grid view.
if (!folder_delegate_) {
if (activated_folder_item_view_)
activated_folder_item_view_->SetVisible(true);
AppListItemView* pressed_item_view =
static_cast<AppListItemView*>(sender);
if (IsFolderItem(pressed_item_view->item()))
activated_folder_item_view_ = pressed_item_view;
else
activated_folder_item_view_ = NULL;
}
delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->item(),
event.flags());
}
}
void AppsGridView::OnListItemAdded(size_t index, AppListItem* item) {
EndDrag(true);
views::View* view = CreateViewForItemAtIndex(index);
view_model_.Add(view, index);
AddChildView(view);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemRemoved(size_t index, AppListItem* item) {
EndDrag(true);
DeleteItemViewAtIndex(index);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemMoved(size_t from_index,
size_t to_index,
AppListItem* item) {
EndDrag(true);
view_model_.Move(from_index, to_index);
UpdatePaging();
AnimateToIdealBounds();
}
void AppsGridView::TotalPagesChanged() {
}
void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) {
if (dragging()) {
CalculateDropTarget(last_drag_point_, true);
Layout();
MaybeStartPageFlipTimer(last_drag_point_);
} else {
ClearSelectedView(selected_view_);
Layout();
}
}
void AppsGridView::TransitionStarted() {
CancelContextMenusOnCurrentPage();
}
void AppsGridView::TransitionChanged() {
// Update layout for valid page transition only since over-scroll no longer
// animates app icons.
const PaginationModel::Transition& transition =
pagination_model_.transition();
if (pagination_model_.is_valid_page(transition.target_page))
Layout();
}
void AppsGridView::OnAppListModelStatusChanged() {
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::SetViewHidden(views::View* view, bool hide, bool immediate) {
ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator());
animator.SetPreemptionStrategy(
immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET :
ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION);
view->layer()->SetOpacity(hide ? 0 : 1);
}
void AppsGridView::OnImplicitAnimationsCompleted() {
if (layer()->opacity() == 0.0f)
SetVisible(false);
}
bool AppsGridView::EnableFolderDragDropUI() {
// Enable drag and drop folder UI only if it is at the app list root level
// and the switch is on and the target folder can still accept new items.
return model_->folders_enabled() && !folder_delegate_ &&
CanDropIntoTarget(drop_target_);
}
bool AppsGridView::CanDropIntoTarget(const Index& drop_target) {
views::View* target_view = GetViewAtSlotOnCurrentPage(drop_target.slot);
if (!target_view)
return true;
AppListItem* target_item =
static_cast<AppListItemView*>(target_view)->item();
// Items can be dropped into non-folders (which have no children) or folders
// that have fewer than the max allowed items.
// OEM folder does not allow to drag/drop other items in it.
return target_item->ChildItemCount() < kMaxFolderItems &&
!IsOEMFolderItem(target_item);
}
// TODO(jennyz): Optimize the calculation for finding nearest tile.
AppsGridView::Index AppsGridView::GetNearestTileForDragView() {
Index nearest_tile;
nearest_tile.page = -1;
nearest_tile.slot = -1;
int d_min = -1;
// Calculate the top left tile |drag_view| intersects.
gfx::Point pt = drag_view_->bounds().origin();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the top right tile |drag_view| intersects.
pt = drag_view_->bounds().top_right();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the bottom left tile |drag_view| intersects.
pt = drag_view_->bounds().bottom_left();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the bottom right tile |drag_view| intersects.
pt = drag_view_->bounds().bottom_right();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
const int d_folder_dropping =
kFolderDroppingCircleRadius + kGridIconDimension / 2;
const int d_reorder = kReorderDroppingCircleRadius + kGridIconDimension / 2;
// If user drags an item across pages to the last page, and targets it
// to the last empty slot on it, push the last item for re-ordering.
if (IsLastPossibleDropTarget(nearest_tile) && d_min < d_reorder) {
drop_attempt_ = DROP_FOR_REORDER;
nearest_tile.slot = nearest_tile.slot - 1;
return nearest_tile;
}
if (IsValidIndex(nearest_tile)) {
if (d_min < d_folder_dropping) {
views::View* target_view = GetViewAtSlotOnCurrentPage(nearest_tile.slot);
if (target_view &&
!IsFolderItem(static_cast<AppListItemView*>(drag_view_)->item())) {
// If a non-folder item is dragged to the target slot with an item
// sitting on it, attempt to drop the dragged item into the folder
// containing the item on nearest_tile.
drop_attempt_ = DROP_FOR_FOLDER;
return nearest_tile;
} else {
// If the target slot is blank, or the dragged item is a folder, attempt
// to re-order.
drop_attempt_ = DROP_FOR_REORDER;
return nearest_tile;
}
} else if (d_min < d_reorder) {
// Entering the re-order circle of the slot.
drop_attempt_ = DROP_FOR_REORDER;
return nearest_tile;
}
}
// If |drag_view| is not entering the re-order or fold dropping region of
// any items, cancel any previous re-order or folder dropping timer, and
// return itself.
drop_attempt_ = DROP_FOR_NONE;
reorder_timer_.Stop();
folder_dropping_timer_.Stop();
// When dragging for reparent a folder item, it should go back to its parent
// folder item if there is no drop target.
if (IsDraggingForReparentInRootLevelGridView()) {
DCHECK(activated_folder_item_view_);
return GetIndexOfView(activated_folder_item_view_);
}
return GetIndexOfView(drag_view_);
}
void AppsGridView::CalculateNearestTileForVertex(const gfx::Point& vertex,
Index* nearest_tile,
int* d_min) {
Index target_index;
gfx::Rect target_bounds = GetTileBoundsForPoint(vertex, &target_index);
if (target_bounds.IsEmpty() || target_index == *nearest_tile)
return;
// Do not count the tile, where drag_view_ used to sit on and is still moving
// on top of it, in calculating nearest tile for drag_view_.
views::View* target_view = GetViewAtSlotOnCurrentPage(target_index.slot);
if (target_index == drag_view_init_index_ && !target_view &&
!IsDraggingForReparentInRootLevelGridView()) {
return;
}
int d_center = GetDistanceBetweenRects(drag_view_->bounds(), target_bounds);
if (*d_min < 0 || d_center < *d_min) {
*d_min = d_center;
*nearest_tile = target_index;
}
}
gfx::Rect AppsGridView::GetTileBoundsForPoint(const gfx::Point& point,
Index *tile_index) {
// Check if |point| is outside of contents bounds.
gfx::Rect bounds(GetContentsBounds());
if (!bounds.Contains(point))
return gfx::Rect();
// Calculate which tile |point| is enclosed in.
int x = point.x();
int y = point.y();
int col = (x - bounds.x()) / kPreferredTileWidth;
int row = (y - bounds.y()) / kPreferredTileHeight;
gfx::Rect tile_rect = GetTileBounds(row, col);
// Check if |point| is outside a valid item's tile.
Index index(pagination_model_.selected_page(), row * cols_ + col);
*tile_index = index;
return tile_rect;
}
gfx::Rect AppsGridView::GetTileBounds(int row, int col) const {
gfx::Rect bounds(GetContentsBounds());
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(bounds);
gfx::Rect tile_rect(
gfx::Point(grid_rect.x() + col * tile_size.width(),
grid_rect.y() + row * tile_size.height()),
tile_size);
return tile_rect;
}
bool AppsGridView::IsLastPossibleDropTarget(const Index& index) const {
int last_possible_slot = view_model_.view_size() % tiles_per_page();
return (index.page == pagination_model_.total_pages() - 1 &&
index.slot == last_possible_slot + 1);
}
views::View* AppsGridView::GetViewAtSlotOnCurrentPage(int slot) {
if (slot < 0)
return NULL;
// Calculate the original bound of the tile at |index|.
int row = slot / cols_;
int col = slot % cols_;
gfx::Rect tile_rect = GetTileBounds(row, col);
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view->bounds() == tile_rect && view != drag_view_)
return view;
}
return NULL;
}
void AppsGridView::SetAsFolderDroppingTarget(const Index& target_index,
bool is_target_folder) {
AppListItemView* target_view =
static_cast<AppListItemView*>(
GetViewAtSlotOnCurrentPage(target_index.slot));
if (target_view)
target_view->SetAsAttemptedFolderTarget(is_target_folder);
}
} // namespace app_list
Make page switch on drag happen at top and bottom for experimental app list.
This CL makes dragging an app in the experimental app list change pages at
the top and bottom of the apps grid rather than at the sides. This matches
the scroll behavior of the experimental app list.
BUG=406222
Review URL: https://codereview.chromium.org/518673008
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#293673}
// 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 "ui/app_list/views/apps_grid_view.h"
#include <algorithm>
#include <set>
#include <string>
#include "base/guid.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_folder_item.h"
#include "ui/app_list/app_list_item.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/pagination_controller.h"
#include "ui/app_list/views/app_list_drag_and_drop_host.h"
#include "ui/app_list/views/app_list_folder_view.h"
#include "ui/app_list/views/app_list_item_view.h"
#include "ui/app_list/views/apps_grid_view_delegate.h"
#include "ui/app_list/views/page_switcher.h"
#include "ui/app_list/views/pulsing_block_view.h"
#include "ui/app_list/views/top_icon_animation_view.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/events/event.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
#include "ui/views/border.h"
#include "ui/views/view_model_utils.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#if defined(OS_WIN)
#include "ui/views/win/hwnd_util.h"
#endif // defined(OS_WIN)
#endif // defined(USE_AURA)
#if defined(OS_WIN)
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/win/shortcut.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/drop_target_win.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#include "ui/gfx/win/dpi.h"
#endif
namespace app_list {
namespace {
// Distance a drag needs to be from the app grid to be considered 'outside', at
// which point we rearrange the apps to their pre-drag configuration, as a drop
// then would be canceled. We have a buffer to make it easier to drag apps to
// other pages.
const int kDragBufferPx = 20;
// Padding space in pixels for fixed layout.
const int kLeftRightPadding = 20;
const int kTopPadding = 1;
const int kBottomPadding = 24;
// Padding space in pixels between pages.
const int kPagePadding = 40;
// Preferred tile size when showing in fixed layout.
const int kPreferredTileWidth = 88;
const int kPreferredTileHeight = 98;
// Width in pixels of the area on the sides that triggers a page flip.
const int kPageFlipZoneSize = 40;
// Delay in milliseconds to do the page flip.
const int kPageFlipDelayInMs = 1000;
// How many pages on either side of the selected one we prerender.
const int kPrerenderPages = 1;
// The drag and drop proxy should get scaled by this factor.
const float kDragAndDropProxyScale = 1.5f;
// Delays in milliseconds to show folder dropping preview circle.
const int kFolderDroppingDelay = 150;
// Delays in milliseconds to show re-order preview.
const int kReorderDelay = 120;
// Delays in milliseconds to show folder item reparent UI.
const int kFolderItemReparentDelay = 50;
// Radius of the circle, in which if entered, show folder dropping preview
// UI.
const int kFolderDroppingCircleRadius = 15;
// RowMoveAnimationDelegate is used when moving an item into a different row.
// Before running the animation, the item's layer is re-created and kept in
// the original position, then the item is moved to just before its target
// position and opacity set to 0. When the animation runs, this delegate moves
// the layer and fades it out while fading in the item at the same time.
class RowMoveAnimationDelegate : public gfx::AnimationDelegate {
public:
RowMoveAnimationDelegate(views::View* view,
ui::Layer* layer,
const gfx::Rect& layer_target)
: view_(view),
layer_(layer),
layer_start_(layer ? layer->bounds() : gfx::Rect()),
layer_target_(layer_target) {
}
virtual ~RowMoveAnimationDelegate() {}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
if (layer_) {
layer_->SetOpacity(1 - animation->GetCurrentValue());
layer_->SetBounds(animation->CurrentValueBetween(layer_start_,
layer_target_));
layer_->ScheduleDraw();
}
}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->SchedulePaint();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->SchedulePaint();
}
private:
// The view that needs to be wrapped. Owned by views hierarchy.
views::View* view_;
scoped_ptr<ui::Layer> layer_;
const gfx::Rect layer_start_;
const gfx::Rect layer_target_;
DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate);
};
// ItemRemoveAnimationDelegate is used to show animation for removing an item.
// This happens when user drags an item into a folder. The dragged item will
// be removed from the original list after it is dropped into the folder.
class ItemRemoveAnimationDelegate : public gfx::AnimationDelegate {
public:
explicit ItemRemoveAnimationDelegate(views::View* view)
: view_(view) {
}
virtual ~ItemRemoveAnimationDelegate() {
}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
}
private:
scoped_ptr<views::View> view_;
DISALLOW_COPY_AND_ASSIGN(ItemRemoveAnimationDelegate);
};
// ItemMoveAnimationDelegate observes when an item finishes animating when it is
// not moving between rows. This is to ensure an item is repainted for the
// "zoom out" case when releasing an item being dragged.
class ItemMoveAnimationDelegate : public gfx::AnimationDelegate {
public:
ItemMoveAnimationDelegate(views::View* view) : view_(view) {}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->SchedulePaint();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->SchedulePaint();
}
private:
views::View* view_;
DISALLOW_COPY_AND_ASSIGN(ItemMoveAnimationDelegate);
};
// Gets the distance between the centers of the |rect_1| and |rect_2|.
int GetDistanceBetweenRects(gfx::Rect rect_1,
gfx::Rect rect_2) {
return (rect_1.CenterPoint() - rect_2.CenterPoint()).Length();
}
// Returns true if the |item| is an folder item.
bool IsFolderItem(AppListItem* item) {
return (item->GetItemType() == AppListFolderItem::kItemType);
}
bool IsOEMFolderItem(AppListItem* item) {
return IsFolderItem(item) &&
(static_cast<AppListFolderItem*>(item))->folder_type() ==
AppListFolderItem::FOLDER_TYPE_OEM;
}
} // namespace
#if defined(OS_WIN)
// Interprets drag events sent from Windows via the drag/drop API and forwards
// them to AppsGridView.
// On Windows, in order to have the OS perform the drag properly we need to
// provide it with a shortcut file which may or may not exist at the time the
// drag is started. Therefore while waiting for that shortcut to be located we
// just do a regular "internal" drag and transition into the synchronous drag
// when the shortcut is found/created. Hence a synchronous drag is an optional
// phase of a regular drag and non-Windows platforms drags are equivalent to a
// Windows drag that never enters the synchronous drag phase.
class SynchronousDrag : public ui::DragSourceWin {
public:
SynchronousDrag(AppsGridView* grid_view,
AppListItemView* drag_view,
const gfx::Point& drag_view_offset)
: grid_view_(grid_view),
drag_view_(drag_view),
drag_view_offset_(drag_view_offset),
has_shortcut_path_(false),
running_(false),
canceled_(false) {}
void set_shortcut_path(const base::FilePath& shortcut_path) {
has_shortcut_path_ = true;
shortcut_path_ = shortcut_path;
}
bool running() { return running_; }
bool CanRun() {
return has_shortcut_path_ && !running_;
}
void Run() {
DCHECK(CanRun());
// Prevent the synchronous dragger being destroyed while the drag is
// running.
scoped_refptr<SynchronousDrag> this_ref = this;
running_ = true;
ui::OSExchangeData data;
SetupExchangeData(&data);
// Hide the dragged view because the OS is going to create its own.
drag_view_->SetVisible(false);
// Blocks until the drag is finished. Calls into the ui::DragSourceWin
// methods.
DWORD effects;
DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects);
// If |drag_view_| is NULL the drag was ended by some reentrant code.
if (drag_view_) {
// Make the drag view visible again.
drag_view_->SetVisible(true);
drag_view_->OnSyncDragEnd();
grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView());
}
}
void EndDragExternally() {
CancelDrag();
DCHECK(drag_view_);
drag_view_->SetVisible(true);
drag_view_ = NULL;
}
private:
// Overridden from ui::DragSourceWin.
virtual void OnDragSourceCancel() OVERRIDE {
canceled_ = true;
}
virtual void OnDragSourceDrop() OVERRIDE {
}
virtual void OnDragSourceMove() OVERRIDE {
grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords());
}
void SetupExchangeData(ui::OSExchangeData* data) {
data->SetFilename(shortcut_path_);
gfx::ImageSkia image(drag_view_->GetDragImage());
gfx::Size image_size(image.size());
drag_utils::SetDragImageOnDataObject(
image,
drag_view_offset_ - drag_view_->GetDragImageOffset(),
data);
}
HWND GetGridViewHWND() {
return views::HWNDForView(grid_view_);
}
bool IsCursorWithinGridView() {
POINT p;
GetCursorPos(&p);
return GetGridViewHWND() == WindowFromPoint(p);
}
gfx::Point GetCursorInGridViewCoords() {
POINT p;
GetCursorPos(&p);
ScreenToClient(GetGridViewHWND(), &p);
gfx::Point grid_view_pt(p.x, p.y);
grid_view_pt = gfx::win::ScreenToDIPPoint(grid_view_pt);
views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt);
return grid_view_pt;
}
AppsGridView* grid_view_;
AppListItemView* drag_view_;
gfx::Point drag_view_offset_;
bool has_shortcut_path_;
base::FilePath shortcut_path_;
bool running_;
bool canceled_;
DISALLOW_COPY_AND_ASSIGN(SynchronousDrag);
};
#endif // defined(OS_WIN)
AppsGridView::AppsGridView(AppsGridViewDelegate* delegate)
: model_(NULL),
item_list_(NULL),
delegate_(delegate),
folder_delegate_(NULL),
page_switcher_view_(NULL),
cols_(0),
rows_per_page_(0),
selected_view_(NULL),
drag_view_(NULL),
drag_start_page_(-1),
#if defined(OS_WIN)
use_synchronous_drag_(true),
#endif
drag_pointer_(NONE),
drop_attempt_(DROP_FOR_NONE),
drag_and_drop_host_(NULL),
forward_events_to_drag_and_drop_host_(false),
page_flip_target_(-1),
page_flip_delay_in_ms_(kPageFlipDelayInMs),
bounds_animator_(this),
activated_folder_item_view_(NULL),
dragging_for_reparent_item_(false) {
SetPaintToLayer(true);
// Clip any icons that are outside the grid view's bounds. These icons would
// otherwise be visible to the user when the grid view is off screen.
layer()->SetMasksToBounds(true);
SetFillsBoundsOpaquely(false);
pagination_model_.SetTransitionDurations(kPageTransitionDurationInMs,
kOverscrollPageTransitionDurationMs);
pagination_model_.AddObserver(this);
// The experimental app list transitions vertically.
PaginationController::ScrollAxis scroll_axis =
app_list::switches::IsExperimentalAppListEnabled()
? PaginationController::SCROLL_AXIS_VERTICAL
: PaginationController::SCROLL_AXIS_HORIZONTAL;
pagination_controller_.reset(
new PaginationController(&pagination_model_, scroll_axis));
if (!switches::IsExperimentalAppListEnabled()) {
page_switcher_view_ = new PageSwitcher(&pagination_model_);
AddChildView(page_switcher_view_);
}
}
AppsGridView::~AppsGridView() {
// Coming here |drag_view_| should already be canceled since otherwise the
// drag would disappear after the app list got animated away and closed,
// which would look odd.
DCHECK(!drag_view_);
if (drag_view_)
EndDrag(true);
if (model_)
model_->RemoveObserver(this);
pagination_model_.RemoveObserver(this);
if (item_list_)
item_list_->RemoveObserver(this);
// Make sure |page_switcher_view_| is deleted before |pagination_model_|.
view_model_.Clear();
RemoveAllChildViews(true);
}
void AppsGridView::SetLayout(int cols, int rows_per_page) {
cols_ = cols;
rows_per_page_ = rows_per_page;
SetBorder(views::Border::CreateEmptyBorder(
kTopPadding, kLeftRightPadding, 0, kLeftRightPadding));
}
void AppsGridView::ResetForShowApps() {
activated_folder_item_view_ = NULL;
ClearDragState();
layer()->SetOpacity(1.0f);
SetVisible(true);
// Set all views to visible in case they weren't made visible again by an
// incomplete animation.
for (int i = 0; i < view_model_.view_size(); ++i) {
view_model_.view_at(i)->SetVisible(true);
}
CHECK_EQ(item_list_->item_count(),
static_cast<size_t>(view_model_.view_size()));
}
void AppsGridView::SetModel(AppListModel* model) {
if (model_)
model_->RemoveObserver(this);
model_ = model;
if (model_)
model_->AddObserver(this);
Update();
}
void AppsGridView::SetItemList(AppListItemList* item_list) {
if (item_list_)
item_list_->RemoveObserver(this);
item_list_ = item_list;
if (item_list_)
item_list_->AddObserver(this);
Update();
}
void AppsGridView::SetSelectedView(views::View* view) {
if (IsSelectedView(view) || IsDraggedView(view))
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
SetSelectedItemByIndex(index);
}
void AppsGridView::ClearSelectedView(views::View* view) {
if (view && IsSelectedView(view)) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
void AppsGridView::ClearAnySelectedView() {
if (selected_view_) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
bool AppsGridView::IsSelectedView(const views::View* view) const {
return selected_view_ == view;
}
void AppsGridView::EnsureViewVisible(const views::View* view) {
if (pagination_model_.has_transition())
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
pagination_model_.SelectPage(index.page, false);
}
void AppsGridView::InitiateDrag(AppListItemView* view,
Pointer pointer,
const ui::LocatedEvent& event) {
DCHECK(view);
if (drag_view_ || pulsing_blocks_model_.view_size())
return;
drag_view_ = view;
drag_view_init_index_ = GetIndexOfView(drag_view_);
drag_view_offset_ = event.location();
drag_start_page_ = pagination_model_.selected_page();
ExtractDragLocation(event, &drag_start_grid_view_);
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
}
void AppsGridView::StartSettingUpSynchronousDrag() {
#if defined(OS_WIN)
if (!delegate_ || !use_synchronous_drag_)
return;
// Folders and downloading items can't be integrated with the OS.
if (IsFolderItem(drag_view_->item()) || drag_view_->item()->is_installing())
return;
// Favor the drag and drop host over native win32 drag. For the Win8/ash
// launcher we want to have ashes drag and drop over win32's.
if (drag_and_drop_host_)
return;
// Never create a second synchronous drag if the drag started in a folder.
if (IsDraggingForReparentInRootLevelGridView())
return;
synchronous_drag_ = new SynchronousDrag(this, drag_view_, drag_view_offset_);
delegate_->GetShortcutPathForApp(drag_view_->item()->id(),
base::Bind(&AppsGridView::OnGotShortcutPath,
base::Unretained(this),
synchronous_drag_));
#endif
}
bool AppsGridView::RunSynchronousDrag() {
#if defined(OS_WIN)
if (!synchronous_drag_)
return false;
if (synchronous_drag_->CanRun()) {
if (IsDraggingForReparentInHiddenGridView())
folder_delegate_->SetRootLevelDragViewVisible(false);
synchronous_drag_->Run();
synchronous_drag_ = NULL;
return true;
} else if (!synchronous_drag_->running()) {
// The OS drag is not ready yet. If the root grid has a drag view because
// a reparent has started, ensure it is visible.
if (IsDraggingForReparentInHiddenGridView())
folder_delegate_->SetRootLevelDragViewVisible(true);
}
#endif
return false;
}
void AppsGridView::CleanUpSynchronousDrag() {
#if defined(OS_WIN)
if (synchronous_drag_)
synchronous_drag_->EndDragExternally();
synchronous_drag_ = NULL;
#endif
}
#if defined(OS_WIN)
void AppsGridView::OnGotShortcutPath(
scoped_refptr<SynchronousDrag> synchronous_drag,
const base::FilePath& path) {
// Drag may have ended before we get the shortcut path or a new drag may have
// begun.
if (synchronous_drag_ != synchronous_drag)
return;
// Setting the shortcut path here means the next time we hit UpdateDrag()
// we'll enter the synchronous drag.
// NOTE we don't Run() the drag here because that causes animations not to
// update for some reason.
synchronous_drag_->set_shortcut_path(path);
DCHECK(synchronous_drag_->CanRun());
}
#endif
bool AppsGridView::UpdateDragFromItem(Pointer pointer,
const ui::LocatedEvent& event) {
if (!drag_view_)
return false; // Drag canceled.
gfx::Point drag_point_in_grid_view;
ExtractDragLocation(event, &drag_point_in_grid_view);
UpdateDrag(pointer, drag_point_in_grid_view);
if (!dragging())
return false;
// If a drag and drop host is provided, see if the drag operation needs to be
// forwarded.
gfx::Point location_in_screen = drag_point_in_grid_view;
views::View::ConvertPointToScreen(this, &location_in_screen);
DispatchDragEventToDragAndDropHost(location_in_screen);
if (drag_and_drop_host_)
drag_and_drop_host_->UpdateDragIconProxy(location_in_screen);
return true;
}
void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) {
if (folder_delegate_)
UpdateDragStateInsideFolder(pointer, point);
if (!drag_view_)
return; // Drag canceled.
if (RunSynchronousDrag())
return;
gfx::Vector2d drag_vector(point - drag_start_grid_view_);
if (!dragging() && ExceededDragThreshold(drag_vector)) {
drag_pointer_ = pointer;
// Move the view to the front so that it appears on top of other views.
ReorderChildView(drag_view_, -1);
bounds_animator_.StopAnimatingView(drag_view_);
// Stopping the animation may have invalidated our drag view due to the
// view hierarchy changing.
if (!drag_view_)
return;
StartSettingUpSynchronousDrag();
if (!dragging_for_reparent_item_)
StartDragAndDropHostDrag(point);
}
if (drag_pointer_ != pointer)
return;
last_drag_point_ = point;
const Index last_drop_target = drop_target_;
DropAttempt last_drop_attempt = drop_attempt_;
CalculateDropTarget(last_drag_point_, false);
if (IsPointWithinDragBuffer(last_drag_point_))
MaybeStartPageFlipTimer(last_drag_point_);
else
StopPageFlipTimer();
if (page_switcher_view_) {
gfx::Point page_switcher_point(last_drag_point_);
views::View::ConvertPointToTarget(
this, page_switcher_view_, &page_switcher_point);
page_switcher_view_->UpdateUIForDragPoint(page_switcher_point);
}
if (!EnableFolderDragDropUI()) {
if (last_drop_target != drop_target_)
AnimateToIdealBounds();
drag_view_->SetPosition(drag_view_start_ + drag_vector);
return;
}
// Update drag with folder UI enabled.
if (last_drop_target != drop_target_ ||
last_drop_attempt != drop_attempt_) {
if (drop_attempt_ == DROP_FOR_REORDER) {
folder_dropping_timer_.Stop();
reorder_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kReorderDelay),
this, &AppsGridView::OnReorderTimer);
} else if (drop_attempt_ == DROP_FOR_FOLDER) {
reorder_timer_.Stop();
folder_dropping_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kFolderDroppingDelay),
this, &AppsGridView::OnFolderDroppingTimer);
}
// Reset the previous drop target.
SetAsFolderDroppingTarget(last_drop_target, false);
}
drag_view_->SetPosition(drag_view_start_ + drag_vector);
}
void AppsGridView::EndDrag(bool cancel) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
// Coming here a drag and drop was in progress.
bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_;
if (forward_events_to_drag_and_drop_host_) {
DCHECK(!IsDraggingForReparentInRootLevelGridView());
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(cancel);
if (IsDraggingForReparentInHiddenGridView()) {
folder_delegate_->DispatchEndDragEventForReparent(
true /* events_forwarded_to_drag_drop_host */,
cancel /* cancel_drag */);
}
} else {
if (IsDraggingForReparentInHiddenGridView()) {
// Forward the EndDrag event to the root level grid view.
folder_delegate_->DispatchEndDragEventForReparent(
false /* events_forwarded_to_drag_drop_host */,
cancel /* cancel_drag */);
EndDragForReparentInHiddenFolderGridView();
return;
}
if (IsDraggingForReparentInRootLevelGridView()) {
// An EndDrag can be received during a reparent via a model change. This
// is always a cancel and needs to be forwarded to the folder.
DCHECK(cancel);
delegate_->CancelDragInActiveFolder();
return;
}
if (!cancel && dragging()) {
// Regular drag ending path, ie, not for reparenting.
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_)) {
if (!EnableFolderDragDropUI()) {
MoveItemInModel(drag_view_, drop_target_);
} else {
if (drop_attempt_ == DROP_FOR_REORDER)
MoveItemInModel(drag_view_, drop_target_);
else if (drop_attempt_ == DROP_FOR_FOLDER)
MoveItemToFolder(drag_view_, drop_target_);
}
}
}
}
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
if (landed_in_drag_and_drop_host) {
// Move the item directly to the target location, avoiding the "zip back"
// animation if the user was pinning it to the shelf.
int i = drop_target_.slot;
gfx::Rect bounds = view_model_.ideal_bounds(i);
drag_view_->SetBoundsRect(bounds);
}
// Fade in slowly if it landed in the shelf.
SetViewHidden(drag_view_,
false /* show */,
!landed_in_drag_and_drop_host /* animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
ClearDragState();
AnimateToIdealBounds();
StopPageFlipTimer();
// If user releases mouse inside a folder's grid view, burst the folder
// container ink bubble.
if (folder_delegate_ && !IsDraggingForReparentInHiddenGridView())
folder_delegate_->UpdateFolderViewBackground(false);
}
void AppsGridView::StopPageFlipTimer() {
page_flip_timer_.Stop();
page_flip_target_ = -1;
}
AppListItemView* AppsGridView::GetItemViewAt(int index) const {
DCHECK(index >= 0 && index < view_model_.view_size());
return static_cast<AppListItemView*>(view_model_.view_at(index));
}
void AppsGridView::SetTopItemViewsVisible(bool visible) {
int top_item_count = std::min(static_cast<int>(kNumFolderTopItems),
view_model_.view_size());
for (int i = 0; i < top_item_count; ++i)
GetItemViewAt(i)->icon()->SetVisible(visible);
}
void AppsGridView::ScheduleShowHideAnimation(bool show) {
// Stop any previous animation.
layer()->GetAnimator()->StopAnimating();
// Set initial state.
SetVisible(true);
layer()->SetOpacity(show ? 0.0f : 1.0f);
ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator());
animation.AddObserver(this);
animation.SetTweenType(
show ? kFolderFadeInTweenType : kFolderFadeOutTweenType);
animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
show ? kFolderTransitionInDurationMs : kFolderTransitionOutDurationMs));
layer()->SetOpacity(show ? 1.0f : 0.0f);
}
void AppsGridView::InitiateDragFromReparentItemInRootLevelGridView(
AppListItemView* original_drag_view,
const gfx::Rect& drag_view_rect,
const gfx::Point& drag_point) {
DCHECK(original_drag_view && !drag_view_);
DCHECK(!dragging_for_reparent_item_);
// Create a new AppListItemView to duplicate the original_drag_view in the
// folder's grid view.
AppListItemView* view = new AppListItemView(this, original_drag_view->item());
AddChildView(view);
drag_view_ = view;
drag_view_->SetPaintToLayer(true);
// Note: For testing purpose, SetFillsBoundsOpaquely can be set to true to
// show the gray background.
drag_view_->SetFillsBoundsOpaquely(false);
drag_view_->SetBoundsRect(drag_view_rect);
drag_view_->SetDragUIState(); // Hide the title of the drag_view_.
// Hide the drag_view_ for drag icon proxy.
SetViewHidden(drag_view_,
true /* hide */,
true /* no animate */);
// Add drag_view_ to the end of the view_model_.
view_model_.Add(drag_view_, view_model_.view_size());
drag_start_page_ = pagination_model_.selected_page();
drag_start_grid_view_ = drag_point;
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
// Set the flag in root level grid view.
dragging_for_reparent_item_ = true;
}
void AppsGridView::UpdateDragFromReparentItem(Pointer pointer,
const gfx::Point& drag_point) {
// Note that if a cancel ocurrs while reparenting, the |drag_view_| in both
// root and folder grid views is cleared, so the check in UpdateDragFromItem()
// for |drag_view_| being NULL (in the folder grid) is sufficient.
DCHECK(drag_view_);
DCHECK(IsDraggingForReparentInRootLevelGridView());
UpdateDrag(pointer, drag_point);
}
bool AppsGridView::IsDraggedView(const views::View* view) const {
return drag_view_ == view;
}
void AppsGridView::ClearDragState() {
drop_attempt_ = DROP_FOR_NONE;
drag_pointer_ = NONE;
drop_target_ = Index();
drag_start_grid_view_ = gfx::Point();
drag_start_page_ = -1;
drag_view_offset_ = gfx::Point();
if (drag_view_) {
drag_view_->OnDragEnded();
if (IsDraggingForReparentInRootLevelGridView()) {
const int drag_view_index = view_model_.GetIndexOfView(drag_view_);
CHECK_EQ(view_model_.view_size() - 1, drag_view_index);
DeleteItemViewAtIndex(drag_view_index);
}
}
drag_view_ = NULL;
dragging_for_reparent_item_ = false;
}
void AppsGridView::SetDragViewVisible(bool visible) {
DCHECK(drag_view_);
SetViewHidden(drag_view_, !visible, true);
}
void AppsGridView::SetDragAndDropHostOfCurrentAppList(
ApplicationDragAndDropHost* drag_and_drop_host) {
drag_and_drop_host_ = drag_and_drop_host;
}
void AppsGridView::Prerender() {
Layout();
int selected_page = std::max(0, pagination_model_.selected_page());
int start = std::max(0, (selected_page - kPrerenderPages) * tiles_per_page());
int end = std::min(view_model_.view_size(),
(selected_page + 1 + kPrerenderPages) * tiles_per_page());
for (int i = start; i < end; i++) {
AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i));
v->Prerender();
}
}
bool AppsGridView::IsAnimatingView(views::View* view) {
return bounds_animator_.IsAnimating(view);
}
gfx::Size AppsGridView::GetPreferredSize() const {
const gfx::Insets insets(GetInsets());
const gfx::Size tile_size = gfx::Size(kPreferredTileWidth,
kPreferredTileHeight);
int page_switcher_height = kBottomPadding;
if (page_switcher_view_)
page_switcher_height = page_switcher_view_->GetPreferredSize().height();
return gfx::Size(
tile_size.width() * cols_ + insets.width(),
tile_size.height() * rows_per_page_ +
page_switcher_height + insets.height());
}
bool AppsGridView::GetDropFormats(
int* formats,
std::set<OSExchangeData::CustomFormat>* custom_formats) {
// TODO(koz): Only accept a specific drag type for app shortcuts.
*formats = OSExchangeData::FILE_NAME;
return true;
}
bool AppsGridView::CanDrop(const OSExchangeData& data) {
return true;
}
int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_MOVE;
}
void AppsGridView::Layout() {
if (bounds_animator_.IsAnimating())
bounds_animator_.Cancel();
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view != drag_view_)
view->SetBoundsRect(view_model_.ideal_bounds(i));
}
views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_);
if (page_switcher_view_) {
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
gfx::Rect rect(GetContentsBounds());
rect.set_y(rect.bottom() - page_switcher_height);
rect.set_height(page_switcher_height);
page_switcher_view_->SetBoundsRect(rect);
}
}
bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyPressed(event);
if (!handled) {
const int forward_dir = base::i18n::IsRTL() ? -1 : 1;
switch (event.key_code()) {
case ui::VKEY_LEFT:
MoveSelected(0, -forward_dir, 0);
return true;
case ui::VKEY_RIGHT:
MoveSelected(0, forward_dir, 0);
return true;
case ui::VKEY_UP:
MoveSelected(0, 0, -1);
return true;
case ui::VKEY_DOWN:
MoveSelected(0, 0, 1);
return true;
case ui::VKEY_PRIOR: {
MoveSelected(-1, 0, 0);
return true;
}
case ui::VKEY_NEXT: {
MoveSelected(1, 0, 0);
return true;
}
default:
break;
}
}
return handled;
}
bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyReleased(event);
return handled;
}
bool AppsGridView::OnMouseWheel(const ui::MouseWheelEvent& event) {
return pagination_controller_->OnScroll(
gfx::Vector2d(event.x_offset(), event.y_offset()));
}
void AppsGridView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (!details.is_add && details.parent == this) {
// The view being delete should not have reference in |view_model_|.
CHECK_EQ(-1, view_model_.GetIndexOfView(details.child));
if (selected_view_ == details.child)
selected_view_ = NULL;
if (activated_folder_item_view_ == details.child)
activated_folder_item_view_ = NULL;
if (drag_view_ == details.child)
EndDrag(true);
bounds_animator_.StopAnimatingView(details.child);
}
}
void AppsGridView::OnGestureEvent(ui::GestureEvent* event) {
if (pagination_controller_->OnGestureEvent(*event, GetContentsBounds()))
event->SetHandled();
}
void AppsGridView::OnScrollEvent(ui::ScrollEvent* event) {
if (event->type() == ui::ET_SCROLL_FLING_CANCEL)
return;
gfx::Vector2dF offset(event->x_offset(), event->y_offset());
if (pagination_controller_->OnScroll(gfx::ToFlooredVector2d(offset))) {
event->SetHandled();
event->StopPropagation();
}
}
void AppsGridView::Update() {
DCHECK(!selected_view_ && !drag_view_);
view_model_.Clear();
if (!item_list_ || !item_list_->item_count())
return;
for (size_t i = 0; i < item_list_->item_count(); ++i) {
views::View* view = CreateViewForItemAtIndex(i);
view_model_.Add(view, i);
AddChildView(view);
}
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::UpdatePaging() {
int total_page = view_model_.view_size() && tiles_per_page()
? (view_model_.view_size() - 1) / tiles_per_page() + 1
: 0;
pagination_model_.SetTotalPages(total_page);
}
void AppsGridView::UpdatePulsingBlockViews() {
const int existing_items = item_list_ ? item_list_->item_count() : 0;
const int available_slots =
tiles_per_page() - existing_items % tiles_per_page();
const int desired = model_->status() == AppListModel::STATUS_SYNCING ?
available_slots : 0;
if (pulsing_blocks_model_.view_size() == desired)
return;
while (pulsing_blocks_model_.view_size() > desired) {
views::View* view = pulsing_blocks_model_.view_at(0);
pulsing_blocks_model_.Remove(0);
delete view;
}
while (pulsing_blocks_model_.view_size() < desired) {
views::View* view = new PulsingBlockView(
gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true);
pulsing_blocks_model_.Add(view, 0);
AddChildView(view);
}
}
views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) {
// The drag_view_ might be pending for deletion, therefore view_model_
// may have one more item than item_list_.
DCHECK_LE(index, item_list_->item_count());
AppListItemView* view = new AppListItemView(this,
item_list_->item_at(index));
view->SetPaintToLayer(true);
view->SetFillsBoundsOpaquely(false);
return view;
}
AppsGridView::Index AppsGridView::GetIndexFromModelIndex(
int model_index) const {
return Index(model_index / tiles_per_page(), model_index % tiles_per_page());
}
int AppsGridView::GetModelIndexFromIndex(const Index& index) const {
return index.page * tiles_per_page() + index.slot;
}
void AppsGridView::SetSelectedItemByIndex(const Index& index) {
if (GetIndexOfView(selected_view_) == index)
return;
views::View* new_selection = GetViewAtIndex(index);
if (!new_selection)
return; // Keep current selection.
if (selected_view_)
selected_view_->SchedulePaint();
EnsureViewVisible(new_selection);
selected_view_ = new_selection;
selected_view_->SchedulePaint();
selected_view_->NotifyAccessibilityEvent(
ui::AX_EVENT_FOCUS, true);
}
bool AppsGridView::IsValidIndex(const Index& index) const {
return index.page >= 0 && index.page < pagination_model_.total_pages() &&
index.slot >= 0 && index.slot < tiles_per_page() &&
GetModelIndexFromIndex(index) < view_model_.view_size();
}
AppsGridView::Index AppsGridView::GetIndexOfView(
const views::View* view) const {
const int model_index = view_model_.GetIndexOfView(view);
if (model_index == -1)
return Index();
return GetIndexFromModelIndex(model_index);
}
views::View* AppsGridView::GetViewAtIndex(const Index& index) const {
if (!IsValidIndex(index))
return NULL;
const int model_index = GetModelIndexFromIndex(index);
return view_model_.view_at(model_index);
}
void AppsGridView::MoveSelected(int page_delta,
int slot_x_delta,
int slot_y_delta) {
if (!selected_view_)
return SetSelectedItemByIndex(Index(pagination_model_.selected_page(), 0));
const Index& selected = GetIndexOfView(selected_view_);
int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_;
if (selected.slot % cols_ == 0 && slot_x_delta == -1) {
if (selected.page > 0) {
page_delta = -1;
target_slot = selected.slot + cols_ - 1;
} else {
target_slot = selected.slot;
}
}
if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) {
if (selected.page < pagination_model_.total_pages() - 1) {
page_delta = 1;
target_slot = selected.slot - cols_ + 1;
} else {
target_slot = selected.slot;
}
}
// Clamp the target slot to the last item if we are moving to the last page
// but our target slot is past the end of the item list.
if (page_delta &&
selected.page + page_delta == pagination_model_.total_pages() - 1) {
int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page();
if (last_item_slot < target_slot) {
target_slot = last_item_slot;
}
}
int target_page = std::min(pagination_model_.total_pages() - 1,
std::max(selected.page + page_delta, 0));
SetSelectedItemByIndex(Index(target_page, target_slot));
}
void AppsGridView::CalculateIdealBounds() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(rect);
// Page size including padding pixels. A tile.x + page_width means the same
// tile slot in the next page; similarly for tile.y + page_height.
const int page_width = grid_rect.width() + kPagePadding;
const int page_height = grid_rect.height() + kPagePadding;
// If there is a transition, calculates offset for current and target page.
const int current_page = pagination_model_.selected_page();
const PaginationModel::Transition& transition =
pagination_model_.transition();
const bool is_valid = pagination_model_.is_valid_page(transition.target_page);
// Transition to previous page means negative offset.
const int dir = transition.target_page > current_page ? -1 : 1;
const int total_views =
view_model_.view_size() + pulsing_blocks_model_.view_size();
int slot_index = 0;
for (int i = 0; i < total_views; ++i) {
if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_) {
if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER)
++slot_index;
continue;
}
Index view_index = GetIndexFromModelIndex(slot_index);
if (drop_target_ == view_index) {
if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER) {
view_index = GetIndexFromModelIndex(slot_index);
} else if (!EnableFolderDragDropUI() ||
drop_attempt_ == DROP_FOR_REORDER) {
++slot_index;
view_index = GetIndexFromModelIndex(slot_index);
}
}
// Decide the x or y offset for current item.
int x_offset = 0;
int y_offset = 0;
if (pagination_controller_->scroll_axis() ==
PaginationController::SCROLL_AXIS_HORIZONTAL) {
if (view_index.page < current_page)
x_offset = -page_width;
else if (view_index.page > current_page)
x_offset = page_width;
if (is_valid) {
if (view_index.page == current_page ||
view_index.page == transition.target_page) {
x_offset += transition.progress * page_width * dir;
}
}
} else {
if (view_index.page < current_page)
y_offset = -page_height;
else if (view_index.page > current_page)
y_offset = page_height;
if (is_valid) {
if (view_index.page == current_page ||
view_index.page == transition.target_page) {
y_offset += transition.progress * page_height * dir;
}
}
}
const int row = view_index.slot / cols_;
const int col = view_index.slot % cols_;
gfx::Rect tile_slot(
gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset,
grid_rect.y() + row * tile_size.height() + y_offset),
tile_size);
if (i < view_model_.view_size()) {
view_model_.set_ideal_bounds(i, tile_slot);
} else {
pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(),
tile_slot);
}
++slot_index;
}
}
void AppsGridView::AnimateToIdealBounds() {
const gfx::Rect visible_bounds(GetVisibleBounds());
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view == drag_view_)
continue;
const gfx::Rect& target = view_model_.ideal_bounds(i);
if (bounds_animator_.GetTargetBounds(view) == target)
continue;
const gfx::Rect& current = view->bounds();
const bool current_visible = visible_bounds.Intersects(current);
const bool target_visible = visible_bounds.Intersects(target);
const bool visible = current_visible || target_visible;
const int y_diff = target.y() - current.y();
if (visible && y_diff && y_diff % kPreferredTileHeight == 0) {
AnimationBetweenRows(view,
current_visible,
current,
target_visible,
target);
} else if (visible || bounds_animator_.IsAnimating(view)) {
bounds_animator_.AnimateViewTo(view, target);
bounds_animator_.SetAnimationDelegate(
view,
scoped_ptr<gfx::AnimationDelegate>(
new ItemMoveAnimationDelegate(view)));
} else {
view->SetBoundsRect(target);
}
}
}
void AppsGridView::AnimationBetweenRows(views::View* view,
bool animate_current,
const gfx::Rect& current,
bool animate_target,
const gfx::Rect& target) {
// Determine page of |current| and |target|. -1 means in the left invisible
// page, 0 is the center visible page and 1 means in the right invisible page.
const int current_page = current.x() < 0 ? -1 :
current.x() >= width() ? 1 : 0;
const int target_page = target.x() < 0 ? -1 :
target.x() >= width() ? 1 : 0;
const int dir = current_page < target_page ||
(current_page == target_page && current.y() < target.y()) ? 1 : -1;
scoped_ptr<ui::Layer> layer;
if (animate_current) {
layer = view->RecreateLayer();
layer->SuppressPaint();
view->SetFillsBoundsOpaquely(false);
view->layer()->SetOpacity(0.f);
}
gfx::Rect current_out(current);
current_out.Offset(dir * kPreferredTileWidth, 0);
gfx::Rect target_in(target);
if (animate_target)
target_in.Offset(-dir * kPreferredTileWidth, 0);
view->SetBoundsRect(target_in);
bounds_animator_.AnimateViewTo(view, target);
bounds_animator_.SetAnimationDelegate(
view,
scoped_ptr<gfx::AnimationDelegate>(
new RowMoveAnimationDelegate(view, layer.release(), current_out)));
}
void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event,
gfx::Point* drag_point) {
#if defined(USE_AURA) && !defined(OS_WIN)
// Use root location of |event| instead of location in |drag_view_|'s
// coordinates because |drag_view_| has a scale transform and location
// could have integer round error and causes jitter.
*drag_point = event.root_location();
// GetWidget() could be NULL for tests.
if (GetWidget()) {
aura::Window::ConvertPointToTarget(
GetWidget()->GetNativeWindow()->GetRootWindow(),
GetWidget()->GetNativeWindow(),
drag_point);
}
views::View::ConvertPointFromWidget(this, drag_point);
#else
// For non-aura, root location is not clearly defined but |drag_view_| does
// not have the scale transform. So no round error would be introduced and
// it's okay to use View::ConvertPointToTarget.
*drag_point = event.location();
views::View::ConvertPointToTarget(drag_view_, this, drag_point);
#endif
}
void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point,
bool use_page_button_hovering) {
if (EnableFolderDragDropUI()) {
CalculateDropTargetWithFolderEnabled(drag_point, use_page_button_hovering);
return;
}
int current_page = pagination_model_.selected_page();
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
current_page = drag_start_page_;
}
if (use_page_button_hovering && page_switcher_view_ &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_.is_valid_page(page)) {
drop_target_.page = page;
drop_target_.slot = tiles_per_page() - 1;
}
} else {
gfx::Rect bounds(GetContentsBounds());
const int drop_row = (point.y() - bounds.y()) / kPreferredTileHeight;
const int drop_col = std::min(cols_ - 1,
(point.x() - bounds.x()) / kPreferredTileWidth);
drop_target_.page = current_page;
drop_target_.slot = std::max(0, std::min(
tiles_per_page() - 1,
drop_row * cols_ + drop_col));
}
// Limits to the last possible slot on last page.
if (drop_target_.page == pagination_model_.total_pages() - 1) {
drop_target_.slot = std::min(
(view_model_.view_size() - 1) % tiles_per_page(),
drop_target_.slot);
}
}
void AppsGridView::CalculateDropTargetWithFolderEnabled(
const gfx::Point& drag_point,
bool use_page_button_hovering) {
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
}
if (use_page_button_hovering && page_switcher_view_ &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_.is_valid_page(page))
drop_attempt_ = DROP_FOR_NONE;
} else {
DCHECK(drag_view_);
// Try to find the nearest target for folder dropping or re-ordering.
drop_target_ = GetNearestTileForDragView();
}
}
void AppsGridView::OnReorderTimer() {
if (drop_attempt_ == DROP_FOR_REORDER)
AnimateToIdealBounds();
}
void AppsGridView::OnFolderItemReparentTimer() {
DCHECK(folder_delegate_);
if (drag_out_of_folder_container_ && drag_view_) {
folder_delegate_->ReparentItem(drag_view_, last_drag_point_);
// Set the flag in the folder's grid view.
dragging_for_reparent_item_ = true;
// Do not observe any data change since it is going to be hidden.
item_list_->RemoveObserver(this);
item_list_ = NULL;
}
}
void AppsGridView::OnFolderDroppingTimer() {
if (drop_attempt_ == DROP_FOR_FOLDER)
SetAsFolderDroppingTarget(drop_target_, true);
}
void AppsGridView::UpdateDragStateInsideFolder(Pointer pointer,
const gfx::Point& drag_point) {
if (IsUnderOEMFolder())
return;
if (IsDraggingForReparentInHiddenGridView()) {
// Dispatch drag event to root level grid view for re-parenting folder
// folder item purpose.
DispatchDragEventForReparent(pointer, drag_point);
return;
}
// Regular drag and drop in a folder's grid view.
folder_delegate_->UpdateFolderViewBackground(true);
// Calculate if the drag_view_ is dragged out of the folder's container
// ink bubble.
gfx::Rect bounds_to_folder_view = ConvertRectToParent(drag_view_->bounds());
gfx::Point pt = bounds_to_folder_view.CenterPoint();
bool is_item_dragged_out_of_folder =
folder_delegate_->IsPointOutsideOfFolderBoundary(pt);
if (is_item_dragged_out_of_folder) {
if (!drag_out_of_folder_container_) {
folder_item_reparent_timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kFolderItemReparentDelay),
this,
&AppsGridView::OnFolderItemReparentTimer);
drag_out_of_folder_container_ = true;
}
} else {
folder_item_reparent_timer_.Stop();
drag_out_of_folder_container_ = false;
}
}
bool AppsGridView::IsDraggingForReparentInRootLevelGridView() const {
return (!folder_delegate_ && dragging_for_reparent_item_);
}
bool AppsGridView::IsDraggingForReparentInHiddenGridView() const {
return (folder_delegate_ && dragging_for_reparent_item_);
}
gfx::Rect AppsGridView::GetTargetIconRectInFolder(
AppListItemView* drag_item_view,
AppListItemView* folder_item_view) {
gfx::Rect view_ideal_bounds = view_model_.ideal_bounds(
view_model_.GetIndexOfView(folder_item_view));
gfx::Rect icon_ideal_bounds =
folder_item_view->GetIconBoundsForTargetViewBounds(view_ideal_bounds);
AppListFolderItem* folder_item =
static_cast<AppListFolderItem*>(folder_item_view->item());
return folder_item->GetTargetIconRectInFolderForItem(
drag_item_view->item(), icon_ideal_bounds);
}
bool AppsGridView::IsUnderOEMFolder() {
if (!folder_delegate_)
return false;
return folder_delegate_->IsOEMFolder();
}
void AppsGridView::DispatchDragEventForReparent(Pointer pointer,
const gfx::Point& drag_point) {
folder_delegate_->DispatchDragEventForReparent(pointer, drag_point);
}
void AppsGridView::EndDragFromReparentItemInRootLevel(
bool events_forwarded_to_drag_drop_host,
bool cancel_drag) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
DCHECK(IsDraggingForReparentInRootLevelGridView());
bool cancel_reparent = cancel_drag || drop_attempt_ == DROP_FOR_NONE;
if (!events_forwarded_to_drag_drop_host && !cancel_reparent) {
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_)) {
if (drop_attempt_ == DROP_FOR_REORDER) {
ReparentItemForReorder(drag_view_, drop_target_);
} else if (drop_attempt_ == DROP_FOR_FOLDER) {
ReparentItemToAnotherFolder(drag_view_, drop_target_);
}
}
SetViewHidden(drag_view_, false /* show */, true /* no animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
if (cancel_reparent) {
CancelFolderItemReparent(drag_view_);
} else {
// By setting |drag_view_| to NULL here, we prevent ClearDragState() from
// cleaning up the newly created AppListItemView, effectively claiming
// ownership of the newly created drag view.
drag_view_->OnDragEnded();
drag_view_ = NULL;
}
ClearDragState();
AnimateToIdealBounds();
StopPageFlipTimer();
}
void AppsGridView::EndDragForReparentInHiddenFolderGridView() {
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
ClearDragState();
}
void AppsGridView::OnFolderItemRemoved() {
DCHECK(folder_delegate_);
item_list_ = NULL;
}
void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) {
// When a drag and drop host is given, the item can be dragged out of the app
// list window. In that case a proxy widget needs to be used.
// Note: This code has very likely to be changed for Windows (non metro mode)
// when a |drag_and_drop_host_| gets implemented.
if (!drag_view_ || !drag_and_drop_host_)
return;
gfx::Point screen_location = grid_location;
views::View::ConvertPointToScreen(this, &screen_location);
// Determine the mouse offset to the center of the icon so that the drag and
// drop host follows this layer.
gfx::Vector2d delta = drag_view_offset_ -
drag_view_->GetLocalBounds().CenterPoint();
delta.set_y(delta.y() + drag_view_->title()->size().height() / 2);
// We have to hide the original item since the drag and drop host will do
// the OS dependent code to "lift off the dragged item".
DCHECK(!IsDraggingForReparentInRootLevelGridView());
drag_and_drop_host_->CreateDragIconProxy(screen_location,
drag_view_->item()->icon(),
drag_view_,
delta,
kDragAndDropProxyScale);
SetViewHidden(drag_view_,
true /* hide */,
true /* no animation */);
}
void AppsGridView::DispatchDragEventToDragAndDropHost(
const gfx::Point& location_in_screen_coordinates) {
if (!drag_view_ || !drag_and_drop_host_)
return;
if (GetLocalBounds().Contains(last_drag_point_)) {
// The event was issued inside the app menu and we should get all events.
if (forward_events_to_drag_and_drop_host_) {
// The DnD host was previously called and needs to be informed that the
// session returns to the owner.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (IsFolderItem(drag_view_->item()))
return;
// The event happened outside our app menu and we might need to dispatch.
if (forward_events_to_drag_and_drop_host_) {
// Dispatch since we have already started.
if (!drag_and_drop_host_->Drag(location_in_screen_coordinates)) {
// The host is not active any longer and we cancel the operation.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (drag_and_drop_host_->StartDrag(drag_view_->item()->id(),
location_in_screen_coordinates)) {
// From now on we forward the drag events.
forward_events_to_drag_and_drop_host_ = true;
// Any flip operations are stopped.
StopPageFlipTimer();
}
}
}
}
void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) {
if (!IsPointWithinDragBuffer(drag_point))
StopPageFlipTimer();
int new_page_flip_target = -1;
// Drag zones are at the edges of the scroll axis.
if (pagination_controller_->scroll_axis() ==
PaginationController::SCROLL_AXIS_VERTICAL) {
if (drag_point.y() < kPageFlipZoneSize)
new_page_flip_target = pagination_model_.selected_page() - 1;
else if (drag_point.y() > height() - kPageFlipZoneSize)
new_page_flip_target = pagination_model_.selected_page() + 1;
} else {
if (page_switcher_view_->bounds().Contains(drag_point)) {
gfx::Point page_switcher_point(drag_point);
views::View::ConvertPointToTarget(
this, page_switcher_view_, &page_switcher_point);
new_page_flip_target =
page_switcher_view_->GetPageForPoint(page_switcher_point);
}
// TODO(xiyuan): Fix this for RTL.
if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize)
new_page_flip_target = pagination_model_.selected_page() - 1;
if (new_page_flip_target == -1 &&
drag_point.x() > width() - kPageFlipZoneSize) {
new_page_flip_target = pagination_model_.selected_page() + 1;
}
}
if (new_page_flip_target == page_flip_target_)
return;
StopPageFlipTimer();
if (pagination_model_.is_valid_page(new_page_flip_target)) {
page_flip_target_ = new_page_flip_target;
if (page_flip_target_ != pagination_model_.selected_page()) {
page_flip_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_),
this, &AppsGridView::OnPageFlipTimer);
}
}
}
void AppsGridView::OnPageFlipTimer() {
DCHECK(pagination_model_.is_valid_page(page_flip_target_));
pagination_model_.SelectPage(page_flip_target_, true);
}
void AppsGridView::MoveItemInModel(views::View* item_view,
const Index& target) {
int current_model_index = view_model_.GetIndexOfView(item_view);
DCHECK_GE(current_model_index, 0);
int target_model_index = GetModelIndexFromIndex(target);
if (target_model_index == current_model_index)
return;
item_list_->RemoveObserver(this);
item_list_->MoveItem(current_model_index, target_model_index);
view_model_.Move(current_model_index, target_model_index);
item_list_->AddObserver(this);
if (pagination_model_.selected_page() != target.page)
pagination_model_.SelectPage(target.page, false);
}
void AppsGridView::MoveItemToFolder(views::View* item_view,
const Index& target) {
const std::string& source_item_id =
static_cast<AppListItemView*>(item_view)->item()->id();
AppListItemView* target_view =
static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot));
const std::string& target_view_item_id = target_view->item()->id();
// Make change to data model.
item_list_->RemoveObserver(this);
std::string folder_item_id =
model_->MergeItems(target_view_item_id, source_item_id);
item_list_->AddObserver(this);
if (folder_item_id.empty()) {
LOG(ERROR) << "Unable to merge into item id: " << target_view_item_id;
return;
}
if (folder_item_id != target_view_item_id) {
// New folder was created, change the view model to replace the old target
// view with the new folder item view.
size_t folder_item_index;
if (item_list_->FindItemIndex(folder_item_id, &folder_item_index)) {
int target_view_index = view_model_.GetIndexOfView(target_view);
gfx::Rect target_view_bounds = target_view->bounds();
DeleteItemViewAtIndex(target_view_index);
views::View* target_folder_view =
CreateViewForItemAtIndex(folder_item_index);
target_folder_view->SetBoundsRect(target_view_bounds);
view_model_.Add(target_folder_view, target_view_index);
AddChildView(target_folder_view);
} else {
LOG(ERROR) << "Folder no longer in item_list: " << folder_item_id;
}
}
// Fade out the drag_view_ and delete it when animation ends.
int drag_view_index = view_model_.GetIndexOfView(drag_view_);
view_model_.Remove(drag_view_index);
bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
bounds_animator_.SetAnimationDelegate(
drag_view_,
scoped_ptr<gfx::AnimationDelegate>(
new ItemRemoveAnimationDelegate(drag_view_)));
UpdatePaging();
}
void AppsGridView::ReparentItemForReorder(views::View* item_view,
const Index& target) {
item_list_->RemoveObserver(this);
model_->RemoveObserver(this);
AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item();
DCHECK(reparent_item->IsInFolder());
const std::string source_folder_id = reparent_item->folder_id();
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
int target_model_index = GetModelIndexFromIndex(target);
// Remove the source folder view if there is only 1 item in it, since the
// source folder will be deleted after its only child item removed from it.
if (source_folder->ChildItemCount() == 1u) {
const int deleted_folder_index =
view_model_.GetIndexOfView(activated_folder_item_view());
DeleteItemViewAtIndex(deleted_folder_index);
// Adjust |target_model_index| if it is beyond the deleted folder index.
if (target_model_index > deleted_folder_index)
--target_model_index;
}
// Move the item from its parent folder to top level item list.
// Must move to target_model_index, the location we expect the target item
// to be, not the item location we want to insert before.
int current_model_index = view_model_.GetIndexOfView(item_view);
syncer::StringOrdinal target_position;
if (target_model_index < static_cast<int>(item_list_->item_count()))
target_position = item_list_->item_at(target_model_index)->position();
model_->MoveItemToFolderAt(reparent_item, "", target_position);
view_model_.Move(current_model_index, target_model_index);
RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
item_list_->AddObserver(this);
model_->AddObserver(this);
UpdatePaging();
}
void AppsGridView::ReparentItemToAnotherFolder(views::View* item_view,
const Index& target) {
DCHECK(IsDraggingForReparentInRootLevelGridView());
AppListItemView* target_view =
static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot));
if (!target_view)
return;
// Make change to data model.
item_list_->RemoveObserver(this);
AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item();
DCHECK(reparent_item->IsInFolder());
const std::string source_folder_id = reparent_item->folder_id();
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
// Remove the source folder view if there is only 1 item in it, since the
// source folder will be deleted after its only child item merged into the
// target item.
if (source_folder->ChildItemCount() == 1u)
DeleteItemViewAtIndex(
view_model_.GetIndexOfView(activated_folder_item_view()));
AppListItem* target_item = target_view->item();
// Move item to the target folder.
std::string target_id_after_merge =
model_->MergeItems(target_item->id(), reparent_item->id());
if (target_id_after_merge.empty()) {
LOG(ERROR) << "Unable to reparent to item id: " << target_item->id();
item_list_->AddObserver(this);
return;
}
if (target_id_after_merge != target_item->id()) {
// New folder was created, change the view model to replace the old target
// view with the new folder item view.
const std::string& new_folder_id = reparent_item->folder_id();
size_t new_folder_index;
if (item_list_->FindItemIndex(new_folder_id, &new_folder_index)) {
int target_view_index = view_model_.GetIndexOfView(target_view);
DeleteItemViewAtIndex(target_view_index);
views::View* new_folder_view =
CreateViewForItemAtIndex(new_folder_index);
view_model_.Add(new_folder_view, target_view_index);
AddChildView(new_folder_view);
} else {
LOG(ERROR) << "Folder no longer in item_list: " << new_folder_id;
}
}
RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
item_list_->AddObserver(this);
// Fade out the drag_view_ and delete it when animation ends.
int drag_view_index = view_model_.GetIndexOfView(drag_view_);
view_model_.Remove(drag_view_index);
bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
bounds_animator_.SetAnimationDelegate(
drag_view_,
scoped_ptr<gfx::AnimationDelegate>(
new ItemRemoveAnimationDelegate(drag_view_)));
UpdatePaging();
}
// After moving the re-parenting item out of the folder, if there is only 1 item
// left, remove the last item out of the folder, delete the folder and insert it
// to the data model at the same position. Make the same change to view_model_
// accordingly.
void AppsGridView::RemoveLastItemFromReparentItemFolderIfNecessary(
const std::string& source_folder_id) {
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
if (!source_folder || source_folder->ChildItemCount() != 1u)
return;
// Delete view associated with the folder item to be removed.
DeleteItemViewAtIndex(
view_model_.GetIndexOfView(activated_folder_item_view()));
// Now make the data change to remove the folder item in model.
AppListItem* last_item = source_folder->item_list()->item_at(0);
model_->MoveItemToFolderAt(last_item, "", source_folder->position());
// Create a new item view for the last item in folder.
size_t last_item_index;
if (!item_list_->FindItemIndex(last_item->id(), &last_item_index) ||
last_item_index > static_cast<size_t>(view_model_.view_size())) {
NOTREACHED();
return;
}
views::View* last_item_view = CreateViewForItemAtIndex(last_item_index);
view_model_.Add(last_item_view, last_item_index);
AddChildView(last_item_view);
}
void AppsGridView::CancelFolderItemReparent(AppListItemView* drag_item_view) {
// The icon of the dragged item must target to its final ideal bounds after
// the animation completes.
CalculateIdealBounds();
gfx::Rect target_icon_rect =
GetTargetIconRectInFolder(drag_item_view, activated_folder_item_view_);
gfx::Rect drag_view_icon_to_grid =
drag_item_view->ConvertRectToParent(drag_item_view->GetIconBounds());
drag_view_icon_to_grid.ClampToCenteredSize(
gfx::Size(kGridIconDimension, kGridIconDimension));
TopIconAnimationView* icon_view = new TopIconAnimationView(
drag_item_view->item()->icon(),
target_icon_rect,
false); /* animate like closing folder */
AddChildView(icon_view);
icon_view->SetBoundsRect(drag_view_icon_to_grid);
icon_view->TransformView();
}
void AppsGridView::CancelContextMenusOnCurrentPage() {
int start = pagination_model_.selected_page() * tiles_per_page();
int end = std::min(view_model_.view_size(), start + tiles_per_page());
for (int i = start; i < end; ++i) {
AppListItemView* view =
static_cast<AppListItemView*>(view_model_.view_at(i));
view->CancelContextMenu();
}
}
void AppsGridView::DeleteItemViewAtIndex(int index) {
views::View* item_view = view_model_.view_at(index);
view_model_.Remove(index);
if (item_view == drag_view_)
drag_view_ = NULL;
delete item_view;
}
bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const {
gfx::Rect rect(GetLocalBounds());
rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx);
return rect.Contains(point);
}
void AppsGridView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (dragging())
return;
if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName))
return;
if (delegate_) {
// Always set the previous activated_folder_item_view_ to be visible. This
// prevents a case where the item would remain hidden due the
// |activated_folder_item_view_| changing during the animation. We only
// need to track |activated_folder_item_view_| in the root level grid view.
if (!folder_delegate_) {
if (activated_folder_item_view_)
activated_folder_item_view_->SetVisible(true);
AppListItemView* pressed_item_view =
static_cast<AppListItemView*>(sender);
if (IsFolderItem(pressed_item_view->item()))
activated_folder_item_view_ = pressed_item_view;
else
activated_folder_item_view_ = NULL;
}
delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->item(),
event.flags());
}
}
void AppsGridView::OnListItemAdded(size_t index, AppListItem* item) {
EndDrag(true);
views::View* view = CreateViewForItemAtIndex(index);
view_model_.Add(view, index);
AddChildView(view);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemRemoved(size_t index, AppListItem* item) {
EndDrag(true);
DeleteItemViewAtIndex(index);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemMoved(size_t from_index,
size_t to_index,
AppListItem* item) {
EndDrag(true);
view_model_.Move(from_index, to_index);
UpdatePaging();
AnimateToIdealBounds();
}
void AppsGridView::TotalPagesChanged() {
}
void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) {
if (dragging()) {
CalculateDropTarget(last_drag_point_, true);
Layout();
MaybeStartPageFlipTimer(last_drag_point_);
} else {
ClearSelectedView(selected_view_);
Layout();
}
}
void AppsGridView::TransitionStarted() {
CancelContextMenusOnCurrentPage();
}
void AppsGridView::TransitionChanged() {
// Update layout for valid page transition only since over-scroll no longer
// animates app icons.
const PaginationModel::Transition& transition =
pagination_model_.transition();
if (pagination_model_.is_valid_page(transition.target_page))
Layout();
}
void AppsGridView::OnAppListModelStatusChanged() {
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::SetViewHidden(views::View* view, bool hide, bool immediate) {
ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator());
animator.SetPreemptionStrategy(
immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET :
ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION);
view->layer()->SetOpacity(hide ? 0 : 1);
}
void AppsGridView::OnImplicitAnimationsCompleted() {
if (layer()->opacity() == 0.0f)
SetVisible(false);
}
bool AppsGridView::EnableFolderDragDropUI() {
// Enable drag and drop folder UI only if it is at the app list root level
// and the switch is on and the target folder can still accept new items.
return model_->folders_enabled() && !folder_delegate_ &&
CanDropIntoTarget(drop_target_);
}
bool AppsGridView::CanDropIntoTarget(const Index& drop_target) {
views::View* target_view = GetViewAtSlotOnCurrentPage(drop_target.slot);
if (!target_view)
return true;
AppListItem* target_item =
static_cast<AppListItemView*>(target_view)->item();
// Items can be dropped into non-folders (which have no children) or folders
// that have fewer than the max allowed items.
// OEM folder does not allow to drag/drop other items in it.
return target_item->ChildItemCount() < kMaxFolderItems &&
!IsOEMFolderItem(target_item);
}
// TODO(jennyz): Optimize the calculation for finding nearest tile.
AppsGridView::Index AppsGridView::GetNearestTileForDragView() {
Index nearest_tile;
nearest_tile.page = -1;
nearest_tile.slot = -1;
int d_min = -1;
// Calculate the top left tile |drag_view| intersects.
gfx::Point pt = drag_view_->bounds().origin();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the top right tile |drag_view| intersects.
pt = drag_view_->bounds().top_right();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the bottom left tile |drag_view| intersects.
pt = drag_view_->bounds().bottom_left();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the bottom right tile |drag_view| intersects.
pt = drag_view_->bounds().bottom_right();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
const int d_folder_dropping =
kFolderDroppingCircleRadius + kGridIconDimension / 2;
const int d_reorder = kReorderDroppingCircleRadius + kGridIconDimension / 2;
// If user drags an item across pages to the last page, and targets it
// to the last empty slot on it, push the last item for re-ordering.
if (IsLastPossibleDropTarget(nearest_tile) && d_min < d_reorder) {
drop_attempt_ = DROP_FOR_REORDER;
nearest_tile.slot = nearest_tile.slot - 1;
return nearest_tile;
}
if (IsValidIndex(nearest_tile)) {
if (d_min < d_folder_dropping) {
views::View* target_view = GetViewAtSlotOnCurrentPage(nearest_tile.slot);
if (target_view &&
!IsFolderItem(static_cast<AppListItemView*>(drag_view_)->item())) {
// If a non-folder item is dragged to the target slot with an item
// sitting on it, attempt to drop the dragged item into the folder
// containing the item on nearest_tile.
drop_attempt_ = DROP_FOR_FOLDER;
return nearest_tile;
} else {
// If the target slot is blank, or the dragged item is a folder, attempt
// to re-order.
drop_attempt_ = DROP_FOR_REORDER;
return nearest_tile;
}
} else if (d_min < d_reorder) {
// Entering the re-order circle of the slot.
drop_attempt_ = DROP_FOR_REORDER;
return nearest_tile;
}
}
// If |drag_view| is not entering the re-order or fold dropping region of
// any items, cancel any previous re-order or folder dropping timer, and
// return itself.
drop_attempt_ = DROP_FOR_NONE;
reorder_timer_.Stop();
folder_dropping_timer_.Stop();
// When dragging for reparent a folder item, it should go back to its parent
// folder item if there is no drop target.
if (IsDraggingForReparentInRootLevelGridView()) {
DCHECK(activated_folder_item_view_);
return GetIndexOfView(activated_folder_item_view_);
}
return GetIndexOfView(drag_view_);
}
void AppsGridView::CalculateNearestTileForVertex(const gfx::Point& vertex,
Index* nearest_tile,
int* d_min) {
Index target_index;
gfx::Rect target_bounds = GetTileBoundsForPoint(vertex, &target_index);
if (target_bounds.IsEmpty() || target_index == *nearest_tile)
return;
// Do not count the tile, where drag_view_ used to sit on and is still moving
// on top of it, in calculating nearest tile for drag_view_.
views::View* target_view = GetViewAtSlotOnCurrentPage(target_index.slot);
if (target_index == drag_view_init_index_ && !target_view &&
!IsDraggingForReparentInRootLevelGridView()) {
return;
}
int d_center = GetDistanceBetweenRects(drag_view_->bounds(), target_bounds);
if (*d_min < 0 || d_center < *d_min) {
*d_min = d_center;
*nearest_tile = target_index;
}
}
gfx::Rect AppsGridView::GetTileBoundsForPoint(const gfx::Point& point,
Index *tile_index) {
// Check if |point| is outside of contents bounds.
gfx::Rect bounds(GetContentsBounds());
if (!bounds.Contains(point))
return gfx::Rect();
// Calculate which tile |point| is enclosed in.
int x = point.x();
int y = point.y();
int col = (x - bounds.x()) / kPreferredTileWidth;
int row = (y - bounds.y()) / kPreferredTileHeight;
gfx::Rect tile_rect = GetTileBounds(row, col);
// Check if |point| is outside a valid item's tile.
Index index(pagination_model_.selected_page(), row * cols_ + col);
*tile_index = index;
return tile_rect;
}
gfx::Rect AppsGridView::GetTileBounds(int row, int col) const {
gfx::Rect bounds(GetContentsBounds());
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(bounds);
gfx::Rect tile_rect(
gfx::Point(grid_rect.x() + col * tile_size.width(),
grid_rect.y() + row * tile_size.height()),
tile_size);
return tile_rect;
}
bool AppsGridView::IsLastPossibleDropTarget(const Index& index) const {
int last_possible_slot = view_model_.view_size() % tiles_per_page();
return (index.page == pagination_model_.total_pages() - 1 &&
index.slot == last_possible_slot + 1);
}
views::View* AppsGridView::GetViewAtSlotOnCurrentPage(int slot) {
if (slot < 0)
return NULL;
// Calculate the original bound of the tile at |index|.
int row = slot / cols_;
int col = slot % cols_;
gfx::Rect tile_rect = GetTileBounds(row, col);
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view->bounds() == tile_rect && view != drag_view_)
return view;
}
return NULL;
}
void AppsGridView::SetAsFolderDroppingTarget(const Index& target_index,
bool is_target_folder) {
AppListItemView* target_view =
static_cast<AppListItemView*>(
GetViewAtSlotOnCurrentPage(target_index.slot));
if (target_view)
target_view->SetAsAttemptedFolderTarget(is_target_folder);
}
} // namespace app_list
|
// 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 "ui/app_list/views/apps_grid_view.h"
#include <algorithm>
#include "content/public/browser/web_contents.h"
#include "ui/app_list/app_list_item_model.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/views/app_list_drag_and_drop_host.h"
#include "ui/app_list/views/app_list_item_view.h"
#include "ui/app_list/views/apps_grid_view_delegate.h"
#include "ui/app_list/views/page_switcher.h"
#include "ui/app_list/views/pulsing_block_view.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/events/event.h"
#include "ui/gfx/animation/animation.h"
#include "ui/views/border.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/view_model_utils.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/root_window.h"
#endif
#if defined(OS_WIN) && !defined(USE_AURA)
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/win/shortcut.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/drop_target_win.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#endif
namespace app_list {
namespace {
// Distance a drag needs to be from the app grid to be considered 'outside', at
// which point we rearrange the apps to their pre-drag configuration, as a drop
// then would be canceled. We have a buffer to make it easier to drag apps to
// other pages.
const int kDragBufferPx = 20;
// Padding space in pixels for fixed layout.
const int kLeftRightPadding = 20;
const int kTopPadding = 1;
// Padding space in pixels between pages.
const int kPagePadding = 40;
// Preferred tile size when showing in fixed layout.
const int kPreferredTileWidth = 88;
const int kPreferredTileHeight = 98;
// Width in pixels of the area on the sides that triggers a page flip.
const int kPageFlipZoneSize = 40;
// Delay in milliseconds to do the page flip.
const int kPageFlipDelayInMs = 1000;
// How many pages on either side of the selected one we prerender.
const int kPrerenderPages = 1;
// The drag and drop proxy should get scaled by this factor.
const float kDragAndDropProxyScale = 1.5f;
// RowMoveAnimationDelegate is used when moving an item into a different row.
// Before running the animation, the item's layer is re-created and kept in
// the original position, then the item is moved to just before its target
// position and opacity set to 0. When the animation runs, this delegate moves
// the layer and fades it out while fading in the item at the same time.
class RowMoveAnimationDelegate
: public views::BoundsAnimator::OwnedAnimationDelegate {
public:
RowMoveAnimationDelegate(views::View* view,
ui::Layer* layer,
const gfx::Rect& layer_target)
: view_(view),
layer_(layer),
layer_start_(layer ? layer->bounds() : gfx::Rect()),
layer_target_(layer_target) {
}
virtual ~RowMoveAnimationDelegate() {}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
if (layer_) {
layer_->SetOpacity(1 - animation->GetCurrentValue());
layer_->SetBounds(animation->CurrentValueBetween(layer_start_,
layer_target_));
layer_->ScheduleDraw();
}
}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->layer()->ScheduleDraw();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->layer()->ScheduleDraw();
}
private:
// The view that needs to be wrapped. Owned by views hierarchy.
views::View* view_;
scoped_ptr<ui::Layer> layer_;
const gfx::Rect layer_start_;
const gfx::Rect layer_target_;
DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate);
};
} // namespace
#if defined(OS_WIN) && !defined(USE_AURA)
// Interprets drag events sent from Windows via the drag/drop API and forwards
// them to AppsGridView.
// On Windows, in order to have the OS perform the drag properly we need to
// provide it with a shortcut file which may or may not exist at the time the
// drag is started. Therefore while waiting for that shortcut to be located we
// just do a regular "internal" drag and transition into the synchronous drag
// when the shortcut is found/created. Hence a synchronous drag is an optional
// phase of a regular drag and non-Windows platforms drags are equivalent to a
// Windows drag that never enters the synchronous drag phase.
class SynchronousDrag : public ui::DragSourceWin {
public:
SynchronousDrag(AppsGridView* grid_view,
AppListItemView* drag_view,
const gfx::Point& drag_view_offset)
: grid_view_(grid_view),
drag_view_(drag_view),
drag_view_offset_(drag_view_offset),
has_shortcut_path_(false),
running_(false),
canceled_(false) {}
void set_shortcut_path(const base::FilePath& shortcut_path) {
has_shortcut_path_ = true;
shortcut_path_ = shortcut_path;
}
bool CanRun() {
return has_shortcut_path_ && !running_;
}
void Run() {
DCHECK(CanRun());
running_ = true;
ui::OSExchangeData data;
SetupExchangeData(&data);
// Hide the dragged view because the OS is going to create its own.
const gfx::Size drag_view_size = drag_view_->size();
drag_view_->SetSize(gfx::Size(0, 0));
// Blocks until the drag is finished. Calls into the ui::DragSourceWin
// methods.
DWORD effects;
DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects);
// Restore the dragged view to its original size.
drag_view_->SetSize(drag_view_size);
grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView());
}
private:
// Overridden from ui::DragSourceWin.
virtual void OnDragSourceCancel() OVERRIDE {
canceled_ = true;
}
virtual void OnDragSourceDrop() OVERRIDE {
}
virtual void OnDragSourceMove() OVERRIDE {
grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords());
}
void SetupExchangeData(ui::OSExchangeData* data) {
data->SetFilename(shortcut_path_);
gfx::ImageSkia image(drag_view_->GetDragImage());
gfx::Size image_size(image.size());
drag_utils::SetDragImageOnDataObject(
image,
image.size(),
gfx::Vector2d(drag_view_offset_.x(), drag_view_offset_.y()),
data);
}
HWND GetGridViewHWND() {
return grid_view_->GetWidget()->GetTopLevelWidget()->GetNativeView();
}
bool IsCursorWithinGridView() {
POINT p;
GetCursorPos(&p);
return GetGridViewHWND() == WindowFromPoint(p);
}
gfx::Point GetCursorInGridViewCoords() {
POINT p;
GetCursorPos(&p);
ScreenToClient(GetGridViewHWND(), &p);
gfx::Point grid_view_pt(p.x, p.y);
views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt);
return grid_view_pt;
}
AppsGridView* grid_view_;
AppListItemView* drag_view_;
gfx::Point drag_view_offset_;
bool has_shortcut_path_;
base::FilePath shortcut_path_;
bool running_;
bool canceled_;
DISALLOW_COPY_AND_ASSIGN(SynchronousDrag);
};
#endif // defined(OS_WIN) && !defined(USE_AURA)
AppsGridView::AppsGridView(AppsGridViewDelegate* delegate,
PaginationModel* pagination_model,
content::WebContents* start_page_contents)
: model_(NULL),
item_list_(NULL),
delegate_(delegate),
pagination_model_(pagination_model),
page_switcher_view_(new PageSwitcher(pagination_model)),
start_page_view_(NULL),
cols_(0),
rows_per_page_(0),
selected_view_(NULL),
drag_view_(NULL),
drag_start_page_(-1),
drag_pointer_(NONE),
drag_and_drop_host_(NULL),
forward_events_to_drag_and_drop_host_(false),
page_flip_target_(-1),
page_flip_delay_in_ms_(kPageFlipDelayInMs),
bounds_animator_(this) {
pagination_model_->AddObserver(this);
AddChildView(page_switcher_view_);
if (start_page_contents) {
start_page_view_ =
new views::WebView(start_page_contents->GetBrowserContext());
start_page_view_->SetWebContents(start_page_contents);
AddChildView(start_page_view_);
}
}
AppsGridView::~AppsGridView() {
// Coming here |drag_view_| should already be canceled since otherwise the
// drag would disappear after the app list got animated away and closed,
// which would look odd.
DCHECK(!drag_view_);
if (drag_view_)
EndDrag(true);
if (model_)
model_->RemoveObserver(this);
pagination_model_->RemoveObserver(this);
if (item_list_)
item_list_->RemoveObserver(this);
}
void AppsGridView::SetLayout(int icon_size, int cols, int rows_per_page) {
icon_size_.SetSize(icon_size, icon_size);
cols_ = cols;
rows_per_page_ = rows_per_page;
set_border(views::Border::CreateEmptyBorder(kTopPadding,
kLeftRightPadding,
0,
kLeftRightPadding));
}
void AppsGridView::SetModel(AppListModel* model) {
if (model_)
model_->RemoveObserver(this);
model_ = model;
if (model_)
model_->AddObserver(this);
Update();
}
void AppsGridView::SetItemList(AppListItemList* item_list) {
if (item_list_)
item_list_->RemoveObserver(this);
item_list_ = item_list;
item_list_->AddObserver(this);
Update();
}
void AppsGridView::SetSelectedView(views::View* view) {
if (IsSelectedView(view) || IsDraggedView(view))
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
SetSelectedItemByIndex(index);
}
void AppsGridView::ClearSelectedView(views::View* view) {
if (view && IsSelectedView(view)) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
bool AppsGridView::IsSelectedView(const views::View* view) const {
return selected_view_ == view;
}
void AppsGridView::EnsureViewVisible(const views::View* view) {
if (pagination_model_->has_transition())
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
pagination_model_->SelectPage(index.page, false);
}
void AppsGridView::InitiateDrag(AppListItemView* view,
Pointer pointer,
const ui::LocatedEvent& event) {
DCHECK(view);
if (drag_view_ || pulsing_blocks_model_.view_size())
return;
drag_view_ = view;
drag_view_offset_ = event.location();
drag_start_page_ = pagination_model_->selected_page();
ExtractDragLocation(event, &drag_start_grid_view_);
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
}
void AppsGridView::OnGotShortcutPath(const base::FilePath& path) {
#if defined(OS_WIN) && !defined(USE_AURA)
// Drag may have ended before we get the shortcut path.
if (!synchronous_drag_)
return;
// Setting the shortcut path here means the next time we hit UpdateDrag()
// we'll enter the synchronous drag.
// NOTE we don't Run() the drag here because that causes animations not to
// update for some reason.
synchronous_drag_->set_shortcut_path(path);
DCHECK(synchronous_drag_->CanRun());
#endif
}
void AppsGridView::StartSettingUpSynchronousDrag() {
#if defined(OS_WIN) && !defined(USE_AURA)
if (!delegate_)
return;
delegate_->GetShortcutPathForApp(
drag_view_->model()->id(),
base::Bind(&AppsGridView::OnGotShortcutPath, base::Unretained(this)));
synchronous_drag_ = new SynchronousDrag(this, drag_view_, drag_view_offset_);
#endif
}
bool AppsGridView::RunSynchronousDrag() {
#if defined(OS_WIN) && !defined(USE_AURA)
if (synchronous_drag_ && synchronous_drag_->CanRun()) {
synchronous_drag_->Run();
synchronous_drag_ = NULL;
return true;
}
#endif
return false;
}
void AppsGridView::CleanUpSynchronousDrag() {
#if defined(OS_WIN) && !defined(USE_AURA)
synchronous_drag_ = NULL;
#endif
}
void AppsGridView::UpdateDragFromItem(Pointer pointer,
const ui::LocatedEvent& event) {
gfx::Point drag_point_in_grid_view;
ExtractDragLocation(event, &drag_point_in_grid_view);
UpdateDrag(pointer, drag_point_in_grid_view);
if (!dragging())
return;
// If a drag and drop host is provided, see if the drag operation needs to be
// forwarded.
DispatchDragEventToDragAndDropHost(event.root_location());
if (drag_and_drop_host_)
drag_and_drop_host_->UpdateDragIconProxy(event.root_location());
}
void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
if (RunSynchronousDrag())
return;
gfx::Vector2d drag_vector(point - drag_start_grid_view_);
if (!dragging() && ExceededDragThreshold(drag_vector)) {
drag_pointer_ = pointer;
// Move the view to the front so that it appears on top of other views.
ReorderChildView(drag_view_, -1);
bounds_animator_.StopAnimatingView(drag_view_);
StartSettingUpSynchronousDrag();
StartDragAndDropHostDrag(point);
}
if (drag_pointer_ != pointer)
return;
last_drag_point_ = point;
const Index last_drop_target = drop_target_;
CalculateDropTarget(last_drag_point_, false);
if (IsPointWithinDragBuffer(last_drag_point_))
MaybeStartPageFlipTimer(last_drag_point_);
else
StopPageFlipTimer();
gfx::Point page_switcher_point(last_drag_point_);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
page_switcher_view_->UpdateUIForDragPoint(page_switcher_point);
if (last_drop_target != drop_target_)
AnimateToIdealBounds();
drag_view_->SetPosition(drag_view_start_ + drag_vector);
}
void AppsGridView::EndDrag(bool cancel) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
// Coming here a drag and drop was in progress.
bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_;
if (forward_events_to_drag_and_drop_host_) {
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(cancel);
} else if (!cancel && dragging()) {
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_))
MoveItemInModel(drag_view_, drop_target_);
}
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
if (landed_in_drag_and_drop_host) {
// Move the item directly to the target location, avoiding the "zip back"
// animation if the user was pinning it to the shelf.
int i = drop_target_.slot;
gfx::Rect bounds = view_model_.ideal_bounds(i);
drag_view_->SetBoundsRect(bounds);
}
// Fade in slowly if it landed in the shelf.
SetViewHidden(drag_view_,
false /* hide */,
!landed_in_drag_and_drop_host /* animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
drag_pointer_ = NONE;
drop_target_ = Index();
drag_view_ = NULL;
drag_start_grid_view_ = gfx::Point();
drag_start_page_ = -1;
drag_view_offset_ = gfx::Point();
AnimateToIdealBounds();
StopPageFlipTimer();
}
void AppsGridView::StopPageFlipTimer() {
page_flip_timer_.Stop();
page_flip_target_ = -1;
}
bool AppsGridView::IsDraggedView(const views::View* view) const {
return drag_view_ == view;
}
void AppsGridView::SetDragAndDropHostOfCurrentAppList(
ApplicationDragAndDropHost* drag_and_drop_host) {
drag_and_drop_host_ = drag_and_drop_host;
}
void AppsGridView::Prerender(int page_index) {
Layout();
int start = std::max(0, (page_index - kPrerenderPages) * tiles_per_page());
int end = std::min(view_model_.view_size(),
(page_index + 1 + kPrerenderPages) * tiles_per_page());
for (int i = start; i < end; i++) {
AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i));
v->Prerender();
}
}
gfx::Size AppsGridView::GetPreferredSize() {
const gfx::Insets insets(GetInsets());
const gfx::Size tile_size = gfx::Size(kPreferredTileWidth,
kPreferredTileHeight);
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
return gfx::Size(
tile_size.width() * cols_ + insets.width(),
tile_size.height() * rows_per_page_ +
page_switcher_height + insets.height());
}
bool AppsGridView::GetDropFormats(
int* formats,
std::set<OSExchangeData::CustomFormat>* custom_formats) {
// TODO(koz): Only accept a specific drag type for app shortcuts.
*formats = OSExchangeData::FILE_NAME;
return true;
}
bool AppsGridView::CanDrop(const OSExchangeData& data) {
return true;
}
int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_MOVE;
}
void AppsGridView::Layout() {
if (bounds_animator_.IsAnimating())
bounds_animator_.Cancel();
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view != drag_view_)
view->SetBoundsRect(view_model_.ideal_bounds(i));
}
views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_);
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
gfx::Rect rect(GetContentsBounds());
rect.set_y(rect.bottom() - page_switcher_height);
rect.set_height(page_switcher_height);
page_switcher_view_->SetBoundsRect(rect);
LayoutStartPage();
}
bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyPressed(event);
if (!handled) {
const int forward_dir = base::i18n::IsRTL() ? -1 : 1;
switch (event.key_code()) {
case ui::VKEY_LEFT:
MoveSelected(0, -forward_dir, 0);
return true;
case ui::VKEY_RIGHT:
MoveSelected(0, forward_dir, 0);
return true;
case ui::VKEY_UP:
MoveSelected(0, 0, -1);
return true;
case ui::VKEY_DOWN:
MoveSelected(0, 0, 1);
return true;
case ui::VKEY_PRIOR: {
MoveSelected(-1, 0, 0);
return true;
}
case ui::VKEY_NEXT: {
MoveSelected(1, 0, 0);
return true;
}
default:
break;
}
}
return handled;
}
bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyReleased(event);
return handled;
}
void AppsGridView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (!details.is_add && details.parent == this) {
if (selected_view_ == details.child)
selected_view_ = NULL;
if (drag_view_ == details.child)
EndDrag(true);
bounds_animator_.StopAnimatingView(details.child);
}
}
void AppsGridView::Update() {
DCHECK(!selected_view_ && !drag_view_);
if (!item_list_)
return;
view_model_.Clear();
if (!item_list_->item_count())
return;
for (size_t i = 0; i < item_list_->item_count(); ++i) {
views::View* view = CreateViewForItemAtIndex(i);
view_model_.Add(view, i);
AddChildView(view);
}
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::UpdatePaging() {
int total_page = start_page_view_ ? 1 : 0;
if (view_model_.view_size() && tiles_per_page())
total_page += (view_model_.view_size() - 1) / tiles_per_page() + 1;
pagination_model_->SetTotalPages(total_page);
}
void AppsGridView::UpdatePulsingBlockViews() {
const int available_slots =
tiles_per_page() - item_list_->item_count() % tiles_per_page();
const int desired = model_->status() == AppListModel::STATUS_SYNCING ?
available_slots : 0;
if (pulsing_blocks_model_.view_size() == desired)
return;
while (pulsing_blocks_model_.view_size() > desired) {
views::View* view = pulsing_blocks_model_.view_at(0);
pulsing_blocks_model_.Remove(0);
delete view;
}
while (pulsing_blocks_model_.view_size() < desired) {
views::View* view = new PulsingBlockView(
gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true);
pulsing_blocks_model_.Add(view, 0);
AddChildView(view);
}
}
views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) {
DCHECK_LT(index, item_list_->item_count());
AppListItemView* view = new AppListItemView(this,
item_list_->item_at(index));
view->SetIconSize(icon_size_);
#if defined(USE_AURA)
view->SetPaintToLayer(true);
view->SetFillsBoundsOpaquely(false);
#endif
return view;
}
AppsGridView::Index AppsGridView::GetIndexFromModelIndex(
int model_index) const {
int page = model_index / tiles_per_page();
if (start_page_view_)
++page;
return Index(page, model_index % tiles_per_page());
}
int AppsGridView::GetModelIndexFromIndex(const Index& index) const {
int model_index = index.page * tiles_per_page() + index.slot;
if (start_page_view_)
model_index -= tiles_per_page();
return model_index;
}
void AppsGridView::SetSelectedItemByIndex(const Index& index) {
if (GetIndexOfView(selected_view_) == index)
return;
views::View* new_selection = GetViewAtIndex(index);
if (!new_selection)
return; // Keep current selection.
if (selected_view_)
selected_view_->SchedulePaint();
EnsureViewVisible(new_selection);
selected_view_ = new_selection;
selected_view_->SchedulePaint();
selected_view_->NotifyAccessibilityEvent(
ui::AccessibilityTypes::EVENT_FOCUS, true);
}
bool AppsGridView::IsValidIndex(const Index& index) const {
const int item_page_start = start_page_view_ ? 1 : 0;
return index.page >= item_page_start &&
index.page < pagination_model_->total_pages() &&
index.slot >= 0 &&
index.slot < tiles_per_page() &&
GetModelIndexFromIndex(index) < view_model_.view_size();
}
AppsGridView::Index AppsGridView::GetIndexOfView(
const views::View* view) const {
const int model_index = view_model_.GetIndexOfView(view);
if (model_index == -1)
return Index();
return GetIndexFromModelIndex(model_index);
}
views::View* AppsGridView::GetViewAtIndex(const Index& index) const {
if (!IsValidIndex(index))
return NULL;
const int model_index = GetModelIndexFromIndex(index);
return view_model_.view_at(model_index);
}
void AppsGridView::MoveSelected(int page_delta,
int slot_x_delta,
int slot_y_delta) {
if (!selected_view_)
return SetSelectedItemByIndex(Index(pagination_model_->selected_page(), 0));
const Index& selected = GetIndexOfView(selected_view_);
int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_;
if (selected.slot % cols_ == 0 && slot_x_delta == -1) {
if (selected.page > 0) {
page_delta = -1;
target_slot = selected.slot + cols_ - 1;
} else {
target_slot = selected.slot;
}
}
if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) {
if (selected.page < pagination_model_->total_pages() - 1) {
page_delta = 1;
target_slot = selected.slot - cols_ + 1;
} else {
target_slot = selected.slot;
}
}
// Clamp the target slot to the last item if we are moving to the last page
// but our target slot is past the end of the item list.
if (page_delta &&
selected.page + page_delta == pagination_model_->total_pages() - 1) {
int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page();
if (last_item_slot < target_slot) {
target_slot = last_item_slot;
}
}
int target_page = std::min(pagination_model_->total_pages() - 1,
std::max(selected.page + page_delta, 0));
SetSelectedItemByIndex(Index(target_page, target_slot));
}
void AppsGridView::CalculateIdealBounds() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(rect);
// Page width including padding pixels. A tile.x + page_width means the same
// tile slot in the next page.
const int page_width = grid_rect.width() + kPagePadding;
// If there is a transition, calculates offset for current and target page.
const int current_page = pagination_model_->selected_page();
const PaginationModel::Transition& transition =
pagination_model_->transition();
const bool is_valid =
pagination_model_->is_valid_page(transition.target_page);
// Transition to right means negative offset.
const int dir = transition.target_page > current_page ? -1 : 1;
const int transition_offset = is_valid ?
transition.progress * page_width * dir : 0;
const int total_views =
view_model_.view_size() + pulsing_blocks_model_.view_size();
int slot_index = 0;
for (int i = 0; i < total_views; ++i) {
if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_)
continue;
Index view_index = GetIndexFromModelIndex(slot_index);
if (drop_target_ == view_index) {
++slot_index;
view_index = GetIndexFromModelIndex(slot_index);
}
// Decides an x_offset for current item.
int x_offset = 0;
if (view_index.page < current_page)
x_offset = -page_width;
else if (view_index.page > current_page)
x_offset = page_width;
if (is_valid) {
if (view_index.page == current_page ||
view_index.page == transition.target_page) {
x_offset += transition_offset;
}
}
const int row = view_index.slot / cols_;
const int col = view_index.slot % cols_;
gfx::Rect tile_slot(
gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset,
grid_rect.y() + row * tile_size.height()),
tile_size);
if (i < view_model_.view_size()) {
view_model_.set_ideal_bounds(i, tile_slot);
} else {
pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(),
tile_slot);
}
++slot_index;
}
}
void AppsGridView::AnimateToIdealBounds() {
const gfx::Rect visible_bounds(GetVisibleBounds());
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view == drag_view_)
continue;
const gfx::Rect& target = view_model_.ideal_bounds(i);
if (bounds_animator_.GetTargetBounds(view) == target)
continue;
const gfx::Rect& current = view->bounds();
const bool current_visible = visible_bounds.Intersects(current);
const bool target_visible = visible_bounds.Intersects(target);
const bool visible = current_visible || target_visible;
const int y_diff = target.y() - current.y();
if (visible && y_diff && y_diff % kPreferredTileHeight == 0) {
AnimationBetweenRows(view,
current_visible,
current,
target_visible,
target);
} else {
bounds_animator_.AnimateViewTo(view, target);
}
}
}
void AppsGridView::AnimationBetweenRows(views::View* view,
bool animate_current,
const gfx::Rect& current,
bool animate_target,
const gfx::Rect& target) {
// Determine page of |current| and |target|. -1 means in the left invisible
// page, 0 is the center visible page and 1 means in the right invisible page.
const int current_page = current.x() < 0 ? -1 :
current.x() >= width() ? 1 : 0;
const int target_page = target.x() < 0 ? -1 :
target.x() >= width() ? 1 : 0;
const int dir = current_page < target_page ||
(current_page == target_page && current.y() < target.y()) ? 1 : -1;
#if defined(USE_AURA)
scoped_ptr<ui::Layer> layer;
if (animate_current) {
layer.reset(view->RecreateLayer());
layer->SuppressPaint();
view->SetFillsBoundsOpaquely(false);
view->layer()->SetOpacity(0.f);
}
gfx::Rect current_out(current);
current_out.Offset(dir * kPreferredTileWidth, 0);
#endif
gfx::Rect target_in(target);
if (animate_target)
target_in.Offset(-dir * kPreferredTileWidth, 0);
view->SetBoundsRect(target_in);
bounds_animator_.AnimateViewTo(view, target);
#if defined(USE_AURA)
bounds_animator_.SetAnimationDelegate(
view,
new RowMoveAnimationDelegate(view, layer.release(), current_out),
true);
#endif
}
void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event,
gfx::Point* drag_point) {
#if defined(USE_AURA)
// Use root location of |event| instead of location in |drag_view_|'s
// coordinates because |drag_view_| has a scale transform and location
// could have integer round error and causes jitter.
*drag_point = event.root_location();
// GetWidget() could be NULL for tests.
if (GetWidget()) {
aura::Window::ConvertPointToTarget(
GetWidget()->GetNativeWindow()->GetRootWindow(),
GetWidget()->GetNativeWindow(),
drag_point);
}
views::View::ConvertPointFromWidget(this, drag_point);
#else
// For non-aura, root location is not clearly defined but |drag_view_| does
// not have the scale transform. So no round error would be introduced and
// it's okay to use View::ConvertPointToTarget.
*drag_point = event.location();
views::View::ConvertPointToTarget(drag_view_, this, drag_point);
#endif
}
void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point,
bool use_page_button_hovering) {
int current_page = pagination_model_->selected_page();
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
current_page = drag_start_page_;
}
if (use_page_button_hovering &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_->is_valid_page(page)) {
drop_target_.page = page;
drop_target_.slot = tiles_per_page() - 1;
}
} else {
gfx::Rect bounds(GetContentsBounds());
const int drop_row = (point.y() - bounds.y()) / kPreferredTileHeight;
const int drop_col = std::min(cols_ - 1,
(point.x() - bounds.x()) / kPreferredTileWidth);
drop_target_.page = current_page;
drop_target_.slot = std::max(0, std::min(
tiles_per_page() - 1,
drop_row * cols_ + drop_col));
}
// Limits to the last possible slot on last page.
if (drop_target_.page == pagination_model_->total_pages() - 1) {
drop_target_.slot = std::min(
(view_model_.view_size() - 1) % tiles_per_page(),
drop_target_.slot);
}
}
void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) {
// When a drag and drop host is given, the item can be dragged out of the app
// list window. In that case a proxy widget needs to be used.
// Note: This code has very likely to be changed for Windows (non metro mode)
// when a |drag_and_drop_host_| gets implemented.
if (!drag_view_ || !drag_and_drop_host_)
return;
gfx::Point screen_location = grid_location;
views::View::ConvertPointToScreen(this, &screen_location);
// Determine the mouse offset to the center of the icon so that the drag and
// drop host follows this layer.
gfx::Vector2d delta = drag_view_offset_ -
drag_view_->GetLocalBounds().CenterPoint();
delta.set_y(delta.y() + drag_view_->title()->size().height() / 2);
// We have to hide the original item since the drag and drop host will do
// the OS dependent code to "lift off the dragged item".
drag_and_drop_host_->CreateDragIconProxy(screen_location,
drag_view_->model()->icon(),
drag_view_,
delta,
kDragAndDropProxyScale);
SetViewHidden(drag_view_,
true /* hide */,
true /* no animation */);
}
void AppsGridView::DispatchDragEventToDragAndDropHost(
const gfx::Point& point) {
if (!drag_view_ || !drag_and_drop_host_)
return;
if (bounds().Contains(last_drag_point_)) {
// The event was issued inside the app menu and we should get all events.
if (forward_events_to_drag_and_drop_host_) {
// The DnD host was previously called and needs to be informed that the
// session returns to the owner.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
// The event happened outside our app menu and we might need to dispatch.
if (forward_events_to_drag_and_drop_host_) {
// Dispatch since we have already started.
if (!drag_and_drop_host_->Drag(point)) {
// The host is not active any longer and we cancel the operation.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (drag_and_drop_host_->StartDrag(drag_view_->model()->id(), point)) {
// From now on we forward the drag events.
forward_events_to_drag_and_drop_host_ = true;
// Any flip operations are stopped.
StopPageFlipTimer();
}
}
}
}
void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) {
if (!IsPointWithinDragBuffer(drag_point))
StopPageFlipTimer();
int new_page_flip_target = -1;
if (page_switcher_view_->bounds().Contains(drag_point)) {
gfx::Point page_switcher_point(drag_point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
new_page_flip_target =
page_switcher_view_->GetPageForPoint(page_switcher_point);
}
// TODO(xiyuan): Fix this for RTL.
if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize)
new_page_flip_target = pagination_model_->selected_page() - 1;
if (new_page_flip_target == -1 &&
drag_point.x() > width() - kPageFlipZoneSize) {
new_page_flip_target = pagination_model_->selected_page() + 1;
}
if (new_page_flip_target == page_flip_target_)
return;
StopPageFlipTimer();
if (pagination_model_->is_valid_page(new_page_flip_target)) {
page_flip_target_ = new_page_flip_target;
if (page_flip_target_ != pagination_model_->selected_page()) {
page_flip_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_),
this, &AppsGridView::OnPageFlipTimer);
}
}
}
void AppsGridView::OnPageFlipTimer() {
DCHECK(pagination_model_->is_valid_page(page_flip_target_));
pagination_model_->SelectPage(page_flip_target_, true);
}
void AppsGridView::MoveItemInModel(views::View* item_view,
const Index& target) {
int current_model_index = view_model_.GetIndexOfView(item_view);
DCHECK_GE(current_model_index, 0);
int target_model_index = GetModelIndexFromIndex(target);
if (target_model_index == current_model_index)
return;
item_list_->RemoveObserver(this);
item_list_->MoveItem(current_model_index, target_model_index);
view_model_.Move(current_model_index, target_model_index);
item_list_->AddObserver(this);
if (pagination_model_->selected_page() != target.page)
pagination_model_->SelectPage(target.page, false);
}
void AppsGridView::CancelContextMenusOnCurrentPage() {
int start = pagination_model_->selected_page() * tiles_per_page();
int end = std::min(view_model_.view_size(), start + tiles_per_page());
for (int i = start; i < end; ++i) {
AppListItemView* view =
static_cast<AppListItemView*>(view_model_.view_at(i));
view->CancelContextMenu();
}
}
bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const {
gfx::Rect rect(GetLocalBounds());
rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx);
return rect.Contains(point);
}
void AppsGridView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (dragging())
return;
if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName))
return;
if (delegate_) {
delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->model(),
event.flags());
}
}
void AppsGridView::LayoutStartPage() {
if (!start_page_view_)
return;
gfx::Rect start_page_bounds(GetLocalBounds());
start_page_bounds.set_height(start_page_bounds.height() -
page_switcher_view_->height());
const int page_width = width() + kPagePadding;
const int current_page = pagination_model_->selected_page();
if (current_page > 0)
start_page_bounds.Offset(-page_width, 0);
const PaginationModel::Transition& transition =
pagination_model_->transition();
if (current_page == 0 || transition.target_page == 0) {
const int dir = transition.target_page > current_page ? -1 : 1;
start_page_bounds.Offset(transition.progress * page_width * dir, 0);
}
start_page_view_->SetBoundsRect(start_page_bounds);
}
void AppsGridView::OnListItemAdded(size_t index, AppListItemModel* item) {
EndDrag(true);
views::View* view = CreateViewForItemAtIndex(index);
view_model_.Add(view, index);
AddChildView(view);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemRemoved(size_t index, AppListItemModel* item) {
EndDrag(true);
views::View* view = view_model_.view_at(index);
view_model_.Remove(index);
delete view;
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemMoved(size_t from_index,
size_t to_index,
AppListItemModel* item) {
EndDrag(true);
view_model_.Move(from_index, to_index);
UpdatePaging();
AnimateToIdealBounds();
}
void AppsGridView::TotalPagesChanged() {
}
void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) {
if (dragging()) {
CalculateDropTarget(last_drag_point_, true);
Layout();
MaybeStartPageFlipTimer(last_drag_point_);
} else {
ClearSelectedView(selected_view_);
Layout();
}
}
void AppsGridView::TransitionStarted() {
CancelContextMenusOnCurrentPage();
}
void AppsGridView::TransitionChanged() {
// Update layout for valid page transition only since over-scroll no longer
// animates app icons.
const PaginationModel::Transition& transition =
pagination_model_->transition();
if (pagination_model_->is_valid_page(transition.target_page))
Layout();
}
void AppsGridView::OnAppListModelStatusChanged() {
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::SetViewHidden(views::View* view, bool hide, bool immediate) {
#if defined(USE_AURA)
ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator());
animator.SetPreemptionStrategy(
immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET :
ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION);
view->layer()->SetOpacity(hide ? 0 : 1);
#endif
}
} // namespace app_list
app_list: Fix sync animation crash.
AppsGridView is used for folder view and it has a NULL item_list_ initially.
This causes a crash when attempting to create pulsing blocks for sync
animation.
BUG=314855
R=jennyz@chromium.org
Review URL: https://codereview.chromium.org/59623005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@233226 0039d316-1c4b-4281-b951-d872f2087c98
// 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 "ui/app_list/views/apps_grid_view.h"
#include <algorithm>
#include "content/public/browser/web_contents.h"
#include "ui/app_list/app_list_item_model.h"
#include "ui/app_list/pagination_model.h"
#include "ui/app_list/views/app_list_drag_and_drop_host.h"
#include "ui/app_list/views/app_list_item_view.h"
#include "ui/app_list/views/apps_grid_view_delegate.h"
#include "ui/app_list/views/page_switcher.h"
#include "ui/app_list/views/pulsing_block_view.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/events/event.h"
#include "ui/gfx/animation/animation.h"
#include "ui/views/border.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/view_model_utils.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/root_window.h"
#endif
#if defined(OS_WIN) && !defined(USE_AURA)
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/win/shortcut.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/drop_target_win.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#endif
namespace app_list {
namespace {
// Distance a drag needs to be from the app grid to be considered 'outside', at
// which point we rearrange the apps to their pre-drag configuration, as a drop
// then would be canceled. We have a buffer to make it easier to drag apps to
// other pages.
const int kDragBufferPx = 20;
// Padding space in pixels for fixed layout.
const int kLeftRightPadding = 20;
const int kTopPadding = 1;
// Padding space in pixels between pages.
const int kPagePadding = 40;
// Preferred tile size when showing in fixed layout.
const int kPreferredTileWidth = 88;
const int kPreferredTileHeight = 98;
// Width in pixels of the area on the sides that triggers a page flip.
const int kPageFlipZoneSize = 40;
// Delay in milliseconds to do the page flip.
const int kPageFlipDelayInMs = 1000;
// How many pages on either side of the selected one we prerender.
const int kPrerenderPages = 1;
// The drag and drop proxy should get scaled by this factor.
const float kDragAndDropProxyScale = 1.5f;
// RowMoveAnimationDelegate is used when moving an item into a different row.
// Before running the animation, the item's layer is re-created and kept in
// the original position, then the item is moved to just before its target
// position and opacity set to 0. When the animation runs, this delegate moves
// the layer and fades it out while fading in the item at the same time.
class RowMoveAnimationDelegate
: public views::BoundsAnimator::OwnedAnimationDelegate {
public:
RowMoveAnimationDelegate(views::View* view,
ui::Layer* layer,
const gfx::Rect& layer_target)
: view_(view),
layer_(layer),
layer_start_(layer ? layer->bounds() : gfx::Rect()),
layer_target_(layer_target) {
}
virtual ~RowMoveAnimationDelegate() {}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
if (layer_) {
layer_->SetOpacity(1 - animation->GetCurrentValue());
layer_->SetBounds(animation->CurrentValueBetween(layer_start_,
layer_target_));
layer_->ScheduleDraw();
}
}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->layer()->ScheduleDraw();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->layer()->ScheduleDraw();
}
private:
// The view that needs to be wrapped. Owned by views hierarchy.
views::View* view_;
scoped_ptr<ui::Layer> layer_;
const gfx::Rect layer_start_;
const gfx::Rect layer_target_;
DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate);
};
} // namespace
#if defined(OS_WIN) && !defined(USE_AURA)
// Interprets drag events sent from Windows via the drag/drop API and forwards
// them to AppsGridView.
// On Windows, in order to have the OS perform the drag properly we need to
// provide it with a shortcut file which may or may not exist at the time the
// drag is started. Therefore while waiting for that shortcut to be located we
// just do a regular "internal" drag and transition into the synchronous drag
// when the shortcut is found/created. Hence a synchronous drag is an optional
// phase of a regular drag and non-Windows platforms drags are equivalent to a
// Windows drag that never enters the synchronous drag phase.
class SynchronousDrag : public ui::DragSourceWin {
public:
SynchronousDrag(AppsGridView* grid_view,
AppListItemView* drag_view,
const gfx::Point& drag_view_offset)
: grid_view_(grid_view),
drag_view_(drag_view),
drag_view_offset_(drag_view_offset),
has_shortcut_path_(false),
running_(false),
canceled_(false) {}
void set_shortcut_path(const base::FilePath& shortcut_path) {
has_shortcut_path_ = true;
shortcut_path_ = shortcut_path;
}
bool CanRun() {
return has_shortcut_path_ && !running_;
}
void Run() {
DCHECK(CanRun());
running_ = true;
ui::OSExchangeData data;
SetupExchangeData(&data);
// Hide the dragged view because the OS is going to create its own.
const gfx::Size drag_view_size = drag_view_->size();
drag_view_->SetSize(gfx::Size(0, 0));
// Blocks until the drag is finished. Calls into the ui::DragSourceWin
// methods.
DWORD effects;
DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects);
// Restore the dragged view to its original size.
drag_view_->SetSize(drag_view_size);
grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView());
}
private:
// Overridden from ui::DragSourceWin.
virtual void OnDragSourceCancel() OVERRIDE {
canceled_ = true;
}
virtual void OnDragSourceDrop() OVERRIDE {
}
virtual void OnDragSourceMove() OVERRIDE {
grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords());
}
void SetupExchangeData(ui::OSExchangeData* data) {
data->SetFilename(shortcut_path_);
gfx::ImageSkia image(drag_view_->GetDragImage());
gfx::Size image_size(image.size());
drag_utils::SetDragImageOnDataObject(
image,
image.size(),
gfx::Vector2d(drag_view_offset_.x(), drag_view_offset_.y()),
data);
}
HWND GetGridViewHWND() {
return grid_view_->GetWidget()->GetTopLevelWidget()->GetNativeView();
}
bool IsCursorWithinGridView() {
POINT p;
GetCursorPos(&p);
return GetGridViewHWND() == WindowFromPoint(p);
}
gfx::Point GetCursorInGridViewCoords() {
POINT p;
GetCursorPos(&p);
ScreenToClient(GetGridViewHWND(), &p);
gfx::Point grid_view_pt(p.x, p.y);
views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt);
return grid_view_pt;
}
AppsGridView* grid_view_;
AppListItemView* drag_view_;
gfx::Point drag_view_offset_;
bool has_shortcut_path_;
base::FilePath shortcut_path_;
bool running_;
bool canceled_;
DISALLOW_COPY_AND_ASSIGN(SynchronousDrag);
};
#endif // defined(OS_WIN) && !defined(USE_AURA)
AppsGridView::AppsGridView(AppsGridViewDelegate* delegate,
PaginationModel* pagination_model,
content::WebContents* start_page_contents)
: model_(NULL),
item_list_(NULL),
delegate_(delegate),
pagination_model_(pagination_model),
page_switcher_view_(new PageSwitcher(pagination_model)),
start_page_view_(NULL),
cols_(0),
rows_per_page_(0),
selected_view_(NULL),
drag_view_(NULL),
drag_start_page_(-1),
drag_pointer_(NONE),
drag_and_drop_host_(NULL),
forward_events_to_drag_and_drop_host_(false),
page_flip_target_(-1),
page_flip_delay_in_ms_(kPageFlipDelayInMs),
bounds_animator_(this) {
pagination_model_->AddObserver(this);
AddChildView(page_switcher_view_);
if (start_page_contents) {
start_page_view_ =
new views::WebView(start_page_contents->GetBrowserContext());
start_page_view_->SetWebContents(start_page_contents);
AddChildView(start_page_view_);
}
}
AppsGridView::~AppsGridView() {
// Coming here |drag_view_| should already be canceled since otherwise the
// drag would disappear after the app list got animated away and closed,
// which would look odd.
DCHECK(!drag_view_);
if (drag_view_)
EndDrag(true);
if (model_)
model_->RemoveObserver(this);
pagination_model_->RemoveObserver(this);
if (item_list_)
item_list_->RemoveObserver(this);
}
void AppsGridView::SetLayout(int icon_size, int cols, int rows_per_page) {
icon_size_.SetSize(icon_size, icon_size);
cols_ = cols;
rows_per_page_ = rows_per_page;
set_border(views::Border::CreateEmptyBorder(kTopPadding,
kLeftRightPadding,
0,
kLeftRightPadding));
}
void AppsGridView::SetModel(AppListModel* model) {
if (model_)
model_->RemoveObserver(this);
model_ = model;
if (model_)
model_->AddObserver(this);
Update();
}
void AppsGridView::SetItemList(AppListItemList* item_list) {
if (item_list_)
item_list_->RemoveObserver(this);
item_list_ = item_list;
item_list_->AddObserver(this);
Update();
}
void AppsGridView::SetSelectedView(views::View* view) {
if (IsSelectedView(view) || IsDraggedView(view))
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
SetSelectedItemByIndex(index);
}
void AppsGridView::ClearSelectedView(views::View* view) {
if (view && IsSelectedView(view)) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
bool AppsGridView::IsSelectedView(const views::View* view) const {
return selected_view_ == view;
}
void AppsGridView::EnsureViewVisible(const views::View* view) {
if (pagination_model_->has_transition())
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
pagination_model_->SelectPage(index.page, false);
}
void AppsGridView::InitiateDrag(AppListItemView* view,
Pointer pointer,
const ui::LocatedEvent& event) {
DCHECK(view);
if (drag_view_ || pulsing_blocks_model_.view_size())
return;
drag_view_ = view;
drag_view_offset_ = event.location();
drag_start_page_ = pagination_model_->selected_page();
ExtractDragLocation(event, &drag_start_grid_view_);
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
}
void AppsGridView::OnGotShortcutPath(const base::FilePath& path) {
#if defined(OS_WIN) && !defined(USE_AURA)
// Drag may have ended before we get the shortcut path.
if (!synchronous_drag_)
return;
// Setting the shortcut path here means the next time we hit UpdateDrag()
// we'll enter the synchronous drag.
// NOTE we don't Run() the drag here because that causes animations not to
// update for some reason.
synchronous_drag_->set_shortcut_path(path);
DCHECK(synchronous_drag_->CanRun());
#endif
}
void AppsGridView::StartSettingUpSynchronousDrag() {
#if defined(OS_WIN) && !defined(USE_AURA)
if (!delegate_)
return;
delegate_->GetShortcutPathForApp(
drag_view_->model()->id(),
base::Bind(&AppsGridView::OnGotShortcutPath, base::Unretained(this)));
synchronous_drag_ = new SynchronousDrag(this, drag_view_, drag_view_offset_);
#endif
}
bool AppsGridView::RunSynchronousDrag() {
#if defined(OS_WIN) && !defined(USE_AURA)
if (synchronous_drag_ && synchronous_drag_->CanRun()) {
synchronous_drag_->Run();
synchronous_drag_ = NULL;
return true;
}
#endif
return false;
}
void AppsGridView::CleanUpSynchronousDrag() {
#if defined(OS_WIN) && !defined(USE_AURA)
synchronous_drag_ = NULL;
#endif
}
void AppsGridView::UpdateDragFromItem(Pointer pointer,
const ui::LocatedEvent& event) {
gfx::Point drag_point_in_grid_view;
ExtractDragLocation(event, &drag_point_in_grid_view);
UpdateDrag(pointer, drag_point_in_grid_view);
if (!dragging())
return;
// If a drag and drop host is provided, see if the drag operation needs to be
// forwarded.
DispatchDragEventToDragAndDropHost(event.root_location());
if (drag_and_drop_host_)
drag_and_drop_host_->UpdateDragIconProxy(event.root_location());
}
void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
if (RunSynchronousDrag())
return;
gfx::Vector2d drag_vector(point - drag_start_grid_view_);
if (!dragging() && ExceededDragThreshold(drag_vector)) {
drag_pointer_ = pointer;
// Move the view to the front so that it appears on top of other views.
ReorderChildView(drag_view_, -1);
bounds_animator_.StopAnimatingView(drag_view_);
StartSettingUpSynchronousDrag();
StartDragAndDropHostDrag(point);
}
if (drag_pointer_ != pointer)
return;
last_drag_point_ = point;
const Index last_drop_target = drop_target_;
CalculateDropTarget(last_drag_point_, false);
if (IsPointWithinDragBuffer(last_drag_point_))
MaybeStartPageFlipTimer(last_drag_point_);
else
StopPageFlipTimer();
gfx::Point page_switcher_point(last_drag_point_);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
page_switcher_view_->UpdateUIForDragPoint(page_switcher_point);
if (last_drop_target != drop_target_)
AnimateToIdealBounds();
drag_view_->SetPosition(drag_view_start_ + drag_vector);
}
void AppsGridView::EndDrag(bool cancel) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
// Coming here a drag and drop was in progress.
bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_;
if (forward_events_to_drag_and_drop_host_) {
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(cancel);
} else if (!cancel && dragging()) {
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_))
MoveItemInModel(drag_view_, drop_target_);
}
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
if (landed_in_drag_and_drop_host) {
// Move the item directly to the target location, avoiding the "zip back"
// animation if the user was pinning it to the shelf.
int i = drop_target_.slot;
gfx::Rect bounds = view_model_.ideal_bounds(i);
drag_view_->SetBoundsRect(bounds);
}
// Fade in slowly if it landed in the shelf.
SetViewHidden(drag_view_,
false /* hide */,
!landed_in_drag_and_drop_host /* animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
drag_pointer_ = NONE;
drop_target_ = Index();
drag_view_ = NULL;
drag_start_grid_view_ = gfx::Point();
drag_start_page_ = -1;
drag_view_offset_ = gfx::Point();
AnimateToIdealBounds();
StopPageFlipTimer();
}
void AppsGridView::StopPageFlipTimer() {
page_flip_timer_.Stop();
page_flip_target_ = -1;
}
bool AppsGridView::IsDraggedView(const views::View* view) const {
return drag_view_ == view;
}
void AppsGridView::SetDragAndDropHostOfCurrentAppList(
ApplicationDragAndDropHost* drag_and_drop_host) {
drag_and_drop_host_ = drag_and_drop_host;
}
void AppsGridView::Prerender(int page_index) {
Layout();
int start = std::max(0, (page_index - kPrerenderPages) * tiles_per_page());
int end = std::min(view_model_.view_size(),
(page_index + 1 + kPrerenderPages) * tiles_per_page());
for (int i = start; i < end; i++) {
AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i));
v->Prerender();
}
}
gfx::Size AppsGridView::GetPreferredSize() {
const gfx::Insets insets(GetInsets());
const gfx::Size tile_size = gfx::Size(kPreferredTileWidth,
kPreferredTileHeight);
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
return gfx::Size(
tile_size.width() * cols_ + insets.width(),
tile_size.height() * rows_per_page_ +
page_switcher_height + insets.height());
}
bool AppsGridView::GetDropFormats(
int* formats,
std::set<OSExchangeData::CustomFormat>* custom_formats) {
// TODO(koz): Only accept a specific drag type for app shortcuts.
*formats = OSExchangeData::FILE_NAME;
return true;
}
bool AppsGridView::CanDrop(const OSExchangeData& data) {
return true;
}
int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_MOVE;
}
void AppsGridView::Layout() {
if (bounds_animator_.IsAnimating())
bounds_animator_.Cancel();
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view != drag_view_)
view->SetBoundsRect(view_model_.ideal_bounds(i));
}
views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_);
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
gfx::Rect rect(GetContentsBounds());
rect.set_y(rect.bottom() - page_switcher_height);
rect.set_height(page_switcher_height);
page_switcher_view_->SetBoundsRect(rect);
LayoutStartPage();
}
bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyPressed(event);
if (!handled) {
const int forward_dir = base::i18n::IsRTL() ? -1 : 1;
switch (event.key_code()) {
case ui::VKEY_LEFT:
MoveSelected(0, -forward_dir, 0);
return true;
case ui::VKEY_RIGHT:
MoveSelected(0, forward_dir, 0);
return true;
case ui::VKEY_UP:
MoveSelected(0, 0, -1);
return true;
case ui::VKEY_DOWN:
MoveSelected(0, 0, 1);
return true;
case ui::VKEY_PRIOR: {
MoveSelected(-1, 0, 0);
return true;
}
case ui::VKEY_NEXT: {
MoveSelected(1, 0, 0);
return true;
}
default:
break;
}
}
return handled;
}
bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyReleased(event);
return handled;
}
void AppsGridView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (!details.is_add && details.parent == this) {
if (selected_view_ == details.child)
selected_view_ = NULL;
if (drag_view_ == details.child)
EndDrag(true);
bounds_animator_.StopAnimatingView(details.child);
}
}
void AppsGridView::Update() {
DCHECK(!selected_view_ && !drag_view_);
if (!item_list_)
return;
view_model_.Clear();
if (!item_list_->item_count())
return;
for (size_t i = 0; i < item_list_->item_count(); ++i) {
views::View* view = CreateViewForItemAtIndex(i);
view_model_.Add(view, i);
AddChildView(view);
}
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::UpdatePaging() {
int total_page = start_page_view_ ? 1 : 0;
if (view_model_.view_size() && tiles_per_page())
total_page += (view_model_.view_size() - 1) / tiles_per_page() + 1;
pagination_model_->SetTotalPages(total_page);
}
void AppsGridView::UpdatePulsingBlockViews() {
const int existing_items = item_list_ ? item_list_->item_count() : 0;
const int available_slots =
tiles_per_page() - existing_items % tiles_per_page();
const int desired = model_->status() == AppListModel::STATUS_SYNCING ?
available_slots : 0;
if (pulsing_blocks_model_.view_size() == desired)
return;
while (pulsing_blocks_model_.view_size() > desired) {
views::View* view = pulsing_blocks_model_.view_at(0);
pulsing_blocks_model_.Remove(0);
delete view;
}
while (pulsing_blocks_model_.view_size() < desired) {
views::View* view = new PulsingBlockView(
gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true);
pulsing_blocks_model_.Add(view, 0);
AddChildView(view);
}
}
views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) {
DCHECK_LT(index, item_list_->item_count());
AppListItemView* view = new AppListItemView(this,
item_list_->item_at(index));
view->SetIconSize(icon_size_);
#if defined(USE_AURA)
view->SetPaintToLayer(true);
view->SetFillsBoundsOpaquely(false);
#endif
return view;
}
AppsGridView::Index AppsGridView::GetIndexFromModelIndex(
int model_index) const {
int page = model_index / tiles_per_page();
if (start_page_view_)
++page;
return Index(page, model_index % tiles_per_page());
}
int AppsGridView::GetModelIndexFromIndex(const Index& index) const {
int model_index = index.page * tiles_per_page() + index.slot;
if (start_page_view_)
model_index -= tiles_per_page();
return model_index;
}
void AppsGridView::SetSelectedItemByIndex(const Index& index) {
if (GetIndexOfView(selected_view_) == index)
return;
views::View* new_selection = GetViewAtIndex(index);
if (!new_selection)
return; // Keep current selection.
if (selected_view_)
selected_view_->SchedulePaint();
EnsureViewVisible(new_selection);
selected_view_ = new_selection;
selected_view_->SchedulePaint();
selected_view_->NotifyAccessibilityEvent(
ui::AccessibilityTypes::EVENT_FOCUS, true);
}
bool AppsGridView::IsValidIndex(const Index& index) const {
const int item_page_start = start_page_view_ ? 1 : 0;
return index.page >= item_page_start &&
index.page < pagination_model_->total_pages() &&
index.slot >= 0 &&
index.slot < tiles_per_page() &&
GetModelIndexFromIndex(index) < view_model_.view_size();
}
AppsGridView::Index AppsGridView::GetIndexOfView(
const views::View* view) const {
const int model_index = view_model_.GetIndexOfView(view);
if (model_index == -1)
return Index();
return GetIndexFromModelIndex(model_index);
}
views::View* AppsGridView::GetViewAtIndex(const Index& index) const {
if (!IsValidIndex(index))
return NULL;
const int model_index = GetModelIndexFromIndex(index);
return view_model_.view_at(model_index);
}
void AppsGridView::MoveSelected(int page_delta,
int slot_x_delta,
int slot_y_delta) {
if (!selected_view_)
return SetSelectedItemByIndex(Index(pagination_model_->selected_page(), 0));
const Index& selected = GetIndexOfView(selected_view_);
int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_;
if (selected.slot % cols_ == 0 && slot_x_delta == -1) {
if (selected.page > 0) {
page_delta = -1;
target_slot = selected.slot + cols_ - 1;
} else {
target_slot = selected.slot;
}
}
if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) {
if (selected.page < pagination_model_->total_pages() - 1) {
page_delta = 1;
target_slot = selected.slot - cols_ + 1;
} else {
target_slot = selected.slot;
}
}
// Clamp the target slot to the last item if we are moving to the last page
// but our target slot is past the end of the item list.
if (page_delta &&
selected.page + page_delta == pagination_model_->total_pages() - 1) {
int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page();
if (last_item_slot < target_slot) {
target_slot = last_item_slot;
}
}
int target_page = std::min(pagination_model_->total_pages() - 1,
std::max(selected.page + page_delta, 0));
SetSelectedItemByIndex(Index(target_page, target_slot));
}
void AppsGridView::CalculateIdealBounds() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(rect);
// Page width including padding pixels. A tile.x + page_width means the same
// tile slot in the next page.
const int page_width = grid_rect.width() + kPagePadding;
// If there is a transition, calculates offset for current and target page.
const int current_page = pagination_model_->selected_page();
const PaginationModel::Transition& transition =
pagination_model_->transition();
const bool is_valid =
pagination_model_->is_valid_page(transition.target_page);
// Transition to right means negative offset.
const int dir = transition.target_page > current_page ? -1 : 1;
const int transition_offset = is_valid ?
transition.progress * page_width * dir : 0;
const int total_views =
view_model_.view_size() + pulsing_blocks_model_.view_size();
int slot_index = 0;
for (int i = 0; i < total_views; ++i) {
if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_)
continue;
Index view_index = GetIndexFromModelIndex(slot_index);
if (drop_target_ == view_index) {
++slot_index;
view_index = GetIndexFromModelIndex(slot_index);
}
// Decides an x_offset for current item.
int x_offset = 0;
if (view_index.page < current_page)
x_offset = -page_width;
else if (view_index.page > current_page)
x_offset = page_width;
if (is_valid) {
if (view_index.page == current_page ||
view_index.page == transition.target_page) {
x_offset += transition_offset;
}
}
const int row = view_index.slot / cols_;
const int col = view_index.slot % cols_;
gfx::Rect tile_slot(
gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset,
grid_rect.y() + row * tile_size.height()),
tile_size);
if (i < view_model_.view_size()) {
view_model_.set_ideal_bounds(i, tile_slot);
} else {
pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(),
tile_slot);
}
++slot_index;
}
}
void AppsGridView::AnimateToIdealBounds() {
const gfx::Rect visible_bounds(GetVisibleBounds());
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view == drag_view_)
continue;
const gfx::Rect& target = view_model_.ideal_bounds(i);
if (bounds_animator_.GetTargetBounds(view) == target)
continue;
const gfx::Rect& current = view->bounds();
const bool current_visible = visible_bounds.Intersects(current);
const bool target_visible = visible_bounds.Intersects(target);
const bool visible = current_visible || target_visible;
const int y_diff = target.y() - current.y();
if (visible && y_diff && y_diff % kPreferredTileHeight == 0) {
AnimationBetweenRows(view,
current_visible,
current,
target_visible,
target);
} else {
bounds_animator_.AnimateViewTo(view, target);
}
}
}
void AppsGridView::AnimationBetweenRows(views::View* view,
bool animate_current,
const gfx::Rect& current,
bool animate_target,
const gfx::Rect& target) {
// Determine page of |current| and |target|. -1 means in the left invisible
// page, 0 is the center visible page and 1 means in the right invisible page.
const int current_page = current.x() < 0 ? -1 :
current.x() >= width() ? 1 : 0;
const int target_page = target.x() < 0 ? -1 :
target.x() >= width() ? 1 : 0;
const int dir = current_page < target_page ||
(current_page == target_page && current.y() < target.y()) ? 1 : -1;
#if defined(USE_AURA)
scoped_ptr<ui::Layer> layer;
if (animate_current) {
layer.reset(view->RecreateLayer());
layer->SuppressPaint();
view->SetFillsBoundsOpaquely(false);
view->layer()->SetOpacity(0.f);
}
gfx::Rect current_out(current);
current_out.Offset(dir * kPreferredTileWidth, 0);
#endif
gfx::Rect target_in(target);
if (animate_target)
target_in.Offset(-dir * kPreferredTileWidth, 0);
view->SetBoundsRect(target_in);
bounds_animator_.AnimateViewTo(view, target);
#if defined(USE_AURA)
bounds_animator_.SetAnimationDelegate(
view,
new RowMoveAnimationDelegate(view, layer.release(), current_out),
true);
#endif
}
void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event,
gfx::Point* drag_point) {
#if defined(USE_AURA)
// Use root location of |event| instead of location in |drag_view_|'s
// coordinates because |drag_view_| has a scale transform and location
// could have integer round error and causes jitter.
*drag_point = event.root_location();
// GetWidget() could be NULL for tests.
if (GetWidget()) {
aura::Window::ConvertPointToTarget(
GetWidget()->GetNativeWindow()->GetRootWindow(),
GetWidget()->GetNativeWindow(),
drag_point);
}
views::View::ConvertPointFromWidget(this, drag_point);
#else
// For non-aura, root location is not clearly defined but |drag_view_| does
// not have the scale transform. So no round error would be introduced and
// it's okay to use View::ConvertPointToTarget.
*drag_point = event.location();
views::View::ConvertPointToTarget(drag_view_, this, drag_point);
#endif
}
void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point,
bool use_page_button_hovering) {
int current_page = pagination_model_->selected_page();
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
current_page = drag_start_page_;
}
if (use_page_button_hovering &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_->is_valid_page(page)) {
drop_target_.page = page;
drop_target_.slot = tiles_per_page() - 1;
}
} else {
gfx::Rect bounds(GetContentsBounds());
const int drop_row = (point.y() - bounds.y()) / kPreferredTileHeight;
const int drop_col = std::min(cols_ - 1,
(point.x() - bounds.x()) / kPreferredTileWidth);
drop_target_.page = current_page;
drop_target_.slot = std::max(0, std::min(
tiles_per_page() - 1,
drop_row * cols_ + drop_col));
}
// Limits to the last possible slot on last page.
if (drop_target_.page == pagination_model_->total_pages() - 1) {
drop_target_.slot = std::min(
(view_model_.view_size() - 1) % tiles_per_page(),
drop_target_.slot);
}
}
void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) {
// When a drag and drop host is given, the item can be dragged out of the app
// list window. In that case a proxy widget needs to be used.
// Note: This code has very likely to be changed for Windows (non metro mode)
// when a |drag_and_drop_host_| gets implemented.
if (!drag_view_ || !drag_and_drop_host_)
return;
gfx::Point screen_location = grid_location;
views::View::ConvertPointToScreen(this, &screen_location);
// Determine the mouse offset to the center of the icon so that the drag and
// drop host follows this layer.
gfx::Vector2d delta = drag_view_offset_ -
drag_view_->GetLocalBounds().CenterPoint();
delta.set_y(delta.y() + drag_view_->title()->size().height() / 2);
// We have to hide the original item since the drag and drop host will do
// the OS dependent code to "lift off the dragged item".
drag_and_drop_host_->CreateDragIconProxy(screen_location,
drag_view_->model()->icon(),
drag_view_,
delta,
kDragAndDropProxyScale);
SetViewHidden(drag_view_,
true /* hide */,
true /* no animation */);
}
void AppsGridView::DispatchDragEventToDragAndDropHost(
const gfx::Point& point) {
if (!drag_view_ || !drag_and_drop_host_)
return;
if (bounds().Contains(last_drag_point_)) {
// The event was issued inside the app menu and we should get all events.
if (forward_events_to_drag_and_drop_host_) {
// The DnD host was previously called and needs to be informed that the
// session returns to the owner.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
// The event happened outside our app menu and we might need to dispatch.
if (forward_events_to_drag_and_drop_host_) {
// Dispatch since we have already started.
if (!drag_and_drop_host_->Drag(point)) {
// The host is not active any longer and we cancel the operation.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (drag_and_drop_host_->StartDrag(drag_view_->model()->id(), point)) {
// From now on we forward the drag events.
forward_events_to_drag_and_drop_host_ = true;
// Any flip operations are stopped.
StopPageFlipTimer();
}
}
}
}
void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) {
if (!IsPointWithinDragBuffer(drag_point))
StopPageFlipTimer();
int new_page_flip_target = -1;
if (page_switcher_view_->bounds().Contains(drag_point)) {
gfx::Point page_switcher_point(drag_point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
new_page_flip_target =
page_switcher_view_->GetPageForPoint(page_switcher_point);
}
// TODO(xiyuan): Fix this for RTL.
if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize)
new_page_flip_target = pagination_model_->selected_page() - 1;
if (new_page_flip_target == -1 &&
drag_point.x() > width() - kPageFlipZoneSize) {
new_page_flip_target = pagination_model_->selected_page() + 1;
}
if (new_page_flip_target == page_flip_target_)
return;
StopPageFlipTimer();
if (pagination_model_->is_valid_page(new_page_flip_target)) {
page_flip_target_ = new_page_flip_target;
if (page_flip_target_ != pagination_model_->selected_page()) {
page_flip_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_),
this, &AppsGridView::OnPageFlipTimer);
}
}
}
void AppsGridView::OnPageFlipTimer() {
DCHECK(pagination_model_->is_valid_page(page_flip_target_));
pagination_model_->SelectPage(page_flip_target_, true);
}
void AppsGridView::MoveItemInModel(views::View* item_view,
const Index& target) {
int current_model_index = view_model_.GetIndexOfView(item_view);
DCHECK_GE(current_model_index, 0);
int target_model_index = GetModelIndexFromIndex(target);
if (target_model_index == current_model_index)
return;
item_list_->RemoveObserver(this);
item_list_->MoveItem(current_model_index, target_model_index);
view_model_.Move(current_model_index, target_model_index);
item_list_->AddObserver(this);
if (pagination_model_->selected_page() != target.page)
pagination_model_->SelectPage(target.page, false);
}
void AppsGridView::CancelContextMenusOnCurrentPage() {
int start = pagination_model_->selected_page() * tiles_per_page();
int end = std::min(view_model_.view_size(), start + tiles_per_page());
for (int i = start; i < end; ++i) {
AppListItemView* view =
static_cast<AppListItemView*>(view_model_.view_at(i));
view->CancelContextMenu();
}
}
bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const {
gfx::Rect rect(GetLocalBounds());
rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx);
return rect.Contains(point);
}
void AppsGridView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (dragging())
return;
if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName))
return;
if (delegate_) {
delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->model(),
event.flags());
}
}
void AppsGridView::LayoutStartPage() {
if (!start_page_view_)
return;
gfx::Rect start_page_bounds(GetLocalBounds());
start_page_bounds.set_height(start_page_bounds.height() -
page_switcher_view_->height());
const int page_width = width() + kPagePadding;
const int current_page = pagination_model_->selected_page();
if (current_page > 0)
start_page_bounds.Offset(-page_width, 0);
const PaginationModel::Transition& transition =
pagination_model_->transition();
if (current_page == 0 || transition.target_page == 0) {
const int dir = transition.target_page > current_page ? -1 : 1;
start_page_bounds.Offset(transition.progress * page_width * dir, 0);
}
start_page_view_->SetBoundsRect(start_page_bounds);
}
void AppsGridView::OnListItemAdded(size_t index, AppListItemModel* item) {
EndDrag(true);
views::View* view = CreateViewForItemAtIndex(index);
view_model_.Add(view, index);
AddChildView(view);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemRemoved(size_t index, AppListItemModel* item) {
EndDrag(true);
views::View* view = view_model_.view_at(index);
view_model_.Remove(index);
delete view;
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemMoved(size_t from_index,
size_t to_index,
AppListItemModel* item) {
EndDrag(true);
view_model_.Move(from_index, to_index);
UpdatePaging();
AnimateToIdealBounds();
}
void AppsGridView::TotalPagesChanged() {
}
void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) {
if (dragging()) {
CalculateDropTarget(last_drag_point_, true);
Layout();
MaybeStartPageFlipTimer(last_drag_point_);
} else {
ClearSelectedView(selected_view_);
Layout();
}
}
void AppsGridView::TransitionStarted() {
CancelContextMenusOnCurrentPage();
}
void AppsGridView::TransitionChanged() {
// Update layout for valid page transition only since over-scroll no longer
// animates app icons.
const PaginationModel::Transition& transition =
pagination_model_->transition();
if (pagination_model_->is_valid_page(transition.target_page))
Layout();
}
void AppsGridView::OnAppListModelStatusChanged() {
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::SetViewHidden(views::View* view, bool hide, bool immediate) {
#if defined(USE_AURA)
ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator());
animator.SetPreemptionStrategy(
immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET :
ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION);
view->layer()->SetOpacity(hide ? 0 : 1);
#endif
}
} // namespace app_list
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemosshrunner.h"
#include "maemodeploystep.h"
#include "maemodeviceconfigurations.h"
#include "maemoglobal.h"
#include "maemoremotemounter.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfiguration.h"
#include <coreplugin/ssh/sshconnection.h>
#include <coreplugin/ssh/sshremoteprocess.h>
#include <QtCore/QFileInfo>
using namespace Core;
namespace Qt4ProjectManager {
namespace Internal {
MaemoSshRunner::MaemoSshRunner(QObject *parent,
MaemoRunConfiguration *runConfig, bool debugging)
: QObject(parent), m_runConfig(runConfig),
m_mounter(new MaemoRemoteMounter(this)),
m_devConfig(runConfig->deviceConfig()), m_shuttingDown(false),
m_debugging(debugging)
{
m_procsToKill
<< QFileInfo(m_runConfig->localExecutableFilePath()).fileName()
<< QLatin1String("utfs-client");
if (debugging)
m_procsToKill << QLatin1String("gdbserver");
connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
connect(m_mounter, SIGNAL(error(QString)), this,
SLOT(handleMounterError(QString)));
connect(m_mounter, SIGNAL(reportProgress(QString)), this,
SIGNAL(reportProgress(QString)));
connect(m_mounter, SIGNAL(debugOutput(QString)), this,
SIGNAL(mountDebugOutput(QString)));
}
MaemoSshRunner::~MaemoSshRunner() {}
void MaemoSshRunner::setConnection(const QSharedPointer<Core::SshConnection> &connection)
{
m_connection = connection;
}
void MaemoSshRunner::start()
{
// Should not happen.
if (m_shuttingDown) {
emit error(tr("Cannot start deployment, as the clean-up from the last time has not finished yet."));
return;
}
m_stop = false;
m_exitStatus = -1;
if (m_connection)
disconnect(m_connection.data(), 0, this, 0);
bool reUse = isConnectionUsable();
if (!reUse)
m_connection = m_runConfig->deployStep()->sshConnection();
reUse = isConnectionUsable();
if (!reUse)
m_connection = SshConnection::create();
connect(m_connection.data(), SIGNAL(connected()), this,
SLOT(handleConnected()));
connect(m_connection.data(), SIGNAL(error(SshError)), this,
SLOT(handleConnectionFailure()));
if (reUse) {
handleConnected();
} else {
emit reportProgress(tr("Connecting to device..."));
m_connection->connectToHost(m_devConfig.server);
}
}
void MaemoSshRunner::stop()
{
if (m_shuttingDown)
return;
m_stop = true;
m_mounter->stop();
if (m_cleaner)
disconnect(m_cleaner.data(), 0, this, 0);
cleanup(false);
}
void MaemoSshRunner::handleConnected()
{
if (m_stop)
return;
cleanup(true);
}
void MaemoSshRunner::handleConnectionFailure()
{
emit error(tr("Could not connect to host: %1")
.arg(m_connection->errorString()));
}
void MaemoSshRunner::cleanup(bool initialCleanup)
{
if (!isConnectionUsable())
return;
emit reportProgress(tr("Killing remote process(es)..."));
m_shuttingDown = !initialCleanup;
QString niceKill;
QString brutalKill;
foreach (const QString &proc, m_procsToKill) {
niceKill += QString::fromLocal8Bit("pkill %1\\$;").arg(proc);
brutalKill += QString::fromLocal8Bit("pkill -9 %1\\$;").arg(proc);
}
QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
connect(m_cleaner.data(), SIGNAL(closed(int)), this,
SLOT(handleCleanupFinished(int)));
m_cleaner->start();
}
void MaemoSshRunner::handleCleanupFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
if (m_shuttingDown) {
m_unmountState = ShutdownUnmount;
m_mounter->unmount();
return;
}
if (m_stop)
return;
if (exitStatus != SshRemoteProcess::ExitedNormally) {
emit error(tr("Initial cleanup failed: %1")
.arg(m_cleaner->errorString()));
} else {
m_mounter->setConnection(m_connection);
m_unmountState = InitialUnmount;
m_mounter->unmount();
}
}
void MaemoSshRunner::handleUnmounted()
{
switch (m_unmountState) {
case InitialUnmount: {
if (m_stop)
return;
m_mounter->resetMountSpecifications();
MaemoPortList portList = m_devConfig.freePorts();
if (m_debugging) { // gdbserver and QML inspector need one port each.
if (m_runConfig->useCppDebugger() && !m_runConfig->useRemoteGdb())
portList.getNext();
if (m_runConfig->useQmlDebugger())
portList.getNext();
}
m_mounter->setToolchain(m_runConfig->toolchain());
m_mounter->setPortList(portList);
const MaemoRemoteMountsModel * const remoteMounts
= m_runConfig->remoteMounts();
for (int i = 0; i < remoteMounts->mountSpecificationCount(); ++i) {
if (!addMountSpecification(remoteMounts->mountSpecificationAt(i)))
return;
}
if (m_debugging && m_runConfig->useRemoteGdb()) {
if (!addMountSpecification(MaemoMountSpecification(
m_runConfig->localDirToMountForRemoteGdb(),
MaemoGlobal::remoteProjectSourcesMountPoint())))
return;
}
m_unmountState = PreMountUnmount;
m_mounter->unmount();
break;
}
case PreMountUnmount:
if (m_stop)
return;
m_mounter->mount();
break;
case ShutdownUnmount:
Q_ASSERT(m_shuttingDown);
m_mounter->resetMountSpecifications();
m_shuttingDown = false;
if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
emit remoteProcessFinished(m_runner->exitCode());
} else if (m_exitStatus == -1) {
emit remoteProcessFinished(-1);
} else {
emit error(tr("Error running remote process: %1")
.arg(m_runner->errorString()));
}
m_exitStatus = -1;
break;
}
}
void MaemoSshRunner::handleMounted()
{
if (!m_stop)
emit readyForExecution();
}
void MaemoSshRunner::handleMounterError(const QString &errorMsg)
{
if (m_shuttingDown)
m_shuttingDown = false;
emit error(errorMsg);
}
void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
{
if (m_runConfig->remoteExecutableFilePath().isEmpty()) {
emit error(tr("Cannot run: No remote executable set."));
return;
}
m_runner = m_connection->createRemoteProcess(remoteCall);
connect(m_runner.data(), SIGNAL(started()), this,
SIGNAL(remoteProcessStarted()));
connect(m_runner.data(), SIGNAL(closed(int)), this,
SLOT(handleRemoteProcessFinished(int)));
connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
SIGNAL(remoteOutput(QByteArray)));
connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
SIGNAL(remoteErrorOutput(QByteArray)));
m_runner->start();
}
void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
m_exitStatus = exitStatus;
cleanup(false);
}
bool MaemoSshRunner::addMountSpecification(const MaemoMountSpecification &mountSpec)
{
if (!m_mounter->addMountSpecification(mountSpec, false)) {
emit error(tr("The device does not have enough free ports "
"for this run configuration."));
return false;
}
return true;
}
bool MaemoSshRunner::isConnectionUsable() const
{
return m_connection && m_connection->state() == SshConnection::Connected
&& m_connection->connectionParameters() == m_devConfig.server;
}
} // namespace Internal
} // namespace Qt4ProjectManager
Maemo: Use tighter regular expression for pkill.
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemosshrunner.h"
#include "maemodeploystep.h"
#include "maemodeviceconfigurations.h"
#include "maemoglobal.h"
#include "maemoremotemounter.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfiguration.h"
#include <coreplugin/ssh/sshconnection.h>
#include <coreplugin/ssh/sshremoteprocess.h>
#include <QtCore/QFileInfo>
using namespace Core;
namespace Qt4ProjectManager {
namespace Internal {
MaemoSshRunner::MaemoSshRunner(QObject *parent,
MaemoRunConfiguration *runConfig, bool debugging)
: QObject(parent), m_runConfig(runConfig),
m_mounter(new MaemoRemoteMounter(this)),
m_devConfig(runConfig->deviceConfig()), m_shuttingDown(false),
m_debugging(debugging)
{
m_procsToKill
<< QFileInfo(m_runConfig->localExecutableFilePath()).fileName()
<< QLatin1String("utfs-client");
if (debugging)
m_procsToKill << QLatin1String("gdbserver");
connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
connect(m_mounter, SIGNAL(error(QString)), this,
SLOT(handleMounterError(QString)));
connect(m_mounter, SIGNAL(reportProgress(QString)), this,
SIGNAL(reportProgress(QString)));
connect(m_mounter, SIGNAL(debugOutput(QString)), this,
SIGNAL(mountDebugOutput(QString)));
}
MaemoSshRunner::~MaemoSshRunner() {}
void MaemoSshRunner::setConnection(const QSharedPointer<Core::SshConnection> &connection)
{
m_connection = connection;
}
void MaemoSshRunner::start()
{
// Should not happen.
if (m_shuttingDown) {
emit error(tr("Cannot start deployment, as the clean-up from the last time has not finished yet."));
return;
}
m_stop = false;
m_exitStatus = -1;
if (m_connection)
disconnect(m_connection.data(), 0, this, 0);
bool reUse = isConnectionUsable();
if (!reUse)
m_connection = m_runConfig->deployStep()->sshConnection();
reUse = isConnectionUsable();
if (!reUse)
m_connection = SshConnection::create();
connect(m_connection.data(), SIGNAL(connected()), this,
SLOT(handleConnected()));
connect(m_connection.data(), SIGNAL(error(SshError)), this,
SLOT(handleConnectionFailure()));
if (reUse) {
handleConnected();
} else {
emit reportProgress(tr("Connecting to device..."));
m_connection->connectToHost(m_devConfig.server);
}
}
void MaemoSshRunner::stop()
{
if (m_shuttingDown)
return;
m_stop = true;
m_mounter->stop();
if (m_cleaner)
disconnect(m_cleaner.data(), 0, this, 0);
cleanup(false);
}
void MaemoSshRunner::handleConnected()
{
if (m_stop)
return;
cleanup(true);
}
void MaemoSshRunner::handleConnectionFailure()
{
emit error(tr("Could not connect to host: %1")
.arg(m_connection->errorString()));
}
void MaemoSshRunner::cleanup(bool initialCleanup)
{
if (!isConnectionUsable())
return;
emit reportProgress(tr("Killing remote process(es)..."));
m_shuttingDown = !initialCleanup;
// pkill behaves differently on Fremantle and Harmattan.
const char *const killTemplate = "pkill -%2 '^%1$'; pkill -%2 '/%1$';";
QString niceKill;
QString brutalKill;
foreach (const QString &proc, m_procsToKill) {
niceKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGTERM");
brutalKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGKILL");
}
QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
connect(m_cleaner.data(), SIGNAL(closed(int)), this,
SLOT(handleCleanupFinished(int)));
m_cleaner->start();
}
void MaemoSshRunner::handleCleanupFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
if (m_shuttingDown) {
m_unmountState = ShutdownUnmount;
m_mounter->unmount();
return;
}
if (m_stop)
return;
if (exitStatus != SshRemoteProcess::ExitedNormally) {
emit error(tr("Initial cleanup failed: %1")
.arg(m_cleaner->errorString()));
} else {
m_mounter->setConnection(m_connection);
m_unmountState = InitialUnmount;
m_mounter->unmount();
}
}
void MaemoSshRunner::handleUnmounted()
{
switch (m_unmountState) {
case InitialUnmount: {
if (m_stop)
return;
m_mounter->resetMountSpecifications();
MaemoPortList portList = m_devConfig.freePorts();
if (m_debugging) { // gdbserver and QML inspector need one port each.
if (m_runConfig->useCppDebugger() && !m_runConfig->useRemoteGdb())
portList.getNext();
if (m_runConfig->useQmlDebugger())
portList.getNext();
}
m_mounter->setToolchain(m_runConfig->toolchain());
m_mounter->setPortList(portList);
const MaemoRemoteMountsModel * const remoteMounts
= m_runConfig->remoteMounts();
for (int i = 0; i < remoteMounts->mountSpecificationCount(); ++i) {
if (!addMountSpecification(remoteMounts->mountSpecificationAt(i)))
return;
}
if (m_debugging && m_runConfig->useRemoteGdb()) {
if (!addMountSpecification(MaemoMountSpecification(
m_runConfig->localDirToMountForRemoteGdb(),
MaemoGlobal::remoteProjectSourcesMountPoint())))
return;
}
m_unmountState = PreMountUnmount;
m_mounter->unmount();
break;
}
case PreMountUnmount:
if (m_stop)
return;
m_mounter->mount();
break;
case ShutdownUnmount:
Q_ASSERT(m_shuttingDown);
m_mounter->resetMountSpecifications();
m_shuttingDown = false;
if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
emit remoteProcessFinished(m_runner->exitCode());
} else if (m_exitStatus == -1) {
emit remoteProcessFinished(-1);
} else {
emit error(tr("Error running remote process: %1")
.arg(m_runner->errorString()));
}
m_exitStatus = -1;
break;
}
}
void MaemoSshRunner::handleMounted()
{
if (!m_stop)
emit readyForExecution();
}
void MaemoSshRunner::handleMounterError(const QString &errorMsg)
{
if (m_shuttingDown)
m_shuttingDown = false;
emit error(errorMsg);
}
void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
{
if (m_runConfig->remoteExecutableFilePath().isEmpty()) {
emit error(tr("Cannot run: No remote executable set."));
return;
}
m_runner = m_connection->createRemoteProcess(remoteCall);
connect(m_runner.data(), SIGNAL(started()), this,
SIGNAL(remoteProcessStarted()));
connect(m_runner.data(), SIGNAL(closed(int)), this,
SLOT(handleRemoteProcessFinished(int)));
connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
SIGNAL(remoteOutput(QByteArray)));
connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
SIGNAL(remoteErrorOutput(QByteArray)));
m_runner->start();
}
void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
m_exitStatus = exitStatus;
cleanup(false);
}
bool MaemoSshRunner::addMountSpecification(const MaemoMountSpecification &mountSpec)
{
if (!m_mounter->addMountSpecification(mountSpec, false)) {
emit error(tr("The device does not have enough free ports "
"for this run configuration."));
return false;
}
return true;
}
bool MaemoSshRunner::isConnectionUsable() const
{
return m_connection && m_connection->state() == SshConnection::Connected
&& m_connection->connectionParameters() == m_devConfig.server;
}
} // namespace Internal
} // namespace Qt4ProjectManager
|
#include "SurfaceCollection.hpp"
#include <map>
namespace Slic3r {
SurfaceCollection::operator Polygons() const
{
Polygons polygons;
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
Polygons surface_p = surface->expolygon;
polygons.insert(polygons.end(), surface_p.begin(), surface_p.end());
}
return polygons;
}
SurfaceCollection::operator ExPolygons() const
{
ExPolygons expp;
expp.reserve(this->surfaces.size());
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
expp.push_back(surface->expolygon);
}
return expp;
}
void
SurfaceCollection::simplify(double tolerance)
{
Surfaces ss;
for (Surfaces::const_iterator it_s = this->surfaces.begin(); it_s != this->surfaces.end(); ++it_s) {
ExPolygons expp;
it_s->expolygon.simplify(tolerance, &expp);
for (ExPolygons::const_iterator it_e = expp.begin(); it_e != expp.end(); ++it_e) {
Surface s = *it_s;
s.expolygon = *it_e;
ss.push_back(s);
}
}
this->surfaces = ss;
}
/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesConstPtr> *retval) const
{
for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
// find a group with the same properties
SurfacesConstPtr* group = NULL;
for (std::vector<SurfacesConstPtr>::iterator git = retval->begin(); git != retval->end(); ++git) {
const Surface* gkey = git->front();
if ( gkey->surface_type == it->surface_type
&& gkey->thickness == it->thickness
&& gkey->thickness_layers == it->thickness_layers
&& gkey->bridge_angle == it->bridge_angle) {
group = &*git;
break;
}
}
// if no group with these properties exists, add one
if (group == NULL) {
retval->resize(retval->size() + 1);
group = &retval->back();
}
// append surface to group
group->push_back(&*it);
}
}
template <class T>
bool
SurfaceCollection::any_internal_contains(const T &item) const
{
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->is_internal() && surface->expolygon.contains(item)) return true;
}
return false;
}
template bool SurfaceCollection::any_internal_contains<Polyline>(const Polyline &item) const;
template <class T>
bool
SurfaceCollection::any_bottom_contains(const T &item) const
{
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->is_bottom() && surface->expolygon.contains(item)) return true;
}
return false;
}
template bool SurfaceCollection::any_bottom_contains<Polyline>(const Polyline &item) const;
SurfacesPtr
SurfaceCollection::filter_by_type(SurfaceType type)
{
SurfacesPtr ss;
for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->surface_type == type) ss.push_back(&*surface);
}
return ss;
}
SurfacesPtr
SurfaceCollection::filter_by_type(std::initializer_list<SurfaceType> types)
{
size_t n {0};
SurfacesPtr ss;
for (const auto& t : types) {
n |= t;
}
for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->surface_type & n == surface->surface_type) ss.push_back(&*surface);
}
return ss;
}
void
SurfaceCollection::filter_by_type(SurfaceType type, Polygons* polygons)
{
for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->surface_type == type)
append_to(*polygons, (Polygons)surface->expolygon);
}
}
void
SurfaceCollection::append(const SurfaceCollection &coll)
{
this->append(coll.surfaces);
}
void
SurfaceCollection::append(const Surfaces &surfaces)
{
append_to(this->surfaces, surfaces);
}
void
SurfaceCollection::append(const ExPolygons &src, const Surface &templ)
{
this->surfaces.reserve(this->surfaces.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it) {
this->surfaces.push_back(templ);
this->surfaces.back().expolygon = *it;
}
}
void
SurfaceCollection::append(const ExPolygons &src, SurfaceType surfaceType)
{
this->surfaces.reserve(this->surfaces.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
this->surfaces.push_back(Surface(surfaceType, *it));
}
size_t
SurfaceCollection::polygons_count() const
{
size_t count = 0;
for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++ it)
count += 1 + it->expolygon.holes.size();
return count;
}
void
SurfaceCollection::remove_type(const SurfaceType type)
{
// Use stl remove_if to remove
auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (Surface& s) { return s.surface_type == type; });
surfaces.erase(ptr, surfaces.cend());
}
void
SurfaceCollection::remove_types(const SurfaceType *types, size_t ntypes)
{
for (size_t i = 0; i < ntypes; ++i)
this->remove_type(types[i]);
}
void
SurfaceCollection::remove_types(std::initializer_list<SurfaceType> types) {
for (const auto& t : types) {
this->remove_type(t);
}
}
void
SurfaceCollection::keep_type(const SurfaceType type)
{
// Use stl remove_if to remove
auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (const Surface& s) { return s.surface_type != type; });
surfaces.erase(ptr, surfaces.cend());
}
void
SurfaceCollection::keep_types(const SurfaceType *types, size_t ntypes)
{
size_t n {0};
for (size_t i = 0; i < ntypes; ++i)
n |= types[i]; // form bitmask.
// Use stl remove_if to remove
auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[n] (const Surface& s) { return s.surface_type & n != s.surface_type; });
surfaces.erase(ptr, surfaces.cend());
}
void
SurfaceCollection::keep_types(std::initializer_list<SurfaceType> types) {
for (const auto& t : types) {
this->keep_type(t);
}
}
/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesPtr> *retval)
{
for (Surfaces::iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
// find a group with the same properties
SurfacesPtr* group = NULL;
for (std::vector<SurfacesPtr>::iterator git = retval->begin(); git != retval->end(); ++git)
if (! git->empty() && surfaces_could_merge(*git->front(), *it)) {
group = &*git;
break;
}
// if no group with these properties exists, add one
if (group == NULL) {
retval->resize(retval->size() + 1);
group = &retval->back();
}
// append surface to group
group->push_back(&*it);
}
}
} // namespace Slic3r
Added parens to declare intent and quiet compiler warnings.
#include "SurfaceCollection.hpp"
#include <map>
namespace Slic3r {
SurfaceCollection::operator Polygons() const
{
Polygons polygons;
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
Polygons surface_p = surface->expolygon;
polygons.insert(polygons.end(), surface_p.begin(), surface_p.end());
}
return polygons;
}
SurfaceCollection::operator ExPolygons() const
{
ExPolygons expp;
expp.reserve(this->surfaces.size());
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
expp.push_back(surface->expolygon);
}
return expp;
}
void
SurfaceCollection::simplify(double tolerance)
{
Surfaces ss;
for (Surfaces::const_iterator it_s = this->surfaces.begin(); it_s != this->surfaces.end(); ++it_s) {
ExPolygons expp;
it_s->expolygon.simplify(tolerance, &expp);
for (ExPolygons::const_iterator it_e = expp.begin(); it_e != expp.end(); ++it_e) {
Surface s = *it_s;
s.expolygon = *it_e;
ss.push_back(s);
}
}
this->surfaces = ss;
}
/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesConstPtr> *retval) const
{
for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
// find a group with the same properties
SurfacesConstPtr* group = NULL;
for (std::vector<SurfacesConstPtr>::iterator git = retval->begin(); git != retval->end(); ++git) {
const Surface* gkey = git->front();
if ( gkey->surface_type == it->surface_type
&& gkey->thickness == it->thickness
&& gkey->thickness_layers == it->thickness_layers
&& gkey->bridge_angle == it->bridge_angle) {
group = &*git;
break;
}
}
// if no group with these properties exists, add one
if (group == NULL) {
retval->resize(retval->size() + 1);
group = &retval->back();
}
// append surface to group
group->push_back(&*it);
}
}
template <class T>
bool
SurfaceCollection::any_internal_contains(const T &item) const
{
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->is_internal() && surface->expolygon.contains(item)) return true;
}
return false;
}
template bool SurfaceCollection::any_internal_contains<Polyline>(const Polyline &item) const;
template <class T>
bool
SurfaceCollection::any_bottom_contains(const T &item) const
{
for (Surfaces::const_iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->is_bottom() && surface->expolygon.contains(item)) return true;
}
return false;
}
template bool SurfaceCollection::any_bottom_contains<Polyline>(const Polyline &item) const;
SurfacesPtr
SurfaceCollection::filter_by_type(SurfaceType type)
{
SurfacesPtr ss;
for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->surface_type == type) ss.push_back(&*surface);
}
return ss;
}
SurfacesPtr
SurfaceCollection::filter_by_type(std::initializer_list<SurfaceType> types)
{
size_t n {0};
SurfacesPtr ss;
for (const auto& t : types) {
n |= t;
}
for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if ((surface->surface_type & n) == surface->surface_type) ss.push_back(&*surface);
}
return ss;
}
void
SurfaceCollection::filter_by_type(SurfaceType type, Polygons* polygons)
{
for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) {
if (surface->surface_type == type)
append_to(*polygons, (Polygons)surface->expolygon);
}
}
void
SurfaceCollection::append(const SurfaceCollection &coll)
{
this->append(coll.surfaces);
}
void
SurfaceCollection::append(const Surfaces &surfaces)
{
append_to(this->surfaces, surfaces);
}
void
SurfaceCollection::append(const ExPolygons &src, const Surface &templ)
{
this->surfaces.reserve(this->surfaces.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it) {
this->surfaces.push_back(templ);
this->surfaces.back().expolygon = *it;
}
}
void
SurfaceCollection::append(const ExPolygons &src, SurfaceType surfaceType)
{
this->surfaces.reserve(this->surfaces.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
this->surfaces.push_back(Surface(surfaceType, *it));
}
size_t
SurfaceCollection::polygons_count() const
{
size_t count = 0;
for (Surfaces::const_iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++ it)
count += 1 + it->expolygon.holes.size();
return count;
}
void
SurfaceCollection::remove_type(const SurfaceType type)
{
// Use stl remove_if to remove
auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (Surface& s) { return s.surface_type == type; });
surfaces.erase(ptr, surfaces.cend());
}
void
SurfaceCollection::remove_types(const SurfaceType *types, size_t ntypes)
{
for (size_t i = 0; i < ntypes; ++i)
this->remove_type(types[i]);
}
void
SurfaceCollection::remove_types(std::initializer_list<SurfaceType> types) {
for (const auto& t : types) {
this->remove_type(t);
}
}
void
SurfaceCollection::keep_type(const SurfaceType type)
{
// Use stl remove_if to remove
auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[type] (const Surface& s) { return s.surface_type != type; });
surfaces.erase(ptr, surfaces.cend());
}
void
SurfaceCollection::keep_types(const SurfaceType *types, size_t ntypes)
{
size_t n {0};
for (size_t i = 0; i < ntypes; ++i)
n |= types[i]; // form bitmask.
// Use stl remove_if to remove
auto ptr = std::remove_if(surfaces.begin(), surfaces.end(),[n] (const Surface& s) { return (s.surface_type & n) != s.surface_type; });
surfaces.erase(ptr, surfaces.cend());
}
void
SurfaceCollection::keep_types(std::initializer_list<SurfaceType> types) {
for (const auto& t : types) {
this->keep_type(t);
}
}
/* group surfaces by common properties */
void
SurfaceCollection::group(std::vector<SurfacesPtr> *retval)
{
for (Surfaces::iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) {
// find a group with the same properties
SurfacesPtr* group = NULL;
for (std::vector<SurfacesPtr>::iterator git = retval->begin(); git != retval->end(); ++git)
if (! git->empty() && surfaces_could_merge(*git->front(), *it)) {
group = &*git;
break;
}
// if no group with these properties exists, add one
if (group == NULL) {
retval->resize(retval->size() + 1);
group = &retval->back();
}
// append surface to group
group->push_back(&*it);
}
}
} // namespace Slic3r
|
//
// yssa_builder.cpp
//
// Created by Edmund Kapusniak on 05/03/2015.
// Copyright (c) 2015 Edmund Kapusniak. All rights reserved.
//
#include "yssa_builder.h"
#include <make_unique.h>
#include "yl_code.h"
yssa_builder::yssa_builder( yl_diagnostics* diagnostics )
: diagnostics( diagnostics )
, module( std::make_unique< yssa_module >() )
{
}
yssa_builder::~yssa_builder()
{
}
bool yssa_builder::build( yl_ast* ast )
{
// Construct each function.
for ( size_t i = 0; i < ast->functions.size(); ++i )
{
yl_ast_func* astf = ast->functions.at( i );
yssa_function_p ssaf = std::make_unique< yssa_function >
(
astf->sloc,
module->alloc.strdup( astf->funcname )
);
funcmap.emplace( std::make_pair( astf, ssaf.get() ) );
module->functions.push_back( std::move( ssaf ) );
}
// Build SSA for each function.
for ( size_t i = 0; i < ast->functions.size(); ++i )
{
yl_ast_func* astf = ast->functions.at( i );
build( astf );
}
return diagnostics->error_count() == 0;
}
yssa_module_p yssa_builder::get_module()
{
return std::move( module );
}
void yssa_builder::build( yl_ast_func* astf )
{
function = funcmap.at( astf );
// Create entry block.
yssa_block_p entry_block = std::make_unique< yssa_block >();
block = entry_block.get();
function->blocks.push_back( std::move( entry_block ) );
// Add parameter ops.
for ( size_t i = 0; i < astf->parameters.size(); ++i )
{
yl_ast_name* param = astf->parameters.at( i );
yssa_opinst* o = op( param->sloc, YSSA_PARAM, 0, 1 );
o->select = (int)i;
declare( param->sloc, variable( param ), o );
}
// Visit the block.
visit( astf->block, 0 );
}
int yssa_builder::fallback( yl_ast_node* node, int count )
{
assert( ! "invalid AST node" );
return 0;
}
int yssa_builder::visit( yl_stmt_block* node, int count )
{
/*
statements
close upvals
*/
if ( node->scope )
{
open_scope( node->scope );
}
for ( size_t i = 0; i < node->stmts.size(); ++i )
{
execute( node->stmts.at( i ) );
}
if ( node->scope )
{
close_scope( node->sloc, node->scope );
}
return 0;
}
int yssa_builder::visit( yl_stmt_if* node, int count )
{
/*
condition
? goto iftrue : goto iffalse
iftrue:
...
goto final
iffalse:
...
goto final
final:
close upvals
*/
open_scope( node->scope );
// Check if condition.
size_t operand = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
yssa_block* test_next = block;
yssa_block* test_fail = block;
// True branch.
if ( node->iftrue )
{
if ( test_next )
{
block = test_next;
block = next_block();
test_next = nullptr;
}
execute( node->iftrue );
}
yssa_block* true_block = block;
// False branch.
if ( node->iffalse )
{
if ( test_fail )
{
block = test_fail;
block = fail_block();
test_fail = nullptr;
}
execute( node->iffalse );
}
yssa_block* false_block = block;
// Final block.
if ( test_next || test_fail || true_block || false_block )
{
block = label_block();
assert( block );
if ( test_next )
{
link_block( test_next, NEXT, block );
}
if ( test_fail )
{
link_block( test_fail, FAIL, block );
}
if ( true_block )
{
link_block( true_block, NEXT, block );
}
if ( false_block )
{
link_block( false_block, NEXT, block );
}
}
close_scope( node->sloc, node->scope );
return 0;
}
int yssa_builder::visit( yl_stmt_switch* node, int count )
{
/*
eval value
eval case0value
if ( equal ) goto case0
eval case1value
if ( equal ) goto case1
goto default
case0:
statements
case1:
default:
statements
break:
close upvals
*/
open_scope( node->scope );
// Push the switch value.
size_t operands = push( node->value, 1 );
// Construct the dispatch table.
std::unordered_map< yl_stmt_case*, yssa_block* > case_gotos;
for ( size_t i = 0; i < node->body->stmts.size(); ++i )
{
// Find case statements.
yl_ast_node* stmt = node->body->stmts.at( i );
if ( stmt->kind != YL_STMT_CASE )
continue;
yl_stmt_case* cstmt = (yl_stmt_case*)stmt;
// Ignore the default case.
if ( ! cstmt->value )
continue;
// Open block.
if ( block && case_gotos.size() )
{
block = fail_block();
}
// Push the case value.
push( cstmt->value, 1 );
// Perform comparison.
yssa_opinst* o = op( cstmt->sloc, YL_EQ, 2, 1 );
pop( operands, 2, o->operand );
// Move to next comparison (if test fails).
if ( block )
{
assert( block->test == nullptr );
block->test = o;
}
case_gotos.emplace( cstmt, block );
// Repush switch value.
operands = push_op( o->operand[ 0 ] );
}
// Pop value.
yssa_opinst* value = nullptr;
pop( operands, 1, &value );
// If execution gets here then all tests have failed.
yssa_block* default_goto = block;
block = nullptr;
// Break to end of switch.
break_entry* sbreak = open_break( node->scope, BREAK );
// Evaluate actual case blocks.
for ( size_t i = 0; i < node->body->stmts.size(); ++i )
{
yl_ast_node* stmt = node->body->stmts.at( i );
if ( stmt->kind == YL_STMT_CASE )
{
yl_stmt_case* cstmt = (yl_stmt_case*)stmt;
// Work out which block to link.
yssa_block* jump_block = nullptr;
link_kind jump_link = NEXT;
if ( cstmt->value )
{
jump_block = case_gotos.at( cstmt );
jump_link = NEXT;
}
else
{
jump_block = default_goto;
jump_link = case_gotos.empty() ? NEXT : FAIL;
default_goto = nullptr;
}
if ( ! jump_block )
{
continue;
}
// Make a block to link to.
block = label_block();
// Link it.
assert( block );
link_block( jump_block, jump_link, block );
}
else
{
execute( stmt );
}
}
if ( default_goto || sbreak->blocks.size() )
{
// Make break target.
block = label_block();
assert( block );
// If there was no default case, the default gets here.
if ( default_goto )
{
link_block( default_goto, case_gotos.empty() ? NEXT : FAIL, block );
}
}
// Link break.
close_break( sbreak, block );
// Close scope.
close_scope( node->sloc, node->scope );
return 0;
}
int yssa_builder::visit( yl_stmt_while* node, int count )
{
/*
continue:
test condition
if ( failed ) goto exit:
statements
close upvals
goto continue
exit:
close upvals
break:
*/
// Enter loop.
if ( block )
{
block = next_block( YSSA_LOOP | YSSA_UNSEALED );
}
yssa_block* loop = block;
// Enter scope.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Test condition.
size_t test = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( test, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
yssa_block* test_fail = block;
if ( block )
{
block = next_block();
}
// Remember enough information to construct the close op
// on the exit branch.
assert( scopes.back().scope == node->scope );
assert( scopes.back().itercount == itercount );
std::vector< yssa_variable* > close;
close.insert
(
close.end(),
localups.begin() + scopes.back().localups,
localups.end()
);
// Statements.
execute( node->body );
close_scope( node->sloc, node->scope );
// Link back to top of loop.
close_break( lcontinue, loop );
if ( block && loop )
{
link_block( block, NEXT, loop );
}
block = nullptr;
if ( loop )
{
seal_block( loop );
}
// Fill in failure branch.
if ( test_fail )
{
block = label_block();
link_block( test_fail, FAIL, block );
// Need to close upvals.
if ( close.size() )
{
yssa_opinst* o = op( node->sloc, YL_CLOSE, close.size(), 0 );
o->a = localups.size();
o->b = itercount;
for ( size_t i = 0; i < close.size(); ++i )
{
o->operand[ i ] = lookup( close.at( i ) );
}
}
}
// Fill in breaks.
if ( lbreak->blocks.size() )
{
block = label_block();
}
close_break( lbreak, block );
return 0;
}
int yssa_builder::visit( yl_stmt_do* node, int count )
{
/*
top:
statements
continue:
test
close upvals
if ( succeeded ) goto top
break:
*/
// Enter loop.
if ( block )
{
block = next_block( YSSA_LOOP | YSSA_UNSEALED );
}
yssa_block* loop = block;
// Enter scope.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Statements.
execute( node->body );
// Link continue.
if ( lcontinue->blocks.size() )
{
block = label_block();
}
close_break( lcontinue, block );
// Perform test.
size_t test = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( test, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
// Close scope.
close_scope( node->sloc, node->scope );
// Link the success condition to the top of the loop.
if ( block && loop )
{
link_block( block, NEXT, loop );
}
if ( loop )
{
seal_block( loop );
}
// Failure exits the loop.
if ( block )
{
block = fail_block();
}
close_break( lbreak, block );
return 0;
}
int yssa_builder::visit( yl_stmt_foreach* node, int count )
{
/*
iter/iterkey list
goto entry
continue:
assign/declare iterator values
statements
close upvals
entry:
if ( have values ) goto continue
close iterator
break:
*/
// Open scope that declares the iterator. We break into a scope that
// does not contain the iterator.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
// Push iterator.
size_t operand = push( node->list, 1 );
yl_opcode opcode = node->eachkey ? YL_ITERKEY : YL_ITER;
yssa_opinst* o = op( node->sloc, opcode, 1, 0 );
pop( operand, 1, o->operand );
size_t iterindex = itercount;
o->r = iterindex;
itercount += 1;
// Goto entry.
yssa_block* entry_block = block;
// Declare body scope, for upvals contained in the body. We continue
// into a scope that contains the iterator.
open_scope( node->scope );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Create (unsealed) continue block. This block is not the loop
// header, as it is dominated by the entry block.
block = label_block( YSSA_UNSEALED );
yssa_block* body_block = block;
// Work out which opcode to use to request values.
opcode = YL_NOP;
if ( node->lvalues.size() == 1 )
opcode = YL_NEXT1;
else if ( node->lvalues.size() == 2 )
opcode = YL_NEXT2;
else
opcode = YL_NEXT;
if ( node->declare )
{
// Request correct number of ops from iterator.
yssa_opinst* o = op( node->sloc, opcode, 0, node->lvalues.size() );
o->b = iterindex;
// Declare each variable.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
assert( node->lvalues.at( i )->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)node->lvalues.at( i );
yssa_variable* v = variable( local->name );
if ( opcode == YL_NEXT )
{
declare( node->sloc, v, o );
}
else
{
yssa_opinst* select = op( node->sloc, YSSA_SELECT, 1, 1 );
select->operand[ 0 ] = o;
select->select = (int)i;
declare( node->sloc, v, select );
}
}
}
else
{
// Push each lvalue.
std::vector< size_t > lvalues;
lvalues.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = push_lvalue( node->lvalues.at( i ) );
lvalues.push_back( lvalue );
}
// Request correct number of ops from iterator.
yssa_opinst* o = op( node->sloc, opcode, 0, node->lvalues.size() );
o->b = iterindex;
// Build select ops.
std::vector< yssa_opinst* > selects;
selects.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
if ( opcode == YL_NEXT )
{
selects.push_back( o );
}
else
{
yssa_opinst* select = op( node->sloc, YSSA_SELECT, 1, 1 );
select->operand[ 0 ] = o;
select->select = (int)i;
selects.push_back( select );
}
}
// Assign each variable.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
yssa_opinst* o = selects.at( i );
assign_lvalue
(
node->sloc,
node->lvalues.at( i ),
lvalues.at( i ),
o
);
}
// Pop lvalues.
for ( size_t i = node->lvalues.size(); i-- > 0; )
{
pop_lvalue( node->lvalues.at( i ), lvalues.at( i ) );
}
}
// Perform statements.
execute( node->body );
// Exit upval scope.
close_scope( node->sloc, node->scope );
// Loop entry block.
if ( block || entry_block )
{
block = label_block( YSSA_LOOP );
assert( block );
if ( entry_block )
{
link_block( entry_block, NEXT, block );
}
}
// Perform loop check.
o = op( node->sloc, YSSA_ITERDONE, 0, 0 );
o->b = iterindex;
if ( block )
{
assert( block->test == nullptr );
block->test = o;
}
// Link continue.
close_break( lcontinue, body_block );
if ( body_block )
{
seal_block( body_block );
}
// Exit iterator scope.
close_scope( node->sloc, node->scope );
// Link break.
if ( lbreak->blocks.size() )
{
block = label_block();
}
close_break( lbreak, block );
return 0;
}
int yssa_builder::visit( yl_stmt_for* node, int count )
{
/*
init
top:
condition
if ( failed ) goto break:
statements
continue:
update
goto top
break:
close upvals
*/
// Scope of for init/condition/update covers all iterations of loop.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Init.
if ( node->init )
{
execute( node->init );
}
// Loop.
if ( block )
{
block = next_block( YSSA_LOOP | YSSA_UNSEALED );
}
yssa_block* loop = block;
// Condition.
yssa_block* test_fail = nullptr;
if ( node->condition )
{
size_t test = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( test, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
test_fail = block;
if ( block )
{
block = next_block();
}
}
// Body. A for body should have its own scope to declare upvals in.
execute( node->body );
// Continue location.
if ( lcontinue->blocks.size() )
{
block = label_block();
}
close_break( lcontinue, block );
if ( node->update )
{
execute( node->update );
}
if ( block && loop )
{
link_block( block, NEXT, loop );
}
if ( loop )
{
seal_block( loop );
}
block = nullptr;
// Break location.
if ( test_fail || lbreak->blocks.size() )
{
block = label_block();
assert( block );
if ( test_fail )
{
link_block( test_fail, FAIL, block );
}
}
close_break( lbreak, block );
// Close scope.
close_scope( node->sloc, node->scope );
return 0;
}
int yssa_builder::visit( yl_stmt_using* node, int count )
{
/*
o0.acquire();
[
o1.acquire();
[
using block
]
o1.release();
unwind
]
o0.release();
unwind
*/
// Call o.acquire().
int valcount = 0;
size_t uvalues = push_all( node->uvalue, &valcount );
// Using does support multiple values (more fool me).
std::vector< yssa_block_p > xchandlers;
for ( int i = 0; i < valcount; ++i )
{
// Call acquire().
yssa_opinst* m = op( node->sloc, YL_KEY, 1, 1 );
m->operand[ 0 ] = peek( uvalues, i );
m->key = "acquire";
yssa_opinst* c = op( node->sloc, YL_CALL, 2, 0 );
c->operand[ 0 ] = m;
c->operand[ 1 ] = peek( uvalues, i );
call( c );
// Open protected context.
yssa_block_p xchandler =
std::make_unique< yssa_block >( YSSA_XCHANDLER );
xchandler->unwind_localups = localups.size();
xchandler->unwind_itercount = itercount;
xchandler->xchandler =
scopes.size() ? scopes.back().xchandler : nullptr;
open_scope( node->scope, xchandler.get() );
xchandlers.push_back( std::move( xchandler ) );
if ( block )
{
block = next_block();
assert( block->xchandler == xchandlers.back().get() );
}
}
// Using block. Leave all the uvalues on the stack - there's
// only one definition of each.
execute( node->body );
// Close each scope and implement handler.
for ( int i = valcount; i-- > 0; )
{
// Leave protected context.
close_scope( node->sloc, node->scope );
// Handler is next block.
yssa_block* xchandler = xchandlers.at( i ).get();
function->blocks.push_back( std::move( xchandlers.at( i ) ) );
if ( block )
{
link_block( block, NEXT, xchandler );
block = xchandler;
}
// Call release().
yssa_opinst* m = op( node->sloc, YL_KEY, 1, 1 );
m->operand[ 0 ] = peek( uvalues, i );
m->key = "release";
yssa_opinst* c = op( node->sloc, YL_CALL, 2, 0 );
c->operand[ 0 ] = m;
c->operand[ 1 ] = peek( uvalues, i );
call( c );
// Continue potential exception unwind.
op( node->sloc, YL_UNWIND, 0, 0 );
// Pop uvalue.
yssa_opinst* value = nullptr;
pop( uvalues + i, 1, &value );
}
return 0;
}
int yssa_builder::visit( yl_stmt_try* node, int count )
{
/*
[
[
tstmt
goto finally
]
catch:
filter
if ( failed ) goto next_catch
catch
goto finally
next_catch:
filter
if ( failed ) goto finally
catch
goto finally
]
finally:
finally statement
unwind
*/
/*
There are two potential protected contexts - one that
passes control to the finally block (which can also be
entered normally), and one that passes control to the
exeption filter chain of catch () statements.
*/
yssa_block_p xcfinally = nullptr;
yssa_block_p xccatch = nullptr;
if ( node->fstmt )
{
xcfinally = std::make_unique< yssa_block >( YSSA_XCHANDLER );
xcfinally->unwind_localups = localups.size();
xcfinally->unwind_itercount = itercount;
xcfinally->xchandler =
scopes.size() ? scopes.back().xchandler : nullptr;
open_scope( nullptr, xcfinally.get() );
}
if ( node->clist.size() )
{
xccatch = std::make_unique< yssa_block >( YSSA_XCHANDLER );
xccatch->unwind_localups = localups.size();
xccatch->unwind_itercount = itercount;
xccatch->xchandler =
scopes.size() ? scopes.back().xchandler : nullptr;
open_scope( nullptr, xccatch.get() );
}
if ( block && ( node->fstmt || node->clist.size() ) )
{
block = next_block();
assert( block->xchandler );
}
execute( node->tstmt );
// Construct exception filter from the catch clauses.
yssa_block* catch_jump = nullptr;
std::vector< yssa_block* > finally_jumps;
if ( node->clist.size() )
{
close_scope( node->sloc, nullptr );
if ( block )
{
finally_jumps.push_back( block );
block = nullptr;
}
// Enter handler block for catch.
block = xccatch.get();
function->blocks.push_back( std::move( xccatch ) );
// If the catch failed, go to the next one.
for ( size_t i = 0; i < node->clist.size(); ++i )
{
assert( node->clist.at( i )->kind == YL_STMT_CATCH );
yl_stmt_catch* cstmt = (yl_stmt_catch*)node->clist.at( i );
// Link from previous failed catch filter expression.
if ( catch_jump )
{
block = label_block();
link_block( catch_jump, FAIL, block );
}
// Get exception.
yssa_opinst* e = nullptr;
if ( cstmt->proto || cstmt->lvalue )
{
e = op( cstmt->sloc, YL_EXCEPT, 0, 1 );
}
// Test catch filter.
if ( cstmt->proto )
{
size_t operands = push_op( e );
push( cstmt->proto, 1 );
yssa_opinst* o = op( cstmt->sloc, YL_IS, 2, 1 );
pop( operands, 2, o->operand );
if ( block )
{
assert( block->test == nullptr );
block->test = o;
catch_jump = block;
block = next_block();
}
}
// Catch block for when test passes.
open_scope( cstmt->scope );
// Make exception assignment.
if ( cstmt->lvalue && cstmt->declare )
{
assert( cstmt->lvalue->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)cstmt->lvalue;
yssa_variable* v = variable( local->name );
declare( cstmt->sloc, v, e );
}
else if ( cstmt->lvalue )
{
size_t lvalue = push_lvalue( cstmt->lvalue );
assign_lvalue( cstmt->sloc, cstmt->lvalue, lvalue, e );
pop_lvalue( cstmt->lvalue, lvalue );
}
execute( cstmt->body );
close_scope( node->sloc, cstmt->scope );
if ( block )
{
finally_jumps.push_back( block );
block = nullptr;
}
}
}
if ( node->fstmt )
{
close_scope( node->sloc, nullptr );
if ( block )
{
finally_jumps.push_back( block );
block = nullptr;
}
block = xcfinally.get();
function->blocks.push_back( std::move( xcfinally ) );
}
else if ( catch_jump || finally_jumps.size() )
{
block = label_block();
}
if ( catch_jump )
{
link_block( catch_jump, FAIL, block );
}
for ( size_t i = 0; i < finally_jumps.size(); ++i )
{
link_block( finally_jumps.at( i ), NEXT, block );
}
if ( node->fstmt )
{
execute( node->fstmt );
op( node->sloc, YL_UNWIND, 0, 0 );
}
return 0;
}
int yssa_builder::visit( yl_stmt_catch* node, int count )
{
assert( ! "catch outside try" );
return 0;
}
int yssa_builder::visit( yl_stmt_delete* node, int count )
{
for ( size_t i = 0; i < node->delvals.size(); ++i )
{
yl_ast_node* delval = node->delvals.at( i );
if ( delval->kind == YL_EXPR_KEY )
{
yl_expr_key* expr = (yl_expr_key*)node;
size_t operand = push( expr->object, 1 );
yssa_opinst* o = op( node->sloc, YL_DELKEY, 1, 0 );
pop( operand, 1, o->operand );
o->key = module->alloc.strdup( expr->key );
}
else if ( delval->kind == YL_EXPR_INKEY )
{
yl_expr_inkey* expr = (yl_expr_inkey*)node;
size_t operands = push( expr->object, 1 );
push( expr->key, 1 );
yssa_opinst* o = op( node->sloc, YL_DELINKEY, 2, 0 );
pop( operands, 2, o->operand );
}
}
return 0;
}
int yssa_builder::visit( yl_stmt_case* node, int count )
{
assert( ! "case outside switch" );
return 0;
}
int yssa_builder::visit( yl_stmt_continue* node, int count )
{
// Get break entry.
auto i = breaks.find( break_key( node->target, CONTINUE ) );
if ( i == breaks.end() )
{
assert( ! "continue outside continuable scope" );
return 0;
}
break_entry* b = i->second.get();
// Close.
close( node->sloc, b->localups, b->itercount );
// This branch terminates at the continue (which should be
// linked when the continuable scope closes).
if ( block )
{
b->blocks.push_back( block );
block = nullptr;
}
return 0;
}
int yssa_builder::visit( yl_stmt_break* node, int count )
{
// Get break entry.
auto i = breaks.find( break_key( node->target, BREAK ) );
if ( i == breaks.end() )
{
assert( "break outside breakable scope" );
return 0;
}
break_entry* b = i->second.get();
// Close.
close( node->sloc, b->localups, b->itercount );
// This branch terminates at the break (which should be
// linked when the breakable scope closes).
if ( block )
{
b->blocks.push_back( block );
block = nullptr;
}
return 0;
}
int yssa_builder::visit( yl_stmt_return* node, int count )
{
// Push return values.
int valcount = 0;
size_t operands = push_all( node->values, &valcount );
// Close everything.
close( node->sloc, 0, 0 );
// Return.
yssa_opinst* o = op( node->sloc, YL_RETURN, valcount, 0 );
pop( operands, valcount, o->operand );
o->multival = multival;
multival = nullptr;
return 0;
}
int yssa_builder::visit( yl_stmt_throw* node, int count )
{
// The stack unwind should take care of closing things.
size_t operand = push( node->value, 1 );
yssa_opinst* o = op( node->sloc, YL_THROW, 1, 0 );
pop( operand, 1, o->operand );
return 0;
}
int yssa_builder::visit( yl_ast_func* node, int count )
{
// Function op.
yssa_function* function = funcmap.at( node );
yssa_opinst* o = op( node->sloc, YL_CLOSURE, 0, 1 );
o->function = function;
// Upval initializers.
for ( size_t i = 0; i < node->upvals.size(); ++i )
{
const yl_ast_upval& uv = node->upvals.at( i );
switch ( uv.kind )
{
case YL_UPVAL_LOCAL:
{
// Make an upval from a local variable.
yssa_variable* v = variable( uv.local );
yssa_opinst* u = op( node->sloc, YL_UPLOCAL, 1, 0 );
u->r = i;
u->associated = o;
u->a = v->localup;
u->operand[ 0 ] = lookup( v );
break;
}
case YL_UPVAL_OBJECT:
{
// Make an upval from a local object under constrution.
yssa_variable* v = varobj( uv.object );
yssa_opinst* u = op( node->sloc, YL_UPLOCAL, 1, 0 );
u->r = i;
u->associated = o;
u->a = v->localup;
u->operand[ 0 ] = lookup( v );
break;
}
case YL_UPVAL_UPVAL:
{
// Make an upval from an existing upval.
yssa_opinst* u = op( node->sloc, YL_UPUPVAL, 0, 0 );
u->r = i;
u->associated = o;
u->a = uv.upval;
break;
}
}
}
// Push onto virtual stack.
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_null* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_NULL, 0, 1 );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_bool* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_BOOL, 0, 1 );
o->a = node->value ? 1 : 0;
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_number* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_NUMBER, 0, 1 );
o->number = node->value;
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_string* node, int count )
{
// Copy string.
char* string = (char*)module->alloc.malloc( node->length + 1 );
memcpy( string, node->string, node->length );
string[ node->length ] = '\0';
// Push value.
yssa_opinst* o = op( node->sloc, YL_STRING, 0, 1 );
o->string = new ( module->alloc ) yssa_string( string, node->length );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_local* node, int count )
{
// Find definition of the variable which reaches this point.
yssa_variable* v = variable( node->name );
push_op( lookup( v ) );
return 1;
}
int yssa_builder::visit( yl_expr_global* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_GLOBAL, 0, 1 );
o->key = module->alloc.strdup( node->name );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_upref* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_GETUP, 0, 1 );
o->a = (uint8_t)node->index;
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_objref* node, int count )
{
// Find definition of object.
yssa_variable* v = varobj( node->object );
push_op( lookup( v ) );
return 1;
}
int yssa_builder::visit( yl_expr_superof* node, int count )
{
size_t operand = push( node->expr, 1 );
yssa_opinst* o = op( node->sloc, YL_SUPER, 1, 1 );
pop( operand, 1, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_key* node, int count )
{
size_t operand = push( node->object, 1 );
yssa_opinst* o = op( node->sloc, YL_KEY, 1, 1 );
pop( operand, 1, o->operand );
o->key = module->alloc.strdup( node->key );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_inkey* node, int count )
{
size_t operands = push( node->object, 1 );
push( node->key, 1 );
yssa_opinst* o = op( node->sloc, YL_INKEY, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_index* node, int count )
{
size_t operands = push( node->object, 1 );
push( node->index, 1 );
yssa_opinst* o = op( node->sloc, YL_INDEX, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_preop* node, int count )
{
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t evalue = push_evalue( node->lvalue, lvalue ); // lv, ev
// perform operation.
yl_opcode opcode = ( node->opkind == YL_ASTOP_PREINC ) ? YL_ADD : YL_SUB;
yssa_opinst* o = op( node->sloc, opcode, 2, 1 );
pop( evalue, 1, o->operand );
o->operand[ 1 ] = op( node->sloc, YL_NUMBER, 0, 1 );
o->operand[ 1 ]->number = 1.0;;
// perform assignment.
o = assign_lvalue( node->sloc, node->lvalue, lvalue, o );
// push updated value onto stack.
pop_lvalue( node->lvalue, lvalue );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_postop* node, int count )
{
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t evalue = push_evalue( node->lvalue, lvalue ); // lv, ev
// perform operation
yl_opcode opcode = ( node->opkind == YL_ASTOP_POSTINC ) ? YL_ADD : YL_SUB;
yssa_opinst* o = op( node->sloc, opcode, 2, 1 );
pop( evalue, 1, o->operand );
o->operand[ 1 ] = op( node->sloc, YL_NUMBER, 0, 1 );
o->operand[ 1 ]->number = 1.0;;
// perform assignment (which might clobber the original value).
size_t ovalue = push_op( o->operand[ 0 ] );
assign_lvalue( node->sloc, node->lvalue, lvalue, o );
// push original value onto stack.
yssa_opinst* value = nullptr;
pop( ovalue, 1, &value );
pop_lvalue( node->lvalue, lvalue );
push_op( value );
return 1;
}
int yssa_builder::visit( yl_expr_unary* node, int count )
{
size_t operand = push( node->operand, 1 );
yl_opcode opcode = YL_NOP;
switch ( node->opkind )
{
case YL_ASTOP_POSITIVE:
{
// Implemented as negative negative.
yssa_opinst* o = op( node->sloc, YL_NEG, 1, 1 );
pop( operand, 1, o->operand );
operand = push_op( o );
opcode = YL_NEG;
break;
}
case YL_ASTOP_NEGATIVE:
opcode = YL_NEG;
break;
case YL_ASTOP_LOGICNOT:
opcode = YL_LNOT;
break;
case YL_ASTOP_BITNOT:
opcode = YL_BITNOT;
break;
default:
assert( ! "invalid unary operator" );
break;
}
yssa_opinst* o = op( node->sloc, opcode, 1, 1 );
pop( operand, 1, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_binary* node, int count )
{
size_t operands = push( node->lhs, 1 );
push( node->rhs, 1 );
yl_opcode opcode = YL_NOP;
switch ( node->opkind )
{
case YL_ASTOP_MULTIPLY:
opcode = YL_MUL;
break;
case YL_ASTOP_DIVIDE:
opcode = YL_DIV;
break;
case YL_ASTOP_MODULUS:
opcode = YL_MOD;
break;
case YL_ASTOP_INTDIV:
opcode = YL_INTDIV;
break;
case YL_ASTOP_ADD:
opcode = YL_ADD;
break;
case YL_ASTOP_SUBTRACT:
opcode = YL_SUB;
break;
case YL_ASTOP_LSHIFT:
opcode = YL_LSL;
break;
case YL_ASTOP_LRSHIFT:
opcode = YL_LSR;
break;
case YL_ASTOP_ARSHIFT:
opcode = YL_ASR;
break;
case YL_ASTOP_BITAND:
opcode = YL_BITAND;
break;
case YL_ASTOP_BITXOR:
opcode = YL_BITXOR;
break;
case YL_ASTOP_BITOR:
opcode = YL_BITOR;
break;
case YL_ASTOP_CONCATENATE:
opcode = YL_CONCAT;
break;
default:
assert( ! "invalid binary operator" );
break;
}
yssa_opinst* o = op( node->sloc, YL_MUL, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_compare* node, int count )
{
/*
operand a
operand b
result = comparison
? goto next1 : goto final
next1:
operand c
result = comparison
? goto next2 : goto final
next2:
operand d
result = comparison
goto final
final:
*/
// With shortcut evaluation, the result could be any of the intermediate
// comparison results. This requires a temporary.
yssa_variable* result = node->opkinds.size() > 1 ?
temporary( "[comparison]", node->sloc ) : nullptr;
// Evaluate first term.
size_t operands = push( node->first, 1 ); // a
// Intermediate comparisons.
std::vector< yssa_block* > blocks;
size_t last = node->opkinds.size() - 1;
for ( size_t i = 0; ; ++i )
{
push( node->terms.at( i ), 1 ); // a, b
// Perform comparison.
yl_ast_opkind opkind = node->opkinds.at( i );
yl_opcode opcode = YL_NOP;
switch ( opkind )
{
case YL_ASTOP_EQUAL:
opcode = YL_EQ;
break;
case YL_ASTOP_NOTEQUAL:
opcode = YL_NE;
break;
case YL_ASTOP_LESS:
opcode = YL_LT;
break;
case YL_ASTOP_GREATER:
opcode = YL_GT;
break;
case YL_ASTOP_LESSEQUAL:
opcode = YL_LE;
break;
case YL_ASTOP_GREATEREQUAL:
opcode = YL_GE;
break;
case YL_ASTOP_IN:
opcode = YL_IN;
break;
case YL_ASTOP_NOTIN:
opcode = YL_IN;
break;
case YL_ASTOP_IS:
opcode = YL_IS;
break;
case YL_ASTOP_NOTIS:
opcode = YL_IS;
break;
default:
assert( ! "unexpected comparison operator" );
break;
}
yssa_opinst* o = op( node->sloc, opcode, 2, 1 );
pop( operands, 2, o->operand );
size_t index = push_op( o );
yssa_opinst* b = o->operand[ 1 ];
if ( opkind == YL_ASTOP_NOTIN || opkind == YL_ASTOP_NOTIS )
{
o = op( node->sloc, YL_LNOT, 1, 1 );
pop( index, 1, o->operand );
index = push_op( o );
}
// Assign to temporary.
if ( result )
{
pop( index, 1, &o );
o = assign( node->sloc, result, o );
}
// No shortcut after last comparison in chain.
if ( i >= last )
{
break;
}
// Only continue to next block if comparison is true.
if ( block )
{
assert( block->test == nullptr );
block->test = o;
blocks.push_back( block );
block = next_block();
}
// Ensure that operand b is on the top of the virtual stack.
operands = push_op( b );
}
// Any failed comparison shortcuts to the end.
if ( blocks.size() )
{
block = label_block();
for ( size_t i = 0; i < blocks.size(); ++i )
{
yssa_block* shortcut = blocks.at( i );
link_block( shortcut, FAIL, block );
}
}
// Push lookup of temporary.
if ( result )
{
push_op( lookup( result ) );
}
return 1;
}
int yssa_builder::visit( yl_expr_logical* node, int count )
{
switch ( node->opkind )
{
case YL_ASTOP_LOGICAND:
{
/*
result = lhs
? goto next : goto final
next:
result = rhs
final:
*/
yssa_variable* result = temporary( "[shortcut and]", node->sloc );
// Evaluate left hand side.
size_t operand = push( node->lhs, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
value = assign( node->sloc, result, value );
// Only continue to next block if lhs is true.
yssa_block* lhs_block = block;
if ( block )
{
assert( block->test == nullptr );
block->test = value;
block = next_block();
}
// Evaluate right hand side.
operand = push( node->rhs, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
// Link in the shortcut.
if ( lhs_block )
{
block = label_block();
link_block( lhs_block, FAIL, block );
}
// Push lookup of temporary.
push_op( lookup( result ) );
return 1;
}
case YL_ASTOP_LOGICXOR:
{
size_t operands = push( node->lhs, 1 );
push( node->rhs, 1 );
yssa_opinst* o = op( node->sloc, YL_LXOR, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
case YL_ASTOP_LOGICOR:
{
/*
result = lhs
? goto final : goto next
next:
result = rhs
final:
*/
yssa_variable* result = temporary( "[shortcut or]", node->sloc );
// Evaluate left hand side.
size_t operand = push( node->lhs, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
value = assign( node->sloc, result, value );
// Only continue to next block if lhs is false.
yssa_block* lhs_block = block;
if ( block )
{
assert( block->test == nullptr );
block->test = value;
block = fail_block();
}
// Evaluate right hand side.
operand = push( node->rhs, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
// Link in the shortcut.
if ( lhs_block )
{
block = label_block();
link_block( lhs_block, NEXT, block );
}
// Push lookup of temporary.
push_op( lookup( result ) );
return 1;
}
default:
assert( ! "invalid logical operator" );
return 0;
}
}
int yssa_builder::visit( yl_expr_qmark* node, int count )
{
/*
condition
? goto iftrue : goto iffalse
iftrue:
result = trueexpr
goto final
iffalse:
result = falseexpr
goto final
final:
*/
// Evaluate condition.
size_t operand = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
// True block.
yssa_block* test_block = block;
if ( block )
{
assert( block->test = nullptr );
block->test = value;
block = next_block();
}
// Result is a temporary since there is more than one definition.
yssa_variable* result = temporary( "[qmark]", node->sloc );
// Evaluate true branch.
operand = push( node->iftrue, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
yssa_block* true_block = block;
// False block.
block = test_block;
if ( block )
{
block = fail_block();
}
// Evaluate false branch.
operand = push( node->iffalse, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
yssa_block* false_block = block;
// Final block.
if ( true_block || false_block )
{
block = label_block();
if ( true_block )
{
link_block( true_block, NEXT, block );
}
if ( false_block )
{
link_block( false_block, NEXT, block );
}
}
// Push lookup of temporary.
push_op( lookup( result ) );
return 1;
}
int yssa_builder::visit( yl_new_new* node, int count )
{
// Evaluate object prototype.
size_t operand = push( node->proto, 1 );
// Create object using prototype.
yssa_opinst* o = op( node->sloc, YL_OBJECT, 1, 1 );
pop( operand, 1, o->operand );
operand = push_op( o );
// Call 'this' method.
yssa_opinst* m = op( node->sloc, YL_KEY, 1, 1 );
m->operand[ 0 ] = o;
m->key = "this";
size_t method = push_op( m );
// Repush the object (as this argument).
push_op( o );
// Push arguments.
int argcount = 0;
push_all( node->arguments, &argcount );
// Perform call.
yssa_opinst* c = op( node->sloc, YL_CALL, argcount + 2, 0 );
pop( method, argcount + 2, c->operand );
c->multival = multival;
multival = nullptr;
call( c );
// Only thing on virtual stack should be the constructed object.
return 1;
}
int yssa_builder::visit( yl_new_object* node, int count )
{
// Evaluate prototype.
yssa_opinst* o = nullptr;
if ( node->proto )
{
size_t operand = push( node->proto, 1 );
o = op( node->sloc, YL_OBJECT, 1, 1 );
pop( operand, 1, o->operand );
}
else
{
o = op( node->sloc, YL_OBJECT, 0, 1 );
}
// Push object onto virtual stack.
push_op( o );
// Declare object (as it can potentially be referenced as an upval).
open_scope( nullptr );
yssa_variable* object = varobj( node );
declare( node->sloc, object, o );
// Execute all member initializers.
for ( size_t i = 0; i < node->members.size(); ++i )
{
execute( node->members.at( i ) );
}
// Close upval (if any).
close_scope( node->sloc, nullptr );
// object should still be on the virtual stack.
return 1;
}
int yssa_builder::visit( yl_new_array* node, int count )
{
// Construct new array.
yssa_opinst* o = op( node->sloc, YL_ARRAY, 0, 1 );
o->c = node->values.size();
push_op( o );
// Append each element.
for ( size_t i = 0; i < node->values.size(); ++i )
{
size_t element = push( node->values.at( i ), 1 );
yssa_opinst* a = op( node->sloc, YL_APPEND, 2, 0 );
a->operand[ 0 ] = o;
pop( element, 1, &a->operand[ 1 ] );
}
// Extend final elements.
if ( node->final )
{
int count = 0;
size_t extend = push_all( node->final, &count );
yssa_opinst* e = op( node->sloc, YL_EXTEND, count + 1, 0 );
e->operand[ 0 ] = o;
pop( extend, count, &e->operand[ 1 ] );
e->multival = multival;
multival = nullptr;
}
// array should still be on virtual stack.
return 1;
}
int yssa_builder::visit( yl_new_table* node, int count )
{
// Construct new table.
yssa_opinst* o = op( node->sloc, YL_TABLE, 0, 1 );
o->c = node->elements.size();
push_op( o );
// Append each element.
for ( size_t i = 0; i < node->elements.size(); ++i )
{
const yl_key_value& kv = node->elements.at( i );
size_t operands = push( kv.key, 1 );
push( kv.value, 1 );
yssa_opinst* e = op( node->sloc, YL_SETINDEX, 2, 0 );
pop( operands, 2, e->operand );
}
// table should still be on virtual stack
return 1;
}
int yssa_builder::visit( yl_expr_mono* node, int count )
{
// Even when used in a context that requests multiple values,
// push only a single value onto the virtual stack.
push( node->expr, 1 );
return 1;
}
int yssa_builder::visit( yl_expr_call* node, int count )
{
// Restrict call expressions without unpack ellipsis to a single result.
if ( ! node->unpack && count != 0 )
{
count = 1;
}
// Check for method call.
size_t function = 0;
int funcount = 0;
switch ( node->function->kind )
{
case YL_EXPR_KEY:
{
yl_expr_key* knode = (yl_expr_key*)node->function;
// Look up key for method.
size_t operand = push( knode->object, 1 );
yssa_opinst* o = op( knode->sloc, YL_KEY, 1, 1 );
pop( operand, 1, o->operand );
o->key = module->alloc.strdup( knode->key );
push_op( o );
// Push the object onto the virtual stack as the 'this' parameter.
push_op( o->operand[ 0 ] );
funcount = 2;
break;
}
case YL_EXPR_INKEY:
{
yl_expr_inkey* knode = (yl_expr_inkey*)node->function;
// Look up index for method.
size_t operands = push( knode->object, 1 );
push( knode->key, 1 );
yssa_opinst* o = op( knode->sloc, YL_INKEY, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
// Push the object onto virtual stack as the 'this' parameter.
push_op( o->operand[ 0 ] );
funcount = 2;
break;
}
default:
{
function = push( node->function, 1 );
funcount = 1;
break;
}
}
// Push arguments.
int argcount = 0;
push_all( node->arguments, &argcount );
// Perform call.
yl_opcode opcode = node->yieldcall ? YL_YCALL : YL_CALL;
yssa_opinst* c = op( node->sloc, opcode, funcount + argcount, count );
pop( function, funcount + argcount, c->operand );
c->multival = multival;
multival = nullptr;
call( c );
// Return results appropriately on the stack.
return push_select( node->sloc, c, count );
}
int yssa_builder::visit( yl_expr_yield* node, int count )
{
// Restrict expressions without unpack to a single result.
if ( ! node->unpack && count != 0 )
{
count = 1;
}
// Push arguments.
int argcount = 0;
size_t arguments = push_all( node->arguments, &argcount );
// Perform yield.
yssa_opinst* y = op( node->sloc, YL_YIELD, argcount, count );
pop( arguments, argcount, y->operand );
y->multival = multival;
multival = nullptr;
call( y );
// Return results appropriately on the stack.
return push_select( node->sloc, y, count );
}
int yssa_builder::visit( yl_expr_vararg* node, int count )
{
if ( count != 0 )
{
yssa_opinst* o = op( node->sloc, YL_VARARG, 0, count );
return push_select( node->sloc, o, count );
}
else
{
return 0;
}
}
int yssa_builder::visit( yl_expr_unpack* node, int count )
{
if ( count != 0 )
{
size_t operand = push( node->array, 1 );
yssa_opinst* o = op( node->sloc, YL_UNPACK, 1, count );
pop( operand, 1, o->operand );
return push_select( node->sloc, o, count );
}
else
{
execute( node->array );
return 0;
}
}
int yssa_builder::visit( yl_expr_list* node, int count )
{
// Work out how many values we need to actually push.
int value_count = (int)node->values.size();
if ( count != -1 )
{
value_count = std::min( value_count, count );
}
// Push value_count values.
for ( size_t i = 0; i < value_count; ++i )
{
push( node->values.at( i ), 1 );
}
// Execute remaining values without leaving them on the stack.
for ( size_t i = value_count; i < node->values.size(); ++i )
{
execute( node->values.at( i ) );
}
// If there's an unpack value at the end of the list, then unpack it.
if ( node->final )
{
if ( count == -1 )
{
int final_count = 0;
push_all( node->final, &final_count );
value_count += final_count;
}
else if ( count > value_count )
{
push( node->final, count - value_count );
value_count = count;
}
else
{
execute( node->final );
}
}
return value_count;
}
int yssa_builder::visit( yl_expr_assign* node, int count )
{
if ( node->assignop == YL_ASTOP_DECLARE )
{
// Lvalue is a new variable.
assert( node->lvalue->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)node->lvalue;
yssa_variable* v = variable( local->name );
// Evaluate rvalue.
yssa_opinst* value = nullptr;
if ( node->rvalue )
{
size_t rvalue = push( node->rvalue, 1 );
pop( rvalue, 1, &value );
}
else
{
value = op( node->sloc, YL_NULL, 0, 1 );
}
// Assign.
value = declare( node->sloc, v, value );
// Push value onto stack as result.
push_op( value );
return 1;
}
else if ( node->assignop == YL_ASTOP_ASSIGN )
{
// Assign rvalue to lvalue.
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t rvalue = push( node->rvalue, 1 ); // lv, rv
yssa_opinst* value = nullptr;
pop( rvalue, 1, &value );
value = assign_lvalue( node->sloc, node->lvalue, lvalue, value );
pop_lvalue( node->lvalue, lvalue );
// Push result value onto stack as result.
push_op( value );
return 1;
}
else
{
// Evaluate lvalue and assign it with the assign op.
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t evalue = push_evalue( node->lvalue, lvalue ); // lv, ev
push( node->rvalue, 1 ); // lv, ev, rv
yssa_opinst* o = assign_op( node->sloc, node->assignop, evalue );
o = assign_lvalue( node->sloc, node->lvalue, lvalue, o );
pop_lvalue( node->lvalue, lvalue );
// Push result value onto stack as result.
push_op( o );
return 1;
}
}
int yssa_builder::visit( yl_expr_assign_list* node, int count )
{
// This is the most complex thing ever.
// Work out how many values we actually need to push. We only have
// as many values as there are lvalues on the left hand side.
int value_count = (int)node->lvalues.size();
if ( count != -1 )
{
value_count = std::min( value_count, count );
}
if ( node->assignop == YL_ASTOP_DECLARE )
{
// Evaluate rvalue list.
size_t rvalues = push( node->rvalues, (int)node->lvalues.size() );
// Assign them all.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
// Lvalue is a new variable.
yl_ast_node* lnode = node->lvalues.at( i );
assert( lnode->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)lnode;
yssa_variable* v = variable( local->name );
// Rvalue is on stack.
declare( node->sloc, v, peek( rvalues, i ) );
}
// Pop values.
std::vector< yssa_opinst* > values;
values.resize( node->lvalues.size() );
pop( rvalues, (int)node->lvalues.size(), values.data() );
// Push correct number of values back.
assert( value_count <= (int)node->lvalues.size() );
for ( int i = 0; i < value_count; ++i )
{
push_op( values.at( i ) );
}
return value_count;
}
else if ( node->assignop == YL_ASTOP_ASSIGN )
{
/*
a, b = b, a;
a = 4;
b = a, a = 3, a + 3;
assert( a == 7 );
assert( b == 3 ); // possibly!
*/
// Push each lvalue.
std::vector< size_t > lvalues;
lvalues.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = push_lvalue( node->lvalues.at( i ) );
lvalues.push_back( lvalue );
}
// Evaluate rvalue list.
size_t rvalues = push( node->rvalues, (int)node->lvalues.size() );
// Assign them all.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
assign_lvalue
(
node->sloc,
node->lvalues.at( i ),
lvalues.at( i ),
peek( rvalues, i )
);
}
// Pop rvalues.
std::vector< yssa_opinst* > values;
values.resize( node->lvalues.size() );
pop( rvalues, (int)node->lvalues.size(), values.data() );
// Pop lvalues.
for ( size_t i = node->lvalues.size(); i-- > 0; )
{
pop_lvalue( node->lvalues.at( i ), lvalues.at( i ) );
}
// Push correct number of values back.
assert( value_count <= (int)node->lvalues.size() );
for ( int i = 0; i < value_count; ++i )
{
push_op( values.at( i ) );
}
return value_count;
}
else
{
// Push each lvalue.
std::vector< size_t > lvalues;
lvalues.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = push_lvalue( node->lvalues.at( i ) );
lvalues.push_back( lvalue );
}
// Evaluate each lvalue.
size_t evalues = stack.size();
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = lvalues.at( i );
push_evalue( node->lvalues.at( i ), lvalue );
}
assert( stack.size() == evalues + node->lvalues.size() );
// Evaluate rvalue list.
size_t rvalues = push( node->rvalues, (int)node->lvalues.size() );
// Perform assignment operations and assignments.
size_t ovalues = stack.size();
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
// Push operands.
size_t operands = push_op( peek( evalues, i ) );
push_op( peek( rvalues, i ) );
// Perform assignment.
yssa_opinst* o = assign_op( node->sloc, node->assignop, operands );
o = assign_lvalue
(
node->sloc,
node->lvalues.at( i ),
lvalues.at( i ),
o
);
push_op( o );
}
assert( stack.size() == ovalues + node->lvalues.size() );
// Pop values.
std::vector< yssa_opinst* > values;
values.resize( node->lvalues.size() );
pop( ovalues, (int)node->lvalues.size(), values.data() );
// Pop rvalues.
std::vector< yssa_opinst* > poprv;
poprv.resize( node->lvalues.size() );
pop( rvalues, (int)node->lvalues.size(), poprv.data() );
// Pop lvalues.
for ( size_t i = node->lvalues.size(); i-- > 0; )
{
pop_lvalue( node->lvalues.at( i ), lvalues.at( i ) );
}
// Push correct number of values back.
assert( value_count <= (int)node->lvalues.size() );
for ( int i = 0; i < value_count; ++i )
{
push_op( values.at( i ) );
}
return value_count;
}
}
/*
Control flow.
*/
yssa_block* yssa_builder::make_block( unsigned flags )
{
function->blocks.emplace_back( new yssa_block( flags ) );
return function->blocks.back().get();
}
yssa_block* yssa_builder::next_block( unsigned flags )
{
yssa_block* next = make_block( flags );
if ( block )
{
link_block( block, NEXT, next );
}
return next;
}
yssa_block* yssa_builder::fail_block( unsigned flags )
{
yssa_block* fail = make_block( flags );
if ( block )
{
link_block( block, FAIL, fail );
}
return fail;
}
yssa_block* yssa_builder::label_block( unsigned flags )
{
/*
Create the next block as the target of a jump.
*/
if ( block && block->ops.empty() )
{
// Current block is empty, so can link to it directly.
return block;
}
else
{
// Return next block.
return next_block( flags );
}
}
void yssa_builder::link_block( yssa_block* prev, link_kind kind, yssa_block* next )
{
switch ( kind )
{
case NEXT:
assert( prev->next == nullptr );
prev->next = next;
next->prev.push_back( prev );
break;
case FAIL:
assert( prev->fail == nullptr );
prev->fail = next;
next->prev.push_back( prev );
break;
default:
assert( ! "unknown link kind" );
break;
}
}
/*
Emitting instructions.
*/
yssa_opinst* yssa_builder::make_op(
int sloc, uint8_t opcode, uint8_t operand_count, uint8_t result_count )
{
// Allocate op from memory region.
void* p = module->alloc.malloc(
sizeof( yssa_opinst ) + sizeof( yssa_opinst* ) * operand_count );
return new ( p ) yssa_opinst( sloc, opcode, operand_count, result_count );
}
yssa_opinst* yssa_builder::op(
int sloc, uint8_t opcode, uint8_t operand_count, uint8_t result_count )
{
// Create op and add to current block.
yssa_opinst* op = make_op( sloc, opcode, operand_count, result_count );
if ( block )
{
block->ops.push_back( op );
}
return op;
}
yssa_opinst* yssa_builder::assign_op(
int sloc, yl_ast_opkind opkind, size_t operands )
{
uint8_t opcode = YL_NOP;
switch ( opkind )
{
case YL_ASTOP_MULASSIGN: opcode = YL_MUL; break;
case YL_ASTOP_DIVASSIGN: opcode = YL_DIV; break;
case YL_ASTOP_MODASSIGN: opcode = YL_MOD; break;
case YL_ASTOP_INTDIVASSIGN: opcode = YL_INTDIV; break;
case YL_ASTOP_ADDASSIGN: opcode = YL_ADD; break;
case YL_ASTOP_SUBASSIGN: opcode = YL_SUB; break;
case YL_ASTOP_LSHIFTASSIGN: opcode = YL_LSL; break;
case YL_ASTOP_LRSHIFTASSIGN: opcode = YL_LSR; break;
case YL_ASTOP_ARSHIFTASSIGN: opcode = YL_ASR; break;
case YL_ASTOP_BITANDASSIGN: opcode = YL_BITAND; break;
case YL_ASTOP_BITXORASSIGN: opcode = YL_BITXOR; break;
case YL_ASTOP_BITORASSIGN: opcode = YL_BITOR; break;
default:
assert( ! "unexpected compound assignment operator" );
break;
}
yssa_opinst* o = op( sloc, opcode, 2, 1 );
pop( operands, 2, o->operand );
return o;
}
/*
Definitions and lookups.
*/
yssa_variable* yssa_builder::variable( yl_ast_name* name )
{
auto i = variables.find( name );
if ( i != variables.end() )
{
return i->second;
}
yssa_variable* v = new ( module->alloc ) yssa_variable();
v->name = module->alloc.strdup( name->name );
v->sloc = name->sloc;
v->xcref = false; // Not (yet) referenced from an exception handler.
v->localup = name->upval ? localups.size() : yl_opinst::NOVAL;
v->r = 0;
variables.emplace( name, v );
return v;
}
yssa_variable* yssa_builder::varobj( yl_new_object* object )
{
auto i = variables.find( object );
if ( i != variables.end() )
{
return i->second;
}
yssa_variable* v = new ( module->alloc ) yssa_variable();
v->name = "[object]";
v->sloc = object->sloc;
v->xcref = false; // Not (yet) referenced from an exception handler.
v->localup = object->upval ? localups.size() : yl_opinst::NOVAL;
v->r = 0;
variables.emplace( object, v );
return v;
}
yssa_variable* yssa_builder::temporary( const char* name, int sloc )
{
yssa_variable* v = new ( module->alloc ) yssa_variable();
v->name = name;
v->sloc = sloc;
v->xcref = false; // You know by now!
v->localup = false; // No way to refer to this variable in inner scope.
v->r = 0;
return v;
}
yssa_opinst* yssa_builder::declare(
int sloc, yssa_variable* variable, yssa_opinst* value )
{
// Upvals exist from their declaration to the end of the closing scope.
if ( variable->localup != yl_opinst::NOVAL )
{
localups.push_back( variable );
}
// Otherwise acts like an ordinary assignment.
return assign( sloc, variable, value );
}
yssa_opinst* yssa_builder::assign(
int sloc, yssa_variable* variable, yssa_opinst* value )
{
if ( value->variable )
{
// The definition was already a definition of another variable.
// One op can't define two variables, so the new definition is
// a move from the previous one.
yssa_opinst* move = op( sloc, YL_MOV, 1, 1 );
move->operand[ 0 ] = value;
value = move;
}
// This op is a definition of the variable.
value->variable = variable;
// Record the definition as the latest definition in the current block.
if ( block )
{
block->definitions[ variable ] = value;
}
return value;
}
/*
Some inspiration taken from:
Simple and Efficient Construction of Static Single Assignment Form
Braun, Sebastian Buchwald, et al.
http://www.cdl.uni-saarland.de/papers/bbhlmz13cc.pdf
*/
/*
When a variable is referenced, we must find the definition that reaches
the point of the reference. We search predecessor blocks recursively,
adding phi functions as necessary. If we reach a block with no ancestors
without finding a definition then the variable is undefined (this is
an error). If we reach a block we have already visited, then the
definition found on that path is the same definition that reaches the
already-visited block.
*/
static yssa_opinst* YSSA_UNDEF = (yssa_opinst*)-1;
static yssa_opinst* YSSA_SELF = (yssa_opinst*)-2;
yssa_opinst* yssa_builder::lookup( yssa_variable* variable )
{
// Lookup the variable.
if ( block )
{
return lookup_block( block, variable );
}
else
{
return nullptr;
}
}
yssa_opinst* yssa_builder::lookup_block(
yssa_block* block, yssa_variable* variable )
{
// Check for a local definition.
auto i = block->definitions.find( variable );
if ( i != block->definitions.end() )
{
return i->second;
}
// Check if we have visited this block already on our search.
if ( block->flags & YSSA_LOOKUP )
{
return YSSA_SELF;
}
// If it's an unsealed block, then we can't proceed, add an incomplete phi.
if ( block->flags & YSSA_UNSEALED )
{
yssa_opinst* incomplete = make_op( -1, YSSA_REF, 1, 1 );
incomplete->variable = variable;
block->phi.push_back( incomplete );
block->definitions.emplace( variable, incomplete );
return incomplete;
}
else
{
yssa_opinst* phi = lookup_seal( block, variable );
assert( phi != YSSA_UNDEF );
assert( phi != YSSA_SELF );
block->phi.push_back( phi );
return phi;
}
}
yssa_opinst* yssa_builder::lookup_seal(
yssa_block* block, yssa_variable* variable )
{
assert( !( block->flags & YSSA_UNSEALED ) );
// If the variable is live in an exception handler block, mark it.
if ( block->flags & YSSA_XCHANDLER )
{
variable->xcref = true;
// If it has no predecessors then the only way to enter
// this block is with an exception. Use YSSA_VAR to indicate
// that the current value of the variable should be used.
if ( block->prev.empty() )
{
yssa_opinst* var = make_op( -1, YSSA_VAR, 0, 1 );
var->variable = variable;
block->phi.push_back( var );
block->definitions.emplace( variable, var );
return var;
}
// Otherwise there should be at least one definition of the
// variable reaching this block.
}
// If the block has no predecessors then the name is undefined.
if ( block->prev.empty() )
{
return YSSA_UNDEF;
}
// Mark this block to prevent infinite recursion in lookups.
block->flags |= YSSA_LOOKUP;
// If there is only one predecessor then continue search.
if ( block->prev.size() == 1 )
{
yssa_opinst* def = lookup_block( block->prev.at( 0 ), variable );
block->flags &= ~YSSA_LOOKUP;
return def;
}
// Find which definition reaches each incoming edge.
yssa_opinst* sole_def = YSSA_SELF;
std::vector< yssa_opinst* > defs;
defs.reserve( block->prev.size() );
for ( size_t i = 0; i < block->prev.size(); ++i )
{
yssa_opinst* def = lookup_block( block->prev.at( i ), variable );
// If any definition is undefined, so is the entire thing.
if ( def == YSSA_UNDEF )
{
block->flags &= ~YSSA_LOOKUP;
return YSSA_UNDEF;
}
// If all of the defs are the same, or YSSA_SELF, then that's the
// sole definition which reaches this point.
if ( sole_def == YSSA_SELF )
{
sole_def = def;
}
if ( sole_def != def )
{
sole_def = nullptr;
}
// Add to the list of definitions.
defs.push_back( def );
}
// Done with lookups.
block->flags &= ~YSSA_LOOKUP;
// Return sole def if the phi-function collapsed.
if ( sole_def == YSSA_SELF )
{
return YSSA_UNDEF;
}
if ( sole_def )
{
return sole_def;
}
// Create phi function.
yssa_opinst* phi = make_op( -1, YSSA_PHI, defs.size(), 1 );
for ( size_t i = 0; i < defs.size(); ++i )
{
yssa_opinst* def = defs.at( i );
if ( def != YSSA_SELF )
{
phi->operand[ i ] = def;
}
else
{
phi->operand[ i ] = phi;
}
}
return phi;
}
void yssa_builder::seal_block( yssa_block* block )
{
assert( block->flags & YSSA_UNSEALED );
block->flags &= ~YSSA_UNSEALED;
for ( size_t i = 0; i < block->phi.size(); ++i )
{
yssa_opinst* ref = block->phi.at( i );
assert( ref->opcode == YSSA_REF );
yssa_opinst* phi = lookup_seal( block, ref->variable );
assert( phi != YSSA_UNDEF );
assert( phi != YSSA_SELF );
ref->operand[ 0 ] = phi;
block->phi[ i ] = phi;
}
}
void yssa_builder::call( yssa_opinst* callop )
{
/*
Any call or yield instruction must implicitly reference all active
upvals, and also clobbers them (we can't prove whether or not they
are written to by the function being called), so any references to
them that are on the virtual stack must be replaced with temporaries.
*/
// Add implicit reference to all active upvals (since they could be
// referenced by anything in the function).
if ( localups.size() )
{
yssa_opinst* o = op( callop->sloc, YSSA_IMPLICIT, localups.size(), 0 );
o->associated = callop;
for ( size_t i = 0; i < localups.size(); ++i )
{
yssa_variable* localup = localups.at( i );
o->operand[ i ] = lookup( localup );
}
}
// Clobber all local upvals (since they could be written by anything
// in the function).
for ( size_t i = 0; i < localups.size(); ++i )
{
clobber( localups.at( i ) );
}
}
void yssa_builder::clobber( yssa_variable* v )
{
/*
Something (potentially) changed the value of v with a new definition.
Any definition of v which is on the stack must be replaced with an
explicit load, at the point where the value was pushed, to ensure that
no two definitions of the same variable are live at the same time.
*/
yssa_opinst* load = nullptr;
yssa_opinst* load_value = nullptr;
stack_entry* load_entry = nullptr;
for ( size_t i = 0; i < stack.size(); ++i )
{
stack_entry& sentry = stack.at( i );
// Locations of other values in the same block will have moved now
// we have inserted a load.
if ( load_entry
&& sentry.block == load_entry->block
&& sentry.index >= load_entry->index )
{
sentry.index += 1;
}
if ( sentry.value->variable != v )
{
continue;
}
// Potentially create load. The oldest copy of the variable
// definition will be lowest in the stack.
if ( ! load )
{
// Create load.
void* p = module->alloc.malloc(
sizeof( yssa_opinst ) + sizeof( yssa_opinst* ) * 1 );
load = new ( p ) yssa_opinst( sentry.value->sloc, YL_MOV, 1, 1 );
load->operand[ 0 ] = sentry.value;
// Insert at point where the value was pushed.
sentry.block->ops.insert
(
sentry.block->ops.begin() + sentry.index,
load
);
// Remember this value.
load_value = sentry.value;
load_entry = &sentry;
}
else
{
// All definitions of v at this point should be the same.
assert( sentry.value == load_value );
}
// Replace value on stack with the new temporary.
sentry.value = load;
}
}
/*
Virtual stack.
*/
void yssa_builder::execute( yl_ast_node* statement )
{
int valcount = visit( statement, 0 );
assert( valcount == 0 || valcount == 1 );
assert( multival == nullptr );
if ( valcount == 1 )
{
stack.pop_back();
}
}
size_t yssa_builder::push_all( yl_ast_node* expression, int* count )
{
size_t result = stack.size();
if ( expression )
{
*count = visit( expression, -1 );
}
else
{
*count = 0;
}
return result;
}
size_t yssa_builder::push( yl_ast_node* expression, int count )
{
size_t result = stack.size();
int valcount = visit( expression, count );
assert( valcount <= count || valcount == 1 );
if ( valcount < count )
{
yssa_opinst* o = op( expression->sloc, YL_NULL, 0, 1 );
for ( int i = valcount; i < count; ++i )
{
push_op( o );
}
}
else if ( valcount > count )
{
assert( count == 0 );
assert( valcount == 1 );
stack.pop_back();
}
assert( stack.size() == result + count );
return result;
}
size_t yssa_builder::push_op( yssa_opinst* o )
{
/*
Don't do the following things between creating an op and pushing it:
- Pushing an expression.
- Assign to variable.
- Notify a call.
We track the block location where each op is pushed, so if we need
to insert a temporary to replace it, the temporary is created at the
point where the op was pushed, not where it is used.
*/
size_t result = stack.size();
stack_entry sentry;
sentry.block = block;
sentry.index = block ? block->ops.size() : 0;
sentry.value = o;
stack.push_back( sentry );
return result;
}
int yssa_builder::push_select( int sloc, yssa_opinst* selop, int count )
{
if ( count == -1 )
{
multival = selop;
return 0;
}
else if ( count == 1 )
{
push_op( selop );
return 1;
}
else
{
for ( int i = 0; i < count; ++i )
{
yssa_opinst* o = op( sloc, YSSA_SELECT, 1, 1 );
o->operand[ 0 ] = selop;
o->select = i;
push_op( o );
}
return count;
}
}
void yssa_builder::pop( size_t index, int count, yssa_opinst** ops )
{
assert( index + count == stack.size() );
for ( int i = 0; i < count; ++i )
{
ops[ i ] = stack.at( index + i ).value;
}
stack.erase( stack.begin() + index, stack.begin() + index + count );
}
yssa_opinst* yssa_builder::peek( size_t index, size_t i )
{
assert( index + i < stack.size() );
return stack.at( index + i ).value;
}
size_t yssa_builder::push_lvalue( yl_ast_node* lvalue )
{
size_t result;
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
case YL_EXPR_GLOBAL:
case YL_EXPR_UPREF:
{
// Don't push anything.
result = stack.size();
break;
}
case YL_EXPR_KEY:
{
// Just the object.
yl_expr_key* keyexpr = (yl_expr_key*)lvalue;
result = push( keyexpr->object, 1 );
break;
}
case YL_EXPR_INKEY:
{
// Object and key.
yl_expr_inkey* inkey = (yl_expr_inkey*)lvalue;
result = push( inkey->object, 1 );
push( inkey->key, 1 );
break;
}
case YL_EXPR_INDEX:
{
// Object and index.
yl_expr_index* index = (yl_expr_index*)lvalue;
result = push( index->object, 1 );
push( index->index, 1 );
break;
}
default:
assert( ! "invalid lvalue" );
break;
}
return result;
}
size_t yssa_builder::push_evalue( yl_ast_node* lvalue, size_t index )
{
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
{
yl_expr_local* local = (yl_expr_local*)lvalue;
yssa_variable* v = variable( local->name );
return push_op( lookup( v ) );
}
case YL_EXPR_GLOBAL:
{
yl_expr_global* global = (yl_expr_global*)lvalue;
yssa_opinst* o = op( global->sloc, YL_GLOBAL, 0, 1 );
o->key = module->alloc.strdup( global->name );
return push_op( o );
}
case YL_EXPR_UPREF:
{
yl_expr_upref* upref = (yl_expr_upref*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_GETUP, 0, 1 );
o->a = upref->index;
return push_op( o );
}
case YL_EXPR_KEY:
{
yl_expr_key* keyexpr = (yl_expr_key*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_KEY, 1, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->key = module->alloc.strdup( keyexpr->key );
return push_op( o );
}
case YL_EXPR_INKEY:
{
yssa_opinst* o = op( lvalue->sloc, YL_INKEY, 2, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
return push_op( o );
}
case YL_EXPR_INDEX:
{
yssa_opinst* o = op( lvalue->sloc, YL_INDEX, 2, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
return push_op( o );
}
default:
{
assert( ! "invalid lvalue" );
yssa_opinst* o = op( lvalue->sloc, YL_NULL, 0, 1 );
return push_op( o );
}
}
}
yssa_opinst* yssa_builder::assign_lvalue(
int sloc, yl_ast_node* lvalue, size_t index, yssa_opinst* value )
{
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
{
yl_expr_local* local = (yl_expr_local*)lvalue;
yssa_variable* v = variable( local->name );
return assign( sloc, v, value );
}
case YL_EXPR_GLOBAL:
{
yl_expr_global* global = (yl_expr_global*)lvalue;
yssa_opinst* o = op( global->sloc, YL_SETGLOBAL, 1, 0 );
o->operand[ 0 ] = value;
o->key = module->alloc.strdup( global->name );
return value;
}
case YL_EXPR_UPREF:
{
yl_expr_upref* upref = (yl_expr_upref*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_SETUP, 1, 0 );
o->operand[ 0 ] = value;
o->a = upref->index;
return value;
}
case YL_EXPR_KEY:
{
yl_expr_key* keyexpr = (yl_expr_key*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_SETKEY, 2, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = value;
o->key = module->alloc.strdup( keyexpr->key );
return value;
}
case YL_EXPR_INKEY:
{
yssa_opinst* o = op( lvalue->sloc, YL_SETINKEY, 3, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
o->operand[ 2 ] = value;
return value;
}
case YL_EXPR_INDEX:
{
yssa_opinst* o = op( lvalue->sloc, YL_SETINDEX, 3, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
o->operand[ 2 ] = value;
return value;
}
default:
assert( ! "invalid lvalue" );
return value;
}
}
void yssa_builder::pop_lvalue( yl_ast_node* lvalue, size_t index )
{
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
case YL_EXPR_GLOBAL:
case YL_EXPR_UPREF:
{
break;
}
case YL_EXPR_KEY:
{
// Just the object.
yssa_opinst* value = nullptr;
pop( index, 1, &value );
break;
}
case YL_EXPR_INKEY:
{
// Object and key.
yssa_opinst* values[ 2 ] = { nullptr, nullptr };
pop( index, 2, values );
break;
}
case YL_EXPR_INDEX:
{
// Object and index.
yssa_opinst* values[ 2 ] = { nullptr, nullptr };
pop( index, 2, values );
break;
}
default:
assert( ! "invalid lvalue" );
break;
}
}
/*
Scope stack.
*/
void yssa_builder::open_scope( yl_ast_scope* scope, yssa_block* xchandler )
{
scope_entry s;
s.scope = scope;
s.localups = localups.size();
s.itercount = itercount;
if ( xchandler )
s.xchandler = xchandler;
else if ( scopes.size() )
s.xchandler = scopes.back().xchandler;
else
s.xchandler = nullptr;
scopes.push_back( s );
}
void yssa_builder::close_scope( int sloc, yl_ast_scope* scope )
{
const scope_entry& s = scopes.back();
assert( s.scope == scope );
// Close.
close( sloc, s.localups, s.itercount );
// Pop upvals and reset iterators.
assert( s.localups <= localups.size() );
assert( s.itercount <= itercount );
localups.resize( s.localups );
itercount = s.itercount;
scopes.pop_back();
}
yssa_builder::break_entry* yssa_builder::open_break(
yl_ast_scope* scope, break_kind kind )
{
// Create break entry.
std::unique_ptr< break_entry > b = std::make_unique< break_entry >();
b->scope = scope;
b->kind = kind;
b->localups = localups.size();
b->itercount = itercount;
// Add break entry to map.
break_entry* bentry = b.get();
breaks.emplace( break_key( scope, kind ), std::move( b ) );
return bentry;
}
void yssa_builder::close_break( break_entry* b, yssa_block* target )
{
if ( target )
{
for ( size_t i = 0; i < b->blocks.size(); ++i )
{
yssa_block* break_block = b->blocks.at( i );
assert( break_block );
link_block( break_block, NEXT, target );
}
}
breaks.erase( break_key( b->scope, b->kind ) );
}
void yssa_builder::close( int sloc, size_t closeups, size_t closeiter )
{
// Don't need to do anything if there's nothing to close.
if ( closeups == localups.size() && closeiter == itercount )
{
return;
}
assert( closeups <= localups.size() );
assert( closeiter <= itercount );
// Otherwise, close everything relevant.
size_t close_count = localups.size() - closeups;
yssa_opinst* o = op( sloc, YL_CLOSE, close_count, 0 );
o->a = closeups;
o->b = closeiter;
for ( size_t i = 0; i < close_count; ++i )
{
o->operand[ i ] = lookup( localups.at( closeups + i ) );
}
}
add the scope containing the function's parameter declarations
//
// yssa_builder.cpp
//
// Created by Edmund Kapusniak on 05/03/2015.
// Copyright (c) 2015 Edmund Kapusniak. All rights reserved.
//
#include "yssa_builder.h"
#include <make_unique.h>
#include "yl_code.h"
yssa_builder::yssa_builder( yl_diagnostics* diagnostics )
: diagnostics( diagnostics )
, module( std::make_unique< yssa_module >() )
{
}
yssa_builder::~yssa_builder()
{
}
bool yssa_builder::build( yl_ast* ast )
{
// Construct each function.
for ( size_t i = 0; i < ast->functions.size(); ++i )
{
yl_ast_func* astf = ast->functions.at( i );
yssa_function_p ssaf = std::make_unique< yssa_function >
(
astf->sloc,
module->alloc.strdup( astf->funcname )
);
funcmap.emplace( std::make_pair( astf, ssaf.get() ) );
module->functions.push_back( std::move( ssaf ) );
}
// Build SSA for each function.
for ( size_t i = 0; i < ast->functions.size(); ++i )
{
yl_ast_func* astf = ast->functions.at( i );
build( astf );
}
return diagnostics->error_count() == 0;
}
yssa_module_p yssa_builder::get_module()
{
return std::move( module );
}
void yssa_builder::build( yl_ast_func* astf )
{
function = funcmap.at( astf );
assert( stack.empty() );
assert( scopes.empty() );
assert( localups.empty() );
assert( itercount == 0 );
// Create entry block.
yssa_block_p entry_block = std::make_unique< yssa_block >();
block = entry_block.get();
function->blocks.push_back( std::move( entry_block ) );
// Enter scope.
open_scope( astf->scope );
// Add parameter ops.
for ( size_t i = 0; i < astf->parameters.size(); ++i )
{
yl_ast_name* param = astf->parameters.at( i );
yssa_opinst* o = op( param->sloc, YSSA_PARAM, 0, 1 );
o->select = (int)i;
declare( param->sloc, variable( param ), o );
}
// Visit the block.
visit( astf->block, 0 );
// Close scope.
close_scope( astf->sloc, astf->scope );
assert( stack.empty() );
assert( scopes.empty() );
assert( localups.empty() );
assert( itercount == 0 );
}
int yssa_builder::fallback( yl_ast_node* node, int count )
{
assert( ! "invalid AST node" );
return 0;
}
int yssa_builder::visit( yl_stmt_block* node, int count )
{
/*
statements
close upvals
*/
if ( node->scope )
{
open_scope( node->scope );
}
for ( size_t i = 0; i < node->stmts.size(); ++i )
{
execute( node->stmts.at( i ) );
}
if ( node->scope )
{
close_scope( node->sloc, node->scope );
}
return 0;
}
int yssa_builder::visit( yl_stmt_if* node, int count )
{
/*
condition
? goto iftrue : goto iffalse
iftrue:
...
goto final
iffalse:
...
goto final
final:
close upvals
*/
open_scope( node->scope );
// Check if condition.
size_t operand = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
yssa_block* test_next = block;
yssa_block* test_fail = block;
// True branch.
if ( node->iftrue )
{
if ( test_next )
{
block = test_next;
block = next_block();
test_next = nullptr;
}
execute( node->iftrue );
}
yssa_block* true_block = block;
// False branch.
if ( node->iffalse )
{
if ( test_fail )
{
block = test_fail;
block = fail_block();
test_fail = nullptr;
}
execute( node->iffalse );
}
yssa_block* false_block = block;
// Final block.
if ( test_next || test_fail || true_block || false_block )
{
block = label_block();
assert( block );
if ( test_next )
{
link_block( test_next, NEXT, block );
}
if ( test_fail )
{
link_block( test_fail, FAIL, block );
}
if ( true_block )
{
link_block( true_block, NEXT, block );
}
if ( false_block )
{
link_block( false_block, NEXT, block );
}
}
close_scope( node->sloc, node->scope );
return 0;
}
int yssa_builder::visit( yl_stmt_switch* node, int count )
{
/*
eval value
eval case0value
if ( equal ) goto case0
eval case1value
if ( equal ) goto case1
goto default
case0:
statements
case1:
default:
statements
break:
close upvals
*/
open_scope( node->scope );
// Push the switch value.
size_t operands = push( node->value, 1 );
// Construct the dispatch table.
std::unordered_map< yl_stmt_case*, yssa_block* > case_gotos;
for ( size_t i = 0; i < node->body->stmts.size(); ++i )
{
// Find case statements.
yl_ast_node* stmt = node->body->stmts.at( i );
if ( stmt->kind != YL_STMT_CASE )
continue;
yl_stmt_case* cstmt = (yl_stmt_case*)stmt;
// Ignore the default case.
if ( ! cstmt->value )
continue;
// Open block.
if ( block && case_gotos.size() )
{
block = fail_block();
}
// Push the case value.
push( cstmt->value, 1 );
// Perform comparison.
yssa_opinst* o = op( cstmt->sloc, YL_EQ, 2, 1 );
pop( operands, 2, o->operand );
// Move to next comparison (if test fails).
if ( block )
{
assert( block->test == nullptr );
block->test = o;
}
case_gotos.emplace( cstmt, block );
// Repush switch value.
operands = push_op( o->operand[ 0 ] );
}
// Pop value.
yssa_opinst* value = nullptr;
pop( operands, 1, &value );
// If execution gets here then all tests have failed.
yssa_block* default_goto = block;
block = nullptr;
// Break to end of switch.
break_entry* sbreak = open_break( node->scope, BREAK );
// Evaluate actual case blocks.
for ( size_t i = 0; i < node->body->stmts.size(); ++i )
{
yl_ast_node* stmt = node->body->stmts.at( i );
if ( stmt->kind == YL_STMT_CASE )
{
yl_stmt_case* cstmt = (yl_stmt_case*)stmt;
// Work out which block to link.
yssa_block* jump_block = nullptr;
link_kind jump_link = NEXT;
if ( cstmt->value )
{
jump_block = case_gotos.at( cstmt );
jump_link = NEXT;
}
else
{
jump_block = default_goto;
jump_link = case_gotos.empty() ? NEXT : FAIL;
default_goto = nullptr;
}
if ( ! jump_block )
{
continue;
}
// Make a block to link to.
block = label_block();
// Link it.
assert( block );
link_block( jump_block, jump_link, block );
}
else
{
execute( stmt );
}
}
if ( default_goto || sbreak->blocks.size() )
{
// Make break target.
block = label_block();
assert( block );
// If there was no default case, the default gets here.
if ( default_goto )
{
link_block( default_goto, case_gotos.empty() ? NEXT : FAIL, block );
}
}
// Link break.
close_break( sbreak, block );
// Close scope.
close_scope( node->sloc, node->scope );
return 0;
}
int yssa_builder::visit( yl_stmt_while* node, int count )
{
/*
continue:
test condition
if ( failed ) goto exit:
statements
close upvals
goto continue
exit:
close upvals
break:
*/
// Enter loop.
if ( block )
{
block = next_block( YSSA_LOOP | YSSA_UNSEALED );
}
yssa_block* loop = block;
// Enter scope.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Test condition.
size_t test = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( test, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
yssa_block* test_fail = block;
if ( block )
{
block = next_block();
}
// Remember enough information to construct the close op
// on the exit branch.
assert( scopes.back().scope == node->scope );
assert( scopes.back().itercount == itercount );
std::vector< yssa_variable* > close;
close.insert
(
close.end(),
localups.begin() + scopes.back().localups,
localups.end()
);
// Statements.
execute( node->body );
close_scope( node->sloc, node->scope );
// Link back to top of loop.
close_break( lcontinue, loop );
if ( block && loop )
{
link_block( block, NEXT, loop );
}
block = nullptr;
if ( loop )
{
seal_block( loop );
}
// Fill in failure branch.
if ( test_fail )
{
block = label_block();
link_block( test_fail, FAIL, block );
// Need to close upvals.
if ( close.size() )
{
yssa_opinst* o = op( node->sloc, YL_CLOSE, close.size(), 0 );
o->a = localups.size();
o->b = itercount;
for ( size_t i = 0; i < close.size(); ++i )
{
o->operand[ i ] = lookup( close.at( i ) );
}
}
}
// Fill in breaks.
if ( lbreak->blocks.size() )
{
block = label_block();
}
close_break( lbreak, block );
return 0;
}
int yssa_builder::visit( yl_stmt_do* node, int count )
{
/*
top:
statements
continue:
test
close upvals
if ( succeeded ) goto top
break:
*/
// Enter loop.
if ( block )
{
block = next_block( YSSA_LOOP | YSSA_UNSEALED );
}
yssa_block* loop = block;
// Enter scope.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Statements.
execute( node->body );
// Link continue.
if ( lcontinue->blocks.size() )
{
block = label_block();
}
close_break( lcontinue, block );
// Perform test.
size_t test = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( test, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
// Close scope.
close_scope( node->sloc, node->scope );
// Link the success condition to the top of the loop.
if ( block && loop )
{
link_block( block, NEXT, loop );
}
if ( loop )
{
seal_block( loop );
}
// Failure exits the loop.
if ( block )
{
block = fail_block();
}
close_break( lbreak, block );
return 0;
}
int yssa_builder::visit( yl_stmt_foreach* node, int count )
{
/*
iter/iterkey list
goto entry
continue:
assign/declare iterator values
statements
close upvals
entry:
if ( have values ) goto continue
close iterator
break:
*/
// Open scope that declares the iterator. We break into a scope that
// does not contain the iterator.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
// Push iterator.
size_t operand = push( node->list, 1 );
yl_opcode opcode = node->eachkey ? YL_ITERKEY : YL_ITER;
yssa_opinst* o = op( node->sloc, opcode, 1, 0 );
pop( operand, 1, o->operand );
size_t iterindex = itercount;
o->r = iterindex;
itercount += 1;
// Goto entry.
yssa_block* entry_block = block;
// Declare body scope, for upvals contained in the body. We continue
// into a scope that contains the iterator.
open_scope( node->scope );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Create (unsealed) continue block. This block is not the loop
// header, as it is dominated by the entry block.
block = label_block( YSSA_UNSEALED );
yssa_block* body_block = block;
// Work out which opcode to use to request values.
opcode = YL_NOP;
if ( node->lvalues.size() == 1 )
opcode = YL_NEXT1;
else if ( node->lvalues.size() == 2 )
opcode = YL_NEXT2;
else
opcode = YL_NEXT;
if ( node->declare )
{
// Request correct number of ops from iterator.
yssa_opinst* o = op( node->sloc, opcode, 0, node->lvalues.size() );
o->b = iterindex;
// Declare each variable.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
assert( node->lvalues.at( i )->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)node->lvalues.at( i );
yssa_variable* v = variable( local->name );
if ( opcode == YL_NEXT )
{
declare( node->sloc, v, o );
}
else
{
yssa_opinst* select = op( node->sloc, YSSA_SELECT, 1, 1 );
select->operand[ 0 ] = o;
select->select = (int)i;
declare( node->sloc, v, select );
}
}
}
else
{
// Push each lvalue.
std::vector< size_t > lvalues;
lvalues.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = push_lvalue( node->lvalues.at( i ) );
lvalues.push_back( lvalue );
}
// Request correct number of ops from iterator.
yssa_opinst* o = op( node->sloc, opcode, 0, node->lvalues.size() );
o->b = iterindex;
// Build select ops.
std::vector< yssa_opinst* > selects;
selects.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
if ( opcode == YL_NEXT )
{
selects.push_back( o );
}
else
{
yssa_opinst* select = op( node->sloc, YSSA_SELECT, 1, 1 );
select->operand[ 0 ] = o;
select->select = (int)i;
selects.push_back( select );
}
}
// Assign each variable.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
yssa_opinst* o = selects.at( i );
assign_lvalue
(
node->sloc,
node->lvalues.at( i ),
lvalues.at( i ),
o
);
}
// Pop lvalues.
for ( size_t i = node->lvalues.size(); i-- > 0; )
{
pop_lvalue( node->lvalues.at( i ), lvalues.at( i ) );
}
}
// Perform statements.
execute( node->body );
// Exit upval scope.
close_scope( node->sloc, node->scope );
// Loop entry block.
if ( block || entry_block )
{
block = label_block( YSSA_LOOP );
assert( block );
if ( entry_block )
{
link_block( entry_block, NEXT, block );
}
}
// Perform loop check.
o = op( node->sloc, YSSA_ITERDONE, 0, 0 );
o->b = iterindex;
if ( block )
{
assert( block->test == nullptr );
block->test = o;
}
// Link continue.
close_break( lcontinue, body_block );
if ( body_block )
{
seal_block( body_block );
}
// Exit iterator scope.
close_scope( node->sloc, node->scope );
// Link break.
if ( lbreak->blocks.size() )
{
block = label_block();
}
close_break( lbreak, block );
return 0;
}
int yssa_builder::visit( yl_stmt_for* node, int count )
{
/*
init
top:
condition
if ( failed ) goto break:
statements
continue:
update
goto top
break:
close upvals
*/
// Scope of for init/condition/update covers all iterations of loop.
open_scope( node->scope );
break_entry* lbreak = open_break( node->scope, BREAK );
break_entry* lcontinue = open_break( node->scope, CONTINUE );
// Init.
if ( node->init )
{
execute( node->init );
}
// Loop.
if ( block )
{
block = next_block( YSSA_LOOP | YSSA_UNSEALED );
}
yssa_block* loop = block;
// Condition.
yssa_block* test_fail = nullptr;
if ( node->condition )
{
size_t test = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( test, 1, &value );
if ( block )
{
assert( block->test == nullptr );
block->test = value;
}
test_fail = block;
if ( block )
{
block = next_block();
}
}
// Body. A for body should have its own scope to declare upvals in.
execute( node->body );
// Continue location.
if ( lcontinue->blocks.size() )
{
block = label_block();
}
close_break( lcontinue, block );
if ( node->update )
{
execute( node->update );
}
if ( block && loop )
{
link_block( block, NEXT, loop );
}
if ( loop )
{
seal_block( loop );
}
block = nullptr;
// Break location.
if ( test_fail || lbreak->blocks.size() )
{
block = label_block();
assert( block );
if ( test_fail )
{
link_block( test_fail, FAIL, block );
}
}
close_break( lbreak, block );
// Close scope.
close_scope( node->sloc, node->scope );
return 0;
}
int yssa_builder::visit( yl_stmt_using* node, int count )
{
/*
o0.acquire();
[
o1.acquire();
[
using block
]
o1.release();
unwind
]
o0.release();
unwind
*/
// Call o.acquire().
int valcount = 0;
size_t uvalues = push_all( node->uvalue, &valcount );
// Using does support multiple values (more fool me).
std::vector< yssa_block_p > xchandlers;
for ( int i = 0; i < valcount; ++i )
{
// Call acquire().
yssa_opinst* m = op( node->sloc, YL_KEY, 1, 1 );
m->operand[ 0 ] = peek( uvalues, i );
m->key = "acquire";
yssa_opinst* c = op( node->sloc, YL_CALL, 2, 0 );
c->operand[ 0 ] = m;
c->operand[ 1 ] = peek( uvalues, i );
call( c );
// Open protected context.
yssa_block_p xchandler =
std::make_unique< yssa_block >( YSSA_XCHANDLER );
xchandler->unwind_localups = localups.size();
xchandler->unwind_itercount = itercount;
xchandler->xchandler =
scopes.size() ? scopes.back().xchandler : nullptr;
open_scope( node->scope, xchandler.get() );
xchandlers.push_back( std::move( xchandler ) );
if ( block )
{
block = next_block();
assert( block->xchandler == xchandlers.back().get() );
}
}
// Using block. Leave all the uvalues on the stack - there's
// only one definition of each.
execute( node->body );
// Close each scope and implement handler.
for ( int i = valcount; i-- > 0; )
{
// Leave protected context.
close_scope( node->sloc, node->scope );
// Handler is next block.
yssa_block* xchandler = xchandlers.at( i ).get();
function->blocks.push_back( std::move( xchandlers.at( i ) ) );
if ( block )
{
link_block( block, NEXT, xchandler );
block = xchandler;
}
// Call release().
yssa_opinst* m = op( node->sloc, YL_KEY, 1, 1 );
m->operand[ 0 ] = peek( uvalues, i );
m->key = "release";
yssa_opinst* c = op( node->sloc, YL_CALL, 2, 0 );
c->operand[ 0 ] = m;
c->operand[ 1 ] = peek( uvalues, i );
call( c );
// Continue potential exception unwind.
op( node->sloc, YL_UNWIND, 0, 0 );
// Pop uvalue.
yssa_opinst* value = nullptr;
pop( uvalues + i, 1, &value );
}
return 0;
}
int yssa_builder::visit( yl_stmt_try* node, int count )
{
/*
[
[
tstmt
goto finally
]
catch:
filter
if ( failed ) goto next_catch
catch
goto finally
next_catch:
filter
if ( failed ) goto finally
catch
goto finally
]
finally:
finally statement
unwind
*/
/*
There are two potential protected contexts - one that
passes control to the finally block (which can also be
entered normally), and one that passes control to the
exeption filter chain of catch () statements.
*/
yssa_block_p xcfinally = nullptr;
yssa_block_p xccatch = nullptr;
if ( node->fstmt )
{
xcfinally = std::make_unique< yssa_block >( YSSA_XCHANDLER );
xcfinally->unwind_localups = localups.size();
xcfinally->unwind_itercount = itercount;
xcfinally->xchandler =
scopes.size() ? scopes.back().xchandler : nullptr;
open_scope( nullptr, xcfinally.get() );
}
if ( node->clist.size() )
{
xccatch = std::make_unique< yssa_block >( YSSA_XCHANDLER );
xccatch->unwind_localups = localups.size();
xccatch->unwind_itercount = itercount;
xccatch->xchandler =
scopes.size() ? scopes.back().xchandler : nullptr;
open_scope( nullptr, xccatch.get() );
}
if ( block && ( node->fstmt || node->clist.size() ) )
{
block = next_block();
assert( block->xchandler );
}
execute( node->tstmt );
// Construct exception filter from the catch clauses.
yssa_block* catch_jump = nullptr;
std::vector< yssa_block* > finally_jumps;
if ( node->clist.size() )
{
close_scope( node->sloc, nullptr );
if ( block )
{
finally_jumps.push_back( block );
block = nullptr;
}
// Enter handler block for catch.
block = xccatch.get();
function->blocks.push_back( std::move( xccatch ) );
// If the catch failed, go to the next one.
for ( size_t i = 0; i < node->clist.size(); ++i )
{
assert( node->clist.at( i )->kind == YL_STMT_CATCH );
yl_stmt_catch* cstmt = (yl_stmt_catch*)node->clist.at( i );
// Link from previous failed catch filter expression.
if ( catch_jump )
{
block = label_block();
link_block( catch_jump, FAIL, block );
}
// Get exception.
yssa_opinst* e = nullptr;
if ( cstmt->proto || cstmt->lvalue )
{
e = op( cstmt->sloc, YL_EXCEPT, 0, 1 );
}
// Test catch filter.
if ( cstmt->proto )
{
size_t operands = push_op( e );
push( cstmt->proto, 1 );
yssa_opinst* o = op( cstmt->sloc, YL_IS, 2, 1 );
pop( operands, 2, o->operand );
if ( block )
{
assert( block->test == nullptr );
block->test = o;
catch_jump = block;
block = next_block();
}
}
// Catch block for when test passes.
open_scope( cstmt->scope );
// Make exception assignment.
if ( cstmt->lvalue && cstmt->declare )
{
assert( cstmt->lvalue->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)cstmt->lvalue;
yssa_variable* v = variable( local->name );
declare( cstmt->sloc, v, e );
}
else if ( cstmt->lvalue )
{
size_t lvalue = push_lvalue( cstmt->lvalue );
assign_lvalue( cstmt->sloc, cstmt->lvalue, lvalue, e );
pop_lvalue( cstmt->lvalue, lvalue );
}
execute( cstmt->body );
close_scope( node->sloc, cstmt->scope );
if ( block )
{
finally_jumps.push_back( block );
block = nullptr;
}
}
}
if ( node->fstmt )
{
close_scope( node->sloc, nullptr );
if ( block )
{
finally_jumps.push_back( block );
block = nullptr;
}
block = xcfinally.get();
function->blocks.push_back( std::move( xcfinally ) );
}
else if ( catch_jump || finally_jumps.size() )
{
block = label_block();
}
if ( catch_jump )
{
link_block( catch_jump, FAIL, block );
}
for ( size_t i = 0; i < finally_jumps.size(); ++i )
{
link_block( finally_jumps.at( i ), NEXT, block );
}
if ( node->fstmt )
{
execute( node->fstmt );
op( node->sloc, YL_UNWIND, 0, 0 );
}
return 0;
}
int yssa_builder::visit( yl_stmt_catch* node, int count )
{
assert( ! "catch outside try" );
return 0;
}
int yssa_builder::visit( yl_stmt_delete* node, int count )
{
for ( size_t i = 0; i < node->delvals.size(); ++i )
{
yl_ast_node* delval = node->delvals.at( i );
if ( delval->kind == YL_EXPR_KEY )
{
yl_expr_key* expr = (yl_expr_key*)node;
size_t operand = push( expr->object, 1 );
yssa_opinst* o = op( node->sloc, YL_DELKEY, 1, 0 );
pop( operand, 1, o->operand );
o->key = module->alloc.strdup( expr->key );
}
else if ( delval->kind == YL_EXPR_INKEY )
{
yl_expr_inkey* expr = (yl_expr_inkey*)node;
size_t operands = push( expr->object, 1 );
push( expr->key, 1 );
yssa_opinst* o = op( node->sloc, YL_DELINKEY, 2, 0 );
pop( operands, 2, o->operand );
}
}
return 0;
}
int yssa_builder::visit( yl_stmt_case* node, int count )
{
assert( ! "case outside switch" );
return 0;
}
int yssa_builder::visit( yl_stmt_continue* node, int count )
{
// Get break entry.
auto i = breaks.find( break_key( node->target, CONTINUE ) );
if ( i == breaks.end() )
{
assert( ! "continue outside continuable scope" );
return 0;
}
break_entry* b = i->second.get();
// Close.
close( node->sloc, b->localups, b->itercount );
// This branch terminates at the continue (which should be
// linked when the continuable scope closes).
if ( block )
{
b->blocks.push_back( block );
block = nullptr;
}
return 0;
}
int yssa_builder::visit( yl_stmt_break* node, int count )
{
// Get break entry.
auto i = breaks.find( break_key( node->target, BREAK ) );
if ( i == breaks.end() )
{
assert( "break outside breakable scope" );
return 0;
}
break_entry* b = i->second.get();
// Close.
close( node->sloc, b->localups, b->itercount );
// This branch terminates at the break (which should be
// linked when the breakable scope closes).
if ( block )
{
b->blocks.push_back( block );
block = nullptr;
}
return 0;
}
int yssa_builder::visit( yl_stmt_return* node, int count )
{
// Push return values.
int valcount = 0;
size_t operands = push_all( node->values, &valcount );
// Close everything.
close( node->sloc, 0, 0 );
// Return.
yssa_opinst* o = op( node->sloc, YL_RETURN, valcount, 0 );
pop( operands, valcount, o->operand );
o->multival = multival;
multival = nullptr;
return 0;
}
int yssa_builder::visit( yl_stmt_throw* node, int count )
{
// The stack unwind should take care of closing things.
size_t operand = push( node->value, 1 );
yssa_opinst* o = op( node->sloc, YL_THROW, 1, 0 );
pop( operand, 1, o->operand );
return 0;
}
int yssa_builder::visit( yl_ast_func* node, int count )
{
// Function op.
yssa_function* function = funcmap.at( node );
yssa_opinst* o = op( node->sloc, YL_CLOSURE, 0, 1 );
o->function = function;
// Upval initializers.
for ( size_t i = 0; i < node->upvals.size(); ++i )
{
const yl_ast_upval& uv = node->upvals.at( i );
switch ( uv.kind )
{
case YL_UPVAL_LOCAL:
{
// Make an upval from a local variable.
yssa_variable* v = variable( uv.local );
yssa_opinst* u = op( node->sloc, YL_UPLOCAL, 1, 0 );
u->r = i;
u->associated = o;
u->a = v->localup;
u->operand[ 0 ] = lookup( v );
break;
}
case YL_UPVAL_OBJECT:
{
// Make an upval from a local object under constrution.
yssa_variable* v = varobj( uv.object );
yssa_opinst* u = op( node->sloc, YL_UPLOCAL, 1, 0 );
u->r = i;
u->associated = o;
u->a = v->localup;
u->operand[ 0 ] = lookup( v );
break;
}
case YL_UPVAL_UPVAL:
{
// Make an upval from an existing upval.
yssa_opinst* u = op( node->sloc, YL_UPUPVAL, 0, 0 );
u->r = i;
u->associated = o;
u->a = uv.upval;
break;
}
}
}
// Push onto virtual stack.
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_null* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_NULL, 0, 1 );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_bool* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_BOOL, 0, 1 );
o->a = node->value ? 1 : 0;
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_number* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_NUMBER, 0, 1 );
o->number = node->value;
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_string* node, int count )
{
// Copy string.
char* string = (char*)module->alloc.malloc( node->length + 1 );
memcpy( string, node->string, node->length );
string[ node->length ] = '\0';
// Push value.
yssa_opinst* o = op( node->sloc, YL_STRING, 0, 1 );
o->string = new ( module->alloc ) yssa_string( string, node->length );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_local* node, int count )
{
// Find definition of the variable which reaches this point.
yssa_variable* v = variable( node->name );
push_op( lookup( v ) );
return 1;
}
int yssa_builder::visit( yl_expr_global* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_GLOBAL, 0, 1 );
o->key = module->alloc.strdup( node->name );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_upref* node, int count )
{
yssa_opinst* o = op( node->sloc, YL_GETUP, 0, 1 );
o->a = (uint8_t)node->index;
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_objref* node, int count )
{
// Find definition of object.
yssa_variable* v = varobj( node->object );
push_op( lookup( v ) );
return 1;
}
int yssa_builder::visit( yl_expr_superof* node, int count )
{
size_t operand = push( node->expr, 1 );
yssa_opinst* o = op( node->sloc, YL_SUPER, 1, 1 );
pop( operand, 1, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_key* node, int count )
{
size_t operand = push( node->object, 1 );
yssa_opinst* o = op( node->sloc, YL_KEY, 1, 1 );
pop( operand, 1, o->operand );
o->key = module->alloc.strdup( node->key );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_inkey* node, int count )
{
size_t operands = push( node->object, 1 );
push( node->key, 1 );
yssa_opinst* o = op( node->sloc, YL_INKEY, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_index* node, int count )
{
size_t operands = push( node->object, 1 );
push( node->index, 1 );
yssa_opinst* o = op( node->sloc, YL_INDEX, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_preop* node, int count )
{
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t evalue = push_evalue( node->lvalue, lvalue ); // lv, ev
// perform operation.
yl_opcode opcode = ( node->opkind == YL_ASTOP_PREINC ) ? YL_ADD : YL_SUB;
yssa_opinst* o = op( node->sloc, opcode, 2, 1 );
pop( evalue, 1, o->operand );
o->operand[ 1 ] = op( node->sloc, YL_NUMBER, 0, 1 );
o->operand[ 1 ]->number = 1.0;;
// perform assignment.
o = assign_lvalue( node->sloc, node->lvalue, lvalue, o );
// push updated value onto stack.
pop_lvalue( node->lvalue, lvalue );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_postop* node, int count )
{
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t evalue = push_evalue( node->lvalue, lvalue ); // lv, ev
// perform operation
yl_opcode opcode = ( node->opkind == YL_ASTOP_POSTINC ) ? YL_ADD : YL_SUB;
yssa_opinst* o = op( node->sloc, opcode, 2, 1 );
pop( evalue, 1, o->operand );
o->operand[ 1 ] = op( node->sloc, YL_NUMBER, 0, 1 );
o->operand[ 1 ]->number = 1.0;;
// perform assignment (which might clobber the original value).
size_t ovalue = push_op( o->operand[ 0 ] );
assign_lvalue( node->sloc, node->lvalue, lvalue, o );
// push original value onto stack.
yssa_opinst* value = nullptr;
pop( ovalue, 1, &value );
pop_lvalue( node->lvalue, lvalue );
push_op( value );
return 1;
}
int yssa_builder::visit( yl_expr_unary* node, int count )
{
size_t operand = push( node->operand, 1 );
yl_opcode opcode = YL_NOP;
switch ( node->opkind )
{
case YL_ASTOP_POSITIVE:
{
// Implemented as negative negative.
yssa_opinst* o = op( node->sloc, YL_NEG, 1, 1 );
pop( operand, 1, o->operand );
operand = push_op( o );
opcode = YL_NEG;
break;
}
case YL_ASTOP_NEGATIVE:
opcode = YL_NEG;
break;
case YL_ASTOP_LOGICNOT:
opcode = YL_LNOT;
break;
case YL_ASTOP_BITNOT:
opcode = YL_BITNOT;
break;
default:
assert( ! "invalid unary operator" );
break;
}
yssa_opinst* o = op( node->sloc, opcode, 1, 1 );
pop( operand, 1, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_binary* node, int count )
{
size_t operands = push( node->lhs, 1 );
push( node->rhs, 1 );
yl_opcode opcode = YL_NOP;
switch ( node->opkind )
{
case YL_ASTOP_MULTIPLY:
opcode = YL_MUL;
break;
case YL_ASTOP_DIVIDE:
opcode = YL_DIV;
break;
case YL_ASTOP_MODULUS:
opcode = YL_MOD;
break;
case YL_ASTOP_INTDIV:
opcode = YL_INTDIV;
break;
case YL_ASTOP_ADD:
opcode = YL_ADD;
break;
case YL_ASTOP_SUBTRACT:
opcode = YL_SUB;
break;
case YL_ASTOP_LSHIFT:
opcode = YL_LSL;
break;
case YL_ASTOP_LRSHIFT:
opcode = YL_LSR;
break;
case YL_ASTOP_ARSHIFT:
opcode = YL_ASR;
break;
case YL_ASTOP_BITAND:
opcode = YL_BITAND;
break;
case YL_ASTOP_BITXOR:
opcode = YL_BITXOR;
break;
case YL_ASTOP_BITOR:
opcode = YL_BITOR;
break;
case YL_ASTOP_CONCATENATE:
opcode = YL_CONCAT;
break;
default:
assert( ! "invalid binary operator" );
break;
}
yssa_opinst* o = op( node->sloc, YL_MUL, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
int yssa_builder::visit( yl_expr_compare* node, int count )
{
/*
operand a
operand b
result = comparison
? goto next1 : goto final
next1:
operand c
result = comparison
? goto next2 : goto final
next2:
operand d
result = comparison
goto final
final:
*/
// With shortcut evaluation, the result could be any of the intermediate
// comparison results. This requires a temporary.
yssa_variable* result = node->opkinds.size() > 1 ?
temporary( "[comparison]", node->sloc ) : nullptr;
// Evaluate first term.
size_t operands = push( node->first, 1 ); // a
// Intermediate comparisons.
std::vector< yssa_block* > blocks;
size_t last = node->opkinds.size() - 1;
for ( size_t i = 0; ; ++i )
{
push( node->terms.at( i ), 1 ); // a, b
// Perform comparison.
yl_ast_opkind opkind = node->opkinds.at( i );
yl_opcode opcode = YL_NOP;
switch ( opkind )
{
case YL_ASTOP_EQUAL:
opcode = YL_EQ;
break;
case YL_ASTOP_NOTEQUAL:
opcode = YL_NE;
break;
case YL_ASTOP_LESS:
opcode = YL_LT;
break;
case YL_ASTOP_GREATER:
opcode = YL_GT;
break;
case YL_ASTOP_LESSEQUAL:
opcode = YL_LE;
break;
case YL_ASTOP_GREATEREQUAL:
opcode = YL_GE;
break;
case YL_ASTOP_IN:
opcode = YL_IN;
break;
case YL_ASTOP_NOTIN:
opcode = YL_IN;
break;
case YL_ASTOP_IS:
opcode = YL_IS;
break;
case YL_ASTOP_NOTIS:
opcode = YL_IS;
break;
default:
assert( ! "unexpected comparison operator" );
break;
}
yssa_opinst* o = op( node->sloc, opcode, 2, 1 );
pop( operands, 2, o->operand );
size_t index = push_op( o );
yssa_opinst* b = o->operand[ 1 ];
if ( opkind == YL_ASTOP_NOTIN || opkind == YL_ASTOP_NOTIS )
{
o = op( node->sloc, YL_LNOT, 1, 1 );
pop( index, 1, o->operand );
index = push_op( o );
}
// Assign to temporary.
if ( result )
{
pop( index, 1, &o );
o = assign( node->sloc, result, o );
}
// No shortcut after last comparison in chain.
if ( i >= last )
{
break;
}
// Only continue to next block if comparison is true.
if ( block )
{
assert( block->test == nullptr );
block->test = o;
blocks.push_back( block );
block = next_block();
}
// Ensure that operand b is on the top of the virtual stack.
operands = push_op( b );
}
// Any failed comparison shortcuts to the end.
if ( blocks.size() )
{
block = label_block();
for ( size_t i = 0; i < blocks.size(); ++i )
{
yssa_block* shortcut = blocks.at( i );
link_block( shortcut, FAIL, block );
}
}
// Push lookup of temporary.
if ( result )
{
push_op( lookup( result ) );
}
return 1;
}
int yssa_builder::visit( yl_expr_logical* node, int count )
{
switch ( node->opkind )
{
case YL_ASTOP_LOGICAND:
{
/*
result = lhs
? goto next : goto final
next:
result = rhs
final:
*/
yssa_variable* result = temporary( "[shortcut and]", node->sloc );
// Evaluate left hand side.
size_t operand = push( node->lhs, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
value = assign( node->sloc, result, value );
// Only continue to next block if lhs is true.
yssa_block* lhs_block = block;
if ( block )
{
assert( block->test == nullptr );
block->test = value;
block = next_block();
}
// Evaluate right hand side.
operand = push( node->rhs, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
// Link in the shortcut.
if ( lhs_block )
{
block = label_block();
link_block( lhs_block, FAIL, block );
}
// Push lookup of temporary.
push_op( lookup( result ) );
return 1;
}
case YL_ASTOP_LOGICXOR:
{
size_t operands = push( node->lhs, 1 );
push( node->rhs, 1 );
yssa_opinst* o = op( node->sloc, YL_LXOR, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
return 1;
}
case YL_ASTOP_LOGICOR:
{
/*
result = lhs
? goto final : goto next
next:
result = rhs
final:
*/
yssa_variable* result = temporary( "[shortcut or]", node->sloc );
// Evaluate left hand side.
size_t operand = push( node->lhs, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
value = assign( node->sloc, result, value );
// Only continue to next block if lhs is false.
yssa_block* lhs_block = block;
if ( block )
{
assert( block->test == nullptr );
block->test = value;
block = fail_block();
}
// Evaluate right hand side.
operand = push( node->rhs, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
// Link in the shortcut.
if ( lhs_block )
{
block = label_block();
link_block( lhs_block, NEXT, block );
}
// Push lookup of temporary.
push_op( lookup( result ) );
return 1;
}
default:
assert( ! "invalid logical operator" );
return 0;
}
}
int yssa_builder::visit( yl_expr_qmark* node, int count )
{
/*
condition
? goto iftrue : goto iffalse
iftrue:
result = trueexpr
goto final
iffalse:
result = falseexpr
goto final
final:
*/
// Evaluate condition.
size_t operand = push( node->condition, 1 );
yssa_opinst* value = nullptr;
pop( operand, 1, &value );
// True block.
yssa_block* test_block = block;
if ( block )
{
assert( block->test = nullptr );
block->test = value;
block = next_block();
}
// Result is a temporary since there is more than one definition.
yssa_variable* result = temporary( "[qmark]", node->sloc );
// Evaluate true branch.
operand = push( node->iftrue, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
yssa_block* true_block = block;
// False block.
block = test_block;
if ( block )
{
block = fail_block();
}
// Evaluate false branch.
operand = push( node->iffalse, 1 );
pop( operand, 1, &value );
assign( node->sloc, result, value );
yssa_block* false_block = block;
// Final block.
if ( true_block || false_block )
{
block = label_block();
if ( true_block )
{
link_block( true_block, NEXT, block );
}
if ( false_block )
{
link_block( false_block, NEXT, block );
}
}
// Push lookup of temporary.
push_op( lookup( result ) );
return 1;
}
int yssa_builder::visit( yl_new_new* node, int count )
{
// Evaluate object prototype.
size_t operand = push( node->proto, 1 );
// Create object using prototype.
yssa_opinst* o = op( node->sloc, YL_OBJECT, 1, 1 );
pop( operand, 1, o->operand );
operand = push_op( o );
// Call 'this' method.
yssa_opinst* m = op( node->sloc, YL_KEY, 1, 1 );
m->operand[ 0 ] = o;
m->key = "this";
size_t method = push_op( m );
// Repush the object (as this argument).
push_op( o );
// Push arguments.
int argcount = 0;
push_all( node->arguments, &argcount );
// Perform call.
yssa_opinst* c = op( node->sloc, YL_CALL, argcount + 2, 0 );
pop( method, argcount + 2, c->operand );
c->multival = multival;
multival = nullptr;
call( c );
// Only thing on virtual stack should be the constructed object.
return 1;
}
int yssa_builder::visit( yl_new_object* node, int count )
{
// Evaluate prototype.
yssa_opinst* o = nullptr;
if ( node->proto )
{
size_t operand = push( node->proto, 1 );
o = op( node->sloc, YL_OBJECT, 1, 1 );
pop( operand, 1, o->operand );
}
else
{
o = op( node->sloc, YL_OBJECT, 0, 1 );
}
// Push object onto virtual stack.
push_op( o );
// Declare object (as it can potentially be referenced as an upval).
open_scope( nullptr );
yssa_variable* object = varobj( node );
declare( node->sloc, object, o );
// Execute all member initializers.
for ( size_t i = 0; i < node->members.size(); ++i )
{
execute( node->members.at( i ) );
}
// Close upval (if any).
close_scope( node->sloc, nullptr );
// object should still be on the virtual stack.
return 1;
}
int yssa_builder::visit( yl_new_array* node, int count )
{
// Construct new array.
yssa_opinst* o = op( node->sloc, YL_ARRAY, 0, 1 );
o->c = node->values.size();
push_op( o );
// Append each element.
for ( size_t i = 0; i < node->values.size(); ++i )
{
size_t element = push( node->values.at( i ), 1 );
yssa_opinst* a = op( node->sloc, YL_APPEND, 2, 0 );
a->operand[ 0 ] = o;
pop( element, 1, &a->operand[ 1 ] );
}
// Extend final elements.
if ( node->final )
{
int count = 0;
size_t extend = push_all( node->final, &count );
yssa_opinst* e = op( node->sloc, YL_EXTEND, count + 1, 0 );
e->operand[ 0 ] = o;
pop( extend, count, &e->operand[ 1 ] );
e->multival = multival;
multival = nullptr;
}
// array should still be on virtual stack.
return 1;
}
int yssa_builder::visit( yl_new_table* node, int count )
{
// Construct new table.
yssa_opinst* o = op( node->sloc, YL_TABLE, 0, 1 );
o->c = node->elements.size();
push_op( o );
// Append each element.
for ( size_t i = 0; i < node->elements.size(); ++i )
{
const yl_key_value& kv = node->elements.at( i );
size_t operands = push( kv.key, 1 );
push( kv.value, 1 );
yssa_opinst* e = op( node->sloc, YL_SETINDEX, 2, 0 );
pop( operands, 2, e->operand );
}
// table should still be on virtual stack
return 1;
}
int yssa_builder::visit( yl_expr_mono* node, int count )
{
// Even when used in a context that requests multiple values,
// push only a single value onto the virtual stack.
push( node->expr, 1 );
return 1;
}
int yssa_builder::visit( yl_expr_call* node, int count )
{
// Restrict call expressions without unpack ellipsis to a single result.
if ( ! node->unpack && count != 0 )
{
count = 1;
}
// Check for method call.
size_t function = 0;
int funcount = 0;
switch ( node->function->kind )
{
case YL_EXPR_KEY:
{
yl_expr_key* knode = (yl_expr_key*)node->function;
// Look up key for method.
size_t operand = push( knode->object, 1 );
yssa_opinst* o = op( knode->sloc, YL_KEY, 1, 1 );
pop( operand, 1, o->operand );
o->key = module->alloc.strdup( knode->key );
push_op( o );
// Push the object onto the virtual stack as the 'this' parameter.
push_op( o->operand[ 0 ] );
funcount = 2;
break;
}
case YL_EXPR_INKEY:
{
yl_expr_inkey* knode = (yl_expr_inkey*)node->function;
// Look up index for method.
size_t operands = push( knode->object, 1 );
push( knode->key, 1 );
yssa_opinst* o = op( knode->sloc, YL_INKEY, 2, 1 );
pop( operands, 2, o->operand );
push_op( o );
// Push the object onto virtual stack as the 'this' parameter.
push_op( o->operand[ 0 ] );
funcount = 2;
break;
}
default:
{
function = push( node->function, 1 );
funcount = 1;
break;
}
}
// Push arguments.
int argcount = 0;
push_all( node->arguments, &argcount );
// Perform call.
yl_opcode opcode = node->yieldcall ? YL_YCALL : YL_CALL;
yssa_opinst* c = op( node->sloc, opcode, funcount + argcount, count );
pop( function, funcount + argcount, c->operand );
c->multival = multival;
multival = nullptr;
call( c );
// Return results appropriately on the stack.
return push_select( node->sloc, c, count );
}
int yssa_builder::visit( yl_expr_yield* node, int count )
{
// Restrict expressions without unpack to a single result.
if ( ! node->unpack && count != 0 )
{
count = 1;
}
// Push arguments.
int argcount = 0;
size_t arguments = push_all( node->arguments, &argcount );
// Perform yield.
yssa_opinst* y = op( node->sloc, YL_YIELD, argcount, count );
pop( arguments, argcount, y->operand );
y->multival = multival;
multival = nullptr;
call( y );
// Return results appropriately on the stack.
return push_select( node->sloc, y, count );
}
int yssa_builder::visit( yl_expr_vararg* node, int count )
{
if ( count != 0 )
{
yssa_opinst* o = op( node->sloc, YL_VARARG, 0, count );
return push_select( node->sloc, o, count );
}
else
{
return 0;
}
}
int yssa_builder::visit( yl_expr_unpack* node, int count )
{
if ( count != 0 )
{
size_t operand = push( node->array, 1 );
yssa_opinst* o = op( node->sloc, YL_UNPACK, 1, count );
pop( operand, 1, o->operand );
return push_select( node->sloc, o, count );
}
else
{
execute( node->array );
return 0;
}
}
int yssa_builder::visit( yl_expr_list* node, int count )
{
// Work out how many values we need to actually push.
int value_count = (int)node->values.size();
if ( count != -1 )
{
value_count = std::min( value_count, count );
}
// Push value_count values.
for ( size_t i = 0; i < value_count; ++i )
{
push( node->values.at( i ), 1 );
}
// Execute remaining values without leaving them on the stack.
for ( size_t i = value_count; i < node->values.size(); ++i )
{
execute( node->values.at( i ) );
}
// If there's an unpack value at the end of the list, then unpack it.
if ( node->final )
{
if ( count == -1 )
{
int final_count = 0;
push_all( node->final, &final_count );
value_count += final_count;
}
else if ( count > value_count )
{
push( node->final, count - value_count );
value_count = count;
}
else
{
execute( node->final );
}
}
return value_count;
}
int yssa_builder::visit( yl_expr_assign* node, int count )
{
if ( node->assignop == YL_ASTOP_DECLARE )
{
// Lvalue is a new variable.
assert( node->lvalue->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)node->lvalue;
yssa_variable* v = variable( local->name );
// Evaluate rvalue.
yssa_opinst* value = nullptr;
if ( node->rvalue )
{
size_t rvalue = push( node->rvalue, 1 );
pop( rvalue, 1, &value );
}
else
{
value = op( node->sloc, YL_NULL, 0, 1 );
}
// Assign.
value = declare( node->sloc, v, value );
// Push value onto stack as result.
push_op( value );
return 1;
}
else if ( node->assignop == YL_ASTOP_ASSIGN )
{
// Assign rvalue to lvalue.
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t rvalue = push( node->rvalue, 1 ); // lv, rv
yssa_opinst* value = nullptr;
pop( rvalue, 1, &value );
value = assign_lvalue( node->sloc, node->lvalue, lvalue, value );
pop_lvalue( node->lvalue, lvalue );
// Push result value onto stack as result.
push_op( value );
return 1;
}
else
{
// Evaluate lvalue and assign it with the assign op.
size_t lvalue = push_lvalue( node->lvalue ); // lv
size_t evalue = push_evalue( node->lvalue, lvalue ); // lv, ev
push( node->rvalue, 1 ); // lv, ev, rv
yssa_opinst* o = assign_op( node->sloc, node->assignop, evalue );
o = assign_lvalue( node->sloc, node->lvalue, lvalue, o );
pop_lvalue( node->lvalue, lvalue );
// Push result value onto stack as result.
push_op( o );
return 1;
}
}
int yssa_builder::visit( yl_expr_assign_list* node, int count )
{
// This is the most complex thing ever.
// Work out how many values we actually need to push. We only have
// as many values as there are lvalues on the left hand side.
int value_count = (int)node->lvalues.size();
if ( count != -1 )
{
value_count = std::min( value_count, count );
}
if ( node->assignop == YL_ASTOP_DECLARE )
{
// Evaluate rvalue list.
size_t rvalues = push( node->rvalues, (int)node->lvalues.size() );
// Assign them all.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
// Lvalue is a new variable.
yl_ast_node* lnode = node->lvalues.at( i );
assert( lnode->kind == YL_EXPR_LOCAL );
yl_expr_local* local = (yl_expr_local*)lnode;
yssa_variable* v = variable( local->name );
// Rvalue is on stack.
declare( node->sloc, v, peek( rvalues, i ) );
}
// Pop values.
std::vector< yssa_opinst* > values;
values.resize( node->lvalues.size() );
pop( rvalues, (int)node->lvalues.size(), values.data() );
// Push correct number of values back.
assert( value_count <= (int)node->lvalues.size() );
for ( int i = 0; i < value_count; ++i )
{
push_op( values.at( i ) );
}
return value_count;
}
else if ( node->assignop == YL_ASTOP_ASSIGN )
{
/*
a, b = b, a;
a = 4;
b = a, a = 3, a + 3;
assert( a == 7 );
assert( b == 3 ); // possibly!
*/
// Push each lvalue.
std::vector< size_t > lvalues;
lvalues.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = push_lvalue( node->lvalues.at( i ) );
lvalues.push_back( lvalue );
}
// Evaluate rvalue list.
size_t rvalues = push( node->rvalues, (int)node->lvalues.size() );
// Assign them all.
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
assign_lvalue
(
node->sloc,
node->lvalues.at( i ),
lvalues.at( i ),
peek( rvalues, i )
);
}
// Pop rvalues.
std::vector< yssa_opinst* > values;
values.resize( node->lvalues.size() );
pop( rvalues, (int)node->lvalues.size(), values.data() );
// Pop lvalues.
for ( size_t i = node->lvalues.size(); i-- > 0; )
{
pop_lvalue( node->lvalues.at( i ), lvalues.at( i ) );
}
// Push correct number of values back.
assert( value_count <= (int)node->lvalues.size() );
for ( int i = 0; i < value_count; ++i )
{
push_op( values.at( i ) );
}
return value_count;
}
else
{
// Push each lvalue.
std::vector< size_t > lvalues;
lvalues.reserve( node->lvalues.size() );
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = push_lvalue( node->lvalues.at( i ) );
lvalues.push_back( lvalue );
}
// Evaluate each lvalue.
size_t evalues = stack.size();
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
size_t lvalue = lvalues.at( i );
push_evalue( node->lvalues.at( i ), lvalue );
}
assert( stack.size() == evalues + node->lvalues.size() );
// Evaluate rvalue list.
size_t rvalues = push( node->rvalues, (int)node->lvalues.size() );
// Perform assignment operations and assignments.
size_t ovalues = stack.size();
for ( size_t i = 0; i < node->lvalues.size(); ++i )
{
// Push operands.
size_t operands = push_op( peek( evalues, i ) );
push_op( peek( rvalues, i ) );
// Perform assignment.
yssa_opinst* o = assign_op( node->sloc, node->assignop, operands );
o = assign_lvalue
(
node->sloc,
node->lvalues.at( i ),
lvalues.at( i ),
o
);
push_op( o );
}
assert( stack.size() == ovalues + node->lvalues.size() );
// Pop values.
std::vector< yssa_opinst* > values;
values.resize( node->lvalues.size() );
pop( ovalues, (int)node->lvalues.size(), values.data() );
// Pop rvalues.
std::vector< yssa_opinst* > poprv;
poprv.resize( node->lvalues.size() );
pop( rvalues, (int)node->lvalues.size(), poprv.data() );
// Pop lvalues.
for ( size_t i = node->lvalues.size(); i-- > 0; )
{
pop_lvalue( node->lvalues.at( i ), lvalues.at( i ) );
}
// Push correct number of values back.
assert( value_count <= (int)node->lvalues.size() );
for ( int i = 0; i < value_count; ++i )
{
push_op( values.at( i ) );
}
return value_count;
}
}
/*
Control flow.
*/
yssa_block* yssa_builder::make_block( unsigned flags )
{
function->blocks.emplace_back( new yssa_block( flags ) );
return function->blocks.back().get();
}
yssa_block* yssa_builder::next_block( unsigned flags )
{
yssa_block* next = make_block( flags );
if ( block )
{
link_block( block, NEXT, next );
}
return next;
}
yssa_block* yssa_builder::fail_block( unsigned flags )
{
yssa_block* fail = make_block( flags );
if ( block )
{
link_block( block, FAIL, fail );
}
return fail;
}
yssa_block* yssa_builder::label_block( unsigned flags )
{
/*
Create the next block as the target of a jump.
*/
if ( block && block->ops.empty() )
{
// Current block is empty, so can link to it directly.
return block;
}
else
{
// Return next block.
return next_block( flags );
}
}
void yssa_builder::link_block( yssa_block* prev, link_kind kind, yssa_block* next )
{
switch ( kind )
{
case NEXT:
assert( prev->next == nullptr );
prev->next = next;
next->prev.push_back( prev );
break;
case FAIL:
assert( prev->fail == nullptr );
prev->fail = next;
next->prev.push_back( prev );
break;
default:
assert( ! "unknown link kind" );
break;
}
}
/*
Emitting instructions.
*/
yssa_opinst* yssa_builder::make_op(
int sloc, uint8_t opcode, uint8_t operand_count, uint8_t result_count )
{
// Allocate op from memory region.
void* p = module->alloc.malloc(
sizeof( yssa_opinst ) + sizeof( yssa_opinst* ) * operand_count );
return new ( p ) yssa_opinst( sloc, opcode, operand_count, result_count );
}
yssa_opinst* yssa_builder::op(
int sloc, uint8_t opcode, uint8_t operand_count, uint8_t result_count )
{
// Create op and add to current block.
yssa_opinst* op = make_op( sloc, opcode, operand_count, result_count );
if ( block )
{
block->ops.push_back( op );
}
return op;
}
yssa_opinst* yssa_builder::assign_op(
int sloc, yl_ast_opkind opkind, size_t operands )
{
uint8_t opcode = YL_NOP;
switch ( opkind )
{
case YL_ASTOP_MULASSIGN: opcode = YL_MUL; break;
case YL_ASTOP_DIVASSIGN: opcode = YL_DIV; break;
case YL_ASTOP_MODASSIGN: opcode = YL_MOD; break;
case YL_ASTOP_INTDIVASSIGN: opcode = YL_INTDIV; break;
case YL_ASTOP_ADDASSIGN: opcode = YL_ADD; break;
case YL_ASTOP_SUBASSIGN: opcode = YL_SUB; break;
case YL_ASTOP_LSHIFTASSIGN: opcode = YL_LSL; break;
case YL_ASTOP_LRSHIFTASSIGN: opcode = YL_LSR; break;
case YL_ASTOP_ARSHIFTASSIGN: opcode = YL_ASR; break;
case YL_ASTOP_BITANDASSIGN: opcode = YL_BITAND; break;
case YL_ASTOP_BITXORASSIGN: opcode = YL_BITXOR; break;
case YL_ASTOP_BITORASSIGN: opcode = YL_BITOR; break;
default:
assert( ! "unexpected compound assignment operator" );
break;
}
yssa_opinst* o = op( sloc, opcode, 2, 1 );
pop( operands, 2, o->operand );
return o;
}
/*
Definitions and lookups.
*/
yssa_variable* yssa_builder::variable( yl_ast_name* name )
{
auto i = variables.find( name );
if ( i != variables.end() )
{
return i->second;
}
yssa_variable* v = new ( module->alloc ) yssa_variable();
v->name = module->alloc.strdup( name->name );
v->sloc = name->sloc;
v->xcref = false; // Not (yet) referenced from an exception handler.
v->localup = name->upval ? localups.size() : yl_opinst::NOVAL;
v->r = 0;
variables.emplace( name, v );
return v;
}
yssa_variable* yssa_builder::varobj( yl_new_object* object )
{
auto i = variables.find( object );
if ( i != variables.end() )
{
return i->second;
}
yssa_variable* v = new ( module->alloc ) yssa_variable();
v->name = "[object]";
v->sloc = object->sloc;
v->xcref = false; // Not (yet) referenced from an exception handler.
v->localup = object->upval ? localups.size() : yl_opinst::NOVAL;
v->r = 0;
variables.emplace( object, v );
return v;
}
yssa_variable* yssa_builder::temporary( const char* name, int sloc )
{
yssa_variable* v = new ( module->alloc ) yssa_variable();
v->name = name;
v->sloc = sloc;
v->xcref = false; // You know by now!
v->localup = false; // No way to refer to this variable in inner scope.
v->r = 0;
return v;
}
yssa_opinst* yssa_builder::declare(
int sloc, yssa_variable* variable, yssa_opinst* value )
{
// Upvals exist from their declaration to the end of the closing scope.
if ( variable->localup != yl_opinst::NOVAL )
{
localups.push_back( variable );
}
// Otherwise acts like an ordinary assignment.
return assign( sloc, variable, value );
}
yssa_opinst* yssa_builder::assign(
int sloc, yssa_variable* variable, yssa_opinst* value )
{
if ( value->variable )
{
// The definition was already a definition of another variable.
// One op can't define two variables, so the new definition is
// a move from the previous one.
yssa_opinst* move = op( sloc, YL_MOV, 1, 1 );
move->operand[ 0 ] = value;
value = move;
}
// This op is a definition of the variable.
value->variable = variable;
// Record the definition as the latest definition in the current block.
if ( block )
{
block->definitions[ variable ] = value;
}
return value;
}
/*
Some inspiration taken from:
Simple and Efficient Construction of Static Single Assignment Form
Braun, Sebastian Buchwald, et al.
http://www.cdl.uni-saarland.de/papers/bbhlmz13cc.pdf
*/
/*
When a variable is referenced, we must find the definition that reaches
the point of the reference. We search predecessor blocks recursively,
adding phi functions as necessary. If we reach a block with no ancestors
without finding a definition then the variable is undefined (this is
an error). If we reach a block we have already visited, then the
definition found on that path is the same definition that reaches the
already-visited block.
*/
static yssa_opinst* YSSA_UNDEF = (yssa_opinst*)-1;
static yssa_opinst* YSSA_SELF = (yssa_opinst*)-2;
yssa_opinst* yssa_builder::lookup( yssa_variable* variable )
{
// Lookup the variable.
if ( block )
{
return lookup_block( block, variable );
}
else
{
return nullptr;
}
}
yssa_opinst* yssa_builder::lookup_block(
yssa_block* block, yssa_variable* variable )
{
// Check for a local definition.
auto i = block->definitions.find( variable );
if ( i != block->definitions.end() )
{
return i->second;
}
// Check if we have visited this block already on our search.
if ( block->flags & YSSA_LOOKUP )
{
return YSSA_SELF;
}
// If it's an unsealed block, then we can't proceed, add an incomplete phi.
if ( block->flags & YSSA_UNSEALED )
{
yssa_opinst* incomplete = make_op( -1, YSSA_REF, 1, 1 );
incomplete->variable = variable;
block->phi.push_back( incomplete );
block->definitions.emplace( variable, incomplete );
return incomplete;
}
else
{
yssa_opinst* phi = lookup_seal( block, variable );
assert( phi != YSSA_UNDEF );
assert( phi != YSSA_SELF );
block->phi.push_back( phi );
return phi;
}
}
yssa_opinst* yssa_builder::lookup_seal(
yssa_block* block, yssa_variable* variable )
{
assert( !( block->flags & YSSA_UNSEALED ) );
// If the variable is live in an exception handler block, mark it.
if ( block->flags & YSSA_XCHANDLER )
{
variable->xcref = true;
// If it has no predecessors then the only way to enter
// this block is with an exception. Use YSSA_VAR to indicate
// that the current value of the variable should be used.
if ( block->prev.empty() )
{
yssa_opinst* var = make_op( -1, YSSA_VAR, 0, 1 );
var->variable = variable;
block->phi.push_back( var );
block->definitions.emplace( variable, var );
return var;
}
// Otherwise there should be at least one definition of the
// variable reaching this block.
}
// If the block has no predecessors then the name is undefined.
if ( block->prev.empty() )
{
return YSSA_UNDEF;
}
// Mark this block to prevent infinite recursion in lookups.
block->flags |= YSSA_LOOKUP;
// If there is only one predecessor then continue search.
if ( block->prev.size() == 1 )
{
yssa_opinst* def = lookup_block( block->prev.at( 0 ), variable );
block->flags &= ~YSSA_LOOKUP;
return def;
}
// Find which definition reaches each incoming edge.
yssa_opinst* sole_def = YSSA_SELF;
std::vector< yssa_opinst* > defs;
defs.reserve( block->prev.size() );
for ( size_t i = 0; i < block->prev.size(); ++i )
{
yssa_opinst* def = lookup_block( block->prev.at( i ), variable );
// If any definition is undefined, so is the entire thing.
if ( def == YSSA_UNDEF )
{
block->flags &= ~YSSA_LOOKUP;
return YSSA_UNDEF;
}
// If all of the defs are the same, or YSSA_SELF, then that's the
// sole definition which reaches this point.
if ( sole_def == YSSA_SELF )
{
sole_def = def;
}
if ( sole_def != def )
{
sole_def = nullptr;
}
// Add to the list of definitions.
defs.push_back( def );
}
// Done with lookups.
block->flags &= ~YSSA_LOOKUP;
// Return sole def if the phi-function collapsed.
if ( sole_def == YSSA_SELF )
{
return YSSA_UNDEF;
}
if ( sole_def )
{
return sole_def;
}
// Create phi function.
yssa_opinst* phi = make_op( -1, YSSA_PHI, defs.size(), 1 );
for ( size_t i = 0; i < defs.size(); ++i )
{
yssa_opinst* def = defs.at( i );
if ( def != YSSA_SELF )
{
phi->operand[ i ] = def;
}
else
{
phi->operand[ i ] = phi;
}
}
return phi;
}
void yssa_builder::seal_block( yssa_block* block )
{
assert( block->flags & YSSA_UNSEALED );
block->flags &= ~YSSA_UNSEALED;
for ( size_t i = 0; i < block->phi.size(); ++i )
{
yssa_opinst* ref = block->phi.at( i );
assert( ref->opcode == YSSA_REF );
yssa_opinst* phi = lookup_seal( block, ref->variable );
assert( phi != YSSA_UNDEF );
assert( phi != YSSA_SELF );
ref->operand[ 0 ] = phi;
block->phi[ i ] = phi;
}
}
void yssa_builder::call( yssa_opinst* callop )
{
/*
Any call or yield instruction must implicitly reference all active
upvals, and also clobbers them (we can't prove whether or not they
are written to by the function being called), so any references to
them that are on the virtual stack must be replaced with temporaries.
*/
// Add implicit reference to all active upvals (since they could be
// referenced by anything in the function).
if ( localups.size() )
{
yssa_opinst* o = op( callop->sloc, YSSA_IMPLICIT, localups.size(), 0 );
o->associated = callop;
for ( size_t i = 0; i < localups.size(); ++i )
{
yssa_variable* localup = localups.at( i );
o->operand[ i ] = lookup( localup );
}
}
// Clobber all local upvals (since they could be written by anything
// in the function).
for ( size_t i = 0; i < localups.size(); ++i )
{
clobber( localups.at( i ) );
}
}
void yssa_builder::clobber( yssa_variable* v )
{
/*
Something (potentially) changed the value of v with a new definition.
Any definition of v which is on the stack must be replaced with an
explicit load, at the point where the value was pushed, to ensure that
no two definitions of the same variable are live at the same time.
*/
yssa_opinst* load = nullptr;
yssa_opinst* load_value = nullptr;
stack_entry* load_entry = nullptr;
for ( size_t i = 0; i < stack.size(); ++i )
{
stack_entry& sentry = stack.at( i );
// Locations of other values in the same block will have moved now
// we have inserted a load.
if ( load_entry
&& sentry.block == load_entry->block
&& sentry.index >= load_entry->index )
{
sentry.index += 1;
}
if ( sentry.value->variable != v )
{
continue;
}
// Potentially create load. The oldest copy of the variable
// definition will be lowest in the stack.
if ( ! load )
{
// Create load.
void* p = module->alloc.malloc(
sizeof( yssa_opinst ) + sizeof( yssa_opinst* ) * 1 );
load = new ( p ) yssa_opinst( sentry.value->sloc, YL_MOV, 1, 1 );
load->operand[ 0 ] = sentry.value;
// Insert at point where the value was pushed.
sentry.block->ops.insert
(
sentry.block->ops.begin() + sentry.index,
load
);
// Remember this value.
load_value = sentry.value;
load_entry = &sentry;
}
else
{
// All definitions of v at this point should be the same.
assert( sentry.value == load_value );
}
// Replace value on stack with the new temporary.
sentry.value = load;
}
}
/*
Virtual stack.
*/
void yssa_builder::execute( yl_ast_node* statement )
{
int valcount = visit( statement, 0 );
assert( valcount == 0 || valcount == 1 );
assert( multival == nullptr );
if ( valcount == 1 )
{
stack.pop_back();
}
}
size_t yssa_builder::push_all( yl_ast_node* expression, int* count )
{
size_t result = stack.size();
if ( expression )
{
*count = visit( expression, -1 );
}
else
{
*count = 0;
}
return result;
}
size_t yssa_builder::push( yl_ast_node* expression, int count )
{
size_t result = stack.size();
int valcount = visit( expression, count );
assert( valcount <= count || valcount == 1 );
if ( valcount < count )
{
yssa_opinst* o = op( expression->sloc, YL_NULL, 0, 1 );
for ( int i = valcount; i < count; ++i )
{
push_op( o );
}
}
else if ( valcount > count )
{
assert( count == 0 );
assert( valcount == 1 );
stack.pop_back();
}
assert( stack.size() == result + count );
return result;
}
size_t yssa_builder::push_op( yssa_opinst* o )
{
/*
Don't do the following things between creating an op and pushing it:
- Pushing an expression.
- Assign to variable.
- Notify a call.
We track the block location where each op is pushed, so if we need
to insert a temporary to replace it, the temporary is created at the
point where the op was pushed, not where it is used.
*/
size_t result = stack.size();
stack_entry sentry;
sentry.block = block;
sentry.index = block ? block->ops.size() : 0;
sentry.value = o;
stack.push_back( sentry );
return result;
}
int yssa_builder::push_select( int sloc, yssa_opinst* selop, int count )
{
if ( count == -1 )
{
multival = selop;
return 0;
}
else if ( count == 1 )
{
push_op( selop );
return 1;
}
else
{
for ( int i = 0; i < count; ++i )
{
yssa_opinst* o = op( sloc, YSSA_SELECT, 1, 1 );
o->operand[ 0 ] = selop;
o->select = i;
push_op( o );
}
return count;
}
}
void yssa_builder::pop( size_t index, int count, yssa_opinst** ops )
{
assert( index + count == stack.size() );
for ( int i = 0; i < count; ++i )
{
ops[ i ] = stack.at( index + i ).value;
}
stack.erase( stack.begin() + index, stack.begin() + index + count );
}
yssa_opinst* yssa_builder::peek( size_t index, size_t i )
{
assert( index + i < stack.size() );
return stack.at( index + i ).value;
}
size_t yssa_builder::push_lvalue( yl_ast_node* lvalue )
{
size_t result;
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
case YL_EXPR_GLOBAL:
case YL_EXPR_UPREF:
{
// Don't push anything.
result = stack.size();
break;
}
case YL_EXPR_KEY:
{
// Just the object.
yl_expr_key* keyexpr = (yl_expr_key*)lvalue;
result = push( keyexpr->object, 1 );
break;
}
case YL_EXPR_INKEY:
{
// Object and key.
yl_expr_inkey* inkey = (yl_expr_inkey*)lvalue;
result = push( inkey->object, 1 );
push( inkey->key, 1 );
break;
}
case YL_EXPR_INDEX:
{
// Object and index.
yl_expr_index* index = (yl_expr_index*)lvalue;
result = push( index->object, 1 );
push( index->index, 1 );
break;
}
default:
assert( ! "invalid lvalue" );
break;
}
return result;
}
size_t yssa_builder::push_evalue( yl_ast_node* lvalue, size_t index )
{
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
{
yl_expr_local* local = (yl_expr_local*)lvalue;
yssa_variable* v = variable( local->name );
return push_op( lookup( v ) );
}
case YL_EXPR_GLOBAL:
{
yl_expr_global* global = (yl_expr_global*)lvalue;
yssa_opinst* o = op( global->sloc, YL_GLOBAL, 0, 1 );
o->key = module->alloc.strdup( global->name );
return push_op( o );
}
case YL_EXPR_UPREF:
{
yl_expr_upref* upref = (yl_expr_upref*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_GETUP, 0, 1 );
o->a = upref->index;
return push_op( o );
}
case YL_EXPR_KEY:
{
yl_expr_key* keyexpr = (yl_expr_key*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_KEY, 1, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->key = module->alloc.strdup( keyexpr->key );
return push_op( o );
}
case YL_EXPR_INKEY:
{
yssa_opinst* o = op( lvalue->sloc, YL_INKEY, 2, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
return push_op( o );
}
case YL_EXPR_INDEX:
{
yssa_opinst* o = op( lvalue->sloc, YL_INDEX, 2, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
return push_op( o );
}
default:
{
assert( ! "invalid lvalue" );
yssa_opinst* o = op( lvalue->sloc, YL_NULL, 0, 1 );
return push_op( o );
}
}
}
yssa_opinst* yssa_builder::assign_lvalue(
int sloc, yl_ast_node* lvalue, size_t index, yssa_opinst* value )
{
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
{
yl_expr_local* local = (yl_expr_local*)lvalue;
yssa_variable* v = variable( local->name );
return assign( sloc, v, value );
}
case YL_EXPR_GLOBAL:
{
yl_expr_global* global = (yl_expr_global*)lvalue;
yssa_opinst* o = op( global->sloc, YL_SETGLOBAL, 1, 0 );
o->operand[ 0 ] = value;
o->key = module->alloc.strdup( global->name );
return value;
}
case YL_EXPR_UPREF:
{
yl_expr_upref* upref = (yl_expr_upref*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_SETUP, 1, 0 );
o->operand[ 0 ] = value;
o->a = upref->index;
return value;
}
case YL_EXPR_KEY:
{
yl_expr_key* keyexpr = (yl_expr_key*)lvalue;
yssa_opinst* o = op( lvalue->sloc, YL_SETKEY, 2, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = value;
o->key = module->alloc.strdup( keyexpr->key );
return value;
}
case YL_EXPR_INKEY:
{
yssa_opinst* o = op( lvalue->sloc, YL_SETINKEY, 3, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
o->operand[ 2 ] = value;
return value;
}
case YL_EXPR_INDEX:
{
yssa_opinst* o = op( lvalue->sloc, YL_SETINDEX, 3, 1 );
o->operand[ 0 ] = peek( index, 0 );
o->operand[ 1 ] = peek( index, 1 );
o->operand[ 2 ] = value;
return value;
}
default:
assert( ! "invalid lvalue" );
return value;
}
}
void yssa_builder::pop_lvalue( yl_ast_node* lvalue, size_t index )
{
switch ( lvalue->kind )
{
case YL_EXPR_LOCAL:
case YL_EXPR_GLOBAL:
case YL_EXPR_UPREF:
{
break;
}
case YL_EXPR_KEY:
{
// Just the object.
yssa_opinst* value = nullptr;
pop( index, 1, &value );
break;
}
case YL_EXPR_INKEY:
{
// Object and key.
yssa_opinst* values[ 2 ] = { nullptr, nullptr };
pop( index, 2, values );
break;
}
case YL_EXPR_INDEX:
{
// Object and index.
yssa_opinst* values[ 2 ] = { nullptr, nullptr };
pop( index, 2, values );
break;
}
default:
assert( ! "invalid lvalue" );
break;
}
}
/*
Scope stack.
*/
void yssa_builder::open_scope( yl_ast_scope* scope, yssa_block* xchandler )
{
scope_entry s;
s.scope = scope;
s.localups = localups.size();
s.itercount = itercount;
if ( xchandler )
s.xchandler = xchandler;
else if ( scopes.size() )
s.xchandler = scopes.back().xchandler;
else
s.xchandler = nullptr;
scopes.push_back( s );
}
void yssa_builder::close_scope( int sloc, yl_ast_scope* scope )
{
const scope_entry& s = scopes.back();
assert( s.scope == scope );
// Close.
close( sloc, s.localups, s.itercount );
// Pop upvals and reset iterators.
assert( s.localups <= localups.size() );
assert( s.itercount <= itercount );
localups.resize( s.localups );
itercount = s.itercount;
scopes.pop_back();
}
yssa_builder::break_entry* yssa_builder::open_break(
yl_ast_scope* scope, break_kind kind )
{
// Create break entry.
std::unique_ptr< break_entry > b = std::make_unique< break_entry >();
b->scope = scope;
b->kind = kind;
b->localups = localups.size();
b->itercount = itercount;
// Add break entry to map.
break_entry* bentry = b.get();
breaks.emplace( break_key( scope, kind ), std::move( b ) );
return bentry;
}
void yssa_builder::close_break( break_entry* b, yssa_block* target )
{
if ( target )
{
for ( size_t i = 0; i < b->blocks.size(); ++i )
{
yssa_block* break_block = b->blocks.at( i );
assert( break_block );
link_block( break_block, NEXT, target );
}
}
breaks.erase( break_key( b->scope, b->kind ) );
}
void yssa_builder::close( int sloc, size_t closeups, size_t closeiter )
{
// Don't need to do anything if there's nothing to close.
if ( closeups == localups.size() && closeiter == itercount )
{
return;
}
assert( closeups <= localups.size() );
assert( closeiter <= itercount );
// Otherwise, close everything relevant.
size_t close_count = localups.size() - closeups;
yssa_opinst* o = op( sloc, YL_CLOSE, close_count, 0 );
o->a = closeups;
o->b = closeiter;
for ( size_t i = 0; i < close_count; ++i )
{
o->operand[ i ] = lookup( localups.at( closeups + i ) );
}
}
|
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include <algorithm>
#include <utility>
#include <v8.h>
#include <v8-debug.h>
#include "v8_proxy.h"
#include "dom_wrapper_map.h"
#include "v8_index.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_collection.h"
#include "v8_nodefilter.h"
#include "V8DOMWindow.h"
#include "ChromiumBridge.h"
#include "BarInfo.h"
#include "CanvasGradient.h"
#include "CanvasPattern.h"
#include "CanvasPixelArray.h"
#include "CanvasRenderingContext2D.h"
#include "CanvasStyle.h"
#include "CharacterData.h"
#include "ClientRect.h"
#include "ClientRectList.h"
#include "Clipboard.h"
#include "Console.h"
#include "Counter.h"
#include "CSSCharsetRule.h"
#include "CSSFontFaceRule.h"
#include "CSSImportRule.h"
#include "CSSMediaRule.h"
#include "CSSPageRule.h"
#include "CSSRule.h"
#include "CSSRuleList.h"
#include "CSSValueList.h"
#include "CSSStyleRule.h"
#include "CSSStyleSheet.h"
#include "CSSVariablesDeclaration.h"
#include "CSSVariablesRule.h"
#include "DocumentType.h"
#include "DocumentFragment.h"
#include "DOMCoreException.h"
#include "DOMImplementation.h"
#include "DOMParser.h"
#include "DOMSelection.h"
#include "DOMStringList.h"
#include "DOMWindow.h"
#include "Entity.h"
#include "EventListener.h"
#include "EventTarget.h"
#include "Event.h"
#include "EventException.h"
#include "ExceptionCode.h"
#include "File.h"
#include "FileList.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "History.h"
#include "HTMLNames.h"
#include "HTMLDocument.h"
#include "HTMLElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLSelectElement.h"
#include "HTMLOptionsCollection.h"
#include "ImageData.h"
#include "InspectorController.h"
#include "KeyboardEvent.h"
#include "Location.h"
#include "MediaError.h"
#include "MediaList.h"
#include "MediaPlayer.h"
#include "MessageChannel.h"
#include "MessageEvent.h"
#include "MessagePort.h"
#include "MimeTypeArray.h"
#include "MouseEvent.h"
#include "MutationEvent.h"
#include "Navigator.h" // for MimeTypeArray
#include "NodeFilter.h"
#include "Notation.h"
#include "NodeList.h"
#include "NodeIterator.h"
#include "OverflowEvent.h"
#include "Page.h"
#include "Plugin.h"
#include "PluginArray.h"
#include "ProcessingInstruction.h"
#include "ProgressEvent.h"
#include "Range.h"
#include "RangeException.h"
#include "Rect.h"
#include "RGBColor.h"
#include "Screen.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "StyleSheet.h"
#include "StyleSheetList.h"
#include "SVGColor.h"
#include "SVGPaint.h"
#include "TextEvent.h"
#include "TextMetrics.h"
#include "TimeRanges.h"
#include "TreeWalker.h"
#include "XSLTProcessor.h"
#include "V8AbstractEventListener.h"
#include "V8CustomEventListener.h"
#include "V8DOMWindow.h"
#include "V8HTMLElement.h"
#include "V8LazyEventListener.h"
#include "V8ObjectEventListener.h"
#include "WebKitAnimationEvent.h"
#include "WebKitCSSKeyframeRule.h"
#include "WebKitCSSKeyframesRule.h"
#include "WebKitCSSMatrix.h"
#include "WebKitCSSTransformValue.h"
#include "WebKitPoint.h"
#include "WebKitTransitionEvent.h"
#include "WheelEvent.h"
#include "XMLHttpRequest.h"
#include "XMLHttpRequestException.h"
#include "XMLHttpRequestProgressEvent.h"
#include "XMLHttpRequestUpload.h"
#include "XMLSerializer.h"
#include "XPathException.h"
#include "XPathExpression.h"
#include "XPathNSResolver.h"
#include "XPathResult.h"
#include "ScriptController.h"
#if ENABLE(SVG)
#include "SVGAngle.h"
#include "SVGAnimatedPoints.h"
#include "SVGElement.h"
#include "SVGElementInstance.h"
#include "SVGElementInstanceList.h"
#include "SVGException.h"
#include "SVGLength.h"
#include "SVGLengthList.h"
#include "SVGNumberList.h"
#include "SVGPathSeg.h"
#include "SVGPathSegArc.h"
#include "SVGPathSegClosePath.h"
#include "SVGPathSegCurvetoCubic.h"
#include "SVGPathSegCurvetoCubicSmooth.h"
#include "SVGPathSegCurvetoQuadratic.h"
#include "SVGPathSegCurvetoQuadraticSmooth.h"
#include "SVGPathSegLineto.h"
#include "SVGPathSegLinetoHorizontal.h"
#include "SVGPathSegLinetoVertical.h"
#include "SVGPathSegList.h"
#include "SVGPathSegMoveto.h"
#include "SVGPointList.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGRenderingIntent.h"
#include "SVGStringList.h"
#include "SVGTransform.h"
#include "SVGTransformList.h"
#include "SVGUnitTypes.h"
#include "SVGURIReference.h"
#include "SVGZoomEvent.h"
#include "V8SVGPODTypeWrapper.h"
#endif // SVG
#if ENABLE(WORKERS)
#include "Worker.h"
#include "WorkerContext.h"
#include "WorkerLocation.h"
#include "WorkerNavigator.h"
#endif // WORKERS
#if ENABLE(XPATH)
#include "XPathEvaluator.h"
#endif
namespace WebCore {
// DOM binding algorithm:
//
// There are two kinds of DOM objects:
// 1. DOM tree nodes, such as Document, HTMLElement, ...
// there classes implements TreeShared<T> interface;
// 2. Non-node DOM objects, such as CSSRule, Location, etc.
// these classes implement a ref-counted scheme.
//
// A DOM object may have a JS wrapper object. If a tree node
// is alive, its JS wrapper must be kept alive even it is not
// reachable from JS roots.
// However, JS wrappers of non-node objects can go away if
// not reachable from other JS objects. It works like a cache.
//
// DOM objects are ref-counted, and JS objects are traced from
// a set of root objects. They can create a cycle. To break
// cycles, we do following:
// Handles from DOM objects to JS wrappers are always weak,
// so JS wrappers of non-node object cannot create a cycle.
// Before starting a global GC, we create a virtual connection
// between nodes in the same tree in the JS heap. If the wrapper
// of one node in a tree is alive, wrappers of all nodes in
// the same tree are considered alive. This is done by creating
// object groups in GC prologue callbacks. The mark-compact
// collector will remove these groups after each GC.
// Static utility context.
v8::Persistent<v8::Context> V8Proxy::m_utilityContext;
// Static list of registered extensions
V8ExtensionList V8Proxy::m_extensions;
// A helper class for undetectable document.all
class UndetectableHTMLCollection : public HTMLCollection {
};
#ifndef NDEBUG
// Keeps track of global handles created (not JS wrappers
// of DOM objects). Often these global handles are source
// of leaks.
//
// If you want to let a C++ object hold a persistent handle
// to a JS object, you should register the handle here to
// keep track of leaks.
//
// When creating a persistent handle, call:
//
// #ifndef NDEBUG
// V8Proxy::RegisterGlobalHandle(type, host, handle);
// #endif
//
// When releasing the handle, call:
//
// #ifndef NDEBUG
// V8Proxy::UnregisterGlobalHandle(type, host, handle);
// #endif
//
typedef HashMap<v8::Value*, GlobalHandleInfo*> GlobalHandleMap;
static GlobalHandleMap& global_handle_map()
{
static GlobalHandleMap static_global_handle_map;
return static_global_handle_map;
}
// The USE_VAR(x) template is used to silence C++ compiler warnings
// issued for unused variables (typically parameters or values that
// we want to watch in the debugger).
template <typename T>
static inline void USE_VAR(T) { }
// The function is the place to set the break point to inspect
// live global handles. Leaks are often come from leaked global handles.
static void EnumerateGlobalHandles()
{
for (GlobalHandleMap::iterator it = global_handle_map().begin(),
end = global_handle_map().end(); it != end; ++it) {
GlobalHandleInfo* info = it->second;
USE_VAR(info);
v8::Value* handle = it->first;
USE_VAR(handle);
}
}
void V8Proxy::RegisterGlobalHandle(GlobalHandleType type, void* host,
v8::Persistent<v8::Value> handle)
{
ASSERT(!global_handle_map().contains(*handle));
global_handle_map().set(*handle, new GlobalHandleInfo(host, type));
}
void V8Proxy::UnregisterGlobalHandle(void* host, v8::Persistent<v8::Value> handle)
{
ASSERT(global_handle_map().contains(*handle));
GlobalHandleInfo* info = global_handle_map().take(*handle);
ASSERT(info->host_ == host);
delete info;
}
#endif // ifndef NDEBUG
void BatchConfigureAttributes(v8::Handle<v8::ObjectTemplate> inst,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedAttribute* attrs,
size_t num_attrs)
{
for (size_t i = 0; i < num_attrs; ++i) {
const BatchedAttribute* a = &attrs[i];
(a->on_proto ? proto : inst)->SetAccessor(
v8::String::New(a->name),
a->getter,
a->setter,
a->data == V8ClassIndex::INVALID_CLASS_INDEX
? v8::Handle<v8::Value>()
: v8::Integer::New(V8ClassIndex::ToInt(a->data)),
a->settings,
a->attribute);
}
}
void BatchConfigureConstants(v8::Handle<v8::FunctionTemplate> desc,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedConstant* consts,
size_t num_consts)
{
for (size_t i = 0; i < num_consts; ++i) {
const BatchedConstant* c = &consts[i];
desc->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
proto->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
}
}
typedef HashMap<Node*, v8::Object*> DOMNodeMap;
typedef HashMap<void*, v8::Object*> DOMObjectMap;
#ifndef NDEBUG
static void EnumerateDOMObjectMap(DOMObjectMap& wrapper_map)
{
for (DOMObjectMap::iterator it = wrapper_map.begin(), end = wrapper_map.end();
it != end; ++it) {
v8::Persistent<v8::Object> wrapper(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
void* obj = it->first;
USE_VAR(type);
USE_VAR(obj);
}
}
static void EnumerateDOMNodeMap(DOMNodeMap& node_map)
{
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
USE_VAR(node);
ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
}
}
#endif // NDEBUG
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj, void* para);
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* para);
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* para);
// A map from DOM node to its JS wrapper.
static DOMWrapperMap<Node>& GetDOMNodeMap()
{
static DOMWrapperMap<Node> static_dom_node_map(&WeakNodeCallback);
return static_dom_node_map;
}
// A map from a DOM object (non-node) to its JS wrapper. This map does not
// contain the DOM objects which can have pending activity (active dom objects).
DOMWrapperMap<void>& GetDOMObjectMap()
{
static DOMWrapperMap<void>
static_dom_object_map(&WeakDOMObjectCallback);
return static_dom_object_map;
}
// A map from a DOM object to its JS wrapper for DOM objects which
// can have pending activity.
static DOMWrapperMap<void>& GetActiveDOMObjectMap()
{
static DOMWrapperMap<void>
static_active_dom_object_map(&WeakActiveDOMObjectCallback);
return static_active_dom_object_map;
}
#if ENABLE(SVG)
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param);
// A map for SVGElementInstances.
static DOMWrapperMap<SVGElementInstance>& dom_svg_element_instance_map()
{
static DOMWrapperMap<SVGElementInstance>
static_dom_svg_element_instance_map(&WeakSVGElementInstanceCallback);
return static_dom_svg_element_instance_map;
}
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param)
{
SVGElementInstance* instance = static_cast<SVGElementInstance*>(param);
ASSERT(dom_svg_element_instance_map().contains(instance));
instance->deref();
dom_svg_element_instance_map().forget(instance);
}
v8::Handle<v8::Value> V8Proxy::SVGElementInstanceToV8Object(
SVGElementInstance* instance)
{
if (!instance)
return v8::Null();
v8::Handle<v8::Object> existing_instance = dom_svg_element_instance_map().get(instance);
if (!existing_instance.IsEmpty())
return existing_instance;
instance->ref();
// Instantiate the V8 object and remember it
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::SVGELEMENTINSTANCE,
V8ClassIndex::SVGELEMENTINSTANCE,
instance);
if (!result.IsEmpty()) {
// Only update the DOM SVG element map if the result is non-empty.
dom_svg_element_instance_map().set(instance,
v8::Persistent<v8::Object>::New(result));
}
return result;
}
// SVG non-node elements may have a reference to a context node which
// should be notified when the element is change
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj);
// Map of SVG objects with contexts to V8 objects
static DOMWrapperMap<void>& dom_svg_object_with_context_map() {
static DOMWrapperMap<void>
static_dom_svg_object_with_context_map(&WeakSVGObjectWithContext);
return static_dom_svg_object_with_context_map;
}
// Map of SVG objects with contexts to their contexts
static HashMap<void*, SVGElement*>& svg_object_to_context_map()
{
static HashMap<void*, SVGElement*> static_svg_object_to_context_map;
return static_svg_object_to_context_map;
}
v8::Handle<v8::Value> V8Proxy::SVGObjectWithContextToV8Object(
V8ClassIndex::V8WrapperType type, void* object)
{
if (!object)
return v8::Null();
v8::Persistent<v8::Object> result =
dom_svg_object_with_context_map().get(object);
if (!result.IsEmpty()) return result;
// Special case: SVGPathSegs need to be downcast to their real type
if (type == V8ClassIndex::SVGPATHSEG)
type = V8Custom::DowncastSVGPathSeg(object);
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, object);
if (!v8obj.IsEmpty()) {
result = v8::Persistent<v8::Object>::New(v8obj);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(object)->ref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(object)->ref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
dom_svg_object_with_context_map().set(object, result);
}
return result;
}
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope handle_scope;
ASSERT(dom_svg_object_with_context_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
dom_svg_object_with_context_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(dom_obj)->deref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
void V8Proxy::SetSVGContext(void* obj, SVGElement* context)
{
SVGElement* old_context = svg_object_to_context_map().get(obj);
if (old_context == context)
return;
if (old_context)
old_context->deref();
if (context)
context->ref();
svg_object_to_context_map().set(obj, context);
}
SVGElement* V8Proxy::GetSVGContext(void* obj)
{
return svg_object_to_context_map().get(obj);
}
#endif
// Called when obj is near death (not reachable from JS roots)
// It is time to remove the entry from the table and dispose
// the handle.
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj) {
v8::HandleScope scope;
ASSERT(GetDOMObjectMap().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
GetDOMObjectMap().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope scope;
ASSERT(GetActiveDOMObjectMap().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
GetActiveDOMObjectMap().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* param)
{
Node* node = static_cast<Node*>(param);
ASSERT(GetDOMNodeMap().contains(node));
GetDOMNodeMap().forget(node);
node->deref();
}
// A map from a DOM node to its JS wrapper, the wrapper
// is kept as a strong reference to survive GCs.
static DOMObjectMap& gc_protected_map() {
static DOMObjectMap static_gc_protected_map;
return static_gc_protected_map;
}
// static
void V8Proxy::GCProtect(void* dom_object)
{
if (!dom_object)
return;
if (gc_protected_map().contains(dom_object))
return;
if (!GetDOMObjectMap().contains(dom_object))
return;
// Create a new (strong) persistent handle for the object.
v8::Persistent<v8::Object> wrapper = GetDOMObjectMap().get(dom_object);
if (wrapper.IsEmpty()) return;
gc_protected_map().set(dom_object, *v8::Persistent<v8::Object>::New(wrapper));
}
// static
void V8Proxy::GCUnprotect(void* dom_object)
{
if (!dom_object)
return;
if (!gc_protected_map().contains(dom_object))
return;
// Dispose the strong reference.
v8::Persistent<v8::Object> wrapper(gc_protected_map().take(dom_object));
wrapper.Dispose();
}
// Create object groups for DOM tree nodes.
static void GCPrologue()
{
v8::HandleScope scope;
#ifndef NDEBUG
EnumerateDOMObjectMap(GetDOMObjectMap().impl());
#endif
// Run through all objects with possible pending activity making their
// wrappers non weak if there is pending activity.
DOMObjectMap active_map = GetActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
ASSERT(wrapper.IsWeak());
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) \
wrapper.ClearWeak(); \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
// Additional handling of message port ensuring that entangled ports also
// have their wrappers entangled. This should ideally be handled when the
// ports are actually entangled in MessagePort::entangle, but to avoid
// forking MessagePort.* this is postponed to GC time. Having this postponed
// has the drawback that the wrappers are "entangled/unentangled" for each
// GC even though their entnaglement most likely is still the same.
if (type == V8ClassIndex::MESSAGEPORT) {
// Get the port and its entangled port.
MessagePort* port1 = static_cast<MessagePort*>(obj);
MessagePort* port2 = port1->entangledPort();
if (port2 != NULL) {
// As ports are always entangled in pairs only perform the entanglement
// once for each pair (see ASSERT in MessagePort::unentangle()).
if (port1 < port2) {
v8::Handle<v8::Value> port1_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
v8::Handle<v8::Value> port2_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port2);
ASSERT(port1_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port1_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port2_wrapper);
ASSERT(port2_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port2_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port1_wrapper);
}
} else {
// Remove the wrapper entanglement when a port is not entangled.
if (V8Proxy::DOMObjectHasJSWrapper(port1)) {
v8::Handle<v8::Value> wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
ASSERT(wrapper->IsObject());
v8::Handle<v8::Object>::Cast(wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, v8::Undefined());
}
}
}
}
// Create object groups.
typedef std::pair<uintptr_t, Node*> GrouperPair;
typedef Vector<GrouperPair> GrouperList;
DOMNodeMap node_map = GetDOMNodeMap().impl();
GrouperList grouper;
grouper.reserveCapacity(node_map.size());
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
// If the node is in document, put it in the ownerDocument's object group.
//
// If an image element was created by JavaScript "new Image",
// it is not in a document. However, if the load event has not
// been fired (still onloading), it is treated as in the document.
//
// Otherwise, the node is put in an object group identified by the root
// elment of the tree to which it belongs.
uintptr_t group_id;
if (node->inDocument() ||
(node->hasTagName(HTMLNames::imgTag) &&
!static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent())) {
group_id = reinterpret_cast<uintptr_t>(node->document());
} else {
Node* root = node;
while (root->parent())
root = root->parent();
// If the node is alone in its DOM tree (doesn't have a parent or any
// children) then the group will be filtered out later anyway.
if (root == node && !node->hasChildNodes())
continue;
group_id = reinterpret_cast<uintptr_t>(root);
}
grouper.append(GrouperPair(group_id, node));
}
// Group by sorting by the group id. This will use the std::pair operator<,
// which will really sort by both the group id and the Node*. However the
// Node* is only involved to sort within a group id, so it will be fine.
std::sort(grouper.begin(), grouper.end());
// TODO(deanm): Should probably work in iterators here, but indexes were
// easier for my simple mind.
for (size_t i = 0; i < grouper.size(); ) {
// Seek to the next key (or the end of the list).
size_t next_key_index = grouper.size();
for (size_t j = i; j < grouper.size(); ++j) {
if (grouper[i].first != grouper[j].first) {
next_key_index = j;
break;
}
}
ASSERT(next_key_index > i);
// We only care about a group if it has more than one object. If it only
// has one object, it has nothing else that needs to be kept alive.
if (next_key_index - i <= 1) {
i = next_key_index;
continue;
}
Vector<v8::Persistent<v8::Value> > group;
group.reserveCapacity(next_key_index - i);
for (; i < next_key_index; ++i) {
v8::Persistent<v8::Value> wrapper =
GetDOMNodeMap().get(grouper[i].second);
if (!wrapper.IsEmpty())
group.append(wrapper);
}
if (group.size() > 1)
v8::V8::AddObjectGroup(&group[0], group.size());
ASSERT(i == next_key_index);
}
}
static void GCEpilogue()
{
v8::HandleScope scope;
// Run through all objects with pending activity making their wrappers weak
// again.
DOMObjectMap active_map = GetActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) { \
ASSERT(!wrapper.IsWeak()); \
wrapper.MakeWeak(impl, &WeakActiveDOMObjectCallback); \
} \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
#ifndef NDEBUG
// Check all survivals are weak.
EnumerateDOMObjectMap(GetDOMObjectMap().impl());
EnumerateDOMNodeMap(GetDOMNodeMap().impl());
EnumerateDOMObjectMap(gc_protected_map());
EnumerateGlobalHandles();
#undef USE_VAR
#endif
}
typedef HashMap<int, v8::FunctionTemplate*> FunctionTemplateMap;
bool AllowAllocation::m_current = false;
// JavaScriptConsoleMessages encapsulate everything needed to
// log messages originating from JavaScript to the Chrome console.
class JavaScriptConsoleMessage {
public:
JavaScriptConsoleMessage(const String& str,
const String& sourceID,
unsigned lineNumber)
: m_string(str)
, m_sourceID(sourceID)
, m_lineNumber(lineNumber) { }
void AddToPage(Page* page) const;
private:
const String m_string;
const String m_sourceID;
const unsigned m_lineNumber;
};
void JavaScriptConsoleMessage::AddToPage(Page* page) const
{
ASSERT(page);
Console* console = page->mainFrame()->domWindow()->console();
console->addMessage(JSMessageSource, ErrorMessageLevel, m_string, m_lineNumber, m_sourceID);
}
// The ConsoleMessageManager handles all console messages that stem
// from JavaScript. It keeps a list of messages that have been delayed but
// it makes sure to add all messages to the console in the right order.
class ConsoleMessageManager {
public:
// Add a message to the console. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void AddMessage(Page* page, const JavaScriptConsoleMessage& message);
// Add a message to the console but delay the reporting until it
// is safe to do so: Either when we leave JavaScript execution or
// when adding other console messages. The primary purpose of this
// method is to avoid calling into V8 to handle console messages
// when the VM is in a state that does not support GCs or allocations.
// Delayed messages are always reported in the page corresponding
// to the active context.
static void AddDelayedMessage(const JavaScriptConsoleMessage& message);
// Process any delayed messages. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void ProcessDelayedMessages();
private:
// All delayed messages are stored in this vector. If the vector
// is NULL, there are no delayed messages.
static Vector<JavaScriptConsoleMessage>* m_delayed;
};
Vector<JavaScriptConsoleMessage>* ConsoleMessageManager::m_delayed = NULL;
void ConsoleMessageManager::AddMessage(
Page* page,
const JavaScriptConsoleMessage& message)
{
// Process any delayed messages to make sure that messages
// appear in the right order in the console.
ProcessDelayedMessages();
message.AddToPage(page);
}
void ConsoleMessageManager::AddDelayedMessage(const JavaScriptConsoleMessage& message)
{
if (!m_delayed)
// Allocate a vector for the delayed messages. Will be
// deallocated when the delayed messages are processed
// in ProcessDelayedMessages().
m_delayed = new Vector<JavaScriptConsoleMessage>();
m_delayed->append(message);
}
void ConsoleMessageManager::ProcessDelayedMessages()
{
// If we have a delayed vector it cannot be empty.
if (!m_delayed)
return;
ASSERT(!m_delayed->isEmpty());
// Add the delayed messages to the page of the active
// context. If that for some bizarre reason does not
// exist, we clear the list of delayed messages to avoid
// posting messages. We still deallocate the vector.
Frame* frame = V8Proxy::retrieveActiveFrame();
Page* page = NULL;
if (frame)
page = frame->page();
if (!page)
m_delayed->clear();
// Iterate through all the delayed messages and add them
// to the console.
const int size = m_delayed->size();
for (int i = 0; i < size; i++) {
m_delayed->at(i).AddToPage(page);
}
// Deallocate the delayed vector.
delete m_delayed;
m_delayed = NULL;
}
// Convenience class for ensuring that delayed messages in the
// ConsoleMessageManager are processed quickly.
class ConsoleMessageScope {
public:
ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
~ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
};
void log_info(Frame* frame, const String& msg, const String& url)
{
Page* page = frame->page();
if (!page)
return;
JavaScriptConsoleMessage message(msg, url, 0);
ConsoleMessageManager::AddMessage(page, message);
}
static void HandleConsoleMessage(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data)
{
// Use the frame where JavaScript is called from.
Frame* frame = V8Proxy::retrieveActiveFrame();
if (!frame)
return;
Page* page = frame->page();
if (!page)
return;
v8::Handle<v8::String> errorMessageString = message->Get();
ASSERT(!errorMessageString.IsEmpty());
String errorMessage = ToWebCoreString(errorMessageString);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool useURL = (resourceName.IsEmpty() || !resourceName->IsString());
String resourceNameString = (useURL)
? frame->document()->url()
: ToWebCoreString(resourceName);
JavaScriptConsoleMessage consoleMessage(errorMessage,
resourceNameString,
message->GetLineNumber());
ConsoleMessageManager::AddMessage(page, consoleMessage);
}
enum DelayReporting {
REPORT_LATER,
REPORT_NOW
};
static void ReportUnsafeAccessTo(Frame* target, DelayReporting delay)
{
ASSERT(target);
Document* targetDocument = target->document();
if (!targetDocument)
return;
Frame* source = V8Proxy::retrieveActiveFrame();
if (!source || !source->document())
return; // Ignore error if the source document is gone.
Document* sourceDocument = source->document();
// FIXME: This error message should contain more specifics of why the same
// origin check has failed.
String str = String::format("Unsafe JavaScript attempt to access frame "
"with URL %s from frame with URL %s. "
"Domains, protocols and ports must match.\n",
targetDocument->url().string().utf8().data(),
sourceDocument->url().string().utf8().data());
// Build a console message with fake source ID and line number.
const String kSourceID = "";
const int kLineNumber = 1;
JavaScriptConsoleMessage message(str, kSourceID, kLineNumber);
if (delay == REPORT_NOW) {
// NOTE(tc): Apple prints the message in the target page, but it seems like
// it should be in the source page. Even for delayed messages, we put it in
// the source page; see ConsoleMessageManager::ProcessDelayedMessages().
ConsoleMessageManager::AddMessage(source->page(), message);
} else {
ASSERT(delay == REPORT_LATER);
// We cannot safely report the message eagerly, because this may cause
// allocations and GCs internally in V8 and we cannot handle that at this
// point. Therefore we delay the reporting.
ConsoleMessageManager::AddDelayedMessage(message);
}
}
static void ReportUnsafeJavaScriptAccess(v8::Local<v8::Object> host,
v8::AccessType type,
v8::Local<v8::Value> data)
{
Frame* target = V8Custom::GetTargetFrame(host, data);
if (target)
ReportUnsafeAccessTo(target, REPORT_LATER);
}
static void HandleFatalErrorInV8()
{
// TODO: We temporarily deal with V8 internal error situations
// such as out-of-memory by crashing the renderer.
CRASH();
}
static void ReportFatalErrorInV8(const char* location, const char* message)
{
// V8 is shutdown, we cannot use V8 api.
// The only thing we can do is to disable JavaScript.
// TODO: clean up V8Proxy and disable JavaScript.
printf("V8 error: %s (%s)\n", message, location);
HandleFatalErrorInV8();
}
V8Proxy::~V8Proxy()
{
clearForClose();
DestroyGlobal();
}
void V8Proxy::DestroyGlobal()
{
if (!m_global.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_global);
#endif
m_global.Dispose();
m_global.Clear();
}
}
bool V8Proxy::DOMObjectHasJSWrapper(void* obj) {
return GetDOMObjectMap().contains(obj) ||
GetActiveDOMObjectMap().contains(obj);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
ASSERT(false);
#undef MAKE_CASE
default: break;
}
#endif
GetDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForActiveDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE: break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default: ASSERT(false);
#undef MAKE_CASE
}
#endif
GetActiveDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased node's ref count.
void V8Proxy::SetJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
GetDOMNodeMap().set(node, wrapper);
}
PassRefPtr<EventListener> V8Proxy::createInlineEventListener(
const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#if ENABLE(SVG)
PassRefPtr<EventListener> V8Proxy::createSVGEventHandler(const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#endif
// Event listeners
static V8EventListener* FindEventListenerInList(V8EventListenerList& list,
v8::Local<v8::Value> listener,
bool isInline)
{
ASSERT(v8::Context::InContext());
if (!listener->IsObject())
return 0;
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
V8EventListener* el = *p;
v8::Local<v8::Object> wrapper = el->getListenerObject();
ASSERT(!wrapper.IsEmpty());
// Since the listener is an object, it is safe to compare for
// strict equality (in the JS sense) by doing a simple equality
// check using the == operator on the handles. This is much,
// much faster than calling StrictEquals through the API in
// the negative case.
if (el->isInline() == isInline && listener == wrapper)
return el;
++p;
}
return 0;
}
// Find an existing wrapper for a JS event listener in the map.
PassRefPtr<V8EventListener> V8Proxy::FindV8EventListener(v8::Local<v8::Value> listener,
bool isInline)
{
return FindEventListenerInList(m_event_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateV8EventListener(v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_event_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8EventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_event_listeners.push_back(new_listener.get());
return new_listener;
}
// Object event listeners (such as XmlHttpRequest and MessagePort) are
// different from listeners on DOM nodes. An object event listener wrapper
// only holds a weak reference to the JS function. A strong reference can
// create a cycle.
//
// The lifetime of these objects is bounded by the life time of its JS
// wrapper. So we can create a hidden reference from the JS wrapper to
// to its JS function.
//
// (map)
// XHR <---------- JS_wrapper
// | (hidden) : ^
// V V : (may reachable by closure)
// V8_listener --------> JS_function
// (weak) <-- may create a cycle if it is strong
//
// The persistent reference is made weak in the constructor
// of V8ObjectEventListener.
PassRefPtr<V8EventListener> V8Proxy::FindObjectEventListener(
v8::Local<v8::Value> listener, bool isInline)
{
return FindEventListenerInList(m_xhr_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateObjectEventListener(
v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_xhr_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8ObjectEventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_xhr_listeners.push_back(new_listener.get());
return new_listener.release();
}
static void RemoveEventListenerFromList(V8EventListenerList& list,
V8EventListener* listener)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
if (*p == listener) {
list.erase(p);
return;
}
++p;
}
}
void V8Proxy::RemoveV8EventListener(V8EventListener* listener)
{
RemoveEventListenerFromList(m_event_listeners, listener);
}
void V8Proxy::RemoveObjectEventListener(V8ObjectEventListener* listener)
{
RemoveEventListenerFromList(m_xhr_listeners, listener);
}
static void DisconnectEventListenersInList(V8EventListenerList& list)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
(*p)->disconnectFrame();
++p;
}
list.clear();
}
void V8Proxy::DisconnectEventListeners()
{
DisconnectEventListenersInList(m_event_listeners);
DisconnectEventListenersInList(m_xhr_listeners);
}
v8::Handle<v8::Script> V8Proxy::CompileScript(v8::Handle<v8::String> code,
const String& fileName,
int baseLine)
{
const uint16_t* fileNameString = FromWebCoreString(fileName);
v8::Handle<v8::String> name =
v8::String::New(fileNameString, fileName.length());
v8::Handle<v8::Integer> line = v8::Integer::New(baseLine);
v8::ScriptOrigin origin(name, line);
v8::Handle<v8::Script> script = v8::Script::Compile(code, &origin);
return script;
}
bool V8Proxy::HandleOutOfMemory()
{
v8::Local<v8::Context> context = v8::Context::GetCurrent();
if (!context->HasOutOfMemoryException())
return false;
// Warning, error, disable JS for this frame?
Frame* frame = V8Proxy::retrieveFrame(context);
V8Proxy* proxy = V8Proxy::retrieve(frame);
// Clean m_context, and event handlers.
proxy->clearForClose();
// Destroy the global object.
proxy->DestroyGlobal();
ChromiumBridge::notifyJSOutOfMemory(frame);
// Disable JS.
Settings* settings = frame->settings();
ASSERT(settings);
settings->setJavaScriptEnabled(false);
return true;
}
void V8Proxy::evaluateInNewContext(const Vector<ScriptSourceCode>& sources)
{
InitContextIfNeeded();
v8::HandleScope handleScope;
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> windowContext = m_context;
v8::Handle<v8::Object> windowGlobal = windowContext->Global();
v8::Handle<v8::Value> windowWrapper =
V8Proxy::LookupDOMWrapper(V8ClassIndex::DOMWINDOW, windowGlobal);
ASSERT(V8Proxy::DOMWrapperToNative<DOMWindow>(windowWrapper) ==
m_frame->domWindow());
v8::Persistent<v8::Context> context =
createNewContext(v8::Handle<v8::Object>());
v8::Context::Scope context_scope(context);
v8::Handle<v8::Object> global = context->Global();
v8::Handle<v8::String> implicitProtoString = v8::String::New("__proto__");
global->Set(implicitProtoString, windowWrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), windowGlobal);
// Run code in the new context.
for (size_t i = 0; i < sources.size(); ++i)
evaluate(sources[i], 0);
// Using the default security token means that the canAccess is always
// called, which is slow.
// TODO(aa): Use tokens where possible. This will mean keeping track of all
// created contexts so that they can all be updated when the document domain
// changes.
context->UseDefaultSecurityToken();
context.Dispose();
}
v8::Local<v8::Value> V8Proxy::evaluate(const ScriptSourceCode& source, Node* n)
{
ASSERT(v8::Context::InContext());
// Compile the script.
v8::Local<v8::String> code = v8ExternalString(source.source());
ChromiumBridge::traceEventBegin("v8.compile", n, "");
// NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at
// 1, whereas v8 starts at 0.
v8::Handle<v8::Script> script = CompileScript(code, source.url(),
source.startLine() - 1);
ChromiumBridge::traceEventEnd("v8.compile", n, "");
ChromiumBridge::traceEventBegin("v8.run", n, "");
v8::Local<v8::Value> result;
{
// Isolate exceptions that occur when executing the code. These
// exceptions should not interfere with javascript code we might
// evaluate from C++ when returning from here
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
// Set inlineCode to true for <a href="javascript:doSomething()">
// and false for <script>doSomething</script>. We make a rough guess at
// this based on whether the script source has a URL.
result = RunScript(script, source.url().string().isNull());
}
ChromiumBridge::traceEventEnd("v8.run", n, "");
return result;
}
v8::Local<v8::Value> V8Proxy::RunScript(v8::Handle<v8::Script> script,
bool inline_code)
{
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Compute the source string and prevent against infinite recursion.
if (m_recursion >= kMaxRecursionDepth) {
v8::Local<v8::String> code =
v8ExternalString("throw RangeError('Recursion too deep')");
// TODO(kasperl): Ideally, we should be able to re-use the origin of the
// script passed to us as the argument instead of using an empty string
// and 0 baseLine.
script = CompileScript(code, "", 0);
}
if (HandleOutOfMemory())
ASSERT(script.IsEmpty());
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Save the previous value of the inlineCode flag and update the flag for
// the duration of the script invocation.
bool previous_inline_code = inlineCode();
setInlineCode(inline_code);
// Run the script and keep track of the current recursion depth.
v8::Local<v8::Value> result;
{ ConsoleMessageScope scope;
m_recursion++;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = script->Run();
m_recursion--;
}
if (HandleOutOfMemory())
ASSERT(result.IsEmpty());
// Handle V8 internal error situation (Out-of-memory).
if (result.IsEmpty())
return v8::Local<v8::Value>();
// Restore inlineCode flag.
setInlineCode(previous_inline_code);
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Value> V8Proxy::CallFunction(v8::Handle<v8::Function> function,
v8::Handle<v8::Object> receiver,
int argc,
v8::Handle<v8::Value> args[])
{
// For now, we don't put any artificial limitations on the depth
// of recursion that stems from calling functions. This is in
// contrast to the script evaluations.
v8::Local<v8::Value> result;
{
ConsoleMessageScope scope;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = function->Call(receiver, argc, args);
}
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Function> V8Proxy::GetConstructor(V8ClassIndex::V8WrapperType t)
{
ASSERT(ContextInitialized());
v8::Local<v8::Value> cached =
m_dom_constructor_cache->Get(v8::Integer::New(V8ClassIndex::ToInt(t)));
if (cached->IsFunction()) {
return v8::Local<v8::Function>::Cast(cached);
}
// Not in cache.
{
// Enter the context of the proxy to make sure that the
// function is constructed in the context corresponding to
// this proxy.
v8::Context::Scope scope(m_context);
v8::Handle<v8::FunctionTemplate> templ = GetTemplate(t);
// Getting the function might fail if we're running out of
// stack or memory.
v8::TryCatch try_catch;
v8::Local<v8::Function> value = templ->GetFunction();
if (value.IsEmpty())
return v8::Local<v8::Function>();
m_dom_constructor_cache->Set(v8::Integer::New(t), value);
// Hotmail fix, see comments in v8_proxy.h above
// m_dom_constructor_cache.
value->Set(v8::String::New("__proto__"), m_object_prototype);
return value;
}
}
// Get the string 'toString'.
static v8::Persistent<v8::String> GetToStringName() {
static v8::Persistent<v8::String> value;
if (value.IsEmpty())
value = v8::Persistent<v8::String>::New(v8::String::New("toString"));
return value;
}
static v8::Handle<v8::Value> ConstructorToString(const v8::Arguments& args) {
// The DOM constructors' toString functions grab the current toString
// for Functions by taking the toString function of itself and then
// calling it with the constructor as its receiver. This means that
// changes to the Function prototype chain or toString function are
// reflected when printing DOM constructors. The only wart is that
// changes to a DOM constructor's toString's toString will cause the
// toString of the DOM constructor itself to change. This is extremely
// obscure and unlikely to be a problem.
v8::Handle<v8::Value> val = args.Callee()->Get(GetToStringName());
if (!val->IsFunction()) return v8::String::New("");
return v8::Handle<v8::Function>::Cast(val)->Call(args.This(), 0, NULL);
}
v8::Persistent<v8::FunctionTemplate> V8Proxy::GetTemplate(
V8ClassIndex::V8WrapperType type)
{
v8::Persistent<v8::FunctionTemplate>* cache_cell =
V8ClassIndex::GetCache(type);
if (!(*cache_cell).IsEmpty())
return *cache_cell;
// not found
FunctionTemplateFactory factory = V8ClassIndex::GetFactory(type);
v8::Persistent<v8::FunctionTemplate> desc = factory();
// DOM constructors are functions and should print themselves as such.
// However, we will later replace their prototypes with Object
// prototypes so we need to explicitly override toString on the
// instance itself. If we later make DOM constructors full objects
// we can give them class names instead and Object.prototype.toString
// will work so we can remove this code.
static v8::Persistent<v8::FunctionTemplate> to_string_template;
if (to_string_template.IsEmpty()) {
to_string_template = v8::Persistent<v8::FunctionTemplate>::New(
v8::FunctionTemplate::New(ConstructorToString));
}
desc->Set(GetToStringName(), to_string_template);
switch (type) {
case V8ClassIndex::CSSSTYLEDECLARATION:
// The named property handler for style declarations has a
// setter. Therefore, the interceptor has to be on the object
// itself and not on the prototype object.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(CSSStyleDeclaration),
USE_NAMED_PROPERTY_SETTER(CSSStyleDeclaration));
setCollectionStringOrNullIndexedGetter<CSSStyleDeclaration>(desc);
break;
case V8ClassIndex::CSSRULELIST:
setCollectionIndexedGetter<CSSRuleList, CSSRule>(desc,
V8ClassIndex::CSSRULE);
break;
case V8ClassIndex::CSSVALUELIST:
setCollectionIndexedGetter<CSSValueList, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::CSSVARIABLESDECLARATION:
setCollectionStringOrNullIndexedGetter<CSSVariablesDeclaration>(desc);
break;
case V8ClassIndex::WEBKITCSSTRANSFORMVALUE:
setCollectionIndexedGetter<WebKitCSSTransformValue, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::UNDETECTABLEHTMLCOLLECTION:
desc->InstanceTemplate()->MarkAsUndetectable(); // fall through
case V8ClassIndex::HTMLCOLLECTION:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
setCollectionIndexedGetter<HTMLCollection, Node>(desc,
V8ClassIndex::NODE);
break;
case V8ClassIndex::HTMLOPTIONSCOLLECTION:
setCollectionNamedGetter<HTMLOptionsCollection, Node>(
desc,
V8ClassIndex::NODE);
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLOptionsCollection),
USE_INDEXED_PROPERTY_SETTER(HTMLOptionsCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
break;
case V8ClassIndex::HTMLSELECTELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
nodeCollectionNamedPropertyGetter<HTMLSelectElement>,
0,
0,
0,
0,
v8::Integer::New(V8ClassIndex::NODE));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
nodeCollectionIndexedPropertyGetter<HTMLSelectElement>,
USE_INDEXED_PROPERTY_SETTER(HTMLSelectElementCollection),
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLSelectElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::HTMLDOCUMENT: {
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLDocument),
0,
0,
USE_NAMED_PROPERTY_DELETER(HTMLDocument));
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
//
// Additionally, we add two extra internal fields for
// HTMLDocuments to implement temporary shadowing of
// document.all. One field holds an object that is used as a
// marker. The other field holds the marker object if
// document.all is not shadowed and some other value if
// document.all is shadowed.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kHTMLDocumentInternalFieldCount);
break;
}
#if ENABLE(SVG)
case V8ClassIndex::SVGDOCUMENT: // fall through
#endif
case V8ClassIndex::DOCUMENT: {
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kDocumentMinimumInternalFieldCount);
break;
}
case V8ClassIndex::HTMLAPPLETELEMENT: // fall through
case V8ClassIndex::HTMLEMBEDELEMENT: // fall through
case V8ClassIndex::HTMLOBJECTELEMENT:
// HTMLAppletElement, HTMLEmbedElement and HTMLObjectElement are
// inherited from HTMLPlugInElement, and they share the same property
// handling code.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLPlugInElement),
USE_NAMED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLPlugInElement),
USE_INDEXED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLPlugInElement));
break;
case V8ClassIndex::HTMLFRAMESETELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFrameSetElement));
break;
case V8ClassIndex::HTMLFORMELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFormElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLFormElement),
0,
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLFormElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::CANVASPIXELARRAY:
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(CanvasPixelArray),
USE_INDEXED_PROPERTY_SETTER(CanvasPixelArray));
break;
case V8ClassIndex::STYLESHEET: // fall through
case V8ClassIndex::CSSSTYLESHEET: {
// We add an extra internal field to hold a reference to
// the owner node.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kStyleSheetInternalFieldCount);
break;
}
case V8ClassIndex::MEDIALIST:
setCollectionStringOrNullIndexedGetter<MediaList>(desc);
break;
case V8ClassIndex::MIMETYPEARRAY:
setCollectionIndexedAndNamedGetters<MimeTypeArray, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::NAMEDNODEMAP:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NamedNodeMap));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(NamedNodeMap),
0,
0,
0,
collectionIndexedPropertyEnumerator<NamedNodeMap>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::NODELIST:
setCollectionIndexedGetter<NodeList, Node>(desc, V8ClassIndex::NODE);
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NodeList));
break;
case V8ClassIndex::PLUGIN:
setCollectionIndexedAndNamedGetters<Plugin, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::PLUGINARRAY:
setCollectionIndexedAndNamedGetters<PluginArray, Plugin>(
desc,
V8ClassIndex::PLUGIN);
break;
case V8ClassIndex::STYLESHEETLIST:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(StyleSheetList));
setCollectionIndexedGetter<StyleSheetList, StyleSheet>(
desc,
V8ClassIndex::STYLESHEET);
break;
case V8ClassIndex::DOMWINDOW: {
v8::Local<v8::Signature> default_signature = v8::Signature::New(desc);
desc->PrototypeTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(DOMWindow));
desc->PrototypeTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(DOMWindow));
desc->SetHiddenPrototype(true);
// Reserve spaces for references to location and navigator objects.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
// Set access check callbacks, but turned off initially.
// When a context is detached from a frame, turn on the access check.
// Turning on checks also invalidates inline caches of the object.
instance_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW),
false);
break;
}
case V8ClassIndex::LOCATION: {
// For security reasons, these functions are on the instance
// instead of on the prototype object to insure that they cannot
// be overwritten.
v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate();
instance->SetAccessor(
v8::String::New("reload"),
V8Custom::v8LocationReloadAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("replace"),
V8Custom::v8LocationReplaceAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("assign"),
V8Custom::v8LocationAssignAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
break;
}
case V8ClassIndex::HISTORY: {
break;
}
case V8ClassIndex::MESSAGECHANNEL: {
// Reserve two more internal fields for referencing the port1
// and port2 wrappers. This ensures that the port wrappers are
// kept alive when the channel wrapper is.
desc->SetCallHandler(USE_CALLBACK(MessageChannelConstructor));
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessageChannelInternalFieldCount);
break;
}
case V8ClassIndex::MESSAGEPORT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessagePortInternalFieldCount);
break;
}
#if ENABLE(WORKERS)
case V8ClassIndex::WORKER: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(WorkerConstructor));
break;
}
case V8ClassIndex::WORKERCONTEXT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerContextInternalFieldCount);
break;
}
#endif // WORKERS
// The following objects are created from JavaScript.
case V8ClassIndex::DOMPARSER:
desc->SetCallHandler(USE_CALLBACK(DOMParserConstructor));
break;
case V8ClassIndex::WEBKITCSSMATRIX:
desc->SetCallHandler(USE_CALLBACK(WebKitCSSMatrixConstructor));
break;
case V8ClassIndex::WEBKITPOINT:
desc->SetCallHandler(USE_CALLBACK(WebKitPointConstructor));
break;
case V8ClassIndex::XMLSERIALIZER:
desc->SetCallHandler(USE_CALLBACK(XMLSerializerConstructor));
break;
case V8ClassIndex::XMLHTTPREQUEST: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(XMLHttpRequestConstructor));
break;
}
case V8ClassIndex::XMLHTTPREQUESTUPLOAD: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
break;
}
case V8ClassIndex::XPATHEVALUATOR:
desc->SetCallHandler(USE_CALLBACK(XPathEvaluatorConstructor));
break;
case V8ClassIndex::XSLTPROCESSOR:
desc->SetCallHandler(USE_CALLBACK(XSLTProcessorConstructor));
break;
default:
break;
}
*cache_cell = desc;
return desc;
}
bool V8Proxy::ContextInitialized()
{
// m_context, m_global, m_object_prototype, and
// m_dom_constructor_cache should all be non-empty if m_context is
// non-empty.
ASSERT(m_context.IsEmpty() || !m_global.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_object_prototype.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_dom_constructor_cache.IsEmpty());
return !m_context.IsEmpty();
}
DOMWindow* V8Proxy::retrieveWindow()
{
// TODO: This seems very fragile. How do we know that the global object
// from the current context is something sensible? Do we need to use the
// last entered here? Who calls this?
return retrieveWindow(v8::Context::GetCurrent());
}
DOMWindow* V8Proxy::retrieveWindow(v8::Handle<v8::Context> context)
{
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
return ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, global);
}
Frame* V8Proxy::retrieveFrame(v8::Handle<v8::Context> context)
{
return retrieveWindow(context)->frame();
}
Frame* V8Proxy::retrieveActiveFrame()
{
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return 0;
return retrieveFrame(context);
}
Frame* V8Proxy::retrieveFrame()
{
DOMWindow* window = retrieveWindow();
return window ? window->frame() : 0;
}
V8Proxy* V8Proxy::retrieve()
{
DOMWindow* window = retrieveWindow();
ASSERT(window);
return retrieve(window->frame());
}
V8Proxy* V8Proxy::retrieve(Frame* frame)
{
if (!frame)
return 0;
return frame->script()->isEnabled() ? frame->script()->proxy() : 0;
}
V8Proxy* V8Proxy::retrieve(ScriptExecutionContext* context)
{
if (!context->isDocument())
return 0;
return retrieve(static_cast<Document*>(context)->frame());
}
void V8Proxy::disconnectFrame()
{
// disconnect all event listeners
DisconnectEventListeners();
}
bool V8Proxy::isEnabled()
{
Settings* settings = m_frame->settings();
if (!settings)
return false;
// In the common case, JavaScript is enabled and we're done.
if (settings->isJavaScriptEnabled())
return true;
// If JavaScript has been disabled, we need to look at the frame to tell
// whether this script came from the web or the embedder. Scripts from the
// embedder are safe to run, but scripts from the other sources are
// disallowed.
Document* document = m_frame->document();
if (!document)
return false;
SecurityOrigin* origin = document->securityOrigin();
if (origin->protocol().isEmpty())
return false; // Uninitialized document
if (origin->protocol() == "http" || origin->protocol() == "https")
return false; // Web site
// TODO(darin): the following are application decisions, and they should
// not be made at this layer. instead, we should bridge out to the
// embedder to allow them to override policy here.
if (origin->protocol() == ChromiumBridge::uiResourceProtocol())
return true; // Embedder's scripts are ok to run
// If the scheme is ftp: or file:, an empty file name indicates a directory
// listing, which requires JavaScript to function properly.
const char* kDirProtocols[] = { "ftp", "file" };
for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
if (origin->protocol() == kDirProtocols[i]) {
const KURL& url = document->url();
return url.pathAfterLastSlash() == url.pathEnd();
}
}
return false; // Other protocols fall through to here
}
void V8Proxy::UpdateDocumentWrapper(v8::Handle<v8::Value> wrapper) {
ClearDocumentWrapper();
ASSERT(m_document.IsEmpty());
m_document = v8::Persistent<v8::Value>::New(wrapper);
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_document);
#endif
}
void V8Proxy::ClearDocumentWrapper()
{
if (!m_document.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_document);
#endif
m_document.Dispose();
m_document.Clear();
}
}
void V8Proxy::DisposeContextHandles() {
if (!m_context.IsEmpty()) {
m_context.Dispose();
m_context.Clear();
}
if (!m_dom_constructor_cache.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_dom_constructor_cache);
#endif
m_dom_constructor_cache.Dispose();
m_dom_constructor_cache.Clear();
}
if (!m_object_prototype.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_object_prototype);
#endif
m_object_prototype.Dispose();
m_object_prototype.Clear();
}
}
void V8Proxy::clearForClose()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle_scope;
ClearDocumentWrapper();
DisposeContextHandles();
}
}
void V8Proxy::clearForNavigation()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle;
ClearDocumentWrapper();
v8::Context::Scope context_scope(m_context);
// Turn on access check on the old DOMWindow wrapper.
v8::Handle<v8::Object> wrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, m_global);
ASSERT(!wrapper.IsEmpty());
wrapper->TurnOnAccessCheck();
// disconnect all event listeners
DisconnectEventListeners();
// Separate the context from its global object.
m_context->DetachGlobal();
DisposeContextHandles();
// Reinitialize the context so the global object points to
// the new DOM window.
InitContextIfNeeded();
}
}
void V8Proxy::SetSecurityToken() {
Document* document = m_frame->document();
// Setup security origin and security token
if (!document) {
m_context->UseDefaultSecurityToken();
return;
}
// Ask the document's SecurityOrigin to generate a security token.
// If two tokens are equal, then the SecurityOrigins canAccess each other.
// If two tokens are not equal, then we have to call canAccess.
// Note: we can't use the HTTPOrigin if it was set from the DOM.
SecurityOrigin* origin = document->securityOrigin();
String token;
if (!origin->domainWasSetInDOM())
token = document->securityOrigin()->toString();
// An empty token means we always have to call canAccess. In this case, we
// use the global object as the security token to avoid calling canAccess
// when a script accesses its own objects.
if (token.isEmpty()) {
m_context->UseDefaultSecurityToken();
return;
}
CString utf8_token = token.utf8();
// NOTE: V8 does identity comparison in fast path, must use a symbol
// as the security token.
m_context->SetSecurityToken(
v8::String::NewSymbol(utf8_token.data(), utf8_token.length()));
}
void V8Proxy::updateDocument()
{
if (!m_frame->document())
return;
if (m_global.IsEmpty()) {
ASSERT(m_context.IsEmpty());
return;
}
{
v8::HandleScope scope;
SetSecurityToken();
}
}
void V8Proxy::updateSecurityOrigin()
{
v8::HandleScope scope;
SetSecurityToken();
}
// Same origin policy implementation:
//
// Same origin policy prevents JS code from domain A access JS & DOM objects
// in a different domain B. There are exceptions and several objects are
// accessible by cross-domain code. For example, the window.frames object is
// accessible by code from a different domain, but window.document is not.
//
// The binding code sets security check callbacks on a function template,
// and accessing instances of the template calls the callback function.
// The callback function checks same origin policy.
//
// Callback functions are expensive. V8 uses a security token string to do
// fast access checks for the common case where source and target are in the
// same domain. A security token is a string object that represents
// the protocol/url/port of a domain.
//
// There are special cases where a security token matching is not enough.
// For example, JavaScript can set its domain to a super domain by calling
// document.setDomain(...). In these cases, the binding code can reset
// a context's security token to its global object so that the fast access
// check will always fail.
// Check if the current execution context can access a target frame.
// First it checks same domain policy using the lexical context
//
// This is equivalent to KJS::Window::allowsAccessFrom(ExecState*, String&).
bool V8Proxy::CanAccessPrivate(DOMWindow* target_window)
{
ASSERT(target_window);
String message;
DOMWindow* origin_window = retrieveWindow();
if (origin_window == target_window)
return true;
if (!origin_window)
return false;
// JS may be attempting to access the "window" object, which should be
// valid, even if the document hasn't been constructed yet.
// If the document doesn't exist yet allow JS to access the window object.
if (!origin_window->document())
return true;
const SecurityOrigin* active_security_origin = origin_window->securityOrigin();
const SecurityOrigin* target_security_origin = target_window->securityOrigin();
// We have seen crashes were the security origin of the target has not been
// initialized. Defend against that.
ASSERT(target_security_origin);
if (!target_security_origin)
return false;
if (active_security_origin->canAccess(target_security_origin))
return true;
// Allow access to a "about:blank" page if the dynamic context is a
// detached context of the same frame as the blank page.
if (target_security_origin->isEmpty() &&
origin_window->frame() == target_window->frame())
return true;
return false;
}
bool V8Proxy::CanAccessFrame(Frame* target, bool report_error)
{
// The subject is detached from a frame, deny accesses.
if (!target)
return false;
if (!CanAccessPrivate(target->domWindow())) {
if (report_error)
ReportUnsafeAccessTo(target, REPORT_NOW);
return false;
}
return true;
}
bool V8Proxy::CheckNodeSecurity(Node* node)
{
if (!node)
return false;
Frame* target = node->document()->frame();
if (!target)
return false;
return CanAccessFrame(target, true);
}
v8::Persistent<v8::Context> V8Proxy::createNewContext(
v8::Handle<v8::Object> global)
{
v8::Persistent<v8::Context> result;
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Persistent<v8::ObjectTemplate> globalTemplate =
V8DOMWindow::GetShadowObjectTemplate();
if (globalTemplate.IsEmpty())
return result;
// Install a security handler with V8.
globalTemplate->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
// Dynamically tell v8 about our extensions now.
const char** extensionNames = new const char*[m_extensions.size()];
int index = 0;
V8ExtensionList::iterator it = m_extensions.begin();
while (it != m_extensions.end()) {
extensionNames[index++] = (*it)->name();
++it;
}
v8::ExtensionConfiguration extensions(m_extensions.size(), extensionNames);
result = v8::Context::New(&extensions, globalTemplate, global);
delete [] extensionNames;
extensionNames = 0;
return result;
}
// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance. However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object. The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript. The javascript object that corresponds to a
// DOMWindow instance is the shadow object. When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
//
// To implement split-window, see
// 1) https://bugs.webkit.org/show_bug.cgi?id=17249
// 2) https://wiki.mozilla.org/Gecko:SplitWindow
// 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
// we need to split the shadow object further into two objects:
// an outer window and an inner window. The inner window is the hidden
// prototype of the outer window. The inner window is the default
// global object of the context. A variable declared in the global
// scope is a property of the inner window.
//
// The outer window sticks to a Frame, it is exposed to JavaScript
// via window.window, window.self, window.parent, etc. The outer window
// has a security token which is the domain. The outer window cannot
// have its own properties. window.foo = 'x' is delegated to the
// inner window.
//
// When a frame navigates to a new page, the inner window is cut off
// the outer window, and the outer window identify is preserved for
// the frame. However, a new inner window is created for the new page.
// If there are JS code holds a closure to the old inner window,
// it won't be able to reach the outer window via its global object.
void V8Proxy::InitContextIfNeeded()
{
// Bail out if the context has already been initialized.
if (!m_context.IsEmpty())
return;
// Setup the security handlers and message listener. This only has
// to be done once.
static bool v8_initialized = false;
if (!v8_initialized) {
// Tells V8 not to call the default OOM handler, binding code
// will handle it.
v8::V8::IgnoreOutOfMemoryException();
v8::V8::SetFatalErrorHandler(ReportFatalErrorInV8);
v8::V8::SetGlobalGCPrologueCallback(&GCPrologue);
v8::V8::SetGlobalGCEpilogueCallback(&GCEpilogue);
v8::V8::AddMessageListener(HandleConsoleMessage);
v8::V8::SetFailedAccessCheckCallbackFunction(ReportUnsafeJavaScriptAccess);
v8_initialized = true;
}
m_context = createNewContext(m_global);
if (m_context.IsEmpty())
return;
// Starting from now, use local context only.
v8::Local<v8::Context> context = GetContext();
v8::Context::Scope scope(context);
// Store the first global object created so we can reuse it.
if (m_global.IsEmpty()) {
m_global = v8::Persistent<v8::Object>::New(context->Global());
// Bail out if allocation of the first global objects fails.
if (m_global.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_global);
#endif
}
// Allocate strings used during initialization.
v8::Handle<v8::String> object_string = v8::String::New("Object");
v8::Handle<v8::String> prototype_string = v8::String::New("prototype");
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
// Bail out if allocation failed.
if (object_string.IsEmpty() ||
prototype_string.IsEmpty() ||
implicit_proto_string.IsEmpty()) {
DisposeContextHandles();
return;
}
// Allocate DOM constructor cache.
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(
m_global->Get(object_string));
m_object_prototype = v8::Persistent<v8::Value>::New(
object->Get(prototype_string));
m_dom_constructor_cache = v8::Persistent<v8::Array>::New(
v8::Array::New(V8ClassIndex::WRAPPER_TYPE_COUNT));
// Bail out if allocation failed.
if (m_object_prototype.IsEmpty() || m_dom_constructor_cache.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_object_prototype);
RegisterGlobalHandle(PROXY, this, m_dom_constructor_cache);
#endif
// Create a new JS window object and use it as the prototype for the
// shadow global object.
v8::Handle<v8::Function> window_constructor =
GetConstructor(V8ClassIndex::DOMWINDOW);
v8::Local<v8::Object> js_window =
SafeAllocation::NewInstance(window_constructor);
// Bail out if allocation failed.
if (js_window.IsEmpty()) {
DisposeContextHandles();
return;
}
DOMWindow* window = m_frame->domWindow();
// Wrap the window.
SetDOMWrapper(js_window,
V8ClassIndex::ToInt(V8ClassIndex::DOMWINDOW),
window);
window->ref();
V8Proxy::SetJSWrapperForDOMObject(window,
v8::Persistent<v8::Object>::New(js_window));
// Insert the window instance as the prototype of the shadow object.
v8::Handle<v8::Object> v8_global = context->Global();
v8_global->Set(implicit_proto_string, js_window);
SetSecurityToken();
m_frame->loader()->dispatchWindowObjectAvailable();
}
void V8Proxy::SetDOMException(int exception_code)
{
if (exception_code <= 0)
return;
ExceptionCodeDescription description;
getExceptionCodeDescription(exception_code, description);
v8::Handle<v8::Value> exception;
switch (description.type) {
case DOMExceptionType:
exception = ToV8Object(V8ClassIndex::DOMCOREEXCEPTION,
DOMCoreException::create(description));
break;
case RangeExceptionType:
exception = ToV8Object(V8ClassIndex::RANGEEXCEPTION,
RangeException::create(description));
break;
case EventExceptionType:
exception = ToV8Object(V8ClassIndex::EVENTEXCEPTION,
EventException::create(description));
break;
case XMLHttpRequestExceptionType:
exception = ToV8Object(V8ClassIndex::XMLHTTPREQUESTEXCEPTION,
XMLHttpRequestException::create(description));
break;
#if ENABLE(SVG)
case SVGExceptionType:
exception = ToV8Object(V8ClassIndex::SVGEXCEPTION,
SVGException::create(description));
break;
#endif
#if ENABLE(XPATH)
case XPathExceptionType:
exception = ToV8Object(V8ClassIndex::XPATHEXCEPTION,
XPathException::create(description));
break;
#endif
}
ASSERT(!exception.IsEmpty());
v8::ThrowException(exception);
}
v8::Handle<v8::Value> V8Proxy::ThrowError(ErrorType type, const char* message)
{
switch (type) {
case RANGE_ERROR:
return v8::ThrowException(v8::Exception::RangeError(v8String(message)));
case REFERENCE_ERROR:
return v8::ThrowException(
v8::Exception::ReferenceError(v8String(message)));
case SYNTAX_ERROR:
return v8::ThrowException(v8::Exception::SyntaxError(v8String(message)));
case TYPE_ERROR:
return v8::ThrowException(v8::Exception::TypeError(v8String(message)));
case GENERAL_ERROR:
return v8::ThrowException(v8::Exception::Error(v8String(message)));
default:
ASSERT(false);
return v8::Handle<v8::Value>();
}
}
v8::Local<v8::Context> V8Proxy::GetContext(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
if (!proxy)
return v8::Local<v8::Context>();
proxy->InitContextIfNeeded();
return proxy->GetContext();
}
v8::Local<v8::Context> V8Proxy::GetCurrentContext()
{
return v8::Context::GetCurrent();
}
v8::Handle<v8::Value> V8Proxy::ToV8Object(V8ClassIndex::V8WrapperType type, void* imp)
{
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(type != V8ClassIndex::EVENT);
bool is_active_dom_object = false;
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
return NodeToV8Object(static_cast<Node*>(imp));
case V8ClassIndex::CSSVALUE:
return CSSValueToV8Object(static_cast<CSSValue*>(imp));
case V8ClassIndex::CSSRULE:
return CSSRuleToV8Object(static_cast<CSSRule*>(imp));
case V8ClassIndex::STYLESHEET:
return StyleSheetToV8Object(static_cast<StyleSheet*>(imp));
case V8ClassIndex::DOMWINDOW:
return WindowToV8Object(static_cast<DOMWindow*>(imp));
#if ENABLE(SVG)
SVG_NONNODE_TYPES(MAKE_CASE)
if (type == V8ClassIndex::SVGELEMENTINSTANCE)
return SVGElementInstanceToV8Object(static_cast<SVGElementInstance*>(imp));
return SVGObjectWithContextToV8Object(type, imp);
#endif
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
is_active_dom_object = true;
break;
default:
break;
}
#undef MAKE_CASE
if (!imp) return v8::Null();
// Non DOM node
v8::Persistent<v8::Object> result = is_active_dom_object ?
GetActiveDOMObjectMap().get(imp) :
GetDOMObjectMap().get(imp);
if (result.IsEmpty()) {
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, imp);
if (!v8obj.IsEmpty()) {
// Go through big switch statement, it has some duplications
// that were handled by code above (such as CSSVALUE, CSSRULE, etc).
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(imp)->ref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
result = v8::Persistent<v8::Object>::New(v8obj);
if (is_active_dom_object)
SetJSWrapperForActiveDOMObject(imp, result);
else
SetJSWrapperForDOMObject(imp, result);
// Special case for Location and Navigator. Both Safari and FF let
// Location and Navigator JS wrappers survive GC. To mimic their
// behaviors, V8 creates hidden references from the DOMWindow to
// location and navigator objects. These references get cleared
// when the DOMWindow is reused by a new page.
if (type == V8ClassIndex::LOCATION) {
SetHiddenWindowReference(static_cast<Location*>(imp)->frame(),
V8Custom::kDOMWindowLocationIndex, result);
} else if (type == V8ClassIndex::NAVIGATOR) {
SetHiddenWindowReference(static_cast<Navigator*>(imp)->frame(),
V8Custom::kDOMWindowNavigatorIndex, result);
}
}
}
return result;
}
void V8Proxy::SetHiddenWindowReference(Frame* frame,
const int internal_index,
v8::Handle<v8::Object> jsobj)
{
// Get DOMWindow
if (!frame) return; // Object might be detached from window
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty()) return;
ASSERT(internal_index < V8Custom::kDOMWindowInternalFieldCount);
v8::Handle<v8::Object> global = context->Global();
// Look for real DOM wrapper.
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
ASSERT(global->GetInternalField(internal_index)->IsUndefined());
global->SetInternalField(internal_index, jsobj);
}
V8ClassIndex::V8WrapperType V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object> object)
{
ASSERT(MaybeDOMWrapper(object));
v8::Handle<v8::Value> type =
object->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
return V8ClassIndex::FromInt(type->Int32Value());
}
void* V8Proxy::ToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
v8::Handle<v8::Value> object)
{
// Native event listener is per frame, it cannot be handled
// by this generic function.
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(MaybeDOMWrapper(object));
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
ASSERT(false);
return NULL;
case V8ClassIndex::XMLHTTPREQUEST:
return DOMWrapperToNative<XMLHttpRequest>(object);
case V8ClassIndex::EVENT:
return DOMWrapperToNative<Event>(object);
case V8ClassIndex::CSSRULE:
return DOMWrapperToNative<CSSRule>(object);
default:
break;
}
#undef MAKE_CASE
return DOMWrapperToNative<void>(object);
}
v8::Handle<v8::Object> V8Proxy::LookupDOMWrapper(
V8ClassIndex::V8WrapperType type, v8::Handle<v8::Value> value)
{
if (value.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::FunctionTemplate> desc = V8Proxy::GetTemplate(type);
while (value->IsObject()) {
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
if (desc->HasInstance(object))
return object;
value = object->GetPrototype();
}
return v8::Handle<v8::Object>();
}
PassRefPtr<NodeFilter> V8Proxy::ToNativeNodeFilter(v8::Handle<v8::Value> filter)
{
// A NodeFilter is used when walking through a DOM tree or iterating tree
// nodes.
// TODO: we may want to cache NodeFilterCondition and NodeFilter
// object, but it is minor.
// NodeFilter is passed to NodeIterator that has a ref counted pointer
// to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
// In NodeFilterCondition, filter object is persisted in its constructor,
// and disposed in its destructor.
if (!filter->IsFunction())
return 0;
NodeFilterCondition* cond = new V8NodeFilterCondition(filter);
return NodeFilter::create(cond);
}
v8::Local<v8::Object> V8Proxy::InstantiateV8Object(
V8ClassIndex::V8WrapperType desc_type,
V8ClassIndex::V8WrapperType cptr_type,
void* imp)
{
// Make a special case for document.all
if (desc_type == V8ClassIndex::HTMLCOLLECTION &&
static_cast<HTMLCollection*>(imp)->type() == HTMLCollection::DocAll) {
desc_type = V8ClassIndex::UNDETECTABLEHTMLCOLLECTION;
}
v8::Local<v8::Function> function;
V8Proxy* proxy = V8Proxy::retrieve();
if (proxy) {
// Make sure that the context of the proxy has been initialized.
proxy->InitContextIfNeeded();
// Constructor is configured.
function = proxy->GetConstructor(desc_type);
} else {
function = GetTemplate(desc_type)->GetFunction();
}
v8::Local<v8::Object> instance = SafeAllocation::NewInstance(function);
if (!instance.IsEmpty()) {
// Avoid setting the DOM wrapper for failed allocations.
SetDOMWrapper(instance, V8ClassIndex::ToInt(cptr_type), imp);
}
return instance;
}
v8::Handle<v8::Value> V8Proxy::CheckNewLegal(const v8::Arguments& args)
{
if (!AllowAllocation::m_current)
return ThrowError(TYPE_ERROR, "Illegal constructor");
return args.This();
}
void V8Proxy::SetDOMWrapper(v8::Handle<v8::Object> obj, int type, void* cptr)
{
ASSERT(obj->InternalFieldCount() >= 2);
obj->SetInternalField(V8Custom::kDOMWrapperObjectIndex, WrapCPointer(cptr));
obj->SetInternalField(V8Custom::kDOMWrapperTypeIndex, v8::Integer::New(type));
}
#ifndef NDEBUG
bool V8Proxy::MaybeDOMWrapper(v8::Handle<v8::Value> value)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
return true;
}
#endif
bool V8Proxy::IsDOMEventWrapper(v8::Handle<v8::Value> value)
{
// All kinds of events use EVENT as dom type in JS wrappers.
// See EventToV8Object
return IsWrapperOfType(value, V8ClassIndex::EVENT);
}
bool V8Proxy::IsWrapperOfType(v8::Handle<v8::Value> value,
V8ClassIndex::V8WrapperType classType)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
return V8ClassIndex::FromInt(type->Int32Value()) == classType;
}
#if ENABLE(VIDEO)
#define FOR_EACH_VIDEO_TAG(macro) \
macro(audio, AUDIO) \
macro(source, SOURCE) \
macro(video, VIDEO)
#else
#define FOR_EACH_VIDEO_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
macro(a, ANCHOR) \
macro(applet, APPLET) \
macro(area, AREA) \
macro(base, BASE) \
macro(basefont, BASEFONT) \
macro(blockquote, BLOCKQUOTE) \
macro(body, BODY) \
macro(br, BR) \
macro(button, BUTTON) \
macro(caption, TABLECAPTION) \
macro(col, TABLECOL) \
macro(colgroup, TABLECOL) \
macro(del, MOD) \
macro(canvas, CANVAS) \
macro(dir, DIRECTORY) \
macro(div, DIV) \
macro(dl, DLIST) \
macro(embed, EMBED) \
macro(fieldset, FIELDSET) \
macro(font, FONT) \
macro(form, FORM) \
macro(frame, FRAME) \
macro(frameset, FRAMESET) \
macro(h1, HEADING) \
macro(h2, HEADING) \
macro(h3, HEADING) \
macro(h4, HEADING) \
macro(h5, HEADING) \
macro(h6, HEADING) \
macro(head, HEAD) \
macro(hr, HR) \
macro(html, HTML) \
macro(img, IMAGE) \
macro(iframe, IFRAME) \
macro(image, IMAGE) \
macro(input, INPUT) \
macro(ins, MOD) \
macro(isindex, ISINDEX) \
macro(keygen, SELECT) \
macro(label, LABEL) \
macro(legend, LEGEND) \
macro(li, LI) \
macro(link, LINK) \
macro(listing, PRE) \
macro(map, MAP) \
macro(marquee, MARQUEE) \
macro(menu, MENU) \
macro(meta, META) \
macro(object, OBJECT) \
macro(ol, OLIST) \
macro(optgroup, OPTGROUP) \
macro(option, OPTION) \
macro(p, PARAGRAPH) \
macro(param, PARAM) \
macro(pre, PRE) \
macro(q, QUOTE) \
macro(script, SCRIPT) \
macro(select, SELECT) \
macro(style, STYLE) \
macro(table, TABLE) \
macro(thead, TABLESECTION) \
macro(tbody, TABLESECTION) \
macro(tfoot, TABLESECTION) \
macro(td, TABLECELL) \
macro(th, TABLECELL) \
macro(tr, TABLEROW) \
macro(textarea, TEXTAREA) \
macro(title, TITLE) \
macro(ul, ULIST) \
macro(xmp, PRE)
V8ClassIndex::V8WrapperType V8Proxy::GetHTMLElementType(HTMLElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::HTML##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#if ENABLE(VIDEO)
if (MediaPlayer::isAvailable()) {
FOR_EACH_VIDEO_TAG(ADD_TO_HASH_MAP)
}
#endif
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0)
return V8ClassIndex::HTMLELEMENT;
return t;
}
#undef FOR_EACH_TAG
#if ENABLE(SVG)
#if ENABLE(SVG_ANIMATION)
#define FOR_EACH_ANIMATION_TAG(macro) \
macro(animateColor, ANIMATECOLOR) \
macro(animate, ANIMATE) \
macro(animateTransform, ANIMATETRANSFORM) \
macro(set, SET)
#else
#define FOR_EACH_ANIMATION_TAG(macro)
#endif
#if ENABLE(SVG_FILTERS)
#define FOR_EACH_FILTERS_TAG(macro) \
macro(feBlend, FEBLEND) \
macro(feColorMatrix, FECOLORMATRIX) \
macro(feComponentTransfer, FECOMPONENTTRANSFER) \
macro(feComposite, FECOMPOSITE) \
macro(feDiffuseLighting, FEDIFFUSELIGHTING) \
macro(feDisplacementMap, FEDISPLACEMENTMAP) \
macro(feDistantLight, FEDISTANTLIGHT) \
macro(feFlood, FEFLOOD) \
macro(feFuncA, FEFUNCA) \
macro(feFuncB, FEFUNCB) \
macro(feFuncG, FEFUNCG) \
macro(feFuncR, FEFUNCR) \
macro(feGaussianBlur, FEGAUSSIANBLUR) \
macro(feImage, FEIMAGE) \
macro(feMerge, FEMERGE) \
macro(feMergeNode, FEMERGENODE) \
macro(feOffset, FEOFFSET) \
macro(fePointLight, FEPOINTLIGHT) \
macro(feSpecularLighting, FESPECULARLIGHTING) \
macro(feSpotLight, FESPOTLIGHT) \
macro(feTile, FETILE) \
macro(feTurbulence, FETURBULENCE) \
macro(filter, FILTER)
#else
#define FOR_EACH_FILTERS_TAG(macro)
#endif
#if ENABLE(SVG_FONTS)
#define FOR_EACH_FONTS_TAG(macro) \
macro(definition-src, DEFINITIONSRC) \
macro(font-face, FONTFACE) \
macro(font-face-format, FONTFACEFORMAT) \
macro(font-face-name, FONTFACENAME) \
macro(font-face-src, FONTFACESRC) \
macro(font-face-uri, FONTFACEURI)
#else
#define FOR_EACH_FONTS_TAG(marco)
#endif
#if ENABLE(SVG_FOREIGN_OBJECT)
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
macro(foreignObject, FOREIGNOBJECT)
#else
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro)
#endif
#if ENABLE(SVG_USE)
#define FOR_EACH_USE_TAG(macro) \
macro(use, USE)
#else
#define FOR_EACH_USE_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
FOR_EACH_ANIMATION_TAG(macro) \
FOR_EACH_FILTERS_TAG(macro) \
FOR_EACH_FONTS_TAG(macro) \
FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
FOR_EACH_USE_TAG(macro) \
macro(a, A) \
macro(altGlyph, ALTGLYPH) \
macro(circle, CIRCLE) \
macro(clipPath, CLIPPATH) \
macro(cursor, CURSOR) \
macro(defs, DEFS) \
macro(desc, DESC) \
macro(ellipse, ELLIPSE) \
macro(g, G) \
macro(glyph, GLYPH) \
macro(image, IMAGE) \
macro(linearGradient, LINEARGRADIENT) \
macro(line, LINE) \
macro(marker, MARKER) \
macro(mask, MASK) \
macro(metadata, METADATA) \
macro(path, PATH) \
macro(pattern, PATTERN) \
macro(polyline, POLYLINE) \
macro(polygon, POLYGON) \
macro(radialGradient, RADIALGRADIENT) \
macro(rect, RECT) \
macro(script, SCRIPT) \
macro(stop, STOP) \
macro(style, STYLE) \
macro(svg, SVG) \
macro(switch, SWITCH) \
macro(symbol, SYMBOL) \
macro(text, TEXT) \
macro(textPath, TEXTPATH) \
macro(title, TITLE) \
macro(tref, TREF) \
macro(tspan, TSPAN) \
macro(view, VIEW) \
// end of macro
V8ClassIndex::V8WrapperType V8Proxy::GetSVGElementType(SVGElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::SVG##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0) return V8ClassIndex::SVGELEMENT;
return t;
}
#undef FOR_EACH_TAG
#endif // ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::EventToV8Object(Event* event)
{
if (!event)
return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(event);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT;
if (event->isUIEvent()) {
if (event->isKeyboardEvent())
type = V8ClassIndex::KEYBOARDEVENT;
else if (event->isTextEvent())
type = V8ClassIndex::TEXTEVENT;
else if (event->isMouseEvent())
type = V8ClassIndex::MOUSEEVENT;
else if (event->isWheelEvent())
type = V8ClassIndex::WHEELEVENT;
#if ENABLE(SVG)
else if (event->isSVGZoomEvent())
type = V8ClassIndex::SVGZOOMEVENT;
#endif
else
type = V8ClassIndex::UIEVENT;
} else if (event->isMutationEvent())
type = V8ClassIndex::MUTATIONEVENT;
else if (event->isOverflowEvent())
type = V8ClassIndex::OVERFLOWEVENT;
else if (event->isMessageEvent())
type = V8ClassIndex::MESSAGEEVENT;
else if (event->isProgressEvent()) {
if (event->isXMLHttpRequestProgressEvent())
type = V8ClassIndex::XMLHTTPREQUESTPROGRESSEVENT;
else
type = V8ClassIndex::PROGRESSEVENT;
} else if (event->isWebKitAnimationEvent())
type = V8ClassIndex::WEBKITANIMATIONEVENT;
else if (event->isWebKitTransitionEvent())
type = V8ClassIndex::WEBKITTRANSITIONEVENT;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::EVENT, event);
if (result.IsEmpty()) {
// Instantiation failed. Avoid updating the DOM object map and
// return null which is already handled by callers of this function
// in case the event is NULL.
return v8::Null();
}
event->ref(); // fast ref
SetJSWrapperForDOMObject(event, v8::Persistent<v8::Object>::New(result));
return result;
}
// Caller checks node is not null.
v8::Handle<v8::Value> V8Proxy::NodeToV8Object(Node* node)
{
if (!node) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMNodeMap().get(node);
if (!wrapper.IsEmpty())
return wrapper;
bool is_document = false; // document type node has special handling
V8ClassIndex::V8WrapperType type;
switch (node->nodeType()) {
case Node::ELEMENT_NODE:
if (node->isHTMLElement())
type = GetHTMLElementType(static_cast<HTMLElement*>(node));
#if ENABLE(SVG)
else if (node->isSVGElement())
type = GetSVGElementType(static_cast<SVGElement*>(node));
#endif
else
type = V8ClassIndex::ELEMENT;
break;
case Node::ATTRIBUTE_NODE:
type = V8ClassIndex::ATTR;
break;
case Node::TEXT_NODE:
type = V8ClassIndex::TEXT;
break;
case Node::CDATA_SECTION_NODE:
type = V8ClassIndex::CDATASECTION;
break;
case Node::ENTITY_NODE:
type = V8ClassIndex::ENTITY;
break;
case Node::PROCESSING_INSTRUCTION_NODE:
type = V8ClassIndex::PROCESSINGINSTRUCTION;
break;
case Node::COMMENT_NODE:
type = V8ClassIndex::COMMENT;
break;
case Node::DOCUMENT_NODE: {
is_document = true;
Document* doc = static_cast<Document*>(node);
if (doc->isHTMLDocument())
type = V8ClassIndex::HTMLDOCUMENT;
#if ENABLE(SVG)
else if (doc->isSVGDocument())
type = V8ClassIndex::SVGDOCUMENT;
#endif
else
type = V8ClassIndex::DOCUMENT;
break;
}
case Node::DOCUMENT_TYPE_NODE:
type = V8ClassIndex::DOCUMENTTYPE;
break;
case Node::NOTATION_NODE:
type = V8ClassIndex::NOTATION;
break;
case Node::DOCUMENT_FRAGMENT_NODE:
type = V8ClassIndex::DOCUMENTFRAGMENT;
break;
case Node::ENTITY_REFERENCE_NODE:
type = V8ClassIndex::ENTITYREFERENCE;
break;
default:
type = V8ClassIndex::NODE;
}
// Find the context to which the node belongs and create the wrapper
// in that context. If the node is not in a document, the current
// context is used.
v8::Local<v8::Context> context;
Document* doc = node->document();
if (doc) {
context = V8Proxy::GetContext(doc->frame());
}
if (!context.IsEmpty()) {
context->Enter();
}
v8::Local<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::NODE, node);
// Exit the node's context if it was entered.
if (!context.IsEmpty()) {
context->Exit();
}
if (result.IsEmpty()) {
// If instantiation failed it's important not to add the result
// to the DOM node map. Instead we return an empty handle, which
// should already be handled by callers of this function in case
// the node is NULL.
return result;
}
node->ref();
SetJSWrapperForDOMNode(node, v8::Persistent<v8::Object>::New(result));
if (is_document) {
Document* doc = static_cast<Document*>(node);
V8Proxy* proxy = V8Proxy::retrieve(doc->frame());
if (proxy)
proxy->UpdateDocumentWrapper(result);
if (type == V8ClassIndex::HTMLDOCUMENT) {
// Create marker object and insert it in two internal fields.
// This is used to implement temporary shadowing of
// document.all.
ASSERT(result->InternalFieldCount() ==
V8Custom::kHTMLDocumentInternalFieldCount);
v8::Local<v8::Object> marker = v8::Object::New();
result->SetInternalField(V8Custom::kHTMLDocumentMarkerIndex, marker);
result->SetInternalField(V8Custom::kHTMLDocumentShadowIndex, marker);
}
}
return result;
}
// A JS object of type EventTarget can only be the following possible types:
// 1) EventTargetNode; 2) XMLHttpRequest; 3) MessagePort; 4) SVGElementInstance;
// 5) XMLHttpRequestUpload 6) Worker
// check EventTarget.h for new type conversion methods
v8::Handle<v8::Value> V8Proxy::EventTargetToV8Object(EventTarget* target)
{
if (!target)
return v8::Null();
#if ENABLE(SVG)
SVGElementInstance* instance = target->toSVGElementInstance();
if (instance)
return ToV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
#endif
#if ENABLE(WORKERS)
Worker* worker = target->toWorker();
if (worker)
return ToV8Object(V8ClassIndex::WORKER, worker);
#endif // WORKERS
Node* node = target->toNode();
if (node)
return NodeToV8Object(node);
// XMLHttpRequest is created within its JS counterpart.
XMLHttpRequest* xhr = target->toXMLHttpRequest();
if (xhr) {
v8::Handle<v8::Object> wrapper = GetActiveDOMObjectMap().get(xhr);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
// MessagePort is created within its JS counterpart
MessagePort* port = target->toMessagePort();
if (port) {
v8::Handle<v8::Object> wrapper = GetActiveDOMObjectMap().get(port);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload();
if (upload) {
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(upload);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
ASSERT(0);
return v8::Handle<v8::Value>();
}
v8::Handle<v8::Value> V8Proxy::EventListenerToV8Object(
EventListener* listener)
{
if (listener == 0) return v8::Null();
// TODO(fqian): can a user take a lazy event listener and set to other places?
V8AbstractEventListener* v8listener =
static_cast<V8AbstractEventListener*>(listener);
return v8listener->getListenerObject();
}
v8::Handle<v8::Value> V8Proxy::DOMImplementationToV8Object(
DOMImplementation* impl)
{
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::DOMIMPLEMENTATION,
V8ClassIndex::DOMIMPLEMENTATION,
impl);
if (result.IsEmpty()) {
// If the instantiation failed, we ignore it and return null instead
// of returning an empty handle.
return v8::Null();
}
return result;
}
v8::Handle<v8::Value> V8Proxy::StyleSheetToV8Object(StyleSheet* sheet)
{
if (!sheet) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(sheet);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::STYLESHEET;
if (sheet->isCSSStyleSheet())
type = V8ClassIndex::CSSSTYLESHEET;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::STYLESHEET, sheet);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
sheet->ref();
SetJSWrapperForDOMObject(sheet, v8::Persistent<v8::Object>::New(result));
}
// Add a hidden reference from stylesheet object to its owner node.
Node* owner_node = sheet->ownerNode();
if (owner_node) {
v8::Handle<v8::Object> owner =
v8::Handle<v8::Object>::Cast(NodeToV8Object(owner_node));
result->SetInternalField(V8Custom::kStyleSheetOwnerNodeIndex, owner);
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSValueToV8Object(CSSValue* value)
{
if (!value) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(value);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
if (value->isWebKitCSSTransformValue())
type = V8ClassIndex::WEBKITCSSTRANSFORMVALUE;
else if (value->isValueList())
type = V8ClassIndex::CSSVALUELIST;
else if (value->isPrimitiveValue())
type = V8ClassIndex::CSSPRIMITIVEVALUE;
#if ENABLE(SVG)
else if (value->isSVGPaint())
type = V8ClassIndex::SVGPAINT;
else if (value->isSVGColor())
type = V8ClassIndex::SVGCOLOR;
#endif
else
type = V8ClassIndex::CSSVALUE;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSVALUE, value);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
value->ref();
SetJSWrapperForDOMObject(value, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSRuleToV8Object(CSSRule* rule)
{
if (!rule) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(rule);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
switch (rule->type()) {
case CSSRule::STYLE_RULE:
type = V8ClassIndex::CSSSTYLERULE;
break;
case CSSRule::CHARSET_RULE:
type = V8ClassIndex::CSSCHARSETRULE;
break;
case CSSRule::IMPORT_RULE:
type = V8ClassIndex::CSSIMPORTRULE;
break;
case CSSRule::MEDIA_RULE:
type = V8ClassIndex::CSSMEDIARULE;
break;
case CSSRule::FONT_FACE_RULE:
type = V8ClassIndex::CSSFONTFACERULE;
break;
case CSSRule::PAGE_RULE:
type = V8ClassIndex::CSSPAGERULE;
break;
case CSSRule::VARIABLES_RULE:
type = V8ClassIndex::CSSVARIABLESRULE;
break;
case CSSRule::WEBKIT_KEYFRAME_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMERULE;
break;
case CSSRule::WEBKIT_KEYFRAMES_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMESRULE;
break;
default: // CSSRule::UNKNOWN_RULE
type = V8ClassIndex::CSSRULE;
break;
}
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSRULE, rule);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
rule->ref();
SetJSWrapperForDOMObject(rule, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::WindowToV8Object(DOMWindow* window)
{
if (!window) return v8::Null();
// Initializes environment of a frame, and return the global object
// of the frame.
Frame* frame = window->frame();
if (!frame)
return v8::Handle<v8::Object>();
// Special case: Because of evaluateInNewContext() one DOMWindow can have
// multipe contexts and multiple global objects associated with it. When
// code running in one of those contexts accesses the window object, we
// want to return the global object associated with that context, not
// necessarily the first global object associated with that DOMWindow.
v8::Handle<v8::Context> current_context = v8::Context::GetCurrent();
v8::Handle<v8::Object> current_global = current_context->Global();
v8::Handle<v8::Object> windowWrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, current_global);
if (!windowWrapper.IsEmpty())
if (DOMWrapperToNative<DOMWindow>(windowWrapper) == window)
return current_global;
// Otherwise, return the global object associated with this frame.
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
return global;
}
void V8Proxy::BindJSObjectToWindow(Frame* frame,
const char* name,
int type,
v8::Handle<v8::FunctionTemplate> desc,
void* imp)
{
// Get environment.
v8::Handle<v8::Context> context = V8Proxy::GetContext(frame);
if (context.IsEmpty())
return; // JS not enabled.
v8::Context::Scope scope(context);
v8::Handle<v8::Object> instance = desc->GetFunction();
SetDOMWrapper(instance, type, imp);
v8::Handle<v8::Object> global = context->Global();
global->Set(v8::String::New(name), instance);
}
void V8Proxy::ProcessConsoleMessages()
{
ConsoleMessageManager::ProcessDelayedMessages();
}
// Create the utility context for holding JavaScript functions used internally
// which are not visible to JavaScript executing on the page.
void V8Proxy::CreateUtilityContext() {
ASSERT(m_utilityContext.IsEmpty());
v8::HandleScope scope;
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
m_utilityContext = v8::Context::New(NULL, global_template);
v8::Context::Scope context_scope(m_utilityContext);
// Compile JavaScript function for retrieving the source line of the top
// JavaScript stack frame.
static const char* frame_source_line_source =
"function frame_source_line(exec_state) {"
" return exec_state.frame(0).sourceLine();"
"}";
v8::Script::Compile(v8::String::New(frame_source_line_source))->Run();
// Compile JavaScript function for retrieving the source name of the top
// JavaScript stack frame.
static const char* frame_source_name_source =
"function frame_source_name(exec_state) {"
" var frame = exec_state.frame(0);"
" if (frame.func().resolved() && "
" frame.func().script() && "
" frame.func().script().name()) {"
" return frame.func().script().name();"
" }"
"}";
v8::Script::Compile(v8::String::New(frame_source_name_source))->Run();
}
int V8Proxy::GetSourceLineNumber() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = V8Proxy::GetUtilityContext();
if (utility_context.IsEmpty()) {
return 0;
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_line;
frame_source_line = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_line")));
if (frame_source_line.IsEmpty()) {
return 0;
}
v8::Handle<v8::Value> result = v8::Debug::Call(frame_source_line);
if (result.IsEmpty()) {
return 0;
}
return result->Int32Value();
}
String V8Proxy::GetSourceName() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = GetUtilityContext();
if (utility_context.IsEmpty()) {
return String();
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_name;
frame_source_name = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_name")));
if (frame_source_name.IsEmpty()) {
return String();
}
return ToWebCoreString(v8::Debug::Call(frame_source_name));
}
void V8Proxy::RegisterExtension(v8::Extension* extension) {
v8::RegisterExtension(extension);
m_extensions.push_back(extension);
}
} // namespace WebCore
Add a handle scope to V8Proxy::initContextIfNeeded.
initContextIfNeeded can be called without a handle scope in place
which will lead to a renderer crash when creating the first handle.
Also V8Proxy::initContextIfNeeded creates a number of local handles
that should be deallocated on exit.
BUG=8922
Review URL: http://codereview.chromium.org/48131
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@11965 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include <algorithm>
#include <utility>
#include <v8.h>
#include <v8-debug.h>
#include "v8_proxy.h"
#include "dom_wrapper_map.h"
#include "v8_index.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_collection.h"
#include "v8_nodefilter.h"
#include "V8DOMWindow.h"
#include "ChromiumBridge.h"
#include "BarInfo.h"
#include "CanvasGradient.h"
#include "CanvasPattern.h"
#include "CanvasPixelArray.h"
#include "CanvasRenderingContext2D.h"
#include "CanvasStyle.h"
#include "CharacterData.h"
#include "ClientRect.h"
#include "ClientRectList.h"
#include "Clipboard.h"
#include "Console.h"
#include "Counter.h"
#include "CSSCharsetRule.h"
#include "CSSFontFaceRule.h"
#include "CSSImportRule.h"
#include "CSSMediaRule.h"
#include "CSSPageRule.h"
#include "CSSRule.h"
#include "CSSRuleList.h"
#include "CSSValueList.h"
#include "CSSStyleRule.h"
#include "CSSStyleSheet.h"
#include "CSSVariablesDeclaration.h"
#include "CSSVariablesRule.h"
#include "DocumentType.h"
#include "DocumentFragment.h"
#include "DOMCoreException.h"
#include "DOMImplementation.h"
#include "DOMParser.h"
#include "DOMSelection.h"
#include "DOMStringList.h"
#include "DOMWindow.h"
#include "Entity.h"
#include "EventListener.h"
#include "EventTarget.h"
#include "Event.h"
#include "EventException.h"
#include "ExceptionCode.h"
#include "File.h"
#include "FileList.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "History.h"
#include "HTMLNames.h"
#include "HTMLDocument.h"
#include "HTMLElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLSelectElement.h"
#include "HTMLOptionsCollection.h"
#include "ImageData.h"
#include "InspectorController.h"
#include "KeyboardEvent.h"
#include "Location.h"
#include "MediaError.h"
#include "MediaList.h"
#include "MediaPlayer.h"
#include "MessageChannel.h"
#include "MessageEvent.h"
#include "MessagePort.h"
#include "MimeTypeArray.h"
#include "MouseEvent.h"
#include "MutationEvent.h"
#include "Navigator.h" // for MimeTypeArray
#include "NodeFilter.h"
#include "Notation.h"
#include "NodeList.h"
#include "NodeIterator.h"
#include "OverflowEvent.h"
#include "Page.h"
#include "Plugin.h"
#include "PluginArray.h"
#include "ProcessingInstruction.h"
#include "ProgressEvent.h"
#include "Range.h"
#include "RangeException.h"
#include "Rect.h"
#include "RGBColor.h"
#include "Screen.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "StyleSheet.h"
#include "StyleSheetList.h"
#include "SVGColor.h"
#include "SVGPaint.h"
#include "TextEvent.h"
#include "TextMetrics.h"
#include "TimeRanges.h"
#include "TreeWalker.h"
#include "XSLTProcessor.h"
#include "V8AbstractEventListener.h"
#include "V8CustomEventListener.h"
#include "V8DOMWindow.h"
#include "V8HTMLElement.h"
#include "V8LazyEventListener.h"
#include "V8ObjectEventListener.h"
#include "WebKitAnimationEvent.h"
#include "WebKitCSSKeyframeRule.h"
#include "WebKitCSSKeyframesRule.h"
#include "WebKitCSSMatrix.h"
#include "WebKitCSSTransformValue.h"
#include "WebKitPoint.h"
#include "WebKitTransitionEvent.h"
#include "WheelEvent.h"
#include "XMLHttpRequest.h"
#include "XMLHttpRequestException.h"
#include "XMLHttpRequestProgressEvent.h"
#include "XMLHttpRequestUpload.h"
#include "XMLSerializer.h"
#include "XPathException.h"
#include "XPathExpression.h"
#include "XPathNSResolver.h"
#include "XPathResult.h"
#include "ScriptController.h"
#if ENABLE(SVG)
#include "SVGAngle.h"
#include "SVGAnimatedPoints.h"
#include "SVGElement.h"
#include "SVGElementInstance.h"
#include "SVGElementInstanceList.h"
#include "SVGException.h"
#include "SVGLength.h"
#include "SVGLengthList.h"
#include "SVGNumberList.h"
#include "SVGPathSeg.h"
#include "SVGPathSegArc.h"
#include "SVGPathSegClosePath.h"
#include "SVGPathSegCurvetoCubic.h"
#include "SVGPathSegCurvetoCubicSmooth.h"
#include "SVGPathSegCurvetoQuadratic.h"
#include "SVGPathSegCurvetoQuadraticSmooth.h"
#include "SVGPathSegLineto.h"
#include "SVGPathSegLinetoHorizontal.h"
#include "SVGPathSegLinetoVertical.h"
#include "SVGPathSegList.h"
#include "SVGPathSegMoveto.h"
#include "SVGPointList.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGRenderingIntent.h"
#include "SVGStringList.h"
#include "SVGTransform.h"
#include "SVGTransformList.h"
#include "SVGUnitTypes.h"
#include "SVGURIReference.h"
#include "SVGZoomEvent.h"
#include "V8SVGPODTypeWrapper.h"
#endif // SVG
#if ENABLE(WORKERS)
#include "Worker.h"
#include "WorkerContext.h"
#include "WorkerLocation.h"
#include "WorkerNavigator.h"
#endif // WORKERS
#if ENABLE(XPATH)
#include "XPathEvaluator.h"
#endif
namespace WebCore {
// DOM binding algorithm:
//
// There are two kinds of DOM objects:
// 1. DOM tree nodes, such as Document, HTMLElement, ...
// there classes implements TreeShared<T> interface;
// 2. Non-node DOM objects, such as CSSRule, Location, etc.
// these classes implement a ref-counted scheme.
//
// A DOM object may have a JS wrapper object. If a tree node
// is alive, its JS wrapper must be kept alive even it is not
// reachable from JS roots.
// However, JS wrappers of non-node objects can go away if
// not reachable from other JS objects. It works like a cache.
//
// DOM objects are ref-counted, and JS objects are traced from
// a set of root objects. They can create a cycle. To break
// cycles, we do following:
// Handles from DOM objects to JS wrappers are always weak,
// so JS wrappers of non-node object cannot create a cycle.
// Before starting a global GC, we create a virtual connection
// between nodes in the same tree in the JS heap. If the wrapper
// of one node in a tree is alive, wrappers of all nodes in
// the same tree are considered alive. This is done by creating
// object groups in GC prologue callbacks. The mark-compact
// collector will remove these groups after each GC.
// Static utility context.
v8::Persistent<v8::Context> V8Proxy::m_utilityContext;
// Static list of registered extensions
V8ExtensionList V8Proxy::m_extensions;
// A helper class for undetectable document.all
class UndetectableHTMLCollection : public HTMLCollection {
};
#ifndef NDEBUG
// Keeps track of global handles created (not JS wrappers
// of DOM objects). Often these global handles are source
// of leaks.
//
// If you want to let a C++ object hold a persistent handle
// to a JS object, you should register the handle here to
// keep track of leaks.
//
// When creating a persistent handle, call:
//
// #ifndef NDEBUG
// V8Proxy::RegisterGlobalHandle(type, host, handle);
// #endif
//
// When releasing the handle, call:
//
// #ifndef NDEBUG
// V8Proxy::UnregisterGlobalHandle(type, host, handle);
// #endif
//
typedef HashMap<v8::Value*, GlobalHandleInfo*> GlobalHandleMap;
static GlobalHandleMap& global_handle_map()
{
static GlobalHandleMap static_global_handle_map;
return static_global_handle_map;
}
// The USE_VAR(x) template is used to silence C++ compiler warnings
// issued for unused variables (typically parameters or values that
// we want to watch in the debugger).
template <typename T>
static inline void USE_VAR(T) { }
// The function is the place to set the break point to inspect
// live global handles. Leaks are often come from leaked global handles.
static void EnumerateGlobalHandles()
{
for (GlobalHandleMap::iterator it = global_handle_map().begin(),
end = global_handle_map().end(); it != end; ++it) {
GlobalHandleInfo* info = it->second;
USE_VAR(info);
v8::Value* handle = it->first;
USE_VAR(handle);
}
}
void V8Proxy::RegisterGlobalHandle(GlobalHandleType type, void* host,
v8::Persistent<v8::Value> handle)
{
ASSERT(!global_handle_map().contains(*handle));
global_handle_map().set(*handle, new GlobalHandleInfo(host, type));
}
void V8Proxy::UnregisterGlobalHandle(void* host, v8::Persistent<v8::Value> handle)
{
ASSERT(global_handle_map().contains(*handle));
GlobalHandleInfo* info = global_handle_map().take(*handle);
ASSERT(info->host_ == host);
delete info;
}
#endif // ifndef NDEBUG
void BatchConfigureAttributes(v8::Handle<v8::ObjectTemplate> inst,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedAttribute* attrs,
size_t num_attrs)
{
for (size_t i = 0; i < num_attrs; ++i) {
const BatchedAttribute* a = &attrs[i];
(a->on_proto ? proto : inst)->SetAccessor(
v8::String::New(a->name),
a->getter,
a->setter,
a->data == V8ClassIndex::INVALID_CLASS_INDEX
? v8::Handle<v8::Value>()
: v8::Integer::New(V8ClassIndex::ToInt(a->data)),
a->settings,
a->attribute);
}
}
void BatchConfigureConstants(v8::Handle<v8::FunctionTemplate> desc,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedConstant* consts,
size_t num_consts)
{
for (size_t i = 0; i < num_consts; ++i) {
const BatchedConstant* c = &consts[i];
desc->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
proto->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
}
}
typedef HashMap<Node*, v8::Object*> DOMNodeMap;
typedef HashMap<void*, v8::Object*> DOMObjectMap;
#ifndef NDEBUG
static void EnumerateDOMObjectMap(DOMObjectMap& wrapper_map)
{
for (DOMObjectMap::iterator it = wrapper_map.begin(), end = wrapper_map.end();
it != end; ++it) {
v8::Persistent<v8::Object> wrapper(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
void* obj = it->first;
USE_VAR(type);
USE_VAR(obj);
}
}
static void EnumerateDOMNodeMap(DOMNodeMap& node_map)
{
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
USE_VAR(node);
ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
}
}
#endif // NDEBUG
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj, void* para);
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* para);
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* para);
// A map from DOM node to its JS wrapper.
static DOMWrapperMap<Node>& GetDOMNodeMap()
{
static DOMWrapperMap<Node> static_dom_node_map(&WeakNodeCallback);
return static_dom_node_map;
}
// A map from a DOM object (non-node) to its JS wrapper. This map does not
// contain the DOM objects which can have pending activity (active dom objects).
DOMWrapperMap<void>& GetDOMObjectMap()
{
static DOMWrapperMap<void>
static_dom_object_map(&WeakDOMObjectCallback);
return static_dom_object_map;
}
// A map from a DOM object to its JS wrapper for DOM objects which
// can have pending activity.
static DOMWrapperMap<void>& GetActiveDOMObjectMap()
{
static DOMWrapperMap<void>
static_active_dom_object_map(&WeakActiveDOMObjectCallback);
return static_active_dom_object_map;
}
#if ENABLE(SVG)
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param);
// A map for SVGElementInstances.
static DOMWrapperMap<SVGElementInstance>& dom_svg_element_instance_map()
{
static DOMWrapperMap<SVGElementInstance>
static_dom_svg_element_instance_map(&WeakSVGElementInstanceCallback);
return static_dom_svg_element_instance_map;
}
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param)
{
SVGElementInstance* instance = static_cast<SVGElementInstance*>(param);
ASSERT(dom_svg_element_instance_map().contains(instance));
instance->deref();
dom_svg_element_instance_map().forget(instance);
}
v8::Handle<v8::Value> V8Proxy::SVGElementInstanceToV8Object(
SVGElementInstance* instance)
{
if (!instance)
return v8::Null();
v8::Handle<v8::Object> existing_instance = dom_svg_element_instance_map().get(instance);
if (!existing_instance.IsEmpty())
return existing_instance;
instance->ref();
// Instantiate the V8 object and remember it
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::SVGELEMENTINSTANCE,
V8ClassIndex::SVGELEMENTINSTANCE,
instance);
if (!result.IsEmpty()) {
// Only update the DOM SVG element map if the result is non-empty.
dom_svg_element_instance_map().set(instance,
v8::Persistent<v8::Object>::New(result));
}
return result;
}
// SVG non-node elements may have a reference to a context node which
// should be notified when the element is change
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj);
// Map of SVG objects with contexts to V8 objects
static DOMWrapperMap<void>& dom_svg_object_with_context_map() {
static DOMWrapperMap<void>
static_dom_svg_object_with_context_map(&WeakSVGObjectWithContext);
return static_dom_svg_object_with_context_map;
}
// Map of SVG objects with contexts to their contexts
static HashMap<void*, SVGElement*>& svg_object_to_context_map()
{
static HashMap<void*, SVGElement*> static_svg_object_to_context_map;
return static_svg_object_to_context_map;
}
v8::Handle<v8::Value> V8Proxy::SVGObjectWithContextToV8Object(
V8ClassIndex::V8WrapperType type, void* object)
{
if (!object)
return v8::Null();
v8::Persistent<v8::Object> result =
dom_svg_object_with_context_map().get(object);
if (!result.IsEmpty()) return result;
// Special case: SVGPathSegs need to be downcast to their real type
if (type == V8ClassIndex::SVGPATHSEG)
type = V8Custom::DowncastSVGPathSeg(object);
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, object);
if (!v8obj.IsEmpty()) {
result = v8::Persistent<v8::Object>::New(v8obj);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(object)->ref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(object)->ref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
dom_svg_object_with_context_map().set(object, result);
}
return result;
}
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope handle_scope;
ASSERT(dom_svg_object_with_context_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
dom_svg_object_with_context_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(dom_obj)->deref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
void V8Proxy::SetSVGContext(void* obj, SVGElement* context)
{
SVGElement* old_context = svg_object_to_context_map().get(obj);
if (old_context == context)
return;
if (old_context)
old_context->deref();
if (context)
context->ref();
svg_object_to_context_map().set(obj, context);
}
SVGElement* V8Proxy::GetSVGContext(void* obj)
{
return svg_object_to_context_map().get(obj);
}
#endif
// Called when obj is near death (not reachable from JS roots)
// It is time to remove the entry from the table and dispose
// the handle.
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj) {
v8::HandleScope scope;
ASSERT(GetDOMObjectMap().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
GetDOMObjectMap().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope scope;
ASSERT(GetActiveDOMObjectMap().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
GetActiveDOMObjectMap().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* param)
{
Node* node = static_cast<Node*>(param);
ASSERT(GetDOMNodeMap().contains(node));
GetDOMNodeMap().forget(node);
node->deref();
}
// A map from a DOM node to its JS wrapper, the wrapper
// is kept as a strong reference to survive GCs.
static DOMObjectMap& gc_protected_map() {
static DOMObjectMap static_gc_protected_map;
return static_gc_protected_map;
}
// static
void V8Proxy::GCProtect(void* dom_object)
{
if (!dom_object)
return;
if (gc_protected_map().contains(dom_object))
return;
if (!GetDOMObjectMap().contains(dom_object))
return;
// Create a new (strong) persistent handle for the object.
v8::Persistent<v8::Object> wrapper = GetDOMObjectMap().get(dom_object);
if (wrapper.IsEmpty()) return;
gc_protected_map().set(dom_object, *v8::Persistent<v8::Object>::New(wrapper));
}
// static
void V8Proxy::GCUnprotect(void* dom_object)
{
if (!dom_object)
return;
if (!gc_protected_map().contains(dom_object))
return;
// Dispose the strong reference.
v8::Persistent<v8::Object> wrapper(gc_protected_map().take(dom_object));
wrapper.Dispose();
}
// Create object groups for DOM tree nodes.
static void GCPrologue()
{
v8::HandleScope scope;
#ifndef NDEBUG
EnumerateDOMObjectMap(GetDOMObjectMap().impl());
#endif
// Run through all objects with possible pending activity making their
// wrappers non weak if there is pending activity.
DOMObjectMap active_map = GetActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
ASSERT(wrapper.IsWeak());
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) \
wrapper.ClearWeak(); \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
// Additional handling of message port ensuring that entangled ports also
// have their wrappers entangled. This should ideally be handled when the
// ports are actually entangled in MessagePort::entangle, but to avoid
// forking MessagePort.* this is postponed to GC time. Having this postponed
// has the drawback that the wrappers are "entangled/unentangled" for each
// GC even though their entnaglement most likely is still the same.
if (type == V8ClassIndex::MESSAGEPORT) {
// Get the port and its entangled port.
MessagePort* port1 = static_cast<MessagePort*>(obj);
MessagePort* port2 = port1->entangledPort();
if (port2 != NULL) {
// As ports are always entangled in pairs only perform the entanglement
// once for each pair (see ASSERT in MessagePort::unentangle()).
if (port1 < port2) {
v8::Handle<v8::Value> port1_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
v8::Handle<v8::Value> port2_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port2);
ASSERT(port1_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port1_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port2_wrapper);
ASSERT(port2_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port2_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port1_wrapper);
}
} else {
// Remove the wrapper entanglement when a port is not entangled.
if (V8Proxy::DOMObjectHasJSWrapper(port1)) {
v8::Handle<v8::Value> wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
ASSERT(wrapper->IsObject());
v8::Handle<v8::Object>::Cast(wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, v8::Undefined());
}
}
}
}
// Create object groups.
typedef std::pair<uintptr_t, Node*> GrouperPair;
typedef Vector<GrouperPair> GrouperList;
DOMNodeMap node_map = GetDOMNodeMap().impl();
GrouperList grouper;
grouper.reserveCapacity(node_map.size());
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
// If the node is in document, put it in the ownerDocument's object group.
//
// If an image element was created by JavaScript "new Image",
// it is not in a document. However, if the load event has not
// been fired (still onloading), it is treated as in the document.
//
// Otherwise, the node is put in an object group identified by the root
// elment of the tree to which it belongs.
uintptr_t group_id;
if (node->inDocument() ||
(node->hasTagName(HTMLNames::imgTag) &&
!static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent())) {
group_id = reinterpret_cast<uintptr_t>(node->document());
} else {
Node* root = node;
while (root->parent())
root = root->parent();
// If the node is alone in its DOM tree (doesn't have a parent or any
// children) then the group will be filtered out later anyway.
if (root == node && !node->hasChildNodes())
continue;
group_id = reinterpret_cast<uintptr_t>(root);
}
grouper.append(GrouperPair(group_id, node));
}
// Group by sorting by the group id. This will use the std::pair operator<,
// which will really sort by both the group id and the Node*. However the
// Node* is only involved to sort within a group id, so it will be fine.
std::sort(grouper.begin(), grouper.end());
// TODO(deanm): Should probably work in iterators here, but indexes were
// easier for my simple mind.
for (size_t i = 0; i < grouper.size(); ) {
// Seek to the next key (or the end of the list).
size_t next_key_index = grouper.size();
for (size_t j = i; j < grouper.size(); ++j) {
if (grouper[i].first != grouper[j].first) {
next_key_index = j;
break;
}
}
ASSERT(next_key_index > i);
// We only care about a group if it has more than one object. If it only
// has one object, it has nothing else that needs to be kept alive.
if (next_key_index - i <= 1) {
i = next_key_index;
continue;
}
Vector<v8::Persistent<v8::Value> > group;
group.reserveCapacity(next_key_index - i);
for (; i < next_key_index; ++i) {
v8::Persistent<v8::Value> wrapper =
GetDOMNodeMap().get(grouper[i].second);
if (!wrapper.IsEmpty())
group.append(wrapper);
}
if (group.size() > 1)
v8::V8::AddObjectGroup(&group[0], group.size());
ASSERT(i == next_key_index);
}
}
static void GCEpilogue()
{
v8::HandleScope scope;
// Run through all objects with pending activity making their wrappers weak
// again.
DOMObjectMap active_map = GetActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) { \
ASSERT(!wrapper.IsWeak()); \
wrapper.MakeWeak(impl, &WeakActiveDOMObjectCallback); \
} \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
#ifndef NDEBUG
// Check all survivals are weak.
EnumerateDOMObjectMap(GetDOMObjectMap().impl());
EnumerateDOMNodeMap(GetDOMNodeMap().impl());
EnumerateDOMObjectMap(gc_protected_map());
EnumerateGlobalHandles();
#undef USE_VAR
#endif
}
typedef HashMap<int, v8::FunctionTemplate*> FunctionTemplateMap;
bool AllowAllocation::m_current = false;
// JavaScriptConsoleMessages encapsulate everything needed to
// log messages originating from JavaScript to the Chrome console.
class JavaScriptConsoleMessage {
public:
JavaScriptConsoleMessage(const String& str,
const String& sourceID,
unsigned lineNumber)
: m_string(str)
, m_sourceID(sourceID)
, m_lineNumber(lineNumber) { }
void AddToPage(Page* page) const;
private:
const String m_string;
const String m_sourceID;
const unsigned m_lineNumber;
};
void JavaScriptConsoleMessage::AddToPage(Page* page) const
{
ASSERT(page);
Console* console = page->mainFrame()->domWindow()->console();
console->addMessage(JSMessageSource, ErrorMessageLevel, m_string, m_lineNumber, m_sourceID);
}
// The ConsoleMessageManager handles all console messages that stem
// from JavaScript. It keeps a list of messages that have been delayed but
// it makes sure to add all messages to the console in the right order.
class ConsoleMessageManager {
public:
// Add a message to the console. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void AddMessage(Page* page, const JavaScriptConsoleMessage& message);
// Add a message to the console but delay the reporting until it
// is safe to do so: Either when we leave JavaScript execution or
// when adding other console messages. The primary purpose of this
// method is to avoid calling into V8 to handle console messages
// when the VM is in a state that does not support GCs or allocations.
// Delayed messages are always reported in the page corresponding
// to the active context.
static void AddDelayedMessage(const JavaScriptConsoleMessage& message);
// Process any delayed messages. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void ProcessDelayedMessages();
private:
// All delayed messages are stored in this vector. If the vector
// is NULL, there are no delayed messages.
static Vector<JavaScriptConsoleMessage>* m_delayed;
};
Vector<JavaScriptConsoleMessage>* ConsoleMessageManager::m_delayed = NULL;
void ConsoleMessageManager::AddMessage(
Page* page,
const JavaScriptConsoleMessage& message)
{
// Process any delayed messages to make sure that messages
// appear in the right order in the console.
ProcessDelayedMessages();
message.AddToPage(page);
}
void ConsoleMessageManager::AddDelayedMessage(const JavaScriptConsoleMessage& message)
{
if (!m_delayed)
// Allocate a vector for the delayed messages. Will be
// deallocated when the delayed messages are processed
// in ProcessDelayedMessages().
m_delayed = new Vector<JavaScriptConsoleMessage>();
m_delayed->append(message);
}
void ConsoleMessageManager::ProcessDelayedMessages()
{
// If we have a delayed vector it cannot be empty.
if (!m_delayed)
return;
ASSERT(!m_delayed->isEmpty());
// Add the delayed messages to the page of the active
// context. If that for some bizarre reason does not
// exist, we clear the list of delayed messages to avoid
// posting messages. We still deallocate the vector.
Frame* frame = V8Proxy::retrieveActiveFrame();
Page* page = NULL;
if (frame)
page = frame->page();
if (!page)
m_delayed->clear();
// Iterate through all the delayed messages and add them
// to the console.
const int size = m_delayed->size();
for (int i = 0; i < size; i++) {
m_delayed->at(i).AddToPage(page);
}
// Deallocate the delayed vector.
delete m_delayed;
m_delayed = NULL;
}
// Convenience class for ensuring that delayed messages in the
// ConsoleMessageManager are processed quickly.
class ConsoleMessageScope {
public:
ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
~ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
};
void log_info(Frame* frame, const String& msg, const String& url)
{
Page* page = frame->page();
if (!page)
return;
JavaScriptConsoleMessage message(msg, url, 0);
ConsoleMessageManager::AddMessage(page, message);
}
static void HandleConsoleMessage(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data)
{
// Use the frame where JavaScript is called from.
Frame* frame = V8Proxy::retrieveActiveFrame();
if (!frame)
return;
Page* page = frame->page();
if (!page)
return;
v8::Handle<v8::String> errorMessageString = message->Get();
ASSERT(!errorMessageString.IsEmpty());
String errorMessage = ToWebCoreString(errorMessageString);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool useURL = (resourceName.IsEmpty() || !resourceName->IsString());
String resourceNameString = (useURL)
? frame->document()->url()
: ToWebCoreString(resourceName);
JavaScriptConsoleMessage consoleMessage(errorMessage,
resourceNameString,
message->GetLineNumber());
ConsoleMessageManager::AddMessage(page, consoleMessage);
}
enum DelayReporting {
REPORT_LATER,
REPORT_NOW
};
static void ReportUnsafeAccessTo(Frame* target, DelayReporting delay)
{
ASSERT(target);
Document* targetDocument = target->document();
if (!targetDocument)
return;
Frame* source = V8Proxy::retrieveActiveFrame();
if (!source || !source->document())
return; // Ignore error if the source document is gone.
Document* sourceDocument = source->document();
// FIXME: This error message should contain more specifics of why the same
// origin check has failed.
String str = String::format("Unsafe JavaScript attempt to access frame "
"with URL %s from frame with URL %s. "
"Domains, protocols and ports must match.\n",
targetDocument->url().string().utf8().data(),
sourceDocument->url().string().utf8().data());
// Build a console message with fake source ID and line number.
const String kSourceID = "";
const int kLineNumber = 1;
JavaScriptConsoleMessage message(str, kSourceID, kLineNumber);
if (delay == REPORT_NOW) {
// NOTE(tc): Apple prints the message in the target page, but it seems like
// it should be in the source page. Even for delayed messages, we put it in
// the source page; see ConsoleMessageManager::ProcessDelayedMessages().
ConsoleMessageManager::AddMessage(source->page(), message);
} else {
ASSERT(delay == REPORT_LATER);
// We cannot safely report the message eagerly, because this may cause
// allocations and GCs internally in V8 and we cannot handle that at this
// point. Therefore we delay the reporting.
ConsoleMessageManager::AddDelayedMessage(message);
}
}
static void ReportUnsafeJavaScriptAccess(v8::Local<v8::Object> host,
v8::AccessType type,
v8::Local<v8::Value> data)
{
Frame* target = V8Custom::GetTargetFrame(host, data);
if (target)
ReportUnsafeAccessTo(target, REPORT_LATER);
}
static void HandleFatalErrorInV8()
{
// TODO: We temporarily deal with V8 internal error situations
// such as out-of-memory by crashing the renderer.
CRASH();
}
static void ReportFatalErrorInV8(const char* location, const char* message)
{
// V8 is shutdown, we cannot use V8 api.
// The only thing we can do is to disable JavaScript.
// TODO: clean up V8Proxy and disable JavaScript.
printf("V8 error: %s (%s)\n", message, location);
HandleFatalErrorInV8();
}
V8Proxy::~V8Proxy()
{
clearForClose();
DestroyGlobal();
}
void V8Proxy::DestroyGlobal()
{
if (!m_global.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_global);
#endif
m_global.Dispose();
m_global.Clear();
}
}
bool V8Proxy::DOMObjectHasJSWrapper(void* obj) {
return GetDOMObjectMap().contains(obj) ||
GetActiveDOMObjectMap().contains(obj);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
ASSERT(false);
#undef MAKE_CASE
default: break;
}
#endif
GetDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForActiveDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE: break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default: ASSERT(false);
#undef MAKE_CASE
}
#endif
GetActiveDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased node's ref count.
void V8Proxy::SetJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
GetDOMNodeMap().set(node, wrapper);
}
PassRefPtr<EventListener> V8Proxy::createInlineEventListener(
const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#if ENABLE(SVG)
PassRefPtr<EventListener> V8Proxy::createSVGEventHandler(const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#endif
// Event listeners
static V8EventListener* FindEventListenerInList(V8EventListenerList& list,
v8::Local<v8::Value> listener,
bool isInline)
{
ASSERT(v8::Context::InContext());
if (!listener->IsObject())
return 0;
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
V8EventListener* el = *p;
v8::Local<v8::Object> wrapper = el->getListenerObject();
ASSERT(!wrapper.IsEmpty());
// Since the listener is an object, it is safe to compare for
// strict equality (in the JS sense) by doing a simple equality
// check using the == operator on the handles. This is much,
// much faster than calling StrictEquals through the API in
// the negative case.
if (el->isInline() == isInline && listener == wrapper)
return el;
++p;
}
return 0;
}
// Find an existing wrapper for a JS event listener in the map.
PassRefPtr<V8EventListener> V8Proxy::FindV8EventListener(v8::Local<v8::Value> listener,
bool isInline)
{
return FindEventListenerInList(m_event_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateV8EventListener(v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_event_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8EventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_event_listeners.push_back(new_listener.get());
return new_listener;
}
// Object event listeners (such as XmlHttpRequest and MessagePort) are
// different from listeners on DOM nodes. An object event listener wrapper
// only holds a weak reference to the JS function. A strong reference can
// create a cycle.
//
// The lifetime of these objects is bounded by the life time of its JS
// wrapper. So we can create a hidden reference from the JS wrapper to
// to its JS function.
//
// (map)
// XHR <---------- JS_wrapper
// | (hidden) : ^
// V V : (may reachable by closure)
// V8_listener --------> JS_function
// (weak) <-- may create a cycle if it is strong
//
// The persistent reference is made weak in the constructor
// of V8ObjectEventListener.
PassRefPtr<V8EventListener> V8Proxy::FindObjectEventListener(
v8::Local<v8::Value> listener, bool isInline)
{
return FindEventListenerInList(m_xhr_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateObjectEventListener(
v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_xhr_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8ObjectEventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_xhr_listeners.push_back(new_listener.get());
return new_listener.release();
}
static void RemoveEventListenerFromList(V8EventListenerList& list,
V8EventListener* listener)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
if (*p == listener) {
list.erase(p);
return;
}
++p;
}
}
void V8Proxy::RemoveV8EventListener(V8EventListener* listener)
{
RemoveEventListenerFromList(m_event_listeners, listener);
}
void V8Proxy::RemoveObjectEventListener(V8ObjectEventListener* listener)
{
RemoveEventListenerFromList(m_xhr_listeners, listener);
}
static void DisconnectEventListenersInList(V8EventListenerList& list)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
(*p)->disconnectFrame();
++p;
}
list.clear();
}
void V8Proxy::DisconnectEventListeners()
{
DisconnectEventListenersInList(m_event_listeners);
DisconnectEventListenersInList(m_xhr_listeners);
}
v8::Handle<v8::Script> V8Proxy::CompileScript(v8::Handle<v8::String> code,
const String& fileName,
int baseLine)
{
const uint16_t* fileNameString = FromWebCoreString(fileName);
v8::Handle<v8::String> name =
v8::String::New(fileNameString, fileName.length());
v8::Handle<v8::Integer> line = v8::Integer::New(baseLine);
v8::ScriptOrigin origin(name, line);
v8::Handle<v8::Script> script = v8::Script::Compile(code, &origin);
return script;
}
bool V8Proxy::HandleOutOfMemory()
{
v8::Local<v8::Context> context = v8::Context::GetCurrent();
if (!context->HasOutOfMemoryException())
return false;
// Warning, error, disable JS for this frame?
Frame* frame = V8Proxy::retrieveFrame(context);
V8Proxy* proxy = V8Proxy::retrieve(frame);
// Clean m_context, and event handlers.
proxy->clearForClose();
// Destroy the global object.
proxy->DestroyGlobal();
ChromiumBridge::notifyJSOutOfMemory(frame);
// Disable JS.
Settings* settings = frame->settings();
ASSERT(settings);
settings->setJavaScriptEnabled(false);
return true;
}
void V8Proxy::evaluateInNewContext(const Vector<ScriptSourceCode>& sources)
{
InitContextIfNeeded();
v8::HandleScope handleScope;
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> windowContext = m_context;
v8::Handle<v8::Object> windowGlobal = windowContext->Global();
v8::Handle<v8::Value> windowWrapper =
V8Proxy::LookupDOMWrapper(V8ClassIndex::DOMWINDOW, windowGlobal);
ASSERT(V8Proxy::DOMWrapperToNative<DOMWindow>(windowWrapper) ==
m_frame->domWindow());
v8::Persistent<v8::Context> context =
createNewContext(v8::Handle<v8::Object>());
v8::Context::Scope context_scope(context);
v8::Handle<v8::Object> global = context->Global();
v8::Handle<v8::String> implicitProtoString = v8::String::New("__proto__");
global->Set(implicitProtoString, windowWrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), windowGlobal);
// Run code in the new context.
for (size_t i = 0; i < sources.size(); ++i)
evaluate(sources[i], 0);
// Using the default security token means that the canAccess is always
// called, which is slow.
// TODO(aa): Use tokens where possible. This will mean keeping track of all
// created contexts so that they can all be updated when the document domain
// changes.
context->UseDefaultSecurityToken();
context.Dispose();
}
v8::Local<v8::Value> V8Proxy::evaluate(const ScriptSourceCode& source, Node* n)
{
ASSERT(v8::Context::InContext());
// Compile the script.
v8::Local<v8::String> code = v8ExternalString(source.source());
ChromiumBridge::traceEventBegin("v8.compile", n, "");
// NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at
// 1, whereas v8 starts at 0.
v8::Handle<v8::Script> script = CompileScript(code, source.url(),
source.startLine() - 1);
ChromiumBridge::traceEventEnd("v8.compile", n, "");
ChromiumBridge::traceEventBegin("v8.run", n, "");
v8::Local<v8::Value> result;
{
// Isolate exceptions that occur when executing the code. These
// exceptions should not interfere with javascript code we might
// evaluate from C++ when returning from here
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
// Set inlineCode to true for <a href="javascript:doSomething()">
// and false for <script>doSomething</script>. We make a rough guess at
// this based on whether the script source has a URL.
result = RunScript(script, source.url().string().isNull());
}
ChromiumBridge::traceEventEnd("v8.run", n, "");
return result;
}
v8::Local<v8::Value> V8Proxy::RunScript(v8::Handle<v8::Script> script,
bool inline_code)
{
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Compute the source string and prevent against infinite recursion.
if (m_recursion >= kMaxRecursionDepth) {
v8::Local<v8::String> code =
v8ExternalString("throw RangeError('Recursion too deep')");
// TODO(kasperl): Ideally, we should be able to re-use the origin of the
// script passed to us as the argument instead of using an empty string
// and 0 baseLine.
script = CompileScript(code, "", 0);
}
if (HandleOutOfMemory())
ASSERT(script.IsEmpty());
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Save the previous value of the inlineCode flag and update the flag for
// the duration of the script invocation.
bool previous_inline_code = inlineCode();
setInlineCode(inline_code);
// Run the script and keep track of the current recursion depth.
v8::Local<v8::Value> result;
{ ConsoleMessageScope scope;
m_recursion++;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = script->Run();
m_recursion--;
}
if (HandleOutOfMemory())
ASSERT(result.IsEmpty());
// Handle V8 internal error situation (Out-of-memory).
if (result.IsEmpty())
return v8::Local<v8::Value>();
// Restore inlineCode flag.
setInlineCode(previous_inline_code);
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Value> V8Proxy::CallFunction(v8::Handle<v8::Function> function,
v8::Handle<v8::Object> receiver,
int argc,
v8::Handle<v8::Value> args[])
{
// For now, we don't put any artificial limitations on the depth
// of recursion that stems from calling functions. This is in
// contrast to the script evaluations.
v8::Local<v8::Value> result;
{
ConsoleMessageScope scope;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = function->Call(receiver, argc, args);
}
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Function> V8Proxy::GetConstructor(V8ClassIndex::V8WrapperType t)
{
ASSERT(ContextInitialized());
v8::Local<v8::Value> cached =
m_dom_constructor_cache->Get(v8::Integer::New(V8ClassIndex::ToInt(t)));
if (cached->IsFunction()) {
return v8::Local<v8::Function>::Cast(cached);
}
// Not in cache.
{
// Enter the context of the proxy to make sure that the
// function is constructed in the context corresponding to
// this proxy.
v8::Context::Scope scope(m_context);
v8::Handle<v8::FunctionTemplate> templ = GetTemplate(t);
// Getting the function might fail if we're running out of
// stack or memory.
v8::TryCatch try_catch;
v8::Local<v8::Function> value = templ->GetFunction();
if (value.IsEmpty())
return v8::Local<v8::Function>();
m_dom_constructor_cache->Set(v8::Integer::New(t), value);
// Hotmail fix, see comments in v8_proxy.h above
// m_dom_constructor_cache.
value->Set(v8::String::New("__proto__"), m_object_prototype);
return value;
}
}
// Get the string 'toString'.
static v8::Persistent<v8::String> GetToStringName() {
static v8::Persistent<v8::String> value;
if (value.IsEmpty())
value = v8::Persistent<v8::String>::New(v8::String::New("toString"));
return value;
}
static v8::Handle<v8::Value> ConstructorToString(const v8::Arguments& args) {
// The DOM constructors' toString functions grab the current toString
// for Functions by taking the toString function of itself and then
// calling it with the constructor as its receiver. This means that
// changes to the Function prototype chain or toString function are
// reflected when printing DOM constructors. The only wart is that
// changes to a DOM constructor's toString's toString will cause the
// toString of the DOM constructor itself to change. This is extremely
// obscure and unlikely to be a problem.
v8::Handle<v8::Value> val = args.Callee()->Get(GetToStringName());
if (!val->IsFunction()) return v8::String::New("");
return v8::Handle<v8::Function>::Cast(val)->Call(args.This(), 0, NULL);
}
v8::Persistent<v8::FunctionTemplate> V8Proxy::GetTemplate(
V8ClassIndex::V8WrapperType type)
{
v8::Persistent<v8::FunctionTemplate>* cache_cell =
V8ClassIndex::GetCache(type);
if (!(*cache_cell).IsEmpty())
return *cache_cell;
// not found
FunctionTemplateFactory factory = V8ClassIndex::GetFactory(type);
v8::Persistent<v8::FunctionTemplate> desc = factory();
// DOM constructors are functions and should print themselves as such.
// However, we will later replace their prototypes with Object
// prototypes so we need to explicitly override toString on the
// instance itself. If we later make DOM constructors full objects
// we can give them class names instead and Object.prototype.toString
// will work so we can remove this code.
static v8::Persistent<v8::FunctionTemplate> to_string_template;
if (to_string_template.IsEmpty()) {
to_string_template = v8::Persistent<v8::FunctionTemplate>::New(
v8::FunctionTemplate::New(ConstructorToString));
}
desc->Set(GetToStringName(), to_string_template);
switch (type) {
case V8ClassIndex::CSSSTYLEDECLARATION:
// The named property handler for style declarations has a
// setter. Therefore, the interceptor has to be on the object
// itself and not on the prototype object.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(CSSStyleDeclaration),
USE_NAMED_PROPERTY_SETTER(CSSStyleDeclaration));
setCollectionStringOrNullIndexedGetter<CSSStyleDeclaration>(desc);
break;
case V8ClassIndex::CSSRULELIST:
setCollectionIndexedGetter<CSSRuleList, CSSRule>(desc,
V8ClassIndex::CSSRULE);
break;
case V8ClassIndex::CSSVALUELIST:
setCollectionIndexedGetter<CSSValueList, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::CSSVARIABLESDECLARATION:
setCollectionStringOrNullIndexedGetter<CSSVariablesDeclaration>(desc);
break;
case V8ClassIndex::WEBKITCSSTRANSFORMVALUE:
setCollectionIndexedGetter<WebKitCSSTransformValue, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::UNDETECTABLEHTMLCOLLECTION:
desc->InstanceTemplate()->MarkAsUndetectable(); // fall through
case V8ClassIndex::HTMLCOLLECTION:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
setCollectionIndexedGetter<HTMLCollection, Node>(desc,
V8ClassIndex::NODE);
break;
case V8ClassIndex::HTMLOPTIONSCOLLECTION:
setCollectionNamedGetter<HTMLOptionsCollection, Node>(
desc,
V8ClassIndex::NODE);
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLOptionsCollection),
USE_INDEXED_PROPERTY_SETTER(HTMLOptionsCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
break;
case V8ClassIndex::HTMLSELECTELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
nodeCollectionNamedPropertyGetter<HTMLSelectElement>,
0,
0,
0,
0,
v8::Integer::New(V8ClassIndex::NODE));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
nodeCollectionIndexedPropertyGetter<HTMLSelectElement>,
USE_INDEXED_PROPERTY_SETTER(HTMLSelectElementCollection),
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLSelectElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::HTMLDOCUMENT: {
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLDocument),
0,
0,
USE_NAMED_PROPERTY_DELETER(HTMLDocument));
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
//
// Additionally, we add two extra internal fields for
// HTMLDocuments to implement temporary shadowing of
// document.all. One field holds an object that is used as a
// marker. The other field holds the marker object if
// document.all is not shadowed and some other value if
// document.all is shadowed.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kHTMLDocumentInternalFieldCount);
break;
}
#if ENABLE(SVG)
case V8ClassIndex::SVGDOCUMENT: // fall through
#endif
case V8ClassIndex::DOCUMENT: {
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kDocumentMinimumInternalFieldCount);
break;
}
case V8ClassIndex::HTMLAPPLETELEMENT: // fall through
case V8ClassIndex::HTMLEMBEDELEMENT: // fall through
case V8ClassIndex::HTMLOBJECTELEMENT:
// HTMLAppletElement, HTMLEmbedElement and HTMLObjectElement are
// inherited from HTMLPlugInElement, and they share the same property
// handling code.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLPlugInElement),
USE_NAMED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLPlugInElement),
USE_INDEXED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLPlugInElement));
break;
case V8ClassIndex::HTMLFRAMESETELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFrameSetElement));
break;
case V8ClassIndex::HTMLFORMELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFormElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLFormElement),
0,
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLFormElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::CANVASPIXELARRAY:
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(CanvasPixelArray),
USE_INDEXED_PROPERTY_SETTER(CanvasPixelArray));
break;
case V8ClassIndex::STYLESHEET: // fall through
case V8ClassIndex::CSSSTYLESHEET: {
// We add an extra internal field to hold a reference to
// the owner node.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kStyleSheetInternalFieldCount);
break;
}
case V8ClassIndex::MEDIALIST:
setCollectionStringOrNullIndexedGetter<MediaList>(desc);
break;
case V8ClassIndex::MIMETYPEARRAY:
setCollectionIndexedAndNamedGetters<MimeTypeArray, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::NAMEDNODEMAP:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NamedNodeMap));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(NamedNodeMap),
0,
0,
0,
collectionIndexedPropertyEnumerator<NamedNodeMap>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::NODELIST:
setCollectionIndexedGetter<NodeList, Node>(desc, V8ClassIndex::NODE);
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NodeList));
break;
case V8ClassIndex::PLUGIN:
setCollectionIndexedAndNamedGetters<Plugin, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::PLUGINARRAY:
setCollectionIndexedAndNamedGetters<PluginArray, Plugin>(
desc,
V8ClassIndex::PLUGIN);
break;
case V8ClassIndex::STYLESHEETLIST:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(StyleSheetList));
setCollectionIndexedGetter<StyleSheetList, StyleSheet>(
desc,
V8ClassIndex::STYLESHEET);
break;
case V8ClassIndex::DOMWINDOW: {
v8::Local<v8::Signature> default_signature = v8::Signature::New(desc);
desc->PrototypeTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(DOMWindow));
desc->PrototypeTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(DOMWindow));
desc->SetHiddenPrototype(true);
// Reserve spaces for references to location and navigator objects.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
// Set access check callbacks, but turned off initially.
// When a context is detached from a frame, turn on the access check.
// Turning on checks also invalidates inline caches of the object.
instance_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW),
false);
break;
}
case V8ClassIndex::LOCATION: {
// For security reasons, these functions are on the instance
// instead of on the prototype object to insure that they cannot
// be overwritten.
v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate();
instance->SetAccessor(
v8::String::New("reload"),
V8Custom::v8LocationReloadAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("replace"),
V8Custom::v8LocationReplaceAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("assign"),
V8Custom::v8LocationAssignAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
break;
}
case V8ClassIndex::HISTORY: {
break;
}
case V8ClassIndex::MESSAGECHANNEL: {
// Reserve two more internal fields for referencing the port1
// and port2 wrappers. This ensures that the port wrappers are
// kept alive when the channel wrapper is.
desc->SetCallHandler(USE_CALLBACK(MessageChannelConstructor));
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessageChannelInternalFieldCount);
break;
}
case V8ClassIndex::MESSAGEPORT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessagePortInternalFieldCount);
break;
}
#if ENABLE(WORKERS)
case V8ClassIndex::WORKER: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(WorkerConstructor));
break;
}
case V8ClassIndex::WORKERCONTEXT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerContextInternalFieldCount);
break;
}
#endif // WORKERS
// The following objects are created from JavaScript.
case V8ClassIndex::DOMPARSER:
desc->SetCallHandler(USE_CALLBACK(DOMParserConstructor));
break;
case V8ClassIndex::WEBKITCSSMATRIX:
desc->SetCallHandler(USE_CALLBACK(WebKitCSSMatrixConstructor));
break;
case V8ClassIndex::WEBKITPOINT:
desc->SetCallHandler(USE_CALLBACK(WebKitPointConstructor));
break;
case V8ClassIndex::XMLSERIALIZER:
desc->SetCallHandler(USE_CALLBACK(XMLSerializerConstructor));
break;
case V8ClassIndex::XMLHTTPREQUEST: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(XMLHttpRequestConstructor));
break;
}
case V8ClassIndex::XMLHTTPREQUESTUPLOAD: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
break;
}
case V8ClassIndex::XPATHEVALUATOR:
desc->SetCallHandler(USE_CALLBACK(XPathEvaluatorConstructor));
break;
case V8ClassIndex::XSLTPROCESSOR:
desc->SetCallHandler(USE_CALLBACK(XSLTProcessorConstructor));
break;
default:
break;
}
*cache_cell = desc;
return desc;
}
bool V8Proxy::ContextInitialized()
{
// m_context, m_global, m_object_prototype, and
// m_dom_constructor_cache should all be non-empty if m_context is
// non-empty.
ASSERT(m_context.IsEmpty() || !m_global.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_object_prototype.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_dom_constructor_cache.IsEmpty());
return !m_context.IsEmpty();
}
DOMWindow* V8Proxy::retrieveWindow()
{
// TODO: This seems very fragile. How do we know that the global object
// from the current context is something sensible? Do we need to use the
// last entered here? Who calls this?
return retrieveWindow(v8::Context::GetCurrent());
}
DOMWindow* V8Proxy::retrieveWindow(v8::Handle<v8::Context> context)
{
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
return ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, global);
}
Frame* V8Proxy::retrieveFrame(v8::Handle<v8::Context> context)
{
return retrieveWindow(context)->frame();
}
Frame* V8Proxy::retrieveActiveFrame()
{
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return 0;
return retrieveFrame(context);
}
Frame* V8Proxy::retrieveFrame()
{
DOMWindow* window = retrieveWindow();
return window ? window->frame() : 0;
}
V8Proxy* V8Proxy::retrieve()
{
DOMWindow* window = retrieveWindow();
ASSERT(window);
return retrieve(window->frame());
}
V8Proxy* V8Proxy::retrieve(Frame* frame)
{
if (!frame)
return 0;
return frame->script()->isEnabled() ? frame->script()->proxy() : 0;
}
V8Proxy* V8Proxy::retrieve(ScriptExecutionContext* context)
{
if (!context->isDocument())
return 0;
return retrieve(static_cast<Document*>(context)->frame());
}
void V8Proxy::disconnectFrame()
{
// disconnect all event listeners
DisconnectEventListeners();
}
bool V8Proxy::isEnabled()
{
Settings* settings = m_frame->settings();
if (!settings)
return false;
// In the common case, JavaScript is enabled and we're done.
if (settings->isJavaScriptEnabled())
return true;
// If JavaScript has been disabled, we need to look at the frame to tell
// whether this script came from the web or the embedder. Scripts from the
// embedder are safe to run, but scripts from the other sources are
// disallowed.
Document* document = m_frame->document();
if (!document)
return false;
SecurityOrigin* origin = document->securityOrigin();
if (origin->protocol().isEmpty())
return false; // Uninitialized document
if (origin->protocol() == "http" || origin->protocol() == "https")
return false; // Web site
// TODO(darin): the following are application decisions, and they should
// not be made at this layer. instead, we should bridge out to the
// embedder to allow them to override policy here.
if (origin->protocol() == ChromiumBridge::uiResourceProtocol())
return true; // Embedder's scripts are ok to run
// If the scheme is ftp: or file:, an empty file name indicates a directory
// listing, which requires JavaScript to function properly.
const char* kDirProtocols[] = { "ftp", "file" };
for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
if (origin->protocol() == kDirProtocols[i]) {
const KURL& url = document->url();
return url.pathAfterLastSlash() == url.pathEnd();
}
}
return false; // Other protocols fall through to here
}
void V8Proxy::UpdateDocumentWrapper(v8::Handle<v8::Value> wrapper) {
ClearDocumentWrapper();
ASSERT(m_document.IsEmpty());
m_document = v8::Persistent<v8::Value>::New(wrapper);
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_document);
#endif
}
void V8Proxy::ClearDocumentWrapper()
{
if (!m_document.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_document);
#endif
m_document.Dispose();
m_document.Clear();
}
}
void V8Proxy::DisposeContextHandles() {
if (!m_context.IsEmpty()) {
m_context.Dispose();
m_context.Clear();
}
if (!m_dom_constructor_cache.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_dom_constructor_cache);
#endif
m_dom_constructor_cache.Dispose();
m_dom_constructor_cache.Clear();
}
if (!m_object_prototype.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_object_prototype);
#endif
m_object_prototype.Dispose();
m_object_prototype.Clear();
}
}
void V8Proxy::clearForClose()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle_scope;
ClearDocumentWrapper();
DisposeContextHandles();
}
}
void V8Proxy::clearForNavigation()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle;
ClearDocumentWrapper();
v8::Context::Scope context_scope(m_context);
// Turn on access check on the old DOMWindow wrapper.
v8::Handle<v8::Object> wrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, m_global);
ASSERT(!wrapper.IsEmpty());
wrapper->TurnOnAccessCheck();
// disconnect all event listeners
DisconnectEventListeners();
// Separate the context from its global object.
m_context->DetachGlobal();
DisposeContextHandles();
// Reinitialize the context so the global object points to
// the new DOM window.
InitContextIfNeeded();
}
}
void V8Proxy::SetSecurityToken() {
Document* document = m_frame->document();
// Setup security origin and security token
if (!document) {
m_context->UseDefaultSecurityToken();
return;
}
// Ask the document's SecurityOrigin to generate a security token.
// If two tokens are equal, then the SecurityOrigins canAccess each other.
// If two tokens are not equal, then we have to call canAccess.
// Note: we can't use the HTTPOrigin if it was set from the DOM.
SecurityOrigin* origin = document->securityOrigin();
String token;
if (!origin->domainWasSetInDOM())
token = document->securityOrigin()->toString();
// An empty token means we always have to call canAccess. In this case, we
// use the global object as the security token to avoid calling canAccess
// when a script accesses its own objects.
if (token.isEmpty()) {
m_context->UseDefaultSecurityToken();
return;
}
CString utf8_token = token.utf8();
// NOTE: V8 does identity comparison in fast path, must use a symbol
// as the security token.
m_context->SetSecurityToken(
v8::String::NewSymbol(utf8_token.data(), utf8_token.length()));
}
void V8Proxy::updateDocument()
{
if (!m_frame->document())
return;
if (m_global.IsEmpty()) {
ASSERT(m_context.IsEmpty());
return;
}
{
v8::HandleScope scope;
SetSecurityToken();
}
}
void V8Proxy::updateSecurityOrigin()
{
v8::HandleScope scope;
SetSecurityToken();
}
// Same origin policy implementation:
//
// Same origin policy prevents JS code from domain A access JS & DOM objects
// in a different domain B. There are exceptions and several objects are
// accessible by cross-domain code. For example, the window.frames object is
// accessible by code from a different domain, but window.document is not.
//
// The binding code sets security check callbacks on a function template,
// and accessing instances of the template calls the callback function.
// The callback function checks same origin policy.
//
// Callback functions are expensive. V8 uses a security token string to do
// fast access checks for the common case where source and target are in the
// same domain. A security token is a string object that represents
// the protocol/url/port of a domain.
//
// There are special cases where a security token matching is not enough.
// For example, JavaScript can set its domain to a super domain by calling
// document.setDomain(...). In these cases, the binding code can reset
// a context's security token to its global object so that the fast access
// check will always fail.
// Check if the current execution context can access a target frame.
// First it checks same domain policy using the lexical context
//
// This is equivalent to KJS::Window::allowsAccessFrom(ExecState*, String&).
bool V8Proxy::CanAccessPrivate(DOMWindow* target_window)
{
ASSERT(target_window);
String message;
DOMWindow* origin_window = retrieveWindow();
if (origin_window == target_window)
return true;
if (!origin_window)
return false;
// JS may be attempting to access the "window" object, which should be
// valid, even if the document hasn't been constructed yet.
// If the document doesn't exist yet allow JS to access the window object.
if (!origin_window->document())
return true;
const SecurityOrigin* active_security_origin = origin_window->securityOrigin();
const SecurityOrigin* target_security_origin = target_window->securityOrigin();
// We have seen crashes were the security origin of the target has not been
// initialized. Defend against that.
ASSERT(target_security_origin);
if (!target_security_origin)
return false;
if (active_security_origin->canAccess(target_security_origin))
return true;
// Allow access to a "about:blank" page if the dynamic context is a
// detached context of the same frame as the blank page.
if (target_security_origin->isEmpty() &&
origin_window->frame() == target_window->frame())
return true;
return false;
}
bool V8Proxy::CanAccessFrame(Frame* target, bool report_error)
{
// The subject is detached from a frame, deny accesses.
if (!target)
return false;
if (!CanAccessPrivate(target->domWindow())) {
if (report_error)
ReportUnsafeAccessTo(target, REPORT_NOW);
return false;
}
return true;
}
bool V8Proxy::CheckNodeSecurity(Node* node)
{
if (!node)
return false;
Frame* target = node->document()->frame();
if (!target)
return false;
return CanAccessFrame(target, true);
}
v8::Persistent<v8::Context> V8Proxy::createNewContext(
v8::Handle<v8::Object> global)
{
v8::Persistent<v8::Context> result;
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Persistent<v8::ObjectTemplate> globalTemplate =
V8DOMWindow::GetShadowObjectTemplate();
if (globalTemplate.IsEmpty())
return result;
// Install a security handler with V8.
globalTemplate->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
// Dynamically tell v8 about our extensions now.
const char** extensionNames = new const char*[m_extensions.size()];
int index = 0;
V8ExtensionList::iterator it = m_extensions.begin();
while (it != m_extensions.end()) {
extensionNames[index++] = (*it)->name();
++it;
}
v8::ExtensionConfiguration extensions(m_extensions.size(), extensionNames);
result = v8::Context::New(&extensions, globalTemplate, global);
delete [] extensionNames;
extensionNames = 0;
return result;
}
// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance. However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object. The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript. The javascript object that corresponds to a
// DOMWindow instance is the shadow object. When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
//
// To implement split-window, see
// 1) https://bugs.webkit.org/show_bug.cgi?id=17249
// 2) https://wiki.mozilla.org/Gecko:SplitWindow
// 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
// we need to split the shadow object further into two objects:
// an outer window and an inner window. The inner window is the hidden
// prototype of the outer window. The inner window is the default
// global object of the context. A variable declared in the global
// scope is a property of the inner window.
//
// The outer window sticks to a Frame, it is exposed to JavaScript
// via window.window, window.self, window.parent, etc. The outer window
// has a security token which is the domain. The outer window cannot
// have its own properties. window.foo = 'x' is delegated to the
// inner window.
//
// When a frame navigates to a new page, the inner window is cut off
// the outer window, and the outer window identify is preserved for
// the frame. However, a new inner window is created for the new page.
// If there are JS code holds a closure to the old inner window,
// it won't be able to reach the outer window via its global object.
void V8Proxy::InitContextIfNeeded()
{
// Bail out if the context has already been initialized.
if (!m_context.IsEmpty())
return;
// Create a handle scope for all local handles.
v8::HandleScope handle_scope;
// Setup the security handlers and message listener. This only has
// to be done once.
static bool v8_initialized = false;
if (!v8_initialized) {
// Tells V8 not to call the default OOM handler, binding code
// will handle it.
v8::V8::IgnoreOutOfMemoryException();
v8::V8::SetFatalErrorHandler(ReportFatalErrorInV8);
v8::V8::SetGlobalGCPrologueCallback(&GCPrologue);
v8::V8::SetGlobalGCEpilogueCallback(&GCEpilogue);
v8::V8::AddMessageListener(HandleConsoleMessage);
v8::V8::SetFailedAccessCheckCallbackFunction(ReportUnsafeJavaScriptAccess);
v8_initialized = true;
}
m_context = createNewContext(m_global);
if (m_context.IsEmpty())
return;
// Starting from now, use local context only.
v8::Local<v8::Context> context = GetContext();
v8::Context::Scope context_scope(context);
// Store the first global object created so we can reuse it.
if (m_global.IsEmpty()) {
m_global = v8::Persistent<v8::Object>::New(context->Global());
// Bail out if allocation of the first global objects fails.
if (m_global.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_global);
#endif
}
// Allocate strings used during initialization.
v8::Handle<v8::String> object_string = v8::String::New("Object");
v8::Handle<v8::String> prototype_string = v8::String::New("prototype");
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
// Bail out if allocation failed.
if (object_string.IsEmpty() ||
prototype_string.IsEmpty() ||
implicit_proto_string.IsEmpty()) {
DisposeContextHandles();
return;
}
// Allocate DOM constructor cache.
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(
m_global->Get(object_string));
m_object_prototype = v8::Persistent<v8::Value>::New(
object->Get(prototype_string));
m_dom_constructor_cache = v8::Persistent<v8::Array>::New(
v8::Array::New(V8ClassIndex::WRAPPER_TYPE_COUNT));
// Bail out if allocation failed.
if (m_object_prototype.IsEmpty() || m_dom_constructor_cache.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_object_prototype);
RegisterGlobalHandle(PROXY, this, m_dom_constructor_cache);
#endif
// Create a new JS window object and use it as the prototype for the
// shadow global object.
v8::Handle<v8::Function> window_constructor =
GetConstructor(V8ClassIndex::DOMWINDOW);
v8::Local<v8::Object> js_window =
SafeAllocation::NewInstance(window_constructor);
// Bail out if allocation failed.
if (js_window.IsEmpty()) {
DisposeContextHandles();
return;
}
DOMWindow* window = m_frame->domWindow();
// Wrap the window.
SetDOMWrapper(js_window,
V8ClassIndex::ToInt(V8ClassIndex::DOMWINDOW),
window);
window->ref();
V8Proxy::SetJSWrapperForDOMObject(window,
v8::Persistent<v8::Object>::New(js_window));
// Insert the window instance as the prototype of the shadow object.
v8::Handle<v8::Object> v8_global = context->Global();
v8_global->Set(implicit_proto_string, js_window);
SetSecurityToken();
m_frame->loader()->dispatchWindowObjectAvailable();
}
void V8Proxy::SetDOMException(int exception_code)
{
if (exception_code <= 0)
return;
ExceptionCodeDescription description;
getExceptionCodeDescription(exception_code, description);
v8::Handle<v8::Value> exception;
switch (description.type) {
case DOMExceptionType:
exception = ToV8Object(V8ClassIndex::DOMCOREEXCEPTION,
DOMCoreException::create(description));
break;
case RangeExceptionType:
exception = ToV8Object(V8ClassIndex::RANGEEXCEPTION,
RangeException::create(description));
break;
case EventExceptionType:
exception = ToV8Object(V8ClassIndex::EVENTEXCEPTION,
EventException::create(description));
break;
case XMLHttpRequestExceptionType:
exception = ToV8Object(V8ClassIndex::XMLHTTPREQUESTEXCEPTION,
XMLHttpRequestException::create(description));
break;
#if ENABLE(SVG)
case SVGExceptionType:
exception = ToV8Object(V8ClassIndex::SVGEXCEPTION,
SVGException::create(description));
break;
#endif
#if ENABLE(XPATH)
case XPathExceptionType:
exception = ToV8Object(V8ClassIndex::XPATHEXCEPTION,
XPathException::create(description));
break;
#endif
}
ASSERT(!exception.IsEmpty());
v8::ThrowException(exception);
}
v8::Handle<v8::Value> V8Proxy::ThrowError(ErrorType type, const char* message)
{
switch (type) {
case RANGE_ERROR:
return v8::ThrowException(v8::Exception::RangeError(v8String(message)));
case REFERENCE_ERROR:
return v8::ThrowException(
v8::Exception::ReferenceError(v8String(message)));
case SYNTAX_ERROR:
return v8::ThrowException(v8::Exception::SyntaxError(v8String(message)));
case TYPE_ERROR:
return v8::ThrowException(v8::Exception::TypeError(v8String(message)));
case GENERAL_ERROR:
return v8::ThrowException(v8::Exception::Error(v8String(message)));
default:
ASSERT(false);
return v8::Handle<v8::Value>();
}
}
v8::Local<v8::Context> V8Proxy::GetContext(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
if (!proxy)
return v8::Local<v8::Context>();
proxy->InitContextIfNeeded();
return proxy->GetContext();
}
v8::Local<v8::Context> V8Proxy::GetCurrentContext()
{
return v8::Context::GetCurrent();
}
v8::Handle<v8::Value> V8Proxy::ToV8Object(V8ClassIndex::V8WrapperType type, void* imp)
{
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(type != V8ClassIndex::EVENT);
bool is_active_dom_object = false;
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
return NodeToV8Object(static_cast<Node*>(imp));
case V8ClassIndex::CSSVALUE:
return CSSValueToV8Object(static_cast<CSSValue*>(imp));
case V8ClassIndex::CSSRULE:
return CSSRuleToV8Object(static_cast<CSSRule*>(imp));
case V8ClassIndex::STYLESHEET:
return StyleSheetToV8Object(static_cast<StyleSheet*>(imp));
case V8ClassIndex::DOMWINDOW:
return WindowToV8Object(static_cast<DOMWindow*>(imp));
#if ENABLE(SVG)
SVG_NONNODE_TYPES(MAKE_CASE)
if (type == V8ClassIndex::SVGELEMENTINSTANCE)
return SVGElementInstanceToV8Object(static_cast<SVGElementInstance*>(imp));
return SVGObjectWithContextToV8Object(type, imp);
#endif
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
is_active_dom_object = true;
break;
default:
break;
}
#undef MAKE_CASE
if (!imp) return v8::Null();
// Non DOM node
v8::Persistent<v8::Object> result = is_active_dom_object ?
GetActiveDOMObjectMap().get(imp) :
GetDOMObjectMap().get(imp);
if (result.IsEmpty()) {
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, imp);
if (!v8obj.IsEmpty()) {
// Go through big switch statement, it has some duplications
// that were handled by code above (such as CSSVALUE, CSSRULE, etc).
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(imp)->ref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
result = v8::Persistent<v8::Object>::New(v8obj);
if (is_active_dom_object)
SetJSWrapperForActiveDOMObject(imp, result);
else
SetJSWrapperForDOMObject(imp, result);
// Special case for Location and Navigator. Both Safari and FF let
// Location and Navigator JS wrappers survive GC. To mimic their
// behaviors, V8 creates hidden references from the DOMWindow to
// location and navigator objects. These references get cleared
// when the DOMWindow is reused by a new page.
if (type == V8ClassIndex::LOCATION) {
SetHiddenWindowReference(static_cast<Location*>(imp)->frame(),
V8Custom::kDOMWindowLocationIndex, result);
} else if (type == V8ClassIndex::NAVIGATOR) {
SetHiddenWindowReference(static_cast<Navigator*>(imp)->frame(),
V8Custom::kDOMWindowNavigatorIndex, result);
}
}
}
return result;
}
void V8Proxy::SetHiddenWindowReference(Frame* frame,
const int internal_index,
v8::Handle<v8::Object> jsobj)
{
// Get DOMWindow
if (!frame) return; // Object might be detached from window
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty()) return;
ASSERT(internal_index < V8Custom::kDOMWindowInternalFieldCount);
v8::Handle<v8::Object> global = context->Global();
// Look for real DOM wrapper.
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
ASSERT(global->GetInternalField(internal_index)->IsUndefined());
global->SetInternalField(internal_index, jsobj);
}
V8ClassIndex::V8WrapperType V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object> object)
{
ASSERT(MaybeDOMWrapper(object));
v8::Handle<v8::Value> type =
object->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
return V8ClassIndex::FromInt(type->Int32Value());
}
void* V8Proxy::ToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
v8::Handle<v8::Value> object)
{
// Native event listener is per frame, it cannot be handled
// by this generic function.
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(MaybeDOMWrapper(object));
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
ASSERT(false);
return NULL;
case V8ClassIndex::XMLHTTPREQUEST:
return DOMWrapperToNative<XMLHttpRequest>(object);
case V8ClassIndex::EVENT:
return DOMWrapperToNative<Event>(object);
case V8ClassIndex::CSSRULE:
return DOMWrapperToNative<CSSRule>(object);
default:
break;
}
#undef MAKE_CASE
return DOMWrapperToNative<void>(object);
}
v8::Handle<v8::Object> V8Proxy::LookupDOMWrapper(
V8ClassIndex::V8WrapperType type, v8::Handle<v8::Value> value)
{
if (value.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::FunctionTemplate> desc = V8Proxy::GetTemplate(type);
while (value->IsObject()) {
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
if (desc->HasInstance(object))
return object;
value = object->GetPrototype();
}
return v8::Handle<v8::Object>();
}
PassRefPtr<NodeFilter> V8Proxy::ToNativeNodeFilter(v8::Handle<v8::Value> filter)
{
// A NodeFilter is used when walking through a DOM tree or iterating tree
// nodes.
// TODO: we may want to cache NodeFilterCondition and NodeFilter
// object, but it is minor.
// NodeFilter is passed to NodeIterator that has a ref counted pointer
// to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
// In NodeFilterCondition, filter object is persisted in its constructor,
// and disposed in its destructor.
if (!filter->IsFunction())
return 0;
NodeFilterCondition* cond = new V8NodeFilterCondition(filter);
return NodeFilter::create(cond);
}
v8::Local<v8::Object> V8Proxy::InstantiateV8Object(
V8ClassIndex::V8WrapperType desc_type,
V8ClassIndex::V8WrapperType cptr_type,
void* imp)
{
// Make a special case for document.all
if (desc_type == V8ClassIndex::HTMLCOLLECTION &&
static_cast<HTMLCollection*>(imp)->type() == HTMLCollection::DocAll) {
desc_type = V8ClassIndex::UNDETECTABLEHTMLCOLLECTION;
}
v8::Local<v8::Function> function;
V8Proxy* proxy = V8Proxy::retrieve();
if (proxy) {
// Make sure that the context of the proxy has been initialized.
proxy->InitContextIfNeeded();
// Constructor is configured.
function = proxy->GetConstructor(desc_type);
} else {
function = GetTemplate(desc_type)->GetFunction();
}
v8::Local<v8::Object> instance = SafeAllocation::NewInstance(function);
if (!instance.IsEmpty()) {
// Avoid setting the DOM wrapper for failed allocations.
SetDOMWrapper(instance, V8ClassIndex::ToInt(cptr_type), imp);
}
return instance;
}
v8::Handle<v8::Value> V8Proxy::CheckNewLegal(const v8::Arguments& args)
{
if (!AllowAllocation::m_current)
return ThrowError(TYPE_ERROR, "Illegal constructor");
return args.This();
}
void V8Proxy::SetDOMWrapper(v8::Handle<v8::Object> obj, int type, void* cptr)
{
ASSERT(obj->InternalFieldCount() >= 2);
obj->SetInternalField(V8Custom::kDOMWrapperObjectIndex, WrapCPointer(cptr));
obj->SetInternalField(V8Custom::kDOMWrapperTypeIndex, v8::Integer::New(type));
}
#ifndef NDEBUG
bool V8Proxy::MaybeDOMWrapper(v8::Handle<v8::Value> value)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
return true;
}
#endif
bool V8Proxy::IsDOMEventWrapper(v8::Handle<v8::Value> value)
{
// All kinds of events use EVENT as dom type in JS wrappers.
// See EventToV8Object
return IsWrapperOfType(value, V8ClassIndex::EVENT);
}
bool V8Proxy::IsWrapperOfType(v8::Handle<v8::Value> value,
V8ClassIndex::V8WrapperType classType)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
return V8ClassIndex::FromInt(type->Int32Value()) == classType;
}
#if ENABLE(VIDEO)
#define FOR_EACH_VIDEO_TAG(macro) \
macro(audio, AUDIO) \
macro(source, SOURCE) \
macro(video, VIDEO)
#else
#define FOR_EACH_VIDEO_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
macro(a, ANCHOR) \
macro(applet, APPLET) \
macro(area, AREA) \
macro(base, BASE) \
macro(basefont, BASEFONT) \
macro(blockquote, BLOCKQUOTE) \
macro(body, BODY) \
macro(br, BR) \
macro(button, BUTTON) \
macro(caption, TABLECAPTION) \
macro(col, TABLECOL) \
macro(colgroup, TABLECOL) \
macro(del, MOD) \
macro(canvas, CANVAS) \
macro(dir, DIRECTORY) \
macro(div, DIV) \
macro(dl, DLIST) \
macro(embed, EMBED) \
macro(fieldset, FIELDSET) \
macro(font, FONT) \
macro(form, FORM) \
macro(frame, FRAME) \
macro(frameset, FRAMESET) \
macro(h1, HEADING) \
macro(h2, HEADING) \
macro(h3, HEADING) \
macro(h4, HEADING) \
macro(h5, HEADING) \
macro(h6, HEADING) \
macro(head, HEAD) \
macro(hr, HR) \
macro(html, HTML) \
macro(img, IMAGE) \
macro(iframe, IFRAME) \
macro(image, IMAGE) \
macro(input, INPUT) \
macro(ins, MOD) \
macro(isindex, ISINDEX) \
macro(keygen, SELECT) \
macro(label, LABEL) \
macro(legend, LEGEND) \
macro(li, LI) \
macro(link, LINK) \
macro(listing, PRE) \
macro(map, MAP) \
macro(marquee, MARQUEE) \
macro(menu, MENU) \
macro(meta, META) \
macro(object, OBJECT) \
macro(ol, OLIST) \
macro(optgroup, OPTGROUP) \
macro(option, OPTION) \
macro(p, PARAGRAPH) \
macro(param, PARAM) \
macro(pre, PRE) \
macro(q, QUOTE) \
macro(script, SCRIPT) \
macro(select, SELECT) \
macro(style, STYLE) \
macro(table, TABLE) \
macro(thead, TABLESECTION) \
macro(tbody, TABLESECTION) \
macro(tfoot, TABLESECTION) \
macro(td, TABLECELL) \
macro(th, TABLECELL) \
macro(tr, TABLEROW) \
macro(textarea, TEXTAREA) \
macro(title, TITLE) \
macro(ul, ULIST) \
macro(xmp, PRE)
V8ClassIndex::V8WrapperType V8Proxy::GetHTMLElementType(HTMLElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::HTML##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#if ENABLE(VIDEO)
if (MediaPlayer::isAvailable()) {
FOR_EACH_VIDEO_TAG(ADD_TO_HASH_MAP)
}
#endif
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0)
return V8ClassIndex::HTMLELEMENT;
return t;
}
#undef FOR_EACH_TAG
#if ENABLE(SVG)
#if ENABLE(SVG_ANIMATION)
#define FOR_EACH_ANIMATION_TAG(macro) \
macro(animateColor, ANIMATECOLOR) \
macro(animate, ANIMATE) \
macro(animateTransform, ANIMATETRANSFORM) \
macro(set, SET)
#else
#define FOR_EACH_ANIMATION_TAG(macro)
#endif
#if ENABLE(SVG_FILTERS)
#define FOR_EACH_FILTERS_TAG(macro) \
macro(feBlend, FEBLEND) \
macro(feColorMatrix, FECOLORMATRIX) \
macro(feComponentTransfer, FECOMPONENTTRANSFER) \
macro(feComposite, FECOMPOSITE) \
macro(feDiffuseLighting, FEDIFFUSELIGHTING) \
macro(feDisplacementMap, FEDISPLACEMENTMAP) \
macro(feDistantLight, FEDISTANTLIGHT) \
macro(feFlood, FEFLOOD) \
macro(feFuncA, FEFUNCA) \
macro(feFuncB, FEFUNCB) \
macro(feFuncG, FEFUNCG) \
macro(feFuncR, FEFUNCR) \
macro(feGaussianBlur, FEGAUSSIANBLUR) \
macro(feImage, FEIMAGE) \
macro(feMerge, FEMERGE) \
macro(feMergeNode, FEMERGENODE) \
macro(feOffset, FEOFFSET) \
macro(fePointLight, FEPOINTLIGHT) \
macro(feSpecularLighting, FESPECULARLIGHTING) \
macro(feSpotLight, FESPOTLIGHT) \
macro(feTile, FETILE) \
macro(feTurbulence, FETURBULENCE) \
macro(filter, FILTER)
#else
#define FOR_EACH_FILTERS_TAG(macro)
#endif
#if ENABLE(SVG_FONTS)
#define FOR_EACH_FONTS_TAG(macro) \
macro(definition-src, DEFINITIONSRC) \
macro(font-face, FONTFACE) \
macro(font-face-format, FONTFACEFORMAT) \
macro(font-face-name, FONTFACENAME) \
macro(font-face-src, FONTFACESRC) \
macro(font-face-uri, FONTFACEURI)
#else
#define FOR_EACH_FONTS_TAG(marco)
#endif
#if ENABLE(SVG_FOREIGN_OBJECT)
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
macro(foreignObject, FOREIGNOBJECT)
#else
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro)
#endif
#if ENABLE(SVG_USE)
#define FOR_EACH_USE_TAG(macro) \
macro(use, USE)
#else
#define FOR_EACH_USE_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
FOR_EACH_ANIMATION_TAG(macro) \
FOR_EACH_FILTERS_TAG(macro) \
FOR_EACH_FONTS_TAG(macro) \
FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
FOR_EACH_USE_TAG(macro) \
macro(a, A) \
macro(altGlyph, ALTGLYPH) \
macro(circle, CIRCLE) \
macro(clipPath, CLIPPATH) \
macro(cursor, CURSOR) \
macro(defs, DEFS) \
macro(desc, DESC) \
macro(ellipse, ELLIPSE) \
macro(g, G) \
macro(glyph, GLYPH) \
macro(image, IMAGE) \
macro(linearGradient, LINEARGRADIENT) \
macro(line, LINE) \
macro(marker, MARKER) \
macro(mask, MASK) \
macro(metadata, METADATA) \
macro(path, PATH) \
macro(pattern, PATTERN) \
macro(polyline, POLYLINE) \
macro(polygon, POLYGON) \
macro(radialGradient, RADIALGRADIENT) \
macro(rect, RECT) \
macro(script, SCRIPT) \
macro(stop, STOP) \
macro(style, STYLE) \
macro(svg, SVG) \
macro(switch, SWITCH) \
macro(symbol, SYMBOL) \
macro(text, TEXT) \
macro(textPath, TEXTPATH) \
macro(title, TITLE) \
macro(tref, TREF) \
macro(tspan, TSPAN) \
macro(view, VIEW) \
// end of macro
V8ClassIndex::V8WrapperType V8Proxy::GetSVGElementType(SVGElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::SVG##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0) return V8ClassIndex::SVGELEMENT;
return t;
}
#undef FOR_EACH_TAG
#endif // ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::EventToV8Object(Event* event)
{
if (!event)
return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(event);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT;
if (event->isUIEvent()) {
if (event->isKeyboardEvent())
type = V8ClassIndex::KEYBOARDEVENT;
else if (event->isTextEvent())
type = V8ClassIndex::TEXTEVENT;
else if (event->isMouseEvent())
type = V8ClassIndex::MOUSEEVENT;
else if (event->isWheelEvent())
type = V8ClassIndex::WHEELEVENT;
#if ENABLE(SVG)
else if (event->isSVGZoomEvent())
type = V8ClassIndex::SVGZOOMEVENT;
#endif
else
type = V8ClassIndex::UIEVENT;
} else if (event->isMutationEvent())
type = V8ClassIndex::MUTATIONEVENT;
else if (event->isOverflowEvent())
type = V8ClassIndex::OVERFLOWEVENT;
else if (event->isMessageEvent())
type = V8ClassIndex::MESSAGEEVENT;
else if (event->isProgressEvent()) {
if (event->isXMLHttpRequestProgressEvent())
type = V8ClassIndex::XMLHTTPREQUESTPROGRESSEVENT;
else
type = V8ClassIndex::PROGRESSEVENT;
} else if (event->isWebKitAnimationEvent())
type = V8ClassIndex::WEBKITANIMATIONEVENT;
else if (event->isWebKitTransitionEvent())
type = V8ClassIndex::WEBKITTRANSITIONEVENT;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::EVENT, event);
if (result.IsEmpty()) {
// Instantiation failed. Avoid updating the DOM object map and
// return null which is already handled by callers of this function
// in case the event is NULL.
return v8::Null();
}
event->ref(); // fast ref
SetJSWrapperForDOMObject(event, v8::Persistent<v8::Object>::New(result));
return result;
}
// Caller checks node is not null.
v8::Handle<v8::Value> V8Proxy::NodeToV8Object(Node* node)
{
if (!node) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMNodeMap().get(node);
if (!wrapper.IsEmpty())
return wrapper;
bool is_document = false; // document type node has special handling
V8ClassIndex::V8WrapperType type;
switch (node->nodeType()) {
case Node::ELEMENT_NODE:
if (node->isHTMLElement())
type = GetHTMLElementType(static_cast<HTMLElement*>(node));
#if ENABLE(SVG)
else if (node->isSVGElement())
type = GetSVGElementType(static_cast<SVGElement*>(node));
#endif
else
type = V8ClassIndex::ELEMENT;
break;
case Node::ATTRIBUTE_NODE:
type = V8ClassIndex::ATTR;
break;
case Node::TEXT_NODE:
type = V8ClassIndex::TEXT;
break;
case Node::CDATA_SECTION_NODE:
type = V8ClassIndex::CDATASECTION;
break;
case Node::ENTITY_NODE:
type = V8ClassIndex::ENTITY;
break;
case Node::PROCESSING_INSTRUCTION_NODE:
type = V8ClassIndex::PROCESSINGINSTRUCTION;
break;
case Node::COMMENT_NODE:
type = V8ClassIndex::COMMENT;
break;
case Node::DOCUMENT_NODE: {
is_document = true;
Document* doc = static_cast<Document*>(node);
if (doc->isHTMLDocument())
type = V8ClassIndex::HTMLDOCUMENT;
#if ENABLE(SVG)
else if (doc->isSVGDocument())
type = V8ClassIndex::SVGDOCUMENT;
#endif
else
type = V8ClassIndex::DOCUMENT;
break;
}
case Node::DOCUMENT_TYPE_NODE:
type = V8ClassIndex::DOCUMENTTYPE;
break;
case Node::NOTATION_NODE:
type = V8ClassIndex::NOTATION;
break;
case Node::DOCUMENT_FRAGMENT_NODE:
type = V8ClassIndex::DOCUMENTFRAGMENT;
break;
case Node::ENTITY_REFERENCE_NODE:
type = V8ClassIndex::ENTITYREFERENCE;
break;
default:
type = V8ClassIndex::NODE;
}
// Find the context to which the node belongs and create the wrapper
// in that context. If the node is not in a document, the current
// context is used.
v8::Local<v8::Context> context;
Document* doc = node->document();
if (doc) {
context = V8Proxy::GetContext(doc->frame());
}
if (!context.IsEmpty()) {
context->Enter();
}
v8::Local<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::NODE, node);
// Exit the node's context if it was entered.
if (!context.IsEmpty()) {
context->Exit();
}
if (result.IsEmpty()) {
// If instantiation failed it's important not to add the result
// to the DOM node map. Instead we return an empty handle, which
// should already be handled by callers of this function in case
// the node is NULL.
return result;
}
node->ref();
SetJSWrapperForDOMNode(node, v8::Persistent<v8::Object>::New(result));
if (is_document) {
Document* doc = static_cast<Document*>(node);
V8Proxy* proxy = V8Proxy::retrieve(doc->frame());
if (proxy)
proxy->UpdateDocumentWrapper(result);
if (type == V8ClassIndex::HTMLDOCUMENT) {
// Create marker object and insert it in two internal fields.
// This is used to implement temporary shadowing of
// document.all.
ASSERT(result->InternalFieldCount() ==
V8Custom::kHTMLDocumentInternalFieldCount);
v8::Local<v8::Object> marker = v8::Object::New();
result->SetInternalField(V8Custom::kHTMLDocumentMarkerIndex, marker);
result->SetInternalField(V8Custom::kHTMLDocumentShadowIndex, marker);
}
}
return result;
}
// A JS object of type EventTarget can only be the following possible types:
// 1) EventTargetNode; 2) XMLHttpRequest; 3) MessagePort; 4) SVGElementInstance;
// 5) XMLHttpRequestUpload 6) Worker
// check EventTarget.h for new type conversion methods
v8::Handle<v8::Value> V8Proxy::EventTargetToV8Object(EventTarget* target)
{
if (!target)
return v8::Null();
#if ENABLE(SVG)
SVGElementInstance* instance = target->toSVGElementInstance();
if (instance)
return ToV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
#endif
#if ENABLE(WORKERS)
Worker* worker = target->toWorker();
if (worker)
return ToV8Object(V8ClassIndex::WORKER, worker);
#endif // WORKERS
Node* node = target->toNode();
if (node)
return NodeToV8Object(node);
// XMLHttpRequest is created within its JS counterpart.
XMLHttpRequest* xhr = target->toXMLHttpRequest();
if (xhr) {
v8::Handle<v8::Object> wrapper = GetActiveDOMObjectMap().get(xhr);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
// MessagePort is created within its JS counterpart
MessagePort* port = target->toMessagePort();
if (port) {
v8::Handle<v8::Object> wrapper = GetActiveDOMObjectMap().get(port);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload();
if (upload) {
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(upload);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
ASSERT(0);
return v8::Handle<v8::Value>();
}
v8::Handle<v8::Value> V8Proxy::EventListenerToV8Object(
EventListener* listener)
{
if (listener == 0) return v8::Null();
// TODO(fqian): can a user take a lazy event listener and set to other places?
V8AbstractEventListener* v8listener =
static_cast<V8AbstractEventListener*>(listener);
return v8listener->getListenerObject();
}
v8::Handle<v8::Value> V8Proxy::DOMImplementationToV8Object(
DOMImplementation* impl)
{
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::DOMIMPLEMENTATION,
V8ClassIndex::DOMIMPLEMENTATION,
impl);
if (result.IsEmpty()) {
// If the instantiation failed, we ignore it and return null instead
// of returning an empty handle.
return v8::Null();
}
return result;
}
v8::Handle<v8::Value> V8Proxy::StyleSheetToV8Object(StyleSheet* sheet)
{
if (!sheet) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(sheet);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::STYLESHEET;
if (sheet->isCSSStyleSheet())
type = V8ClassIndex::CSSSTYLESHEET;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::STYLESHEET, sheet);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
sheet->ref();
SetJSWrapperForDOMObject(sheet, v8::Persistent<v8::Object>::New(result));
}
// Add a hidden reference from stylesheet object to its owner node.
Node* owner_node = sheet->ownerNode();
if (owner_node) {
v8::Handle<v8::Object> owner =
v8::Handle<v8::Object>::Cast(NodeToV8Object(owner_node));
result->SetInternalField(V8Custom::kStyleSheetOwnerNodeIndex, owner);
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSValueToV8Object(CSSValue* value)
{
if (!value) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(value);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
if (value->isWebKitCSSTransformValue())
type = V8ClassIndex::WEBKITCSSTRANSFORMVALUE;
else if (value->isValueList())
type = V8ClassIndex::CSSVALUELIST;
else if (value->isPrimitiveValue())
type = V8ClassIndex::CSSPRIMITIVEVALUE;
#if ENABLE(SVG)
else if (value->isSVGPaint())
type = V8ClassIndex::SVGPAINT;
else if (value->isSVGColor())
type = V8ClassIndex::SVGCOLOR;
#endif
else
type = V8ClassIndex::CSSVALUE;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSVALUE, value);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
value->ref();
SetJSWrapperForDOMObject(value, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSRuleToV8Object(CSSRule* rule)
{
if (!rule) return v8::Null();
v8::Handle<v8::Object> wrapper = GetDOMObjectMap().get(rule);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
switch (rule->type()) {
case CSSRule::STYLE_RULE:
type = V8ClassIndex::CSSSTYLERULE;
break;
case CSSRule::CHARSET_RULE:
type = V8ClassIndex::CSSCHARSETRULE;
break;
case CSSRule::IMPORT_RULE:
type = V8ClassIndex::CSSIMPORTRULE;
break;
case CSSRule::MEDIA_RULE:
type = V8ClassIndex::CSSMEDIARULE;
break;
case CSSRule::FONT_FACE_RULE:
type = V8ClassIndex::CSSFONTFACERULE;
break;
case CSSRule::PAGE_RULE:
type = V8ClassIndex::CSSPAGERULE;
break;
case CSSRule::VARIABLES_RULE:
type = V8ClassIndex::CSSVARIABLESRULE;
break;
case CSSRule::WEBKIT_KEYFRAME_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMERULE;
break;
case CSSRule::WEBKIT_KEYFRAMES_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMESRULE;
break;
default: // CSSRule::UNKNOWN_RULE
type = V8ClassIndex::CSSRULE;
break;
}
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSRULE, rule);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
rule->ref();
SetJSWrapperForDOMObject(rule, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::WindowToV8Object(DOMWindow* window)
{
if (!window) return v8::Null();
// Initializes environment of a frame, and return the global object
// of the frame.
Frame* frame = window->frame();
if (!frame)
return v8::Handle<v8::Object>();
// Special case: Because of evaluateInNewContext() one DOMWindow can have
// multipe contexts and multiple global objects associated with it. When
// code running in one of those contexts accesses the window object, we
// want to return the global object associated with that context, not
// necessarily the first global object associated with that DOMWindow.
v8::Handle<v8::Context> current_context = v8::Context::GetCurrent();
v8::Handle<v8::Object> current_global = current_context->Global();
v8::Handle<v8::Object> windowWrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, current_global);
if (!windowWrapper.IsEmpty())
if (DOMWrapperToNative<DOMWindow>(windowWrapper) == window)
return current_global;
// Otherwise, return the global object associated with this frame.
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
return global;
}
void V8Proxy::BindJSObjectToWindow(Frame* frame,
const char* name,
int type,
v8::Handle<v8::FunctionTemplate> desc,
void* imp)
{
// Get environment.
v8::Handle<v8::Context> context = V8Proxy::GetContext(frame);
if (context.IsEmpty())
return; // JS not enabled.
v8::Context::Scope scope(context);
v8::Handle<v8::Object> instance = desc->GetFunction();
SetDOMWrapper(instance, type, imp);
v8::Handle<v8::Object> global = context->Global();
global->Set(v8::String::New(name), instance);
}
void V8Proxy::ProcessConsoleMessages()
{
ConsoleMessageManager::ProcessDelayedMessages();
}
// Create the utility context for holding JavaScript functions used internally
// which are not visible to JavaScript executing on the page.
void V8Proxy::CreateUtilityContext() {
ASSERT(m_utilityContext.IsEmpty());
v8::HandleScope scope;
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
m_utilityContext = v8::Context::New(NULL, global_template);
v8::Context::Scope context_scope(m_utilityContext);
// Compile JavaScript function for retrieving the source line of the top
// JavaScript stack frame.
static const char* frame_source_line_source =
"function frame_source_line(exec_state) {"
" return exec_state.frame(0).sourceLine();"
"}";
v8::Script::Compile(v8::String::New(frame_source_line_source))->Run();
// Compile JavaScript function for retrieving the source name of the top
// JavaScript stack frame.
static const char* frame_source_name_source =
"function frame_source_name(exec_state) {"
" var frame = exec_state.frame(0);"
" if (frame.func().resolved() && "
" frame.func().script() && "
" frame.func().script().name()) {"
" return frame.func().script().name();"
" }"
"}";
v8::Script::Compile(v8::String::New(frame_source_name_source))->Run();
}
int V8Proxy::GetSourceLineNumber() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = V8Proxy::GetUtilityContext();
if (utility_context.IsEmpty()) {
return 0;
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_line;
frame_source_line = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_line")));
if (frame_source_line.IsEmpty()) {
return 0;
}
v8::Handle<v8::Value> result = v8::Debug::Call(frame_source_line);
if (result.IsEmpty()) {
return 0;
}
return result->Int32Value();
}
String V8Proxy::GetSourceName() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = GetUtilityContext();
if (utility_context.IsEmpty()) {
return String();
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_name;
frame_source_name = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_name")));
if (frame_source_name.IsEmpty()) {
return String();
}
return ToWebCoreString(v8::Debug::Call(frame_source_name));
}
void V8Proxy::RegisterExtension(v8::Extension* extension) {
v8::RegisterExtension(extension);
m_extensions.push_back(extension);
}
} // namespace WebCore
|
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include <algorithm>
#include <utility>
#include <v8.h>
#include <v8-debug.h>
#include "v8_proxy.h"
#include "v8_index.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "V8Collection.h"
#include "V8DOMWindow.h"
#include "ChromiumBridge.h"
#include "DOMObjectsInclude.h"
#include "ScriptController.h"
#include "V8DOMMap.h"
namespace WebCore {
// Static utility context.
v8::Persistent<v8::Context> V8Proxy::m_utilityContext;
// Static list of registered extensions
V8ExtensionList V8Proxy::m_extensions;
#ifndef NDEBUG
// Keeps track of global handles created (not JS wrappers
// of DOM objects). Often these global handles are source
// of leaks.
//
// If you want to let a C++ object hold a persistent handle
// to a JS object, you should register the handle here to
// keep track of leaks.
//
// When creating a persistent handle, call:
//
// #ifndef NDEBUG
// V8Proxy::RegisterGlobalHandle(type, host, handle);
// #endif
//
// When releasing the handle, call:
//
// #ifndef NDEBUG
// V8Proxy::UnregisterGlobalHandle(type, host, handle);
// #endif
//
typedef HashMap<v8::Value*, GlobalHandleInfo*> GlobalHandleMap;
static GlobalHandleMap& global_handle_map()
{
static GlobalHandleMap static_global_handle_map;
return static_global_handle_map;
}
// The USE_VAR(x) template is used to silence C++ compiler warnings
// issued for unused variables (typically parameters or values that
// we want to watch in the debugger).
template <typename T>
static inline void USE_VAR(T) { }
// The function is the place to set the break point to inspect
// live global handles. Leaks are often come from leaked global handles.
static void EnumerateGlobalHandles()
{
for (GlobalHandleMap::iterator it = global_handle_map().begin(),
end = global_handle_map().end(); it != end; ++it) {
GlobalHandleInfo* info = it->second;
USE_VAR(info);
v8::Value* handle = it->first;
USE_VAR(handle);
}
}
void V8Proxy::RegisterGlobalHandle(GlobalHandleType type, void* host,
v8::Persistent<v8::Value> handle)
{
ASSERT(!global_handle_map().contains(*handle));
global_handle_map().set(*handle, new GlobalHandleInfo(host, type));
}
void V8Proxy::UnregisterGlobalHandle(void* host, v8::Persistent<v8::Value> handle)
{
ASSERT(global_handle_map().contains(*handle));
GlobalHandleInfo* info = global_handle_map().take(*handle);
ASSERT(info->host_ == host);
delete info;
}
#endif // ifndef NDEBUG
void BatchConfigureAttributes(v8::Handle<v8::ObjectTemplate> inst,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedAttribute* attrs,
size_t num_attrs)
{
for (size_t i = 0; i < num_attrs; ++i) {
const BatchedAttribute* a = &attrs[i];
(a->on_proto ? proto : inst)->SetAccessor(
v8::String::New(a->name),
a->getter,
a->setter,
a->data == V8ClassIndex::INVALID_CLASS_INDEX
? v8::Handle<v8::Value>()
: v8::Integer::New(V8ClassIndex::ToInt(a->data)),
a->settings,
a->attribute);
}
}
void BatchConfigureConstants(v8::Handle<v8::FunctionTemplate> desc,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedConstant* consts,
size_t num_consts)
{
for (size_t i = 0; i < num_consts; ++i) {
const BatchedConstant* c = &consts[i];
desc->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
proto->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
}
}
typedef HashMap<Node*, v8::Object*> DOMNodeMap;
typedef HashMap<void*, v8::Object*> DOMObjectMap;
#ifndef NDEBUG
static void EnumerateDOMObjectMap(DOMObjectMap& wrapper_map)
{
for (DOMObjectMap::iterator it = wrapper_map.begin(), end = wrapper_map.end();
it != end; ++it) {
v8::Persistent<v8::Object> wrapper(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
void* obj = it->first;
USE_VAR(type);
USE_VAR(obj);
}
}
static void EnumerateDOMNodeMap(DOMNodeMap& node_map)
{
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
USE_VAR(node);
ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
}
}
#endif // NDEBUG
#if ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::SVGElementInstanceToV8Object(
SVGElementInstance* instance)
{
if (!instance)
return v8::Null();
v8::Handle<v8::Object> existing_instance = getDOMSVGElementInstanceMap().get(instance);
if (!existing_instance.IsEmpty())
return existing_instance;
instance->ref();
// Instantiate the V8 object and remember it
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::SVGELEMENTINSTANCE,
V8ClassIndex::SVGELEMENTINSTANCE,
instance);
if (!result.IsEmpty()) {
// Only update the DOM SVG element map if the result is non-empty.
getDOMSVGElementInstanceMap().set(instance,
v8::Persistent<v8::Object>::New(result));
}
return result;
}
// Map of SVG objects with contexts to their contexts
static HashMap<void*, SVGElement*>& svg_object_to_context_map()
{
static HashMap<void*, SVGElement*> static_svg_object_to_context_map;
return static_svg_object_to_context_map;
}
v8::Handle<v8::Value> V8Proxy::SVGObjectWithContextToV8Object(
V8ClassIndex::V8WrapperType type, void* object)
{
if (!object)
return v8::Null();
v8::Persistent<v8::Object> result =
getDOMSVGObjectWithContextMap().get(object);
if (!result.IsEmpty()) return result;
// Special case: SVGPathSegs need to be downcast to their real type
if (type == V8ClassIndex::SVGPATHSEG)
type = V8Custom::DowncastSVGPathSeg(object);
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, object);
if (!v8obj.IsEmpty()) {
result = v8::Persistent<v8::Object>::New(v8obj);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(object)->ref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(object)->ref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
getDOMSVGObjectWithContextMap().set(object, result);
}
return result;
}
void V8Proxy::SetSVGContext(void* obj, SVGElement* context)
{
SVGElement* old_context = svg_object_to_context_map().get(obj);
if (old_context == context)
return;
if (old_context)
old_context->deref();
if (context)
context->ref();
svg_object_to_context_map().set(obj, context);
}
SVGElement* V8Proxy::GetSVGContext(void* obj)
{
return svg_object_to_context_map().get(obj);
}
#endif
// A map from a DOM node to its JS wrapper, the wrapper
// is kept as a strong reference to survive GCs.
static DOMObjectMap& gc_protected_map() {
static DOMObjectMap static_gc_protected_map;
return static_gc_protected_map;
}
// static
void V8Proxy::GCProtect(void* dom_object)
{
if (!dom_object)
return;
if (gc_protected_map().contains(dom_object))
return;
if (!getDOMObjectMap().contains(dom_object))
return;
// Create a new (strong) persistent handle for the object.
v8::Persistent<v8::Object> wrapper = getDOMObjectMap().get(dom_object);
if (wrapper.IsEmpty()) return;
gc_protected_map().set(dom_object, *v8::Persistent<v8::Object>::New(wrapper));
}
// static
void V8Proxy::GCUnprotect(void* dom_object)
{
if (!dom_object)
return;
if (!gc_protected_map().contains(dom_object))
return;
// Dispose the strong reference.
v8::Persistent<v8::Object> wrapper(gc_protected_map().take(dom_object));
wrapper.Dispose();
}
// Create object groups for DOM tree nodes.
static void GCPrologue()
{
v8::HandleScope scope;
#ifndef NDEBUG
EnumerateDOMObjectMap(getDOMObjectMap().impl());
#endif
// Run through all objects with possible pending activity making their
// wrappers non weak if there is pending activity.
DOMObjectMap active_map = getActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
ASSERT(wrapper.IsWeak());
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) \
wrapper.ClearWeak(); \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
// Additional handling of message port ensuring that entangled ports also
// have their wrappers entangled. This should ideally be handled when the
// ports are actually entangled in MessagePort::entangle, but to avoid
// forking MessagePort.* this is postponed to GC time. Having this postponed
// has the drawback that the wrappers are "entangled/unentangled" for each
// GC even though their entnaglement most likely is still the same.
if (type == V8ClassIndex::MESSAGEPORT) {
// Get the port and its entangled port.
MessagePort* port1 = static_cast<MessagePort*>(obj);
MessagePortProxy* port2 = port1->entangledPort();
if (port2 != NULL) {
// As ports are always entangled in pairs only perform the entanglement
// once for each pair (see ASSERT in MessagePort::unentangle()).
if (port1 < port2) {
v8::Handle<v8::Value> port1_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
v8::Handle<v8::Value> port2_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port2);
ASSERT(port1_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port1_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port2_wrapper);
ASSERT(port2_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port2_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port1_wrapper);
}
} else {
// Remove the wrapper entanglement when a port is not entangled.
if (V8Proxy::DOMObjectHasJSWrapper(port1)) {
v8::Handle<v8::Value> wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
ASSERT(wrapper->IsObject());
v8::Handle<v8::Object>::Cast(wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, v8::Undefined());
}
}
}
}
// Create object groups.
typedef std::pair<uintptr_t, Node*> GrouperPair;
typedef Vector<GrouperPair> GrouperList;
DOMNodeMap node_map = getDOMNodeMap().impl();
GrouperList grouper;
grouper.reserveCapacity(node_map.size());
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
// If the node is in document, put it in the ownerDocument's object group.
//
// If an image element was created by JavaScript "new Image",
// it is not in a document. However, if the load event has not
// been fired (still onloading), it is treated as in the document.
//
// Otherwise, the node is put in an object group identified by the root
// elment of the tree to which it belongs.
uintptr_t group_id;
if (node->inDocument() ||
(node->hasTagName(HTMLNames::imgTag) &&
!static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent())) {
group_id = reinterpret_cast<uintptr_t>(node->document());
} else {
Node* root = node;
while (root->parent())
root = root->parent();
// If the node is alone in its DOM tree (doesn't have a parent or any
// children) then the group will be filtered out later anyway.
if (root == node && !node->hasChildNodes())
continue;
group_id = reinterpret_cast<uintptr_t>(root);
}
grouper.append(GrouperPair(group_id, node));
}
// Group by sorting by the group id. This will use the std::pair operator<,
// which will really sort by both the group id and the Node*. However the
// Node* is only involved to sort within a group id, so it will be fine.
std::sort(grouper.begin(), grouper.end());
// TODO(deanm): Should probably work in iterators here, but indexes were
// easier for my simple mind.
for (size_t i = 0; i < grouper.size(); ) {
// Seek to the next key (or the end of the list).
size_t next_key_index = grouper.size();
for (size_t j = i; j < grouper.size(); ++j) {
if (grouper[i].first != grouper[j].first) {
next_key_index = j;
break;
}
}
ASSERT(next_key_index > i);
// We only care about a group if it has more than one object. If it only
// has one object, it has nothing else that needs to be kept alive.
if (next_key_index - i <= 1) {
i = next_key_index;
continue;
}
Vector<v8::Persistent<v8::Value> > group;
group.reserveCapacity(next_key_index - i);
for (; i < next_key_index; ++i) {
v8::Persistent<v8::Value> wrapper =
getDOMNodeMap().get(grouper[i].second);
if (!wrapper.IsEmpty())
group.append(wrapper);
}
if (group.size() > 1)
v8::V8::AddObjectGroup(&group[0], group.size());
ASSERT(i == next_key_index);
}
}
static void GCEpilogue()
{
v8::HandleScope scope;
// Run through all objects with pending activity making their wrappers weak
// again.
DOMObjectMap active_map = getActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) { \
ASSERT(!wrapper.IsWeak()); \
wrapper.MakeWeak(impl, &weakActiveDOMObjectCallback); \
} \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
#ifndef NDEBUG
// Check all survivals are weak.
EnumerateDOMObjectMap(getDOMObjectMap().impl());
EnumerateDOMNodeMap(getDOMNodeMap().impl());
EnumerateDOMObjectMap(gc_protected_map());
EnumerateGlobalHandles();
#undef USE_VAR
#endif
}
typedef HashMap<int, v8::FunctionTemplate*> FunctionTemplateMap;
bool AllowAllocation::m_current = false;
// JavaScriptConsoleMessages encapsulate everything needed to
// log messages originating from JavaScript to the Chrome console.
class JavaScriptConsoleMessage {
public:
JavaScriptConsoleMessage(const String& str,
const String& sourceID,
unsigned lineNumber)
: m_string(str)
, m_sourceID(sourceID)
, m_lineNumber(lineNumber) { }
void AddToPage(Page* page) const;
private:
const String m_string;
const String m_sourceID;
const unsigned m_lineNumber;
};
void JavaScriptConsoleMessage::AddToPage(Page* page) const
{
ASSERT(page);
Console* console = page->mainFrame()->domWindow()->console();
console->addMessage(JSMessageSource, ErrorMessageLevel, m_string, m_lineNumber, m_sourceID);
}
// The ConsoleMessageManager handles all console messages that stem
// from JavaScript. It keeps a list of messages that have been delayed but
// it makes sure to add all messages to the console in the right order.
class ConsoleMessageManager {
public:
// Add a message to the console. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void AddMessage(Page* page, const JavaScriptConsoleMessage& message);
// Add a message to the console but delay the reporting until it
// is safe to do so: Either when we leave JavaScript execution or
// when adding other console messages. The primary purpose of this
// method is to avoid calling into V8 to handle console messages
// when the VM is in a state that does not support GCs or allocations.
// Delayed messages are always reported in the page corresponding
// to the active context.
static void AddDelayedMessage(const JavaScriptConsoleMessage& message);
// Process any delayed messages. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void ProcessDelayedMessages();
private:
// All delayed messages are stored in this vector. If the vector
// is NULL, there are no delayed messages.
static Vector<JavaScriptConsoleMessage>* m_delayed;
};
Vector<JavaScriptConsoleMessage>* ConsoleMessageManager::m_delayed = NULL;
void ConsoleMessageManager::AddMessage(
Page* page,
const JavaScriptConsoleMessage& message)
{
// Process any delayed messages to make sure that messages
// appear in the right order in the console.
ProcessDelayedMessages();
message.AddToPage(page);
}
void ConsoleMessageManager::AddDelayedMessage(const JavaScriptConsoleMessage& message)
{
if (!m_delayed)
// Allocate a vector for the delayed messages. Will be
// deallocated when the delayed messages are processed
// in ProcessDelayedMessages().
m_delayed = new Vector<JavaScriptConsoleMessage>();
m_delayed->append(message);
}
void ConsoleMessageManager::ProcessDelayedMessages()
{
// If we have a delayed vector it cannot be empty.
if (!m_delayed)
return;
ASSERT(!m_delayed->isEmpty());
// Add the delayed messages to the page of the active
// context. If that for some bizarre reason does not
// exist, we clear the list of delayed messages to avoid
// posting messages. We still deallocate the vector.
Frame* frame = V8Proxy::retrieveActiveFrame();
Page* page = NULL;
if (frame)
page = frame->page();
if (!page)
m_delayed->clear();
// Iterate through all the delayed messages and add them
// to the console.
const int size = m_delayed->size();
for (int i = 0; i < size; i++) {
m_delayed->at(i).AddToPage(page);
}
// Deallocate the delayed vector.
delete m_delayed;
m_delayed = NULL;
}
// Convenience class for ensuring that delayed messages in the
// ConsoleMessageManager are processed quickly.
class ConsoleMessageScope {
public:
ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
~ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
};
void log_info(Frame* frame, const String& msg, const String& url)
{
Page* page = frame->page();
if (!page)
return;
JavaScriptConsoleMessage message(msg, url, 0);
ConsoleMessageManager::AddMessage(page, message);
}
static void HandleConsoleMessage(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data)
{
// Use the frame where JavaScript is called from.
Frame* frame = V8Proxy::retrieveActiveFrame();
if (!frame)
return;
Page* page = frame->page();
if (!page)
return;
v8::Handle<v8::String> errorMessageString = message->Get();
ASSERT(!errorMessageString.IsEmpty());
String errorMessage = ToWebCoreString(errorMessageString);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool useURL = (resourceName.IsEmpty() || !resourceName->IsString());
String resourceNameString = (useURL)
? frame->document()->url()
: ToWebCoreString(resourceName);
JavaScriptConsoleMessage consoleMessage(errorMessage,
resourceNameString,
message->GetLineNumber());
ConsoleMessageManager::AddMessage(page, consoleMessage);
}
enum DelayReporting {
REPORT_LATER,
REPORT_NOW
};
static void ReportUnsafeAccessTo(Frame* target, DelayReporting delay)
{
ASSERT(target);
Document* targetDocument = target->document();
if (!targetDocument)
return;
Frame* source = V8Proxy::retrieveActiveFrame();
if (!source || !source->document())
return; // Ignore error if the source document is gone.
Document* sourceDocument = source->document();
// FIXME: This error message should contain more specifics of why the same
// origin check has failed.
String str = String::format("Unsafe JavaScript attempt to access frame "
"with URL %s from frame with URL %s. "
"Domains, protocols and ports must match.\n",
targetDocument->url().string().utf8().data(),
sourceDocument->url().string().utf8().data());
// Build a console message with fake source ID and line number.
const String kSourceID = "";
const int kLineNumber = 1;
JavaScriptConsoleMessage message(str, kSourceID, kLineNumber);
if (delay == REPORT_NOW) {
// NOTE(tc): Apple prints the message in the target page, but it seems like
// it should be in the source page. Even for delayed messages, we put it in
// the source page; see ConsoleMessageManager::ProcessDelayedMessages().
ConsoleMessageManager::AddMessage(source->page(), message);
} else {
ASSERT(delay == REPORT_LATER);
// We cannot safely report the message eagerly, because this may cause
// allocations and GCs internally in V8 and we cannot handle that at this
// point. Therefore we delay the reporting.
ConsoleMessageManager::AddDelayedMessage(message);
}
}
static void ReportUnsafeJavaScriptAccess(v8::Local<v8::Object> host,
v8::AccessType type,
v8::Local<v8::Value> data)
{
Frame* target = V8Custom::GetTargetFrame(host, data);
if (target)
ReportUnsafeAccessTo(target, REPORT_LATER);
}
static void HandleFatalErrorInV8()
{
// TODO: We temporarily deal with V8 internal error situations
// such as out-of-memory by crashing the renderer.
CRASH();
}
static void ReportFatalErrorInV8(const char* location, const char* message)
{
// V8 is shutdown, we cannot use V8 api.
// The only thing we can do is to disable JavaScript.
// TODO: clean up V8Proxy and disable JavaScript.
printf("V8 error: %s (%s)\n", message, location);
HandleFatalErrorInV8();
}
V8Proxy::~V8Proxy()
{
clearForClose();
DestroyGlobal();
}
void V8Proxy::DestroyGlobal()
{
if (!m_global.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_global);
#endif
m_global.Dispose();
m_global.Clear();
}
}
bool V8Proxy::DOMObjectHasJSWrapper(void* obj) {
return getDOMObjectMap().contains(obj) ||
getActiveDOMObjectMap().contains(obj);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
ASSERT(false);
#undef MAKE_CASE
default: break;
}
#endif
getDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForActiveDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE: break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default: ASSERT(false);
#undef MAKE_CASE
}
#endif
getActiveDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased node's ref count.
void V8Proxy::SetJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
getDOMNodeMap().set(node, wrapper);
}
PassRefPtr<EventListener> V8Proxy::createInlineEventListener(
const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#if ENABLE(SVG)
PassRefPtr<EventListener> V8Proxy::createSVGEventHandler(const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#endif
// Event listeners
static V8EventListener* FindEventListenerInList(V8EventListenerList& list,
v8::Local<v8::Value> listener,
bool isInline)
{
ASSERT(v8::Context::InContext());
if (!listener->IsObject())
return 0;
return list.find(listener->ToObject(), isInline);
}
// Find an existing wrapper for a JS event listener in the map.
PassRefPtr<V8EventListener> V8Proxy::FindV8EventListener(v8::Local<v8::Value> listener,
bool isInline)
{
return FindEventListenerInList(m_event_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateV8EventListener(v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_event_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8EventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_event_listeners.add(new_listener.get());
return new_listener;
}
// Object event listeners (such as XmlHttpRequest and MessagePort) are
// different from listeners on DOM nodes. An object event listener wrapper
// only holds a weak reference to the JS function. A strong reference can
// create a cycle.
//
// The lifetime of these objects is bounded by the life time of its JS
// wrapper. So we can create a hidden reference from the JS wrapper to
// to its JS function.
//
// (map)
// XHR <---------- JS_wrapper
// | (hidden) : ^
// V V : (may reachable by closure)
// V8_listener --------> JS_function
// (weak) <-- may create a cycle if it is strong
//
// The persistent reference is made weak in the constructor
// of V8ObjectEventListener.
PassRefPtr<V8EventListener> V8Proxy::FindObjectEventListener(
v8::Local<v8::Value> listener, bool isInline)
{
return FindEventListenerInList(m_xhr_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateObjectEventListener(
v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_xhr_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8ObjectEventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_xhr_listeners.add(new_listener.get());
return new_listener.release();
}
static void RemoveEventListenerFromList(V8EventListenerList& list,
V8EventListener* listener)
{
list.remove(listener);
}
void V8Proxy::RemoveV8EventListener(V8EventListener* listener)
{
ASSERT(!m_context.IsEmpty());
v8::Context::Scope contextScope(m_context);
RemoveEventListenerFromList(m_event_listeners, listener);
}
void V8Proxy::RemoveObjectEventListener(V8ObjectEventListener* listener)
{
ASSERT(!m_context.IsEmpty());
v8::Context::Scope contextScope(m_context);
RemoveEventListenerFromList(m_xhr_listeners, listener);
}
static void DisconnectEventListenersInList(V8EventListenerList& list)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
(*p)->disconnectFrame();
++p;
}
list.clear();
}
void V8Proxy::DisconnectEventListeners()
{
if (m_event_listeners.begin() != m_event_listeners.end() ||
m_xhr_listeners.begin() != m_xhr_listeners.end()) {
ASSERT(!m_context.IsEmpty());
v8::Context::Scope contextScope(m_context);
DisconnectEventListenersInList(m_event_listeners);
DisconnectEventListenersInList(m_xhr_listeners);
}
}
v8::Handle<v8::Script> V8Proxy::CompileScript(v8::Handle<v8::String> code,
const String& fileName,
int baseLine)
{
const uint16_t* fileNameString = FromWebCoreString(fileName);
v8::Handle<v8::String> name =
v8::String::New(fileNameString, fileName.length());
v8::Handle<v8::Integer> line = v8::Integer::New(baseLine);
v8::ScriptOrigin origin(name, line);
v8::Handle<v8::Script> script = v8::Script::Compile(code, &origin);
return script;
}
bool V8Proxy::HandleOutOfMemory()
{
v8::Local<v8::Context> context = v8::Context::GetCurrent();
if (!context->HasOutOfMemoryException())
return false;
// Warning, error, disable JS for this frame?
Frame* frame = V8Proxy::retrieveFrame(context);
V8Proxy* proxy = V8Proxy::retrieve(frame);
// Clean m_context, and event handlers.
proxy->clearForClose();
// Destroy the global object.
proxy->DestroyGlobal();
ChromiumBridge::notifyJSOutOfMemory(frame);
// Disable JS.
Settings* settings = frame->settings();
ASSERT(settings);
settings->setJavaScriptEnabled(false);
return true;
}
void V8Proxy::evaluateInNewContext(const Vector<ScriptSourceCode>& sources)
{
InitContextIfNeeded();
v8::HandleScope handleScope;
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> windowContext = m_context;
v8::Handle<v8::Object> windowGlobal = windowContext->Global();
v8::Handle<v8::Value> windowWrapper =
V8Proxy::LookupDOMWrapper(V8ClassIndex::DOMWINDOW, windowGlobal);
ASSERT(V8Proxy::DOMWrapperToNative<DOMWindow>(windowWrapper) ==
m_frame->domWindow());
v8::Persistent<v8::Context> context =
createNewContext(v8::Handle<v8::Object>());
v8::Context::Scope context_scope(context);
v8::Handle<v8::Object> global = context->Global();
v8::Handle<v8::String> implicitProtoString = v8::String::New("__proto__");
global->Set(implicitProtoString, windowWrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), windowGlobal);
// Run code in the new context.
for (size_t i = 0; i < sources.size(); ++i)
evaluate(sources[i], 0);
// Using the default security token means that the canAccess is always
// called, which is slow.
// TODO(aa): Use tokens where possible. This will mean keeping track of all
// created contexts so that they can all be updated when the document domain
// changes.
context->UseDefaultSecurityToken();
context.Dispose();
}
v8::Local<v8::Value> V8Proxy::evaluate(const ScriptSourceCode& source, Node* n)
{
ASSERT(v8::Context::InContext());
// Compile the script.
v8::Local<v8::String> code = v8ExternalString(source.source());
ChromiumBridge::traceEventBegin("v8.compile", n, "");
// NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at
// 1, whereas v8 starts at 0.
v8::Handle<v8::Script> script = CompileScript(code, source.url(),
source.startLine() - 1);
ChromiumBridge::traceEventEnd("v8.compile", n, "");
ChromiumBridge::traceEventBegin("v8.run", n, "");
v8::Local<v8::Value> result;
{
// Isolate exceptions that occur when executing the code. These
// exceptions should not interfere with javascript code we might
// evaluate from C++ when returning from here
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
// Set inlineCode to true for <a href="javascript:doSomething()">
// and false for <script>doSomething</script>. We make a rough guess at
// this based on whether the script source has a URL.
result = RunScript(script, source.url().string().isNull());
}
ChromiumBridge::traceEventEnd("v8.run", n, "");
return result;
}
v8::Local<v8::Value> V8Proxy::RunScript(v8::Handle<v8::Script> script,
bool inline_code)
{
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Compute the source string and prevent against infinite recursion.
if (m_recursion >= kMaxRecursionDepth) {
v8::Local<v8::String> code =
v8ExternalString("throw RangeError('Recursion too deep')");
// TODO(kasperl): Ideally, we should be able to re-use the origin of the
// script passed to us as the argument instead of using an empty string
// and 0 baseLine.
script = CompileScript(code, "", 0);
}
if (HandleOutOfMemory())
ASSERT(script.IsEmpty());
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Save the previous value of the inlineCode flag and update the flag for
// the duration of the script invocation.
bool previous_inline_code = inlineCode();
setInlineCode(inline_code);
// Run the script and keep track of the current recursion depth.
v8::Local<v8::Value> result;
{ ConsoleMessageScope scope;
m_recursion++;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = script->Run();
m_recursion--;
}
if (HandleOutOfMemory())
ASSERT(result.IsEmpty());
// Handle V8 internal error situation (Out-of-memory).
if (result.IsEmpty())
return v8::Local<v8::Value>();
// Restore inlineCode flag.
setInlineCode(previous_inline_code);
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Value> V8Proxy::CallFunction(v8::Handle<v8::Function> function,
v8::Handle<v8::Object> receiver,
int argc,
v8::Handle<v8::Value> args[])
{
// For now, we don't put any artificial limitations on the depth
// of recursion that stems from calling functions. This is in
// contrast to the script evaluations.
v8::Local<v8::Value> result;
{
ConsoleMessageScope scope;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = function->Call(receiver, argc, args);
}
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Function> V8Proxy::GetConstructor(V8ClassIndex::V8WrapperType t){
// A DOM constructor is a function instance created from a DOM constructor
// template. There is one instance per context. A DOM constructor is
// different from a normal function in two ways:
// 1) it cannot be called as constructor (aka, used to create a DOM object)
// 2) its __proto__ points to Object.prototype rather than
// Function.prototype.
// The reason for 2) is that, in Safari, a DOM constructor is a normal JS
// object, but not a function. Hotmail relies on the fact that, in Safari,
// HTMLElement.__proto__ == Object.prototype.
//
// m_object_prototype is a cache of the original Object.prototype.
ASSERT(ContextInitialized());
// Enter the context of the proxy to make sure that the
// function is constructed in the context corresponding to
// this proxy.
v8::Context::Scope scope(m_context);
v8::Handle<v8::FunctionTemplate> templ = GetTemplate(t);
// Getting the function might fail if we're running out of
// stack or memory.
v8::TryCatch try_catch;
v8::Local<v8::Function> value = templ->GetFunction();
if (value.IsEmpty())
return v8::Local<v8::Function>();
// Hotmail fix, see comments above.
value->Set(v8::String::New("__proto__"), m_object_prototype);
return value;
}
v8::Local<v8::Object> V8Proxy::CreateWrapperFromCache(V8ClassIndex::V8WrapperType type) {
int class_index = V8ClassIndex::ToInt(type);
v8::Local<v8::Value> cached_object =
m_wrapper_boilerplates->Get(v8::Integer::New(class_index));
if (cached_object->IsObject()) {
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(cached_object);
return object->Clone();
}
// Not in cache.
InitContextIfNeeded();
v8::Context::Scope scope(m_context);
v8::Local<v8::Function> function = GetConstructor(type);
v8::Local<v8::Object> instance = SafeAllocation::NewInstance(function);
if (!instance.IsEmpty()) {
m_wrapper_boilerplates->Set(v8::Integer::New(class_index), instance);
return instance->Clone();
}
return v8::Local<v8::Object>();
}
// Get the string 'toString'.
static v8::Persistent<v8::String> GetToStringName() {
static v8::Persistent<v8::String> value;
if (value.IsEmpty())
value = v8::Persistent<v8::String>::New(v8::String::New("toString"));
return value;
}
static v8::Handle<v8::Value> ConstructorToString(const v8::Arguments& args) {
// The DOM constructors' toString functions grab the current toString
// for Functions by taking the toString function of itself and then
// calling it with the constructor as its receiver. This means that
// changes to the Function prototype chain or toString function are
// reflected when printing DOM constructors. The only wart is that
// changes to a DOM constructor's toString's toString will cause the
// toString of the DOM constructor itself to change. This is extremely
// obscure and unlikely to be a problem.
v8::Handle<v8::Value> val = args.Callee()->Get(GetToStringName());
if (!val->IsFunction()) return v8::String::New("");
return v8::Handle<v8::Function>::Cast(val)->Call(args.This(), 0, NULL);
}
v8::Persistent<v8::FunctionTemplate> V8Proxy::GetTemplate(
V8ClassIndex::V8WrapperType type)
{
v8::Persistent<v8::FunctionTemplate>* cache_cell =
V8ClassIndex::GetCache(type);
if (!(*cache_cell).IsEmpty())
return *cache_cell;
// not found
FunctionTemplateFactory factory = V8ClassIndex::GetFactory(type);
v8::Persistent<v8::FunctionTemplate> desc = factory();
// DOM constructors are functions and should print themselves as such.
// However, we will later replace their prototypes with Object
// prototypes so we need to explicitly override toString on the
// instance itself. If we later make DOM constructors full objects
// we can give them class names instead and Object.prototype.toString
// will work so we can remove this code.
static v8::Persistent<v8::FunctionTemplate> to_string_template;
if (to_string_template.IsEmpty()) {
to_string_template = v8::Persistent<v8::FunctionTemplate>::New(
v8::FunctionTemplate::New(ConstructorToString));
}
desc->Set(GetToStringName(), to_string_template);
switch (type) {
case V8ClassIndex::CSSSTYLEDECLARATION:
// The named property handler for style declarations has a
// setter. Therefore, the interceptor has to be on the object
// itself and not on the prototype object.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(CSSStyleDeclaration),
USE_NAMED_PROPERTY_SETTER(CSSStyleDeclaration));
setCollectionStringOrNullIndexedGetter<CSSStyleDeclaration>(desc);
break;
case V8ClassIndex::CSSRULELIST:
setCollectionIndexedGetter<CSSRuleList, CSSRule>(desc,
V8ClassIndex::CSSRULE);
break;
case V8ClassIndex::CSSVALUELIST:
setCollectionIndexedGetter<CSSValueList, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::CSSVARIABLESDECLARATION:
setCollectionStringOrNullIndexedGetter<CSSVariablesDeclaration>(desc);
break;
case V8ClassIndex::WEBKITCSSTRANSFORMVALUE:
setCollectionIndexedGetter<WebKitCSSTransformValue, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::UNDETECTABLEHTMLCOLLECTION:
desc->InstanceTemplate()->MarkAsUndetectable(); // fall through
case V8ClassIndex::HTMLCOLLECTION:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
setCollectionIndexedGetter<HTMLCollection, Node>(desc,
V8ClassIndex::NODE);
break;
case V8ClassIndex::HTMLOPTIONSCOLLECTION:
setCollectionNamedGetter<HTMLOptionsCollection, Node>(
desc,
V8ClassIndex::NODE);
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLOptionsCollection),
USE_INDEXED_PROPERTY_SETTER(HTMLOptionsCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
break;
case V8ClassIndex::HTMLSELECTELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
nodeCollectionNamedPropertyGetter<HTMLSelectElement>,
0,
0,
0,
0,
v8::Integer::New(V8ClassIndex::NODE));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
nodeCollectionIndexedPropertyGetter<HTMLSelectElement>,
USE_INDEXED_PROPERTY_SETTER(HTMLSelectElementCollection),
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLSelectElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::HTMLDOCUMENT: {
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLDocument),
0,
0,
USE_NAMED_PROPERTY_DELETER(HTMLDocument));
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
//
// Additionally, we add two extra internal fields for
// HTMLDocuments to implement temporary shadowing of
// document.all. One field holds an object that is used as a
// marker. The other field holds the marker object if
// document.all is not shadowed and some other value if
// document.all is shadowed.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kHTMLDocumentInternalFieldCount);
break;
}
#if ENABLE(SVG)
case V8ClassIndex::SVGDOCUMENT: // fall through
#endif
case V8ClassIndex::DOCUMENT: {
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kDocumentMinimumInternalFieldCount);
break;
}
case V8ClassIndex::HTMLAPPLETELEMENT: // fall through
case V8ClassIndex::HTMLEMBEDELEMENT: // fall through
case V8ClassIndex::HTMLOBJECTELEMENT:
// HTMLAppletElement, HTMLEmbedElement and HTMLObjectElement are
// inherited from HTMLPlugInElement, and they share the same property
// handling code.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLPlugInElement),
USE_NAMED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLPlugInElement),
USE_INDEXED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLPlugInElement));
break;
case V8ClassIndex::HTMLFRAMESETELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFrameSetElement));
break;
case V8ClassIndex::HTMLFORMELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFormElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLFormElement),
0,
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLFormElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::CANVASPIXELARRAY:
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(CanvasPixelArray),
USE_INDEXED_PROPERTY_SETTER(CanvasPixelArray));
break;
case V8ClassIndex::STYLESHEET: // fall through
case V8ClassIndex::CSSSTYLESHEET: {
// We add an extra internal field to hold a reference to
// the owner node.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kStyleSheetInternalFieldCount);
break;
}
case V8ClassIndex::MEDIALIST:
setCollectionStringOrNullIndexedGetter<MediaList>(desc);
break;
case V8ClassIndex::MIMETYPEARRAY:
setCollectionIndexedAndNamedGetters<MimeTypeArray, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::NAMEDNODEMAP:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NamedNodeMap));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(NamedNodeMap),
0,
0,
0,
collectionIndexedPropertyEnumerator<NamedNodeMap>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::NODELIST:
setCollectionIndexedGetter<NodeList, Node>(desc, V8ClassIndex::NODE);
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NodeList));
break;
case V8ClassIndex::PLUGIN:
setCollectionIndexedAndNamedGetters<Plugin, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::PLUGINARRAY:
setCollectionIndexedAndNamedGetters<PluginArray, Plugin>(
desc,
V8ClassIndex::PLUGIN);
break;
case V8ClassIndex::STYLESHEETLIST:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(StyleSheetList));
setCollectionIndexedGetter<StyleSheetList, StyleSheet>(
desc,
V8ClassIndex::STYLESHEET);
break;
case V8ClassIndex::DOMWINDOW: {
v8::Local<v8::Signature> default_signature = v8::Signature::New(desc);
desc->PrototypeTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(DOMWindow));
desc->PrototypeTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(DOMWindow));
desc->SetHiddenPrototype(true);
// Reserve spaces for references to location, history and
// navigator objects.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
// Set access check callbacks, but turned off initially.
// When a context is detached from a frame, turn on the access check.
// Turning on checks also invalidates inline caches of the object.
instance_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW),
false);
break;
}
case V8ClassIndex::LOCATION: {
// For security reasons, these functions are on the instance
// instead of on the prototype object to insure that they cannot
// be overwritten.
v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate();
instance->SetAccessor(
v8::String::New("reload"),
V8Custom::v8LocationReloadAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("replace"),
V8Custom::v8LocationReplaceAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("assign"),
V8Custom::v8LocationAssignAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
break;
}
case V8ClassIndex::HISTORY: {
break;
}
case V8ClassIndex::MESSAGECHANNEL: {
// Reserve two more internal fields for referencing the port1
// and port2 wrappers. This ensures that the port wrappers are
// kept alive when the channel wrapper is.
desc->SetCallHandler(USE_CALLBACK(MessageChannelConstructor));
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessageChannelInternalFieldCount);
break;
}
case V8ClassIndex::MESSAGEPORT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessagePortInternalFieldCount);
break;
}
#if ENABLE(WORKERS)
case V8ClassIndex::WORKER: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(WorkerConstructor));
break;
}
case V8ClassIndex::WORKERCONTEXT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerContextInternalFieldCount);
break;
}
#endif // WORKERS
// The following objects are created from JavaScript.
case V8ClassIndex::DOMPARSER:
desc->SetCallHandler(USE_CALLBACK(DOMParserConstructor));
break;
case V8ClassIndex::WEBKITCSSMATRIX:
desc->SetCallHandler(USE_CALLBACK(WebKitCSSMatrixConstructor));
break;
case V8ClassIndex::WEBKITPOINT:
desc->SetCallHandler(USE_CALLBACK(WebKitPointConstructor));
break;
case V8ClassIndex::XMLSERIALIZER:
desc->SetCallHandler(USE_CALLBACK(XMLSerializerConstructor));
break;
case V8ClassIndex::XMLHTTPREQUEST: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(XMLHttpRequestConstructor));
break;
}
case V8ClassIndex::XMLHTTPREQUESTUPLOAD: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
break;
}
case V8ClassIndex::XPATHEVALUATOR:
desc->SetCallHandler(USE_CALLBACK(XPathEvaluatorConstructor));
break;
case V8ClassIndex::XSLTPROCESSOR:
desc->SetCallHandler(USE_CALLBACK(XSLTProcessorConstructor));
break;
default:
break;
}
*cache_cell = desc;
return desc;
}
bool V8Proxy::ContextInitialized()
{
// m_context, m_global, m_object_prototype and m_wrapper_boilerplates should
// all be non-empty if if m_context is non-empty.
ASSERT(m_context.IsEmpty() || !m_global.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_object_prototype.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_wrapper_boilerplates.IsEmpty());
return !m_context.IsEmpty();
}
DOMWindow* V8Proxy::retrieveWindow()
{
// TODO: This seems very fragile. How do we know that the global object
// from the current context is something sensible? Do we need to use the
// last entered here? Who calls this?
return retrieveWindow(v8::Context::GetCurrent());
}
DOMWindow* V8Proxy::retrieveWindow(v8::Handle<v8::Context> context)
{
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
return ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, global);
}
Frame* V8Proxy::retrieveFrame(v8::Handle<v8::Context> context)
{
return retrieveWindow(context)->frame();
}
Frame* V8Proxy::retrieveActiveFrame()
{
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return 0;
return retrieveFrame(context);
}
Frame* V8Proxy::retrieveFrame()
{
DOMWindow* window = retrieveWindow();
return window ? window->frame() : 0;
}
V8Proxy* V8Proxy::retrieve()
{
DOMWindow* window = retrieveWindow();
ASSERT(window);
return retrieve(window->frame());
}
V8Proxy* V8Proxy::retrieve(Frame* frame)
{
if (!frame)
return 0;
return frame->script()->isEnabled() ? frame->script()->proxy() : 0;
}
V8Proxy* V8Proxy::retrieve(ScriptExecutionContext* context)
{
if (!context->isDocument())
return 0;
return retrieve(static_cast<Document*>(context)->frame());
}
void V8Proxy::disconnectFrame()
{
// disconnect all event listeners
DisconnectEventListeners();
}
bool V8Proxy::isEnabled()
{
Settings* settings = m_frame->settings();
if (!settings)
return false;
// In the common case, JavaScript is enabled and we're done.
if (settings->isJavaScriptEnabled())
return true;
// If JavaScript has been disabled, we need to look at the frame to tell
// whether this script came from the web or the embedder. Scripts from the
// embedder are safe to run, but scripts from the other sources are
// disallowed.
Document* document = m_frame->document();
if (!document)
return false;
SecurityOrigin* origin = document->securityOrigin();
if (origin->protocol().isEmpty())
return false; // Uninitialized document
if (origin->protocol() == "http" || origin->protocol() == "https")
return false; // Web site
// TODO(darin): the following are application decisions, and they should
// not be made at this layer. instead, we should bridge out to the
// embedder to allow them to override policy here.
if (origin->protocol() == ChromiumBridge::uiResourceProtocol())
return true; // Embedder's scripts are ok to run
// If the scheme is ftp: or file:, an empty file name indicates a directory
// listing, which requires JavaScript to function properly.
const char* kDirProtocols[] = { "ftp", "file" };
for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
if (origin->protocol() == kDirProtocols[i]) {
const KURL& url = document->url();
return url.pathAfterLastSlash() == url.pathEnd();
}
}
return false; // Other protocols fall through to here
}
void V8Proxy::UpdateDocumentWrapper(v8::Handle<v8::Value> wrapper) {
ClearDocumentWrapper();
ASSERT(m_document.IsEmpty());
m_document = v8::Persistent<v8::Value>::New(wrapper);
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_document);
#endif
}
void V8Proxy::ClearDocumentWrapper()
{
if (!m_document.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_document);
#endif
m_document.Dispose();
m_document.Clear();
}
}
void V8Proxy::DisposeContextHandles() {
if (!m_context.IsEmpty()) {
m_context.Dispose();
m_context.Clear();
}
if (!m_wrapper_boilerplates.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_wrapper_boilerplates);
#endif
m_wrapper_boilerplates.Dispose();
m_wrapper_boilerplates.Clear();
}
if (!m_object_prototype.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_object_prototype);
#endif
m_object_prototype.Dispose();
m_object_prototype.Clear();
}
}
void V8Proxy::clearForClose()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle_scope;
ClearDocumentWrapper();
DisposeContextHandles();
}
}
void V8Proxy::clearForNavigation()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle;
ClearDocumentWrapper();
v8::Context::Scope context_scope(m_context);
// Turn on access check on the old DOMWindow wrapper.
v8::Handle<v8::Object> wrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, m_global);
ASSERT(!wrapper.IsEmpty());
wrapper->TurnOnAccessCheck();
// disconnect all event listeners
DisconnectEventListeners();
// Separate the context from its global object.
m_context->DetachGlobal();
DisposeContextHandles();
// Reinitialize the context so the global object points to
// the new DOM window.
InitContextIfNeeded();
}
}
void V8Proxy::SetSecurityToken() {
Document* document = m_frame->document();
// Setup security origin and security token
if (!document) {
m_context->UseDefaultSecurityToken();
return;
}
// Ask the document's SecurityOrigin to generate a security token.
// If two tokens are equal, then the SecurityOrigins canAccess each other.
// If two tokens are not equal, then we have to call canAccess.
// Note: we can't use the HTTPOrigin if it was set from the DOM.
SecurityOrigin* origin = document->securityOrigin();
String token;
if (!origin->domainWasSetInDOM())
token = document->securityOrigin()->toString();
// An empty or "null" token means we always have to call
// canAccess. The toString method on securityOrigins returns the
// string "null" for empty security origins and for security
// origins that should only allow access to themselves. In this
// case, we use the global object as the security token to avoid
// calling canAccess when a script accesses its own objects.
if (token.isEmpty() || token == "null") {
m_context->UseDefaultSecurityToken();
return;
}
CString utf8_token = token.utf8();
// NOTE: V8 does identity comparison in fast path, must use a symbol
// as the security token.
m_context->SetSecurityToken(
v8::String::NewSymbol(utf8_token.data(), utf8_token.length()));
}
void V8Proxy::updateDocument()
{
if (!m_frame->document())
return;
if (m_global.IsEmpty()) {
ASSERT(m_context.IsEmpty());
return;
}
{
v8::HandleScope scope;
SetSecurityToken();
}
}
void V8Proxy::updateSecurityOrigin()
{
v8::HandleScope scope;
SetSecurityToken();
}
// Same origin policy implementation:
//
// Same origin policy prevents JS code from domain A access JS & DOM objects
// in a different domain B. There are exceptions and several objects are
// accessible by cross-domain code. For example, the window.frames object is
// accessible by code from a different domain, but window.document is not.
//
// The binding code sets security check callbacks on a function template,
// and accessing instances of the template calls the callback function.
// The callback function checks same origin policy.
//
// Callback functions are expensive. V8 uses a security token string to do
// fast access checks for the common case where source and target are in the
// same domain. A security token is a string object that represents
// the protocol/url/port of a domain.
//
// There are special cases where a security token matching is not enough.
// For example, JavaScript can set its domain to a super domain by calling
// document.setDomain(...). In these cases, the binding code can reset
// a context's security token to its global object so that the fast access
// check will always fail.
// Check if the current execution context can access a target frame.
// First it checks same domain policy using the lexical context
//
// This is equivalent to KJS::Window::allowsAccessFrom(ExecState*, String&).
bool V8Proxy::CanAccessPrivate(DOMWindow* target_window)
{
ASSERT(target_window);
String message;
DOMWindow* origin_window = retrieveWindow();
if (origin_window == target_window)
return true;
if (!origin_window)
return false;
// JS may be attempting to access the "window" object, which should be
// valid, even if the document hasn't been constructed yet.
// If the document doesn't exist yet allow JS to access the window object.
if (!origin_window->document())
return true;
const SecurityOrigin* active_security_origin = origin_window->securityOrigin();
const SecurityOrigin* target_security_origin = target_window->securityOrigin();
// We have seen crashes were the security origin of the target has not been
// initialized. Defend against that.
if (!target_security_origin)
return false;
if (active_security_origin->canAccess(target_security_origin))
return true;
// Allow access to a "about:blank" page if the dynamic context is a
// detached context of the same frame as the blank page.
if (target_security_origin->isEmpty() &&
origin_window->frame() == target_window->frame())
return true;
return false;
}
bool V8Proxy::CanAccessFrame(Frame* target, bool report_error)
{
// The subject is detached from a frame, deny accesses.
if (!target)
return false;
if (!CanAccessPrivate(target->domWindow())) {
if (report_error)
ReportUnsafeAccessTo(target, REPORT_NOW);
return false;
}
return true;
}
bool V8Proxy::CheckNodeSecurity(Node* node)
{
if (!node)
return false;
Frame* target = node->document()->frame();
if (!target)
return false;
return CanAccessFrame(target, true);
}
v8::Persistent<v8::Context> V8Proxy::createNewContext(
v8::Handle<v8::Object> global)
{
v8::Persistent<v8::Context> result;
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Persistent<v8::ObjectTemplate> globalTemplate =
V8DOMWindow::GetShadowObjectTemplate();
if (globalTemplate.IsEmpty())
return result;
// Install a security handler with V8.
globalTemplate->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
// Dynamically tell v8 about our extensions now.
const char** extensionNames = new const char*[m_extensions.size()];
int index = 0;
for (V8ExtensionList::iterator it = m_extensions.begin();
it != m_extensions.end(); ++it) {
if (it->scheme.length() > 0 &&
it->scheme != m_frame->document()->url().protocol())
continue;
extensionNames[index++] = it->extension->name();
}
v8::ExtensionConfiguration extensions(index, extensionNames);
result = v8::Context::New(&extensions, globalTemplate, global);
delete [] extensionNames;
extensionNames = 0;
return result;
}
// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance. However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object. The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript. The javascript object that corresponds to a
// DOMWindow instance is the shadow object. When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
//
// To implement split-window, see
// 1) https://bugs.webkit.org/show_bug.cgi?id=17249
// 2) https://wiki.mozilla.org/Gecko:SplitWindow
// 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
// we need to split the shadow object further into two objects:
// an outer window and an inner window. The inner window is the hidden
// prototype of the outer window. The inner window is the default
// global object of the context. A variable declared in the global
// scope is a property of the inner window.
//
// The outer window sticks to a Frame, it is exposed to JavaScript
// via window.window, window.self, window.parent, etc. The outer window
// has a security token which is the domain. The outer window cannot
// have its own properties. window.foo = 'x' is delegated to the
// inner window.
//
// When a frame navigates to a new page, the inner window is cut off
// the outer window, and the outer window identify is preserved for
// the frame. However, a new inner window is created for the new page.
// If there are JS code holds a closure to the old inner window,
// it won't be able to reach the outer window via its global object.
void V8Proxy::InitContextIfNeeded()
{
// Bail out if the context has already been initialized.
if (!m_context.IsEmpty())
return;
// Create a handle scope for all local handles.
v8::HandleScope handle_scope;
// Setup the security handlers and message listener. This only has
// to be done once.
static bool v8_initialized = false;
if (!v8_initialized) {
// Tells V8 not to call the default OOM handler, binding code
// will handle it.
v8::V8::IgnoreOutOfMemoryException();
v8::V8::SetFatalErrorHandler(ReportFatalErrorInV8);
v8::V8::SetGlobalGCPrologueCallback(&GCPrologue);
v8::V8::SetGlobalGCEpilogueCallback(&GCEpilogue);
v8::V8::AddMessageListener(HandleConsoleMessage);
v8::V8::SetFailedAccessCheckCallbackFunction(ReportUnsafeJavaScriptAccess);
v8_initialized = true;
}
m_context = createNewContext(m_global);
if (m_context.IsEmpty())
return;
// Starting from now, use local context only.
v8::Local<v8::Context> context = GetContext();
v8::Context::Scope context_scope(context);
// Store the first global object created so we can reuse it.
if (m_global.IsEmpty()) {
m_global = v8::Persistent<v8::Object>::New(context->Global());
// Bail out if allocation of the first global objects fails.
if (m_global.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_global);
#endif
}
// Allocate strings used during initialization.
v8::Handle<v8::String> object_string = v8::String::New("Object");
v8::Handle<v8::String> prototype_string = v8::String::New("prototype");
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
// Bail out if allocation failed.
if (object_string.IsEmpty() ||
prototype_string.IsEmpty() ||
implicit_proto_string.IsEmpty()) {
DisposeContextHandles();
return;
}
// Allocate clone cache and pre-allocated objects
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(
m_global->Get(object_string));
m_object_prototype = v8::Persistent<v8::Value>::New(
object->Get(prototype_string));
m_wrapper_boilerplates = v8::Persistent<v8::Array>::New(
v8::Array::New(V8ClassIndex::WRAPPER_TYPE_COUNT));
// Bail out if allocation failed.
if (m_object_prototype.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_object_prototype);
RegisterGlobalHandle(PROXY, this, m_wrapper_boilerplates);
#endif
// Create a new JS window object and use it as the prototype for the
// shadow global object.
v8::Handle<v8::Function> window_constructor =
GetConstructor(V8ClassIndex::DOMWINDOW);
v8::Local<v8::Object> js_window =
SafeAllocation::NewInstance(window_constructor);
// Bail out if allocation failed.
if (js_window.IsEmpty()) {
DisposeContextHandles();
return;
}
DOMWindow* window = m_frame->domWindow();
// Wrap the window.
SetDOMWrapper(js_window,
V8ClassIndex::ToInt(V8ClassIndex::DOMWINDOW),
window);
window->ref();
V8Proxy::SetJSWrapperForDOMObject(window,
v8::Persistent<v8::Object>::New(js_window));
// Insert the window instance as the prototype of the shadow object.
v8::Handle<v8::Object> v8_global = context->Global();
v8_global->Set(implicit_proto_string, js_window);
SetSecurityToken();
m_frame->loader()->dispatchWindowObjectAvailable();
}
void V8Proxy::SetDOMException(int exception_code)
{
if (exception_code <= 0)
return;
ExceptionCodeDescription description;
getExceptionCodeDescription(exception_code, description);
v8::Handle<v8::Value> exception;
switch (description.type) {
case DOMExceptionType:
exception = ToV8Object(V8ClassIndex::DOMCOREEXCEPTION,
DOMCoreException::create(description));
break;
case RangeExceptionType:
exception = ToV8Object(V8ClassIndex::RANGEEXCEPTION,
RangeException::create(description));
break;
case EventExceptionType:
exception = ToV8Object(V8ClassIndex::EVENTEXCEPTION,
EventException::create(description));
break;
case XMLHttpRequestExceptionType:
exception = ToV8Object(V8ClassIndex::XMLHTTPREQUESTEXCEPTION,
XMLHttpRequestException::create(description));
break;
#if ENABLE(SVG)
case SVGExceptionType:
exception = ToV8Object(V8ClassIndex::SVGEXCEPTION,
SVGException::create(description));
break;
#endif
#if ENABLE(XPATH)
case XPathExceptionType:
exception = ToV8Object(V8ClassIndex::XPATHEXCEPTION,
XPathException::create(description));
break;
#endif
}
ASSERT(!exception.IsEmpty());
v8::ThrowException(exception);
}
v8::Handle<v8::Value> V8Proxy::ThrowError(ErrorType type, const char* message)
{
switch (type) {
case RANGE_ERROR:
return v8::ThrowException(v8::Exception::RangeError(v8String(message)));
case REFERENCE_ERROR:
return v8::ThrowException(
v8::Exception::ReferenceError(v8String(message)));
case SYNTAX_ERROR:
return v8::ThrowException(v8::Exception::SyntaxError(v8String(message)));
case TYPE_ERROR:
return v8::ThrowException(v8::Exception::TypeError(v8String(message)));
case GENERAL_ERROR:
return v8::ThrowException(v8::Exception::Error(v8String(message)));
default:
ASSERT(false);
return v8::Handle<v8::Value>();
}
}
v8::Local<v8::Context> V8Proxy::GetContext(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
if (!proxy)
return v8::Local<v8::Context>();
proxy->InitContextIfNeeded();
return proxy->GetContext();
}
v8::Local<v8::Context> V8Proxy::GetCurrentContext()
{
return v8::Context::GetCurrent();
}
v8::Handle<v8::Value> V8Proxy::ToV8Object(V8ClassIndex::V8WrapperType type, void* imp)
{
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(type != V8ClassIndex::EVENT);
bool is_active_dom_object = false;
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
return NodeToV8Object(static_cast<Node*>(imp));
case V8ClassIndex::CSSVALUE:
return CSSValueToV8Object(static_cast<CSSValue*>(imp));
case V8ClassIndex::CSSRULE:
return CSSRuleToV8Object(static_cast<CSSRule*>(imp));
case V8ClassIndex::STYLESHEET:
return StyleSheetToV8Object(static_cast<StyleSheet*>(imp));
case V8ClassIndex::DOMWINDOW:
return WindowToV8Object(static_cast<DOMWindow*>(imp));
#if ENABLE(SVG)
SVG_NONNODE_TYPES(MAKE_CASE)
if (type == V8ClassIndex::SVGELEMENTINSTANCE)
return SVGElementInstanceToV8Object(static_cast<SVGElementInstance*>(imp));
return SVGObjectWithContextToV8Object(type, imp);
#endif
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
is_active_dom_object = true;
break;
default:
break;
}
#undef MAKE_CASE
if (!imp) return v8::Null();
// Non DOM node
v8::Persistent<v8::Object> result = is_active_dom_object ?
getActiveDOMObjectMap().get(imp) :
getDOMObjectMap().get(imp);
if (result.IsEmpty()) {
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, imp);
if (!v8obj.IsEmpty()) {
// Go through big switch statement, it has some duplications
// that were handled by code above (such as CSSVALUE, CSSRULE, etc).
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(imp)->ref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
result = v8::Persistent<v8::Object>::New(v8obj);
if (is_active_dom_object)
SetJSWrapperForActiveDOMObject(imp, result);
else
SetJSWrapperForDOMObject(imp, result);
// Special case for non-node objects associated with a
// DOMWindow. Both Safari and FF let the JS wrappers for these
// objects survive GC. To mimic their behavior, V8 creates
// hidden references from the DOMWindow to these wrapper
// objects. These references get cleared when the DOMWindow is
// reused by a new page.
switch (type) {
case V8ClassIndex::CONSOLE:
SetHiddenWindowReference(static_cast<Console*>(imp)->frame(),
V8Custom::kDOMWindowConsoleIndex, result);
break;
case V8ClassIndex::HISTORY:
SetHiddenWindowReference(static_cast<History*>(imp)->frame(),
V8Custom::kDOMWindowHistoryIndex, result);
break;
case V8ClassIndex::NAVIGATOR:
SetHiddenWindowReference(static_cast<Navigator*>(imp)->frame(),
V8Custom::kDOMWindowNavigatorIndex, result);
break;
case V8ClassIndex::SCREEN:
SetHiddenWindowReference(static_cast<Screen*>(imp)->frame(),
V8Custom::kDOMWindowScreenIndex, result);
break;
case V8ClassIndex::LOCATION:
SetHiddenWindowReference(static_cast<Location*>(imp)->frame(),
V8Custom::kDOMWindowLocationIndex, result);
break;
case V8ClassIndex::DOMSELECTION:
SetHiddenWindowReference(static_cast<DOMSelection*>(imp)->frame(),
V8Custom::kDOMWindowDOMSelectionIndex, result);
break;
case V8ClassIndex::BARINFO: {
BarInfo* barinfo = static_cast<BarInfo*>(imp);
Frame* frame = barinfo->frame();
switch (barinfo->type()) {
case BarInfo::Locationbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowLocationbarIndex, result);
break;
case BarInfo::Menubar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowMenubarIndex, result);
break;
case BarInfo::Personalbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowPersonalbarIndex, result);
break;
case BarInfo::Scrollbars:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowScrollbarsIndex, result);
break;
case BarInfo::Statusbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowStatusbarIndex, result);
break;
case BarInfo::Toolbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowToolbarIndex, result);
break;
}
break;
}
default:
break;
}
}
}
return result;
}
void V8Proxy::SetHiddenWindowReference(Frame* frame,
const int internal_index,
v8::Handle<v8::Object> jsobj)
{
// Get DOMWindow
if (!frame) return; // Object might be detached from window
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty()) return;
ASSERT(internal_index < V8Custom::kDOMWindowInternalFieldCount);
v8::Handle<v8::Object> global = context->Global();
// Look for real DOM wrapper.
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
ASSERT(global->GetInternalField(internal_index)->IsUndefined());
global->SetInternalField(internal_index, jsobj);
}
V8ClassIndex::V8WrapperType V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object> object)
{
ASSERT(MaybeDOMWrapper(object));
v8::Handle<v8::Value> type =
object->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
return V8ClassIndex::FromInt(type->Int32Value());
}
void* V8Proxy::ToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
v8::Handle<v8::Value> object)
{
// Native event listener is per frame, it cannot be handled
// by this generic function.
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(MaybeDOMWrapper(object));
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
ASSERT(false);
return NULL;
case V8ClassIndex::XMLHTTPREQUEST:
return DOMWrapperToNative<XMLHttpRequest>(object);
case V8ClassIndex::EVENT:
return DOMWrapperToNative<Event>(object);
case V8ClassIndex::CSSRULE:
return DOMWrapperToNative<CSSRule>(object);
default:
break;
}
#undef MAKE_CASE
return DOMWrapperToNative<void>(object);
}
v8::Handle<v8::Object> V8Proxy::LookupDOMWrapper(
V8ClassIndex::V8WrapperType type, v8::Handle<v8::Value> value)
{
if (value.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::FunctionTemplate> desc = V8Proxy::GetTemplate(type);
while (value->IsObject()) {
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
if (desc->HasInstance(object))
return object;
value = object->GetPrototype();
}
return v8::Handle<v8::Object>();
}
PassRefPtr<NodeFilter> V8Proxy::ToNativeNodeFilter(v8::Handle<v8::Value> filter)
{
// A NodeFilter is used when walking through a DOM tree or iterating tree
// nodes.
// TODO: we may want to cache NodeFilterCondition and NodeFilter
// object, but it is minor.
// NodeFilter is passed to NodeIterator that has a ref counted pointer
// to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
// In NodeFilterCondition, filter object is persisted in its constructor,
// and disposed in its destructor.
if (!filter->IsFunction())
return 0;
NodeFilterCondition* cond = new V8NodeFilterCondition(filter);
return NodeFilter::create(cond);
}
v8::Local<v8::Object> V8Proxy::InstantiateV8Object(
V8ClassIndex::V8WrapperType desc_type,
V8ClassIndex::V8WrapperType cptr_type,
void* imp)
{
// Make a special case for document.all
if (desc_type == V8ClassIndex::HTMLCOLLECTION &&
static_cast<HTMLCollection*>(imp)->type() == HTMLCollection::DocAll) {
desc_type = V8ClassIndex::UNDETECTABLEHTMLCOLLECTION;
}
V8Proxy* proxy = V8Proxy::retrieve();
v8::Local<v8::Object> instance;
if (proxy) {
instance = proxy->CreateWrapperFromCache(desc_type);
} else {
v8::Local<v8::Function> function = GetTemplate(desc_type)->GetFunction();
instance = SafeAllocation::NewInstance(function);
}
if (!instance.IsEmpty()) {
// Avoid setting the DOM wrapper for failed allocations.
SetDOMWrapper(instance, V8ClassIndex::ToInt(cptr_type), imp);
}
return instance;
}
v8::Handle<v8::Value> V8Proxy::CheckNewLegal(const v8::Arguments& args)
{
if (!AllowAllocation::m_current)
return ThrowError(TYPE_ERROR, "Illegal constructor");
return args.This();
}
void V8Proxy::SetDOMWrapper(v8::Handle<v8::Object> obj, int type, void* cptr)
{
ASSERT(obj->InternalFieldCount() >= 2);
obj->SetInternalField(V8Custom::kDOMWrapperObjectIndex, WrapCPointer(cptr));
obj->SetInternalField(V8Custom::kDOMWrapperTypeIndex, v8::Integer::New(type));
}
#ifndef NDEBUG
bool V8Proxy::MaybeDOMWrapper(v8::Handle<v8::Value> value)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
return true;
}
#endif
bool V8Proxy::IsDOMEventWrapper(v8::Handle<v8::Value> value)
{
// All kinds of events use EVENT as dom type in JS wrappers.
// See EventToV8Object
return IsWrapperOfType(value, V8ClassIndex::EVENT);
}
bool V8Proxy::IsWrapperOfType(v8::Handle<v8::Value> value,
V8ClassIndex::V8WrapperType classType)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
return V8ClassIndex::FromInt(type->Int32Value()) == classType;
}
#if ENABLE(VIDEO)
#define FOR_EACH_VIDEO_TAG(macro) \
macro(audio, AUDIO) \
macro(source, SOURCE) \
macro(video, VIDEO)
#else
#define FOR_EACH_VIDEO_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
macro(a, ANCHOR) \
macro(applet, APPLET) \
macro(area, AREA) \
macro(base, BASE) \
macro(basefont, BASEFONT) \
macro(blockquote, BLOCKQUOTE) \
macro(body, BODY) \
macro(br, BR) \
macro(button, BUTTON) \
macro(caption, TABLECAPTION) \
macro(col, TABLECOL) \
macro(colgroup, TABLECOL) \
macro(del, MOD) \
macro(canvas, CANVAS) \
macro(dir, DIRECTORY) \
macro(div, DIV) \
macro(dl, DLIST) \
macro(embed, EMBED) \
macro(fieldset, FIELDSET) \
macro(font, FONT) \
macro(form, FORM) \
macro(frame, FRAME) \
macro(frameset, FRAMESET) \
macro(h1, HEADING) \
macro(h2, HEADING) \
macro(h3, HEADING) \
macro(h4, HEADING) \
macro(h5, HEADING) \
macro(h6, HEADING) \
macro(head, HEAD) \
macro(hr, HR) \
macro(html, HTML) \
macro(img, IMAGE) \
macro(iframe, IFRAME) \
macro(image, IMAGE) \
macro(input, INPUT) \
macro(ins, MOD) \
macro(isindex, ISINDEX) \
macro(keygen, SELECT) \
macro(label, LABEL) \
macro(legend, LEGEND) \
macro(li, LI) \
macro(link, LINK) \
macro(listing, PRE) \
macro(map, MAP) \
macro(marquee, MARQUEE) \
macro(menu, MENU) \
macro(meta, META) \
macro(object, OBJECT) \
macro(ol, OLIST) \
macro(optgroup, OPTGROUP) \
macro(option, OPTION) \
macro(p, PARAGRAPH) \
macro(param, PARAM) \
macro(pre, PRE) \
macro(q, QUOTE) \
macro(script, SCRIPT) \
macro(select, SELECT) \
macro(style, STYLE) \
macro(table, TABLE) \
macro(thead, TABLESECTION) \
macro(tbody, TABLESECTION) \
macro(tfoot, TABLESECTION) \
macro(td, TABLECELL) \
macro(th, TABLECELL) \
macro(tr, TABLEROW) \
macro(textarea, TEXTAREA) \
macro(title, TITLE) \
macro(ul, ULIST) \
macro(xmp, PRE)
V8ClassIndex::V8WrapperType V8Proxy::GetHTMLElementType(HTMLElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::HTML##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#if ENABLE(VIDEO)
if (MediaPlayer::isAvailable()) {
FOR_EACH_VIDEO_TAG(ADD_TO_HASH_MAP)
}
#endif
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0)
return V8ClassIndex::HTMLELEMENT;
return t;
}
#undef FOR_EACH_TAG
#if ENABLE(SVG)
#if ENABLE(SVG_ANIMATION)
#define FOR_EACH_ANIMATION_TAG(macro) \
macro(animateColor, ANIMATECOLOR) \
macro(animate, ANIMATE) \
macro(animateTransform, ANIMATETRANSFORM) \
macro(set, SET)
#else
#define FOR_EACH_ANIMATION_TAG(macro)
#endif
#if ENABLE(SVG_FILTERS)
#define FOR_EACH_FILTERS_TAG(macro) \
macro(feBlend, FEBLEND) \
macro(feColorMatrix, FECOLORMATRIX) \
macro(feComponentTransfer, FECOMPONENTTRANSFER) \
macro(feComposite, FECOMPOSITE) \
macro(feDiffuseLighting, FEDIFFUSELIGHTING) \
macro(feDisplacementMap, FEDISPLACEMENTMAP) \
macro(feDistantLight, FEDISTANTLIGHT) \
macro(feFlood, FEFLOOD) \
macro(feFuncA, FEFUNCA) \
macro(feFuncB, FEFUNCB) \
macro(feFuncG, FEFUNCG) \
macro(feFuncR, FEFUNCR) \
macro(feGaussianBlur, FEGAUSSIANBLUR) \
macro(feImage, FEIMAGE) \
macro(feMerge, FEMERGE) \
macro(feMergeNode, FEMERGENODE) \
macro(feOffset, FEOFFSET) \
macro(fePointLight, FEPOINTLIGHT) \
macro(feSpecularLighting, FESPECULARLIGHTING) \
macro(feSpotLight, FESPOTLIGHT) \
macro(feTile, FETILE) \
macro(feTurbulence, FETURBULENCE) \
macro(filter, FILTER)
#else
#define FOR_EACH_FILTERS_TAG(macro)
#endif
#if ENABLE(SVG_FONTS)
#define FOR_EACH_FONTS_TAG(macro) \
macro(definition-src, DEFINITIONSRC) \
macro(font-face, FONTFACE) \
macro(font-face-format, FONTFACEFORMAT) \
macro(font-face-name, FONTFACENAME) \
macro(font-face-src, FONTFACESRC) \
macro(font-face-uri, FONTFACEURI)
#else
#define FOR_EACH_FONTS_TAG(marco)
#endif
#if ENABLE(SVG_FOREIGN_OBJECT)
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
macro(foreignObject, FOREIGNOBJECT)
#else
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro)
#endif
#if ENABLE(SVG_USE)
#define FOR_EACH_USE_TAG(macro) \
macro(use, USE)
#else
#define FOR_EACH_USE_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
FOR_EACH_ANIMATION_TAG(macro) \
FOR_EACH_FILTERS_TAG(macro) \
FOR_EACH_FONTS_TAG(macro) \
FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
FOR_EACH_USE_TAG(macro) \
macro(a, A) \
macro(altGlyph, ALTGLYPH) \
macro(circle, CIRCLE) \
macro(clipPath, CLIPPATH) \
macro(cursor, CURSOR) \
macro(defs, DEFS) \
macro(desc, DESC) \
macro(ellipse, ELLIPSE) \
macro(g, G) \
macro(glyph, GLYPH) \
macro(image, IMAGE) \
macro(linearGradient, LINEARGRADIENT) \
macro(line, LINE) \
macro(marker, MARKER) \
macro(mask, MASK) \
macro(metadata, METADATA) \
macro(path, PATH) \
macro(pattern, PATTERN) \
macro(polyline, POLYLINE) \
macro(polygon, POLYGON) \
macro(radialGradient, RADIALGRADIENT) \
macro(rect, RECT) \
macro(script, SCRIPT) \
macro(stop, STOP) \
macro(style, STYLE) \
macro(svg, SVG) \
macro(switch, SWITCH) \
macro(symbol, SYMBOL) \
macro(text, TEXT) \
macro(textPath, TEXTPATH) \
macro(title, TITLE) \
macro(tref, TREF) \
macro(tspan, TSPAN) \
macro(view, VIEW) \
// end of macro
V8ClassIndex::V8WrapperType V8Proxy::GetSVGElementType(SVGElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::SVG##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0) return V8ClassIndex::SVGELEMENT;
return t;
}
#undef FOR_EACH_TAG
#endif // ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::EventToV8Object(Event* event)
{
if (!event)
return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(event);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT;
if (event->isUIEvent()) {
if (event->isKeyboardEvent())
type = V8ClassIndex::KEYBOARDEVENT;
else if (event->isTextEvent())
type = V8ClassIndex::TEXTEVENT;
else if (event->isMouseEvent())
type = V8ClassIndex::MOUSEEVENT;
else if (event->isWheelEvent())
type = V8ClassIndex::WHEELEVENT;
#if ENABLE(SVG)
else if (event->isSVGZoomEvent())
type = V8ClassIndex::SVGZOOMEVENT;
#endif
else
type = V8ClassIndex::UIEVENT;
} else if (event->isMutationEvent())
type = V8ClassIndex::MUTATIONEVENT;
else if (event->isOverflowEvent())
type = V8ClassIndex::OVERFLOWEVENT;
else if (event->isMessageEvent())
type = V8ClassIndex::MESSAGEEVENT;
else if (event->isProgressEvent()) {
if (event->isXMLHttpRequestProgressEvent())
type = V8ClassIndex::XMLHTTPREQUESTPROGRESSEVENT;
else
type = V8ClassIndex::PROGRESSEVENT;
} else if (event->isWebKitAnimationEvent())
type = V8ClassIndex::WEBKITANIMATIONEVENT;
else if (event->isWebKitTransitionEvent())
type = V8ClassIndex::WEBKITTRANSITIONEVENT;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::EVENT, event);
if (result.IsEmpty()) {
// Instantiation failed. Avoid updating the DOM object map and
// return null which is already handled by callers of this function
// in case the event is NULL.
return v8::Null();
}
event->ref(); // fast ref
SetJSWrapperForDOMObject(event, v8::Persistent<v8::Object>::New(result));
return result;
}
// Caller checks node is not null.
v8::Handle<v8::Value> V8Proxy::NodeToV8Object(Node* node)
{
if (!node) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMNodeMap().get(node);
if (!wrapper.IsEmpty())
return wrapper;
bool is_document = false; // document type node has special handling
V8ClassIndex::V8WrapperType type;
switch (node->nodeType()) {
case Node::ELEMENT_NODE:
if (node->isHTMLElement())
type = GetHTMLElementType(static_cast<HTMLElement*>(node));
#if ENABLE(SVG)
else if (node->isSVGElement())
type = GetSVGElementType(static_cast<SVGElement*>(node));
#endif
else
type = V8ClassIndex::ELEMENT;
break;
case Node::ATTRIBUTE_NODE:
type = V8ClassIndex::ATTR;
break;
case Node::TEXT_NODE:
type = V8ClassIndex::TEXT;
break;
case Node::CDATA_SECTION_NODE:
type = V8ClassIndex::CDATASECTION;
break;
case Node::ENTITY_NODE:
type = V8ClassIndex::ENTITY;
break;
case Node::PROCESSING_INSTRUCTION_NODE:
type = V8ClassIndex::PROCESSINGINSTRUCTION;
break;
case Node::COMMENT_NODE:
type = V8ClassIndex::COMMENT;
break;
case Node::DOCUMENT_NODE: {
is_document = true;
Document* doc = static_cast<Document*>(node);
if (doc->isHTMLDocument())
type = V8ClassIndex::HTMLDOCUMENT;
#if ENABLE(SVG)
else if (doc->isSVGDocument())
type = V8ClassIndex::SVGDOCUMENT;
#endif
else
type = V8ClassIndex::DOCUMENT;
break;
}
case Node::DOCUMENT_TYPE_NODE:
type = V8ClassIndex::DOCUMENTTYPE;
break;
case Node::NOTATION_NODE:
type = V8ClassIndex::NOTATION;
break;
case Node::DOCUMENT_FRAGMENT_NODE:
type = V8ClassIndex::DOCUMENTFRAGMENT;
break;
case Node::ENTITY_REFERENCE_NODE:
type = V8ClassIndex::ENTITYREFERENCE;
break;
default:
type = V8ClassIndex::NODE;
}
// Find the context to which the node belongs and create the wrapper
// in that context. If the node is not in a document, the current
// context is used.
v8::Local<v8::Context> context;
Document* doc = node->document();
if (doc) {
context = V8Proxy::GetContext(doc->frame());
}
if (!context.IsEmpty()) {
context->Enter();
}
v8::Local<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::NODE, node);
// Exit the node's context if it was entered.
if (!context.IsEmpty()) {
context->Exit();
}
if (result.IsEmpty()) {
// If instantiation failed it's important not to add the result
// to the DOM node map. Instead we return an empty handle, which
// should already be handled by callers of this function in case
// the node is NULL.
return result;
}
node->ref();
SetJSWrapperForDOMNode(node, v8::Persistent<v8::Object>::New(result));
if (is_document) {
Document* doc = static_cast<Document*>(node);
V8Proxy* proxy = V8Proxy::retrieve(doc->frame());
if (proxy)
proxy->UpdateDocumentWrapper(result);
if (type == V8ClassIndex::HTMLDOCUMENT) {
// Create marker object and insert it in two internal fields.
// This is used to implement temporary shadowing of
// document.all.
ASSERT(result->InternalFieldCount() ==
V8Custom::kHTMLDocumentInternalFieldCount);
v8::Local<v8::Object> marker = v8::Object::New();
result->SetInternalField(V8Custom::kHTMLDocumentMarkerIndex, marker);
result->SetInternalField(V8Custom::kHTMLDocumentShadowIndex, marker);
}
}
return result;
}
// A JS object of type EventTarget can only be the following possible types:
// 1) EventTargetNode; 2) XMLHttpRequest; 3) MessagePort; 4) SVGElementInstance;
// 5) XMLHttpRequestUpload 6) Worker
// check EventTarget.h for new type conversion methods
v8::Handle<v8::Value> V8Proxy::EventTargetToV8Object(EventTarget* target)
{
if (!target)
return v8::Null();
#if ENABLE(SVG)
SVGElementInstance* instance = target->toSVGElementInstance();
if (instance)
return ToV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
#endif
#if ENABLE(WORKERS)
Worker* worker = target->toWorker();
if (worker)
return ToV8Object(V8ClassIndex::WORKER, worker);
#endif // WORKERS
Node* node = target->toNode();
if (node)
return NodeToV8Object(node);
// XMLHttpRequest is created within its JS counterpart.
XMLHttpRequest* xhr = target->toXMLHttpRequest();
if (xhr) {
v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(xhr);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
// MessagePort is created within its JS counterpart
MessagePort* port = target->toMessagePort();
if (port) {
v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(port);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload();
if (upload) {
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(upload);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
ASSERT(0);
return v8::Handle<v8::Value>();
}
v8::Handle<v8::Value> V8Proxy::EventListenerToV8Object(
EventListener* listener)
{
if (listener == 0) return v8::Null();
// TODO(fqian): can a user take a lazy event listener and set to other places?
V8AbstractEventListener* v8listener =
static_cast<V8AbstractEventListener*>(listener);
return v8listener->getListenerObject();
}
v8::Handle<v8::Value> V8Proxy::DOMImplementationToV8Object(
DOMImplementation* impl)
{
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::DOMIMPLEMENTATION,
V8ClassIndex::DOMIMPLEMENTATION,
impl);
if (result.IsEmpty()) {
// If the instantiation failed, we ignore it and return null instead
// of returning an empty handle.
return v8::Null();
}
return result;
}
v8::Handle<v8::Value> V8Proxy::StyleSheetToV8Object(StyleSheet* sheet)
{
if (!sheet) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(sheet);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::STYLESHEET;
if (sheet->isCSSStyleSheet())
type = V8ClassIndex::CSSSTYLESHEET;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::STYLESHEET, sheet);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
sheet->ref();
SetJSWrapperForDOMObject(sheet, v8::Persistent<v8::Object>::New(result));
}
// Add a hidden reference from stylesheet object to its owner node.
Node* owner_node = sheet->ownerNode();
if (owner_node) {
v8::Handle<v8::Object> owner =
v8::Handle<v8::Object>::Cast(NodeToV8Object(owner_node));
result->SetInternalField(V8Custom::kStyleSheetOwnerNodeIndex, owner);
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSValueToV8Object(CSSValue* value)
{
if (!value) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(value);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
if (value->isWebKitCSSTransformValue())
type = V8ClassIndex::WEBKITCSSTRANSFORMVALUE;
else if (value->isValueList())
type = V8ClassIndex::CSSVALUELIST;
else if (value->isPrimitiveValue())
type = V8ClassIndex::CSSPRIMITIVEVALUE;
#if ENABLE(SVG)
else if (value->isSVGPaint())
type = V8ClassIndex::SVGPAINT;
else if (value->isSVGColor())
type = V8ClassIndex::SVGCOLOR;
#endif
else
type = V8ClassIndex::CSSVALUE;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSVALUE, value);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
value->ref();
SetJSWrapperForDOMObject(value, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSRuleToV8Object(CSSRule* rule)
{
if (!rule) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(rule);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
switch (rule->type()) {
case CSSRule::STYLE_RULE:
type = V8ClassIndex::CSSSTYLERULE;
break;
case CSSRule::CHARSET_RULE:
type = V8ClassIndex::CSSCHARSETRULE;
break;
case CSSRule::IMPORT_RULE:
type = V8ClassIndex::CSSIMPORTRULE;
break;
case CSSRule::MEDIA_RULE:
type = V8ClassIndex::CSSMEDIARULE;
break;
case CSSRule::FONT_FACE_RULE:
type = V8ClassIndex::CSSFONTFACERULE;
break;
case CSSRule::PAGE_RULE:
type = V8ClassIndex::CSSPAGERULE;
break;
case CSSRule::VARIABLES_RULE:
type = V8ClassIndex::CSSVARIABLESRULE;
break;
case CSSRule::WEBKIT_KEYFRAME_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMERULE;
break;
case CSSRule::WEBKIT_KEYFRAMES_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMESRULE;
break;
default: // CSSRule::UNKNOWN_RULE
type = V8ClassIndex::CSSRULE;
break;
}
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSRULE, rule);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
rule->ref();
SetJSWrapperForDOMObject(rule, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::WindowToV8Object(DOMWindow* window)
{
if (!window) return v8::Null();
// Initializes environment of a frame, and return the global object
// of the frame.
Frame* frame = window->frame();
if (!frame)
return v8::Handle<v8::Object>();
// Special case: Because of evaluateInNewContext() one DOMWindow can have
// multipe contexts and multiple global objects associated with it. When
// code running in one of those contexts accesses the window object, we
// want to return the global object associated with that context, not
// necessarily the first global object associated with that DOMWindow.
v8::Handle<v8::Context> current_context = v8::Context::GetCurrent();
v8::Handle<v8::Object> current_global = current_context->Global();
v8::Handle<v8::Object> windowWrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, current_global);
if (!windowWrapper.IsEmpty())
if (DOMWrapperToNative<DOMWindow>(windowWrapper) == window)
return current_global;
// Otherwise, return the global object associated with this frame.
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
return global;
}
void V8Proxy::BindJSObjectToWindow(Frame* frame,
const char* name,
int type,
v8::Handle<v8::FunctionTemplate> desc,
void* imp)
{
// Get environment.
v8::Handle<v8::Context> context = V8Proxy::GetContext(frame);
if (context.IsEmpty())
return; // JS not enabled.
v8::Context::Scope scope(context);
v8::Handle<v8::Object> instance = desc->GetFunction();
SetDOMWrapper(instance, type, imp);
v8::Handle<v8::Object> global = context->Global();
global->Set(v8::String::New(name), instance);
}
void V8Proxy::ProcessConsoleMessages()
{
ConsoleMessageManager::ProcessDelayedMessages();
}
// Create the utility context for holding JavaScript functions used internally
// which are not visible to JavaScript executing on the page.
void V8Proxy::CreateUtilityContext() {
ASSERT(m_utilityContext.IsEmpty());
v8::HandleScope scope;
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
m_utilityContext = v8::Context::New(NULL, global_template);
v8::Context::Scope context_scope(m_utilityContext);
// Compile JavaScript function for retrieving the source line of the top
// JavaScript stack frame.
static const char* frame_source_line_source =
"function frame_source_line(exec_state) {"
" return exec_state.frame(0).sourceLine();"
"}";
v8::Script::Compile(v8::String::New(frame_source_line_source))->Run();
// Compile JavaScript function for retrieving the source name of the top
// JavaScript stack frame.
static const char* frame_source_name_source =
"function frame_source_name(exec_state) {"
" var frame = exec_state.frame(0);"
" if (frame.func().resolved() && "
" frame.func().script() && "
" frame.func().script().name()) {"
" return frame.func().script().name();"
" }"
"}";
v8::Script::Compile(v8::String::New(frame_source_name_source))->Run();
}
int V8Proxy::GetSourceLineNumber() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = V8Proxy::GetUtilityContext();
if (utility_context.IsEmpty()) {
return 0;
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_line;
frame_source_line = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_line")));
if (frame_source_line.IsEmpty()) {
return 0;
}
v8::Handle<v8::Value> result = v8::Debug::Call(frame_source_line);
if (result.IsEmpty()) {
return 0;
}
return result->Int32Value();
}
String V8Proxy::GetSourceName() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = GetUtilityContext();
if (utility_context.IsEmpty()) {
return String();
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_name;
frame_source_name = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_name")));
if (frame_source_name.IsEmpty()) {
return String();
}
return ToWebCoreString(v8::Debug::Call(frame_source_name));
}
void V8Proxy::RegisterExtension(v8::Extension* extension,
const String& schemeRestriction) {
v8::RegisterExtension(extension);
V8ExtensionInfo info = {schemeRestriction, extension};
m_extensions.push_back(info);
}
} // namespace WebCore
Revert changes causing memory_test problems.
This undoes changes from:
http://codereview.chromium.org/66045
Review URL: http://codereview.chromium.org/67114
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@13639 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include <algorithm>
#include <utility>
#include <v8.h>
#include <v8-debug.h>
#include "v8_proxy.h"
#include "v8_index.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "V8Collection.h"
#include "V8DOMWindow.h"
#include "ChromiumBridge.h"
#include "DOMObjectsInclude.h"
#include "ScriptController.h"
#include "V8DOMMap.h"
namespace WebCore {
// Static utility context.
v8::Persistent<v8::Context> V8Proxy::m_utilityContext;
// Static list of registered extensions
V8ExtensionList V8Proxy::m_extensions;
#ifndef NDEBUG
// Keeps track of global handles created (not JS wrappers
// of DOM objects). Often these global handles are source
// of leaks.
//
// If you want to let a C++ object hold a persistent handle
// to a JS object, you should register the handle here to
// keep track of leaks.
//
// When creating a persistent handle, call:
//
// #ifndef NDEBUG
// V8Proxy::RegisterGlobalHandle(type, host, handle);
// #endif
//
// When releasing the handle, call:
//
// #ifndef NDEBUG
// V8Proxy::UnregisterGlobalHandle(type, host, handle);
// #endif
//
typedef HashMap<v8::Value*, GlobalHandleInfo*> GlobalHandleMap;
static GlobalHandleMap& global_handle_map()
{
static GlobalHandleMap static_global_handle_map;
return static_global_handle_map;
}
// The USE_VAR(x) template is used to silence C++ compiler warnings
// issued for unused variables (typically parameters or values that
// we want to watch in the debugger).
template <typename T>
static inline void USE_VAR(T) { }
// The function is the place to set the break point to inspect
// live global handles. Leaks are often come from leaked global handles.
static void EnumerateGlobalHandles()
{
for (GlobalHandleMap::iterator it = global_handle_map().begin(),
end = global_handle_map().end(); it != end; ++it) {
GlobalHandleInfo* info = it->second;
USE_VAR(info);
v8::Value* handle = it->first;
USE_VAR(handle);
}
}
void V8Proxy::RegisterGlobalHandle(GlobalHandleType type, void* host,
v8::Persistent<v8::Value> handle)
{
ASSERT(!global_handle_map().contains(*handle));
global_handle_map().set(*handle, new GlobalHandleInfo(host, type));
}
void V8Proxy::UnregisterGlobalHandle(void* host, v8::Persistent<v8::Value> handle)
{
ASSERT(global_handle_map().contains(*handle));
GlobalHandleInfo* info = global_handle_map().take(*handle);
ASSERT(info->host_ == host);
delete info;
}
#endif // ifndef NDEBUG
void BatchConfigureAttributes(v8::Handle<v8::ObjectTemplate> inst,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedAttribute* attrs,
size_t num_attrs)
{
for (size_t i = 0; i < num_attrs; ++i) {
const BatchedAttribute* a = &attrs[i];
(a->on_proto ? proto : inst)->SetAccessor(
v8::String::New(a->name),
a->getter,
a->setter,
a->data == V8ClassIndex::INVALID_CLASS_INDEX
? v8::Handle<v8::Value>()
: v8::Integer::New(V8ClassIndex::ToInt(a->data)),
a->settings,
a->attribute);
}
}
void BatchConfigureConstants(v8::Handle<v8::FunctionTemplate> desc,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedConstant* consts,
size_t num_consts)
{
for (size_t i = 0; i < num_consts; ++i) {
const BatchedConstant* c = &consts[i];
desc->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
proto->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
}
}
typedef HashMap<Node*, v8::Object*> DOMNodeMap;
typedef HashMap<void*, v8::Object*> DOMObjectMap;
#ifndef NDEBUG
static void EnumerateDOMObjectMap(DOMObjectMap& wrapper_map)
{
for (DOMObjectMap::iterator it = wrapper_map.begin(), end = wrapper_map.end();
it != end; ++it) {
v8::Persistent<v8::Object> wrapper(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
void* obj = it->first;
USE_VAR(type);
USE_VAR(obj);
}
}
static void EnumerateDOMNodeMap(DOMNodeMap& node_map)
{
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
USE_VAR(node);
ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
}
}
#endif // NDEBUG
#if ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::SVGElementInstanceToV8Object(
SVGElementInstance* instance)
{
if (!instance)
return v8::Null();
v8::Handle<v8::Object> existing_instance = getDOMSVGElementInstanceMap().get(instance);
if (!existing_instance.IsEmpty())
return existing_instance;
instance->ref();
// Instantiate the V8 object and remember it
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::SVGELEMENTINSTANCE,
V8ClassIndex::SVGELEMENTINSTANCE,
instance);
if (!result.IsEmpty()) {
// Only update the DOM SVG element map if the result is non-empty.
getDOMSVGElementInstanceMap().set(instance,
v8::Persistent<v8::Object>::New(result));
}
return result;
}
// Map of SVG objects with contexts to their contexts
static HashMap<void*, SVGElement*>& svg_object_to_context_map()
{
static HashMap<void*, SVGElement*> static_svg_object_to_context_map;
return static_svg_object_to_context_map;
}
v8::Handle<v8::Value> V8Proxy::SVGObjectWithContextToV8Object(
V8ClassIndex::V8WrapperType type, void* object)
{
if (!object)
return v8::Null();
v8::Persistent<v8::Object> result =
getDOMSVGObjectWithContextMap().get(object);
if (!result.IsEmpty()) return result;
// Special case: SVGPathSegs need to be downcast to their real type
if (type == V8ClassIndex::SVGPATHSEG)
type = V8Custom::DowncastSVGPathSeg(object);
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, object);
if (!v8obj.IsEmpty()) {
result = v8::Persistent<v8::Object>::New(v8obj);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(object)->ref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(object)->ref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
getDOMSVGObjectWithContextMap().set(object, result);
}
return result;
}
void V8Proxy::SetSVGContext(void* obj, SVGElement* context)
{
SVGElement* old_context = svg_object_to_context_map().get(obj);
if (old_context == context)
return;
if (old_context)
old_context->deref();
if (context)
context->ref();
svg_object_to_context_map().set(obj, context);
}
SVGElement* V8Proxy::GetSVGContext(void* obj)
{
return svg_object_to_context_map().get(obj);
}
#endif
// A map from a DOM node to its JS wrapper, the wrapper
// is kept as a strong reference to survive GCs.
static DOMObjectMap& gc_protected_map() {
static DOMObjectMap static_gc_protected_map;
return static_gc_protected_map;
}
// static
void V8Proxy::GCProtect(void* dom_object)
{
if (!dom_object)
return;
if (gc_protected_map().contains(dom_object))
return;
if (!getDOMObjectMap().contains(dom_object))
return;
// Create a new (strong) persistent handle for the object.
v8::Persistent<v8::Object> wrapper = getDOMObjectMap().get(dom_object);
if (wrapper.IsEmpty()) return;
gc_protected_map().set(dom_object, *v8::Persistent<v8::Object>::New(wrapper));
}
// static
void V8Proxy::GCUnprotect(void* dom_object)
{
if (!dom_object)
return;
if (!gc_protected_map().contains(dom_object))
return;
// Dispose the strong reference.
v8::Persistent<v8::Object> wrapper(gc_protected_map().take(dom_object));
wrapper.Dispose();
}
// Create object groups for DOM tree nodes.
static void GCPrologue()
{
v8::HandleScope scope;
#ifndef NDEBUG
EnumerateDOMObjectMap(getDOMObjectMap().impl());
#endif
// Run through all objects with possible pending activity making their
// wrappers non weak if there is pending activity.
DOMObjectMap active_map = getActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
ASSERT(wrapper.IsWeak());
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) \
wrapper.ClearWeak(); \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
// Additional handling of message port ensuring that entangled ports also
// have their wrappers entangled. This should ideally be handled when the
// ports are actually entangled in MessagePort::entangle, but to avoid
// forking MessagePort.* this is postponed to GC time. Having this postponed
// has the drawback that the wrappers are "entangled/unentangled" for each
// GC even though their entnaglement most likely is still the same.
if (type == V8ClassIndex::MESSAGEPORT) {
// Get the port and its entangled port.
MessagePort* port1 = static_cast<MessagePort*>(obj);
MessagePortProxy* port2 = port1->entangledPort();
if (port2 != NULL) {
// As ports are always entangled in pairs only perform the entanglement
// once for each pair (see ASSERT in MessagePort::unentangle()).
if (port1 < port2) {
v8::Handle<v8::Value> port1_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
v8::Handle<v8::Value> port2_wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port2);
ASSERT(port1_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port1_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port2_wrapper);
ASSERT(port2_wrapper->IsObject());
v8::Handle<v8::Object>::Cast(port2_wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, port1_wrapper);
}
} else {
// Remove the wrapper entanglement when a port is not entangled.
if (V8Proxy::DOMObjectHasJSWrapper(port1)) {
v8::Handle<v8::Value> wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port1);
ASSERT(wrapper->IsObject());
v8::Handle<v8::Object>::Cast(wrapper)->SetInternalField(
V8Custom::kMessagePortEntangledPortIndex, v8::Undefined());
}
}
}
}
// Create object groups.
typedef std::pair<uintptr_t, Node*> GrouperPair;
typedef Vector<GrouperPair> GrouperList;
DOMNodeMap node_map = getDOMNodeMap().impl();
GrouperList grouper;
grouper.reserveCapacity(node_map.size());
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
// If the node is in document, put it in the ownerDocument's object group.
//
// If an image element was created by JavaScript "new Image",
// it is not in a document. However, if the load event has not
// been fired (still onloading), it is treated as in the document.
//
// Otherwise, the node is put in an object group identified by the root
// elment of the tree to which it belongs.
uintptr_t group_id;
if (node->inDocument() ||
(node->hasTagName(HTMLNames::imgTag) &&
!static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent())) {
group_id = reinterpret_cast<uintptr_t>(node->document());
} else {
Node* root = node;
while (root->parent())
root = root->parent();
// If the node is alone in its DOM tree (doesn't have a parent or any
// children) then the group will be filtered out later anyway.
if (root == node && !node->hasChildNodes())
continue;
group_id = reinterpret_cast<uintptr_t>(root);
}
grouper.append(GrouperPair(group_id, node));
}
// Group by sorting by the group id. This will use the std::pair operator<,
// which will really sort by both the group id and the Node*. However the
// Node* is only involved to sort within a group id, so it will be fine.
std::sort(grouper.begin(), grouper.end());
// TODO(deanm): Should probably work in iterators here, but indexes were
// easier for my simple mind.
for (size_t i = 0; i < grouper.size(); ) {
// Seek to the next key (or the end of the list).
size_t next_key_index = grouper.size();
for (size_t j = i; j < grouper.size(); ++j) {
if (grouper[i].first != grouper[j].first) {
next_key_index = j;
break;
}
}
ASSERT(next_key_index > i);
// We only care about a group if it has more than one object. If it only
// has one object, it has nothing else that needs to be kept alive.
if (next_key_index - i <= 1) {
i = next_key_index;
continue;
}
Vector<v8::Persistent<v8::Value> > group;
group.reserveCapacity(next_key_index - i);
for (; i < next_key_index; ++i) {
v8::Persistent<v8::Value> wrapper =
getDOMNodeMap().get(grouper[i].second);
if (!wrapper.IsEmpty())
group.append(wrapper);
}
if (group.size() > 1)
v8::V8::AddObjectGroup(&group[0], group.size());
ASSERT(i == next_key_index);
}
}
static void GCEpilogue()
{
v8::HandleScope scope;
// Run through all objects with pending activity making their wrappers weak
// again.
DOMObjectMap active_map = getActiveDOMObjectMap().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) { \
ASSERT(!wrapper.IsWeak()); \
wrapper.MakeWeak(impl, &weakActiveDOMObjectCallback); \
} \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
#ifndef NDEBUG
// Check all survivals are weak.
EnumerateDOMObjectMap(getDOMObjectMap().impl());
EnumerateDOMNodeMap(getDOMNodeMap().impl());
EnumerateDOMObjectMap(gc_protected_map());
EnumerateGlobalHandles();
#undef USE_VAR
#endif
}
typedef HashMap<int, v8::FunctionTemplate*> FunctionTemplateMap;
bool AllowAllocation::m_current = false;
// JavaScriptConsoleMessages encapsulate everything needed to
// log messages originating from JavaScript to the Chrome console.
class JavaScriptConsoleMessage {
public:
JavaScriptConsoleMessage(const String& str,
const String& sourceID,
unsigned lineNumber)
: m_string(str)
, m_sourceID(sourceID)
, m_lineNumber(lineNumber) { }
void AddToPage(Page* page) const;
private:
const String m_string;
const String m_sourceID;
const unsigned m_lineNumber;
};
void JavaScriptConsoleMessage::AddToPage(Page* page) const
{
ASSERT(page);
Console* console = page->mainFrame()->domWindow()->console();
console->addMessage(JSMessageSource, ErrorMessageLevel, m_string, m_lineNumber, m_sourceID);
}
// The ConsoleMessageManager handles all console messages that stem
// from JavaScript. It keeps a list of messages that have been delayed but
// it makes sure to add all messages to the console in the right order.
class ConsoleMessageManager {
public:
// Add a message to the console. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void AddMessage(Page* page, const JavaScriptConsoleMessage& message);
// Add a message to the console but delay the reporting until it
// is safe to do so: Either when we leave JavaScript execution or
// when adding other console messages. The primary purpose of this
// method is to avoid calling into V8 to handle console messages
// when the VM is in a state that does not support GCs or allocations.
// Delayed messages are always reported in the page corresponding
// to the active context.
static void AddDelayedMessage(const JavaScriptConsoleMessage& message);
// Process any delayed messages. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void ProcessDelayedMessages();
private:
// All delayed messages are stored in this vector. If the vector
// is NULL, there are no delayed messages.
static Vector<JavaScriptConsoleMessage>* m_delayed;
};
Vector<JavaScriptConsoleMessage>* ConsoleMessageManager::m_delayed = NULL;
void ConsoleMessageManager::AddMessage(
Page* page,
const JavaScriptConsoleMessage& message)
{
// Process any delayed messages to make sure that messages
// appear in the right order in the console.
ProcessDelayedMessages();
message.AddToPage(page);
}
void ConsoleMessageManager::AddDelayedMessage(const JavaScriptConsoleMessage& message)
{
if (!m_delayed)
// Allocate a vector for the delayed messages. Will be
// deallocated when the delayed messages are processed
// in ProcessDelayedMessages().
m_delayed = new Vector<JavaScriptConsoleMessage>();
m_delayed->append(message);
}
void ConsoleMessageManager::ProcessDelayedMessages()
{
// If we have a delayed vector it cannot be empty.
if (!m_delayed)
return;
ASSERT(!m_delayed->isEmpty());
// Add the delayed messages to the page of the active
// context. If that for some bizarre reason does not
// exist, we clear the list of delayed messages to avoid
// posting messages. We still deallocate the vector.
Frame* frame = V8Proxy::retrieveActiveFrame();
Page* page = NULL;
if (frame)
page = frame->page();
if (!page)
m_delayed->clear();
// Iterate through all the delayed messages and add them
// to the console.
const int size = m_delayed->size();
for (int i = 0; i < size; i++) {
m_delayed->at(i).AddToPage(page);
}
// Deallocate the delayed vector.
delete m_delayed;
m_delayed = NULL;
}
// Convenience class for ensuring that delayed messages in the
// ConsoleMessageManager are processed quickly.
class ConsoleMessageScope {
public:
ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
~ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
};
void log_info(Frame* frame, const String& msg, const String& url)
{
Page* page = frame->page();
if (!page)
return;
JavaScriptConsoleMessage message(msg, url, 0);
ConsoleMessageManager::AddMessage(page, message);
}
static void HandleConsoleMessage(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data)
{
// Use the frame where JavaScript is called from.
Frame* frame = V8Proxy::retrieveActiveFrame();
if (!frame)
return;
Page* page = frame->page();
if (!page)
return;
v8::Handle<v8::String> errorMessageString = message->Get();
ASSERT(!errorMessageString.IsEmpty());
String errorMessage = ToWebCoreString(errorMessageString);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool useURL = (resourceName.IsEmpty() || !resourceName->IsString());
String resourceNameString = (useURL)
? frame->document()->url()
: ToWebCoreString(resourceName);
JavaScriptConsoleMessage consoleMessage(errorMessage,
resourceNameString,
message->GetLineNumber());
ConsoleMessageManager::AddMessage(page, consoleMessage);
}
enum DelayReporting {
REPORT_LATER,
REPORT_NOW
};
static void ReportUnsafeAccessTo(Frame* target, DelayReporting delay)
{
ASSERT(target);
Document* targetDocument = target->document();
if (!targetDocument)
return;
Frame* source = V8Proxy::retrieveActiveFrame();
if (!source || !source->document())
return; // Ignore error if the source document is gone.
Document* sourceDocument = source->document();
// FIXME: This error message should contain more specifics of why the same
// origin check has failed.
String str = String::format("Unsafe JavaScript attempt to access frame "
"with URL %s from frame with URL %s. "
"Domains, protocols and ports must match.\n",
targetDocument->url().string().utf8().data(),
sourceDocument->url().string().utf8().data());
// Build a console message with fake source ID and line number.
const String kSourceID = "";
const int kLineNumber = 1;
JavaScriptConsoleMessage message(str, kSourceID, kLineNumber);
if (delay == REPORT_NOW) {
// NOTE(tc): Apple prints the message in the target page, but it seems like
// it should be in the source page. Even for delayed messages, we put it in
// the source page; see ConsoleMessageManager::ProcessDelayedMessages().
ConsoleMessageManager::AddMessage(source->page(), message);
} else {
ASSERT(delay == REPORT_LATER);
// We cannot safely report the message eagerly, because this may cause
// allocations and GCs internally in V8 and we cannot handle that at this
// point. Therefore we delay the reporting.
ConsoleMessageManager::AddDelayedMessage(message);
}
}
static void ReportUnsafeJavaScriptAccess(v8::Local<v8::Object> host,
v8::AccessType type,
v8::Local<v8::Value> data)
{
Frame* target = V8Custom::GetTargetFrame(host, data);
if (target)
ReportUnsafeAccessTo(target, REPORT_LATER);
}
static void HandleFatalErrorInV8()
{
// TODO: We temporarily deal with V8 internal error situations
// such as out-of-memory by crashing the renderer.
CRASH();
}
static void ReportFatalErrorInV8(const char* location, const char* message)
{
// V8 is shutdown, we cannot use V8 api.
// The only thing we can do is to disable JavaScript.
// TODO: clean up V8Proxy and disable JavaScript.
printf("V8 error: %s (%s)\n", message, location);
HandleFatalErrorInV8();
}
V8Proxy::~V8Proxy()
{
clearForClose();
DestroyGlobal();
}
void V8Proxy::DestroyGlobal()
{
if (!m_global.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_global);
#endif
m_global.Dispose();
m_global.Clear();
}
}
bool V8Proxy::DOMObjectHasJSWrapper(void* obj) {
return getDOMObjectMap().contains(obj) ||
getActiveDOMObjectMap().contains(obj);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
ASSERT(false);
#undef MAKE_CASE
default: break;
}
#endif
getDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForActiveDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE: break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default: ASSERT(false);
#undef MAKE_CASE
}
#endif
getActiveDOMObjectMap().set(obj, wrapper);
}
// The caller must have increased node's ref count.
void V8Proxy::SetJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
getDOMNodeMap().set(node, wrapper);
}
PassRefPtr<EventListener> V8Proxy::createInlineEventListener(
const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#if ENABLE(SVG)
PassRefPtr<EventListener> V8Proxy::createSVGEventHandler(const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#endif
// Event listeners
static V8EventListener* FindEventListenerInList(V8EventListenerList& list,
v8::Local<v8::Value> listener,
bool isInline)
{
ASSERT(v8::Context::InContext());
if (!listener->IsObject())
return 0;
return list.find(listener->ToObject(), isInline);
}
// Find an existing wrapper for a JS event listener in the map.
PassRefPtr<V8EventListener> V8Proxy::FindV8EventListener(v8::Local<v8::Value> listener,
bool isInline)
{
return FindEventListenerInList(m_event_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateV8EventListener(v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_event_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8EventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_event_listeners.add(new_listener.get());
return new_listener;
}
// Object event listeners (such as XmlHttpRequest and MessagePort) are
// different from listeners on DOM nodes. An object event listener wrapper
// only holds a weak reference to the JS function. A strong reference can
// create a cycle.
//
// The lifetime of these objects is bounded by the life time of its JS
// wrapper. So we can create a hidden reference from the JS wrapper to
// to its JS function.
//
// (map)
// XHR <---------- JS_wrapper
// | (hidden) : ^
// V V : (may reachable by closure)
// V8_listener --------> JS_function
// (weak) <-- may create a cycle if it is strong
//
// The persistent reference is made weak in the constructor
// of V8ObjectEventListener.
PassRefPtr<V8EventListener> V8Proxy::FindObjectEventListener(
v8::Local<v8::Value> listener, bool isInline)
{
return FindEventListenerInList(m_xhr_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateObjectEventListener(
v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_xhr_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8ObjectEventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_xhr_listeners.add(new_listener.get());
return new_listener.release();
}
static void RemoveEventListenerFromList(V8EventListenerList& list,
V8EventListener* listener)
{
list.remove(listener);
}
void V8Proxy::RemoveV8EventListener(V8EventListener* listener)
{
RemoveEventListenerFromList(m_event_listeners, listener);
}
void V8Proxy::RemoveObjectEventListener(V8ObjectEventListener* listener)
{
RemoveEventListenerFromList(m_xhr_listeners, listener);
}
static void DisconnectEventListenersInList(V8EventListenerList& list)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
(*p)->disconnectFrame();
++p;
}
list.clear();
}
void V8Proxy::DisconnectEventListeners()
{
DisconnectEventListenersInList(m_event_listeners);
DisconnectEventListenersInList(m_xhr_listeners);
}
v8::Handle<v8::Script> V8Proxy::CompileScript(v8::Handle<v8::String> code,
const String& fileName,
int baseLine)
{
const uint16_t* fileNameString = FromWebCoreString(fileName);
v8::Handle<v8::String> name =
v8::String::New(fileNameString, fileName.length());
v8::Handle<v8::Integer> line = v8::Integer::New(baseLine);
v8::ScriptOrigin origin(name, line);
v8::Handle<v8::Script> script = v8::Script::Compile(code, &origin);
return script;
}
bool V8Proxy::HandleOutOfMemory()
{
v8::Local<v8::Context> context = v8::Context::GetCurrent();
if (!context->HasOutOfMemoryException())
return false;
// Warning, error, disable JS for this frame?
Frame* frame = V8Proxy::retrieveFrame(context);
V8Proxy* proxy = V8Proxy::retrieve(frame);
// Clean m_context, and event handlers.
proxy->clearForClose();
// Destroy the global object.
proxy->DestroyGlobal();
ChromiumBridge::notifyJSOutOfMemory(frame);
// Disable JS.
Settings* settings = frame->settings();
ASSERT(settings);
settings->setJavaScriptEnabled(false);
return true;
}
void V8Proxy::evaluateInNewContext(const Vector<ScriptSourceCode>& sources)
{
InitContextIfNeeded();
v8::HandleScope handleScope;
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> windowContext = m_context;
v8::Handle<v8::Object> windowGlobal = windowContext->Global();
v8::Handle<v8::Value> windowWrapper =
V8Proxy::LookupDOMWrapper(V8ClassIndex::DOMWINDOW, windowGlobal);
ASSERT(V8Proxy::DOMWrapperToNative<DOMWindow>(windowWrapper) ==
m_frame->domWindow());
v8::Persistent<v8::Context> context =
createNewContext(v8::Handle<v8::Object>());
v8::Context::Scope context_scope(context);
v8::Handle<v8::Object> global = context->Global();
v8::Handle<v8::String> implicitProtoString = v8::String::New("__proto__");
global->Set(implicitProtoString, windowWrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), windowGlobal);
// Run code in the new context.
for (size_t i = 0; i < sources.size(); ++i)
evaluate(sources[i], 0);
// Using the default security token means that the canAccess is always
// called, which is slow.
// TODO(aa): Use tokens where possible. This will mean keeping track of all
// created contexts so that they can all be updated when the document domain
// changes.
context->UseDefaultSecurityToken();
context.Dispose();
}
v8::Local<v8::Value> V8Proxy::evaluate(const ScriptSourceCode& source, Node* n)
{
ASSERT(v8::Context::InContext());
// Compile the script.
v8::Local<v8::String> code = v8ExternalString(source.source());
ChromiumBridge::traceEventBegin("v8.compile", n, "");
// NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at
// 1, whereas v8 starts at 0.
v8::Handle<v8::Script> script = CompileScript(code, source.url(),
source.startLine() - 1);
ChromiumBridge::traceEventEnd("v8.compile", n, "");
ChromiumBridge::traceEventBegin("v8.run", n, "");
v8::Local<v8::Value> result;
{
// Isolate exceptions that occur when executing the code. These
// exceptions should not interfere with javascript code we might
// evaluate from C++ when returning from here
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
// Set inlineCode to true for <a href="javascript:doSomething()">
// and false for <script>doSomething</script>. We make a rough guess at
// this based on whether the script source has a URL.
result = RunScript(script, source.url().string().isNull());
}
ChromiumBridge::traceEventEnd("v8.run", n, "");
return result;
}
v8::Local<v8::Value> V8Proxy::RunScript(v8::Handle<v8::Script> script,
bool inline_code)
{
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Compute the source string and prevent against infinite recursion.
if (m_recursion >= kMaxRecursionDepth) {
v8::Local<v8::String> code =
v8ExternalString("throw RangeError('Recursion too deep')");
// TODO(kasperl): Ideally, we should be able to re-use the origin of the
// script passed to us as the argument instead of using an empty string
// and 0 baseLine.
script = CompileScript(code, "", 0);
}
if (HandleOutOfMemory())
ASSERT(script.IsEmpty());
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Save the previous value of the inlineCode flag and update the flag for
// the duration of the script invocation.
bool previous_inline_code = inlineCode();
setInlineCode(inline_code);
// Run the script and keep track of the current recursion depth.
v8::Local<v8::Value> result;
{ ConsoleMessageScope scope;
m_recursion++;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = script->Run();
m_recursion--;
}
if (HandleOutOfMemory())
ASSERT(result.IsEmpty());
// Handle V8 internal error situation (Out-of-memory).
if (result.IsEmpty())
return v8::Local<v8::Value>();
// Restore inlineCode flag.
setInlineCode(previous_inline_code);
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Value> V8Proxy::CallFunction(v8::Handle<v8::Function> function,
v8::Handle<v8::Object> receiver,
int argc,
v8::Handle<v8::Value> args[])
{
// For now, we don't put any artificial limitations on the depth
// of recursion that stems from calling functions. This is in
// contrast to the script evaluations.
v8::Local<v8::Value> result;
{
ConsoleMessageScope scope;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = function->Call(receiver, argc, args);
}
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Function> V8Proxy::GetConstructor(V8ClassIndex::V8WrapperType t){
// A DOM constructor is a function instance created from a DOM constructor
// template. There is one instance per context. A DOM constructor is
// different from a normal function in two ways:
// 1) it cannot be called as constructor (aka, used to create a DOM object)
// 2) its __proto__ points to Object.prototype rather than
// Function.prototype.
// The reason for 2) is that, in Safari, a DOM constructor is a normal JS
// object, but not a function. Hotmail relies on the fact that, in Safari,
// HTMLElement.__proto__ == Object.prototype.
//
// m_object_prototype is a cache of the original Object.prototype.
ASSERT(ContextInitialized());
// Enter the context of the proxy to make sure that the
// function is constructed in the context corresponding to
// this proxy.
v8::Context::Scope scope(m_context);
v8::Handle<v8::FunctionTemplate> templ = GetTemplate(t);
// Getting the function might fail if we're running out of
// stack or memory.
v8::TryCatch try_catch;
v8::Local<v8::Function> value = templ->GetFunction();
if (value.IsEmpty())
return v8::Local<v8::Function>();
// Hotmail fix, see comments above.
value->Set(v8::String::New("__proto__"), m_object_prototype);
return value;
}
v8::Local<v8::Object> V8Proxy::CreateWrapperFromCache(V8ClassIndex::V8WrapperType type) {
int class_index = V8ClassIndex::ToInt(type);
v8::Local<v8::Value> cached_object =
m_wrapper_boilerplates->Get(v8::Integer::New(class_index));
if (cached_object->IsObject()) {
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(cached_object);
return object->Clone();
}
// Not in cache.
InitContextIfNeeded();
v8::Context::Scope scope(m_context);
v8::Local<v8::Function> function = GetConstructor(type);
v8::Local<v8::Object> instance = SafeAllocation::NewInstance(function);
if (!instance.IsEmpty()) {
m_wrapper_boilerplates->Set(v8::Integer::New(class_index), instance);
return instance->Clone();
}
return v8::Local<v8::Object>();
}
// Get the string 'toString'.
static v8::Persistent<v8::String> GetToStringName() {
static v8::Persistent<v8::String> value;
if (value.IsEmpty())
value = v8::Persistent<v8::String>::New(v8::String::New("toString"));
return value;
}
static v8::Handle<v8::Value> ConstructorToString(const v8::Arguments& args) {
// The DOM constructors' toString functions grab the current toString
// for Functions by taking the toString function of itself and then
// calling it with the constructor as its receiver. This means that
// changes to the Function prototype chain or toString function are
// reflected when printing DOM constructors. The only wart is that
// changes to a DOM constructor's toString's toString will cause the
// toString of the DOM constructor itself to change. This is extremely
// obscure and unlikely to be a problem.
v8::Handle<v8::Value> val = args.Callee()->Get(GetToStringName());
if (!val->IsFunction()) return v8::String::New("");
return v8::Handle<v8::Function>::Cast(val)->Call(args.This(), 0, NULL);
}
v8::Persistent<v8::FunctionTemplate> V8Proxy::GetTemplate(
V8ClassIndex::V8WrapperType type)
{
v8::Persistent<v8::FunctionTemplate>* cache_cell =
V8ClassIndex::GetCache(type);
if (!(*cache_cell).IsEmpty())
return *cache_cell;
// not found
FunctionTemplateFactory factory = V8ClassIndex::GetFactory(type);
v8::Persistent<v8::FunctionTemplate> desc = factory();
// DOM constructors are functions and should print themselves as such.
// However, we will later replace their prototypes with Object
// prototypes so we need to explicitly override toString on the
// instance itself. If we later make DOM constructors full objects
// we can give them class names instead and Object.prototype.toString
// will work so we can remove this code.
static v8::Persistent<v8::FunctionTemplate> to_string_template;
if (to_string_template.IsEmpty()) {
to_string_template = v8::Persistent<v8::FunctionTemplate>::New(
v8::FunctionTemplate::New(ConstructorToString));
}
desc->Set(GetToStringName(), to_string_template);
switch (type) {
case V8ClassIndex::CSSSTYLEDECLARATION:
// The named property handler for style declarations has a
// setter. Therefore, the interceptor has to be on the object
// itself and not on the prototype object.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(CSSStyleDeclaration),
USE_NAMED_PROPERTY_SETTER(CSSStyleDeclaration));
setCollectionStringOrNullIndexedGetter<CSSStyleDeclaration>(desc);
break;
case V8ClassIndex::CSSRULELIST:
setCollectionIndexedGetter<CSSRuleList, CSSRule>(desc,
V8ClassIndex::CSSRULE);
break;
case V8ClassIndex::CSSVALUELIST:
setCollectionIndexedGetter<CSSValueList, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::CSSVARIABLESDECLARATION:
setCollectionStringOrNullIndexedGetter<CSSVariablesDeclaration>(desc);
break;
case V8ClassIndex::WEBKITCSSTRANSFORMVALUE:
setCollectionIndexedGetter<WebKitCSSTransformValue, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::UNDETECTABLEHTMLCOLLECTION:
desc->InstanceTemplate()->MarkAsUndetectable(); // fall through
case V8ClassIndex::HTMLCOLLECTION:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
setCollectionIndexedGetter<HTMLCollection, Node>(desc,
V8ClassIndex::NODE);
break;
case V8ClassIndex::HTMLOPTIONSCOLLECTION:
setCollectionNamedGetter<HTMLOptionsCollection, Node>(
desc,
V8ClassIndex::NODE);
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLOptionsCollection),
USE_INDEXED_PROPERTY_SETTER(HTMLOptionsCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
break;
case V8ClassIndex::HTMLSELECTELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
nodeCollectionNamedPropertyGetter<HTMLSelectElement>,
0,
0,
0,
0,
v8::Integer::New(V8ClassIndex::NODE));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
nodeCollectionIndexedPropertyGetter<HTMLSelectElement>,
USE_INDEXED_PROPERTY_SETTER(HTMLSelectElementCollection),
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLSelectElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::HTMLDOCUMENT: {
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLDocument),
0,
0,
USE_NAMED_PROPERTY_DELETER(HTMLDocument));
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
//
// Additionally, we add two extra internal fields for
// HTMLDocuments to implement temporary shadowing of
// document.all. One field holds an object that is used as a
// marker. The other field holds the marker object if
// document.all is not shadowed and some other value if
// document.all is shadowed.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kHTMLDocumentInternalFieldCount);
break;
}
#if ENABLE(SVG)
case V8ClassIndex::SVGDOCUMENT: // fall through
#endif
case V8ClassIndex::DOCUMENT: {
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kDocumentMinimumInternalFieldCount);
break;
}
case V8ClassIndex::HTMLAPPLETELEMENT: // fall through
case V8ClassIndex::HTMLEMBEDELEMENT: // fall through
case V8ClassIndex::HTMLOBJECTELEMENT:
// HTMLAppletElement, HTMLEmbedElement and HTMLObjectElement are
// inherited from HTMLPlugInElement, and they share the same property
// handling code.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLPlugInElement),
USE_NAMED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLPlugInElement),
USE_INDEXED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLPlugInElement));
break;
case V8ClassIndex::HTMLFRAMESETELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFrameSetElement));
break;
case V8ClassIndex::HTMLFORMELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFormElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLFormElement),
0,
0,
0,
nodeCollectionIndexedPropertyEnumerator<HTMLFormElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::CANVASPIXELARRAY:
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(CanvasPixelArray),
USE_INDEXED_PROPERTY_SETTER(CanvasPixelArray));
break;
case V8ClassIndex::STYLESHEET: // fall through
case V8ClassIndex::CSSSTYLESHEET: {
// We add an extra internal field to hold a reference to
// the owner node.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kStyleSheetInternalFieldCount);
break;
}
case V8ClassIndex::MEDIALIST:
setCollectionStringOrNullIndexedGetter<MediaList>(desc);
break;
case V8ClassIndex::MIMETYPEARRAY:
setCollectionIndexedAndNamedGetters<MimeTypeArray, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::NAMEDNODEMAP:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NamedNodeMap));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(NamedNodeMap),
0,
0,
0,
collectionIndexedPropertyEnumerator<NamedNodeMap>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::NODELIST:
setCollectionIndexedGetter<NodeList, Node>(desc, V8ClassIndex::NODE);
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NodeList));
break;
case V8ClassIndex::PLUGIN:
setCollectionIndexedAndNamedGetters<Plugin, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::PLUGINARRAY:
setCollectionIndexedAndNamedGetters<PluginArray, Plugin>(
desc,
V8ClassIndex::PLUGIN);
break;
case V8ClassIndex::STYLESHEETLIST:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(StyleSheetList));
setCollectionIndexedGetter<StyleSheetList, StyleSheet>(
desc,
V8ClassIndex::STYLESHEET);
break;
case V8ClassIndex::DOMWINDOW: {
v8::Local<v8::Signature> default_signature = v8::Signature::New(desc);
desc->PrototypeTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(DOMWindow));
desc->PrototypeTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(DOMWindow));
desc->SetHiddenPrototype(true);
// Reserve spaces for references to location, history and
// navigator objects.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
// Set access check callbacks, but turned off initially.
// When a context is detached from a frame, turn on the access check.
// Turning on checks also invalidates inline caches of the object.
instance_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW),
false);
break;
}
case V8ClassIndex::LOCATION: {
// For security reasons, these functions are on the instance
// instead of on the prototype object to insure that they cannot
// be overwritten.
v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate();
instance->SetAccessor(
v8::String::New("reload"),
V8Custom::v8LocationReloadAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("replace"),
V8Custom::v8LocationReplaceAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
instance->SetAccessor(
v8::String::New("assign"),
V8Custom::v8LocationAssignAccessorGetter,
0,
v8::Handle<v8::Value>(),
v8::ALL_CAN_READ,
static_cast<v8::PropertyAttribute>(v8::DontDelete|v8::ReadOnly));
break;
}
case V8ClassIndex::HISTORY: {
break;
}
case V8ClassIndex::MESSAGECHANNEL: {
// Reserve two more internal fields for referencing the port1
// and port2 wrappers. This ensures that the port wrappers are
// kept alive when the channel wrapper is.
desc->SetCallHandler(USE_CALLBACK(MessageChannelConstructor));
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessageChannelInternalFieldCount);
break;
}
case V8ClassIndex::MESSAGEPORT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessagePortInternalFieldCount);
break;
}
#if ENABLE(WORKERS)
case V8ClassIndex::WORKER: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(WorkerConstructor));
break;
}
case V8ClassIndex::WORKERCONTEXT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kWorkerContextInternalFieldCount);
break;
}
#endif // WORKERS
// The following objects are created from JavaScript.
case V8ClassIndex::DOMPARSER:
desc->SetCallHandler(USE_CALLBACK(DOMParserConstructor));
break;
case V8ClassIndex::WEBKITCSSMATRIX:
desc->SetCallHandler(USE_CALLBACK(WebKitCSSMatrixConstructor));
break;
case V8ClassIndex::WEBKITPOINT:
desc->SetCallHandler(USE_CALLBACK(WebKitPointConstructor));
break;
case V8ClassIndex::XMLSERIALIZER:
desc->SetCallHandler(USE_CALLBACK(XMLSerializerConstructor));
break;
case V8ClassIndex::XMLHTTPREQUEST: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(XMLHttpRequestConstructor));
break;
}
case V8ClassIndex::XMLHTTPREQUESTUPLOAD: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
break;
}
case V8ClassIndex::XPATHEVALUATOR:
desc->SetCallHandler(USE_CALLBACK(XPathEvaluatorConstructor));
break;
case V8ClassIndex::XSLTPROCESSOR:
desc->SetCallHandler(USE_CALLBACK(XSLTProcessorConstructor));
break;
default:
break;
}
*cache_cell = desc;
return desc;
}
bool V8Proxy::ContextInitialized()
{
// m_context, m_global, m_object_prototype and m_wrapper_boilerplates should
// all be non-empty if if m_context is non-empty.
ASSERT(m_context.IsEmpty() || !m_global.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_object_prototype.IsEmpty());
ASSERT(m_context.IsEmpty() || !m_wrapper_boilerplates.IsEmpty());
return !m_context.IsEmpty();
}
DOMWindow* V8Proxy::retrieveWindow()
{
// TODO: This seems very fragile. How do we know that the global object
// from the current context is something sensible? Do we need to use the
// last entered here? Who calls this?
return retrieveWindow(v8::Context::GetCurrent());
}
DOMWindow* V8Proxy::retrieveWindow(v8::Handle<v8::Context> context)
{
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
return ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, global);
}
Frame* V8Proxy::retrieveFrame(v8::Handle<v8::Context> context)
{
return retrieveWindow(context)->frame();
}
Frame* V8Proxy::retrieveActiveFrame()
{
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return 0;
return retrieveFrame(context);
}
Frame* V8Proxy::retrieveFrame()
{
DOMWindow* window = retrieveWindow();
return window ? window->frame() : 0;
}
V8Proxy* V8Proxy::retrieve()
{
DOMWindow* window = retrieveWindow();
ASSERT(window);
return retrieve(window->frame());
}
V8Proxy* V8Proxy::retrieve(Frame* frame)
{
if (!frame)
return 0;
return frame->script()->isEnabled() ? frame->script()->proxy() : 0;
}
V8Proxy* V8Proxy::retrieve(ScriptExecutionContext* context)
{
if (!context->isDocument())
return 0;
return retrieve(static_cast<Document*>(context)->frame());
}
void V8Proxy::disconnectFrame()
{
// disconnect all event listeners
DisconnectEventListeners();
}
bool V8Proxy::isEnabled()
{
Settings* settings = m_frame->settings();
if (!settings)
return false;
// In the common case, JavaScript is enabled and we're done.
if (settings->isJavaScriptEnabled())
return true;
// If JavaScript has been disabled, we need to look at the frame to tell
// whether this script came from the web or the embedder. Scripts from the
// embedder are safe to run, but scripts from the other sources are
// disallowed.
Document* document = m_frame->document();
if (!document)
return false;
SecurityOrigin* origin = document->securityOrigin();
if (origin->protocol().isEmpty())
return false; // Uninitialized document
if (origin->protocol() == "http" || origin->protocol() == "https")
return false; // Web site
// TODO(darin): the following are application decisions, and they should
// not be made at this layer. instead, we should bridge out to the
// embedder to allow them to override policy here.
if (origin->protocol() == ChromiumBridge::uiResourceProtocol())
return true; // Embedder's scripts are ok to run
// If the scheme is ftp: or file:, an empty file name indicates a directory
// listing, which requires JavaScript to function properly.
const char* kDirProtocols[] = { "ftp", "file" };
for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
if (origin->protocol() == kDirProtocols[i]) {
const KURL& url = document->url();
return url.pathAfterLastSlash() == url.pathEnd();
}
}
return false; // Other protocols fall through to here
}
void V8Proxy::UpdateDocumentWrapper(v8::Handle<v8::Value> wrapper) {
ClearDocumentWrapper();
ASSERT(m_document.IsEmpty());
m_document = v8::Persistent<v8::Value>::New(wrapper);
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_document);
#endif
}
void V8Proxy::ClearDocumentWrapper()
{
if (!m_document.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_document);
#endif
m_document.Dispose();
m_document.Clear();
}
}
void V8Proxy::DisposeContextHandles() {
if (!m_context.IsEmpty()) {
m_context.Dispose();
m_context.Clear();
}
if (!m_wrapper_boilerplates.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_wrapper_boilerplates);
#endif
m_wrapper_boilerplates.Dispose();
m_wrapper_boilerplates.Clear();
}
if (!m_object_prototype.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_object_prototype);
#endif
m_object_prototype.Dispose();
m_object_prototype.Clear();
}
}
void V8Proxy::clearForClose()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle_scope;
ClearDocumentWrapper();
DisposeContextHandles();
}
}
void V8Proxy::clearForNavigation()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle;
ClearDocumentWrapper();
v8::Context::Scope context_scope(m_context);
// Turn on access check on the old DOMWindow wrapper.
v8::Handle<v8::Object> wrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, m_global);
ASSERT(!wrapper.IsEmpty());
wrapper->TurnOnAccessCheck();
// disconnect all event listeners
DisconnectEventListeners();
// Separate the context from its global object.
m_context->DetachGlobal();
DisposeContextHandles();
// Reinitialize the context so the global object points to
// the new DOM window.
InitContextIfNeeded();
}
}
void V8Proxy::SetSecurityToken() {
Document* document = m_frame->document();
// Setup security origin and security token
if (!document) {
m_context->UseDefaultSecurityToken();
return;
}
// Ask the document's SecurityOrigin to generate a security token.
// If two tokens are equal, then the SecurityOrigins canAccess each other.
// If two tokens are not equal, then we have to call canAccess.
// Note: we can't use the HTTPOrigin if it was set from the DOM.
SecurityOrigin* origin = document->securityOrigin();
String token;
if (!origin->domainWasSetInDOM())
token = document->securityOrigin()->toString();
// An empty or "null" token means we always have to call
// canAccess. The toString method on securityOrigins returns the
// string "null" for empty security origins and for security
// origins that should only allow access to themselves. In this
// case, we use the global object as the security token to avoid
// calling canAccess when a script accesses its own objects.
if (token.isEmpty() || token == "null") {
m_context->UseDefaultSecurityToken();
return;
}
CString utf8_token = token.utf8();
// NOTE: V8 does identity comparison in fast path, must use a symbol
// as the security token.
m_context->SetSecurityToken(
v8::String::NewSymbol(utf8_token.data(), utf8_token.length()));
}
void V8Proxy::updateDocument()
{
if (!m_frame->document())
return;
if (m_global.IsEmpty()) {
ASSERT(m_context.IsEmpty());
return;
}
{
v8::HandleScope scope;
SetSecurityToken();
}
}
void V8Proxy::updateSecurityOrigin()
{
v8::HandleScope scope;
SetSecurityToken();
}
// Same origin policy implementation:
//
// Same origin policy prevents JS code from domain A access JS & DOM objects
// in a different domain B. There are exceptions and several objects are
// accessible by cross-domain code. For example, the window.frames object is
// accessible by code from a different domain, but window.document is not.
//
// The binding code sets security check callbacks on a function template,
// and accessing instances of the template calls the callback function.
// The callback function checks same origin policy.
//
// Callback functions are expensive. V8 uses a security token string to do
// fast access checks for the common case where source and target are in the
// same domain. A security token is a string object that represents
// the protocol/url/port of a domain.
//
// There are special cases where a security token matching is not enough.
// For example, JavaScript can set its domain to a super domain by calling
// document.setDomain(...). In these cases, the binding code can reset
// a context's security token to its global object so that the fast access
// check will always fail.
// Check if the current execution context can access a target frame.
// First it checks same domain policy using the lexical context
//
// This is equivalent to KJS::Window::allowsAccessFrom(ExecState*, String&).
bool V8Proxy::CanAccessPrivate(DOMWindow* target_window)
{
ASSERT(target_window);
String message;
DOMWindow* origin_window = retrieveWindow();
if (origin_window == target_window)
return true;
if (!origin_window)
return false;
// JS may be attempting to access the "window" object, which should be
// valid, even if the document hasn't been constructed yet.
// If the document doesn't exist yet allow JS to access the window object.
if (!origin_window->document())
return true;
const SecurityOrigin* active_security_origin = origin_window->securityOrigin();
const SecurityOrigin* target_security_origin = target_window->securityOrigin();
// We have seen crashes were the security origin of the target has not been
// initialized. Defend against that.
if (!target_security_origin)
return false;
if (active_security_origin->canAccess(target_security_origin))
return true;
// Allow access to a "about:blank" page if the dynamic context is a
// detached context of the same frame as the blank page.
if (target_security_origin->isEmpty() &&
origin_window->frame() == target_window->frame())
return true;
return false;
}
bool V8Proxy::CanAccessFrame(Frame* target, bool report_error)
{
// The subject is detached from a frame, deny accesses.
if (!target)
return false;
if (!CanAccessPrivate(target->domWindow())) {
if (report_error)
ReportUnsafeAccessTo(target, REPORT_NOW);
return false;
}
return true;
}
bool V8Proxy::CheckNodeSecurity(Node* node)
{
if (!node)
return false;
Frame* target = node->document()->frame();
if (!target)
return false;
return CanAccessFrame(target, true);
}
v8::Persistent<v8::Context> V8Proxy::createNewContext(
v8::Handle<v8::Object> global)
{
v8::Persistent<v8::Context> result;
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Persistent<v8::ObjectTemplate> globalTemplate =
V8DOMWindow::GetShadowObjectTemplate();
if (globalTemplate.IsEmpty())
return result;
// Install a security handler with V8.
globalTemplate->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
// Dynamically tell v8 about our extensions now.
const char** extensionNames = new const char*[m_extensions.size()];
int index = 0;
for (V8ExtensionList::iterator it = m_extensions.begin();
it != m_extensions.end(); ++it) {
if (it->scheme.length() > 0 &&
it->scheme != m_frame->document()->url().protocol())
continue;
extensionNames[index++] = it->extension->name();
}
v8::ExtensionConfiguration extensions(index, extensionNames);
result = v8::Context::New(&extensions, globalTemplate, global);
delete [] extensionNames;
extensionNames = 0;
return result;
}
// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance. However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object. The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript. The javascript object that corresponds to a
// DOMWindow instance is the shadow object. When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
//
// To implement split-window, see
// 1) https://bugs.webkit.org/show_bug.cgi?id=17249
// 2) https://wiki.mozilla.org/Gecko:SplitWindow
// 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
// we need to split the shadow object further into two objects:
// an outer window and an inner window. The inner window is the hidden
// prototype of the outer window. The inner window is the default
// global object of the context. A variable declared in the global
// scope is a property of the inner window.
//
// The outer window sticks to a Frame, it is exposed to JavaScript
// via window.window, window.self, window.parent, etc. The outer window
// has a security token which is the domain. The outer window cannot
// have its own properties. window.foo = 'x' is delegated to the
// inner window.
//
// When a frame navigates to a new page, the inner window is cut off
// the outer window, and the outer window identify is preserved for
// the frame. However, a new inner window is created for the new page.
// If there are JS code holds a closure to the old inner window,
// it won't be able to reach the outer window via its global object.
void V8Proxy::InitContextIfNeeded()
{
// Bail out if the context has already been initialized.
if (!m_context.IsEmpty())
return;
// Create a handle scope for all local handles.
v8::HandleScope handle_scope;
// Setup the security handlers and message listener. This only has
// to be done once.
static bool v8_initialized = false;
if (!v8_initialized) {
// Tells V8 not to call the default OOM handler, binding code
// will handle it.
v8::V8::IgnoreOutOfMemoryException();
v8::V8::SetFatalErrorHandler(ReportFatalErrorInV8);
v8::V8::SetGlobalGCPrologueCallback(&GCPrologue);
v8::V8::SetGlobalGCEpilogueCallback(&GCEpilogue);
v8::V8::AddMessageListener(HandleConsoleMessage);
v8::V8::SetFailedAccessCheckCallbackFunction(ReportUnsafeJavaScriptAccess);
v8_initialized = true;
}
m_context = createNewContext(m_global);
if (m_context.IsEmpty())
return;
// Starting from now, use local context only.
v8::Local<v8::Context> context = GetContext();
v8::Context::Scope context_scope(context);
// Store the first global object created so we can reuse it.
if (m_global.IsEmpty()) {
m_global = v8::Persistent<v8::Object>::New(context->Global());
// Bail out if allocation of the first global objects fails.
if (m_global.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_global);
#endif
}
// Allocate strings used during initialization.
v8::Handle<v8::String> object_string = v8::String::New("Object");
v8::Handle<v8::String> prototype_string = v8::String::New("prototype");
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
// Bail out if allocation failed.
if (object_string.IsEmpty() ||
prototype_string.IsEmpty() ||
implicit_proto_string.IsEmpty()) {
DisposeContextHandles();
return;
}
// Allocate clone cache and pre-allocated objects
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(
m_global->Get(object_string));
m_object_prototype = v8::Persistent<v8::Value>::New(
object->Get(prototype_string));
m_wrapper_boilerplates = v8::Persistent<v8::Array>::New(
v8::Array::New(V8ClassIndex::WRAPPER_TYPE_COUNT));
// Bail out if allocation failed.
if (m_object_prototype.IsEmpty()) {
DisposeContextHandles();
return;
}
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_object_prototype);
RegisterGlobalHandle(PROXY, this, m_wrapper_boilerplates);
#endif
// Create a new JS window object and use it as the prototype for the
// shadow global object.
v8::Handle<v8::Function> window_constructor =
GetConstructor(V8ClassIndex::DOMWINDOW);
v8::Local<v8::Object> js_window =
SafeAllocation::NewInstance(window_constructor);
// Bail out if allocation failed.
if (js_window.IsEmpty()) {
DisposeContextHandles();
return;
}
DOMWindow* window = m_frame->domWindow();
// Wrap the window.
SetDOMWrapper(js_window,
V8ClassIndex::ToInt(V8ClassIndex::DOMWINDOW),
window);
window->ref();
V8Proxy::SetJSWrapperForDOMObject(window,
v8::Persistent<v8::Object>::New(js_window));
// Insert the window instance as the prototype of the shadow object.
v8::Handle<v8::Object> v8_global = context->Global();
v8_global->Set(implicit_proto_string, js_window);
SetSecurityToken();
m_frame->loader()->dispatchWindowObjectAvailable();
}
void V8Proxy::SetDOMException(int exception_code)
{
if (exception_code <= 0)
return;
ExceptionCodeDescription description;
getExceptionCodeDescription(exception_code, description);
v8::Handle<v8::Value> exception;
switch (description.type) {
case DOMExceptionType:
exception = ToV8Object(V8ClassIndex::DOMCOREEXCEPTION,
DOMCoreException::create(description));
break;
case RangeExceptionType:
exception = ToV8Object(V8ClassIndex::RANGEEXCEPTION,
RangeException::create(description));
break;
case EventExceptionType:
exception = ToV8Object(V8ClassIndex::EVENTEXCEPTION,
EventException::create(description));
break;
case XMLHttpRequestExceptionType:
exception = ToV8Object(V8ClassIndex::XMLHTTPREQUESTEXCEPTION,
XMLHttpRequestException::create(description));
break;
#if ENABLE(SVG)
case SVGExceptionType:
exception = ToV8Object(V8ClassIndex::SVGEXCEPTION,
SVGException::create(description));
break;
#endif
#if ENABLE(XPATH)
case XPathExceptionType:
exception = ToV8Object(V8ClassIndex::XPATHEXCEPTION,
XPathException::create(description));
break;
#endif
}
ASSERT(!exception.IsEmpty());
v8::ThrowException(exception);
}
v8::Handle<v8::Value> V8Proxy::ThrowError(ErrorType type, const char* message)
{
switch (type) {
case RANGE_ERROR:
return v8::ThrowException(v8::Exception::RangeError(v8String(message)));
case REFERENCE_ERROR:
return v8::ThrowException(
v8::Exception::ReferenceError(v8String(message)));
case SYNTAX_ERROR:
return v8::ThrowException(v8::Exception::SyntaxError(v8String(message)));
case TYPE_ERROR:
return v8::ThrowException(v8::Exception::TypeError(v8String(message)));
case GENERAL_ERROR:
return v8::ThrowException(v8::Exception::Error(v8String(message)));
default:
ASSERT(false);
return v8::Handle<v8::Value>();
}
}
v8::Local<v8::Context> V8Proxy::GetContext(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
if (!proxy)
return v8::Local<v8::Context>();
proxy->InitContextIfNeeded();
return proxy->GetContext();
}
v8::Local<v8::Context> V8Proxy::GetCurrentContext()
{
return v8::Context::GetCurrent();
}
v8::Handle<v8::Value> V8Proxy::ToV8Object(V8ClassIndex::V8WrapperType type, void* imp)
{
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(type != V8ClassIndex::EVENT);
bool is_active_dom_object = false;
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
return NodeToV8Object(static_cast<Node*>(imp));
case V8ClassIndex::CSSVALUE:
return CSSValueToV8Object(static_cast<CSSValue*>(imp));
case V8ClassIndex::CSSRULE:
return CSSRuleToV8Object(static_cast<CSSRule*>(imp));
case V8ClassIndex::STYLESHEET:
return StyleSheetToV8Object(static_cast<StyleSheet*>(imp));
case V8ClassIndex::DOMWINDOW:
return WindowToV8Object(static_cast<DOMWindow*>(imp));
#if ENABLE(SVG)
SVG_NONNODE_TYPES(MAKE_CASE)
if (type == V8ClassIndex::SVGELEMENTINSTANCE)
return SVGElementInstanceToV8Object(static_cast<SVGElementInstance*>(imp));
return SVGObjectWithContextToV8Object(type, imp);
#endif
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
is_active_dom_object = true;
break;
default:
break;
}
#undef MAKE_CASE
if (!imp) return v8::Null();
// Non DOM node
v8::Persistent<v8::Object> result = is_active_dom_object ?
getActiveDOMObjectMap().get(imp) :
getDOMObjectMap().get(imp);
if (result.IsEmpty()) {
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, imp);
if (!v8obj.IsEmpty()) {
// Go through big switch statement, it has some duplications
// that were handled by code above (such as CSSVALUE, CSSRULE, etc).
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(imp)->ref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
result = v8::Persistent<v8::Object>::New(v8obj);
if (is_active_dom_object)
SetJSWrapperForActiveDOMObject(imp, result);
else
SetJSWrapperForDOMObject(imp, result);
// Special case for non-node objects associated with a
// DOMWindow. Both Safari and FF let the JS wrappers for these
// objects survive GC. To mimic their behavior, V8 creates
// hidden references from the DOMWindow to these wrapper
// objects. These references get cleared when the DOMWindow is
// reused by a new page.
switch (type) {
case V8ClassIndex::CONSOLE:
SetHiddenWindowReference(static_cast<Console*>(imp)->frame(),
V8Custom::kDOMWindowConsoleIndex, result);
break;
case V8ClassIndex::HISTORY:
SetHiddenWindowReference(static_cast<History*>(imp)->frame(),
V8Custom::kDOMWindowHistoryIndex, result);
break;
case V8ClassIndex::NAVIGATOR:
SetHiddenWindowReference(static_cast<Navigator*>(imp)->frame(),
V8Custom::kDOMWindowNavigatorIndex, result);
break;
case V8ClassIndex::SCREEN:
SetHiddenWindowReference(static_cast<Screen*>(imp)->frame(),
V8Custom::kDOMWindowScreenIndex, result);
break;
case V8ClassIndex::LOCATION:
SetHiddenWindowReference(static_cast<Location*>(imp)->frame(),
V8Custom::kDOMWindowLocationIndex, result);
break;
case V8ClassIndex::DOMSELECTION:
SetHiddenWindowReference(static_cast<DOMSelection*>(imp)->frame(),
V8Custom::kDOMWindowDOMSelectionIndex, result);
break;
case V8ClassIndex::BARINFO: {
BarInfo* barinfo = static_cast<BarInfo*>(imp);
Frame* frame = barinfo->frame();
switch (barinfo->type()) {
case BarInfo::Locationbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowLocationbarIndex, result);
break;
case BarInfo::Menubar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowMenubarIndex, result);
break;
case BarInfo::Personalbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowPersonalbarIndex, result);
break;
case BarInfo::Scrollbars:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowScrollbarsIndex, result);
break;
case BarInfo::Statusbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowStatusbarIndex, result);
break;
case BarInfo::Toolbar:
SetHiddenWindowReference(frame, V8Custom::kDOMWindowToolbarIndex, result);
break;
}
break;
}
default:
break;
}
}
}
return result;
}
void V8Proxy::SetHiddenWindowReference(Frame* frame,
const int internal_index,
v8::Handle<v8::Object> jsobj)
{
// Get DOMWindow
if (!frame) return; // Object might be detached from window
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty()) return;
ASSERT(internal_index < V8Custom::kDOMWindowInternalFieldCount);
v8::Handle<v8::Object> global = context->Global();
// Look for real DOM wrapper.
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
ASSERT(global->GetInternalField(internal_index)->IsUndefined());
global->SetInternalField(internal_index, jsobj);
}
V8ClassIndex::V8WrapperType V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object> object)
{
ASSERT(MaybeDOMWrapper(object));
v8::Handle<v8::Value> type =
object->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
return V8ClassIndex::FromInt(type->Int32Value());
}
void* V8Proxy::ToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
v8::Handle<v8::Value> object)
{
// Native event listener is per frame, it cannot be handled
// by this generic function.
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(MaybeDOMWrapper(object));
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
ASSERT(false);
return NULL;
case V8ClassIndex::XMLHTTPREQUEST:
return DOMWrapperToNative<XMLHttpRequest>(object);
case V8ClassIndex::EVENT:
return DOMWrapperToNative<Event>(object);
case V8ClassIndex::CSSRULE:
return DOMWrapperToNative<CSSRule>(object);
default:
break;
}
#undef MAKE_CASE
return DOMWrapperToNative<void>(object);
}
v8::Handle<v8::Object> V8Proxy::LookupDOMWrapper(
V8ClassIndex::V8WrapperType type, v8::Handle<v8::Value> value)
{
if (value.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::FunctionTemplate> desc = V8Proxy::GetTemplate(type);
while (value->IsObject()) {
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
if (desc->HasInstance(object))
return object;
value = object->GetPrototype();
}
return v8::Handle<v8::Object>();
}
PassRefPtr<NodeFilter> V8Proxy::ToNativeNodeFilter(v8::Handle<v8::Value> filter)
{
// A NodeFilter is used when walking through a DOM tree or iterating tree
// nodes.
// TODO: we may want to cache NodeFilterCondition and NodeFilter
// object, but it is minor.
// NodeFilter is passed to NodeIterator that has a ref counted pointer
// to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
// In NodeFilterCondition, filter object is persisted in its constructor,
// and disposed in its destructor.
if (!filter->IsFunction())
return 0;
NodeFilterCondition* cond = new V8NodeFilterCondition(filter);
return NodeFilter::create(cond);
}
v8::Local<v8::Object> V8Proxy::InstantiateV8Object(
V8ClassIndex::V8WrapperType desc_type,
V8ClassIndex::V8WrapperType cptr_type,
void* imp)
{
// Make a special case for document.all
if (desc_type == V8ClassIndex::HTMLCOLLECTION &&
static_cast<HTMLCollection*>(imp)->type() == HTMLCollection::DocAll) {
desc_type = V8ClassIndex::UNDETECTABLEHTMLCOLLECTION;
}
V8Proxy* proxy = V8Proxy::retrieve();
v8::Local<v8::Object> instance;
if (proxy) {
instance = proxy->CreateWrapperFromCache(desc_type);
} else {
v8::Local<v8::Function> function = GetTemplate(desc_type)->GetFunction();
instance = SafeAllocation::NewInstance(function);
}
if (!instance.IsEmpty()) {
// Avoid setting the DOM wrapper for failed allocations.
SetDOMWrapper(instance, V8ClassIndex::ToInt(cptr_type), imp);
}
return instance;
}
v8::Handle<v8::Value> V8Proxy::CheckNewLegal(const v8::Arguments& args)
{
if (!AllowAllocation::m_current)
return ThrowError(TYPE_ERROR, "Illegal constructor");
return args.This();
}
void V8Proxy::SetDOMWrapper(v8::Handle<v8::Object> obj, int type, void* cptr)
{
ASSERT(obj->InternalFieldCount() >= 2);
obj->SetInternalField(V8Custom::kDOMWrapperObjectIndex, WrapCPointer(cptr));
obj->SetInternalField(V8Custom::kDOMWrapperTypeIndex, v8::Integer::New(type));
}
#ifndef NDEBUG
bool V8Proxy::MaybeDOMWrapper(v8::Handle<v8::Value> value)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
return true;
}
#endif
bool V8Proxy::IsDOMEventWrapper(v8::Handle<v8::Value> value)
{
// All kinds of events use EVENT as dom type in JS wrappers.
// See EventToV8Object
return IsWrapperOfType(value, V8ClassIndex::EVENT);
}
bool V8Proxy::IsWrapperOfType(v8::Handle<v8::Value> value,
V8ClassIndex::V8WrapperType classType)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
return V8ClassIndex::FromInt(type->Int32Value()) == classType;
}
#if ENABLE(VIDEO)
#define FOR_EACH_VIDEO_TAG(macro) \
macro(audio, AUDIO) \
macro(source, SOURCE) \
macro(video, VIDEO)
#else
#define FOR_EACH_VIDEO_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
macro(a, ANCHOR) \
macro(applet, APPLET) \
macro(area, AREA) \
macro(base, BASE) \
macro(basefont, BASEFONT) \
macro(blockquote, BLOCKQUOTE) \
macro(body, BODY) \
macro(br, BR) \
macro(button, BUTTON) \
macro(caption, TABLECAPTION) \
macro(col, TABLECOL) \
macro(colgroup, TABLECOL) \
macro(del, MOD) \
macro(canvas, CANVAS) \
macro(dir, DIRECTORY) \
macro(div, DIV) \
macro(dl, DLIST) \
macro(embed, EMBED) \
macro(fieldset, FIELDSET) \
macro(font, FONT) \
macro(form, FORM) \
macro(frame, FRAME) \
macro(frameset, FRAMESET) \
macro(h1, HEADING) \
macro(h2, HEADING) \
macro(h3, HEADING) \
macro(h4, HEADING) \
macro(h5, HEADING) \
macro(h6, HEADING) \
macro(head, HEAD) \
macro(hr, HR) \
macro(html, HTML) \
macro(img, IMAGE) \
macro(iframe, IFRAME) \
macro(image, IMAGE) \
macro(input, INPUT) \
macro(ins, MOD) \
macro(isindex, ISINDEX) \
macro(keygen, SELECT) \
macro(label, LABEL) \
macro(legend, LEGEND) \
macro(li, LI) \
macro(link, LINK) \
macro(listing, PRE) \
macro(map, MAP) \
macro(marquee, MARQUEE) \
macro(menu, MENU) \
macro(meta, META) \
macro(object, OBJECT) \
macro(ol, OLIST) \
macro(optgroup, OPTGROUP) \
macro(option, OPTION) \
macro(p, PARAGRAPH) \
macro(param, PARAM) \
macro(pre, PRE) \
macro(q, QUOTE) \
macro(script, SCRIPT) \
macro(select, SELECT) \
macro(style, STYLE) \
macro(table, TABLE) \
macro(thead, TABLESECTION) \
macro(tbody, TABLESECTION) \
macro(tfoot, TABLESECTION) \
macro(td, TABLECELL) \
macro(th, TABLECELL) \
macro(tr, TABLEROW) \
macro(textarea, TEXTAREA) \
macro(title, TITLE) \
macro(ul, ULIST) \
macro(xmp, PRE)
V8ClassIndex::V8WrapperType V8Proxy::GetHTMLElementType(HTMLElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::HTML##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#if ENABLE(VIDEO)
if (MediaPlayer::isAvailable()) {
FOR_EACH_VIDEO_TAG(ADD_TO_HASH_MAP)
}
#endif
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0)
return V8ClassIndex::HTMLELEMENT;
return t;
}
#undef FOR_EACH_TAG
#if ENABLE(SVG)
#if ENABLE(SVG_ANIMATION)
#define FOR_EACH_ANIMATION_TAG(macro) \
macro(animateColor, ANIMATECOLOR) \
macro(animate, ANIMATE) \
macro(animateTransform, ANIMATETRANSFORM) \
macro(set, SET)
#else
#define FOR_EACH_ANIMATION_TAG(macro)
#endif
#if ENABLE(SVG_FILTERS)
#define FOR_EACH_FILTERS_TAG(macro) \
macro(feBlend, FEBLEND) \
macro(feColorMatrix, FECOLORMATRIX) \
macro(feComponentTransfer, FECOMPONENTTRANSFER) \
macro(feComposite, FECOMPOSITE) \
macro(feDiffuseLighting, FEDIFFUSELIGHTING) \
macro(feDisplacementMap, FEDISPLACEMENTMAP) \
macro(feDistantLight, FEDISTANTLIGHT) \
macro(feFlood, FEFLOOD) \
macro(feFuncA, FEFUNCA) \
macro(feFuncB, FEFUNCB) \
macro(feFuncG, FEFUNCG) \
macro(feFuncR, FEFUNCR) \
macro(feGaussianBlur, FEGAUSSIANBLUR) \
macro(feImage, FEIMAGE) \
macro(feMerge, FEMERGE) \
macro(feMergeNode, FEMERGENODE) \
macro(feOffset, FEOFFSET) \
macro(fePointLight, FEPOINTLIGHT) \
macro(feSpecularLighting, FESPECULARLIGHTING) \
macro(feSpotLight, FESPOTLIGHT) \
macro(feTile, FETILE) \
macro(feTurbulence, FETURBULENCE) \
macro(filter, FILTER)
#else
#define FOR_EACH_FILTERS_TAG(macro)
#endif
#if ENABLE(SVG_FONTS)
#define FOR_EACH_FONTS_TAG(macro) \
macro(definition-src, DEFINITIONSRC) \
macro(font-face, FONTFACE) \
macro(font-face-format, FONTFACEFORMAT) \
macro(font-face-name, FONTFACENAME) \
macro(font-face-src, FONTFACESRC) \
macro(font-face-uri, FONTFACEURI)
#else
#define FOR_EACH_FONTS_TAG(marco)
#endif
#if ENABLE(SVG_FOREIGN_OBJECT)
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
macro(foreignObject, FOREIGNOBJECT)
#else
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro)
#endif
#if ENABLE(SVG_USE)
#define FOR_EACH_USE_TAG(macro) \
macro(use, USE)
#else
#define FOR_EACH_USE_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
FOR_EACH_ANIMATION_TAG(macro) \
FOR_EACH_FILTERS_TAG(macro) \
FOR_EACH_FONTS_TAG(macro) \
FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
FOR_EACH_USE_TAG(macro) \
macro(a, A) \
macro(altGlyph, ALTGLYPH) \
macro(circle, CIRCLE) \
macro(clipPath, CLIPPATH) \
macro(cursor, CURSOR) \
macro(defs, DEFS) \
macro(desc, DESC) \
macro(ellipse, ELLIPSE) \
macro(g, G) \
macro(glyph, GLYPH) \
macro(image, IMAGE) \
macro(linearGradient, LINEARGRADIENT) \
macro(line, LINE) \
macro(marker, MARKER) \
macro(mask, MASK) \
macro(metadata, METADATA) \
macro(path, PATH) \
macro(pattern, PATTERN) \
macro(polyline, POLYLINE) \
macro(polygon, POLYGON) \
macro(radialGradient, RADIALGRADIENT) \
macro(rect, RECT) \
macro(script, SCRIPT) \
macro(stop, STOP) \
macro(style, STYLE) \
macro(svg, SVG) \
macro(switch, SWITCH) \
macro(symbol, SYMBOL) \
macro(text, TEXT) \
macro(textPath, TEXTPATH) \
macro(title, TITLE) \
macro(tref, TREF) \
macro(tspan, TSPAN) \
macro(view, VIEW) \
// end of macro
V8ClassIndex::V8WrapperType V8Proxy::GetSVGElementType(SVGElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::SVG##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0) return V8ClassIndex::SVGELEMENT;
return t;
}
#undef FOR_EACH_TAG
#endif // ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::EventToV8Object(Event* event)
{
if (!event)
return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(event);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT;
if (event->isUIEvent()) {
if (event->isKeyboardEvent())
type = V8ClassIndex::KEYBOARDEVENT;
else if (event->isTextEvent())
type = V8ClassIndex::TEXTEVENT;
else if (event->isMouseEvent())
type = V8ClassIndex::MOUSEEVENT;
else if (event->isWheelEvent())
type = V8ClassIndex::WHEELEVENT;
#if ENABLE(SVG)
else if (event->isSVGZoomEvent())
type = V8ClassIndex::SVGZOOMEVENT;
#endif
else
type = V8ClassIndex::UIEVENT;
} else if (event->isMutationEvent())
type = V8ClassIndex::MUTATIONEVENT;
else if (event->isOverflowEvent())
type = V8ClassIndex::OVERFLOWEVENT;
else if (event->isMessageEvent())
type = V8ClassIndex::MESSAGEEVENT;
else if (event->isProgressEvent()) {
if (event->isXMLHttpRequestProgressEvent())
type = V8ClassIndex::XMLHTTPREQUESTPROGRESSEVENT;
else
type = V8ClassIndex::PROGRESSEVENT;
} else if (event->isWebKitAnimationEvent())
type = V8ClassIndex::WEBKITANIMATIONEVENT;
else if (event->isWebKitTransitionEvent())
type = V8ClassIndex::WEBKITTRANSITIONEVENT;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::EVENT, event);
if (result.IsEmpty()) {
// Instantiation failed. Avoid updating the DOM object map and
// return null which is already handled by callers of this function
// in case the event is NULL.
return v8::Null();
}
event->ref(); // fast ref
SetJSWrapperForDOMObject(event, v8::Persistent<v8::Object>::New(result));
return result;
}
// Caller checks node is not null.
v8::Handle<v8::Value> V8Proxy::NodeToV8Object(Node* node)
{
if (!node) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMNodeMap().get(node);
if (!wrapper.IsEmpty())
return wrapper;
bool is_document = false; // document type node has special handling
V8ClassIndex::V8WrapperType type;
switch (node->nodeType()) {
case Node::ELEMENT_NODE:
if (node->isHTMLElement())
type = GetHTMLElementType(static_cast<HTMLElement*>(node));
#if ENABLE(SVG)
else if (node->isSVGElement())
type = GetSVGElementType(static_cast<SVGElement*>(node));
#endif
else
type = V8ClassIndex::ELEMENT;
break;
case Node::ATTRIBUTE_NODE:
type = V8ClassIndex::ATTR;
break;
case Node::TEXT_NODE:
type = V8ClassIndex::TEXT;
break;
case Node::CDATA_SECTION_NODE:
type = V8ClassIndex::CDATASECTION;
break;
case Node::ENTITY_NODE:
type = V8ClassIndex::ENTITY;
break;
case Node::PROCESSING_INSTRUCTION_NODE:
type = V8ClassIndex::PROCESSINGINSTRUCTION;
break;
case Node::COMMENT_NODE:
type = V8ClassIndex::COMMENT;
break;
case Node::DOCUMENT_NODE: {
is_document = true;
Document* doc = static_cast<Document*>(node);
if (doc->isHTMLDocument())
type = V8ClassIndex::HTMLDOCUMENT;
#if ENABLE(SVG)
else if (doc->isSVGDocument())
type = V8ClassIndex::SVGDOCUMENT;
#endif
else
type = V8ClassIndex::DOCUMENT;
break;
}
case Node::DOCUMENT_TYPE_NODE:
type = V8ClassIndex::DOCUMENTTYPE;
break;
case Node::NOTATION_NODE:
type = V8ClassIndex::NOTATION;
break;
case Node::DOCUMENT_FRAGMENT_NODE:
type = V8ClassIndex::DOCUMENTFRAGMENT;
break;
case Node::ENTITY_REFERENCE_NODE:
type = V8ClassIndex::ENTITYREFERENCE;
break;
default:
type = V8ClassIndex::NODE;
}
// Find the context to which the node belongs and create the wrapper
// in that context. If the node is not in a document, the current
// context is used.
v8::Local<v8::Context> context;
Document* doc = node->document();
if (doc) {
context = V8Proxy::GetContext(doc->frame());
}
if (!context.IsEmpty()) {
context->Enter();
}
v8::Local<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::NODE, node);
// Exit the node's context if it was entered.
if (!context.IsEmpty()) {
context->Exit();
}
if (result.IsEmpty()) {
// If instantiation failed it's important not to add the result
// to the DOM node map. Instead we return an empty handle, which
// should already be handled by callers of this function in case
// the node is NULL.
return result;
}
node->ref();
SetJSWrapperForDOMNode(node, v8::Persistent<v8::Object>::New(result));
if (is_document) {
Document* doc = static_cast<Document*>(node);
V8Proxy* proxy = V8Proxy::retrieve(doc->frame());
if (proxy)
proxy->UpdateDocumentWrapper(result);
if (type == V8ClassIndex::HTMLDOCUMENT) {
// Create marker object and insert it in two internal fields.
// This is used to implement temporary shadowing of
// document.all.
ASSERT(result->InternalFieldCount() ==
V8Custom::kHTMLDocumentInternalFieldCount);
v8::Local<v8::Object> marker = v8::Object::New();
result->SetInternalField(V8Custom::kHTMLDocumentMarkerIndex, marker);
result->SetInternalField(V8Custom::kHTMLDocumentShadowIndex, marker);
}
}
return result;
}
// A JS object of type EventTarget can only be the following possible types:
// 1) EventTargetNode; 2) XMLHttpRequest; 3) MessagePort; 4) SVGElementInstance;
// 5) XMLHttpRequestUpload 6) Worker
// check EventTarget.h for new type conversion methods
v8::Handle<v8::Value> V8Proxy::EventTargetToV8Object(EventTarget* target)
{
if (!target)
return v8::Null();
#if ENABLE(SVG)
SVGElementInstance* instance = target->toSVGElementInstance();
if (instance)
return ToV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
#endif
#if ENABLE(WORKERS)
Worker* worker = target->toWorker();
if (worker)
return ToV8Object(V8ClassIndex::WORKER, worker);
#endif // WORKERS
Node* node = target->toNode();
if (node)
return NodeToV8Object(node);
// XMLHttpRequest is created within its JS counterpart.
XMLHttpRequest* xhr = target->toXMLHttpRequest();
if (xhr) {
v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(xhr);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
// MessagePort is created within its JS counterpart
MessagePort* port = target->toMessagePort();
if (port) {
v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(port);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload();
if (upload) {
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(upload);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
ASSERT(0);
return v8::Handle<v8::Value>();
}
v8::Handle<v8::Value> V8Proxy::EventListenerToV8Object(
EventListener* listener)
{
if (listener == 0) return v8::Null();
// TODO(fqian): can a user take a lazy event listener and set to other places?
V8AbstractEventListener* v8listener =
static_cast<V8AbstractEventListener*>(listener);
return v8listener->getListenerObject();
}
v8::Handle<v8::Value> V8Proxy::DOMImplementationToV8Object(
DOMImplementation* impl)
{
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::DOMIMPLEMENTATION,
V8ClassIndex::DOMIMPLEMENTATION,
impl);
if (result.IsEmpty()) {
// If the instantiation failed, we ignore it and return null instead
// of returning an empty handle.
return v8::Null();
}
return result;
}
v8::Handle<v8::Value> V8Proxy::StyleSheetToV8Object(StyleSheet* sheet)
{
if (!sheet) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(sheet);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::STYLESHEET;
if (sheet->isCSSStyleSheet())
type = V8ClassIndex::CSSSTYLESHEET;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::STYLESHEET, sheet);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
sheet->ref();
SetJSWrapperForDOMObject(sheet, v8::Persistent<v8::Object>::New(result));
}
// Add a hidden reference from stylesheet object to its owner node.
Node* owner_node = sheet->ownerNode();
if (owner_node) {
v8::Handle<v8::Object> owner =
v8::Handle<v8::Object>::Cast(NodeToV8Object(owner_node));
result->SetInternalField(V8Custom::kStyleSheetOwnerNodeIndex, owner);
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSValueToV8Object(CSSValue* value)
{
if (!value) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(value);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
if (value->isWebKitCSSTransformValue())
type = V8ClassIndex::WEBKITCSSTRANSFORMVALUE;
else if (value->isValueList())
type = V8ClassIndex::CSSVALUELIST;
else if (value->isPrimitiveValue())
type = V8ClassIndex::CSSPRIMITIVEVALUE;
#if ENABLE(SVG)
else if (value->isSVGPaint())
type = V8ClassIndex::SVGPAINT;
else if (value->isSVGColor())
type = V8ClassIndex::SVGCOLOR;
#endif
else
type = V8ClassIndex::CSSVALUE;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSVALUE, value);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
value->ref();
SetJSWrapperForDOMObject(value, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSRuleToV8Object(CSSRule* rule)
{
if (!rule) return v8::Null();
v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(rule);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
switch (rule->type()) {
case CSSRule::STYLE_RULE:
type = V8ClassIndex::CSSSTYLERULE;
break;
case CSSRule::CHARSET_RULE:
type = V8ClassIndex::CSSCHARSETRULE;
break;
case CSSRule::IMPORT_RULE:
type = V8ClassIndex::CSSIMPORTRULE;
break;
case CSSRule::MEDIA_RULE:
type = V8ClassIndex::CSSMEDIARULE;
break;
case CSSRule::FONT_FACE_RULE:
type = V8ClassIndex::CSSFONTFACERULE;
break;
case CSSRule::PAGE_RULE:
type = V8ClassIndex::CSSPAGERULE;
break;
case CSSRule::VARIABLES_RULE:
type = V8ClassIndex::CSSVARIABLESRULE;
break;
case CSSRule::WEBKIT_KEYFRAME_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMERULE;
break;
case CSSRule::WEBKIT_KEYFRAMES_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMESRULE;
break;
default: // CSSRule::UNKNOWN_RULE
type = V8ClassIndex::CSSRULE;
break;
}
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSRULE, rule);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
rule->ref();
SetJSWrapperForDOMObject(rule, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::WindowToV8Object(DOMWindow* window)
{
if (!window) return v8::Null();
// Initializes environment of a frame, and return the global object
// of the frame.
Frame* frame = window->frame();
if (!frame)
return v8::Handle<v8::Object>();
// Special case: Because of evaluateInNewContext() one DOMWindow can have
// multipe contexts and multiple global objects associated with it. When
// code running in one of those contexts accesses the window object, we
// want to return the global object associated with that context, not
// necessarily the first global object associated with that DOMWindow.
v8::Handle<v8::Context> current_context = v8::Context::GetCurrent();
v8::Handle<v8::Object> current_global = current_context->Global();
v8::Handle<v8::Object> windowWrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, current_global);
if (!windowWrapper.IsEmpty())
if (DOMWrapperToNative<DOMWindow>(windowWrapper) == window)
return current_global;
// Otherwise, return the global object associated with this frame.
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
return global;
}
void V8Proxy::BindJSObjectToWindow(Frame* frame,
const char* name,
int type,
v8::Handle<v8::FunctionTemplate> desc,
void* imp)
{
// Get environment.
v8::Handle<v8::Context> context = V8Proxy::GetContext(frame);
if (context.IsEmpty())
return; // JS not enabled.
v8::Context::Scope scope(context);
v8::Handle<v8::Object> instance = desc->GetFunction();
SetDOMWrapper(instance, type, imp);
v8::Handle<v8::Object> global = context->Global();
global->Set(v8::String::New(name), instance);
}
void V8Proxy::ProcessConsoleMessages()
{
ConsoleMessageManager::ProcessDelayedMessages();
}
// Create the utility context for holding JavaScript functions used internally
// which are not visible to JavaScript executing on the page.
void V8Proxy::CreateUtilityContext() {
ASSERT(m_utilityContext.IsEmpty());
v8::HandleScope scope;
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
m_utilityContext = v8::Context::New(NULL, global_template);
v8::Context::Scope context_scope(m_utilityContext);
// Compile JavaScript function for retrieving the source line of the top
// JavaScript stack frame.
static const char* frame_source_line_source =
"function frame_source_line(exec_state) {"
" return exec_state.frame(0).sourceLine();"
"}";
v8::Script::Compile(v8::String::New(frame_source_line_source))->Run();
// Compile JavaScript function for retrieving the source name of the top
// JavaScript stack frame.
static const char* frame_source_name_source =
"function frame_source_name(exec_state) {"
" var frame = exec_state.frame(0);"
" if (frame.func().resolved() && "
" frame.func().script() && "
" frame.func().script().name()) {"
" return frame.func().script().name();"
" }"
"}";
v8::Script::Compile(v8::String::New(frame_source_name_source))->Run();
}
int V8Proxy::GetSourceLineNumber() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = V8Proxy::GetUtilityContext();
if (utility_context.IsEmpty()) {
return 0;
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_line;
frame_source_line = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_line")));
if (frame_source_line.IsEmpty()) {
return 0;
}
v8::Handle<v8::Value> result = v8::Debug::Call(frame_source_line);
if (result.IsEmpty()) {
return 0;
}
return result->Int32Value();
}
String V8Proxy::GetSourceName() {
v8::HandleScope scope;
v8::Handle<v8::Context> utility_context = GetUtilityContext();
if (utility_context.IsEmpty()) {
return String();
}
v8::Context::Scope context_scope(utility_context);
v8::Handle<v8::Function> frame_source_name;
frame_source_name = v8::Local<v8::Function>::Cast(
utility_context->Global()->Get(v8::String::New("frame_source_name")));
if (frame_source_name.IsEmpty()) {
return String();
}
return ToWebCoreString(v8::Debug::Call(frame_source_name));
}
void V8Proxy::RegisterExtension(v8::Extension* extension,
const String& schemeRestriction) {
v8::RegisterExtension(extension);
V8ExtensionInfo info = {schemeRestriction, extension};
m_extensions.push_back(info);
}
} // namespace WebCore
|
#include "gtest/gtest.h"
#include "maze.h"
TEST (Direction, ClearDirectionData_AllNorth)
{
location_t loc = {5, 6};
SetDirection (loc, SOUTH);
MazeClearDirectionData();
for (loc.row = 0; loc.row < MAZE_ROWS; loc.row++) {
for (loc.col = 0; loc.col < MAZE_COLS; loc.col++) {
EXPECT_EQ (NORTH, MazeGetDirection (loc));
}
}
}
TEST (Direction, MazeGetDirection_defaultValue_getNORTH)
{
location_t loc = Home();
EXPECT_EQ (NORTH, MazeGetDirection (loc));
}
TEST (Direction, MazeSetDirection_ReturnSetValue)
{
location_t loc = {3, 4};
direction_t dir = EAST;
EXPECT_EQ (NORTH, MazeGetDirection (loc));
SetDirection (loc, dir);
EXPECT_EQ (dir, MazeGetDirection (loc));
}
TEST (Direction, DirectionGetLeftFrom)
{
EXPECT_EQ (WEST, LeftFrom (NORTH));
EXPECT_EQ (SOUTH, LeftFrom (WEST));
EXPECT_EQ (EAST, LeftFrom (SOUTH));
EXPECT_EQ (NORTH, LeftFrom (EAST));
}
TEST (Direction, DirectionGetRightFrom)
{
EXPECT_EQ (EAST, RightFrom (NORTH));
EXPECT_EQ (SOUTH, RightFrom (EAST));
EXPECT_EQ (WEST, RightFrom (SOUTH));
EXPECT_EQ (NORTH, RightFrom (WEST));
}
TEST (Direction, Behind)
{
EXPECT_EQ (SOUTH, Behind (NORTH));
EXPECT_EQ (WEST, Behind (EAST));
EXPECT_EQ (NORTH, Behind (SOUTH));
EXPECT_EQ (EAST, Behind (WEST));
}
updated direction tests to cope with INVALID directions
#include "gtest/gtest.h"
#include "maze.h"
TEST (Direction, ClearDirectionData_AllNorth)
{
location_t loc = {5, 6};
SetDirection (loc, SOUTH);
MazeClearDirectionData();
for (loc.row = 0; loc.row < MAZE_ROWS; loc.row++) {
for (loc.col = 0; loc.col < MAZE_COLS; loc.col++) {
EXPECT_EQ (INVALID, MazeGetDirection (loc));
}
}
}
TEST (Direction, MazeGetDirection_defaultValue_getNORTH)
{
location_t loc = Home();
EXPECT_EQ (INVALID, MazeGetDirection (loc));
}
TEST (Direction, MazeSetDirection_ReturnSetValue)
{
location_t loc = {3, 4};
direction_t dir = EAST;
EXPECT_EQ (INVALID, MazeGetDirection (loc));
SetDirection (loc, dir);
EXPECT_EQ (dir, MazeGetDirection (loc));
}
TEST (Direction, DirectionGetLeftFrom)
{
EXPECT_EQ (WEST, LeftFrom (NORTH));
EXPECT_EQ (SOUTH, LeftFrom (WEST));
EXPECT_EQ (EAST, LeftFrom (SOUTH));
EXPECT_EQ (NORTH, LeftFrom (EAST));
}
TEST (Direction, DirectionGetRightFrom)
{
EXPECT_EQ (EAST, RightFrom (NORTH));
EXPECT_EQ (SOUTH, RightFrom (EAST));
EXPECT_EQ (WEST, RightFrom (SOUTH));
EXPECT_EQ (NORTH, RightFrom (WEST));
}
TEST (Direction, Behind)
{
EXPECT_EQ (SOUTH, Behind (NORTH));
EXPECT_EQ (WEST, Behind (EAST));
EXPECT_EQ (NORTH, Behind (SOUTH));
EXPECT_EQ (EAST, Behind (WEST));
}
|
// Includes
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <list>
#include <utility>
#include <vector>
using namespace std;
// Macros
#define Sc(t,v) static_cast<t>(v)
#define Neg(v) memset((v), -1, sizeof(v))
#define Zero(v) memset((v), 0, sizeof(v))
#define cIter(t,v) t::const_iterator v
#define For(t,v,c) for(t::iterator v=c.begin(); v != c.end(); ++v)
#define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); ++v)
#define crFor(t,v,c) \
for(t::const_reverse_iterator v=c.rbegin(); v != c.rend(); ++v)
// Typedefs
typedef unsigned int u32;
typedef long long i64;
typedef vector<int> IV;
typedef pair<int, int> II;
typedef set<II> IIS;
//
// I/O
//
#define BUF 65536
struct Reader {
char buf[BUF]; char b; int bi, bz;
Reader() { bi=bz=0; read(); }
void read() {
if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); }
b = bz ? buf[bi++] : 0; }
void skip() { while (b > 0 && b <= 32) read(); }
u32 next_u32() {
u32 v = 0; for (skip(); b > 32; read()) v = v*10 + b-48; return v; }
void skip_line() {
for (; b != 10 && b != 13 && b != 0; read());
char p = b; read();
if ((p == 10 && b == 13) || (p == 13 && b == 10)) read(); }
int next_int() {
int v = 0; bool s = false;
skip(); if (b == '-') { s = true; read(); }
for (; b > 32; read()) v = v*10 + b-48; return s ? -v : v; }
bool has_next() { skip(); return b > 0; }
void next(char *s) { for (skip(); b > 32; read()) *s++ = b; *s = 0; }
void next_line(char *s) {
for (; b != 10 && b != 13 && b != 0; read()) *s++ = b; *s = 0;
while (b == 10 || b == 13) read(); }
char next_char() { skip(); char c = b; read(); return c; }
void next_real_line(char *s, int &l) {
for (l = 0; b != 10 && b != 13 && b != 0; read()) *s++ = b, ++l;
*s = 0; char p = b; read();
if ((p == 10 && b == 13) || (p == 13 && b == 10)) read(); }
};
// Union-Find disjoint set
struct Set {
IV s;
Set(int n) { for (int i=0; i <= n; ++i) s.push_back(i); }
int find(int i) { if (s[i] == i) return i; return s[i]=find(s[i]); }
void merge(int i, int j) { s[find(i)] = find(j); }
};
//
// Graphs
//
typedef int w_t;
struct Graph {
struct Edge { int v; w_t w; Edge(int V, w_t W) : v(V), w(W) {} };
typedef list<Edge> EL;
typedef vector<EL> ELV;
ELV adj; int n;
void init(int N) { n=N; adj.clear(); adj.resize(n); }
void add(int u, int v, w_t w) { adj[u].push_back(Edge(v, w)); }
void prim_min(ELV &g, int src) {
IIS q;
IV dis(n, INF);
BV flg(n);
dis[src] = 0;
q.insert(II(0, src));
while (! q.empty()) {
int d = q.begin()->first;
int v = q.begin()->second;
q.erase(q.begin());
if (flg[v]) continue;
flg[v] = true;
cFor (EL, e, g[v])
if (!flg[e->v] && e->w < dis[e->v]) {
if (dis[e->v] != INF) q.erase(II(dis[e->v], e->v));
dis[e->v] = e->w;
q.insert(II(dis[e->v], e->v));
}
}
}
void dijkstra(int src, IV &dis) {
IIS q;
dis = IV(n, INF);
BV flg(n);
dis[src] = 0;
q.insert(II(0, src));
while (! q.empty()) {
int v = q.begin()->second;
q.erase(q.begin());
if (flg[v]) continue;
flg[v] = true;
cFor (EL, e, adj[v]) {
int d = dis[v] + e->w;
if (!flg[e->v] && d < dis[e->v]) {
if (dis[e->v] != INF) q.erase(II(dis[e->v], e->v));
dis[e->v] = d;
q.insert(II(dis[e->v], e->v));
}
}
}
}
void topo_sort(IV &in, IV &order) {
IQ q;
for (int i = 0; i < n; ++i) if (in[i] == 0) q.push(i);
order.clear();
while (! q.empty()) {
int v = q.front(); q.pop();
order.push_back(v);
cFor (EL, e, adj[v])
if (--in[e->v] == 0) q.push(e->v);
}
}
// Kosaraju's algorithm
struct Kos {
IVV sccs; IV scc; IK vs; BV vis; ELV radj;
Kos(int n) { vis = BV(n); radj.resize(n); }
};
void kosaraju_scc(IVV &sccs) {
Kos k(n);
for (int v=0; v<n; ++v) if (! k.vis[v]) kosaraju_dfs(v, k);
k.vis = BV(n);
while (! k.vs.empty()) {
int v = k.vs.top(); k.vs.pop();
if (k.vis[v]) continue;
k.scc = IV();
kosaraju_dfs2(v, k);
k.sccs.push_back(k.scc);
}
sccs = k.sccs;
}
void kosaraju_dfs(int v, Kos &k) {
k.vis[v] = true;
cFor (EL, ep, adj[v]) {
Edge e = *ep;
int u = e.v; e.v = v;
k.radj[u].push_back(e);
if (! k.vis[u]) kosaraju_dfs(u, k);
}
k.vs.push(v);
}
void kosaraju_dfs2(int v, Kos &k) {
k.vis[v] = true;
k.scc.push_back(v);
cFor (EL, e, k.radj[v])
if (! k.vis[e->v]) kosaraju_dfs2(e->v, k);
}
// Tarjan
struct Tarjan {
IVV sccs; IS s; BV flg; IV low, idx; int cnt;
Tarjan(int n) {
flg = BV(n);
low = IV(n);
idx = IV(n);
cnt = 1;
}
};
void tarjan_scc(IVV &sccs) {
Tarjan t(n);
for (int i = 0; i < n; ++i)
if (t.low[i] == 0) tarjan_visit(i, t);
sccs = t.sccs;
}
void tarjan_visit(int v, Tarjan &t) {
t.idx[v] = t.low[v] = t.cnt++;
t.s.push(v); t.flg[v] = true;
cFor (EL, e, adj[v]) {
if (t.low[e->v] == 0) {
tarjan_visit(e->v, t);
t.low[v] = min(t.low[v], t.low[e->v]);
}
else if (t.flg[e->v])
t.low[v] = min(t.low[v], t.idx[e->v]);
}
if (t.low[v] != t.idx[v]) return;
IV scc;
for (int u=-1; u != v;) {
u=t.s.top(); t.s.pop();
t.flg[u]=false;
scc.push_back(u);
}
t.sccs.push_back(scc);
}
void scc_to_dag(const IVV &sccs, Graph &dag) {
int ndag = sccs.size();
IV vcomp(n);
for (int i=0; i < ndag; ++i)
for (int j=0, lim=sccs[i].size(); j < lim; ++j)
vcomp[sccs[i][j]] = i;
dag.init(ndag);
for (int u=0; u < n; u++)
cFor (EL, e, adj[u])
if (vcomp[u] != vcomp[e->v])
dag.add(vcomp[u], vcomp[e->v], 0);
}
// Hopcroft-Karp for bipartite matching. Receives the vertices in G1,
// and depends on vertex #0 being reserved as the NIL vertex
struct HK {
IV pair_g1, pair_g2, dist;
Graph &g;
IV &g1;
HK(Graph &G, IV &G1) : g(G), g1(G1) {
pair_g1 = IV(g.n); pair_g2 = IV(g.n); dist = IV(g.n); }
bool bfs() {
IQ q;
cFor (IV, v, g1) {
if (pair_g1[*v] == 0) {
dist[*v] = 0;
q.push(*v);
}
else
dist[*v] = INF;
}
dist[0] = INF;
while (! q.empty()) {
int v = q.front(); q.pop();
cFor (EL, e, g.adj[v]) {
int p = pair_g2[e->v];
if (dist[p] != INF) continue;
dist[p] = dist[v] + 1;
q.push(p);
}
}
return dist[0] != INF;
}
bool dfs(int v) {
if (v == 0) return true;
cFor (EL, e, g.adj[v]) {
int p = pair_g2[e->v];
if (dist[p] == dist[v] + 1 && dfs(p)) {
pair_g2[e->v] = v;
pair_g1[v] = e->v;
return true;
}
}
dist[v] = INF;
return false;
}
};
int hopcroft(IV &g1) {
HK hk(*this, g1);
int m = 0;
while (hk.bfs())
cFor (IV, v, g1)
if (hk.pair_g1[*v] == 0 && hk.dfs(*v))
++m;
return m;
}
// Articulations/bridges
struct Artic {
IV low, idx;
BV is_art;
IIV bridges;
int cnt;
Graph &g;
Artic(Graph &G) : g(G) {
low = IV(g.n);
idx = IV(g.n);
is_art = BV(g.n);
cnt = 1;
}
void dfs(int u, int v) {
int children = 0;
low[v] = idx[v] = cnt++;
cFor(EL, e, g.adj[v]) {
if (idx[e->v] == 0) {
++children;
dfs(v, e->v);
low[v] = min(low[v], low[e->v]);
if (low[e->v] >= idx[v] && u != v)
is_art[v] = true;
if (low[e->v] == idx[e->v])
bridges.push_back(II(v, e->v));
}
else if (e->v != u)
low[v] = min(low[v], idx[e->v]);
}
if (u == v && children > 1)
is_art[v] = true;
}
};
void articulations(IIV &bridges) {
Artic a(*this);
for (int i = 0; i < n; ++i)
if (a.idx[i] == 0) a.dfs(i, i);
bridges = a.bridges;
}
};
struct Graph {
struct Edge {
int u, v, w;
Edge(int U, int V, int W) : u(U), v(V), w(W) {}
bool operator<(const Edge &e) const { return w < e.w; }
};
typedef vector<Edge> EV;
EV edges;
void init(size_t m=16) { edges.clear(); edges.reserve(m); }
void add(int u, int v, int w) { edges.push_back(Edge(u, v, w)); }
// Minimum Spanning Tree
void kruskalMST(int n, int &ans) {
sort(edges.begin(), edges.end());
Set uf; uf.init(n);
int nedges = 0;
ans = 0;
EV mst;
cFor (EV, e, edges) {
if (uf.find(e->u) == uf.find(e->v)) continue;
mst.push_back(*e);
uf.merge(e->u, e->v);
ans += e->w;
if (++nedges == n - 1) break;
}
if (nedges < n - 1) ans = -1;
else edges = mst;
}
// Bellman-Ford
bool bellman_ford_neg_cycle(int n) {
IV dis(n);
for (int i = 0; i < n-1; i++)
cFor (EV, e, edges)
if(dis[e->u] + e->w < dis[e->v])
dis[e->v] = dis[e->u] + e->w;
cFor (EV, e, edges)
if (dis[e->u] + e->w < dis[e->v])
return true;
return false;
}
};
struct Graph {
// Shortest paths
void floyd(int **g, int N)
{
for (int k = 0; k < N; k++)
for(int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
int t = g[i][k] + g[k][j];
if (t < g[i][j]) g[i][j] = t;
}
}
};
//
// 2-SAT
//
struct TwoSat {
Graph g;
int n;
TwoSat(int N) : n(N) { g.init(2*N); }
void add_cons(int a, bool ta, int b, bool tb) {
int p = val(a, ta), q = val(b, tb);
g.add(neg(p), q); g.add(neg(q), p);
}
int val(int v, bool t) { return 2*v + (t ? 0 : 1); }
int neg(int p) { return p ^ 1; }
bool solve(IV &sol) {
IVV sccs;
g.kosaraju_scc(sccs);
IV vscc(n);
sol.clear();
for (int i = 0, I = sccs.size(); i < I; ++i) {
for (int j=0, J=sccs[i].size(); j < J; ++j) {
int p = sccs[i][j];
int v = p/2;
if (vscc[v] == i+1) return false;
if (vscc[v] != 0) break;
vscc[v] = i+1;
if (p & 1) sol.push_back(v);
}
}
return true;
}
};
//
// Number Theory
//
#define IsComp(n) (_c[n>>6]&(1<<((n>>1)&31)))
#define SetComp(n) _c[n>>6]|=(1<<((n>>1)&31))
namespace Num
{
const int MAX = 1000000; // 10^6
const int LMT = 1000; // sqrt(MAX)
int _c[(MAX>>6)+1];
IV primes;
void prime_sieve() {
for (int i = 3; i <= LMT; i += 2)
if (!IsComp(i)) for (int j = i*i; j <= MAX; j+=i+i) SetComp(j);
primes.push_back(2);
for (int i=3; i <= MAX; i+=2) if (!IsComp(i)) primes.push_back(i);
}
bool is_prime(int n) {
if (n < 2 || n % 2 == 0) return false;
return ! IsComp(n);
}
// Finds prime numbers between a and b, using basic primes up to sqrt(b)
void prime_seg_sieve(i64 a, i64 b, IV &seg_primes) {
BV pmap(b - a + 1, true);
i64 sqr_b = sqrt(b);
cFor (IV, pp, primes) {
int p = *pp;
if (p > sqr_b) break;
for (i64 j = (a+p-1)/p, v=(j==1?p+p:j*p); v <= b; v += p)
pmap[v-a] = false;
}
seg_primes.clear();
if (a == 1) pmap[0] = false;
for (int i = a%2 ? 0 : 1, I = b - a + 1; i < I; i += 2)
if (pmap[i])
seg_primes.push_back(a + i);
}
void prime_factorize(int n, IIV &f) {
int sn = sqrt(n);
cFor (IV, p, primes) {
int prime = *p;
if (prime > sn) break; if (n % prime) continue;
int e = 0; for (; n % prime == 0; e++, n /= prime);
f.push_back(II(prime, e));
sn = sqrt(n);
}
if (n > 1) f.push_back(II(n, 1));
}
void divisors(int n, IV &ds)
{
ds.clear();
ds.push_back(1);
int sn = sqrt(n);
cFor(IV, pp, primes) {
int p = *pp;
if (p > sn) break;
if (n % p != 0) continue;
IV aux(ds.begin(), ds.end());
int q = 1;
while (n % p == 0) {
q *= p; n /= p;
cFor(IV, v, ds) aux.push_back(*v * q);
}
sn = sqrt(n); ds = aux;
}
if (n > 1) {
IV aux(ds.begin(), ds.end());
cFor(IV, v, ds) aux.push_back(*v * n);
ds = aux;
}
}
void euler_phi(int a[], int N) {
for (int i = 1; i <= N; i++) a[i] = i;
for (int i = 2; i <= N; i += 2) a[i] = i/2;
for (int i = 3; i <= N; i += 2)
if (a[i] == i) {
a[i]--; for (int j = i+i; j <= N; j += i) a[j] -= a[j]/i;
}
}
int mod_pow(int _b, i64 e, int m) {
i64 res = 1;
for (i64 b=_b; e; e >>= 1, b = b*b%m) if (e & 1) res = res*b%m;
return res;
}
int ipow(int b, int e) {
int res = 1; for (; e; e >>= 1, b *= b) if (e & 1) res *= b;
return res;
}
int gcd(int a, int b) { for (int c = a%b; c; a=b,b=c,c=a%b); return b; }
void ext_euclid(int a, int b, int &x, int &y, int &gcd) {
x = 0; y = 1; gcd = b;
int m, n, q, r;
for (int u=1, v=0; a != 0; gcd=a, a=r) {
q = gcd / a; r = gcd % a;
m = x-u*q; n = y-v*q;
x=u; y=v; u=m; v=n;
}
}
int mod_inv(int n, int m) {
int x, y, gcd;
ext_euclid(n, m, x, y, gcd);
if (gcd == 1) return x % m;
return 0;
}
// Calculates the highest exponent of prime p that divides n!
int pow_div_fact(int n, int p) {
int sd = 0; for (int N=n; N; N /= p) sd += N % p; return (n-sd)/(p-1);
}
// Binomial coefficients
#define BCSIZE 1000
int bc[BCSIZE + 1][BCSIZE + 1];
void choose_table() {
for (int n = 1; n <= BCSIZE; n++) { bc[n][n] = 1; bc[n][1] = n; }
for (int n = 3; n <= BCSIZE; n++)
for (int k = 2; k < n; k++)
bc[n][k] = (bc[n-1][k-1] + bc[n-1][k]) % MOD;
}
int choose(int n, int k) {
if (k > n) return 0;
i64 r=1;
for (int d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
}
//
// Big Integer
//
#define BIBAS 1000
#define BIDIG 3
#define BIFMT "%03d"
struct Bigint {
IV d; bool sgn;
Bigint(i64 n=0) {
if (n < 0) sgn = true, n = -n; else sgn = false;
if (n < BIBAS) d.push_back(n);
else while (n != 0) { d.push_back(n % BIBAS); n /= BIBAS; }
}
Bigint(const char *s) {
if (*s == '-') sgn = true, s++; else sgn = false;
for (int end = strlen(s), i = max(0, end-BIDIG); true;) {
int n = 0; for (int j=i; j != end; j++) n = n*10 + s[j] - '0';
d.push_back(n); if (i == 0) break;
end = i, i = max(0, i-BIDIG);
} clean();
}
size_t len() const { return d.size(); }
bool is_zero() const { return len() == 1 && d[0] == 0; }
void flip() { sgn = !sgn; }
Bigint neg() const { Bigint x = *this; x.flip(); return x; }
bool operator==(const Bigint &b) const {
return sgn == b.sgn && d == b.d;
}
bool operator<(const Bigint &b) const {
if (sgn != b.sgn) return sgn;
if (len() != b.len()) return sgn ^ (len() < b.len());
for (int i = len() - 1; i >= 0; --i)
if (d[i] != b.d[i]) return sgn ^ (d[i] < b.d[i]);
return false;
}
Bigint &operator+=(const Bigint &b) {
if (sgn != b.sgn) { (*this) -= b.neg(); return *this; }
int s1 = len(), s2 = b.len(), s3 = max(s1, s2) + 1;
IV res(s3); int c = 0;
for (int i = 0; i < s3; ++i) {
int sum = c;
sum += i < s1 ? d[i] : 0;
sum += i < s2 ? b.d[i] : 0;
if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0;
res[i] = sum;
}
d = res; clean();
return *this;
}
Bigint &operator-=(const Bigint &b) {
if (sgn != b.sgn) { (*this) += b.neg(); return *this; }
if (*this < b) { Bigint x = b; x -= *this; return *this = x.neg(); }
int s1 = len(), s2 = b.len(), s3 = s1;
IV res(s3); int c = 0;
for (int i = 0; i < s3; ++i) {
int sum = d[i] - (i < s2 ? b.d[i] : 0) - c;
if (sum < 0) { sum += BIBAS; c = 1; } else c = 0;
res[i] = sum;
}
d = res; clean();
return *this;
}
Bigint &operator*=(const Bigint &b) {
int s1 = len(), s2 = b.len(), s3 = s1+s2;
IV res(s3); int c = 0;
for (int k=0; k < s3; ++k) {
int sum = c;
for (int i=max(0,k-s2+1), I=min(k+1, s1), j=k-i; i < I; ++i, --j)
sum += d[i] * b.d[j];
if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0;
res[k] = sum;
}
d = res; sgn ^= b.sgn; clean();
return *this;
}
Bigint &short_div(int b) {
for (int r = 0, i = len() - 1; i >= 0; --i)
r = r*BIBAS + d[i], d[i] = r / b, r %= b;
clean(); return *this;
}
Bigint &operator/=(const Bigint &b) {
if (b.is_zero()) { int x=0; return *this=Bigint(x/x); }
sgn ^= b.sgn; size_t l = len(), n = b.len();
if (n == 1) return short_div(b.d[0]);
if (l < n || (l == n && d.back() < b.d.back()))
return *this = Bigint(0);
Bigint r(0); IV res(l);
for (int i = l - 1; i >= 0; --i) {
r.d.insert(r.d.begin(), d[i]); r.clean();
int x = r.len() >= n ? r.d[n-1] : 0;
if (r.len() > n) x += BIBAS * r.d[n];
int q = x / b.d[n-1];
Bigint g = b; g *= Bigint(q);
while (r < g) g -= b, --q;
res[i] = q, r -= g;
}
d = res; clean(); return *this;
}
Bigint pow(int e) {
if (e == 0) return Bigint(1);
if (e == 1) return *this;
if (e % 2 == 0) {
Bigint tmp = this->pow(e/2);
tmp *= tmp;
return tmp;
}
Bigint tmp = this->pow(e-1);
tmp *= *this;
return tmp;
}
void clean() {
IVi i; for (i=d.end()-1; *i == 0 && i != d.begin(); i--);
d.erase(i+1, d.end());
if (sgn && d.size() == 1 && d[0] == 0) sgn = false;
}
void println() {
if (sgn) putchar('-');
bool flg = true;
crFor (IV, i, d) {
if (flg) { printf("%d", *i); flg=false; }
else printf(BIFMT, *i);
} putchar('\n');
}
int to_int() {
int res = 0, p = 1;
for (int i=0, I=len(); i < I; i++) { res += d[i] * p; p *= BIBAS; }
return sgn ? -res : res;
}
string to_string() {
char buf[BIDIG+1]; string str;
if (sgn) str.push_back('-');
bool flg = true;
crFor (IV, i, d) {
if (flg) { sprintf(buf, "%d", *i); flg=false; }
else sprintf(buf, BIFMT, *i);
str.append(buf);
}
return str;
}
};
//
// Fraction
//
struct Fraction {
int p, q;
Fraction(int P, int Q) : p(P), q(Q) { simplify(); }
Fraction(int P) : p(P), q(1) {}
void simplify() {
int g = gcd(p, q);
p /= g;
q /= g;
}
Fraction operator+(const Fraction &f) const {
return Fraction(p * f.q + q * f.p, q * f.q);
}
Fraction operator-(const Fraction &f) const {
return Fraction(p * f.q - q * f.p, q * f.q);
}
Fraction operator*(const Fraction &f) const {
return Fraction(p * f.p, q * f.q);
}
Fraction operator/(const Fraction &f) const {
return Fraction(p * f.q, q * f.p);
}
Fraction operator%(int m) const {
return Fraction(p % (m*q), q);
}
};
//
// Matrix Exponentiation
//
typedef u32 t_m;
#define MAXR (MAXK + 2)
#define MAXC (MAXK + 2)
struct Matrix {
int r, c;
t_m m[MAXR][MAXC];
void init(int R, int C) { Zero(m); r=R; c=C; }
void print() {
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j)
printf("%4d ", m[i][j]);
printf("\n");
}
}
};
void matrix_mul(const Matrix &a, const Matrix &b, Matrix &c)
{
c.r = a.r, c.c = b.c;
t_m x;
for (int i = 0; i < c.r; ++i)
for (int j = 0; j < c.c; ++j) {
x = 0;
for (int k = 0; k < a.c; ++k)
x += a.m[i][k] * b.m[k][j];
c.m[i][j] = x;
}
}
void matrix_exp(const Matrix &m, u64 e, Matrix &r)
{
if (e == 1) { r = m; return; }
Matrix x;
if (e % 2 == 0) {
matrix_exp(m, e / 2, x);
matrix_mul(x, x, r);
return;
}
matrix_exp(m, e-1, x);
matrix_mul(x, m, r);
}
//
// Geometry
//
double circle_angle(double a) { return a >= 0 ? a : Pi2 + a; }
bool eps_less(double a, double b) { return b - a > EPS; }
bool eps_equal(double a, double b) { return fabs(a - b) < EPS; }
typedef double p_t;
struct Point {
p_t x, y;
Point() { x=y=0; }
Point(p_t X, p_t Y) : x(X), y(Y) {}
p_t distance(Point p) {
p_t dx = p.x - x, dy = p.y - y; return sqrt(dx*dx + dy*dy);
}
bool operator<(const Point &p) const {
return x < p.x || (x == p.x && y < p.y);
}
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
bool collinear(const Point &b, const Point &c) const {
return (b.y - y) * (c.x - x) == (c.y - y) * (b.x - x);
}
};
struct Vector {
double x, y;
Vector(double X, p_t Y) : x(X), y(Y) {}
Vector(const Point &p) : x(p.x), y(p.y) {}
double norm() { return sqrt(x*x + y*y); }
double angle(const Vector &p) const {
return circle_angle(atan2(p.y, p.x) - atan2(y, x));
}
void rotate(double a) {
double px = x, py = y;
x = px*cos(a) - py*sin(a);
y = px*sin(a) + py*cos(a);
}
double distance_line_point(Point a, Point p) {
return fabs((p.x-a.x)*y - (p.y-a.y)*x) / sqrt(x*x + y*y);
}
};
typedef vector<Point> PV;
struct Circle {
double x, y, r;
Circle() {}
Circle(double X, double Y, double R) : x(X), y(Y), r(R) {}
bool perimeters_touch(const Circle &c) const {
double dx = x - c.x;
double dy = y - c.y;
double dist = sqrt(dx*dx + dy*dy);
return ! (eps_less(r + c.r, dist) ||
eps_less(dist, fabs(r - c.r)));
}
};
p_t cross(const Point &o, const Point &a, const Point &b) {
return (a.x-o.x)*(b.y-o.y) - (a.y-o.y)*(b.x-o.x);
}
void convex_hull(PV &p, PV &h) {
// Post-cond: p.size() > 1 => h.front() == h.back()
int n = p.size(), k = 0;
h.resize(2*n);
sort(p.begin(), p.end());
for (int i = 0; i < n; ++i) {
while (k >= 2 && cross(h[k-2], h[k-1], p[i]) <= 0) k--;
h[k++] = p[i];
}
for (int i = n-2, t=k+1; i >= 0; --i) {
while (k >= t && cross(h[k-2], h[k-1], p[i]) <= 0) k--;
h[k++] = p[i];
}
h.resize(k);
}
// Finds the circle formed by three points
void find_circle(Point &p1, Point &p2, Point &p3, Point &c, double &r)
{
Point m, a, b;
if (! eps_equal(p1.x, p2.x) && ! eps_equal(p1.x, p3.x))
m = p1, a = p2, b = p3;
else if (! eps_equal(p2.x, p1.x) && ! eps_equal(p2.x, p3.x))
m = p2, a = p1, b = p3;
else
m = p3, a = p1, b = p2;
double ma = (m.y - a.y) / (m.x - a.x);
double mb = (b.y - m.y) / (b.x - m.x);
c.x = ma*mb*(a.y - b.y) + mb*(a.x + m.x) - ma*(m.x + b.x);
c.x /= (mb - ma)*2.0;
if (eps_equal(0.0, ma))
c.y = (m.y + b.y) / 2.0 - (c.x - (m.x + b.x)/2.0) / mb;
else
c.y = (a.y + m.y) / 2.0 - (c.x - (a.x + m.x)/2.0) / ma;
r = c.distance(p1);
}
//
// Trie
//
struct Trie {
struct Node {
int ch[26];
int n;
Node() { n=0; Zero(ch); }
};
int sz;
vector<Node> nodes;
void init() { nodes.clear(); nodes.resize(1); sz = 1; }
void insert(const char *s) {
int idx, cur = 0;
for (; *s; ++s) {
idx = *s - 'A';
if (! nodes[cur].ch[idx]) {
nodes[cur].ch[idx] = sz++;
nodes.resize(sz);
}
cur = nodes[cur].ch[idx];
}
}
};
//
// Hash Map
//
#define HASHB 4096
struct HM {
typedef IV Datum; typedef vector<Datum> DV; DV b[HASHB];
u32 fnv_hash(const Datum &k, int len) const {
uch *p = reinterpret_cast<uch*>(const_cast<int*>(&k[0]));
u32 h = 2166136261U;
for (int i = 0; i < len; ++i) h = (h * 16777619U ) ^ p[i];
return h;
}
bool add(const Datum &k, u64 &id) {
int i = fnv_hash(k, k.size() * sizeof(int)) % HASHB;
for (int j = 0, J = b[i].size(); j < J; ++j)
if (b[i][j] == k) { id = i; id <<= 32; id |= j; return false; }
b[i].push_back(k);
id = i; id <<= 32; id |= (b[i].size() - 1);
return true;
}
Datum get(u64 id) const { return b[id>>32][id&0xFFFFFFFF]; }
};
//
// Time - Leap years
//
// A[i] has the accumulated number of days from months previous to i
const int A[13] = { 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
// same as A, but for a leap year
const int B[13] = { 0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
// returns number of leap years up to, and including, y
int leap_years(int y) { return y / 4 - y / 100 + y / 400; }
bool is_leap(int y) { return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0); }
// number of days in blocks of years
const int p400 = 400*365 + leap_years(400);
const int p100 = 100*365 + leap_years(100);
const int p4 = 4*365 + 1;
const int p1 = 365;
int date_to_days(int d, int m, int y)
{
return (y - 1) * 365 + leap_years(y - 1) + (is_leap(y) ? B[m] : A[m]) + d;
}
void days_to_date(int days, int &d, int &m, int &y)
{
bool top100; // are we in the top 100 years of a 400 block?
bool top4; // are we in the top 4 years of a 100 block?
bool top1; // are we in the top year of a 4 block?
y = 1;
top100 = top4 = top1 = false;
y += ((days-1) / p400) * 400;
d = (days-1) % p400 + 1;
if (d > p100*3) top100 = true, d -= 3*p100, y += 300;
else y += ((d-1) / p100) * 100, d = (d-1) % p100 + 1;
if (d > p4*24) top4 = true, d -= 24*p4, y += 24*4;
else y += ((d-1) / p4) * 4, d = (d-1) % p4 + 1;
if (d > p1*3) top1 = true, d -= p1*3, y += 3;
else y += (d-1) / p1, d = (d-1) % p1 + 1;
const int *ac = top1 && (!top4 || top100) ? B : A;
for (m = 1; m < 12; ++m) if (d <= ac[m + 1]) break;
d -= ac[m];
}
//
// Quickselect - for locating the median
//
struct Data {
int v; // value
int n; // occurrences
int p; // original position of data, to break ties
Data(int V, int N, int P) : v(V), n(N), p(P) {}
bool operator<(const Data &x) const {
if (v != x.v) return v < x.v;
if (n != x.n) return n < x.n;
return p < x.p;
}
};
typedef vector<Data> DV;
typedef DV::iterator DVi;
int select_kth(DVi lo, DVi hi, int k)
{
if (hi == lo + 1) return lo->v;
swap(*(lo + (rand() % (hi - lo))), *(hi - 1));
Data piv = *(hi - 1);
DVi x = lo;
int lt = 0;
for (DVi i = lo, I = hi - 1; i != I; ++i)
if (*i < piv) { swap(*i, *x); lt += x->n, ++x; }
swap(*x, *(hi - 1));
if (k < lt) return select_kth(lo, x, k);
if (k >= lt + x->n) return select_kth(x + 1, hi, k - lt - x->n);
return x->v;
}
//
// Merge sort - useful for adapting it to sorting-related problems
//
void merge(IVi lo, IVi hi, IVi mid)
{
IV x;
for (IVi a = lo, b = mid; a < mid || b < hi; ) {
if (a >= mid) { x.push_back(*b++); continue; }
if (b >= hi) { x.push_back(*a++); continue; }
if (*a < *b) { x.push_back(*a++); continue; }
x.push_back(*b++);
}
for (IVi a = lo, b = x.begin(); a < hi; ++a, ++b) *a = *b;
}
void merge_sort(IVi lo, IVi hi)
{
if (hi <= lo + 1) return;
IVi mid = lo + ((hi - lo) / 2);
merge_sort(lo, mid); merge_sort(mid, hi); merge(lo, hi, mid);
}
//
// Misc functions
//
// next higher number with same number of 1's in binary
u32 next_popcount(u32 n)
{
u32 c = (n & -n);
u32 r = n+c;
return (((r ^ n) >> 2) / c) | r;
}
// Returns first integer with exactly n bits set
u32 init_popcount(int n) { return (1 << n) - 1; }
#define Back(b) ((b) & -(b))
#define PopBack(b) (b &= ~Back(b))
// Finds the most significant bit set on n. The bit is left in b, and its
// zero-indexed position in p
void msb(i64 n, i64 &b, int &p)
{
for (b = 1, p = 0, n >>= 1; n; b <<= 1, n >>= 1, ++p);
}
// returns the position of the last visited in range [0, n-1]
int josephus(int n, int k)
{
if (n == 1) return 0;
return (josephus(n-1, k) + k) % n;
}
Increased buffer size for Input
// Includes
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <list>
#include <utility>
#include <vector>
using namespace std;
// Macros
#define Sc(t,v) static_cast<t>(v)
#define Neg(v) memset((v), -1, sizeof(v))
#define Zero(v) memset((v), 0, sizeof(v))
#define cIter(t,v) t::const_iterator v
#define For(t,v,c) for(t::iterator v=c.begin(); v != c.end(); ++v)
#define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); ++v)
#define crFor(t,v,c) \
for(t::const_reverse_iterator v=c.rbegin(); v != c.rend(); ++v)
// Typedefs
typedef unsigned int u32;
typedef long long i64;
typedef vector<int> IV;
typedef pair<int, int> II;
typedef set<II> IIS;
//
// I/O
//
#define BUF 524288
struct Reader {
char buf[BUF]; char b; int bi, bz;
Reader() { bi=bz=0; read(); }
void read() {
if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); }
b = bz ? buf[bi++] : 0; }
void skip() { while (b > 0 && b <= 32) read(); }
u32 next_u32() {
u32 v = 0; for (skip(); b > 32; read()) v = v*10 + b-48; return v; }
void skip_line() {
for (; b != 10 && b != 13 && b != 0; read());
char p = b; read();
if ((p == 10 && b == 13) || (p == 13 && b == 10)) read(); }
int next_int() {
int v = 0; bool s = false;
skip(); if (b == '-') { s = true; read(); }
for (; b > 32; read()) v = v*10 + b-48; return s ? -v : v; }
bool has_next() { skip(); return b > 0; }
void next(char *s) { for (skip(); b > 32; read()) *s++ = b; *s = 0; }
void next_line(char *s) {
for (; b != 10 && b != 13 && b != 0; read()) *s++ = b; *s = 0;
while (b == 10 || b == 13) read(); }
char next_char() { skip(); char c = b; read(); return c; }
void next_real_line(char *s, int &l) {
for (l = 0; b != 10 && b != 13 && b != 0; read()) *s++ = b, ++l;
*s = 0; char p = b; read();
if ((p == 10 && b == 13) || (p == 13 && b == 10)) read(); }
};
// Union-Find disjoint set
struct Set {
IV s;
Set(int n) { for (int i=0; i <= n; ++i) s.push_back(i); }
int find(int i) { if (s[i] == i) return i; return s[i]=find(s[i]); }
void merge(int i, int j) { s[find(i)] = find(j); }
};
//
// Graphs
//
typedef int w_t;
struct Graph {
struct Edge { int v; w_t w; Edge(int V, w_t W) : v(V), w(W) {} };
typedef list<Edge> EL;
typedef vector<EL> ELV;
ELV adj; int n;
void init(int N) { n=N; adj.clear(); adj.resize(n); }
void add(int u, int v, w_t w) { adj[u].push_back(Edge(v, w)); }
void prim_min(ELV &g, int src) {
IIS q;
IV dis(n, INF);
BV flg(n);
dis[src] = 0;
q.insert(II(0, src));
while (! q.empty()) {
int d = q.begin()->first;
int v = q.begin()->second;
q.erase(q.begin());
if (flg[v]) continue;
flg[v] = true;
cFor (EL, e, g[v])
if (!flg[e->v] && e->w < dis[e->v]) {
if (dis[e->v] != INF) q.erase(II(dis[e->v], e->v));
dis[e->v] = e->w;
q.insert(II(dis[e->v], e->v));
}
}
}
void dijkstra(int src, IV &dis) {
IIS q;
dis = IV(n, INF);
BV flg(n);
dis[src] = 0;
q.insert(II(0, src));
while (! q.empty()) {
int v = q.begin()->second;
q.erase(q.begin());
if (flg[v]) continue;
flg[v] = true;
cFor (EL, e, adj[v]) {
int d = dis[v] + e->w;
if (!flg[e->v] && d < dis[e->v]) {
if (dis[e->v] != INF) q.erase(II(dis[e->v], e->v));
dis[e->v] = d;
q.insert(II(dis[e->v], e->v));
}
}
}
}
void topo_sort(IV &in, IV &order) {
IQ q;
for (int i = 0; i < n; ++i) if (in[i] == 0) q.push(i);
order.clear();
while (! q.empty()) {
int v = q.front(); q.pop();
order.push_back(v);
cFor (EL, e, adj[v])
if (--in[e->v] == 0) q.push(e->v);
}
}
// Kosaraju's algorithm
struct Kos {
IVV sccs; IV scc; IK vs; BV vis; ELV radj;
Kos(int n) { vis = BV(n); radj.resize(n); }
};
void kosaraju_scc(IVV &sccs) {
Kos k(n);
for (int v=0; v<n; ++v) if (! k.vis[v]) kosaraju_dfs(v, k);
k.vis = BV(n);
while (! k.vs.empty()) {
int v = k.vs.top(); k.vs.pop();
if (k.vis[v]) continue;
k.scc = IV();
kosaraju_dfs2(v, k);
k.sccs.push_back(k.scc);
}
sccs = k.sccs;
}
void kosaraju_dfs(int v, Kos &k) {
k.vis[v] = true;
cFor (EL, ep, adj[v]) {
Edge e = *ep;
int u = e.v; e.v = v;
k.radj[u].push_back(e);
if (! k.vis[u]) kosaraju_dfs(u, k);
}
k.vs.push(v);
}
void kosaraju_dfs2(int v, Kos &k) {
k.vis[v] = true;
k.scc.push_back(v);
cFor (EL, e, k.radj[v])
if (! k.vis[e->v]) kosaraju_dfs2(e->v, k);
}
// Tarjan
struct Tarjan {
IVV sccs; IS s; BV flg; IV low, idx; int cnt;
Tarjan(int n) {
flg = BV(n);
low = IV(n);
idx = IV(n);
cnt = 1;
}
};
void tarjan_scc(IVV &sccs) {
Tarjan t(n);
for (int i = 0; i < n; ++i)
if (t.low[i] == 0) tarjan_visit(i, t);
sccs = t.sccs;
}
void tarjan_visit(int v, Tarjan &t) {
t.idx[v] = t.low[v] = t.cnt++;
t.s.push(v); t.flg[v] = true;
cFor (EL, e, adj[v]) {
if (t.low[e->v] == 0) {
tarjan_visit(e->v, t);
t.low[v] = min(t.low[v], t.low[e->v]);
}
else if (t.flg[e->v])
t.low[v] = min(t.low[v], t.idx[e->v]);
}
if (t.low[v] != t.idx[v]) return;
IV scc;
for (int u=-1; u != v;) {
u=t.s.top(); t.s.pop();
t.flg[u]=false;
scc.push_back(u);
}
t.sccs.push_back(scc);
}
void scc_to_dag(const IVV &sccs, Graph &dag) {
int ndag = sccs.size();
IV vcomp(n);
for (int i=0; i < ndag; ++i)
for (int j=0, lim=sccs[i].size(); j < lim; ++j)
vcomp[sccs[i][j]] = i;
dag.init(ndag);
for (int u=0; u < n; u++)
cFor (EL, e, adj[u])
if (vcomp[u] != vcomp[e->v])
dag.add(vcomp[u], vcomp[e->v], 0);
}
// Hopcroft-Karp for bipartite matching. Receives the vertices in G1,
// and depends on vertex #0 being reserved as the NIL vertex
struct HK {
IV pair_g1, pair_g2, dist;
Graph &g;
IV &g1;
HK(Graph &G, IV &G1) : g(G), g1(G1) {
pair_g1 = IV(g.n); pair_g2 = IV(g.n); dist = IV(g.n); }
bool bfs() {
IQ q;
cFor (IV, v, g1) {
if (pair_g1[*v] == 0) {
dist[*v] = 0;
q.push(*v);
}
else
dist[*v] = INF;
}
dist[0] = INF;
while (! q.empty()) {
int v = q.front(); q.pop();
cFor (EL, e, g.adj[v]) {
int p = pair_g2[e->v];
if (dist[p] != INF) continue;
dist[p] = dist[v] + 1;
q.push(p);
}
}
return dist[0] != INF;
}
bool dfs(int v) {
if (v == 0) return true;
cFor (EL, e, g.adj[v]) {
int p = pair_g2[e->v];
if (dist[p] == dist[v] + 1 && dfs(p)) {
pair_g2[e->v] = v;
pair_g1[v] = e->v;
return true;
}
}
dist[v] = INF;
return false;
}
};
int hopcroft(IV &g1) {
HK hk(*this, g1);
int m = 0;
while (hk.bfs())
cFor (IV, v, g1)
if (hk.pair_g1[*v] == 0 && hk.dfs(*v))
++m;
return m;
}
// Articulations/bridges
struct Artic {
IV low, idx;
BV is_art;
IIV bridges;
int cnt;
Graph &g;
Artic(Graph &G) : g(G) {
low = IV(g.n);
idx = IV(g.n);
is_art = BV(g.n);
cnt = 1;
}
void dfs(int u, int v) {
int children = 0;
low[v] = idx[v] = cnt++;
cFor(EL, e, g.adj[v]) {
if (idx[e->v] == 0) {
++children;
dfs(v, e->v);
low[v] = min(low[v], low[e->v]);
if (low[e->v] >= idx[v] && u != v)
is_art[v] = true;
if (low[e->v] == idx[e->v])
bridges.push_back(II(v, e->v));
}
else if (e->v != u)
low[v] = min(low[v], idx[e->v]);
}
if (u == v && children > 1)
is_art[v] = true;
}
};
void articulations(IIV &bridges) {
Artic a(*this);
for (int i = 0; i < n; ++i)
if (a.idx[i] == 0) a.dfs(i, i);
bridges = a.bridges;
}
};
struct Graph {
struct Edge {
int u, v, w;
Edge(int U, int V, int W) : u(U), v(V), w(W) {}
bool operator<(const Edge &e) const { return w < e.w; }
};
typedef vector<Edge> EV;
EV edges;
void init(size_t m=16) { edges.clear(); edges.reserve(m); }
void add(int u, int v, int w) { edges.push_back(Edge(u, v, w)); }
// Minimum Spanning Tree
void kruskalMST(int n, int &ans) {
sort(edges.begin(), edges.end());
Set uf; uf.init(n);
int nedges = 0;
ans = 0;
EV mst;
cFor (EV, e, edges) {
if (uf.find(e->u) == uf.find(e->v)) continue;
mst.push_back(*e);
uf.merge(e->u, e->v);
ans += e->w;
if (++nedges == n - 1) break;
}
if (nedges < n - 1) ans = -1;
else edges = mst;
}
// Bellman-Ford
bool bellman_ford_neg_cycle(int n) {
IV dis(n);
for (int i = 0; i < n-1; i++)
cFor (EV, e, edges)
if(dis[e->u] + e->w < dis[e->v])
dis[e->v] = dis[e->u] + e->w;
cFor (EV, e, edges)
if (dis[e->u] + e->w < dis[e->v])
return true;
return false;
}
};
struct Graph {
// Shortest paths
void floyd(int **g, int N)
{
for (int k = 0; k < N; k++)
for(int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
int t = g[i][k] + g[k][j];
if (t < g[i][j]) g[i][j] = t;
}
}
};
//
// 2-SAT
//
struct TwoSat {
Graph g;
int n;
TwoSat(int N) : n(N) { g.init(2*N); }
void add_cons(int a, bool ta, int b, bool tb) {
int p = val(a, ta), q = val(b, tb);
g.add(neg(p), q); g.add(neg(q), p);
}
int val(int v, bool t) { return 2*v + (t ? 0 : 1); }
int neg(int p) { return p ^ 1; }
bool solve(IV &sol) {
IVV sccs;
g.kosaraju_scc(sccs);
IV vscc(n);
sol.clear();
for (int i = 0, I = sccs.size(); i < I; ++i) {
for (int j=0, J=sccs[i].size(); j < J; ++j) {
int p = sccs[i][j];
int v = p/2;
if (vscc[v] == i+1) return false;
if (vscc[v] != 0) break;
vscc[v] = i+1;
if (p & 1) sol.push_back(v);
}
}
return true;
}
};
//
// Number Theory
//
#define IsComp(n) (_c[n>>6]&(1<<((n>>1)&31)))
#define SetComp(n) _c[n>>6]|=(1<<((n>>1)&31))
namespace Num
{
const int MAX = 1000000; // 10^6
const int LMT = 1000; // sqrt(MAX)
int _c[(MAX>>6)+1];
IV primes;
void prime_sieve() {
for (int i = 3; i <= LMT; i += 2)
if (!IsComp(i)) for (int j = i*i; j <= MAX; j+=i+i) SetComp(j);
primes.push_back(2);
for (int i=3; i <= MAX; i+=2) if (!IsComp(i)) primes.push_back(i);
}
bool is_prime(int n) {
if (n < 2 || n % 2 == 0) return false;
return ! IsComp(n);
}
// Finds prime numbers between a and b, using basic primes up to sqrt(b)
void prime_seg_sieve(i64 a, i64 b, IV &seg_primes) {
BV pmap(b - a + 1, true);
i64 sqr_b = sqrt(b);
cFor (IV, pp, primes) {
int p = *pp;
if (p > sqr_b) break;
for (i64 j = (a+p-1)/p, v=(j==1?p+p:j*p); v <= b; v += p)
pmap[v-a] = false;
}
seg_primes.clear();
if (a == 1) pmap[0] = false;
for (int i = a%2 ? 0 : 1, I = b - a + 1; i < I; i += 2)
if (pmap[i])
seg_primes.push_back(a + i);
}
void prime_factorize(int n, IIV &f) {
int sn = sqrt(n);
cFor (IV, p, primes) {
int prime = *p;
if (prime > sn) break; if (n % prime) continue;
int e = 0; for (; n % prime == 0; e++, n /= prime);
f.push_back(II(prime, e));
sn = sqrt(n);
}
if (n > 1) f.push_back(II(n, 1));
}
void divisors(int n, IV &ds)
{
ds.clear();
ds.push_back(1);
int sn = sqrt(n);
cFor(IV, pp, primes) {
int p = *pp;
if (p > sn) break;
if (n % p != 0) continue;
IV aux(ds.begin(), ds.end());
int q = 1;
while (n % p == 0) {
q *= p; n /= p;
cFor(IV, v, ds) aux.push_back(*v * q);
}
sn = sqrt(n); ds = aux;
}
if (n > 1) {
IV aux(ds.begin(), ds.end());
cFor(IV, v, ds) aux.push_back(*v * n);
ds = aux;
}
}
void euler_phi(int a[], int N) {
for (int i = 1; i <= N; i++) a[i] = i;
for (int i = 2; i <= N; i += 2) a[i] = i/2;
for (int i = 3; i <= N; i += 2)
if (a[i] == i) {
a[i]--; for (int j = i+i; j <= N; j += i) a[j] -= a[j]/i;
}
}
int mod_pow(int _b, i64 e, int m) {
i64 res = 1;
for (i64 b=_b; e; e >>= 1, b = b*b%m) if (e & 1) res = res*b%m;
return res;
}
int ipow(int b, int e) {
int res = 1; for (; e; e >>= 1, b *= b) if (e & 1) res *= b;
return res;
}
int gcd(int a, int b) { for (int c = a%b; c; a=b,b=c,c=a%b); return b; }
void ext_euclid(int a, int b, int &x, int &y, int &gcd) {
x = 0; y = 1; gcd = b;
int m, n, q, r;
for (int u=1, v=0; a != 0; gcd=a, a=r) {
q = gcd / a; r = gcd % a;
m = x-u*q; n = y-v*q;
x=u; y=v; u=m; v=n;
}
}
int mod_inv(int n, int m) {
int x, y, gcd;
ext_euclid(n, m, x, y, gcd);
if (gcd == 1) return x % m;
return 0;
}
// Calculates the highest exponent of prime p that divides n!
int pow_div_fact(int n, int p) {
int sd = 0; for (int N=n; N; N /= p) sd += N % p; return (n-sd)/(p-1);
}
// Binomial coefficients
#define BCSIZE 1000
int bc[BCSIZE + 1][BCSIZE + 1];
void choose_table() {
for (int n = 1; n <= BCSIZE; n++) { bc[n][n] = 1; bc[n][1] = n; }
for (int n = 3; n <= BCSIZE; n++)
for (int k = 2; k < n; k++)
bc[n][k] = (bc[n-1][k-1] + bc[n-1][k]) % MOD;
}
int choose(int n, int k) {
if (k > n) return 0;
i64 r=1;
for (int d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
}
//
// Big Integer
//
#define BIBAS 1000
#define BIDIG 3
#define BIFMT "%03d"
struct Bigint {
IV d; bool sgn;
Bigint(i64 n=0) {
if (n < 0) sgn = true, n = -n; else sgn = false;
if (n < BIBAS) d.push_back(n);
else while (n != 0) { d.push_back(n % BIBAS); n /= BIBAS; }
}
Bigint(const char *s) {
if (*s == '-') sgn = true, s++; else sgn = false;
for (int end = strlen(s), i = max(0, end-BIDIG); true;) {
int n = 0; for (int j=i; j != end; j++) n = n*10 + s[j] - '0';
d.push_back(n); if (i == 0) break;
end = i, i = max(0, i-BIDIG);
} clean();
}
size_t len() const { return d.size(); }
bool is_zero() const { return len() == 1 && d[0] == 0; }
void flip() { sgn = !sgn; }
Bigint neg() const { Bigint x = *this; x.flip(); return x; }
bool operator==(const Bigint &b) const {
return sgn == b.sgn && d == b.d;
}
bool operator<(const Bigint &b) const {
if (sgn != b.sgn) return sgn;
if (len() != b.len()) return sgn ^ (len() < b.len());
for (int i = len() - 1; i >= 0; --i)
if (d[i] != b.d[i]) return sgn ^ (d[i] < b.d[i]);
return false;
}
Bigint &operator+=(const Bigint &b) {
if (sgn != b.sgn) { (*this) -= b.neg(); return *this; }
int s1 = len(), s2 = b.len(), s3 = max(s1, s2) + 1;
IV res(s3); int c = 0;
for (int i = 0; i < s3; ++i) {
int sum = c;
sum += i < s1 ? d[i] : 0;
sum += i < s2 ? b.d[i] : 0;
if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0;
res[i] = sum;
}
d = res; clean();
return *this;
}
Bigint &operator-=(const Bigint &b) {
if (sgn != b.sgn) { (*this) += b.neg(); return *this; }
if (*this < b) { Bigint x = b; x -= *this; return *this = x.neg(); }
int s1 = len(), s2 = b.len(), s3 = s1;
IV res(s3); int c = 0;
for (int i = 0; i < s3; ++i) {
int sum = d[i] - (i < s2 ? b.d[i] : 0) - c;
if (sum < 0) { sum += BIBAS; c = 1; } else c = 0;
res[i] = sum;
}
d = res; clean();
return *this;
}
Bigint &operator*=(const Bigint &b) {
int s1 = len(), s2 = b.len(), s3 = s1+s2;
IV res(s3); int c = 0;
for (int k=0; k < s3; ++k) {
int sum = c;
for (int i=max(0,k-s2+1), I=min(k+1, s1), j=k-i; i < I; ++i, --j)
sum += d[i] * b.d[j];
if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0;
res[k] = sum;
}
d = res; sgn ^= b.sgn; clean();
return *this;
}
Bigint &short_div(int b) {
for (int r = 0, i = len() - 1; i >= 0; --i)
r = r*BIBAS + d[i], d[i] = r / b, r %= b;
clean(); return *this;
}
Bigint &operator/=(const Bigint &b) {
if (b.is_zero()) { int x=0; return *this=Bigint(x/x); }
sgn ^= b.sgn; size_t l = len(), n = b.len();
if (n == 1) return short_div(b.d[0]);
if (l < n || (l == n && d.back() < b.d.back()))
return *this = Bigint(0);
Bigint r(0); IV res(l);
for (int i = l - 1; i >= 0; --i) {
r.d.insert(r.d.begin(), d[i]); r.clean();
int x = r.len() >= n ? r.d[n-1] : 0;
if (r.len() > n) x += BIBAS * r.d[n];
int q = x / b.d[n-1];
Bigint g = b; g *= Bigint(q);
while (r < g) g -= b, --q;
res[i] = q, r -= g;
}
d = res; clean(); return *this;
}
Bigint pow(int e) {
if (e == 0) return Bigint(1);
if (e == 1) return *this;
if (e % 2 == 0) {
Bigint tmp = this->pow(e/2);
tmp *= tmp;
return tmp;
}
Bigint tmp = this->pow(e-1);
tmp *= *this;
return tmp;
}
void clean() {
IVi i; for (i=d.end()-1; *i == 0 && i != d.begin(); i--);
d.erase(i+1, d.end());
if (sgn && d.size() == 1 && d[0] == 0) sgn = false;
}
void println() {
if (sgn) putchar('-');
bool flg = true;
crFor (IV, i, d) {
if (flg) { printf("%d", *i); flg=false; }
else printf(BIFMT, *i);
} putchar('\n');
}
int to_int() {
int res = 0, p = 1;
for (int i=0, I=len(); i < I; i++) { res += d[i] * p; p *= BIBAS; }
return sgn ? -res : res;
}
string to_string() {
char buf[BIDIG+1]; string str;
if (sgn) str.push_back('-');
bool flg = true;
crFor (IV, i, d) {
if (flg) { sprintf(buf, "%d", *i); flg=false; }
else sprintf(buf, BIFMT, *i);
str.append(buf);
}
return str;
}
};
//
// Fraction
//
struct Fraction {
int p, q;
Fraction(int P, int Q) : p(P), q(Q) { simplify(); }
Fraction(int P) : p(P), q(1) {}
void simplify() {
int g = gcd(p, q);
p /= g;
q /= g;
}
Fraction operator+(const Fraction &f) const {
return Fraction(p * f.q + q * f.p, q * f.q);
}
Fraction operator-(const Fraction &f) const {
return Fraction(p * f.q - q * f.p, q * f.q);
}
Fraction operator*(const Fraction &f) const {
return Fraction(p * f.p, q * f.q);
}
Fraction operator/(const Fraction &f) const {
return Fraction(p * f.q, q * f.p);
}
Fraction operator%(int m) const {
return Fraction(p % (m*q), q);
}
};
//
// Matrix Exponentiation
//
typedef u32 t_m;
#define MAXR (MAXK + 2)
#define MAXC (MAXK + 2)
struct Matrix {
int r, c;
t_m m[MAXR][MAXC];
void init(int R, int C) { Zero(m); r=R; c=C; }
void print() {
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j)
printf("%4d ", m[i][j]);
printf("\n");
}
}
};
void matrix_mul(const Matrix &a, const Matrix &b, Matrix &c)
{
c.r = a.r, c.c = b.c;
t_m x;
for (int i = 0; i < c.r; ++i)
for (int j = 0; j < c.c; ++j) {
x = 0;
for (int k = 0; k < a.c; ++k)
x += a.m[i][k] * b.m[k][j];
c.m[i][j] = x;
}
}
void matrix_exp(const Matrix &m, u64 e, Matrix &r)
{
if (e == 1) { r = m; return; }
Matrix x;
if (e % 2 == 0) {
matrix_exp(m, e / 2, x);
matrix_mul(x, x, r);
return;
}
matrix_exp(m, e-1, x);
matrix_mul(x, m, r);
}
//
// Geometry
//
double circle_angle(double a) { return a >= 0 ? a : Pi2 + a; }
bool eps_less(double a, double b) { return b - a > EPS; }
bool eps_equal(double a, double b) { return fabs(a - b) < EPS; }
typedef double p_t;
struct Point {
p_t x, y;
Point() { x=y=0; }
Point(p_t X, p_t Y) : x(X), y(Y) {}
p_t distance(Point p) {
p_t dx = p.x - x, dy = p.y - y; return sqrt(dx*dx + dy*dy);
}
bool operator<(const Point &p) const {
return x < p.x || (x == p.x && y < p.y);
}
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
bool collinear(const Point &b, const Point &c) const {
return (b.y - y) * (c.x - x) == (c.y - y) * (b.x - x);
}
};
struct Vector {
double x, y;
Vector(double X, p_t Y) : x(X), y(Y) {}
Vector(const Point &p) : x(p.x), y(p.y) {}
double norm() { return sqrt(x*x + y*y); }
double angle(const Vector &p) const {
return circle_angle(atan2(p.y, p.x) - atan2(y, x));
}
void rotate(double a) {
double px = x, py = y;
x = px*cos(a) - py*sin(a);
y = px*sin(a) + py*cos(a);
}
double distance_line_point(Point a, Point p) {
return fabs((p.x-a.x)*y - (p.y-a.y)*x) / sqrt(x*x + y*y);
}
};
typedef vector<Point> PV;
struct Circle {
double x, y, r;
Circle() {}
Circle(double X, double Y, double R) : x(X), y(Y), r(R) {}
bool perimeters_touch(const Circle &c) const {
double dx = x - c.x;
double dy = y - c.y;
double dist = sqrt(dx*dx + dy*dy);
return ! (eps_less(r + c.r, dist) ||
eps_less(dist, fabs(r - c.r)));
}
};
p_t cross(const Point &o, const Point &a, const Point &b) {
return (a.x-o.x)*(b.y-o.y) - (a.y-o.y)*(b.x-o.x);
}
void convex_hull(PV &p, PV &h) {
// Post-cond: p.size() > 1 => h.front() == h.back()
int n = p.size(), k = 0;
h.resize(2*n);
sort(p.begin(), p.end());
for (int i = 0; i < n; ++i) {
while (k >= 2 && cross(h[k-2], h[k-1], p[i]) <= 0) k--;
h[k++] = p[i];
}
for (int i = n-2, t=k+1; i >= 0; --i) {
while (k >= t && cross(h[k-2], h[k-1], p[i]) <= 0) k--;
h[k++] = p[i];
}
h.resize(k);
}
// Finds the circle formed by three points
void find_circle(Point &p1, Point &p2, Point &p3, Point &c, double &r)
{
Point m, a, b;
if (! eps_equal(p1.x, p2.x) && ! eps_equal(p1.x, p3.x))
m = p1, a = p2, b = p3;
else if (! eps_equal(p2.x, p1.x) && ! eps_equal(p2.x, p3.x))
m = p2, a = p1, b = p3;
else
m = p3, a = p1, b = p2;
double ma = (m.y - a.y) / (m.x - a.x);
double mb = (b.y - m.y) / (b.x - m.x);
c.x = ma*mb*(a.y - b.y) + mb*(a.x + m.x) - ma*(m.x + b.x);
c.x /= (mb - ma)*2.0;
if (eps_equal(0.0, ma))
c.y = (m.y + b.y) / 2.0 - (c.x - (m.x + b.x)/2.0) / mb;
else
c.y = (a.y + m.y) / 2.0 - (c.x - (a.x + m.x)/2.0) / ma;
r = c.distance(p1);
}
//
// Trie
//
struct Trie {
struct Node {
int ch[26];
int n;
Node() { n=0; Zero(ch); }
};
int sz;
vector<Node> nodes;
void init() { nodes.clear(); nodes.resize(1); sz = 1; }
void insert(const char *s) {
int idx, cur = 0;
for (; *s; ++s) {
idx = *s - 'A';
if (! nodes[cur].ch[idx]) {
nodes[cur].ch[idx] = sz++;
nodes.resize(sz);
}
cur = nodes[cur].ch[idx];
}
}
};
//
// Hash Map
//
#define HASHB 4096
struct HM {
typedef IV Datum; typedef vector<Datum> DV; DV b[HASHB];
u32 fnv_hash(const Datum &k, int len) const {
uch *p = reinterpret_cast<uch*>(const_cast<int*>(&k[0]));
u32 h = 2166136261U;
for (int i = 0; i < len; ++i) h = (h * 16777619U ) ^ p[i];
return h;
}
bool add(const Datum &k, u64 &id) {
int i = fnv_hash(k, k.size() * sizeof(int)) % HASHB;
for (int j = 0, J = b[i].size(); j < J; ++j)
if (b[i][j] == k) { id = i; id <<= 32; id |= j; return false; }
b[i].push_back(k);
id = i; id <<= 32; id |= (b[i].size() - 1);
return true;
}
Datum get(u64 id) const { return b[id>>32][id&0xFFFFFFFF]; }
};
//
// Time - Leap years
//
// A[i] has the accumulated number of days from months previous to i
const int A[13] = { 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
// same as A, but for a leap year
const int B[13] = { 0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
// returns number of leap years up to, and including, y
int leap_years(int y) { return y / 4 - y / 100 + y / 400; }
bool is_leap(int y) { return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0); }
// number of days in blocks of years
const int p400 = 400*365 + leap_years(400);
const int p100 = 100*365 + leap_years(100);
const int p4 = 4*365 + 1;
const int p1 = 365;
int date_to_days(int d, int m, int y)
{
return (y - 1) * 365 + leap_years(y - 1) + (is_leap(y) ? B[m] : A[m]) + d;
}
void days_to_date(int days, int &d, int &m, int &y)
{
bool top100; // are we in the top 100 years of a 400 block?
bool top4; // are we in the top 4 years of a 100 block?
bool top1; // are we in the top year of a 4 block?
y = 1;
top100 = top4 = top1 = false;
y += ((days-1) / p400) * 400;
d = (days-1) % p400 + 1;
if (d > p100*3) top100 = true, d -= 3*p100, y += 300;
else y += ((d-1) / p100) * 100, d = (d-1) % p100 + 1;
if (d > p4*24) top4 = true, d -= 24*p4, y += 24*4;
else y += ((d-1) / p4) * 4, d = (d-1) % p4 + 1;
if (d > p1*3) top1 = true, d -= p1*3, y += 3;
else y += (d-1) / p1, d = (d-1) % p1 + 1;
const int *ac = top1 && (!top4 || top100) ? B : A;
for (m = 1; m < 12; ++m) if (d <= ac[m + 1]) break;
d -= ac[m];
}
//
// Quickselect - for locating the median
//
struct Data {
int v; // value
int n; // occurrences
int p; // original position of data, to break ties
Data(int V, int N, int P) : v(V), n(N), p(P) {}
bool operator<(const Data &x) const {
if (v != x.v) return v < x.v;
if (n != x.n) return n < x.n;
return p < x.p;
}
};
typedef vector<Data> DV;
typedef DV::iterator DVi;
int select_kth(DVi lo, DVi hi, int k)
{
if (hi == lo + 1) return lo->v;
swap(*(lo + (rand() % (hi - lo))), *(hi - 1));
Data piv = *(hi - 1);
DVi x = lo;
int lt = 0;
for (DVi i = lo, I = hi - 1; i != I; ++i)
if (*i < piv) { swap(*i, *x); lt += x->n, ++x; }
swap(*x, *(hi - 1));
if (k < lt) return select_kth(lo, x, k);
if (k >= lt + x->n) return select_kth(x + 1, hi, k - lt - x->n);
return x->v;
}
//
// Merge sort - useful for adapting it to sorting-related problems
//
void merge(IVi lo, IVi hi, IVi mid)
{
IV x;
for (IVi a = lo, b = mid; a < mid || b < hi; ) {
if (a >= mid) { x.push_back(*b++); continue; }
if (b >= hi) { x.push_back(*a++); continue; }
if (*a < *b) { x.push_back(*a++); continue; }
x.push_back(*b++);
}
for (IVi a = lo, b = x.begin(); a < hi; ++a, ++b) *a = *b;
}
void merge_sort(IVi lo, IVi hi)
{
if (hi <= lo + 1) return;
IVi mid = lo + ((hi - lo) / 2);
merge_sort(lo, mid); merge_sort(mid, hi); merge(lo, hi, mid);
}
//
// Misc functions
//
// next higher number with same number of 1's in binary
u32 next_popcount(u32 n)
{
u32 c = (n & -n);
u32 r = n+c;
return (((r ^ n) >> 2) / c) | r;
}
// Returns first integer with exactly n bits set
u32 init_popcount(int n) { return (1 << n) - 1; }
#define Back(b) ((b) & -(b))
#define PopBack(b) (b &= ~Back(b))
// Finds the most significant bit set on n. The bit is left in b, and its
// zero-indexed position in p
void msb(i64 n, i64 &b, int &p)
{
for (b = 1, p = 0, n >>= 1; n; b <<= 1, n >>= 1, ++p);
}
// returns the position of the last visited in range [0, n-1]
int josephus(int n, int k)
{
if (n == 1) return 0;
return (josephus(n-1, k) + k) % n;
}
|
//This is a testing version of the BDT training code
//Author: Zhaoyuan "Maxwell" Cui
//Physics department, Unversity of Arizona
#include "iostream"
#include "fstream"
#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TMVA/Factory.h"
#include "TMVA/Tools.h"
#include "TMVA/TMVAGui.h"
int bdt_vlq()
{
//Load the library
TMVA::Tools::Instance();
std::cout<<std::endl;
std::cout<<"==>Start BDT"<<std::endl;
TString outputFileName("BDT_VLQ_data.root");
TFile *outputFile=TFile::Open(outputFileName, "RECREATE");
//Register TMVA Factory
TMVA::Factory *factory=new TMVA::Factory("BDT_VLQ", outputFile,
"V:!Silent:Color:DrawProgressBar:AnalysisType=Classification");
//Read training data
//
TString fSig="../normalization/BBS_sig.root";
TString fBkg_VV="../normalization/VV.root";
TString fBkg_VVV="../normalization/VVV.root";
TString fBkg_ttW_np2="../normalization/ttW_np2_bkg.root";
TString fBkg_ttW_np1="../normalization/ttW_np1_bkg.root";
TString fBkg_ttW_np0="../normalization/ttW_np0_bkg.root";
TString fBkg_ttH="../normalization/ttH.root";
std::ifstream inputFile("datafiles.txt");
std::string fileName;
while(std::getline(inputFile,fileName))
{
TFile *inputBg=TFile::Open(fileName);
}
//---
// TFile *inputSig=TFile::Open(fSig);
// TFile *inputVV=TFile::Open(fBkg_VV);
// TFile *inputVVV=TFile::Open(fBkg_VVV);
// TFile *inputNP2=TFile::Open(fBkg_ttW_np2);
// TFile *inputNP1=TFile::Open(fBkg_ttW_np1);
// TFile *inputNP0=TFile::Open(fBkg_ttW_np0);
// TFile *inputttH=TFile::Open(fBkg_ttH);
TTree *signal=(TTree*)inputSig->Get("nominal_Loose");
TTree *vv=(TTree*)inputVV->Get("nominal_Loose");
TTree *vvv=(TTree*)inputVVV->Get("nominal_Loose");
TTree *ttW_np2=(TTree*)inputNP2->Get("nominal_Loose");
TTree *ttW_np1=(TTree*)inputNP1->Get("nominal_Loose");
TTree *ttW_np0=(TTree*)inputNP0->Get("nominal_Loose");
TTree *ttH=(TTree*)inputttH->Get("nominal_Loose");
std::cout<<"File operation done"<<std::endl;
//Add variables that will be used for MVA training
factory->AddVariable("mu",'F');
factory->AddVariable("el_pt.[0]",'F');
factory->AddVariable("mu_pt.[0]",'F');
factory->AddVariable("jet_pt.[0]",'F');
factory->AddVariable("met_met",'F');
factory->AddVariable("met_phi",'F');
factory->AddVariable("SSee_2016",'I');
factory->AddVariable("SSem_2016",'I');
factory->AddVariable("SSmm_2016",'I');
factory->AddVariable("eee_2016",'I');
factory->AddVariable("eem_2016",'I');
factory->AddVariable("emm_2016",'I');
factory->AddVariable("mmm_2016",'I');
factory->AddVariable("lep_pt.[0]",'I');
factory->AddVariable("ht",'F');
factory->AddVariable("met_sumet",'F');
factory->AddVariable("bj",'I');
std::cout<<" --- BDT_VLQ\tUsing input file: "
<<"\n\t"
<<inputSig->GetName()<<"\n\t"
<<inputVV->GetName()<<"\n\t"
<<inputVVV->GetName()<<"\n\t"
<<inputNP2->GetName()<<"\n\t"
<<inputNP1->GetName()<<"\n\t"
<<inputNP0->GetName()<<"\n\t"
<<inputttH->GetName()<<std::endl;
//Global event weights per tree
Double_t signalWeight=1.0;
Double_t vvWeight=1.0;
Double_t vvvWeight=1.0;
Double_t ttW_np2Weight=1.0;
Double_t ttW_np1Weight=1.0;
Double_t ttW_np0Weight=1.0;
Double_t ttHWeight=1.0;
// factory->AddSignalTree(signal,signalWeight);
// factory->AddBackgroundTree(vv,vvWeight);
// factory->AddBackgroundTree(vvv,vvvWeight);
// factory->AddBackgroundTree(ttW_np2,ttW_np2Weight);
// factory->AddBackgroundTree(ttW_np1,ttW_np2Weight);
// factory->AddBackgroundTree(ttW_np0,ttW_np2Weight);
// factory->AddBackgroundTree(ttH,ttHWeight);
// factory->SetWeightExpression("evtWeight");
//Apply additional cuts on the signal and background samples
TCut mycut="";
factory->PrepareTrainingAndTestTree(mycut,"SplitMode=random:!V:NormMode=None");
// --- Book MVA method
//
//Boosted Decision Tree
//TString Option="!H:!V:NTrees=400:MaxDepth=10:MinNodeSize=5%:nCuts=20:NegWeightTreatment=IgnoreNegWeightsInTraining:SeparationType=GiniIndex:BoostType=AdaBoost:VarTransform=Decorrelate";
//TString Option="!H:!V:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex";
TString Option="!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate";
factory->BookMethod( TMVA::Types::kBDT, "BDT",
Option);
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
outputFile->Close();
std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
std::cout << "==> TMVAClassification is done!" << std::endl;
delete factory;
//Launch the GUI for the root macros
if (!gROOT->IsBatch())
TMVA::TMVAGui(outputFileName);
return 0;
}
int main()
{
return bdt_vlq();
}
update input method
//This is a testing version of the BDT training code
//Author: Zhaoyuan "Maxwell" Cui
//Physics department, Unversity of Arizona
#include "iostream"
#include "fstream"
#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TMVA/Factory.h"
#include "TMVA/Tools.h"
#include "TMVA/TMVAGui.h"
int bdt_vlq()
{
//Load the library
TMVA::Tools::Instance();
std::cout<<std::endl;
std::cout<<"==>Start BDT"<<std::endl;
TString outputFileName("BDT_VLQ_data.root");
TFile *outputFile=TFile::Open(outputFileName, "RECREATE");
//Register TMVA Factory
TMVA::Factory *factory=new TMVA::Factory("BDT_VLQ", outputFile,
"V:!Silent:Color:DrawProgressBar:AnalysisType=Classification");
//Read training data
//
TString fSig;
TString fBkg;
TString prefix="normalized_";
std::ifstream inputFile("datafiles.txt");
std::string fileName;
TFile *inputBg=new TFile[10];
TTree *bgTree=new TTree[10];
Int_t counter=0;
while(std::getline(inputFile,fileName))
{
fileName=prefix+fileName;
inputBg[counter]=new TFile::Open(fileName);
bgTree[counter]=(TTree*)inputBg[counter]->Get("nominal_Loose");
counter++;
}
//---
// TFile *inputSig=TFile::Open(fSig);
// TFile *inputVV=TFile::Open(fBkg_VV);
// TFile *inputVVV=TFile::Open(fBkg_VVV);
// TFile *inputNP2=TFile::Open(fBkg_ttW_np2);
// TFile *inputNP1=TFile::Open(fBkg_ttW_np1);
// TFile *inputNP0=TFile::Open(fBkg_ttW_np0);
// TFile *inputttH=TFile::Open(fBkg_ttH);
// TTree *signal=(TTree*)inputSig->Get("nominal_Loose");
// TTree *vv=(TTree*)inputVV->Get("nominal_Loose");
// TTree *vvv=(TTree*)inputVVV->Get("nominal_Loose");
// TTree *ttW_np2=(TTree*)inputNP2->Get("nominal_Loose");
// TTree *ttW_np1=(TTree*)inputNP1->Get("nominal_Loose");
// TTree *ttW_np0=(TTree*)inputNP0->Get("nominal_Loose");
// TTree *ttH=(TTree*)inputttH->Get("nominal_Loose");
std::cout<<"File operation done"<<std::endl;
//Add variables that will be used for MVA training
factory->AddVariable("mu",'F');
factory->AddVariable("el_pt.[0]",'F');
factory->AddVariable("mu_pt.[0]",'F');
factory->AddVariable("jet_pt.[0]",'F');
factory->AddVariable("met_met",'F');
factory->AddVariable("met_phi",'F');
factory->AddVariable("SSee_2016",'I');
factory->AddVariable("SSem_2016",'I');
factory->AddVariable("SSmm_2016",'I');
factory->AddVariable("eee_2016",'I');
factory->AddVariable("eem_2016",'I');
factory->AddVariable("emm_2016",'I');
factory->AddVariable("mmm_2016",'I');
factory->AddVariable("lep_pt.[0]",'I');
factory->AddVariable("ht",'F');
factory->AddVariable("met_sumet",'F');
factory->AddVariable("bjet",'I');
for(Int_t n=0;n<10;n++)
{
std::cout<<" --- BDT_VLQ\tUsing input file: "
<<"\n\t"
<<inputBg[n]->GetName()<<"\n\t"
<<std::endl;
}
//Global event weights per tree
// Double_t signalWeight=1.0;
// Double_t vvWeight=1.0;
// Double_t vvvWeight=1.0;
// Double_t ttW_np2Weight=1.0;
// Double_t ttW_np1Weight=1.0;
// Double_t ttW_np0Weight=1.0;
// Double_t ttHWeight=1.0;
// factory->AddSignalTree(signal,signalWeight);
// factory->AddBackgroundTree(vv,vvWeight);
// factory->AddBackgroundTree(vvv,vvvWeight);
// factory->AddBackgroundTree(ttW_np2,ttW_np2Weight);
// factory->AddBackgroundTree(ttW_np1,ttW_np2Weight);
// factory->AddBackgroundTree(ttW_np0,ttW_np2Weight);
// factory->AddBackgroundTree(ttH,ttHWeight);
factory->SetWeightExpression("evtWeight");
//Apply additional cuts on the signal and background samples
TCut mycut="";
factory->PrepareTrainingAndTestTree(mycut,"SplitMode=random:!V:NormMode=None");
// --- Book MVA method
//
//Boosted Decision Tree
//TString Option="!H:!V:NTrees=400:MaxDepth=10:MinNodeSize=5%:nCuts=20:NegWeightTreatment=IgnoreNegWeightsInTraining:SeparationType=GiniIndex:BoostType=AdaBoost:VarTransform=Decorrelate";
//TString Option="!H:!V:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex";
TString Option="!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate";
factory->BookMethod( TMVA::Types::kBDT, "BDT",
Option);
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
outputFile->Close();
std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
std::cout << "==> TMVAClassification is done!" << std::endl;
delete factory;
//Launch the GUI for the root macros
if (!gROOT->IsBatch())
TMVA::TMVAGui(outputFileName);
return 0;
}
int main()
{
return bdt_vlq();
}
|
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include <v8.h>
#include "v8_proxy.h"
#include "dom_wrapper_map.h"
#include "v8_index.h"
#include "v8_events.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_collection.h"
#include "v8_nodefilter.h"
#include "V8DOMWindow.h"
#include "ChromiumBridge.h"
#include "BarInfo.h"
#include "CanvasGradient.h"
#include "CanvasPattern.h"
#include "CanvasPixelArray.h"
#include "CanvasRenderingContext2D.h"
#include "CanvasStyle.h"
#include "CharacterData.h"
#include "Clipboard.h"
#include "Console.h"
#include "Counter.h"
#include "CSSCharsetRule.h"
#include "CSSFontFaceRule.h"
#include "CSSImportRule.h"
#include "CSSMediaRule.h"
#include "CSSPageRule.h"
#include "CSSRule.h"
#include "CSSRuleList.h"
#include "CSSValueList.h"
#include "CSSStyleRule.h"
#include "CSSStyleSheet.h"
#include "CSSVariablesDeclaration.h"
#include "CSSVariablesRule.h"
#include "DocumentType.h"
#include "DocumentFragment.h"
#include "DOMCoreException.h"
#include "DOMImplementation.h"
#include "DOMParser.h"
#include "DOMSelection.h"
#include "DOMWindow.h"
#include "Entity.h"
#include "EventListener.h"
#include "EventTargetNode.h"
#include "EventTarget.h"
#include "Event.h"
#include "EventException.h"
#include "ExceptionCode.h"
#include "File.h"
#include "FileList.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "History.h"
#include "HTMLNames.h"
#include "HTMLDocument.h"
#include "HTMLElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLSelectElement.h"
#include "HTMLOptionsCollection.h"
#include "ImageData.h"
#include "InspectorController.h"
#include "KeyboardEvent.h"
#include "Location.h"
#include "MediaList.h"
#include "MessageChannel.h"
#include "MessageEvent.h"
#include "MessagePort.h"
#include "MimeTypeArray.h"
#include "MouseEvent.h"
#include "MutationEvent.h"
#include "Navigator.h" // for MimeTypeArray
#include "NodeFilter.h"
#include "Notation.h"
#include "NodeList.h"
#include "NodeIterator.h"
#include "OverflowEvent.h"
#include "Page.h"
#include "Plugin.h"
#include "PluginArray.h"
#include "ProcessingInstruction.h"
#include "ProgressEvent.h"
#include "Range.h"
#include "RangeException.h"
#include "Rect.h"
#include "RGBColor.h"
#include "Screen.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "StyleSheet.h"
#include "StyleSheetList.h"
#include "TextEvent.h"
#include "TextMetrics.h"
#include "TreeWalker.h"
#include "WebKitCSSTransformValue.h"
#include "XMLHttpRequest.h"
#include "XMLHttpRequestUpload.h"
#include "XMLHttpRequestException.h"
#include "XMLSerializer.h"
#include "XPathException.h"
#include "XPathExpression.h"
#include "XPathNSResolver.h"
#include "XPathResult.h"
#include "XSLTProcessor.h"
#include "WebKitAnimationEvent.h"
#include "WebKitCSSKeyframeRule.h"
#include "WebKitCSSKeyframesRule.h"
#include "WebKitTransitionEvent.h"
#include "WheelEvent.h"
#include "XMLHttpRequestProgressEvent.h"
#include "V8DOMWindow.h"
#include "V8HTMLElement.h"
#include "ScriptController.h"
#if ENABLE(SVG)
#include "SVGAngle.h"
#include "SVGAnimatedPoints.h"
#include "SVGElement.h"
#include "SVGElementInstance.h"
#include "SVGElementInstanceList.h"
#include "SVGException.h"
#include "SVGLength.h"
#include "SVGLengthList.h"
#include "SVGNumberList.h"
#include "SVGPathSeg.h"
#include "SVGPathSegArc.h"
#include "SVGPathSegClosePath.h"
#include "SVGPathSegCurvetoCubic.h"
#include "SVGPathSegCurvetoCubicSmooth.h"
#include "SVGPathSegCurvetoQuadratic.h"
#include "SVGPathSegCurvetoQuadraticSmooth.h"
#include "SVGPathSegLineto.h"
#include "SVGPathSegLinetoHorizontal.h"
#include "SVGPathSegLinetoVertical.h"
#include "SVGPathSegList.h"
#include "SVGPathSegMoveto.h"
#include "SVGPointList.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGRenderingIntent.h"
#include "SVGStringList.h"
#include "SVGTransform.h"
#include "SVGTransformList.h"
#include "SVGUnitTypes.h"
#include "SVGURIReference.h"
#include "SVGZoomEvent.h"
#include "V8SVGPODTypeWrapper.h"
#endif // SVG
#if ENABLE(XPATH)
#include "XPathEvaluator.h"
#endif
namespace WebCore {
// DOM binding algorithm:
//
// There are two kinds of DOM objects:
// 1. DOM tree nodes, such as Document, HTMLElement, ...
// there classes implements TreeShared<T> interface;
// 2. Non-node DOM objects, such as CSSRule, Location, etc.
// these classes implement a ref-counted scheme.
//
// A DOM object may have a JS wrapper object. If a tree node
// is alive, its JS wrapper must be kept alive even it is not
// reachable from JS roots.
// However, JS wrappers of non-node objects can go away if
// not reachable from other JS objects. It works like a cache.
//
// DOM objects are ref-counted, and JS objects are traced from
// a set of root objects. They can create a cycle. To break
// cycles, we do following:
// Peer from DOM objects to JS wrappers are always weak,
// so JS wrappers of non-node object cannot create a cycle.
// Before starting a global GC, we create a virtual connection
// between nodes in the same tree in the JS heap. If the wrapper
// of one node in a tree is alive, wrappers of all nodes in
// the same tree are considered alive. This is done by creating
// object groups in GC prologue callbacks. The mark-compact
// collector will remove these groups after each GC.
// A helper class for undetectable document.all
class UndetectableHTMLCollection : public HTMLCollection {
};
#ifndef NDEBUG
// Keeps track of global handles created (not JS wrappers
// of DOM objects). Often these global handles are source
// of leaks.
//
// If you want to let a C++ object hold a persistent handle
// to a JS object, you should register the handle here to
// keep track of leaks.
//
// When creating a persistent handle, call:
//
// #ifndef NDEBUG
// V8Proxy::RegisterGlobalHandle(type, host, handle);
// #endif
//
// When releasing the handle, call:
//
// #ifndef NDEBUG
// V8Proxy::UnregisterGlobalHandle(type, host, handle);
// #endif
//
typedef HashMap<v8::Value*, GlobalHandleInfo*> GlobalHandleMap;
static GlobalHandleMap& global_handle_map()
{
static GlobalHandleMap static_global_handle_map;
return static_global_handle_map;
}
// The USE_VAR(x) template is used to silence C++ compiler warnings
// issued for unused variables (typically parameters or values that
// we want to watch in the debugger).
template <typename T>
static inline void USE_VAR(T) { }
// The function is the place to set the break point to inspect
// live global handles. Leaks are often come from leaked global handles.
static void EnumerateGlobalHandles()
{
for (GlobalHandleMap::iterator it = global_handle_map().begin(),
end = global_handle_map().end(); it != end; ++it) {
GlobalHandleInfo* info = it->second;
USE_VAR(info);
v8::Value* handle = it->first;
USE_VAR(handle);
}
}
void V8Proxy::RegisterGlobalHandle(GlobalHandleType type, void* host,
v8::Persistent<v8::Value> handle)
{
ASSERT(!global_handle_map().contains(*handle));
global_handle_map().set(*handle, new GlobalHandleInfo(host, type));
}
void V8Proxy::UnregisterGlobalHandle(void* host, v8::Persistent<v8::Value> handle)
{
ASSERT(global_handle_map().contains(*handle));
GlobalHandleInfo* info = global_handle_map().take(*handle);
ASSERT(info->host_ == host);
delete info;
}
#endif // ifndef NDEBUG
void BatchConfigureAttributes(v8::Handle<v8::ObjectTemplate> inst,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedAttribute* attrs,
size_t num_attrs)
{
for (size_t i = 0; i < num_attrs; ++i) {
const BatchedAttribute* a = &attrs[i];
(a->on_proto ? proto : inst)->SetAccessor(
v8::String::New(a->name),
a->getter,
a->setter,
a->data == V8ClassIndex::INVALID_CLASS_INDEX
? v8::Handle<v8::Value>()
: v8::Integer::New(V8ClassIndex::ToInt(a->data)),
a->settings,
a->attribute);
}
}
void BatchConfigureConstants(v8::Handle<v8::FunctionTemplate> desc,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedConstant* consts,
size_t num_consts)
{
for (size_t i = 0; i < num_consts; ++i) {
const BatchedConstant* c = &consts[i];
desc->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
proto->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
}
}
typedef HashMap<Node*, v8::Object*> DOMNodeMap;
typedef HashMap<void*, v8::Object*> DOMObjectMap;
#ifndef NDEBUG
static void EnumerateDOMObjectMap(DOMObjectMap& wrapper_map)
{
for (DOMObjectMap::iterator it = wrapper_map.begin(), end = wrapper_map.end();
it != end; ++it) {
v8::Persistent<v8::Object> wrapper(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
void* obj = it->first;
USE_VAR(type);
USE_VAR(obj);
}
}
static void EnumerateDOMNodeMap(DOMNodeMap& node_map)
{
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
USE_VAR(node);
ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
}
}
#endif // NDEBUG
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj, void* para);
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* para);
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* para);
// A map from DOM node to its JS wrapper.
static DOMWrapperMap<Node>& dom_node_map()
{
static DOMWrapperMap<Node> static_dom_node_map(&WeakNodeCallback);
return static_dom_node_map;
}
// A map from a DOM object (non-node) to its JS wrapper. This map does not
// contain the DOM objects which can have pending activity (active dom objects).
static DOMWrapperMap<void>& dom_object_map()
{
static DOMWrapperMap<void>
static_dom_object_map(&WeakDOMObjectCallback);
return static_dom_object_map;
}
// A map from a DOM object to its JS wrapper for DOM objects which
// can have pending activity.
static DOMWrapperMap<void>& active_dom_object_map()
{
static DOMWrapperMap<void>
static_active_dom_object_map(&WeakActiveDOMObjectCallback);
return static_active_dom_object_map;
}
#if ENABLE(SVG)
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param);
// A map for SVGElementInstances.
static DOMWrapperMap<SVGElementInstance>& dom_svg_element_instance_map()
{
static DOMWrapperMap<SVGElementInstance>
static_dom_svg_element_instance_map(&WeakSVGElementInstanceCallback);
return static_dom_svg_element_instance_map;
}
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param)
{
SVGElementInstance* instance = static_cast<SVGElementInstance*>(param);
ASSERT(dom_svg_element_instance_map().contains(instance));
instance->deref();
dom_svg_element_instance_map().forget(instance);
}
v8::Handle<v8::Value> V8Proxy::SVGElementInstanceToV8Object(
SVGElementInstance* instance)
{
if (!instance)
return v8::Null();
v8::Handle<v8::Object> existing_instance = dom_svg_element_instance_map().get(instance);
if (!existing_instance.IsEmpty())
return existing_instance;
instance->ref();
// Instantiate the V8 object and remember it
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::SVGELEMENTINSTANCE,
V8ClassIndex::SVGELEMENTINSTANCE,
instance);
if (!result.IsEmpty()) {
// Only update the DOM SVG element map if the result is non-empty.
dom_svg_element_instance_map().set(instance,
v8::Persistent<v8::Object>::New(result));
}
return result;
}
// SVG non-node elements may have a reference to a context node which
// should be notified when the element is change
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj);
// Map of SVG objects with contexts to V8 objects
static DOMWrapperMap<void>& dom_svg_object_with_context_map() {
static DOMWrapperMap<void>
static_dom_svg_object_with_context_map(&WeakSVGObjectWithContext);
return static_dom_svg_object_with_context_map;
}
// Map of SVG objects with contexts to their contexts
static HashMap<void*, SVGElement*>& svg_object_to_context_map()
{
static HashMap<void*, SVGElement*> static_svg_object_to_context_map;
return static_svg_object_to_context_map;
}
v8::Handle<v8::Value> V8Proxy::SVGObjectWithContextToV8Object(
V8ClassIndex::V8WrapperType type, void* object)
{
if (!object)
return v8::Null();
v8::Persistent<v8::Object> result =
dom_svg_object_with_context_map().get(object);
if (!result.IsEmpty()) return result;
// Special case: SVGPathSegs need to be downcast to their real type
if (type == V8ClassIndex::SVGPATHSEG)
type = V8Custom::DowncastSVGPathSeg(object);
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, object);
if (!v8obj.IsEmpty()) {
result = v8::Persistent<v8::Object>::New(v8obj);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(object)->ref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(object)->ref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
dom_svg_object_with_context_map().set(object, result);
}
return result;
}
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope handle_scope;
ASSERT(dom_svg_object_with_context_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
dom_svg_object_with_context_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(dom_obj)->deref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
void V8Proxy::SetSVGContext(void* obj, SVGElement* context)
{
SVGElement* old_context = svg_object_to_context_map().get(obj);
if (old_context == context)
return;
if (old_context)
old_context->deref();
if (context)
context->ref();
svg_object_to_context_map().set(obj, context);
}
SVGElement* V8Proxy::GetSVGContext(void* obj)
{
return svg_object_to_context_map().get(obj);
}
#endif
// Called when obj is near death (not reachable from JS roots)
// It is time to remove the entry from the table and dispose
// the handle.
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj) {
v8::HandleScope scope;
ASSERT(dom_object_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
dom_object_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope scope;
ASSERT(active_dom_object_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
active_dom_object_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* param)
{
Node* node = static_cast<Node*>(param);
ASSERT(dom_node_map().contains(node));
dom_node_map().forget(node);
node->deref();
}
// A map from a DOM node to its JS wrapper, the wrapper
// is kept as a strong reference to survive GCs.
static DOMObjectMap& gc_protected_map() {
static DOMObjectMap static_gc_protected_map;
return static_gc_protected_map;
}
// static
void V8Proxy::GCProtect(void* dom_object)
{
if (!dom_object)
return;
if (gc_protected_map().contains(dom_object))
return;
if (!dom_object_map().contains(dom_object))
return;
// Create a new (strong) persistent handle for the object.
v8::Persistent<v8::Object> wrapper = dom_object_map().get(dom_object);
if (wrapper.IsEmpty()) return;
gc_protected_map().set(dom_object, *v8::Persistent<v8::Object>::New(wrapper));
}
// static
void V8Proxy::GCUnprotect(void* dom_object)
{
if (!dom_object)
return;
if (!gc_protected_map().contains(dom_object))
return;
// Dispose the strong reference.
v8::Persistent<v8::Object> wrapper(gc_protected_map().take(dom_object));
wrapper.Dispose();
}
// Create object groups for DOM tree nodes.
static void GCPrologue()
{
v8::HandleScope scope;
#ifndef NDEBUG
EnumerateDOMObjectMap(dom_object_map().impl());
#endif
// Run through all objects with possible pending activity making their
// wrappers non weak if there is pending activity.
DOMObjectMap active_map = active_dom_object_map().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
ASSERT(wrapper.IsWeak());
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) \
wrapper.ClearWeak(); \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
// Create object groups.
DOMNodeMap node_map = dom_node_map().impl();
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
// If the node is in document, put it in the ownerDocument's
// object group. Otherwise, skip it.
//
// If an image element was created by JavaScript "new Image",
// it is not in a document. However, if the load event has not
// been fired (still onloading), it is treated as in the document.
//
// Otherwise, the node is put in an object group identified by the root
// elment of the tree to which it belongs.
void* group_id;
if (node->inDocument() ||
(node->hasTagName(HTMLNames::imgTag) &&
!static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent()) ) {
group_id = node->document();
} else {
Node* root = node;
while (root->parent()) {
root = root->parent();
}
group_id = root;
}
v8::Persistent<v8::Object> wrapper = dom_node_map().get(node);
if (!wrapper.IsEmpty())
v8::V8::AddObjectToGroup(group_id, wrapper);
}
}
static void GCEpilogue()
{
v8::HandleScope scope;
// Run through all objects with pending activity making their wrappers weak
// again.
DOMObjectMap active_map = active_dom_object_map().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
ASSERT(!wrapper.IsWeak());
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) \
wrapper.MakeWeak(impl, &WeakActiveDOMObjectCallback); \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
#ifndef NDEBUG
// Check all survivals are weak.
EnumerateDOMObjectMap(dom_object_map().impl());
EnumerateDOMNodeMap(dom_node_map().impl());
EnumerateDOMObjectMap(gc_protected_map());
EnumerateGlobalHandles();
#undef USE_VAR
#endif
}
typedef HashMap<int, v8::FunctionTemplate*> FunctionTemplateMap;
bool AllowAllocation::m_current = false;
// JavaScriptConsoleMessages encapsulate everything needed to
// log messages originating from JavaScript to the Chrome console.
class JavaScriptConsoleMessage {
public:
JavaScriptConsoleMessage(const String& str,
const String& sourceID,
unsigned lineNumber)
: m_string(str)
, m_sourceID(sourceID)
, m_lineNumber(lineNumber) { }
void AddToPage(Page* page) const;
private:
const String m_string;
const String m_sourceID;
const unsigned m_lineNumber;
};
void JavaScriptConsoleMessage::AddToPage(Page* page) const
{
ASSERT(page);
Console* console = page->mainFrame()->domWindow()->console();
console->addMessage(JSMessageSource, ErrorMessageLevel, m_string, m_lineNumber, m_sourceID);
}
// The ConsoleMessageManager handles all console messages that stem
// from JavaScript. It keeps a list of messages that have been delayed but
// it makes sure to add all messages to the console in the right order.
class ConsoleMessageManager {
public:
// Add a message to the console. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void AddMessage(Page* page, const JavaScriptConsoleMessage& message);
// Add a message to the console but delay the reporting until it
// is safe to do so: Either when we leave JavaScript execution or
// when adding other console messages. The primary purpose of this
// method is to avoid calling into V8 to handle console messages
// when the VM is in a state that does not support GCs or allocations.
// Delayed messages are always reported in the page corresponding
// to the active context.
static void AddDelayedMessage(const JavaScriptConsoleMessage& message);
// Process any delayed messages. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void ProcessDelayedMessages();
private:
// All delayed messages are stored in this vector. If the vector
// is NULL, there are no delayed messages.
static Vector<JavaScriptConsoleMessage>* m_delayed;
};
Vector<JavaScriptConsoleMessage>* ConsoleMessageManager::m_delayed = NULL;
void ConsoleMessageManager::AddMessage(
Page* page,
const JavaScriptConsoleMessage& message)
{
// Process any delayed messages to make sure that messages
// appear in the right order in the console.
ProcessDelayedMessages();
message.AddToPage(page);
}
void ConsoleMessageManager::AddDelayedMessage(const JavaScriptConsoleMessage& message)
{
if (!m_delayed)
// Allocate a vector for the delayed messages. Will be
// deallocated when the delayed messages are processed
// in ProcessDelayedMessages().
m_delayed = new Vector<JavaScriptConsoleMessage>();
m_delayed->append(message);
}
void ConsoleMessageManager::ProcessDelayedMessages()
{
// If we have a delayed vector it cannot be empty.
if (!m_delayed)
return;
ASSERT(!m_delayed->isEmpty());
// Add the delayed messages to the page of the active
// context. If that for some bizarre reason does not
// exist, we clear the list of delayed messages to avoid
// posting messages. We still deallocate the vector.
Frame* frame = V8Proxy::retrieveActiveFrame();
Page* page = NULL;
if (frame)
page = frame->page();
if (!page)
m_delayed->clear();
// Iterate through all the delayed messages and add them
// to the console.
const int size = m_delayed->size();
for (int i = 0; i < size; i++) {
m_delayed->at(i).AddToPage(page);
}
// Deallocate the delayed vector.
delete m_delayed;
m_delayed = NULL;
}
// Convenience class for ensuring that delayed messages in the
// ConsoleMessageManager are processed quickly.
class ConsoleMessageScope {
public:
ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
~ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
};
void log_info(Frame* frame, const String& msg, const String& url)
{
Page* page = frame->page();
if (!page)
return;
JavaScriptConsoleMessage message(msg, url, 0);
ConsoleMessageManager::AddMessage(page, message);
}
static void HandleConsoleMessage(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data)
{
// Use the frame where JavaScript is called from.
Frame* frame = V8Proxy::retrieveActiveFrame();
if (!frame)
return;
Page* page = frame->page();
if (!page)
return;
v8::Handle<v8::String> errorMessageString = message->Get();
ASSERT(!errorMessageString.IsEmpty());
String errorMessage = ToWebCoreString(errorMessageString);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool useURL = (resourceName.IsEmpty() || !resourceName->IsString());
String resourceNameString = (useURL)
? frame->document()->url()
: ToWebCoreString(resourceName);
JavaScriptConsoleMessage consoleMessage(errorMessage,
resourceNameString,
message->GetLineNumber());
ConsoleMessageManager::AddMessage(page, consoleMessage);
}
enum DelayReporting {
REPORT_LATER,
REPORT_NOW
};
static void ReportUnsafeAccessTo(Frame* target, DelayReporting delay)
{
ASSERT(target);
Document* targetDocument = target->document();
if (!targetDocument)
return;
Frame* source = V8Proxy::retrieveActiveFrame();
if (!source || !source->document())
return; // Ignore error if the source document is gone.
Document* sourceDocument = source->document();
// FIXME: This error message should contain more specifics of why the same
// origin check has failed.
String str = String::format("Unsafe JavaScript attempt to access frame "
"with URL %s from frame with URL %s. "
"Domains, protocols and ports must match.\n",
targetDocument->url().string().utf8().data(),
sourceDocument->url().string().utf8().data());
// Build a console message with fake source ID and line number.
const String kSourceID = "";
const int kLineNumber = 1;
JavaScriptConsoleMessage message(str, kSourceID, kLineNumber);
if (delay == REPORT_NOW) {
// NOTE(tc): Apple prints the message in the target page, but it seems like
// it should be in the source page. Even for delayed messages, we put it in
// the source page; see ConsoleMessageManager::ProcessDelayedMessages().
ConsoleMessageManager::AddMessage(source->page(), message);
} else {
ASSERT(delay == REPORT_LATER);
// We cannot safely report the message eagerly, because this may cause
// allocations and GCs internally in V8 and we cannot handle that at this
// point. Therefore we delay the reporting.
ConsoleMessageManager::AddDelayedMessage(message);
}
}
static void ReportUnsafeJavaScriptAccess(v8::Local<v8::Object> host,
v8::AccessType type,
v8::Local<v8::Value> data)
{
Frame* target = V8Custom::GetTargetFrame(host, data);
if (target)
ReportUnsafeAccessTo(target, REPORT_LATER);
}
static void HandleFatalErrorInV8()
{
// TODO: We temporarily deal with V8 internal error situations
// such as out-of-memory by crashing the renderer.
CRASH();
}
static void ReportFatalErrorInV8(const char* location, const char* message)
{
// V8 is shutdown, we cannot use V8 api.
// The only thing we can do is to disable JavaScript.
// TODO: clean up V8Proxy and disable JavaScript.
printf("V8 error: %s (%s)\n", message, location);
HandleFatalErrorInV8();
}
V8Proxy::~V8Proxy()
{
clearForClose();
DestroyGlobal();
}
void V8Proxy::DestroyGlobal()
{
if (!m_global.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_global);
#endif
m_global.Dispose();
m_global.Clear();
}
}
bool V8Proxy::DOMObjectHasJSWrapper(void* obj) {
return dom_object_map().contains(obj) ||
active_dom_object_map().contains(obj);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
ASSERT(false);
#undef MAKE_CASE
default: break;
}
#endif
dom_object_map().set(obj, wrapper);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForActiveDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE: break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default: ASSERT(false);
#undef MAKE_CASE
}
#endif
active_dom_object_map().set(obj, wrapper);
}
// The caller must have increased node's ref count.
void V8Proxy::SetJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
dom_node_map().set(node, wrapper);
}
PassRefPtr<EventListener> V8Proxy::createInlineEventListener(
const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#if ENABLE(SVG)
PassRefPtr<EventListener> V8Proxy::createSVGEventHandler(const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#endif
// Event listeners
static V8EventListener* FindEventListenerInList(V8EventListenerList& list,
v8::Local<v8::Value> listener,
bool isInline)
{
ASSERT(v8::Context::InContext());
if (!listener->IsObject())
return 0;
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
V8EventListener* el = *p;
v8::Local<v8::Object> wrapper = el->GetListenerObject();
ASSERT(!wrapper.IsEmpty());
// Since the listener is an object, it is safe to compare for
// strict equality (in the JS sense) by doing a simple equality
// check using the == operator on the handles. This is much,
// much faster than calling StrictEquals through the API in
// the negative case.
if (el->isInline() == isInline && listener == wrapper)
return el;
++p;
}
return 0;
}
// Find an existing wrapper for a JS event listener in the map.
PassRefPtr<V8EventListener> V8Proxy::FindV8EventListener(v8::Local<v8::Value> listener,
bool isInline)
{
return FindEventListenerInList(m_event_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateV8EventListener(v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_event_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8EventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_event_listeners.push_back(new_listener.get());
return new_listener;
}
// Object event listeners (such as XmlHttpRequest and MessagePort) are
// different from listeners on DOM nodes. An object event listener wrapper
// only holds a weak reference to the JS function. A strong reference can
// create a cycle.
//
// The lifetime of these objects is bounded by the life time of its JS
// wrapper. So we can create a hidden reference from the JS wrapper to
// to its JS function.
//
// (map)
// XHR <---------- JS_wrapper
// | (hidden) : ^
// V V : (may reachable by closure)
// V8_listener --------> JS_function
// (weak) <-- may create a cycle if it is strong
//
// The persistent reference is made weak in the constructor
// of V8ObjectEventListener.
PassRefPtr<V8EventListener> V8Proxy::FindObjectEventListener(
v8::Local<v8::Value> listener, bool isInline)
{
return FindEventListenerInList(m_xhr_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateObjectEventListener(
v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_xhr_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8ObjectEventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_xhr_listeners.push_back(new_listener.get());
return new_listener.release();
}
static void RemoveEventListenerFromList(V8EventListenerList& list,
V8EventListener* listener)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
if (*p == listener) {
list.erase(p);
return;
}
++p;
}
}
void V8Proxy::RemoveV8EventListener(V8EventListener* listener)
{
RemoveEventListenerFromList(m_event_listeners, listener);
}
void V8Proxy::RemoveObjectEventListener(V8ObjectEventListener* listener)
{
RemoveEventListenerFromList(m_xhr_listeners, listener);
}
static void DisconnectEventListenersInList(V8EventListenerList& list)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
(*p)->disconnectFrame();
++p;
}
list.clear();
}
void V8Proxy::DisconnectEventListeners()
{
DisconnectEventListenersInList(m_event_listeners);
DisconnectEventListenersInList(m_xhr_listeners);
}
v8::Handle<v8::Script> V8Proxy::CompileScript(v8::Handle<v8::String> code,
const String& fileName,
int baseLine)
{
const uint16_t* fileNameString = FromWebCoreString(fileName);
v8::Handle<v8::String> name =
v8::String::New(fileNameString, fileName.length());
v8::Handle<v8::Integer> line = v8::Integer::New(baseLine);
v8::ScriptOrigin origin(name, line);
v8::Handle<v8::Script> script = v8::Script::Compile(code, &origin);
return script;
}
bool V8Proxy::HandleOutOfMemory()
{
v8::Local<v8::Context> context = v8::Context::GetCurrent();
if (!context->HasOutOfMemoryException())
return false;
// Warning, error, disable JS for this frame?
Frame* frame = V8Proxy::retrieveFrame(context);
V8Proxy* proxy = V8Proxy::retrieve(frame);
// Clean m_context, and event handlers.
proxy->clearForClose();
// Destroy the global object.
proxy->DestroyGlobal();
ChromiumBridge::notifyJSOutOfMemory(frame);
// Disable JS.
Settings* settings = frame->settings();
ASSERT(settings);
settings->setJavaScriptEnabled(false);
return true;
}
v8::Local<v8::Value> V8Proxy::Evaluate(const String& fileName, int baseLine,
const String& str, Node* n)
{
ASSERT(v8::Context::InContext());
// Compile the script.
v8::Local<v8::String> code = v8ExternalString(str);
ChromiumBridge::traceEventBegin("v8.compile", n, "");
v8::Handle<v8::Script> script = CompileScript(code, fileName, baseLine);
ChromiumBridge::traceEventEnd("v8.compile", n, "");
// Set inlineCode to true for <a href="javascript:doSomething()">
// and false for <script>doSomething</script>. For some reason, fileName
// gives us this information.
ChromiumBridge::traceEventBegin("v8.run", n, "");
v8::Local<v8::Value> result = RunScript(script, fileName.isNull());
ChromiumBridge::traceEventEnd("v8.run", n, "");
return result;
}
v8::Local<v8::Value> V8Proxy::RunScript(v8::Handle<v8::Script> script,
bool inline_code)
{
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Compute the source string and prevent against infinite recursion.
if (m_recursion >= 20) {
v8::Local<v8::String> code =
v8ExternalString("throw RangeError('Recursion too deep')");
// TODO(kasperl): Ideally, we should be able to re-use the origin of the
// script passed to us as the argument instead of using an empty string
// and 0 baseLine.
script = CompileScript(code, "", 0);
}
if (HandleOutOfMemory())
ASSERT(script.IsEmpty());
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Save the previous value of the inlineCode flag and update the flag for
// the duration of the script invocation.
bool previous_inline_code = inlineCode();
setInlineCode(inline_code);
// Run the script and keep track of the current recursion depth.
v8::Local<v8::Value> result;
{ ConsoleMessageScope scope;
m_recursion++;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = script->Run();
m_recursion--;
}
if (HandleOutOfMemory())
ASSERT(result.IsEmpty());
// Handle V8 internal error situation (Out-of-memory).
if (result.IsEmpty())
return v8::Local<v8::Value>();
// Restore inlineCode flag.
setInlineCode(previous_inline_code);
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Value> V8Proxy::CallFunction(v8::Handle<v8::Function> function,
v8::Handle<v8::Object> receiver,
int argc,
v8::Handle<v8::Value> args[])
{
// For now, we don't put any artificial limitations on the depth
// of recursion that stems from calling functions. This is in
// contrast to the script evaluations.
v8::Local<v8::Value> result;
{
ConsoleMessageScope scope;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = function->Call(receiver, argc, args);
}
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Persistent<v8::FunctionTemplate> V8Proxy::GetTemplate(
V8ClassIndex::V8WrapperType type)
{
v8::Persistent<v8::FunctionTemplate>* cache_cell =
V8ClassIndex::GetCache(type);
if (!(*cache_cell).IsEmpty())
return *cache_cell;
// not found
FunctionTemplateFactory factory = V8ClassIndex::GetFactory(type);
v8::Persistent<v8::FunctionTemplate> desc = factory();
switch (type) {
case V8ClassIndex::CSSSTYLEDECLARATION:
// The named property handler for style declarations has a
// setter. Therefore, the interceptor has to be on the object
// itself and not on the prototype object.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(CSSStyleDeclaration),
USE_NAMED_PROPERTY_SETTER(CSSStyleDeclaration));
SetCollectionStringOrNullIndexedGetter<CSSStyleDeclaration>(desc);
break;
case V8ClassIndex::CSSRULELIST:
SetCollectionIndexedGetter<CSSRuleList, CSSRule>(desc,
V8ClassIndex::CSSRULE);
break;
case V8ClassIndex::CSSVALUELIST:
SetCollectionIndexedGetter<CSSValueList, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::CSSVARIABLESDECLARATION:
SetCollectionStringOrNullIndexedGetter<CSSVariablesDeclaration>(desc);
break;
case V8ClassIndex::WEBKITCSSTRANSFORMVALUE:
SetCollectionIndexedGetter<WebKitCSSTransformValue, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::UNDETECTABLEHTMLCOLLECTION:
desc->InstanceTemplate()->MarkAsUndetectable(); // fall through
case V8ClassIndex::HTMLCOLLECTION:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
SetCollectionIndexedGetter<HTMLCollection, Node>(desc,
V8ClassIndex::NODE);
break;
case V8ClassIndex::HTMLOPTIONSCOLLECTION:
SetCollectionNamedGetter<HTMLOptionsCollection, Node>(
desc,
V8ClassIndex::NODE);
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLOptionsCollection),
USE_INDEXED_PROPERTY_SETTER(HTMLOptionsCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
break;
case V8ClassIndex::HTMLSELECTELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
NodeCollectionNamedPropertyGetter<HTMLSelectElement>,
0,
0,
0,
0,
v8::Integer::New(V8ClassIndex::NODE));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
NodeCollectionIndexedPropertyGetter<HTMLSelectElement>,
USE_INDEXED_PROPERTY_SETTER(HTMLSelectElementCollection),
0,
0,
NodeCollectionIndexedPropertyEnumerator<HTMLSelectElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::HTMLDOCUMENT: {
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLDocument),
USE_NAMED_PROPERTY_SETTER(HTMLDocument),
0,
USE_NAMED_PROPERTY_DELETER(HTMLDocument));
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
//
// Additionally, we add two extra internal fields for
// HTMLDocuments to implement temporary shadowing of
// document.all. One field holds an object that is used as a
// marker. The other field holds the marker object if
// document.all is not shadowed and some other value if
// document.all is shadowed.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kHTMLDocumentInternalFieldCount);
break;
}
#if ENABLE(SVG)
case V8ClassIndex::SVGDOCUMENT: // fall through
#endif
case V8ClassIndex::DOCUMENT: {
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kDocumentMinimumInternalFieldCount);
break;
}
case V8ClassIndex::HTMLAPPLETELEMENT: // fall through
case V8ClassIndex::HTMLEMBEDELEMENT: // fall through
case V8ClassIndex::HTMLOBJECTELEMENT:
// HTMLAppletElement, HTMLEmbedElement and HTMLObjectElement are
// inherited from HTMLPlugInElement, and they share the same property
// handling code.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLPlugInElement),
USE_NAMED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLPlugInElement),
USE_INDEXED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLPlugInElement));
break;
case V8ClassIndex::HTMLFRAMESETELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFrameSetElement));
break;
case V8ClassIndex::HTMLFORMELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFormElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLFormElement),
0,
0,
0,
NodeCollectionIndexedPropertyEnumerator<HTMLFormElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::CANVASPIXELARRAY:
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(CanvasPixelArray),
USE_INDEXED_PROPERTY_SETTER(CanvasPixelArray));
break;
case V8ClassIndex::STYLESHEET: // fall through
case V8ClassIndex::CSSSTYLESHEET: {
// We add an extra internal field to hold a reference to
// the owner node.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kStyleSheetInternalFieldCount);
break;
}
case V8ClassIndex::MEDIALIST:
SetCollectionStringOrNullIndexedGetter<MediaList>(desc);
break;
case V8ClassIndex::MIMETYPEARRAY:
SetCollectionIndexedAndNamedGetters<MimeTypeArray, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::NAMEDNODEMAP:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NamedNodeMap));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(NamedNodeMap),
0,
0,
0,
CollectionIndexedPropertyEnumerator<NamedNodeMap>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::NODELIST:
SetCollectionIndexedGetter<NodeList, Node>(desc, V8ClassIndex::NODE);
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NodeList));
break;
case V8ClassIndex::PLUGIN:
SetCollectionIndexedAndNamedGetters<Plugin, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::PLUGINARRAY:
SetCollectionIndexedAndNamedGetters<PluginArray, Plugin>(
desc,
V8ClassIndex::PLUGIN);
break;
case V8ClassIndex::STYLESHEETLIST:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(StyleSheetList));
SetCollectionIndexedGetter<StyleSheetList, StyleSheet>(
desc,
V8ClassIndex::STYLESHEET);
break;
case V8ClassIndex::DOMWINDOW: {
v8::Local<v8::Signature> default_signature = v8::Signature::New(desc);
desc->PrototypeTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(DOMWindow));
desc->PrototypeTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(DOMWindow));
desc->SetHiddenPrototype(true);
// Reserve spaces for references to location and navigator objects.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
// Set access check callbacks, but turned off initially.
// When a context is detached from a frame, turn on the access check.
// Turning on checks also invalidates inline caches of the object.
instance_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW),
false);
break;
}
case V8ClassIndex::LOCATION: {
break;
}
case V8ClassIndex::HISTORY: {
break;
}
case V8ClassIndex::MESSAGECHANNEL: {
// Reserve two more internal fields for referencing the port1
// and port2 wrappers. This ensures that the port wrappers are
// kept alive when the channel wrapper is.
desc->SetCallHandler(USE_CALLBACK(MessageChannelConstructor));
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessageChannelInternalFieldCount);
break;
}
case V8ClassIndex::MESSAGEPORT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessagePortInternalFieldCount);
break;
}
// DOMParser, XMLSerializer, and XMLHttpRequest objects are created from
// JS world, but we setup the constructor function lazily in
// WindowNamedPropertyHandler::get.
case V8ClassIndex::DOMPARSER:
desc->SetCallHandler(USE_CALLBACK(DOMParserConstructor));
break;
case V8ClassIndex::XMLSERIALIZER:
desc->SetCallHandler(USE_CALLBACK(XMLSerializerConstructor));
break;
case V8ClassIndex::XMLHTTPREQUEST: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(XMLHttpRequestConstructor));
break;
}
case V8ClassIndex::XMLHTTPREQUESTUPLOAD: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
break;
}
case V8ClassIndex::XPATHEVALUATOR:
desc->SetCallHandler(USE_CALLBACK(XPathEvaluatorConstructor));
break;
case V8ClassIndex::XSLTPROCESSOR:
desc->SetCallHandler(USE_CALLBACK(XSLTProcessorConstructor));
break;
default:
break;
}
*cache_cell = desc;
return desc;
}
bool V8Proxy::ContextInitialized()
{
return !m_context.IsEmpty();
}
DOMWindow* V8Proxy::retrieveWindow()
{
// TODO: This seems very fragile. How do we know that the global object
// from the current context is something sensible? Do we need to use the
// last entered here? Who calls this?
return retrieveWindow(v8::Context::GetCurrent());
}
DOMWindow* V8Proxy::retrieveWindow(v8::Handle<v8::Context> context)
{
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
return ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, global);
}
Frame* V8Proxy::retrieveFrame(v8::Handle<v8::Context> context)
{
return retrieveWindow(context)->frame();
}
Frame* V8Proxy::retrieveActiveFrame()
{
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return 0;
return retrieveFrame(context);
}
Frame* V8Proxy::retrieveFrame()
{
DOMWindow* window = retrieveWindow();
return window ? window->frame() : 0;
}
V8Proxy* V8Proxy::retrieve()
{
DOMWindow* window = retrieveWindow();
ASSERT(window);
return retrieve(window->frame());
}
V8Proxy* V8Proxy::retrieve(Frame* frame)
{
if (!frame)
return 0;
return frame->script()->isEnabled() ? frame->script()->proxy() : 0;
}
V8Proxy* V8Proxy::retrieve(ScriptExecutionContext* context)
{
if (!context->isDocument())
return 0;
return retrieve(static_cast<Document*>(context)->frame());
}
void V8Proxy::disconnectFrame()
{
// disconnect all event listeners
DisconnectEventListeners();
// remove all timeouts
if (m_frame->domWindow())
m_frame->domWindow()->clearAllTimeouts();
}
bool V8Proxy::isEnabled()
{
Settings* settings = m_frame->settings();
if (!settings)
return false;
// In the common case, JavaScript is enabled and we're done.
if (settings->isJavaScriptEnabled())
return true;
// If JavaScript has been disabled, we need to look at the frame to tell
// whether this script came from the web or the embedder. Scripts from the
// embedder are safe to run, but scripts from the other sources are
// disallowed.
Document* document = m_frame->document();
if (!document)
return false;
SecurityOrigin* origin = document->securityOrigin();
if (origin->protocol().isEmpty())
return false; // Uninitialized document
if (origin->protocol() == "http" || origin->protocol() == "https")
return false; // Web site
if (origin->protocol() == ChromiumBridge::uiResourceProtocol())
return true; // Embedder's scripts are ok to run
// If the scheme is ftp: or file:, an empty file name indicates a directory
// listing, which requires JavaScript to function properly.
const char* kDirProtocols[] = { "ftp", "file" };
for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
if (origin->protocol() == kDirProtocols[i]) {
const KURL& url = document->url();
return url.pathAfterLastSlash() == url.pathEnd();
}
}
return false; // Other protocols fall through to here
}
// static
void V8Proxy::DomainChanged(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
// Restore to default security token.
proxy->m_context->UseDefaultSecurityToken();
}
void V8Proxy::UpdateDocumentWrapper(v8::Handle<v8::Value> wrapper) {
ClearDocumentWrapper();
ASSERT(m_document.IsEmpty());
m_document = v8::Persistent<v8::Value>::New(wrapper);
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_document);
#endif
}
void V8Proxy::ClearDocumentWrapper()
{
if (!m_document.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_document);
#endif
m_document.Dispose();
m_document.Clear();
}
}
void V8Proxy::clearForClose()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle_scope;
ClearDocumentWrapper();
m_context.Dispose();
m_context.Clear();
}
}
void V8Proxy::clearForNavigation()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle;
ClearDocumentWrapper();
v8::Context::Scope context_scope(m_context);
// Turn on access check on the old DOMWindow wrapper.
v8::Handle<v8::Object> wrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, m_global);
ASSERT(!wrapper.IsEmpty());
wrapper->TurnOnAccessCheck();
// Clear all timeouts.
DOMWindow* domWindow =
ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, wrapper);
domWindow->clearAllTimeouts();
// disconnect all event listeners
DisconnectEventListeners();
// Separate the context from its global object.
m_context->DetachGlobal();
m_context.Dispose();
m_context.Clear();
// Reinitialize the context so the global object points to
// the new DOM window.
initContextIfNeeded();
}
}
void V8Proxy::SetSecurityToken() {
Document* document = m_frame->document();
// Setup security origin and security token
if (!document) {
m_context->UseDefaultSecurityToken();
return;
}
// Ask the document's SecurityOrigin to generate a security token.
// If two tokens are equal, then the SecurityOrigins canAccess each other.
// If two tokens are not equal, then we have to call canAccess.
// Note: we can't use the HTTPOrigin if it was set from the DOM.
SecurityOrigin* origin = document->securityOrigin();
String token;
if (!origin->domainWasSetInDOM())
token = document->securityOrigin()->toString();
// An empty token means we always have to call canAccess. In this case, we
// use the global object as the security token to avoid calling canAccess
// when a script accesses its own objects.
if (token.isEmpty()) {
m_context->UseDefaultSecurityToken();
return;
}
CString utf8_token = token.utf8();
// NOTE: V8 does identity comparison in fast path, must use a symbol
// as the security token.
m_context->SetSecurityToken(
v8::String::NewSymbol(utf8_token.data(), utf8_token.length()));
}
void V8Proxy::updateDocument()
{
if (!m_frame->document())
return;
if (m_global.IsEmpty()) {
ASSERT(m_context.IsEmpty());
return;
}
{
v8::HandleScope scope;
SetSecurityToken();
}
}
// Check if the current execution context can access a target frame.
// First it checks same domain policy using the lexical context
//
// This is equivalent to KJS::Window::allowsAccessFrom(ExecState*, String&).
bool V8Proxy::CanAccessPrivate(DOMWindow* target_window)
{
ASSERT(target_window);
String message;
DOMWindow* origin_window = retrieveWindow();
if (origin_window == target_window)
return true;
if (!origin_window)
return false;
// JS may be attempting to access the "window" object, which should be
// valid, even if the document hasn't been constructed yet.
// If the document doesn't exist yet allow JS to access the window object.
if (!origin_window->document())
return true;
const SecurityOrigin* active_security_origin = origin_window->securityOrigin();
const SecurityOrigin* target_security_origin = target_window->securityOrigin();
String ui_resource_protocol = ChromiumBridge::uiResourceProtocol();
if (active_security_origin->protocol() == ui_resource_protocol) {
KURL inspector_url = ChromiumBridge::inspectorURL();
ASSERT(inspector_url.protocol() == ui_resource_protocol);
ASSERT(inspector_url.protocol().endsWith("-resource"));
// The Inspector can access anything.
if (active_security_origin->host() == inspector_url.host())
return true;
// To mitigate XSS vulnerabilities on the browser itself, UI resources
// besides the Inspector can't access other documents.
return false;
}
if (active_security_origin->canAccess(target_security_origin))
return true;
// Allow access to a "about:blank" page if the dynamic context is a
// detached context of the same frame as the blank page.
if (target_security_origin->isEmpty() &&
origin_window->frame() == target_window->frame())
return true;
return false;
}
bool V8Proxy::CanAccessFrame(Frame* target, bool report_error)
{
// The subject is detached from a frame, deny accesses.
if (!target)
return false;
if (!CanAccessPrivate(target->domWindow())) {
if (report_error)
ReportUnsafeAccessTo(target, REPORT_NOW);
return false;
}
return true;
}
bool V8Proxy::CheckNodeSecurity(Node* node)
{
if (!node)
return false;
Frame* target = node->document()->frame();
if (!target)
return false;
return CanAccessFrame(target, true);
}
// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance. However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object. The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript. The javascript object that corresponds to a
// DOMWindow instance is the shadow object. When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
//
// To implement split-window, see
// 1) https://bugs.webkit.org/show_bug.cgi?id=17249
// 2) https://wiki.mozilla.org/Gecko:SplitWindow
// 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
// we need to split the shadow object further into two objects:
// an outer window and an inner window. The inner window is the hidden
// prototype of the outer window. The inner window is the default
// global object of the context. A variable declared in the global
// scope is a property of the inner window.
//
// The outer window sticks to a Frame, it is exposed to JavaScript
// via window.window, window.self, window.parent, etc. The outer window
// has a security token which is the domain. The outer window cannot
// have its own properties. window.foo = 'x' is delegated to the
// inner window.
//
// When a frame navigates to a new page, the inner window is cut off
// the outer window, and the outer window identify is preserved for
// the frame. However, a new inner window is created for the new page.
// If there are JS code holds a closure to the old inner window,
// it won't be able to reach the outer window via its global object.
void V8Proxy::initContextIfNeeded()
{
// Bail out if the context has already been initialized.
if (!m_context.IsEmpty())
return;
// Install counters handler with V8.
static bool v8_counters_initialized = false;
if (!v8_counters_initialized) {
ChromiumBridge::initV8CounterFunction();
v8_counters_initialized = true;
}
// Setup the security handlers and message listener. This only has
// to be done once.
static bool v8_initialized = false;
if (!v8_initialized) {
v8_initialized = true;
// Tells V8 not to call the default OOM handler, binding code
// will handle it.
v8::V8::IgnoreOutOfMemoryException();
v8::V8::SetFatalErrorHandler(ReportFatalErrorInV8);
v8::V8::SetGlobalGCPrologueCallback(&GCPrologue);
v8::V8::SetGlobalGCEpilogueCallback(&GCEpilogue);
v8::V8::AddMessageListener(HandleConsoleMessage);
v8::V8::SetFailedAccessCheckCallbackFunction(ReportUnsafeJavaScriptAccess);
}
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Persistent<v8::ObjectTemplate> global_template =
V8DOMWindow::GetShadowObjectTemplate();
if (global_template.IsEmpty())
return;
// Install a security handler with V8.
global_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
if (ScriptController::shouldExposeGCController()) {
v8::RegisterExtension(new v8::Extension("v8/GCController",
"(function v8_GCController() {"
" var v8_gc;"
" if (gc) v8_gc = gc;"
" GCController = new Object();"
" GCController.collect ="
" function() {if (v8_gc) v8_gc(); };"
" })()"));
const char* extension_names[] = { "v8/GCController" };
v8::ExtensionConfiguration extensions(1, extension_names);
// Create a new context.
m_context = v8::Context::New(&extensions, global_template, m_global);
} else {
m_context = v8::Context::New(NULL, global_template, m_global);
}
if (m_context.IsEmpty())
return;
// Starting from now, use local context only.
v8::Local<v8::Context> context = GetContext();
v8::Context::Scope scope(context);
// Store the first global object created so we can reuse it.
if (m_global.IsEmpty()) {
m_global = v8::Persistent<v8::Object>::New(context->Global());
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_global);
#endif
}
// Create a new JS window object and use it as the prototype for the
// shadow global object.
v8::Persistent<v8::FunctionTemplate> window_descriptor =
GetTemplate(V8ClassIndex::DOMWINDOW);
v8::Local<v8::Object> js_window =
SafeAllocation::NewInstance(window_descriptor->GetFunction());
if (js_window.IsEmpty())
return;
DOMWindow* window = m_frame->domWindow();
// Wrap the window.
SetDOMWrapper(js_window,
V8ClassIndex::ToInt(V8ClassIndex::DOMWINDOW),
window);
window->ref();
V8Proxy::SetJSWrapperForDOMObject(window,
v8::Persistent<v8::Object>::New(js_window));
// Insert the window instance as the prototype of the shadow object.
v8::Handle<v8::Object> v8_global = context->Global();
v8_global->Set(v8::String::New("__proto__"), js_window);
SetSecurityToken();
m_frame->loader()->dispatchWindowObjectAvailable();
if (ScriptController::RecordPlaybackMode()) {
// Inject code which overrides a few common JS functions for implementing
// randomness. In order to implement effective record & playback of
// websites, it is important that the URLs not change. Many popular web
// based apps use randomness in URLs to unique-ify urls for proxies.
// Unfortunately, this breaks playback.
// To work around this, we take the two most common client-side randomness
// generators and make them constant. They really need to be constant
// (rather than a constant seed followed by constant change)
// because the playback mode wants flexibility in how it plays them back
// and cannot always guarantee that requests for randomness are played back
// in exactly the same order in which they were recorded.
String script(
"Math.random = function() { return 0.5; };"
"__ORIGDATE__ = Date;"
"Date.__proto__.now = function() { "
" return new __ORIGDATE__(1204251968254); };"
"Date = function() { return Date.now(); };");
this->Evaluate(String(), 0, script, 0);
}
}
void V8Proxy::SetDOMException(int exception_code)
{
if (exception_code <= 0)
return;
ExceptionCodeDescription description;
getExceptionCodeDescription(exception_code, description);
v8::Handle<v8::Value> exception;
switch (description.type) {
case DOMExceptionType:
exception = ToV8Object(V8ClassIndex::DOMCOREEXCEPTION,
DOMCoreException::create(description));
break;
case RangeExceptionType:
exception = ToV8Object(V8ClassIndex::RANGEEXCEPTION,
RangeException::create(description));
break;
case EventExceptionType:
exception = ToV8Object(V8ClassIndex::EVENTEXCEPTION,
EventException::create(description));
break;
case XMLHttpRequestExceptionType:
exception = ToV8Object(V8ClassIndex::XMLHTTPREQUESTEXCEPTION,
XMLHttpRequestException::create(description));
break;
#if ENABLE(SVG)
case SVGExceptionType:
exception = ToV8Object(V8ClassIndex::SVGEXCEPTION,
SVGException::create(description));
break;
#endif
#if ENABLE(XPATH)
case XPathExceptionType:
exception = ToV8Object(V8ClassIndex::XPATHEXCEPTION,
XPathException::create(description));
break;
#endif
}
ASSERT(!exception.IsEmpty());
v8::ThrowException(exception);
}
v8::Handle<v8::Value> V8Proxy::ThrowError(ErrorType type, const char* message)
{
switch (type) {
case RANGE_ERROR:
return v8::ThrowException(v8::Exception::RangeError(v8String(message)));
case REFERENCE_ERROR:
return v8::ThrowException(
v8::Exception::ReferenceError(v8String(message)));
case SYNTAX_ERROR:
return v8::ThrowException(v8::Exception::SyntaxError(v8String(message)));
case TYPE_ERROR:
return v8::ThrowException(v8::Exception::TypeError(v8String(message)));
case GENERAL_ERROR:
return v8::ThrowException(v8::Exception::Error(v8String(message)));
default:
ASSERT(false);
return v8::Handle<v8::Value>();
}
}
v8::Local<v8::Context> V8Proxy::GetContext(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
if (!proxy)
return v8::Local<v8::Context>();
proxy->initContextIfNeeded();
return proxy->GetContext();
}
v8::Local<v8::Context> V8Proxy::GetCurrentContext()
{
return v8::Context::GetCurrent();
}
v8::Handle<v8::Value> V8Proxy::ToV8Object(V8ClassIndex::V8WrapperType type, void* imp)
{
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(type != V8ClassIndex::EVENT);
bool is_active_dom_object = false;
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
return NodeToV8Object(static_cast<Node*>(imp));
case V8ClassIndex::CSSVALUE:
return CSSValueToV8Object(static_cast<CSSValue*>(imp));
case V8ClassIndex::CSSRULE:
return CSSRuleToV8Object(static_cast<CSSRule*>(imp));
case V8ClassIndex::STYLESHEET:
return StyleSheetToV8Object(static_cast<StyleSheet*>(imp));
case V8ClassIndex::DOMWINDOW:
return WindowToV8Object(static_cast<DOMWindow*>(imp));
#if ENABLE(SVG)
SVG_NONNODE_TYPES(MAKE_CASE)
if (type == V8ClassIndex::SVGELEMENTINSTANCE)
return SVGElementInstanceToV8Object(static_cast<SVGElementInstance*>(imp));
return SVGObjectWithContextToV8Object(type, imp);
#endif
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
is_active_dom_object = true;
break;
default:
break;
}
#undef MAKE_CASE
if (!imp) return v8::Null();
// Non DOM node
v8::Persistent<v8::Object> result = is_active_dom_object ?
active_dom_object_map().get(imp) :
dom_object_map().get(imp);
if (result.IsEmpty()) {
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, imp);
if (!v8obj.IsEmpty()) {
// Go through big switch statement, it has some duplications
// that were handled by code above (such as CSSVALUE, CSSRULE, etc).
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(imp)->ref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
result = v8::Persistent<v8::Object>::New(v8obj);
if (is_active_dom_object)
SetJSWrapperForActiveDOMObject(imp, result);
else
SetJSWrapperForDOMObject(imp, result);
// Special case for Location and Navigator. Both Safari and FF let
// Location and Navigator JS wrappers survive GC. To mimic their
// behaviors, V8 creates hidden references from the DOMWindow to
// location and navigator objects. These references get cleared
// when the DOMWindow is reused by a new page.
if (type == V8ClassIndex::LOCATION) {
SetHiddenWindowReference(static_cast<Location*>(imp)->frame(),
V8Custom::kDOMWindowLocationIndex, result);
} else if (type == V8ClassIndex::NAVIGATOR) {
SetHiddenWindowReference(static_cast<Navigator*>(imp)->frame(),
V8Custom::kDOMWindowNavigatorIndex, result);
}
}
}
return result;
}
void V8Proxy::SetHiddenWindowReference(Frame* frame,
const int internal_index,
v8::Handle<v8::Object> jsobj)
{
// Get DOMWindow
if (!frame) return; // Object might be detached from window
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty()) return;
ASSERT(internal_index < V8Custom::kDOMWindowInternalFieldCount);
v8::Handle<v8::Object> global = context->Global();
// Look for real DOM wrapper.
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
ASSERT(global->GetInternalField(internal_index)->IsUndefined());
global->SetInternalField(internal_index, jsobj);
}
V8ClassIndex::V8WrapperType V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object> object)
{
ASSERT(MaybeDOMWrapper(object));
v8::Handle<v8::Value> type =
object->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
return V8ClassIndex::FromInt(type->Int32Value());
}
void* V8Proxy::ToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
v8::Handle<v8::Value> object)
{
// Native event listener is per frame, it cannot be handled
// by this generic function.
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(MaybeDOMWrapper(object));
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
ASSERT(false);
return NULL;
case V8ClassIndex::XMLHTTPREQUEST:
return DOMWrapperToNative<XMLHttpRequest>(object);
case V8ClassIndex::EVENT:
return DOMWrapperToNative<Event>(object);
case V8ClassIndex::CSSRULE:
return DOMWrapperToNative<CSSRule>(object);
default:
break;
}
#undef MAKE_CASE
return DOMWrapperToNative<void>(object);
}
v8::Handle<v8::Object> V8Proxy::LookupDOMWrapper(
V8ClassIndex::V8WrapperType type, v8::Handle<v8::Value> value)
{
if (value.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::FunctionTemplate> desc = V8Proxy::GetTemplate(type);
while (value->IsObject()) {
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
if (desc->HasInstance(object))
return object;
value = object->GetPrototype();
}
return v8::Handle<v8::Object>();
}
PassRefPtr<NodeFilter> V8Proxy::ToNativeNodeFilter(v8::Handle<v8::Value> filter)
{
// A NodeFilter is used when walking through a DOM tree or iterating tree
// nodes.
// TODO: we may want to cache NodeFilterCondition and NodeFilter
// object, but it is minor.
// NodeFilter is passed to NodeIterator that has a ref counted pointer
// to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
// In NodeFilterCondition, filter object is persisted in its constructor,
// and disposed in its destructor.
if (!filter->IsFunction())
return 0;
NodeFilterCondition* cond = new V8NodeFilterCondition(filter);
return NodeFilter::create(cond);
}
v8::Local<v8::Object> V8Proxy::InstantiateV8Object(
V8ClassIndex::V8WrapperType desc_type,
V8ClassIndex::V8WrapperType cptr_type,
void* imp)
{
// Make a special case for document.all
if (desc_type == V8ClassIndex::HTMLCOLLECTION &&
static_cast<HTMLCollection*>(imp)->type() == HTMLCollection::DocAll) {
desc_type = V8ClassIndex::UNDETECTABLEHTMLCOLLECTION;
}
v8::Persistent<v8::FunctionTemplate> desc = GetTemplate(desc_type);
v8::Local<v8::Function> function = desc->GetFunction();
v8::Local<v8::Object> instance = SafeAllocation::NewInstance(function);
if (!instance.IsEmpty()) {
// Avoid setting the DOM wrapper for failed allocations.
SetDOMWrapper(instance, V8ClassIndex::ToInt(cptr_type), imp);
}
return instance;
}
v8::Handle<v8::Value> V8Proxy::CheckNewLegal(const v8::Arguments& args)
{
if (!AllowAllocation::m_current)
return ThrowError(TYPE_ERROR, "Illegal constructor");
return args.This();
}
void V8Proxy::SetDOMWrapper(v8::Handle<v8::Object> obj, int type, void* cptr)
{
ASSERT(obj->InternalFieldCount() >= 2);
obj->SetInternalField(V8Custom::kDOMWrapperObjectIndex, WrapCPointer(cptr));
obj->SetInternalField(V8Custom::kDOMWrapperTypeIndex, v8::Integer::New(type));
}
#ifndef NDEBUG
bool V8Proxy::MaybeDOMWrapper(v8::Handle<v8::Value> value)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
return true;
}
#endif
bool V8Proxy::IsDOMEventWrapper(v8::Handle<v8::Value> value)
{
// All kinds of events use EVENT as dom type in JS wrappers.
// See EventToV8Object
return IsWrapperOfType(value, V8ClassIndex::EVENT);
}
bool V8Proxy::IsWrapperOfType(v8::Handle<v8::Value> value,
V8ClassIndex::V8WrapperType classType)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
return V8ClassIndex::FromInt(type->Int32Value()) == classType;
}
#if ENABLE(VIDEO)
#define FOR_EACH_VIDEO_TAG(macro) \
macro(audio, AUDIO) \
macro(source, SOURCE) \
macro(video, VIDEO)
#else
#define FOR_EACH_VIDEO_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
macro(a, ANCHOR) \
macro(applet, APPLET) \
macro(area, AREA) \
macro(base, BASE) \
macro(basefont, BASEFONT) \
macro(blockquote, BLOCKQUOTE) \
macro(body, BODY) \
macro(br, BR) \
macro(button, BUTTON) \
macro(caption, TABLECAPTION) \
macro(col, TABLECOL) \
macro(colgroup, TABLECOL) \
macro(del, MOD) \
macro(canvas, CANVAS) \
macro(dir, DIRECTORY) \
macro(div, DIV) \
macro(dl, DLIST) \
macro(embed, EMBED) \
macro(fieldset, FIELDSET) \
macro(font, FONT) \
macro(form, FORM) \
macro(frame, FRAME) \
macro(frameset, FRAMESET) \
macro(h1, HEADING) \
macro(h2, HEADING) \
macro(h3, HEADING) \
macro(h4, HEADING) \
macro(h5, HEADING) \
macro(h6, HEADING) \
macro(head, HEAD) \
macro(hr, HR) \
macro(html, HTML) \
macro(img, IMAGE) \
macro(iframe, IFRAME) \
macro(image, IMAGE) \
macro(input, INPUT) \
macro(ins, MOD) \
macro(isindex, ISINDEX) \
macro(keygen, SELECT) \
macro(label, LABEL) \
macro(legend, LEGEND) \
macro(li, LI) \
macro(link, LINK) \
macro(listing, PRE) \
macro(map, MAP) \
macro(marquee, MARQUEE) \
macro(menu, MENU) \
macro(meta, META) \
macro(object, OBJECT) \
macro(ol, OLIST) \
macro(optgroup, OPTGROUP) \
macro(option, OPTION) \
macro(p, PARAGRAPH) \
macro(param, PARAM) \
macro(pre, PRE) \
macro(q, QUOTE) \
macro(script, SCRIPT) \
macro(select, SELECT) \
macro(style, STYLE) \
macro(table, TABLE) \
macro(thead, TABLESECTION) \
macro(tbody, TABLESECTION) \
macro(tfoot, TABLESECTION) \
macro(td, TABLECELL) \
macro(th, TABLECELL) \
macro(tr, TABLEROW) \
macro(textarea, TEXTAREA) \
macro(title, TITLE) \
macro(ul, ULIST) \
macro(xmp, PRE) \
FOR_EACH_VIDEO_TAG(macro)
V8ClassIndex::V8WrapperType V8Proxy::GetHTMLElementType(HTMLElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::HTML##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0)
return V8ClassIndex::HTMLELEMENT;
return t;
}
#undef FOR_EACH_TAG
#if ENABLE(SVG)
#if ENABLE(SVG_ANIMATION)
#define FOR_EACH_ANIMATION_TAG(macro) \
macro(animateColor, ANIMATECOLOR) \
macro(animate, ANIMATE) \
macro(animateTransform, ANIMATETRANSFORM) \
macro(set, SET)
#else
#define FOR_EACH_ANIMATION_TAG(macro)
#endif
#if ENABLE(SVG_FILTERS)
#define FOR_EACH_FILTERS_TAG(macro) \
macro(feBlend, FEBLEND) \
macro(feColorMatrix, FECOLORMATRIX) \
macro(feComponentTransfer, FECOMPONENTTRANSFER) \
macro(feComposite, FECOMPOSITE) \
macro(feDiffuseLighting, FEDIFFUSELIGHTING) \
macro(feDisplacementMap, FEDISPLACEMENTMAP) \
macro(feDistantLight, FEDISTANTLIGHT) \
macro(feFlood, FEFLOOD) \
macro(feFuncA, FEFUNCA) \
macro(feFuncB, FEFUNCB) \
macro(feFuncG, FEFUNCG) \
macro(feFuncR, FEFUNCR) \
macro(feGaussianBlur, FEGAUSSIANBLUR) \
macro(feImage, FEIMAGE) \
macro(feMerge, FEMERGE) \
macro(feMergeNode, FEMERGENODE) \
macro(feOffset, FEOFFSET) \
macro(fePointLight, FEPOINTLIGHT) \
macro(feSpecularLighting, FESPECULARLIGHTING) \
macro(feSpotLight, FESPOTLIGHT) \
macro(feTile, FETILE) \
macro(feTurbulence, FETURBULENCE) \
macro(filter, FILTER)
#else
#define FOR_EACH_FILTERS_TAG(macro)
#endif
#if ENABLE(SVG_FONTS)
#define FOR_EACH_FONTS_TAG(macro) \
macro(definition-src, DEFINITIONSRC) \
macro(font-face, FONTFACE) \
macro(font-face-format, FONTFACEFORMAT) \
macro(font-face-name, FONTFACENAME) \
macro(font-face-src, FONTFACESRC) \
macro(font-face-uri, FONTFACEURI)
#else
#define FOR_EACH_FONTS_TAG(marco)
#endif
#if ENABLE(SVG_FOREIGN_OBJECT)
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
macro(foreignObject, FOREIGNOBJECT)
#else
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro)
#endif
#if ENABLE(SVG_USE)
#define FOR_EACH_USE_TAG(macro) \
macro(use, USE)
#else
#define FOR_EACH_USE_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
FOR_EACH_ANIMATION_TAG(macro) \
FOR_EACH_FILTERS_TAG(macro) \
FOR_EACH_FONTS_TAG(macro) \
FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
FOR_EACH_USE_TAG(macro) \
macro(a, A) \
macro(altGlyph, ALTGLYPH) \
macro(circle, CIRCLE) \
macro(clipPath, CLIPPATH) \
macro(cursor, CURSOR) \
macro(defs, DEFS) \
macro(desc, DESC) \
macro(ellipse, ELLIPSE) \
macro(g, G) \
macro(glyph, GLYPH) \
macro(image, IMAGE) \
macro(linearGradient, LINEARGRADIENT) \
macro(line, LINE) \
macro(marker, MARKER) \
macro(mask, MASK) \
macro(metadata, METADATA) \
macro(path, PATH) \
macro(pattern, PATTERN) \
macro(polyline, POLYLINE) \
macro(polygon, POLYGON) \
macro(radialGradient, RADIALGRADIENT) \
macro(rect, RECT) \
macro(script, SCRIPT) \
macro(stop, STOP) \
macro(style, STYLE) \
macro(svg, SVG) \
macro(switch, SWITCH) \
macro(symbol, SYMBOL) \
macro(text, TEXT) \
macro(textPath, TEXTPATH) \
macro(title, TITLE) \
macro(tref, TREF) \
macro(tspan, TSPAN) \
macro(view, VIEW) \
// end of macro
V8ClassIndex::V8WrapperType V8Proxy::GetSVGElementType(SVGElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::SVG##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0) return V8ClassIndex::SVGELEMENT;
return t;
}
#undef FOR_EACH_TAG
#endif // ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::EventToV8Object(Event* event)
{
if (!event)
return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(event);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT;
if (event->isUIEvent()) {
if (event->isKeyboardEvent())
type = V8ClassIndex::KEYBOARDEVENT;
else if (event->isTextEvent())
type = V8ClassIndex::TEXTEVENT;
else if (event->isMouseEvent())
type = V8ClassIndex::MOUSEEVENT;
else if (event->isWheelEvent())
type = V8ClassIndex::WHEELEVENT;
#if ENABLE(SVG)
else if (event->isSVGZoomEvent())
type = V8ClassIndex::SVGZOOMEVENT;
#endif
else
type = V8ClassIndex::UIEVENT;
} else if (event->isMutationEvent())
type = V8ClassIndex::MUTATIONEVENT;
else if (event->isOverflowEvent())
type = V8ClassIndex::OVERFLOWEVENT;
else if (event->isMessageEvent())
type = V8ClassIndex::MESSAGEEVENT;
else if (event->isProgressEvent()) {
if (event->isXMLHttpRequestProgressEvent())
type = V8ClassIndex::XMLHTTPREQUESTPROGRESSEVENT;
else
type = V8ClassIndex::PROGRESSEVENT;
} else if (event->isWebKitAnimationEvent())
type = V8ClassIndex::WEBKITANIMATIONEVENT;
else if (event->isWebKitTransitionEvent())
type = V8ClassIndex::WEBKITTRANSITIONEVENT;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::EVENT, event);
if (result.IsEmpty()) {
// Instantiation failed. Avoid updating the DOM object map and
// return null which is already handled by callers of this function
// in case the event is NULL.
return v8::Null();
}
event->ref(); // fast ref
SetJSWrapperForDOMObject(event, v8::Persistent<v8::Object>::New(result));
return result;
}
// Caller checks node is not null.
v8::Handle<v8::Value> V8Proxy::NodeToV8Object(Node* node)
{
if (!node) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_node_map().get(node);
if (!wrapper.IsEmpty())
return wrapper;
bool is_document = false; // document type node has special handling
V8ClassIndex::V8WrapperType type;
switch (node->nodeType()) {
case Node::ELEMENT_NODE:
if (node->isHTMLElement())
type = GetHTMLElementType(static_cast<HTMLElement*>(node));
#if ENABLE(SVG)
else if (node->isSVGElement())
type = GetSVGElementType(static_cast<SVGElement*>(node));
#endif
else
type = V8ClassIndex::ELEMENT;
break;
case Node::ATTRIBUTE_NODE:
type = V8ClassIndex::ATTR;
break;
case Node::TEXT_NODE:
type = V8ClassIndex::TEXT;
break;
case Node::CDATA_SECTION_NODE:
type = V8ClassIndex::CDATASECTION;
break;
case Node::ENTITY_NODE:
type = V8ClassIndex::ENTITY;
break;
case Node::PROCESSING_INSTRUCTION_NODE:
type = V8ClassIndex::PROCESSINGINSTRUCTION;
break;
case Node::COMMENT_NODE:
type = V8ClassIndex::COMMENT;
break;
case Node::DOCUMENT_NODE: {
is_document = true;
Document* doc = static_cast<Document*>(node);
if (doc->isHTMLDocument())
type = V8ClassIndex::HTMLDOCUMENT;
#if ENABLE(SVG)
else if (doc->isSVGDocument())
type = V8ClassIndex::SVGDOCUMENT;
#endif
else
type = V8ClassIndex::DOCUMENT;
break;
}
case Node::DOCUMENT_TYPE_NODE:
type = V8ClassIndex::DOCUMENTTYPE;
break;
case Node::NOTATION_NODE:
type = V8ClassIndex::NOTATION;
break;
case Node::DOCUMENT_FRAGMENT_NODE:
type = V8ClassIndex::DOCUMENTFRAGMENT;
break;
case Node::ENTITY_REFERENCE_NODE:
type = V8ClassIndex::ENTITYREFERENCE;
break;
default:
type = V8ClassIndex::NODE;
}
// Find the context to which the node belongs and create the wrapper
// in that context. If the node is not in a document, the current
// context is used.
v8::Local<v8::Context> context;
Document* doc = node->document();
if (doc) {
context = V8Proxy::GetContext(doc->frame());
}
if (!context.IsEmpty()) {
context->Enter();
}
v8::Local<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::NODE, node);
// Exit the node's context if it was entered.
if (!context.IsEmpty()) {
context->Exit();
}
if (result.IsEmpty()) {
// If instantiation failed it's important not to add the result
// to the DOM node map. Instead we return an empty handle, which
// should already be handled by callers of this function in case
// the node is NULL.
return result;
}
node->ref();
SetJSWrapperForDOMNode(node, v8::Persistent<v8::Object>::New(result));
if (is_document) {
Document* doc = static_cast<Document*>(node);
V8Proxy* proxy = V8Proxy::retrieve(doc->frame());
if (proxy)
proxy->UpdateDocumentWrapper(result);
if (type == V8ClassIndex::HTMLDOCUMENT) {
// Create marker object and insert it in two internal fields.
// This is used to implement temporary shadowing of
// document.all.
ASSERT(result->InternalFieldCount() ==
V8Custom::kHTMLDocumentInternalFieldCount);
v8::Local<v8::Object> marker = v8::Object::New();
result->SetInternalField(V8Custom::kHTMLDocumentMarkerIndex, marker);
result->SetInternalField(V8Custom::kHTMLDocumentShadowIndex, marker);
}
}
return result;
}
// A JS object of type EventTarget can only be five possible types:
// 1) EventTargetNode; 2) XMLHttpRequest; 3) MessagePort; 4) SVGElementInstance;
// 5) XMLHttpRequestUpload
// check EventTarget.h for new type conversion methods
// also make sure to sync with V8EventListener::GetThisObject (v8_events.cpp)
v8::Handle<v8::Value> V8Proxy::EventTargetToV8Object(EventTarget* target)
{
if (!target)
return v8::Null();
#if ENABLE(SVG)
SVGElementInstance* instance = target->toSVGElementInstance();
if (instance)
return ToV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
#endif
Node* node = target->toNode();
if (node)
return NodeToV8Object(node);
// XMLHttpRequest is created within its JS counterpart.
XMLHttpRequest* xhr = target->toXMLHttpRequest();
if (xhr) {
v8::Handle<v8::Object> wrapper = active_dom_object_map().get(xhr);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
// MessagePort is created within its JS counterpart
MessagePort* port = target->toMessagePort();
if (port) {
v8::Handle<v8::Object> wrapper = active_dom_object_map().get(port);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload();
if (upload) {
v8::Handle<v8::Object> wrapper = dom_object_map().get(upload);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
ASSERT(0);
return v8::Handle<v8::Value>();
}
v8::Handle<v8::Value> V8Proxy::EventListenerToV8Object(
EventListener* listener)
{
if (listener == 0) return v8::Null();
// TODO(fqian): can a user take a lazy event listener and set to other places?
V8AbstractEventListener* v8listener =
static_cast<V8AbstractEventListener*>(listener);
return v8listener->GetListenerObject();
}
v8::Handle<v8::Value> V8Proxy::DOMImplementationToV8Object(
DOMImplementation* impl)
{
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::DOMIMPLEMENTATION,
V8ClassIndex::DOMIMPLEMENTATION,
impl);
if (result.IsEmpty()) {
// If the instantiation failed, we ignore it and return null instead
// of returning an empty handle.
return v8::Null();
}
return result;
}
v8::Handle<v8::Value> V8Proxy::StyleSheetToV8Object(StyleSheet* sheet)
{
if (!sheet) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(sheet);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::STYLESHEET;
if (sheet->isCSSStyleSheet())
type = V8ClassIndex::CSSSTYLESHEET;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::STYLESHEET, sheet);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
sheet->ref();
SetJSWrapperForDOMObject(sheet, v8::Persistent<v8::Object>::New(result));
}
// Add a hidden reference from stylesheet object to its owner node.
Node* owner_node = sheet->ownerNode();
if (owner_node) {
v8::Handle<v8::Object> owner =
v8::Handle<v8::Object>::Cast(NodeToV8Object(owner_node));
result->SetInternalField(V8Custom::kStyleSheetOwnerNodeIndex, owner);
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSValueToV8Object(CSSValue* value)
{
if (!value) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(value);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
if (value->isWebKitCSSTransformValue())
type = V8ClassIndex::WEBKITCSSTRANSFORMVALUE;
else if (value->isValueList())
type = V8ClassIndex::CSSVALUELIST;
else if (value->isPrimitiveValue())
type = V8ClassIndex::CSSPRIMITIVEVALUE;
#if ENABLE(SVG)
else if (value->isSVGPaint())
type = V8ClassIndex::SVGPAINT;
else if (value->isSVGColor())
type = V8ClassIndex::SVGCOLOR;
#endif
else
type = V8ClassIndex::CSSVALUE;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSVALUE, value);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
value->ref();
SetJSWrapperForDOMObject(value, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSRuleToV8Object(CSSRule* rule)
{
if (!rule) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(rule);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
switch (rule->type()) {
case CSSRule::STYLE_RULE:
type = V8ClassIndex::CSSSTYLERULE;
break;
case CSSRule::CHARSET_RULE:
type = V8ClassIndex::CSSCHARSETRULE;
break;
case CSSRule::IMPORT_RULE:
type = V8ClassIndex::CSSIMPORTRULE;
break;
case CSSRule::MEDIA_RULE:
type = V8ClassIndex::CSSMEDIARULE;
break;
case CSSRule::FONT_FACE_RULE:
type = V8ClassIndex::CSSFONTFACERULE;
break;
case CSSRule::PAGE_RULE:
type = V8ClassIndex::CSSPAGERULE;
break;
case CSSRule::VARIABLES_RULE:
type = V8ClassIndex::CSSVARIABLESRULE;
break;
case CSSRule::WEBKIT_KEYFRAME_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMERULE;
break;
case CSSRule::WEBKIT_KEYFRAMES_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMESRULE;
break;
default: // CSSRule::UNKNOWN_RULE
type = V8ClassIndex::CSSRULE;
break;
}
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSRULE, rule);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
rule->ref();
SetJSWrapperForDOMObject(rule, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::WindowToV8Object(DOMWindow* window)
{
if (!window) return v8::Null();
// Initializes environment of a frame, and return the global object
// of the frame.
Frame* frame = window->frame();
if (!frame)
return v8::Handle<v8::Object>();
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
return global;
}
void V8Proxy::BindJSObjectToWindow(Frame* frame,
const char* name,
int type,
v8::Handle<v8::FunctionTemplate> desc,
void* imp)
{
// Get environment.
v8::Handle<v8::Context> context = V8Proxy::GetContext(frame);
if (context.IsEmpty())
return; // JS not enabled.
v8::Context::Scope scope(context);
v8::Handle<v8::Object> instance = desc->GetFunction();
SetDOMWrapper(instance, type, imp);
v8::Handle<v8::Object> global = context->Global();
global->Set(v8::String::New(name), instance);
}
void V8Proxy::ProcessConsoleMessages()
{
ConsoleMessageManager::ProcessDelayedMessages();
}
} // namespace WebCore
Move ASSERT that was accidentally moved to the wrong position. The
ASSERT is invalid in the new position and it is causing layout test
failures in debug mode.
TBR=feng
Review URL: http://codereview.chromium.org/13123
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@6352 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include <v8.h>
#include "v8_proxy.h"
#include "dom_wrapper_map.h"
#include "v8_index.h"
#include "v8_events.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_collection.h"
#include "v8_nodefilter.h"
#include "V8DOMWindow.h"
#include "ChromiumBridge.h"
#include "BarInfo.h"
#include "CanvasGradient.h"
#include "CanvasPattern.h"
#include "CanvasPixelArray.h"
#include "CanvasRenderingContext2D.h"
#include "CanvasStyle.h"
#include "CharacterData.h"
#include "Clipboard.h"
#include "Console.h"
#include "Counter.h"
#include "CSSCharsetRule.h"
#include "CSSFontFaceRule.h"
#include "CSSImportRule.h"
#include "CSSMediaRule.h"
#include "CSSPageRule.h"
#include "CSSRule.h"
#include "CSSRuleList.h"
#include "CSSValueList.h"
#include "CSSStyleRule.h"
#include "CSSStyleSheet.h"
#include "CSSVariablesDeclaration.h"
#include "CSSVariablesRule.h"
#include "DocumentType.h"
#include "DocumentFragment.h"
#include "DOMCoreException.h"
#include "DOMImplementation.h"
#include "DOMParser.h"
#include "DOMSelection.h"
#include "DOMWindow.h"
#include "Entity.h"
#include "EventListener.h"
#include "EventTargetNode.h"
#include "EventTarget.h"
#include "Event.h"
#include "EventException.h"
#include "ExceptionCode.h"
#include "File.h"
#include "FileList.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "History.h"
#include "HTMLNames.h"
#include "HTMLDocument.h"
#include "HTMLElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLSelectElement.h"
#include "HTMLOptionsCollection.h"
#include "ImageData.h"
#include "InspectorController.h"
#include "KeyboardEvent.h"
#include "Location.h"
#include "MediaList.h"
#include "MessageChannel.h"
#include "MessageEvent.h"
#include "MessagePort.h"
#include "MimeTypeArray.h"
#include "MouseEvent.h"
#include "MutationEvent.h"
#include "Navigator.h" // for MimeTypeArray
#include "NodeFilter.h"
#include "Notation.h"
#include "NodeList.h"
#include "NodeIterator.h"
#include "OverflowEvent.h"
#include "Page.h"
#include "Plugin.h"
#include "PluginArray.h"
#include "ProcessingInstruction.h"
#include "ProgressEvent.h"
#include "Range.h"
#include "RangeException.h"
#include "Rect.h"
#include "RGBColor.h"
#include "Screen.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "StyleSheet.h"
#include "StyleSheetList.h"
#include "TextEvent.h"
#include "TextMetrics.h"
#include "TreeWalker.h"
#include "WebKitCSSTransformValue.h"
#include "XMLHttpRequest.h"
#include "XMLHttpRequestUpload.h"
#include "XMLHttpRequestException.h"
#include "XMLSerializer.h"
#include "XPathException.h"
#include "XPathExpression.h"
#include "XPathNSResolver.h"
#include "XPathResult.h"
#include "XSLTProcessor.h"
#include "WebKitAnimationEvent.h"
#include "WebKitCSSKeyframeRule.h"
#include "WebKitCSSKeyframesRule.h"
#include "WebKitTransitionEvent.h"
#include "WheelEvent.h"
#include "XMLHttpRequestProgressEvent.h"
#include "V8DOMWindow.h"
#include "V8HTMLElement.h"
#include "ScriptController.h"
#if ENABLE(SVG)
#include "SVGAngle.h"
#include "SVGAnimatedPoints.h"
#include "SVGElement.h"
#include "SVGElementInstance.h"
#include "SVGElementInstanceList.h"
#include "SVGException.h"
#include "SVGLength.h"
#include "SVGLengthList.h"
#include "SVGNumberList.h"
#include "SVGPathSeg.h"
#include "SVGPathSegArc.h"
#include "SVGPathSegClosePath.h"
#include "SVGPathSegCurvetoCubic.h"
#include "SVGPathSegCurvetoCubicSmooth.h"
#include "SVGPathSegCurvetoQuadratic.h"
#include "SVGPathSegCurvetoQuadraticSmooth.h"
#include "SVGPathSegLineto.h"
#include "SVGPathSegLinetoHorizontal.h"
#include "SVGPathSegLinetoVertical.h"
#include "SVGPathSegList.h"
#include "SVGPathSegMoveto.h"
#include "SVGPointList.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGRenderingIntent.h"
#include "SVGStringList.h"
#include "SVGTransform.h"
#include "SVGTransformList.h"
#include "SVGUnitTypes.h"
#include "SVGURIReference.h"
#include "SVGZoomEvent.h"
#include "V8SVGPODTypeWrapper.h"
#endif // SVG
#if ENABLE(XPATH)
#include "XPathEvaluator.h"
#endif
namespace WebCore {
// DOM binding algorithm:
//
// There are two kinds of DOM objects:
// 1. DOM tree nodes, such as Document, HTMLElement, ...
// there classes implements TreeShared<T> interface;
// 2. Non-node DOM objects, such as CSSRule, Location, etc.
// these classes implement a ref-counted scheme.
//
// A DOM object may have a JS wrapper object. If a tree node
// is alive, its JS wrapper must be kept alive even it is not
// reachable from JS roots.
// However, JS wrappers of non-node objects can go away if
// not reachable from other JS objects. It works like a cache.
//
// DOM objects are ref-counted, and JS objects are traced from
// a set of root objects. They can create a cycle. To break
// cycles, we do following:
// Peer from DOM objects to JS wrappers are always weak,
// so JS wrappers of non-node object cannot create a cycle.
// Before starting a global GC, we create a virtual connection
// between nodes in the same tree in the JS heap. If the wrapper
// of one node in a tree is alive, wrappers of all nodes in
// the same tree are considered alive. This is done by creating
// object groups in GC prologue callbacks. The mark-compact
// collector will remove these groups after each GC.
// A helper class for undetectable document.all
class UndetectableHTMLCollection : public HTMLCollection {
};
#ifndef NDEBUG
// Keeps track of global handles created (not JS wrappers
// of DOM objects). Often these global handles are source
// of leaks.
//
// If you want to let a C++ object hold a persistent handle
// to a JS object, you should register the handle here to
// keep track of leaks.
//
// When creating a persistent handle, call:
//
// #ifndef NDEBUG
// V8Proxy::RegisterGlobalHandle(type, host, handle);
// #endif
//
// When releasing the handle, call:
//
// #ifndef NDEBUG
// V8Proxy::UnregisterGlobalHandle(type, host, handle);
// #endif
//
typedef HashMap<v8::Value*, GlobalHandleInfo*> GlobalHandleMap;
static GlobalHandleMap& global_handle_map()
{
static GlobalHandleMap static_global_handle_map;
return static_global_handle_map;
}
// The USE_VAR(x) template is used to silence C++ compiler warnings
// issued for unused variables (typically parameters or values that
// we want to watch in the debugger).
template <typename T>
static inline void USE_VAR(T) { }
// The function is the place to set the break point to inspect
// live global handles. Leaks are often come from leaked global handles.
static void EnumerateGlobalHandles()
{
for (GlobalHandleMap::iterator it = global_handle_map().begin(),
end = global_handle_map().end(); it != end; ++it) {
GlobalHandleInfo* info = it->second;
USE_VAR(info);
v8::Value* handle = it->first;
USE_VAR(handle);
}
}
void V8Proxy::RegisterGlobalHandle(GlobalHandleType type, void* host,
v8::Persistent<v8::Value> handle)
{
ASSERT(!global_handle_map().contains(*handle));
global_handle_map().set(*handle, new GlobalHandleInfo(host, type));
}
void V8Proxy::UnregisterGlobalHandle(void* host, v8::Persistent<v8::Value> handle)
{
ASSERT(global_handle_map().contains(*handle));
GlobalHandleInfo* info = global_handle_map().take(*handle);
ASSERT(info->host_ == host);
delete info;
}
#endif // ifndef NDEBUG
void BatchConfigureAttributes(v8::Handle<v8::ObjectTemplate> inst,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedAttribute* attrs,
size_t num_attrs)
{
for (size_t i = 0; i < num_attrs; ++i) {
const BatchedAttribute* a = &attrs[i];
(a->on_proto ? proto : inst)->SetAccessor(
v8::String::New(a->name),
a->getter,
a->setter,
a->data == V8ClassIndex::INVALID_CLASS_INDEX
? v8::Handle<v8::Value>()
: v8::Integer::New(V8ClassIndex::ToInt(a->data)),
a->settings,
a->attribute);
}
}
void BatchConfigureConstants(v8::Handle<v8::FunctionTemplate> desc,
v8::Handle<v8::ObjectTemplate> proto,
const BatchedConstant* consts,
size_t num_consts)
{
for (size_t i = 0; i < num_consts; ++i) {
const BatchedConstant* c = &consts[i];
desc->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
proto->Set(v8::String::New(c->name),
v8::Integer::New(c->value),
v8::ReadOnly);
}
}
typedef HashMap<Node*, v8::Object*> DOMNodeMap;
typedef HashMap<void*, v8::Object*> DOMObjectMap;
#ifndef NDEBUG
static void EnumerateDOMObjectMap(DOMObjectMap& wrapper_map)
{
for (DOMObjectMap::iterator it = wrapper_map.begin(), end = wrapper_map.end();
it != end; ++it) {
v8::Persistent<v8::Object> wrapper(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
void* obj = it->first;
USE_VAR(type);
USE_VAR(obj);
}
}
static void EnumerateDOMNodeMap(DOMNodeMap& node_map)
{
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
USE_VAR(node);
ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
}
}
#endif // NDEBUG
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj, void* para);
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* para);
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* para);
// A map from DOM node to its JS wrapper.
static DOMWrapperMap<Node>& dom_node_map()
{
static DOMWrapperMap<Node> static_dom_node_map(&WeakNodeCallback);
return static_dom_node_map;
}
// A map from a DOM object (non-node) to its JS wrapper. This map does not
// contain the DOM objects which can have pending activity (active dom objects).
static DOMWrapperMap<void>& dom_object_map()
{
static DOMWrapperMap<void>
static_dom_object_map(&WeakDOMObjectCallback);
return static_dom_object_map;
}
// A map from a DOM object to its JS wrapper for DOM objects which
// can have pending activity.
static DOMWrapperMap<void>& active_dom_object_map()
{
static DOMWrapperMap<void>
static_active_dom_object_map(&WeakActiveDOMObjectCallback);
return static_active_dom_object_map;
}
#if ENABLE(SVG)
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param);
// A map for SVGElementInstances.
static DOMWrapperMap<SVGElementInstance>& dom_svg_element_instance_map()
{
static DOMWrapperMap<SVGElementInstance>
static_dom_svg_element_instance_map(&WeakSVGElementInstanceCallback);
return static_dom_svg_element_instance_map;
}
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Value> obj,
void* param)
{
SVGElementInstance* instance = static_cast<SVGElementInstance*>(param);
ASSERT(dom_svg_element_instance_map().contains(instance));
instance->deref();
dom_svg_element_instance_map().forget(instance);
}
v8::Handle<v8::Value> V8Proxy::SVGElementInstanceToV8Object(
SVGElementInstance* instance)
{
if (!instance)
return v8::Null();
v8::Handle<v8::Object> existing_instance = dom_svg_element_instance_map().get(instance);
if (!existing_instance.IsEmpty())
return existing_instance;
instance->ref();
// Instantiate the V8 object and remember it
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::SVGELEMENTINSTANCE,
V8ClassIndex::SVGELEMENTINSTANCE,
instance);
if (!result.IsEmpty()) {
// Only update the DOM SVG element map if the result is non-empty.
dom_svg_element_instance_map().set(instance,
v8::Persistent<v8::Object>::New(result));
}
return result;
}
// SVG non-node elements may have a reference to a context node which
// should be notified when the element is change
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj);
// Map of SVG objects with contexts to V8 objects
static DOMWrapperMap<void>& dom_svg_object_with_context_map() {
static DOMWrapperMap<void>
static_dom_svg_object_with_context_map(&WeakSVGObjectWithContext);
return static_dom_svg_object_with_context_map;
}
// Map of SVG objects with contexts to their contexts
static HashMap<void*, SVGElement*>& svg_object_to_context_map()
{
static HashMap<void*, SVGElement*> static_svg_object_to_context_map;
return static_svg_object_to_context_map;
}
v8::Handle<v8::Value> V8Proxy::SVGObjectWithContextToV8Object(
V8ClassIndex::V8WrapperType type, void* object)
{
if (!object)
return v8::Null();
v8::Persistent<v8::Object> result =
dom_svg_object_with_context_map().get(object);
if (!result.IsEmpty()) return result;
// Special case: SVGPathSegs need to be downcast to their real type
if (type == V8ClassIndex::SVGPATHSEG)
type = V8Custom::DowncastSVGPathSeg(object);
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, object);
if (!v8obj.IsEmpty()) {
result = v8::Persistent<v8::Object>::New(v8obj);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(object)->ref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(object)->ref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
dom_svg_object_with_context_map().set(object, result);
}
return result;
}
static void WeakSVGObjectWithContext(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope handle_scope;
ASSERT(dom_svg_object_with_context_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
dom_svg_object_with_context_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
SVG_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: \
static_cast<V8SVGPODTypeWrapper<NAME>*>(dom_obj)->deref(); break;
SVG_POD_NATIVE_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
void V8Proxy::SetSVGContext(void* obj, SVGElement* context)
{
SVGElement* old_context = svg_object_to_context_map().get(obj);
if (old_context == context)
return;
if (old_context)
old_context->deref();
if (context)
context->ref();
svg_object_to_context_map().set(obj, context);
}
SVGElement* V8Proxy::GetSVGContext(void* obj)
{
return svg_object_to_context_map().get(obj);
}
#endif
// Called when obj is near death (not reachable from JS roots)
// It is time to remove the entry from the table and dispose
// the handle.
static void WeakDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj) {
v8::HandleScope scope;
ASSERT(dom_object_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
dom_object_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakActiveDOMObjectCallback(v8::Persistent<v8::Value> obj,
void* dom_obj)
{
v8::HandleScope scope;
ASSERT(active_dom_object_map().contains(dom_obj));
ASSERT(obj->IsObject());
// Forget function removes object from the map and dispose the wrapper.
active_dom_object_map().forget(dom_obj);
V8ClassIndex::V8WrapperType type =
V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object>::Cast(obj));
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(dom_obj)->deref(); break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
}
static void WeakNodeCallback(v8::Persistent<v8::Value> obj, void* param)
{
Node* node = static_cast<Node*>(param);
ASSERT(dom_node_map().contains(node));
dom_node_map().forget(node);
node->deref();
}
// A map from a DOM node to its JS wrapper, the wrapper
// is kept as a strong reference to survive GCs.
static DOMObjectMap& gc_protected_map() {
static DOMObjectMap static_gc_protected_map;
return static_gc_protected_map;
}
// static
void V8Proxy::GCProtect(void* dom_object)
{
if (!dom_object)
return;
if (gc_protected_map().contains(dom_object))
return;
if (!dom_object_map().contains(dom_object))
return;
// Create a new (strong) persistent handle for the object.
v8::Persistent<v8::Object> wrapper = dom_object_map().get(dom_object);
if (wrapper.IsEmpty()) return;
gc_protected_map().set(dom_object, *v8::Persistent<v8::Object>::New(wrapper));
}
// static
void V8Proxy::GCUnprotect(void* dom_object)
{
if (!dom_object)
return;
if (!gc_protected_map().contains(dom_object))
return;
// Dispose the strong reference.
v8::Persistent<v8::Object> wrapper(gc_protected_map().take(dom_object));
wrapper.Dispose();
}
// Create object groups for DOM tree nodes.
static void GCPrologue()
{
v8::HandleScope scope;
#ifndef NDEBUG
EnumerateDOMObjectMap(dom_object_map().impl());
#endif
// Run through all objects with possible pending activity making their
// wrappers non weak if there is pending activity.
DOMObjectMap active_map = active_dom_object_map().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
ASSERT(wrapper.IsWeak());
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) \
wrapper.ClearWeak(); \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
// Create object groups.
DOMNodeMap node_map = dom_node_map().impl();
for (DOMNodeMap::iterator it = node_map.begin(), end = node_map.end();
it != end; ++it) {
Node* node = it->first;
// If the node is in document, put it in the ownerDocument's
// object group. Otherwise, skip it.
//
// If an image element was created by JavaScript "new Image",
// it is not in a document. However, if the load event has not
// been fired (still onloading), it is treated as in the document.
//
// Otherwise, the node is put in an object group identified by the root
// elment of the tree to which it belongs.
void* group_id;
if (node->inDocument() ||
(node->hasTagName(HTMLNames::imgTag) &&
!static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent()) ) {
group_id = node->document();
} else {
Node* root = node;
while (root->parent()) {
root = root->parent();
}
group_id = root;
}
v8::Persistent<v8::Object> wrapper = dom_node_map().get(node);
if (!wrapper.IsEmpty())
v8::V8::AddObjectToGroup(group_id, wrapper);
}
}
static void GCEpilogue()
{
v8::HandleScope scope;
// Run through all objects with pending activity making their wrappers weak
// again.
DOMObjectMap active_map = active_dom_object_map().impl();
for (DOMObjectMap::iterator it = active_map.begin(), end = active_map.end();
it != end; ++it) {
void* obj = it->first;
v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>(it->second);
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: { \
NAME* impl = static_cast<NAME*>(obj); \
if (impl->hasPendingActivity()) { \
ASSERT(!wrapper.IsWeak()); \
wrapper.MakeWeak(impl, &WeakActiveDOMObjectCallback); \
} \
break; \
}
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default:
ASSERT(false);
#undef MAKE_CASE
}
}
#ifndef NDEBUG
// Check all survivals are weak.
EnumerateDOMObjectMap(dom_object_map().impl());
EnumerateDOMNodeMap(dom_node_map().impl());
EnumerateDOMObjectMap(gc_protected_map());
EnumerateGlobalHandles();
#undef USE_VAR
#endif
}
typedef HashMap<int, v8::FunctionTemplate*> FunctionTemplateMap;
bool AllowAllocation::m_current = false;
// JavaScriptConsoleMessages encapsulate everything needed to
// log messages originating from JavaScript to the Chrome console.
class JavaScriptConsoleMessage {
public:
JavaScriptConsoleMessage(const String& str,
const String& sourceID,
unsigned lineNumber)
: m_string(str)
, m_sourceID(sourceID)
, m_lineNumber(lineNumber) { }
void AddToPage(Page* page) const;
private:
const String m_string;
const String m_sourceID;
const unsigned m_lineNumber;
};
void JavaScriptConsoleMessage::AddToPage(Page* page) const
{
ASSERT(page);
Console* console = page->mainFrame()->domWindow()->console();
console->addMessage(JSMessageSource, ErrorMessageLevel, m_string, m_lineNumber, m_sourceID);
}
// The ConsoleMessageManager handles all console messages that stem
// from JavaScript. It keeps a list of messages that have been delayed but
// it makes sure to add all messages to the console in the right order.
class ConsoleMessageManager {
public:
// Add a message to the console. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void AddMessage(Page* page, const JavaScriptConsoleMessage& message);
// Add a message to the console but delay the reporting until it
// is safe to do so: Either when we leave JavaScript execution or
// when adding other console messages. The primary purpose of this
// method is to avoid calling into V8 to handle console messages
// when the VM is in a state that does not support GCs or allocations.
// Delayed messages are always reported in the page corresponding
// to the active context.
static void AddDelayedMessage(const JavaScriptConsoleMessage& message);
// Process any delayed messages. May end up calling JavaScript code
// indirectly through the inspector so only call this function when
// it is safe to do allocations.
static void ProcessDelayedMessages();
private:
// All delayed messages are stored in this vector. If the vector
// is NULL, there are no delayed messages.
static Vector<JavaScriptConsoleMessage>* m_delayed;
};
Vector<JavaScriptConsoleMessage>* ConsoleMessageManager::m_delayed = NULL;
void ConsoleMessageManager::AddMessage(
Page* page,
const JavaScriptConsoleMessage& message)
{
// Process any delayed messages to make sure that messages
// appear in the right order in the console.
ProcessDelayedMessages();
message.AddToPage(page);
}
void ConsoleMessageManager::AddDelayedMessage(const JavaScriptConsoleMessage& message)
{
if (!m_delayed)
// Allocate a vector for the delayed messages. Will be
// deallocated when the delayed messages are processed
// in ProcessDelayedMessages().
m_delayed = new Vector<JavaScriptConsoleMessage>();
m_delayed->append(message);
}
void ConsoleMessageManager::ProcessDelayedMessages()
{
// If we have a delayed vector it cannot be empty.
if (!m_delayed)
return;
ASSERT(!m_delayed->isEmpty());
// Add the delayed messages to the page of the active
// context. If that for some bizarre reason does not
// exist, we clear the list of delayed messages to avoid
// posting messages. We still deallocate the vector.
Frame* frame = V8Proxy::retrieveActiveFrame();
Page* page = NULL;
if (frame)
page = frame->page();
if (!page)
m_delayed->clear();
// Iterate through all the delayed messages and add them
// to the console.
const int size = m_delayed->size();
for (int i = 0; i < size; i++) {
m_delayed->at(i).AddToPage(page);
}
// Deallocate the delayed vector.
delete m_delayed;
m_delayed = NULL;
}
// Convenience class for ensuring that delayed messages in the
// ConsoleMessageManager are processed quickly.
class ConsoleMessageScope {
public:
ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
~ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
};
void log_info(Frame* frame, const String& msg, const String& url)
{
Page* page = frame->page();
if (!page)
return;
JavaScriptConsoleMessage message(msg, url, 0);
ConsoleMessageManager::AddMessage(page, message);
}
static void HandleConsoleMessage(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data)
{
// Use the frame where JavaScript is called from.
Frame* frame = V8Proxy::retrieveActiveFrame();
if (!frame)
return;
Page* page = frame->page();
if (!page)
return;
v8::Handle<v8::String> errorMessageString = message->Get();
ASSERT(!errorMessageString.IsEmpty());
String errorMessage = ToWebCoreString(errorMessageString);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool useURL = (resourceName.IsEmpty() || !resourceName->IsString());
String resourceNameString = (useURL)
? frame->document()->url()
: ToWebCoreString(resourceName);
JavaScriptConsoleMessage consoleMessage(errorMessage,
resourceNameString,
message->GetLineNumber());
ConsoleMessageManager::AddMessage(page, consoleMessage);
}
enum DelayReporting {
REPORT_LATER,
REPORT_NOW
};
static void ReportUnsafeAccessTo(Frame* target, DelayReporting delay)
{
ASSERT(target);
Document* targetDocument = target->document();
if (!targetDocument)
return;
Frame* source = V8Proxy::retrieveActiveFrame();
if (!source || !source->document())
return; // Ignore error if the source document is gone.
Document* sourceDocument = source->document();
// FIXME: This error message should contain more specifics of why the same
// origin check has failed.
String str = String::format("Unsafe JavaScript attempt to access frame "
"with URL %s from frame with URL %s. "
"Domains, protocols and ports must match.\n",
targetDocument->url().string().utf8().data(),
sourceDocument->url().string().utf8().data());
// Build a console message with fake source ID and line number.
const String kSourceID = "";
const int kLineNumber = 1;
JavaScriptConsoleMessage message(str, kSourceID, kLineNumber);
if (delay == REPORT_NOW) {
// NOTE(tc): Apple prints the message in the target page, but it seems like
// it should be in the source page. Even for delayed messages, we put it in
// the source page; see ConsoleMessageManager::ProcessDelayedMessages().
ConsoleMessageManager::AddMessage(source->page(), message);
} else {
ASSERT(delay == REPORT_LATER);
// We cannot safely report the message eagerly, because this may cause
// allocations and GCs internally in V8 and we cannot handle that at this
// point. Therefore we delay the reporting.
ConsoleMessageManager::AddDelayedMessage(message);
}
}
static void ReportUnsafeJavaScriptAccess(v8::Local<v8::Object> host,
v8::AccessType type,
v8::Local<v8::Value> data)
{
Frame* target = V8Custom::GetTargetFrame(host, data);
if (target)
ReportUnsafeAccessTo(target, REPORT_LATER);
}
static void HandleFatalErrorInV8()
{
// TODO: We temporarily deal with V8 internal error situations
// such as out-of-memory by crashing the renderer.
CRASH();
}
static void ReportFatalErrorInV8(const char* location, const char* message)
{
// V8 is shutdown, we cannot use V8 api.
// The only thing we can do is to disable JavaScript.
// TODO: clean up V8Proxy and disable JavaScript.
printf("V8 error: %s (%s)\n", message, location);
HandleFatalErrorInV8();
}
V8Proxy::~V8Proxy()
{
clearForClose();
DestroyGlobal();
}
void V8Proxy::DestroyGlobal()
{
if (!m_global.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_global);
#endif
m_global.Dispose();
m_global.Clear();
}
}
bool V8Proxy::DOMObjectHasJSWrapper(void* obj) {
return dom_object_map().contains(obj) ||
active_dom_object_map().contains(obj);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
ASSERT(false);
#undef MAKE_CASE
default: break;
}
#endif
dom_object_map().set(obj, wrapper);
}
// The caller must have increased obj's ref count.
void V8Proxy::SetJSWrapperForActiveDOMObject(void* obj, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
#ifndef NDEBUG
V8ClassIndex::V8WrapperType type = V8Proxy::GetDOMWrapperType(wrapper);
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE: break;
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
default: ASSERT(false);
#undef MAKE_CASE
}
#endif
active_dom_object_map().set(obj, wrapper);
}
// The caller must have increased node's ref count.
void V8Proxy::SetJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
{
ASSERT(MaybeDOMWrapper(wrapper));
dom_node_map().set(node, wrapper);
}
PassRefPtr<EventListener> V8Proxy::createInlineEventListener(
const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#if ENABLE(SVG)
PassRefPtr<EventListener> V8Proxy::createSVGEventHandler(const String& functionName,
const String& code, Node* node)
{
return V8LazyEventListener::create(m_frame, code, functionName);
}
#endif
// Event listeners
static V8EventListener* FindEventListenerInList(V8EventListenerList& list,
v8::Local<v8::Value> listener,
bool isInline)
{
ASSERT(v8::Context::InContext());
if (!listener->IsObject())
return 0;
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
V8EventListener* el = *p;
v8::Local<v8::Object> wrapper = el->GetListenerObject();
ASSERT(!wrapper.IsEmpty());
// Since the listener is an object, it is safe to compare for
// strict equality (in the JS sense) by doing a simple equality
// check using the == operator on the handles. This is much,
// much faster than calling StrictEquals through the API in
// the negative case.
if (el->isInline() == isInline && listener == wrapper)
return el;
++p;
}
return 0;
}
// Find an existing wrapper for a JS event listener in the map.
PassRefPtr<V8EventListener> V8Proxy::FindV8EventListener(v8::Local<v8::Value> listener,
bool isInline)
{
return FindEventListenerInList(m_event_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateV8EventListener(v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_event_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8EventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_event_listeners.push_back(new_listener.get());
return new_listener;
}
// Object event listeners (such as XmlHttpRequest and MessagePort) are
// different from listeners on DOM nodes. An object event listener wrapper
// only holds a weak reference to the JS function. A strong reference can
// create a cycle.
//
// The lifetime of these objects is bounded by the life time of its JS
// wrapper. So we can create a hidden reference from the JS wrapper to
// to its JS function.
//
// (map)
// XHR <---------- JS_wrapper
// | (hidden) : ^
// V V : (may reachable by closure)
// V8_listener --------> JS_function
// (weak) <-- may create a cycle if it is strong
//
// The persistent reference is made weak in the constructor
// of V8ObjectEventListener.
PassRefPtr<V8EventListener> V8Proxy::FindObjectEventListener(
v8::Local<v8::Value> listener, bool isInline)
{
return FindEventListenerInList(m_xhr_listeners, listener, isInline);
}
PassRefPtr<V8EventListener> V8Proxy::FindOrCreateObjectEventListener(
v8::Local<v8::Value> obj, bool isInline)
{
ASSERT(v8::Context::InContext());
if (!obj->IsObject())
return 0;
V8EventListener* wrapper =
FindEventListenerInList(m_xhr_listeners, obj, isInline);
if (wrapper)
return wrapper;
// Create a new one, and add to cache.
RefPtr<V8EventListener> new_listener =
V8ObjectEventListener::create(m_frame, v8::Local<v8::Object>::Cast(obj), isInline);
m_xhr_listeners.push_back(new_listener.get());
return new_listener.release();
}
static void RemoveEventListenerFromList(V8EventListenerList& list,
V8EventListener* listener)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
if (*p == listener) {
list.erase(p);
return;
}
++p;
}
}
void V8Proxy::RemoveV8EventListener(V8EventListener* listener)
{
RemoveEventListenerFromList(m_event_listeners, listener);
}
void V8Proxy::RemoveObjectEventListener(V8ObjectEventListener* listener)
{
RemoveEventListenerFromList(m_xhr_listeners, listener);
}
static void DisconnectEventListenersInList(V8EventListenerList& list)
{
V8EventListenerList::iterator p = list.begin();
while (p != list.end()) {
(*p)->disconnectFrame();
++p;
}
list.clear();
}
void V8Proxy::DisconnectEventListeners()
{
DisconnectEventListenersInList(m_event_listeners);
DisconnectEventListenersInList(m_xhr_listeners);
}
v8::Handle<v8::Script> V8Proxy::CompileScript(v8::Handle<v8::String> code,
const String& fileName,
int baseLine)
{
const uint16_t* fileNameString = FromWebCoreString(fileName);
v8::Handle<v8::String> name =
v8::String::New(fileNameString, fileName.length());
v8::Handle<v8::Integer> line = v8::Integer::New(baseLine);
v8::ScriptOrigin origin(name, line);
v8::Handle<v8::Script> script = v8::Script::Compile(code, &origin);
return script;
}
bool V8Proxy::HandleOutOfMemory()
{
v8::Local<v8::Context> context = v8::Context::GetCurrent();
if (!context->HasOutOfMemoryException())
return false;
// Warning, error, disable JS for this frame?
Frame* frame = V8Proxy::retrieveFrame(context);
V8Proxy* proxy = V8Proxy::retrieve(frame);
// Clean m_context, and event handlers.
proxy->clearForClose();
// Destroy the global object.
proxy->DestroyGlobal();
ChromiumBridge::notifyJSOutOfMemory(frame);
// Disable JS.
Settings* settings = frame->settings();
ASSERT(settings);
settings->setJavaScriptEnabled(false);
return true;
}
v8::Local<v8::Value> V8Proxy::Evaluate(const String& fileName, int baseLine,
const String& str, Node* n)
{
ASSERT(v8::Context::InContext());
// Compile the script.
v8::Local<v8::String> code = v8ExternalString(str);
ChromiumBridge::traceEventBegin("v8.compile", n, "");
v8::Handle<v8::Script> script = CompileScript(code, fileName, baseLine);
ChromiumBridge::traceEventEnd("v8.compile", n, "");
// Set inlineCode to true for <a href="javascript:doSomething()">
// and false for <script>doSomething</script>. For some reason, fileName
// gives us this information.
ChromiumBridge::traceEventBegin("v8.run", n, "");
v8::Local<v8::Value> result = RunScript(script, fileName.isNull());
ChromiumBridge::traceEventEnd("v8.run", n, "");
return result;
}
v8::Local<v8::Value> V8Proxy::RunScript(v8::Handle<v8::Script> script,
bool inline_code)
{
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Compute the source string and prevent against infinite recursion.
if (m_recursion >= 20) {
v8::Local<v8::String> code =
v8ExternalString("throw RangeError('Recursion too deep')");
// TODO(kasperl): Ideally, we should be able to re-use the origin of the
// script passed to us as the argument instead of using an empty string
// and 0 baseLine.
script = CompileScript(code, "", 0);
}
if (HandleOutOfMemory())
ASSERT(script.IsEmpty());
if (script.IsEmpty())
return v8::Local<v8::Value>();
// Save the previous value of the inlineCode flag and update the flag for
// the duration of the script invocation.
bool previous_inline_code = inlineCode();
setInlineCode(inline_code);
// Run the script and keep track of the current recursion depth.
v8::Local<v8::Value> result;
{ ConsoleMessageScope scope;
m_recursion++;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = script->Run();
m_recursion--;
}
if (HandleOutOfMemory())
ASSERT(result.IsEmpty());
// Handle V8 internal error situation (Out-of-memory).
if (result.IsEmpty())
return v8::Local<v8::Value>();
// Restore inlineCode flag.
setInlineCode(previous_inline_code);
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Local<v8::Value> V8Proxy::CallFunction(v8::Handle<v8::Function> function,
v8::Handle<v8::Object> receiver,
int argc,
v8::Handle<v8::Value> args[])
{
// For now, we don't put any artificial limitations on the depth
// of recursion that stems from calling functions. This is in
// contrast to the script evaluations.
v8::Local<v8::Value> result;
{
ConsoleMessageScope scope;
// Evaluating the JavaScript could cause the frame to be deallocated,
// so we start the keep alive timer here.
// Frame::keepAlive method adds the ref count of the frame and sets a
// timer to decrease the ref count. It assumes that the current JavaScript
// execution finishs before firing the timer.
// See issue 1218756 and 914430.
m_frame->keepAlive();
result = function->Call(receiver, argc, args);
}
if (v8::V8::IsDead())
HandleFatalErrorInV8();
return result;
}
v8::Persistent<v8::FunctionTemplate> V8Proxy::GetTemplate(
V8ClassIndex::V8WrapperType type)
{
v8::Persistent<v8::FunctionTemplate>* cache_cell =
V8ClassIndex::GetCache(type);
if (!(*cache_cell).IsEmpty())
return *cache_cell;
// not found
FunctionTemplateFactory factory = V8ClassIndex::GetFactory(type);
v8::Persistent<v8::FunctionTemplate> desc = factory();
switch (type) {
case V8ClassIndex::CSSSTYLEDECLARATION:
// The named property handler for style declarations has a
// setter. Therefore, the interceptor has to be on the object
// itself and not on the prototype object.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(CSSStyleDeclaration),
USE_NAMED_PROPERTY_SETTER(CSSStyleDeclaration));
SetCollectionStringOrNullIndexedGetter<CSSStyleDeclaration>(desc);
break;
case V8ClassIndex::CSSRULELIST:
SetCollectionIndexedGetter<CSSRuleList, CSSRule>(desc,
V8ClassIndex::CSSRULE);
break;
case V8ClassIndex::CSSVALUELIST:
SetCollectionIndexedGetter<CSSValueList, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::CSSVARIABLESDECLARATION:
SetCollectionStringOrNullIndexedGetter<CSSVariablesDeclaration>(desc);
break;
case V8ClassIndex::WEBKITCSSTRANSFORMVALUE:
SetCollectionIndexedGetter<WebKitCSSTransformValue, CSSValue>(
desc,
V8ClassIndex::CSSVALUE);
break;
case V8ClassIndex::UNDETECTABLEHTMLCOLLECTION:
desc->InstanceTemplate()->MarkAsUndetectable(); // fall through
case V8ClassIndex::HTMLCOLLECTION:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
SetCollectionIndexedGetter<HTMLCollection, Node>(desc,
V8ClassIndex::NODE);
break;
case V8ClassIndex::HTMLOPTIONSCOLLECTION:
SetCollectionNamedGetter<HTMLOptionsCollection, Node>(
desc,
V8ClassIndex::NODE);
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLOptionsCollection),
USE_INDEXED_PROPERTY_SETTER(HTMLOptionsCollection));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLCollectionCallAsFunction));
break;
case V8ClassIndex::HTMLSELECTELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
NodeCollectionNamedPropertyGetter<HTMLSelectElement>,
0,
0,
0,
0,
v8::Integer::New(V8ClassIndex::NODE));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
NodeCollectionIndexedPropertyGetter<HTMLSelectElement>,
USE_INDEXED_PROPERTY_SETTER(HTMLSelectElementCollection),
0,
0,
NodeCollectionIndexedPropertyEnumerator<HTMLSelectElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::HTMLDOCUMENT: {
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLDocument),
USE_NAMED_PROPERTY_SETTER(HTMLDocument),
0,
USE_NAMED_PROPERTY_DELETER(HTMLDocument));
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
//
// Additionally, we add two extra internal fields for
// HTMLDocuments to implement temporary shadowing of
// document.all. One field holds an object that is used as a
// marker. The other field holds the marker object if
// document.all is not shadowed and some other value if
// document.all is shadowed.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kHTMLDocumentInternalFieldCount);
break;
}
#if ENABLE(SVG)
case V8ClassIndex::SVGDOCUMENT: // fall through
#endif
case V8ClassIndex::DOCUMENT: {
// We add an extra internal field to all Document wrappers for
// storing a per document DOMImplementation wrapper.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kDocumentMinimumInternalFieldCount);
break;
}
case V8ClassIndex::HTMLAPPLETELEMENT: // fall through
case V8ClassIndex::HTMLEMBEDELEMENT: // fall through
case V8ClassIndex::HTMLOBJECTELEMENT:
// HTMLAppletElement, HTMLEmbedElement and HTMLObjectElement are
// inherited from HTMLPlugInElement, and they share the same property
// handling code.
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLPlugInElement),
USE_NAMED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLPlugInElement),
USE_INDEXED_PROPERTY_SETTER(HTMLPlugInElement));
desc->InstanceTemplate()->SetCallAsFunctionHandler(
USE_CALLBACK(HTMLPlugInElement));
break;
case V8ClassIndex::HTMLFRAMESETELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFrameSetElement));
break;
case V8ClassIndex::HTMLFORMELEMENT:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(HTMLFormElement));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(HTMLFormElement),
0,
0,
0,
NodeCollectionIndexedPropertyEnumerator<HTMLFormElement>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::CANVASPIXELARRAY:
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(CanvasPixelArray),
USE_INDEXED_PROPERTY_SETTER(CanvasPixelArray));
break;
case V8ClassIndex::STYLESHEET: // fall through
case V8ClassIndex::CSSSTYLESHEET: {
// We add an extra internal field to hold a reference to
// the owner node.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
ASSERT(instance_template->InternalFieldCount() ==
V8Custom::kDefaultWrapperInternalFieldCount);
instance_template->SetInternalFieldCount(
V8Custom::kStyleSheetInternalFieldCount);
break;
}
case V8ClassIndex::MEDIALIST:
SetCollectionStringOrNullIndexedGetter<MediaList>(desc);
break;
case V8ClassIndex::MIMETYPEARRAY:
SetCollectionIndexedAndNamedGetters<MimeTypeArray, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::NAMEDNODEMAP:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NamedNodeMap));
desc->InstanceTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(NamedNodeMap),
0,
0,
0,
CollectionIndexedPropertyEnumerator<NamedNodeMap>,
v8::Integer::New(V8ClassIndex::NODE));
break;
case V8ClassIndex::NODELIST:
SetCollectionIndexedGetter<NodeList, Node>(desc, V8ClassIndex::NODE);
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(NodeList));
break;
case V8ClassIndex::PLUGIN:
SetCollectionIndexedAndNamedGetters<Plugin, MimeType>(
desc,
V8ClassIndex::MIMETYPE);
break;
case V8ClassIndex::PLUGINARRAY:
SetCollectionIndexedAndNamedGetters<PluginArray, Plugin>(
desc,
V8ClassIndex::PLUGIN);
break;
case V8ClassIndex::STYLESHEETLIST:
desc->InstanceTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(StyleSheetList));
SetCollectionIndexedGetter<StyleSheetList, StyleSheet>(
desc,
V8ClassIndex::STYLESHEET);
break;
case V8ClassIndex::DOMWINDOW: {
v8::Local<v8::Signature> default_signature = v8::Signature::New(desc);
desc->PrototypeTemplate()->SetNamedPropertyHandler(
USE_NAMED_PROPERTY_GETTER(DOMWindow));
desc->PrototypeTemplate()->SetIndexedPropertyHandler(
USE_INDEXED_PROPERTY_GETTER(DOMWindow));
desc->SetHiddenPrototype(true);
// Reserve spaces for references to location and navigator objects.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kDOMWindowInternalFieldCount);
// Set access check callbacks, but turned off initially.
// When a context is detached from a frame, turn on the access check.
// Turning on checks also invalidates inline caches of the object.
instance_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW),
false);
break;
}
case V8ClassIndex::LOCATION: {
break;
}
case V8ClassIndex::HISTORY: {
break;
}
case V8ClassIndex::MESSAGECHANNEL: {
// Reserve two more internal fields for referencing the port1
// and port2 wrappers. This ensures that the port wrappers are
// kept alive when the channel wrapper is.
desc->SetCallHandler(USE_CALLBACK(MessageChannelConstructor));
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessageChannelInternalFieldCount);
break;
}
case V8ClassIndex::MESSAGEPORT: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kMessagePortInternalFieldCount);
break;
}
// DOMParser, XMLSerializer, and XMLHttpRequest objects are created from
// JS world, but we setup the constructor function lazily in
// WindowNamedPropertyHandler::get.
case V8ClassIndex::DOMPARSER:
desc->SetCallHandler(USE_CALLBACK(DOMParserConstructor));
break;
case V8ClassIndex::XMLSERIALIZER:
desc->SetCallHandler(USE_CALLBACK(XMLSerializerConstructor));
break;
case V8ClassIndex::XMLHTTPREQUEST: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
desc->SetCallHandler(USE_CALLBACK(XMLHttpRequestConstructor));
break;
}
case V8ClassIndex::XMLHTTPREQUESTUPLOAD: {
// Reserve one more internal field for keeping event listeners.
v8::Local<v8::ObjectTemplate> instance_template =
desc->InstanceTemplate();
instance_template->SetInternalFieldCount(
V8Custom::kXMLHttpRequestInternalFieldCount);
break;
}
case V8ClassIndex::XPATHEVALUATOR:
desc->SetCallHandler(USE_CALLBACK(XPathEvaluatorConstructor));
break;
case V8ClassIndex::XSLTPROCESSOR:
desc->SetCallHandler(USE_CALLBACK(XSLTProcessorConstructor));
break;
default:
break;
}
*cache_cell = desc;
return desc;
}
bool V8Proxy::ContextInitialized()
{
return !m_context.IsEmpty();
}
DOMWindow* V8Proxy::retrieveWindow()
{
// TODO: This seems very fragile. How do we know that the global object
// from the current context is something sensible? Do we need to use the
// last entered here? Who calls this?
return retrieveWindow(v8::Context::GetCurrent());
}
DOMWindow* V8Proxy::retrieveWindow(v8::Handle<v8::Context> context)
{
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
return ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, global);
}
Frame* V8Proxy::retrieveFrame(v8::Handle<v8::Context> context)
{
return retrieveWindow(context)->frame();
}
Frame* V8Proxy::retrieveActiveFrame()
{
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return 0;
return retrieveFrame(context);
}
Frame* V8Proxy::retrieveFrame()
{
DOMWindow* window = retrieveWindow();
return window ? window->frame() : 0;
}
V8Proxy* V8Proxy::retrieve()
{
DOMWindow* window = retrieveWindow();
ASSERT(window);
return retrieve(window->frame());
}
V8Proxy* V8Proxy::retrieve(Frame* frame)
{
if (!frame)
return 0;
return frame->script()->isEnabled() ? frame->script()->proxy() : 0;
}
V8Proxy* V8Proxy::retrieve(ScriptExecutionContext* context)
{
if (!context->isDocument())
return 0;
return retrieve(static_cast<Document*>(context)->frame());
}
void V8Proxy::disconnectFrame()
{
// disconnect all event listeners
DisconnectEventListeners();
// remove all timeouts
if (m_frame->domWindow())
m_frame->domWindow()->clearAllTimeouts();
}
bool V8Proxy::isEnabled()
{
Settings* settings = m_frame->settings();
if (!settings)
return false;
// In the common case, JavaScript is enabled and we're done.
if (settings->isJavaScriptEnabled())
return true;
// If JavaScript has been disabled, we need to look at the frame to tell
// whether this script came from the web or the embedder. Scripts from the
// embedder are safe to run, but scripts from the other sources are
// disallowed.
Document* document = m_frame->document();
if (!document)
return false;
SecurityOrigin* origin = document->securityOrigin();
if (origin->protocol().isEmpty())
return false; // Uninitialized document
if (origin->protocol() == "http" || origin->protocol() == "https")
return false; // Web site
if (origin->protocol() == ChromiumBridge::uiResourceProtocol())
return true; // Embedder's scripts are ok to run
// If the scheme is ftp: or file:, an empty file name indicates a directory
// listing, which requires JavaScript to function properly.
const char* kDirProtocols[] = { "ftp", "file" };
for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
if (origin->protocol() == kDirProtocols[i]) {
const KURL& url = document->url();
return url.pathAfterLastSlash() == url.pathEnd();
}
}
return false; // Other protocols fall through to here
}
// static
void V8Proxy::DomainChanged(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
// Restore to default security token.
proxy->m_context->UseDefaultSecurityToken();
}
void V8Proxy::UpdateDocumentWrapper(v8::Handle<v8::Value> wrapper) {
ClearDocumentWrapper();
ASSERT(m_document.IsEmpty());
m_document = v8::Persistent<v8::Value>::New(wrapper);
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_document);
#endif
}
void V8Proxy::ClearDocumentWrapper()
{
if (!m_document.IsEmpty()) {
#ifndef NDEBUG
UnregisterGlobalHandle(this, m_document);
#endif
m_document.Dispose();
m_document.Clear();
}
}
void V8Proxy::clearForClose()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle_scope;
ClearDocumentWrapper();
m_context.Dispose();
m_context.Clear();
}
}
void V8Proxy::clearForNavigation()
{
if (!m_context.IsEmpty()) {
v8::HandleScope handle;
ClearDocumentWrapper();
v8::Context::Scope context_scope(m_context);
// Turn on access check on the old DOMWindow wrapper.
v8::Handle<v8::Object> wrapper =
LookupDOMWrapper(V8ClassIndex::DOMWINDOW, m_global);
ASSERT(!wrapper.IsEmpty());
wrapper->TurnOnAccessCheck();
// Clear all timeouts.
DOMWindow* domWindow =
ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, wrapper);
domWindow->clearAllTimeouts();
// disconnect all event listeners
DisconnectEventListeners();
// Separate the context from its global object.
m_context->DetachGlobal();
m_context.Dispose();
m_context.Clear();
// Reinitialize the context so the global object points to
// the new DOM window.
initContextIfNeeded();
}
}
void V8Proxy::SetSecurityToken() {
Document* document = m_frame->document();
// Setup security origin and security token
if (!document) {
m_context->UseDefaultSecurityToken();
return;
}
// Ask the document's SecurityOrigin to generate a security token.
// If two tokens are equal, then the SecurityOrigins canAccess each other.
// If two tokens are not equal, then we have to call canAccess.
// Note: we can't use the HTTPOrigin if it was set from the DOM.
SecurityOrigin* origin = document->securityOrigin();
String token;
if (!origin->domainWasSetInDOM())
token = document->securityOrigin()->toString();
// An empty token means we always have to call canAccess. In this case, we
// use the global object as the security token to avoid calling canAccess
// when a script accesses its own objects.
if (token.isEmpty()) {
m_context->UseDefaultSecurityToken();
return;
}
CString utf8_token = token.utf8();
// NOTE: V8 does identity comparison in fast path, must use a symbol
// as the security token.
m_context->SetSecurityToken(
v8::String::NewSymbol(utf8_token.data(), utf8_token.length()));
}
void V8Proxy::updateDocument()
{
if (!m_frame->document())
return;
if (m_global.IsEmpty()) {
ASSERT(m_context.IsEmpty());
return;
}
{
v8::HandleScope scope;
SetSecurityToken();
}
}
// Check if the current execution context can access a target frame.
// First it checks same domain policy using the lexical context
//
// This is equivalent to KJS::Window::allowsAccessFrom(ExecState*, String&).
bool V8Proxy::CanAccessPrivate(DOMWindow* target_window)
{
ASSERT(target_window);
String message;
DOMWindow* origin_window = retrieveWindow();
if (origin_window == target_window)
return true;
if (!origin_window)
return false;
// JS may be attempting to access the "window" object, which should be
// valid, even if the document hasn't been constructed yet.
// If the document doesn't exist yet allow JS to access the window object.
if (!origin_window->document())
return true;
const SecurityOrigin* active_security_origin = origin_window->securityOrigin();
const SecurityOrigin* target_security_origin = target_window->securityOrigin();
String ui_resource_protocol = ChromiumBridge::uiResourceProtocol();
if (active_security_origin->protocol() == ui_resource_protocol) {
KURL inspector_url = ChromiumBridge::inspectorURL();
ASSERT(inspector_url.protocol() == ui_resource_protocol);
ASSERT(inspector_url.protocol().endsWith("-resource"));
// The Inspector can access anything.
if (active_security_origin->host() == inspector_url.host())
return true;
// To mitigate XSS vulnerabilities on the browser itself, UI resources
// besides the Inspector can't access other documents.
return false;
}
if (active_security_origin->canAccess(target_security_origin))
return true;
// Allow access to a "about:blank" page if the dynamic context is a
// detached context of the same frame as the blank page.
if (target_security_origin->isEmpty() &&
origin_window->frame() == target_window->frame())
return true;
return false;
}
bool V8Proxy::CanAccessFrame(Frame* target, bool report_error)
{
// The subject is detached from a frame, deny accesses.
if (!target)
return false;
if (!CanAccessPrivate(target->domWindow())) {
if (report_error)
ReportUnsafeAccessTo(target, REPORT_NOW);
return false;
}
return true;
}
bool V8Proxy::CheckNodeSecurity(Node* node)
{
if (!node)
return false;
Frame* target = node->document()->frame();
if (!target)
return false;
return CanAccessFrame(target, true);
}
// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance. However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object. The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript. The javascript object that corresponds to a
// DOMWindow instance is the shadow object. When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
//
// To implement split-window, see
// 1) https://bugs.webkit.org/show_bug.cgi?id=17249
// 2) https://wiki.mozilla.org/Gecko:SplitWindow
// 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
// we need to split the shadow object further into two objects:
// an outer window and an inner window. The inner window is the hidden
// prototype of the outer window. The inner window is the default
// global object of the context. A variable declared in the global
// scope is a property of the inner window.
//
// The outer window sticks to a Frame, it is exposed to JavaScript
// via window.window, window.self, window.parent, etc. The outer window
// has a security token which is the domain. The outer window cannot
// have its own properties. window.foo = 'x' is delegated to the
// inner window.
//
// When a frame navigates to a new page, the inner window is cut off
// the outer window, and the outer window identify is preserved for
// the frame. However, a new inner window is created for the new page.
// If there are JS code holds a closure to the old inner window,
// it won't be able to reach the outer window via its global object.
void V8Proxy::initContextIfNeeded()
{
// Bail out if the context has already been initialized.
if (!m_context.IsEmpty())
return;
// Install counters handler with V8.
static bool v8_counters_initialized = false;
if (!v8_counters_initialized) {
ChromiumBridge::initV8CounterFunction();
v8_counters_initialized = true;
}
// Setup the security handlers and message listener. This only has
// to be done once.
static bool v8_initialized = false;
if (!v8_initialized) {
v8_initialized = true;
// Tells V8 not to call the default OOM handler, binding code
// will handle it.
v8::V8::IgnoreOutOfMemoryException();
v8::V8::SetFatalErrorHandler(ReportFatalErrorInV8);
v8::V8::SetGlobalGCPrologueCallback(&GCPrologue);
v8::V8::SetGlobalGCEpilogueCallback(&GCEpilogue);
v8::V8::AddMessageListener(HandleConsoleMessage);
v8::V8::SetFailedAccessCheckCallbackFunction(ReportUnsafeJavaScriptAccess);
}
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Persistent<v8::ObjectTemplate> global_template =
V8DOMWindow::GetShadowObjectTemplate();
if (global_template.IsEmpty())
return;
// Install a security handler with V8.
global_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
if (ScriptController::shouldExposeGCController()) {
v8::RegisterExtension(new v8::Extension("v8/GCController",
"(function v8_GCController() {"
" var v8_gc;"
" if (gc) v8_gc = gc;"
" GCController = new Object();"
" GCController.collect ="
" function() {if (v8_gc) v8_gc(); };"
" })()"));
const char* extension_names[] = { "v8/GCController" };
v8::ExtensionConfiguration extensions(1, extension_names);
// Create a new context.
m_context = v8::Context::New(&extensions, global_template, m_global);
} else {
m_context = v8::Context::New(NULL, global_template, m_global);
}
if (m_context.IsEmpty())
return;
// Starting from now, use local context only.
v8::Local<v8::Context> context = GetContext();
v8::Context::Scope scope(context);
// Store the first global object created so we can reuse it.
if (m_global.IsEmpty()) {
m_global = v8::Persistent<v8::Object>::New(context->Global());
#ifndef NDEBUG
RegisterGlobalHandle(PROXY, this, m_global);
#endif
}
// Create a new JS window object and use it as the prototype for the
// shadow global object.
v8::Persistent<v8::FunctionTemplate> window_descriptor =
GetTemplate(V8ClassIndex::DOMWINDOW);
v8::Local<v8::Object> js_window =
SafeAllocation::NewInstance(window_descriptor->GetFunction());
if (js_window.IsEmpty())
return;
DOMWindow* window = m_frame->domWindow();
// Wrap the window.
SetDOMWrapper(js_window,
V8ClassIndex::ToInt(V8ClassIndex::DOMWINDOW),
window);
window->ref();
V8Proxy::SetJSWrapperForDOMObject(window,
v8::Persistent<v8::Object>::New(js_window));
// Insert the window instance as the prototype of the shadow object.
v8::Handle<v8::Object> v8_global = context->Global();
v8_global->Set(v8::String::New("__proto__"), js_window);
SetSecurityToken();
m_frame->loader()->dispatchWindowObjectAvailable();
if (ScriptController::RecordPlaybackMode()) {
// Inject code which overrides a few common JS functions for implementing
// randomness. In order to implement effective record & playback of
// websites, it is important that the URLs not change. Many popular web
// based apps use randomness in URLs to unique-ify urls for proxies.
// Unfortunately, this breaks playback.
// To work around this, we take the two most common client-side randomness
// generators and make them constant. They really need to be constant
// (rather than a constant seed followed by constant change)
// because the playback mode wants flexibility in how it plays them back
// and cannot always guarantee that requests for randomness are played back
// in exactly the same order in which they were recorded.
String script(
"Math.random = function() { return 0.5; };"
"__ORIGDATE__ = Date;"
"Date.__proto__.now = function() { "
" return new __ORIGDATE__(1204251968254); };"
"Date = function() { return Date.now(); };");
this->Evaluate(String(), 0, script, 0);
}
}
void V8Proxy::SetDOMException(int exception_code)
{
if (exception_code <= 0)
return;
ExceptionCodeDescription description;
getExceptionCodeDescription(exception_code, description);
v8::Handle<v8::Value> exception;
switch (description.type) {
case DOMExceptionType:
exception = ToV8Object(V8ClassIndex::DOMCOREEXCEPTION,
DOMCoreException::create(description));
break;
case RangeExceptionType:
exception = ToV8Object(V8ClassIndex::RANGEEXCEPTION,
RangeException::create(description));
break;
case EventExceptionType:
exception = ToV8Object(V8ClassIndex::EVENTEXCEPTION,
EventException::create(description));
break;
case XMLHttpRequestExceptionType:
exception = ToV8Object(V8ClassIndex::XMLHTTPREQUESTEXCEPTION,
XMLHttpRequestException::create(description));
break;
#if ENABLE(SVG)
case SVGExceptionType:
exception = ToV8Object(V8ClassIndex::SVGEXCEPTION,
SVGException::create(description));
break;
#endif
#if ENABLE(XPATH)
case XPathExceptionType:
exception = ToV8Object(V8ClassIndex::XPATHEXCEPTION,
XPathException::create(description));
break;
#endif
}
ASSERT(!exception.IsEmpty());
v8::ThrowException(exception);
}
v8::Handle<v8::Value> V8Proxy::ThrowError(ErrorType type, const char* message)
{
switch (type) {
case RANGE_ERROR:
return v8::ThrowException(v8::Exception::RangeError(v8String(message)));
case REFERENCE_ERROR:
return v8::ThrowException(
v8::Exception::ReferenceError(v8String(message)));
case SYNTAX_ERROR:
return v8::ThrowException(v8::Exception::SyntaxError(v8String(message)));
case TYPE_ERROR:
return v8::ThrowException(v8::Exception::TypeError(v8String(message)));
case GENERAL_ERROR:
return v8::ThrowException(v8::Exception::Error(v8String(message)));
default:
ASSERT(false);
return v8::Handle<v8::Value>();
}
}
v8::Local<v8::Context> V8Proxy::GetContext(Frame* frame)
{
V8Proxy* proxy = retrieve(frame);
if (!proxy)
return v8::Local<v8::Context>();
proxy->initContextIfNeeded();
return proxy->GetContext();
}
v8::Local<v8::Context> V8Proxy::GetCurrentContext()
{
return v8::Context::GetCurrent();
}
v8::Handle<v8::Value> V8Proxy::ToV8Object(V8ClassIndex::V8WrapperType type, void* imp)
{
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(type != V8ClassIndex::EVENT);
bool is_active_dom_object = false;
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
return NodeToV8Object(static_cast<Node*>(imp));
case V8ClassIndex::CSSVALUE:
return CSSValueToV8Object(static_cast<CSSValue*>(imp));
case V8ClassIndex::CSSRULE:
return CSSRuleToV8Object(static_cast<CSSRule*>(imp));
case V8ClassIndex::STYLESHEET:
return StyleSheetToV8Object(static_cast<StyleSheet*>(imp));
case V8ClassIndex::DOMWINDOW:
return WindowToV8Object(static_cast<DOMWindow*>(imp));
#if ENABLE(SVG)
SVG_NONNODE_TYPES(MAKE_CASE)
if (type == V8ClassIndex::SVGELEMENTINSTANCE)
return SVGElementInstanceToV8Object(static_cast<SVGElementInstance*>(imp));
return SVGObjectWithContextToV8Object(type, imp);
#endif
ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
is_active_dom_object = true;
break;
default:
break;
}
#undef MAKE_CASE
if (!imp) return v8::Null();
// Non DOM node
v8::Persistent<v8::Object> result = is_active_dom_object ?
active_dom_object_map().get(imp) :
dom_object_map().get(imp);
if (result.IsEmpty()) {
v8::Local<v8::Object> v8obj = InstantiateV8Object(type, type, imp);
if (!v8obj.IsEmpty()) {
// Go through big switch statement, it has some duplications
// that were handled by code above (such as CSSVALUE, CSSRULE, etc).
switch (type) {
#define MAKE_CASE(TYPE, NAME) \
case V8ClassIndex::TYPE: static_cast<NAME*>(imp)->ref(); break;
DOM_OBJECT_TYPES(MAKE_CASE)
#undef MAKE_CASE
default:
ASSERT(false);
}
result = v8::Persistent<v8::Object>::New(v8obj);
if (is_active_dom_object)
SetJSWrapperForActiveDOMObject(imp, result);
else
SetJSWrapperForDOMObject(imp, result);
// Special case for Location and Navigator. Both Safari and FF let
// Location and Navigator JS wrappers survive GC. To mimic their
// behaviors, V8 creates hidden references from the DOMWindow to
// location and navigator objects. These references get cleared
// when the DOMWindow is reused by a new page.
if (type == V8ClassIndex::LOCATION) {
SetHiddenWindowReference(static_cast<Location*>(imp)->frame(),
V8Custom::kDOMWindowLocationIndex, result);
} else if (type == V8ClassIndex::NAVIGATOR) {
SetHiddenWindowReference(static_cast<Navigator*>(imp)->frame(),
V8Custom::kDOMWindowNavigatorIndex, result);
}
}
}
return result;
}
void V8Proxy::SetHiddenWindowReference(Frame* frame,
const int internal_index,
v8::Handle<v8::Object> jsobj)
{
// Get DOMWindow
if (!frame) return; // Object might be detached from window
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty()) return;
ASSERT(internal_index < V8Custom::kDOMWindowInternalFieldCount);
v8::Handle<v8::Object> global = context->Global();
// Look for real DOM wrapper.
global = LookupDOMWrapper(V8ClassIndex::DOMWINDOW, global);
ASSERT(!global.IsEmpty());
ASSERT(global->GetInternalField(internal_index)->IsUndefined());
global->SetInternalField(internal_index, jsobj);
}
V8ClassIndex::V8WrapperType V8Proxy::GetDOMWrapperType(v8::Handle<v8::Object> object)
{
ASSERT(MaybeDOMWrapper(object));
v8::Handle<v8::Value> type =
object->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
return V8ClassIndex::FromInt(type->Int32Value());
}
void* V8Proxy::ToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
v8::Handle<v8::Value> object)
{
// Native event listener is per frame, it cannot be handled
// by this generic function.
ASSERT(type != V8ClassIndex::EVENTLISTENER);
ASSERT(type != V8ClassIndex::EVENTTARGET);
ASSERT(MaybeDOMWrapper(object));
switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
DOM_NODE_TYPES(MAKE_CASE)
#if ENABLE(SVG)
SVG_NODE_TYPES(MAKE_CASE)
#endif
ASSERT(false);
return NULL;
case V8ClassIndex::XMLHTTPREQUEST:
return DOMWrapperToNative<XMLHttpRequest>(object);
case V8ClassIndex::EVENT:
return DOMWrapperToNative<Event>(object);
case V8ClassIndex::CSSRULE:
return DOMWrapperToNative<CSSRule>(object);
default:
break;
}
#undef MAKE_CASE
return DOMWrapperToNative<void>(object);
}
v8::Handle<v8::Object> V8Proxy::LookupDOMWrapper(
V8ClassIndex::V8WrapperType type, v8::Handle<v8::Value> value)
{
if (value.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::FunctionTemplate> desc = V8Proxy::GetTemplate(type);
while (value->IsObject()) {
v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
if (desc->HasInstance(object))
return object;
value = object->GetPrototype();
}
return v8::Handle<v8::Object>();
}
PassRefPtr<NodeFilter> V8Proxy::ToNativeNodeFilter(v8::Handle<v8::Value> filter)
{
// A NodeFilter is used when walking through a DOM tree or iterating tree
// nodes.
// TODO: we may want to cache NodeFilterCondition and NodeFilter
// object, but it is minor.
// NodeFilter is passed to NodeIterator that has a ref counted pointer
// to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
// In NodeFilterCondition, filter object is persisted in its constructor,
// and disposed in its destructor.
if (!filter->IsFunction())
return 0;
NodeFilterCondition* cond = new V8NodeFilterCondition(filter);
return NodeFilter::create(cond);
}
v8::Local<v8::Object> V8Proxy::InstantiateV8Object(
V8ClassIndex::V8WrapperType desc_type,
V8ClassIndex::V8WrapperType cptr_type,
void* imp)
{
// Make a special case for document.all
if (desc_type == V8ClassIndex::HTMLCOLLECTION &&
static_cast<HTMLCollection*>(imp)->type() == HTMLCollection::DocAll) {
desc_type = V8ClassIndex::UNDETECTABLEHTMLCOLLECTION;
}
v8::Persistent<v8::FunctionTemplate> desc = GetTemplate(desc_type);
v8::Local<v8::Function> function = desc->GetFunction();
v8::Local<v8::Object> instance = SafeAllocation::NewInstance(function);
if (!instance.IsEmpty()) {
// Avoid setting the DOM wrapper for failed allocations.
SetDOMWrapper(instance, V8ClassIndex::ToInt(cptr_type), imp);
}
return instance;
}
v8::Handle<v8::Value> V8Proxy::CheckNewLegal(const v8::Arguments& args)
{
if (!AllowAllocation::m_current)
return ThrowError(TYPE_ERROR, "Illegal constructor");
return args.This();
}
void V8Proxy::SetDOMWrapper(v8::Handle<v8::Object> obj, int type, void* cptr)
{
ASSERT(obj->InternalFieldCount() >= 2);
obj->SetInternalField(V8Custom::kDOMWrapperObjectIndex, WrapCPointer(cptr));
obj->SetInternalField(V8Custom::kDOMWrapperTypeIndex, v8::Integer::New(type));
}
#ifndef NDEBUG
bool V8Proxy::MaybeDOMWrapper(v8::Handle<v8::Value> value)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
return true;
}
#endif
bool V8Proxy::IsDOMEventWrapper(v8::Handle<v8::Value> value)
{
// All kinds of events use EVENT as dom type in JS wrappers.
// See EventToV8Object
return IsWrapperOfType(value, V8ClassIndex::EVENT);
}
bool V8Proxy::IsWrapperOfType(v8::Handle<v8::Value> value,
V8ClassIndex::V8WrapperType classType)
{
if (value.IsEmpty() || !value->IsObject()) return false;
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
if (obj->InternalFieldCount() == 0) return false;
ASSERT(obj->InternalFieldCount() >=
V8Custom::kDefaultWrapperInternalFieldCount);
v8::Handle<v8::Value> wrapper =
obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
v8::Handle<v8::Value> type =
obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
ASSERT(type->IsInt32());
ASSERT(V8ClassIndex::INVALID_CLASS_INDEX < type->Int32Value() &&
type->Int32Value() < V8ClassIndex::CLASSINDEX_END);
return V8ClassIndex::FromInt(type->Int32Value()) == classType;
}
#if ENABLE(VIDEO)
#define FOR_EACH_VIDEO_TAG(macro) \
macro(audio, AUDIO) \
macro(source, SOURCE) \
macro(video, VIDEO)
#else
#define FOR_EACH_VIDEO_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
macro(a, ANCHOR) \
macro(applet, APPLET) \
macro(area, AREA) \
macro(base, BASE) \
macro(basefont, BASEFONT) \
macro(blockquote, BLOCKQUOTE) \
macro(body, BODY) \
macro(br, BR) \
macro(button, BUTTON) \
macro(caption, TABLECAPTION) \
macro(col, TABLECOL) \
macro(colgroup, TABLECOL) \
macro(del, MOD) \
macro(canvas, CANVAS) \
macro(dir, DIRECTORY) \
macro(div, DIV) \
macro(dl, DLIST) \
macro(embed, EMBED) \
macro(fieldset, FIELDSET) \
macro(font, FONT) \
macro(form, FORM) \
macro(frame, FRAME) \
macro(frameset, FRAMESET) \
macro(h1, HEADING) \
macro(h2, HEADING) \
macro(h3, HEADING) \
macro(h4, HEADING) \
macro(h5, HEADING) \
macro(h6, HEADING) \
macro(head, HEAD) \
macro(hr, HR) \
macro(html, HTML) \
macro(img, IMAGE) \
macro(iframe, IFRAME) \
macro(image, IMAGE) \
macro(input, INPUT) \
macro(ins, MOD) \
macro(isindex, ISINDEX) \
macro(keygen, SELECT) \
macro(label, LABEL) \
macro(legend, LEGEND) \
macro(li, LI) \
macro(link, LINK) \
macro(listing, PRE) \
macro(map, MAP) \
macro(marquee, MARQUEE) \
macro(menu, MENU) \
macro(meta, META) \
macro(object, OBJECT) \
macro(ol, OLIST) \
macro(optgroup, OPTGROUP) \
macro(option, OPTION) \
macro(p, PARAGRAPH) \
macro(param, PARAM) \
macro(pre, PRE) \
macro(q, QUOTE) \
macro(script, SCRIPT) \
macro(select, SELECT) \
macro(style, STYLE) \
macro(table, TABLE) \
macro(thead, TABLESECTION) \
macro(tbody, TABLESECTION) \
macro(tfoot, TABLESECTION) \
macro(td, TABLECELL) \
macro(th, TABLECELL) \
macro(tr, TABLEROW) \
macro(textarea, TEXTAREA) \
macro(title, TITLE) \
macro(ul, ULIST) \
macro(xmp, PRE) \
FOR_EACH_VIDEO_TAG(macro)
V8ClassIndex::V8WrapperType V8Proxy::GetHTMLElementType(HTMLElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::HTML##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0)
return V8ClassIndex::HTMLELEMENT;
return t;
}
#undef FOR_EACH_TAG
#if ENABLE(SVG)
#if ENABLE(SVG_ANIMATION)
#define FOR_EACH_ANIMATION_TAG(macro) \
macro(animateColor, ANIMATECOLOR) \
macro(animate, ANIMATE) \
macro(animateTransform, ANIMATETRANSFORM) \
macro(set, SET)
#else
#define FOR_EACH_ANIMATION_TAG(macro)
#endif
#if ENABLE(SVG_FILTERS)
#define FOR_EACH_FILTERS_TAG(macro) \
macro(feBlend, FEBLEND) \
macro(feColorMatrix, FECOLORMATRIX) \
macro(feComponentTransfer, FECOMPONENTTRANSFER) \
macro(feComposite, FECOMPOSITE) \
macro(feDiffuseLighting, FEDIFFUSELIGHTING) \
macro(feDisplacementMap, FEDISPLACEMENTMAP) \
macro(feDistantLight, FEDISTANTLIGHT) \
macro(feFlood, FEFLOOD) \
macro(feFuncA, FEFUNCA) \
macro(feFuncB, FEFUNCB) \
macro(feFuncG, FEFUNCG) \
macro(feFuncR, FEFUNCR) \
macro(feGaussianBlur, FEGAUSSIANBLUR) \
macro(feImage, FEIMAGE) \
macro(feMerge, FEMERGE) \
macro(feMergeNode, FEMERGENODE) \
macro(feOffset, FEOFFSET) \
macro(fePointLight, FEPOINTLIGHT) \
macro(feSpecularLighting, FESPECULARLIGHTING) \
macro(feSpotLight, FESPOTLIGHT) \
macro(feTile, FETILE) \
macro(feTurbulence, FETURBULENCE) \
macro(filter, FILTER)
#else
#define FOR_EACH_FILTERS_TAG(macro)
#endif
#if ENABLE(SVG_FONTS)
#define FOR_EACH_FONTS_TAG(macro) \
macro(definition-src, DEFINITIONSRC) \
macro(font-face, FONTFACE) \
macro(font-face-format, FONTFACEFORMAT) \
macro(font-face-name, FONTFACENAME) \
macro(font-face-src, FONTFACESRC) \
macro(font-face-uri, FONTFACEURI)
#else
#define FOR_EACH_FONTS_TAG(marco)
#endif
#if ENABLE(SVG_FOREIGN_OBJECT)
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
macro(foreignObject, FOREIGNOBJECT)
#else
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro)
#endif
#if ENABLE(SVG_USE)
#define FOR_EACH_USE_TAG(macro) \
macro(use, USE)
#else
#define FOR_EACH_USE_TAG(macro)
#endif
#define FOR_EACH_TAG(macro) \
FOR_EACH_ANIMATION_TAG(macro) \
FOR_EACH_FILTERS_TAG(macro) \
FOR_EACH_FONTS_TAG(macro) \
FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
FOR_EACH_USE_TAG(macro) \
macro(a, A) \
macro(altGlyph, ALTGLYPH) \
macro(circle, CIRCLE) \
macro(clipPath, CLIPPATH) \
macro(cursor, CURSOR) \
macro(defs, DEFS) \
macro(desc, DESC) \
macro(ellipse, ELLIPSE) \
macro(g, G) \
macro(glyph, GLYPH) \
macro(image, IMAGE) \
macro(linearGradient, LINEARGRADIENT) \
macro(line, LINE) \
macro(marker, MARKER) \
macro(mask, MASK) \
macro(metadata, METADATA) \
macro(path, PATH) \
macro(pattern, PATTERN) \
macro(polyline, POLYLINE) \
macro(polygon, POLYGON) \
macro(radialGradient, RADIALGRADIENT) \
macro(rect, RECT) \
macro(script, SCRIPT) \
macro(stop, STOP) \
macro(style, STYLE) \
macro(svg, SVG) \
macro(switch, SWITCH) \
macro(symbol, SYMBOL) \
macro(text, TEXT) \
macro(textPath, TEXTPATH) \
macro(title, TITLE) \
macro(tref, TREF) \
macro(tspan, TSPAN) \
macro(view, VIEW) \
// end of macro
V8ClassIndex::V8WrapperType V8Proxy::GetSVGElementType(SVGElement* element)
{
static HashMap<String, V8ClassIndex::V8WrapperType> map;
if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
map.set(#tag, V8ClassIndex::SVG##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
}
V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
if (t == 0) return V8ClassIndex::SVGELEMENT;
return t;
}
#undef FOR_EACH_TAG
#endif // ENABLE(SVG)
v8::Handle<v8::Value> V8Proxy::EventToV8Object(Event* event)
{
if (!event)
return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(event);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT;
if (event->isUIEvent()) {
if (event->isKeyboardEvent())
type = V8ClassIndex::KEYBOARDEVENT;
else if (event->isTextEvent())
type = V8ClassIndex::TEXTEVENT;
else if (event->isMouseEvent())
type = V8ClassIndex::MOUSEEVENT;
else if (event->isWheelEvent())
type = V8ClassIndex::WHEELEVENT;
#if ENABLE(SVG)
else if (event->isSVGZoomEvent())
type = V8ClassIndex::SVGZOOMEVENT;
#endif
else
type = V8ClassIndex::UIEVENT;
} else if (event->isMutationEvent())
type = V8ClassIndex::MUTATIONEVENT;
else if (event->isOverflowEvent())
type = V8ClassIndex::OVERFLOWEVENT;
else if (event->isMessageEvent())
type = V8ClassIndex::MESSAGEEVENT;
else if (event->isProgressEvent()) {
if (event->isXMLHttpRequestProgressEvent())
type = V8ClassIndex::XMLHTTPREQUESTPROGRESSEVENT;
else
type = V8ClassIndex::PROGRESSEVENT;
} else if (event->isWebKitAnimationEvent())
type = V8ClassIndex::WEBKITANIMATIONEVENT;
else if (event->isWebKitTransitionEvent())
type = V8ClassIndex::WEBKITTRANSITIONEVENT;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::EVENT, event);
if (result.IsEmpty()) {
// Instantiation failed. Avoid updating the DOM object map and
// return null which is already handled by callers of this function
// in case the event is NULL.
return v8::Null();
}
event->ref(); // fast ref
SetJSWrapperForDOMObject(event, v8::Persistent<v8::Object>::New(result));
return result;
}
// Caller checks node is not null.
v8::Handle<v8::Value> V8Proxy::NodeToV8Object(Node* node)
{
if (!node) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_node_map().get(node);
if (!wrapper.IsEmpty())
return wrapper;
bool is_document = false; // document type node has special handling
V8ClassIndex::V8WrapperType type;
switch (node->nodeType()) {
case Node::ELEMENT_NODE:
if (node->isHTMLElement())
type = GetHTMLElementType(static_cast<HTMLElement*>(node));
#if ENABLE(SVG)
else if (node->isSVGElement())
type = GetSVGElementType(static_cast<SVGElement*>(node));
#endif
else
type = V8ClassIndex::ELEMENT;
break;
case Node::ATTRIBUTE_NODE:
type = V8ClassIndex::ATTR;
break;
case Node::TEXT_NODE:
type = V8ClassIndex::TEXT;
break;
case Node::CDATA_SECTION_NODE:
type = V8ClassIndex::CDATASECTION;
break;
case Node::ENTITY_NODE:
type = V8ClassIndex::ENTITY;
break;
case Node::PROCESSING_INSTRUCTION_NODE:
type = V8ClassIndex::PROCESSINGINSTRUCTION;
break;
case Node::COMMENT_NODE:
type = V8ClassIndex::COMMENT;
break;
case Node::DOCUMENT_NODE: {
is_document = true;
Document* doc = static_cast<Document*>(node);
if (doc->isHTMLDocument())
type = V8ClassIndex::HTMLDOCUMENT;
#if ENABLE(SVG)
else if (doc->isSVGDocument())
type = V8ClassIndex::SVGDOCUMENT;
#endif
else
type = V8ClassIndex::DOCUMENT;
break;
}
case Node::DOCUMENT_TYPE_NODE:
type = V8ClassIndex::DOCUMENTTYPE;
break;
case Node::NOTATION_NODE:
type = V8ClassIndex::NOTATION;
break;
case Node::DOCUMENT_FRAGMENT_NODE:
type = V8ClassIndex::DOCUMENTFRAGMENT;
break;
case Node::ENTITY_REFERENCE_NODE:
type = V8ClassIndex::ENTITYREFERENCE;
break;
default:
type = V8ClassIndex::NODE;
}
// Find the context to which the node belongs and create the wrapper
// in that context. If the node is not in a document, the current
// context is used.
v8::Local<v8::Context> context;
Document* doc = node->document();
if (doc) {
context = V8Proxy::GetContext(doc->frame());
}
if (!context.IsEmpty()) {
context->Enter();
}
v8::Local<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::NODE, node);
// Exit the node's context if it was entered.
if (!context.IsEmpty()) {
context->Exit();
}
if (result.IsEmpty()) {
// If instantiation failed it's important not to add the result
// to the DOM node map. Instead we return an empty handle, which
// should already be handled by callers of this function in case
// the node is NULL.
return result;
}
node->ref();
SetJSWrapperForDOMNode(node, v8::Persistent<v8::Object>::New(result));
if (is_document) {
Document* doc = static_cast<Document*>(node);
V8Proxy* proxy = V8Proxy::retrieve(doc->frame());
if (proxy)
proxy->UpdateDocumentWrapper(result);
if (type == V8ClassIndex::HTMLDOCUMENT) {
// Create marker object and insert it in two internal fields.
// This is used to implement temporary shadowing of
// document.all.
ASSERT(result->InternalFieldCount() ==
V8Custom::kHTMLDocumentInternalFieldCount);
v8::Local<v8::Object> marker = v8::Object::New();
result->SetInternalField(V8Custom::kHTMLDocumentMarkerIndex, marker);
result->SetInternalField(V8Custom::kHTMLDocumentShadowIndex, marker);
}
}
return result;
}
// A JS object of type EventTarget can only be five possible types:
// 1) EventTargetNode; 2) XMLHttpRequest; 3) MessagePort; 4) SVGElementInstance;
// 5) XMLHttpRequestUpload
// check EventTarget.h for new type conversion methods
// also make sure to sync with V8EventListener::GetThisObject (v8_events.cpp)
v8::Handle<v8::Value> V8Proxy::EventTargetToV8Object(EventTarget* target)
{
if (!target)
return v8::Null();
#if ENABLE(SVG)
SVGElementInstance* instance = target->toSVGElementInstance();
if (instance)
return ToV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
#endif
Node* node = target->toNode();
if (node)
return NodeToV8Object(node);
// XMLHttpRequest is created within its JS counterpart.
XMLHttpRequest* xhr = target->toXMLHttpRequest();
if (xhr) {
v8::Handle<v8::Object> wrapper = active_dom_object_map().get(xhr);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
// MessagePort is created within its JS counterpart
MessagePort* port = target->toMessagePort();
if (port) {
v8::Handle<v8::Object> wrapper = active_dom_object_map().get(port);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload();
if (upload) {
v8::Handle<v8::Object> wrapper = dom_object_map().get(upload);
ASSERT(!wrapper.IsEmpty());
return wrapper;
}
ASSERT(0);
return v8::Handle<v8::Value>();
}
v8::Handle<v8::Value> V8Proxy::EventListenerToV8Object(
EventListener* listener)
{
if (listener == 0) return v8::Null();
// TODO(fqian): can a user take a lazy event listener and set to other places?
V8AbstractEventListener* v8listener =
static_cast<V8AbstractEventListener*>(listener);
return v8listener->GetListenerObject();
}
v8::Handle<v8::Value> V8Proxy::DOMImplementationToV8Object(
DOMImplementation* impl)
{
v8::Handle<v8::Object> result =
InstantiateV8Object(V8ClassIndex::DOMIMPLEMENTATION,
V8ClassIndex::DOMIMPLEMENTATION,
impl);
if (result.IsEmpty()) {
// If the instantiation failed, we ignore it and return null instead
// of returning an empty handle.
return v8::Null();
}
return result;
}
v8::Handle<v8::Value> V8Proxy::StyleSheetToV8Object(StyleSheet* sheet)
{
if (!sheet) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(sheet);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type = V8ClassIndex::STYLESHEET;
if (sheet->isCSSStyleSheet())
type = V8ClassIndex::CSSSTYLESHEET;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::STYLESHEET, sheet);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
sheet->ref();
SetJSWrapperForDOMObject(sheet, v8::Persistent<v8::Object>::New(result));
}
// Add a hidden reference from stylesheet object to its owner node.
Node* owner_node = sheet->ownerNode();
if (owner_node) {
v8::Handle<v8::Object> owner =
v8::Handle<v8::Object>::Cast(NodeToV8Object(owner_node));
result->SetInternalField(V8Custom::kStyleSheetOwnerNodeIndex, owner);
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSValueToV8Object(CSSValue* value)
{
if (!value) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(value);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
if (value->isWebKitCSSTransformValue())
type = V8ClassIndex::WEBKITCSSTRANSFORMVALUE;
else if (value->isValueList())
type = V8ClassIndex::CSSVALUELIST;
else if (value->isPrimitiveValue())
type = V8ClassIndex::CSSPRIMITIVEVALUE;
#if ENABLE(SVG)
else if (value->isSVGPaint())
type = V8ClassIndex::SVGPAINT;
else if (value->isSVGColor())
type = V8ClassIndex::SVGCOLOR;
#endif
else
type = V8ClassIndex::CSSVALUE;
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSVALUE, value);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
value->ref();
SetJSWrapperForDOMObject(value, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::CSSRuleToV8Object(CSSRule* rule)
{
if (!rule) return v8::Null();
v8::Handle<v8::Object> wrapper = dom_object_map().get(rule);
if (!wrapper.IsEmpty())
return wrapper;
V8ClassIndex::V8WrapperType type;
switch (rule->type()) {
case CSSRule::STYLE_RULE:
type = V8ClassIndex::CSSSTYLERULE;
break;
case CSSRule::CHARSET_RULE:
type = V8ClassIndex::CSSCHARSETRULE;
break;
case CSSRule::IMPORT_RULE:
type = V8ClassIndex::CSSIMPORTRULE;
break;
case CSSRule::MEDIA_RULE:
type = V8ClassIndex::CSSMEDIARULE;
break;
case CSSRule::FONT_FACE_RULE:
type = V8ClassIndex::CSSFONTFACERULE;
break;
case CSSRule::PAGE_RULE:
type = V8ClassIndex::CSSPAGERULE;
break;
case CSSRule::VARIABLES_RULE:
type = V8ClassIndex::CSSVARIABLESRULE;
break;
case CSSRule::WEBKIT_KEYFRAME_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMERULE;
break;
case CSSRule::WEBKIT_KEYFRAMES_RULE:
type = V8ClassIndex::WEBKITCSSKEYFRAMESRULE;
break;
default: // CSSRule::UNKNOWN_RULE
type = V8ClassIndex::CSSRULE;
break;
}
v8::Handle<v8::Object> result =
InstantiateV8Object(type, V8ClassIndex::CSSRULE, rule);
if (!result.IsEmpty()) {
// Only update the DOM object map if the result is non-empty.
rule->ref();
SetJSWrapperForDOMObject(rule, v8::Persistent<v8::Object>::New(result));
}
return result;
}
v8::Handle<v8::Value> V8Proxy::WindowToV8Object(DOMWindow* window)
{
if (!window) return v8::Null();
// Initializes environment of a frame, and return the global object
// of the frame.
Frame* frame = window->frame();
if (!frame)
return v8::Handle<v8::Object>();
v8::Handle<v8::Context> context = GetContext(frame);
if (context.IsEmpty())
return v8::Handle<v8::Object>();
v8::Handle<v8::Object> global = context->Global();
ASSERT(!global.IsEmpty());
return global;
}
void V8Proxy::BindJSObjectToWindow(Frame* frame,
const char* name,
int type,
v8::Handle<v8::FunctionTemplate> desc,
void* imp)
{
// Get environment.
v8::Handle<v8::Context> context = V8Proxy::GetContext(frame);
if (context.IsEmpty())
return; // JS not enabled.
v8::Context::Scope scope(context);
v8::Handle<v8::Object> instance = desc->GetFunction();
SetDOMWrapper(instance, type, imp);
v8::Handle<v8::Object> global = context->Global();
global->Set(v8::String::New(name), instance);
}
void V8Proxy::ProcessConsoleMessages()
{
ConsoleMessageManager::ProcessDelayedMessages();
}
} // namespace WebCore
|
#include <boost/test/unit_test.hpp>
//#include "clotho/powerset/powerset.hpp"
#include "clotho/powerset/variable_subset.hpp"
struct test_element {
double k, v;
test_element( double _k = 0., double _v = 0.) : k (_k), v(_v) {}
test_element( const test_element & t ) : k(t.k), v(t.v) {}
friend bool operator==( const test_element & lhs, const test_element & rhs );
friend bool operator!=( const test_element & lhs, const test_element & rhs );
};
inline bool operator==( const test_element & lhs, const test_element & rhs ) {
return ( lhs.k == rhs.k && lhs.v == rhs.v);
}
inline bool operator!=( const test_element & lhs, const test_element & rhs ) {
return ( lhs.k != rhs.k && lhs.v != rhs.v);
}
namespace clotho {
namespace powersets {
template <>
struct element_key_of< test_element > {
typedef double key_type;
inline key_type operator()( const test_element & t ) { return t.k; }
};
template< class Block >
struct block_map< test_element, Block > {
typedef test_element element_type;
typedef Block size_type;
static const unsigned int bits_per_block = sizeof(size_type) * 8;
inline size_type operator()( const element_type & elem ) {
assert( 0. < elem.k && elem.k < 1. );
return elem.k * bits_per_block;
}
};
} // namespace powersets
} // namespace clotho
typedef clotho::powersets::variable_subset< test_element > subset_type;
typedef typename subset_type::powerset_type powerset_type;
BOOST_AUTO_TEST_SUITE( test_powerset )
BOOST_AUTO_TEST_CASE( create_powerset ) {
powerset_type ps;
typename powerset_type::block_map_type bmap;
double k = 0.5;
test_element te( k, 2.0 );
typename powerset_type::element_index_type idx = ps.find_or_create(te);
BOOST_REQUIRE_MESSAGE( idx == bmap(te), "Unexpected index returned" );
}
BOOST_AUTO_TEST_SUITE_END()
added basic unit tests
#include <boost/test/unit_test.hpp>
//#include "clotho/powerset/powerset.hpp"
#include "clotho/powerset/variable_subset.hpp"
struct test_element {
double k, v;
test_element( double _k = 0., double _v = 0.) : k (_k), v(_v) {}
test_element( const test_element & t ) : k(t.k), v(t.v) {}
friend bool operator==( const test_element & lhs, const test_element & rhs );
friend bool operator!=( const test_element & lhs, const test_element & rhs );
};
inline bool operator==( const test_element & lhs, const test_element & rhs ) {
return ( lhs.k == rhs.k && lhs.v == rhs.v);
}
inline bool operator!=( const test_element & lhs, const test_element & rhs ) {
return ( lhs.k != rhs.k && lhs.v != rhs.v);
}
namespace clotho {
namespace powersets {
template <>
struct element_key_of< test_element > {
typedef double key_type;
inline key_type operator()( const test_element & t ) { return t.k; }
};
template< class Block >
struct block_map< test_element, Block > {
typedef test_element element_type;
typedef Block size_type;
static const unsigned int bits_per_block = sizeof(size_type) * 8;
inline size_type operator()( const element_type & elem ) {
assert( 0. <= elem.k && elem.k < 1. );
return elem.k * bits_per_block;
}
};
} // namespace powersets
} // namespace clotho
typedef clotho::powersets::variable_subset< test_element > subset_type;
typedef typename subset_type::powerset_type powerset_type;
typedef powerset_type::block_map_type bmap;
BOOST_AUTO_TEST_SUITE( test_powerset )
BOOST_AUTO_TEST_CASE( create_powerset_simple) {
powerset_type ps;
double k = 0.75;
test_element te( k, 2.0 );
typename powerset_type::element_index_type idx = ps.find_or_create(te);
BOOST_REQUIRE_MESSAGE( idx == bmap()(te), "Unexpected index returned" );
BOOST_REQUIRE_MESSAGE( ps.size() == 1, "Unexpected size" );
BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() );
}
BOOST_AUTO_TEST_CASE( create_powerset_width ) {
powerset_type ps;
BOOST_REQUIRE_MESSAGE( ps.empty(), "Unexpected size" );
for( unsigned int i = 0; i < bmap::bits_per_block; ++i ) {
double v = (double) i;
double k = v / (double) bmap::bits_per_block;
test_element te(k, 1.0);
typename powerset_type::element_index_type idx = ps.find_or_create(te);
BOOST_REQUIRE_MESSAGE( idx == i, "Unexpected index " << idx << " returned for " << i << "(" << k << ")" );
}
BOOST_REQUIRE_MESSAGE( ps.size() == bmap::bits_per_block, "Unexpected size" );
}
BOOST_AUTO_TEST_SUITE_END()
|
//===- unittests/ADT/IListIteratorTest.cpp - ilist_iterator unit tests ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/simple_ilist.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
struct Node : ilist_node<Node> {};
TEST(IListIteratorTest, DefaultConstructor) {
simple_ilist<Node>::iterator I;
simple_ilist<Node>::reverse_iterator RI;
simple_ilist<Node>::const_iterator CI;
simple_ilist<Node>::const_reverse_iterator CRI;
EXPECT_EQ(nullptr, I.getNodePtr());
EXPECT_EQ(nullptr, CI.getNodePtr());
EXPECT_EQ(nullptr, RI.getNodePtr());
EXPECT_EQ(nullptr, CRI.getNodePtr());
EXPECT_EQ(I, I);
EXPECT_EQ(I, CI);
EXPECT_EQ(CI, I);
EXPECT_EQ(CI, CI);
EXPECT_EQ(RI, RI);
EXPECT_EQ(RI, CRI);
EXPECT_EQ(CRI, RI);
EXPECT_EQ(CRI, CRI);
EXPECT_EQ(I, RI.getReverse());
EXPECT_EQ(RI, I.getReverse());
}
TEST(IListIteratorTest, Empty) {
simple_ilist<Node> L;
// Check iterators of L.
EXPECT_EQ(L.begin(), L.end());
EXPECT_EQ(L.rbegin(), L.rend());
// Reverse of end should be rend (since the sentinel sits on both sides).
EXPECT_EQ(L.end(), L.rend().getReverse());
EXPECT_EQ(L.rend(), L.end().getReverse());
// Iterators shouldn't match default constructors.
simple_ilist<Node>::iterator I;
simple_ilist<Node>::reverse_iterator RI;
EXPECT_NE(I, L.begin());
EXPECT_NE(I, L.end());
EXPECT_NE(RI, L.rbegin());
EXPECT_NE(RI, L.rend());
}
TEST(IListIteratorTest, OneNodeList) {
simple_ilist<Node> L;
Node A;
L.insert(L.end(), A);
// Check address of reference.
EXPECT_EQ(&A, &*L.begin());
EXPECT_EQ(&A, &*L.rbegin());
// Check that the handle matches.
EXPECT_EQ(L.rbegin().getNodePtr(), L.begin().getNodePtr());
// Check iteration.
EXPECT_EQ(L.end(), ++L.begin());
EXPECT_EQ(L.begin(), --L.end());
EXPECT_EQ(L.rend(), ++L.rbegin());
EXPECT_EQ(L.rbegin(), --L.rend());
// Check conversions.
EXPECT_EQ(L.rbegin(), L.begin().getReverse());
EXPECT_EQ(L.begin(), L.rbegin().getReverse());
}
TEST(IListIteratorTest, TwoNodeList) {
simple_ilist<Node> L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Check order.
EXPECT_EQ(&A, &*L.begin());
EXPECT_EQ(&B, &*++L.begin());
EXPECT_EQ(L.end(), ++++L.begin());
EXPECT_EQ(&B, &*L.rbegin());
EXPECT_EQ(&A, &*++L.rbegin());
EXPECT_EQ(L.rend(), ++++L.rbegin());
// Check conversions.
EXPECT_EQ(++L.rbegin(), L.begin().getReverse());
EXPECT_EQ(L.rbegin(), (++L.begin()).getReverse());
EXPECT_EQ(++L.begin(), L.rbegin().getReverse());
EXPECT_EQ(L.begin(), (++L.rbegin()).getReverse());
}
TEST(IListIteratorTest, CheckEraseForward) {
simple_ilist<Node> L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Erase nodes.
auto I = L.begin();
EXPECT_EQ(&A, &*I);
L.remove(*I++);
EXPECT_EQ(&B, &*I);
L.remove(*I++);
EXPECT_EQ(L.end(), I);
}
TEST(IListIteratorTest, CheckEraseReverse) {
simple_ilist<Node> L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Erase nodes.
auto RI = L.rbegin();
EXPECT_EQ(&B, &*RI);
L.remove(*RI++);
EXPECT_EQ(&A, &*RI);
L.remove(*RI++);
EXPECT_EQ(L.rend(), RI);
}
TEST(IListIteratorTest, ReverseConstructor) {
simple_ilist<Node> L;
const simple_ilist<Node> &CL = L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Save typing.
typedef simple_ilist<Node>::iterator iterator;
typedef simple_ilist<Node>::reverse_iterator reverse_iterator;
typedef simple_ilist<Node>::const_iterator const_iterator;
typedef simple_ilist<Node>::const_reverse_iterator const_reverse_iterator;
// Check conversion values.
EXPECT_EQ(L.begin(), iterator(L.rend()));
EXPECT_EQ(++L.begin(), iterator(++L.rbegin()));
EXPECT_EQ(L.end(), iterator(L.rbegin()));
EXPECT_EQ(L.rbegin(), reverse_iterator(L.end()));
EXPECT_EQ(++L.rbegin(), reverse_iterator(++L.begin()));
EXPECT_EQ(L.rend(), reverse_iterator(L.begin()));
// Check const iterator constructors.
EXPECT_EQ(CL.begin(), const_iterator(L.rend()));
EXPECT_EQ(CL.begin(), const_iterator(CL.rend()));
EXPECT_EQ(CL.rbegin(), const_reverse_iterator(L.end()));
EXPECT_EQ(CL.rbegin(), const_reverse_iterator(CL.end()));
// Confirm lack of implicit conversions.
static_assert(std::is_convertible<iterator, reverse_iterator>::value,
"unexpected implicit conversion");
static_assert(std::is_convertible<reverse_iterator, iterator>::value,
"unexpected implicit conversion");
static_assert(
std::is_convertible<const_iterator, const_reverse_iterator>::value,
"unexpected implicit conversion");
static_assert(
std::is_convertible<const_reverse_iterator, const_iterator>::value,
"unexpected implicit conversion");
}
} // end namespace
Fix some missing negations in the traits checking from r294349
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@294357 91177308-0d34-0410-b5e6-96231b3b80d8
//===- unittests/ADT/IListIteratorTest.cpp - ilist_iterator unit tests ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/simple_ilist.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
struct Node : ilist_node<Node> {};
TEST(IListIteratorTest, DefaultConstructor) {
simple_ilist<Node>::iterator I;
simple_ilist<Node>::reverse_iterator RI;
simple_ilist<Node>::const_iterator CI;
simple_ilist<Node>::const_reverse_iterator CRI;
EXPECT_EQ(nullptr, I.getNodePtr());
EXPECT_EQ(nullptr, CI.getNodePtr());
EXPECT_EQ(nullptr, RI.getNodePtr());
EXPECT_EQ(nullptr, CRI.getNodePtr());
EXPECT_EQ(I, I);
EXPECT_EQ(I, CI);
EXPECT_EQ(CI, I);
EXPECT_EQ(CI, CI);
EXPECT_EQ(RI, RI);
EXPECT_EQ(RI, CRI);
EXPECT_EQ(CRI, RI);
EXPECT_EQ(CRI, CRI);
EXPECT_EQ(I, RI.getReverse());
EXPECT_EQ(RI, I.getReverse());
}
TEST(IListIteratorTest, Empty) {
simple_ilist<Node> L;
// Check iterators of L.
EXPECT_EQ(L.begin(), L.end());
EXPECT_EQ(L.rbegin(), L.rend());
// Reverse of end should be rend (since the sentinel sits on both sides).
EXPECT_EQ(L.end(), L.rend().getReverse());
EXPECT_EQ(L.rend(), L.end().getReverse());
// Iterators shouldn't match default constructors.
simple_ilist<Node>::iterator I;
simple_ilist<Node>::reverse_iterator RI;
EXPECT_NE(I, L.begin());
EXPECT_NE(I, L.end());
EXPECT_NE(RI, L.rbegin());
EXPECT_NE(RI, L.rend());
}
TEST(IListIteratorTest, OneNodeList) {
simple_ilist<Node> L;
Node A;
L.insert(L.end(), A);
// Check address of reference.
EXPECT_EQ(&A, &*L.begin());
EXPECT_EQ(&A, &*L.rbegin());
// Check that the handle matches.
EXPECT_EQ(L.rbegin().getNodePtr(), L.begin().getNodePtr());
// Check iteration.
EXPECT_EQ(L.end(), ++L.begin());
EXPECT_EQ(L.begin(), --L.end());
EXPECT_EQ(L.rend(), ++L.rbegin());
EXPECT_EQ(L.rbegin(), --L.rend());
// Check conversions.
EXPECT_EQ(L.rbegin(), L.begin().getReverse());
EXPECT_EQ(L.begin(), L.rbegin().getReverse());
}
TEST(IListIteratorTest, TwoNodeList) {
simple_ilist<Node> L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Check order.
EXPECT_EQ(&A, &*L.begin());
EXPECT_EQ(&B, &*++L.begin());
EXPECT_EQ(L.end(), ++++L.begin());
EXPECT_EQ(&B, &*L.rbegin());
EXPECT_EQ(&A, &*++L.rbegin());
EXPECT_EQ(L.rend(), ++++L.rbegin());
// Check conversions.
EXPECT_EQ(++L.rbegin(), L.begin().getReverse());
EXPECT_EQ(L.rbegin(), (++L.begin()).getReverse());
EXPECT_EQ(++L.begin(), L.rbegin().getReverse());
EXPECT_EQ(L.begin(), (++L.rbegin()).getReverse());
}
TEST(IListIteratorTest, CheckEraseForward) {
simple_ilist<Node> L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Erase nodes.
auto I = L.begin();
EXPECT_EQ(&A, &*I);
L.remove(*I++);
EXPECT_EQ(&B, &*I);
L.remove(*I++);
EXPECT_EQ(L.end(), I);
}
TEST(IListIteratorTest, CheckEraseReverse) {
simple_ilist<Node> L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Erase nodes.
auto RI = L.rbegin();
EXPECT_EQ(&B, &*RI);
L.remove(*RI++);
EXPECT_EQ(&A, &*RI);
L.remove(*RI++);
EXPECT_EQ(L.rend(), RI);
}
TEST(IListIteratorTest, ReverseConstructor) {
simple_ilist<Node> L;
const simple_ilist<Node> &CL = L;
Node A, B;
L.insert(L.end(), A);
L.insert(L.end(), B);
// Save typing.
typedef simple_ilist<Node>::iterator iterator;
typedef simple_ilist<Node>::reverse_iterator reverse_iterator;
typedef simple_ilist<Node>::const_iterator const_iterator;
typedef simple_ilist<Node>::const_reverse_iterator const_reverse_iterator;
// Check conversion values.
EXPECT_EQ(L.begin(), iterator(L.rend()));
EXPECT_EQ(++L.begin(), iterator(++L.rbegin()));
EXPECT_EQ(L.end(), iterator(L.rbegin()));
EXPECT_EQ(L.rbegin(), reverse_iterator(L.end()));
EXPECT_EQ(++L.rbegin(), reverse_iterator(++L.begin()));
EXPECT_EQ(L.rend(), reverse_iterator(L.begin()));
// Check const iterator constructors.
EXPECT_EQ(CL.begin(), const_iterator(L.rend()));
EXPECT_EQ(CL.begin(), const_iterator(CL.rend()));
EXPECT_EQ(CL.rbegin(), const_reverse_iterator(L.end()));
EXPECT_EQ(CL.rbegin(), const_reverse_iterator(CL.end()));
// Confirm lack of implicit conversions.
static_assert(!std::is_convertible<iterator, reverse_iterator>::value,
"unexpected implicit conversion");
static_assert(!std::is_convertible<reverse_iterator, iterator>::value,
"unexpected implicit conversion");
static_assert(
!std::is_convertible<const_iterator, const_reverse_iterator>::value,
"unexpected implicit conversion");
static_assert(
!std::is_convertible<const_reverse_iterator, const_iterator>::value,
"unexpected implicit conversion");
}
} // end namespace
|
//=== - llvm/unittest/Support/Alignment.cpp - Alignment utility tests -----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Alignment.h"
#include "gtest/gtest.h"
#include <vector>
using namespace llvm;
namespace {
std::vector<uint64_t> getValidAlignments() {
std::vector<uint64_t> Out;
for (size_t Shift = 0; Shift < 64; ++Shift)
Out.push_back(1ULL << Shift);
return Out;
}
// We use a subset of valid alignments for DEATH_TESTs as they are particularly
// slow.
std::vector<uint64_t> getValidAlignmentsForDeathTest() {
return {1, 1ULL << 31, 1ULL << 63};
}
std::vector<uint64_t> getNonPowerOfTwo() { return {3, 10, 15}; }
TEST(Alignment, AlignDefaultCTor) { EXPECT_EQ(Align().value(), 1ULL); }
TEST(Alignment, MaybeAlignDefaultCTor) {
EXPECT_FALSE(MaybeAlign().hasValue());
}
TEST(Alignment, ValidCTors) {
for (size_t Value : getValidAlignments()) {
EXPECT_EQ(Align(Value).value(), Value);
EXPECT_EQ((*MaybeAlign(Value)).value(), Value);
}
}
TEST(Alignment, InvalidCTors) {
EXPECT_DEATH((Align(0)), "Value must not be 0");
for (size_t Value : getNonPowerOfTwo()) {
EXPECT_DEATH((Align(Value)), "Alignment is not a power of 2");
EXPECT_DEATH((MaybeAlign(Value)), "Alignment is not 0 or a power of 2");
}
}
TEST(Alignment, CheckMaybeAlignHasValue) {
EXPECT_TRUE(MaybeAlign(1));
EXPECT_TRUE(MaybeAlign(1).hasValue());
EXPECT_FALSE(MaybeAlign(0));
EXPECT_FALSE(MaybeAlign(0).hasValue());
EXPECT_FALSE(MaybeAlign());
EXPECT_FALSE(MaybeAlign().hasValue());
}
TEST(Alignment, CantConvertUnsetMaybe) {
EXPECT_DEATH((MaybeAlign(0).getValue()), ".*");
}
TEST(Alignment, Division) {
for (size_t Value : getValidAlignments()) {
if (Value == 1) {
EXPECT_DEATH(Align(Value) / 2, "Can't halve byte alignment");
EXPECT_DEATH(MaybeAlign(Value) / 2, "Can't halve byte alignment");
} else {
EXPECT_EQ(Align(Value) / 2, Value / 2);
EXPECT_EQ(MaybeAlign(Value) / 2, Value / 2);
}
}
EXPECT_EQ(MaybeAlign(0) / 2, MaybeAlign(0));
EXPECT_DEATH(Align(8) / 0, "Divisor must be positive and a power of 2");
EXPECT_DEATH(Align(8) / 3, "Divisor must be positive and a power of 2");
}
TEST(Alignment, AlignTo) {
struct {
uint64_t alignment;
uint64_t offset;
uint64_t rounded;
} kTests[] = {
// MaybeAlign
{0, 0, 0},
{0, 1, 1},
{0, 5, 5},
// MaybeAlign / Align
{1, 0, 0},
{1, 1, 1},
{1, 5, 5},
{2, 0, 0},
{2, 1, 2},
{2, 2, 2},
{2, 7, 8},
{2, 16, 16},
{4, 0, 0},
{4, 1, 4},
{4, 4, 4},
{4, 6, 8},
};
for (const auto &T : kTests) {
MaybeAlign A(T.alignment);
// Test MaybeAlign
EXPECT_EQ(alignTo(T.offset, A), T.rounded);
// Test Align
if (A)
EXPECT_EQ(alignTo(T.offset, A.getValue()), T.rounded);
}
}
TEST(Alignment, Log2) {
for (size_t Value : getValidAlignments()) {
EXPECT_EQ(Log2(Align(Value)), Log2_64(Value));
EXPECT_EQ(Log2(MaybeAlign(Value)), Log2_64(Value));
}
EXPECT_DEATH(Log2(MaybeAlign(0)), ".* should be defined");
}
TEST(Alignment, MinAlign) {
struct {
uint64_t A;
uint64_t B;
uint64_t MinAlign;
} kTests[] = {
// MaybeAlign
{0, 0, 0},
{0, 8, 8},
{2, 0, 2},
// MaybeAlign / Align
{1, 2, 1},
{8, 4, 4},
};
for (const auto &T : kTests) {
EXPECT_EQ(commonAlignment(MaybeAlign(T.A), MaybeAlign(T.B)), T.MinAlign);
EXPECT_EQ(MinAlign(T.A, T.B), T.MinAlign);
if (T.A)
EXPECT_EQ(commonAlignment(Align(T.A), MaybeAlign(T.B)), T.MinAlign);
if (T.B)
EXPECT_EQ(commonAlignment(MaybeAlign(T.A), Align(T.B)), T.MinAlign);
if (T.A && T.B)
EXPECT_EQ(commonAlignment(Align(T.A), Align(T.B)), T.MinAlign);
}
}
TEST(Alignment, Encode_Decode) {
for (size_t Value : getValidAlignments()) {
{
Align Actual(Value);
Align Expected = decodeMaybeAlign(encode(Actual)).getValue();
EXPECT_EQ(Expected, Actual);
}
{
MaybeAlign Actual(Value);
MaybeAlign Expected = decodeMaybeAlign(encode(Actual));
EXPECT_EQ(Expected, Actual);
}
}
MaybeAlign Actual(0);
MaybeAlign Expected = decodeMaybeAlign(encode(Actual));
EXPECT_EQ(Expected, Actual);
}
TEST(Alignment, isAligned) {
struct {
uint64_t alignment;
uint64_t offset;
bool isAligned;
} kTests[] = {
// MaybeAlign / Align
{1, 0, true}, {1, 1, true}, {1, 5, true}, {2, 0, true},
{2, 1, false}, {2, 2, true}, {2, 7, false}, {2, 16, true},
{4, 0, true}, {4, 1, false}, {4, 4, true}, {4, 6, false},
};
for (const auto &T : kTests) {
MaybeAlign A(T.alignment);
// Test MaybeAlign
EXPECT_EQ(isAligned(A, T.offset), T.isAligned);
// Test Align
if (A)
EXPECT_EQ(isAligned(A.getValue(), T.offset), T.isAligned);
}
}
TEST(Alignment, AlignComparisons) {
std::vector<uint64_t> ValidAlignments = getValidAlignments();
std::sort(ValidAlignments.begin(), ValidAlignments.end());
for (size_t I = 1; I < ValidAlignments.size(); ++I) {
assert(I >= 1);
const Align A(ValidAlignments[I - 1]);
const Align B(ValidAlignments[I]);
EXPECT_EQ(A, A);
EXPECT_NE(A, B);
EXPECT_LT(A, B);
EXPECT_GT(B, A);
EXPECT_LE(A, B);
EXPECT_GE(B, A);
EXPECT_LE(A, A);
EXPECT_GE(A, A);
EXPECT_EQ(A, A.value());
EXPECT_NE(A, B.value());
EXPECT_LT(A, B.value());
EXPECT_GT(B, A.value());
EXPECT_LE(A, B.value());
EXPECT_GE(B, A.value());
EXPECT_LE(A, A.value());
EXPECT_GE(A, A.value());
EXPECT_EQ(std::max(A, B), B);
EXPECT_EQ(std::min(A, B), A);
const MaybeAlign MA(ValidAlignments[I - 1]);
const MaybeAlign MB(ValidAlignments[I]);
EXPECT_EQ(MA, MA);
EXPECT_NE(MA, MB);
EXPECT_LT(MA, MB);
EXPECT_GT(MB, MA);
EXPECT_LE(MA, MB);
EXPECT_GE(MB, MA);
EXPECT_LE(MA, MA);
EXPECT_GE(MA, MA);
EXPECT_EQ(MA, MA ? (*MA).value() : 0);
EXPECT_NE(MA, MB ? (*MB).value() : 0);
EXPECT_LT(MA, MB ? (*MB).value() : 0);
EXPECT_GT(MB, MA ? (*MA).value() : 0);
EXPECT_LE(MA, MB ? (*MB).value() : 0);
EXPECT_GE(MB, MA ? (*MA).value() : 0);
EXPECT_LE(MA, MA ? (*MA).value() : 0);
EXPECT_GE(MA, MA ? (*MA).value() : 0);
EXPECT_EQ(std::max(A, B), B);
EXPECT_EQ(std::min(A, B), A);
}
}
TEST(Alignment, AssumeAligned) {
EXPECT_EQ(assumeAligned(0), Align(1));
EXPECT_EQ(assumeAligned(0), Align());
EXPECT_EQ(assumeAligned(1), Align(1));
EXPECT_EQ(assumeAligned(1), Align());
}
TEST(Alignment, ComparisonsWithZero) {
for (size_t Value : getValidAlignmentsForDeathTest()) {
EXPECT_DEATH((void)(Align(Value) == 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) != 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) >= 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) <= 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) > 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) < 0), ".* should be defined");
}
}
TEST(Alignment, CompareMaybeAlignToZero) {
for (size_t Value : getValidAlignmentsForDeathTest()) {
// MaybeAlign is allowed to be == or != 0
(void)(MaybeAlign(Value) == 0);
(void)(MaybeAlign(Value) != 0);
EXPECT_DEATH((void)(MaybeAlign(Value) >= 0), ".* should be defined");
EXPECT_DEATH((void)(MaybeAlign(Value) <= 0), ".* should be defined");
EXPECT_DEATH((void)(MaybeAlign(Value) > 0), ".* should be defined");
EXPECT_DEATH((void)(MaybeAlign(Value) < 0), ".* should be defined");
}
}
TEST(Alignment, CompareAlignToUndefMaybeAlign) {
for (size_t Value : getValidAlignmentsForDeathTest()) {
EXPECT_DEATH((void)(Align(Value) == MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) != MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) >= MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) <= MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) > MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) < MaybeAlign(0)), ".* should be defined");
}
}
} // end anonymous namespace
[LLVM] Fix Alignment death tests in Release Mode
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@367427 91177308-0d34-0410-b5e6-96231b3b80d8
//=== - llvm/unittest/Support/Alignment.cpp - Alignment utility tests -----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Alignment.h"
#include "gtest/gtest.h"
#include <vector>
using namespace llvm;
namespace {
std::vector<uint64_t> getValidAlignments() {
std::vector<uint64_t> Out;
for (size_t Shift = 0; Shift < 64; ++Shift)
Out.push_back(1ULL << Shift);
return Out;
}
TEST(AlignmentTest, AlignDefaultCTor) { EXPECT_EQ(Align().value(), 1ULL); }
TEST(AlignmentTest, MaybeAlignDefaultCTor) {
EXPECT_FALSE(MaybeAlign().hasValue());
}
TEST(AlignmentTest, ValidCTors) {
for (size_t Value : getValidAlignments()) {
EXPECT_EQ(Align(Value).value(), Value);
EXPECT_EQ((*MaybeAlign(Value)).value(), Value);
}
}
TEST(AlignmentTest, CheckMaybeAlignHasValue) {
EXPECT_TRUE(MaybeAlign(1));
EXPECT_TRUE(MaybeAlign(1).hasValue());
EXPECT_FALSE(MaybeAlign(0));
EXPECT_FALSE(MaybeAlign(0).hasValue());
EXPECT_FALSE(MaybeAlign());
EXPECT_FALSE(MaybeAlign().hasValue());
}
TEST(AlignmentTest, Division) {
for (size_t Value : getValidAlignments()) {
if (Value > 1) {
EXPECT_EQ(Align(Value) / 2, Value / 2);
EXPECT_EQ(MaybeAlign(Value) / 2, Value / 2);
}
}
EXPECT_EQ(MaybeAlign(0) / 2, MaybeAlign(0));
}
TEST(AlignmentTest, AlignTo) {
struct {
uint64_t alignment;
uint64_t offset;
uint64_t rounded;
} kTests[] = {
// MaybeAlign
{0, 0, 0},
{0, 1, 1},
{0, 5, 5},
// MaybeAlign / Align
{1, 0, 0},
{1, 1, 1},
{1, 5, 5},
{2, 0, 0},
{2, 1, 2},
{2, 2, 2},
{2, 7, 8},
{2, 16, 16},
{4, 0, 0},
{4, 1, 4},
{4, 4, 4},
{4, 6, 8},
};
for (const auto &T : kTests) {
MaybeAlign A(T.alignment);
// Test MaybeAlign
EXPECT_EQ(alignTo(T.offset, A), T.rounded);
// Test Align
if (A)
EXPECT_EQ(alignTo(T.offset, A.getValue()), T.rounded);
}
}
TEST(AlignmentTest, Log2) {
for (size_t Value : getValidAlignments()) {
EXPECT_EQ(Log2(Align(Value)), Log2_64(Value));
EXPECT_EQ(Log2(MaybeAlign(Value)), Log2_64(Value));
}
}
TEST(AlignmentTest, MinAlign) {
struct {
uint64_t A;
uint64_t B;
uint64_t MinAlign;
} kTests[] = {
// MaybeAlign
{0, 0, 0},
{0, 8, 8},
{2, 0, 2},
// MaybeAlign / Align
{1, 2, 1},
{8, 4, 4},
};
for (const auto &T : kTests) {
EXPECT_EQ(commonAlignment(MaybeAlign(T.A), MaybeAlign(T.B)), T.MinAlign);
EXPECT_EQ(MinAlign(T.A, T.B), T.MinAlign);
if (T.A)
EXPECT_EQ(commonAlignment(Align(T.A), MaybeAlign(T.B)), T.MinAlign);
if (T.B)
EXPECT_EQ(commonAlignment(MaybeAlign(T.A), Align(T.B)), T.MinAlign);
if (T.A && T.B)
EXPECT_EQ(commonAlignment(Align(T.A), Align(T.B)), T.MinAlign);
}
}
TEST(AlignmentTest, Encode_Decode) {
for (size_t Value : getValidAlignments()) {
{
Align Actual(Value);
Align Expected = decodeMaybeAlign(encode(Actual)).getValue();
EXPECT_EQ(Expected, Actual);
}
{
MaybeAlign Actual(Value);
MaybeAlign Expected = decodeMaybeAlign(encode(Actual));
EXPECT_EQ(Expected, Actual);
}
}
MaybeAlign Actual(0);
MaybeAlign Expected = decodeMaybeAlign(encode(Actual));
EXPECT_EQ(Expected, Actual);
}
TEST(AlignmentTest, isAligned) {
struct {
uint64_t alignment;
uint64_t offset;
bool isAligned;
} kTests[] = {
// MaybeAlign / Align
{1, 0, true}, {1, 1, true}, {1, 5, true}, {2, 0, true},
{2, 1, false}, {2, 2, true}, {2, 7, false}, {2, 16, true},
{4, 0, true}, {4, 1, false}, {4, 4, true}, {4, 6, false},
};
for (const auto &T : kTests) {
MaybeAlign A(T.alignment);
// Test MaybeAlign
EXPECT_EQ(isAligned(A, T.offset), T.isAligned);
// Test Align
if (A)
EXPECT_EQ(isAligned(A.getValue(), T.offset), T.isAligned);
}
}
TEST(AlignmentTest, AlignComparisons) {
std::vector<uint64_t> ValidAlignments = getValidAlignments();
std::sort(ValidAlignments.begin(), ValidAlignments.end());
for (size_t I = 1; I < ValidAlignments.size(); ++I) {
assert(I >= 1);
const Align A(ValidAlignments[I - 1]);
const Align B(ValidAlignments[I]);
EXPECT_EQ(A, A);
EXPECT_NE(A, B);
EXPECT_LT(A, B);
EXPECT_GT(B, A);
EXPECT_LE(A, B);
EXPECT_GE(B, A);
EXPECT_LE(A, A);
EXPECT_GE(A, A);
EXPECT_EQ(A, A.value());
EXPECT_NE(A, B.value());
EXPECT_LT(A, B.value());
EXPECT_GT(B, A.value());
EXPECT_LE(A, B.value());
EXPECT_GE(B, A.value());
EXPECT_LE(A, A.value());
EXPECT_GE(A, A.value());
EXPECT_EQ(std::max(A, B), B);
EXPECT_EQ(std::min(A, B), A);
const MaybeAlign MA(ValidAlignments[I - 1]);
const MaybeAlign MB(ValidAlignments[I]);
EXPECT_EQ(MA, MA);
EXPECT_NE(MA, MB);
EXPECT_LT(MA, MB);
EXPECT_GT(MB, MA);
EXPECT_LE(MA, MB);
EXPECT_GE(MB, MA);
EXPECT_LE(MA, MA);
EXPECT_GE(MA, MA);
EXPECT_EQ(MA, MA ? (*MA).value() : 0);
EXPECT_NE(MA, MB ? (*MB).value() : 0);
EXPECT_LT(MA, MB ? (*MB).value() : 0);
EXPECT_GT(MB, MA ? (*MA).value() : 0);
EXPECT_LE(MA, MB ? (*MB).value() : 0);
EXPECT_GE(MB, MA ? (*MA).value() : 0);
EXPECT_LE(MA, MA ? (*MA).value() : 0);
EXPECT_GE(MA, MA ? (*MA).value() : 0);
EXPECT_EQ(std::max(A, B), B);
EXPECT_EQ(std::min(A, B), A);
}
}
TEST(AlignmentTest, AssumeAligned) {
EXPECT_EQ(assumeAligned(0), Align(1));
EXPECT_EQ(assumeAligned(0), Align());
EXPECT_EQ(assumeAligned(1), Align(1));
EXPECT_EQ(assumeAligned(1), Align());
}
// Death tests reply on assert which is disabled in release mode.
#ifndef NDEBUG
// We use a subset of valid alignments for DEATH_TESTs as they are particularly
// slow.
std::vector<uint64_t> getValidAlignmentsForDeathTest() {
return {1, 1ULL << 31, 1ULL << 63};
}
std::vector<uint64_t> getNonPowerOfTwo() { return {3, 10, 15}; }
TEST(AlignmentDeathTest, Log2) {
EXPECT_DEATH(Log2(MaybeAlign(0)), ".* should be defined");
}
TEST(AlignmentDeathTest, CantConvertUnsetMaybe) {
EXPECT_DEATH((MaybeAlign(0).getValue()), ".*");
}
TEST(AlignmentDeathTest, Division) {
EXPECT_DEATH(Align(1) / 2, "Can't halve byte alignment");
EXPECT_DEATH(MaybeAlign(1) / 2, "Can't halve byte alignment");
EXPECT_DEATH(Align(8) / 0, "Divisor must be positive and a power of 2");
EXPECT_DEATH(Align(8) / 3, "Divisor must be positive and a power of 2");
}
TEST(AlignmentDeathTest, InvalidCTors) {
EXPECT_DEATH((Align(0)), "Value must not be 0");
for (size_t Value : getNonPowerOfTwo()) {
EXPECT_DEATH((Align(Value)), "Alignment is not a power of 2");
EXPECT_DEATH((MaybeAlign(Value)), "Alignment is not 0 or a power of 2");
}
}
TEST(AlignmentDeathTest, ComparisonsWithZero) {
for (size_t Value : getValidAlignmentsForDeathTest()) {
EXPECT_DEATH((void)(Align(Value) == 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) != 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) >= 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) <= 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) > 0), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) < 0), ".* should be defined");
}
}
TEST(AlignmentDeathTest, CompareMaybeAlignToZero) {
for (size_t Value : getValidAlignmentsForDeathTest()) {
// MaybeAlign is allowed to be == or != 0
(void)(MaybeAlign(Value) == 0);
(void)(MaybeAlign(Value) != 0);
EXPECT_DEATH((void)(MaybeAlign(Value) >= 0), ".* should be defined");
EXPECT_DEATH((void)(MaybeAlign(Value) <= 0), ".* should be defined");
EXPECT_DEATH((void)(MaybeAlign(Value) > 0), ".* should be defined");
EXPECT_DEATH((void)(MaybeAlign(Value) < 0), ".* should be defined");
}
}
TEST(AlignmentDeathTest, CompareAlignToUndefMaybeAlign) {
for (size_t Value : getValidAlignmentsForDeathTest()) {
EXPECT_DEATH((void)(Align(Value) == MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) != MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) >= MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) <= MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) > MaybeAlign(0)), ".* should be defined");
EXPECT_DEATH((void)(Align(Value) < MaybeAlign(0)), ".* should be defined");
}
}
#endif // NDEBUG
} // end anonymous namespace
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/AlignedVector3>
namespace Eigen {
template<typename T,typename Derived>
T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b)
{
return test_relative_error(a.coeffs().template head<3>(), b);
}
}
template<typename Scalar>
void alignedvector3()
{
Scalar s1 = internal::random<Scalar>();
Scalar s2 = internal::random<Scalar>();
typedef Matrix<Scalar,3,1> RefType;
typedef Matrix<Scalar,3,3> Mat33;
typedef AlignedVector3<Scalar> FastType;
RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),
r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());
FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);
Mat33 m1(Mat33::Random());
VERIFY_IS_APPROX(f1,r1);
VERIFY_IS_APPROX(f4,r4);
VERIFY_IS_APPROX(f4+f1,r4+r1);
VERIFY_IS_APPROX(f4-f1,r4-r1);
VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);
VERIFY_IS_APPROX(f4+=f3,r4+=r3);
VERIFY_IS_APPROX(f4-=f5,r4-=r5);
VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);
VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);
VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2);
VERIFY_IS_APPROX(m1*f4,m1*r4);
VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);
VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));
VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));
VERIFY_IS_APPROX(f2.norm(),r2.norm());
VERIFY_IS_APPROX(f2.normalized(),r2.normalized());
VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());
f2.normalize();
r2.normalize();
VERIFY_IS_APPROX(f2,r2);
std::stringstream ss1, ss2;
ss1 << f1;
ss2 << r1;
VERIFY(ss1.str()==ss2.str());
}
void test_alignedvector3()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( alignedvector3<float>() );
}
}
add regression unit test for previous changeset
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/AlignedVector3>
namespace Eigen {
template<typename T,typename Derived>
T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b)
{
return test_relative_error(a.coeffs().template head<3>(), b);
}
}
template<typename Scalar>
void alignedvector3()
{
Scalar s1 = internal::random<Scalar>();
Scalar s2 = internal::random<Scalar>();
typedef Matrix<Scalar,3,1> RefType;
typedef Matrix<Scalar,3,3> Mat33;
typedef AlignedVector3<Scalar> FastType;
RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),
r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());
FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);
Mat33 m1(Mat33::Random());
VERIFY_IS_APPROX(f1,r1);
VERIFY_IS_APPROX(f4,r4);
VERIFY_IS_APPROX(f4+f1,r4+r1);
VERIFY_IS_APPROX(f4-f1,r4-r1);
VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);
VERIFY_IS_APPROX(f4+=f3,r4+=r3);
VERIFY_IS_APPROX(f4-=f5,r4-=r5);
VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);
VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);
VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2);
VERIFY_IS_APPROX(m1*f4,m1*r4);
VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);
VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));
VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));
VERIFY_IS_APPROX(f2.norm(),r2.norm());
VERIFY_IS_APPROX(f2.normalized(),r2.normalized());
VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());
f2.normalize();
r2.normalize();
VERIFY_IS_APPROX(f2,r2);
{
FastType f6 = RefType::Zero();
FastType f7 = FastType::Zero();
VERIFY_IS_APPROX(f6,f7);
f6 = r4+r1;
VERIFY_IS_APPROX(f6,r4+r1);
f6 -= Scalar(2)*r4;
VERIFY_IS_APPROX(f6,r1-r4);
}
std::stringstream ss1, ss2;
ss1 << f1;
ss2 << r1;
VERIFY(ss1.str()==ss2.str());
}
void test_alignedvector3()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( alignedvector3<float>() );
}
}
|
/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "RestoreFiles.h"
#include "../Interface/Server.h"
#include "../Interface/SettingsReader.h"
#include "ClientService.h"
#include "InternetClient.h"
#include "ServerIdentityMgr.h"
#include "../common/data.h"
#include "../urbackupcommon/capa_bits.h"
#include "../urbackupcommon/escape.h"
#include "client.h"
#include "database.h"
#include "../stringtools.h"
#include "../urbackupcommon/json.h"
#include "../cryptoplugin/ICryptoFactory.h"
#ifdef _WIN32
#include "win_sysvol.h"
#include "win_ver.h"
#include "win_all_volumes.h"
#include "DirectoryWatcherThread.h"
#else
#include "lin_ver.h"
std::string getSysVolumeCached(std::string &mpath){ return ""; }
std::string getEspVolumeCached(std::string &mpath){ return ""; }
#endif
#include "../client_version.h"
#include <stdlib.h>
#include <limits.h>
#ifndef _WIN32
#define _atoi64 atoll
#endif
extern std::string time_format_str;
extern ICryptoFactory *crypto_fak;
void ClientConnector::CMD_ADD_IDENTITY(const std::string &identity, const std::string &cmd, bool ident_ok)
{
if(identity.empty())
{
tcpstack.Send(pipe, "Identity empty");
}
else
{
if(Server->getServerParameter("restore_mode")=="true" && !ident_ok )
{
ServerIdentityMgr::addServerIdentity(identity, SPublicKeys());
tcpstack.Send(pipe, "OK");
}
else if( ident_ok )
{
tcpstack.Send(pipe, "OK");
}
else
{
ServerIdentityMgr::loadServerIdentities();
if( ServerIdentityMgr::checkServerIdentity(identity) )
{
if(ServerIdentityMgr::hasPublicKey(identity))
{
tcpstack.Send(pipe, "needs certificate");
}
else
{
tcpstack.Send(pipe, "OK");
}
return;
}
if( ServerIdentityMgr::numServerIdentities()==0 )
{
ServerIdentityMgr::addServerIdentity(identity, SPublicKeys());
tcpstack.Send(pipe, "OK");
}
else
{
if( !ServerIdentityMgr::hasOnlineServer() && ServerIdentityMgr::isNewIdentity(identity) )
{
IScopedLock lock(ident_mutex);
new_server_idents.push_back(identity);
}
tcpstack.Send(pipe, "failed");
}
}
}
}
void ClientConnector::CMD_GET_CHALLENGE(const std::string &identity, const std::string& cmd)
{
if(identity.empty())
{
tcpstack.Send(pipe, "");
return;
}
std::string clientsubname;
if (cmd.size() > 14)
{
std::string s_params = cmd.substr(14);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
clientsubname = params["clientsubname"];
}
IScopedLock lock(ident_mutex);
std::string challenge = Server->secureRandomString(30)+"-"+convert(Server->getTimeSeconds())+"-"+convert(Server->getTimeMS());
challenges[std::make_pair(identity, clientsubname)]=challenge;
tcpstack.Send(pipe, challenge);
}
void ClientConnector::CMD_SIGNATURE(const std::string &identity, const std::string &cmd)
{
if(identity.empty())
{
Server->Log("Signature error: Empty identity", LL_ERROR);
tcpstack.Send(pipe, "empty identity");
return;
}
if(crypto_fak==NULL)
{
Server->Log("Signature error: No crypto module", LL_ERROR);
tcpstack.Send(pipe, "no crypto");
return;
}
size_t hashpos = cmd.find("#");
if (hashpos == std::string::npos)
{
Server->Log("Signature error: No parameters", LL_ERROR);
tcpstack.Send(pipe, "no parameters");
return;
}
str_map params;
ParseParamStrHttp(cmd.substr(hashpos + 1), ¶ms);
std::string clientsubname = params["clientsubname"];
std::map<std::pair<std::string, std::string>, std::string>::iterator challenge_it = challenges.find(std::make_pair(identity, clientsubname));
if(challenge_it==challenges.end() || challenge_it->second.empty())
{
Server->Log("Signature error: No challenge", LL_ERROR);
tcpstack.Send(pipe, "no challenge");
return;
}
const std::string& challenge = challenge_it->second;
std::string pubkey = base64_decode_dash(params["pubkey"]);
std::string pubkey_ecdsa409k1 = base64_decode_dash(params["pubkey_ecdsa409k1"]);
std::string signature = base64_decode_dash(params["signature"]);
std::string signature_ecdsa409k1 = base64_decode_dash(params["signature_ecdsa409k1"]);
std::string session_identity = params["session_identity"];
if(!ServerIdentityMgr::hasPublicKey(identity))
{
ServerIdentityMgr::setPublicKeys(identity, SPublicKeys(pubkey, pubkey_ecdsa409k1));
}
SPublicKeys pubkeys = ServerIdentityMgr::getPublicKeys(identity);
if( (!pubkeys.ecdsa409k1_key.empty() && crypto_fak->verifyData(pubkeys.ecdsa409k1_key, challenge, signature_ecdsa409k1))
|| (pubkeys.ecdsa409k1_key.empty() && !pubkeys.dsa_key.empty() && crypto_fak->verifyDataDSA(pubkeys.dsa_key, challenge, signature)) )
{
ServerIdentityMgr::addSessionIdentity(session_identity, endpoint_name);
ServerIdentityMgr::setPublicKeys(identity, SPublicKeys(pubkey, pubkey_ecdsa409k1));
tcpstack.Send(pipe, "ok");
challenges.erase(challenge_it);
}
else
{
Server->Log("Signature error: Verification failed", LL_ERROR);
tcpstack.Send(pipe, "signature verification failed");
}
}
void ClientConnector::CMD_START_INCR_FILEBACKUP(const std::string &cmd)
{
std::string s_params;
if(next(cmd, 0, "3START BACKUP"))
{
file_version=2;
if(cmd.size()>14)
s_params=cmd.substr(14);
}
else if(cmd=="2START BACKUP")
{
file_version=2;
}
str_map params;
if(!s_params.empty())
{
ParseParamStrHttp(s_params, ¶ms);
}
int64 server_id = watoi64(params["status_id"]);
std::string resume = params["resume"];
std::string sha_version_str = params["sha"];
int sha_version = 512;
if(!sha_version_str.empty())
{
sha_version = watoi(sha_version_str);
}
int group=c_group_default;
str_map::iterator it_group = params.find("group");
if(it_group!=params.end())
{
group = watoi(it_group->second);
}
std::string clientsubname;
str_map::iterator it_clientsubname = params.find("clientsubname");
if(it_clientsubname!=params.end())
{
clientsubname = conv_filename((it_clientsubname->second));
}
unsigned int flags = 0;
if(params.find("with_scripts")!=params.end())
{
flags |= flag_with_scripts;
}
if(params.find("with_orig_path")!=params.end())
{
flags |= flag_with_orig_path;
}
if(params.find("with_sequence")!=params.end())
{
flags |= flag_with_sequence;
}
if(params.find("with_proper_symlinks")!=params.end())
{
flags |= flag_with_proper_symlinks;
}
if(end_to_end_file_backup_verification_enabled)
{
flags |= flag_end_to_end_verification;
}
if(calculateFilehashesOnClient(clientsubname))
{
flags |= flag_calc_checksums;
}
state=CCSTATE_START_FILEBACKUP;
IScopedLock lock(backup_mutex);
CWData data;
data.addChar(IndexThread::IndexThreadAction_StartIncrFileBackup);
data.addVoidPtr(mempipe);
data.addString(server_token);
data.addInt(group);
data.addInt(flags);
data.addString(clientsubname);
data.addInt(sha_version);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
RunningAction action = RUNNING_NONE;
if(resume.empty())
{
action =RUNNING_INCR_FILE;
}
else if(resume=="full")
{
action =RUNNING_RESUME_FULL_FILE;
}
else if(resume=="incr")
{
action =RUNNING_RESUME_INCR_FILE;
}
SRunningProcess new_proc;
new_proc.action = action;
new_proc.server_id = server_id;
new_proc.id = ++curr_backup_running_id;
new_proc.server_token = server_token;
IScopedLock process_lock(process_mutex);
removeTimedOutProcesses(server_token, true);
running_processes.push_back(new_proc);
status_updated = true;
end_to_end_file_backup_verification_enabled=false;
}
void ClientConnector::CMD_START_FULL_FILEBACKUP(const std::string &cmd)
{
std::string s_params;
if(cmd=="2START FULL BACKUP")
{
file_version=2;
}
else if(next(cmd,0,"3START FULL BACKUP"))
{
file_version=2;
if(cmd.size()>19)
s_params=cmd.substr(19);
}
str_map params;
if(!s_params.empty())
{
ParseParamStrHttp(s_params, ¶ms);
}
int group=c_group_default;
str_map::iterator it_group = params.find("group");
if(it_group!=params.end())
{
group = watoi(it_group->second);
}
int64 server_id = watoi64(params["status_id"]);
std::string sha_version_str = params["sha"];
int sha_version = 512;
if(!sha_version_str.empty())
{
sha_version = watoi(sha_version_str);
}
std::string clientsubname;
str_map::iterator it_clientsubname = params.find("clientsubname");
if(it_clientsubname!=params.end())
{
clientsubname = conv_filename((it_clientsubname->second));
}
int flags = 0;
if(params.find("with_scripts")!=params.end())
{
flags |= flag_with_scripts;
}
if(params.find("with_orig_path")!=params.end())
{
flags |= flag_with_orig_path;
}
if(params.find("with_sequence")!=params.end())
{
flags |= flag_with_sequence;
}
if(params.find("with_proper_symlinks")!=params.end())
{
flags |= flag_with_proper_symlinks;
}
if(end_to_end_file_backup_verification_enabled)
{
flags |= flag_end_to_end_verification;
}
if(calculateFilehashesOnClient(clientsubname))
{
flags |= flag_calc_checksums;
}
state=CCSTATE_START_FILEBACKUP;
IScopedLock lock(backup_mutex);
CWData data;
data.addChar(IndexThread::IndexThreadAction_StartFullFileBackup);
data.addVoidPtr(mempipe);
data.addString(server_token);
data.addInt(group);
data.addInt(flags);
data.addString(clientsubname);
data.addInt(sha_version);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
end_to_end_file_backup_verification_enabled=false;
SRunningProcess new_proc;
new_proc.action = RUNNING_FULL_FILE;
new_proc.server_id = server_id;
new_proc.id = ++curr_backup_running_id;
new_proc.server_token = server_token;
IScopedLock process_lock(process_mutex);
removeTimedOutProcesses(server_token, true);
running_processes.push_back(new_proc);
status_updated = true;
}
void ClientConnector::CMD_START_SHADOWCOPY(const std::string &cmd)
{
if(cmd[cmd.size()-1]=='"')
{
state=CCSTATE_SHADOWCOPY;
std::string dir=cmd.substr(10, cmd.size()-11);
std::string clientsubname;
if (dir.find("/") != std::string::npos)
{
std::string str_params = getafter("/", dir);
dir = getuntil("/", dir);
str_map params;
ParseParamStrHttp(str_params, ¶ms);
clientsubname = params["clientsubname"];
}
CWData data;
data.addChar(IndexThread::IndexThreadAction_ReferenceShadowcopy);
data.addVoidPtr(mempipe);
data.addString(dir);
data.addString(server_token);
data.addUChar(0);
data.addUChar(1);
data.addString(clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
}
else
{
Server->Log("Invalid command", LL_ERROR);
}
}
void ClientConnector::CMD_STOP_SHADOWCOPY(const std::string &cmd)
{
if(cmd[cmd.size()-1]=='"')
{
state=CCSTATE_SHADOWCOPY;
std::string dir=cmd.substr(9, cmd.size()-10);
std::string clientsubname;
if (dir.find("/") != std::string::npos)
{
std::string str_params = getafter("/", dir);
dir = getuntil("/", dir);
str_map params;
ParseParamStrHttp(str_params, ¶ms);
clientsubname = params["clientsubname"];
}
CWData data;
data.addChar(IndexThread::IndexThreadAction_ReleaseShadowcopy);
data.addVoidPtr(mempipe);
data.addString(dir);
data.addString(server_token);
data.addUChar(0);
data.addInt(-1);
data.addString(clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
}
else
{
Server->Log("Invalid command", LL_ERROR);
}
}
void ClientConnector::CMD_SET_INCRINTERVAL(const std::string &cmd)
{
if(cmd[cmd.size()-1]=='"')
{
IScopedLock lock(backup_mutex);
std::string intervall=cmd.substr(15, cmd.size()-16);
bool update_db=false;
if(intervall.find("?")!=std::string::npos)
{
str_map params;
ParseParamStrHttp(getafter("?", intervall), ¶ms);
str_map::iterator it_startup_delay=params.find("startup_delay");
if(it_startup_delay!=params.end())
{
int new_waittime = watoi(it_startup_delay->second);
if(new_waittime>backup_alert_delay)
{
update_db=true;
backup_alert_delay = new_waittime;
}
}
}
int new_interval=atoi(intervall.c_str());
if(new_interval!=0 && new_interval!=backup_interval)
{
update_db=true;
backup_interval = new_interval;
}
tcpstack.Send(pipe, "OK");
lasttime=Server->getTimeMS();
if(update_db)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
ClientDAO dao(db);
dao.updateMiscValue("backup_interval", convert(backup_interval));
dao.updateMiscValue("backup_alert_delay", convert(backup_alert_delay));
}
}
else
{
Server->Log("Invalid command", LL_ERROR);
}
}
void ClientConnector::CMD_GET_BACKUPDIRS(const std::string &cmd)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
IQuery *q=db->Prepare("SELECT id,name,path,tgroup,optional FROM backupdirs WHERE symlinked=0");
int timeoutms=300;
db_results res=q->Read(&timeoutms);
IQuery* q_get_virtual_client = db->Prepare("SELECT virtual_client FROM virtual_client_group_offsets WHERE group_offset=?");
if(timeoutms==0)
{
JSON::Object ret;
JSON::Array dirs;
for(size_t i=0;i<res.size();++i)
{
if(res[i]["name"]=="*") continue;
JSON::Object cdir;
cdir.set("id", watoi(res[i]["id"]));
cdir.set("name", res[i]["name"]);
cdir.set("path", res[i]["path"]);
int tgroup = watoi(res[i]["tgroup"]);
cdir.set("group", tgroup%c_group_size);
if (tgroup >= c_group_size)
{
int offset = (tgroup / c_group_size)*c_group_size;
q_get_virtual_client->Bind(offset);
db_results res_vc = q_get_virtual_client->Read();
q_get_virtual_client->Reset();
if (!res_vc.empty())
{
cdir.set("virtual_client", res_vc[0]["virtual_client"]);
}
}
int flags = watoi(res[i]["optional"]);
std::vector<std::pair<int, std::string> > flag_mapping;
flag_mapping.push_back(std::make_pair(EBackupDirFlag_Optional, "optional"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_FollowSymlinks, "follow_symlinks"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_SymlinksOptional, "symlinks_optional"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_OneFilesystem, "one_filesystem"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_RequireSnapshot, "require_snapshot"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_KeepFiles, "keep"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_ShareHashes, "share_hashes"));
std::string str_flags;
for (size_t j = 0; j < flag_mapping.size(); ++j)
{
if (flags & flag_mapping[j].first)
{
if (!str_flags.empty()) str_flags += ",";
str_flags += flag_mapping[j].second;
}
}
cdir.set("flags", str_flags);
dirs.add(cdir);
}
ret.set("dirs", dirs);
tcpstack.Send(pipe, ret.stringify(false));
}
else
{
pipe->shutdown();
}
db->destroyAllQueries();
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_SAVE_BACKUPDIRS(const std::string &cmd, str_map ¶ms)
{
if(last_capa & DONT_ALLOW_CONFIG_PATHS)
{
tcpstack.Send(pipe, "FAILED");
return;
}
if(saveBackupDirs(params))
{
tcpstack.Send(pipe, "OK");
}
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_DID_BACKUP(const std::string &cmd)
{
updateLastBackup();
tcpstack.Send(pipe, "OK");
{
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
SRunningProcess* proc = getRunningFileBackupProcess(std::string(), 0);
if (proc != NULL)
{
removeRunningProcess(proc->id, true);
}
lasttime=Server->getTimeMS();
status_updated = true;
}
IndexThread::execute_postbackup_hook("postfilebackup");
}
void ClientConnector::CMD_DID_BACKUP2(const std::string &cmd)
{
std::string params_str = cmd.substr(12);
str_map params;
ParseParamStrHttp(params_str, ¶ms);
updateLastBackup();
tcpstack.Send(pipe, "OK");
std::string server_token = params["server_token"];
if (server_token.empty())
{
return;
}
{
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
SRunningProcess* proc = getRunningFileBackupProcess(server_token, watoi64(params["status_id"]));
if (proc != NULL)
{
removeRunningProcess(proc->id, true);
}
lasttime = Server->getTimeMS();
status_updated = true;
}
IndexThread::execute_postbackup_hook("postfilebackup");
}
int64 ClientConnector::getLastBackupTime()
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
IQuery *q=db->Prepare("SELECT strftime('%s',last_backup) AS last_backup FROM status", false);
if (q == NULL)
return 0;
int timeoutms=300;
db_results res=q->Read(&timeoutms);
if(timeoutms==1)
{
res=cached_status;
}
else
{
cached_status=res;
}
db->destroyQuery(q);
if(res.size()>0)
{
return watoi64(res[0]["last_backup"]);
}
else
{
return 0;
}
}
std::string ClientConnector::getCurrRunningJob(bool reset_done, int& pcdone)
{
SRunningProcess* proc = getActiveProcess(x_pingtimeout);
if(proc==NULL )
{
return getHasNoRecentBackup();
}
else
{
pcdone = proc->pcdone;
return actionToStr(proc->action);
}
}
SChannel * ClientConnector::getCurrChannel()
{
for (size_t i = 0; i < channel_pipes.size(); ++i)
{
if (channel_pipes[i].pipe == pipe)
{
return &channel_pipes[i];
}
}
return NULL;
}
void ClientConnector::CMD_STATUS(const std::string &cmd)
{
state=CCSTATE_STATUS;
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_STATUS_DETAIL(const std::string &cmd)
{
IScopedLock lock(backup_mutex);
JSON::Object ret;
ret.set("last_backup_time", getLastBackupTime());
JSON::Array j_running_processes;
for (size_t i = 0; i < running_processes.size(); ++i)
{
if (Server->getTimeMS() - running_processes[i].last_pingtime > x_pingtimeout)
{
continue;
}
JSON::Object obj;
obj.set("percent_done", running_processes[i].pcdone);
obj.set("action", actionToStr(running_processes[i].action));
obj.set("eta_ms", running_processes[i].eta_ms);
if (!running_processes[i].details.empty())
{
obj.set("details", running_processes[i].details);
}
if (running_processes[i].detail_pc != -1)
{
obj.set("detail_pc", running_processes[i].detail_pc);
}
if (running_processes[i].total_bytes >= 0)
{
obj.set("total_bytes", running_processes[i].total_bytes);
obj.set("done_bytes", running_processes[i].done_bytes);
}
obj.set("process_id", running_processes[i].id);
obj.set("server_status_id", running_processes[i].server_id);
obj.set("speed_bpms", running_processes[i].speed_bpms);
j_running_processes.add(obj);
}
ret.set("running_processes", j_running_processes);
JSON::Array j_finished_processes;
for (size_t i = 0; i < finished_processes.size(); ++i)
{
JSON::Object obj;
obj.set("process_id", finished_processes[i].id);
obj.set("success", finished_processes[i].success);
j_finished_processes.add(obj);
}
ret.set("finished_processes", j_finished_processes);
JSON::Array servers;
for(size_t i=0;i<channel_pipes.size();++i)
{
JSON::Object obj;
obj.set("internet_connection", channel_pipes[i].internet_connection);
obj.set("name", channel_pipes[i].endpoint_name);
servers.add(obj);
}
ret.set("servers", servers);
ret.set("time_since_last_lan_connection", InternetClient::timeSinceLastLanConnection());
ret.set("internet_connected", InternetClient::isConnected());
ret.set("internet_status", InternetClient::getStatusMsg());
ret.set("capability_bits", getCapabilities());
tcpstack.Send(pipe, ret.stringify(false));
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
db->destroyAllQueries();
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_UPDATE_SETTINGS(const std::string &cmd)
{
std::string s_settings=cmd.substr(9);
unescapeMessage(s_settings);
updateSettings( s_settings );
tcpstack.Send(pipe, "OK");
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_PING_RUNNING(const std::string &cmd)
{
tcpstack.Send(pipe, "OK");
idle_timeout = 120000;
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
lasttime=Server->getTimeMS();
std::string pcdone_new = getbetween("-", "-", cmd);
last_token_times[server_token] = Server->getTimeSeconds();
SRunningProcess* proc = getRunningFileBackupProcess(server_token, 0);
if (proc == NULL)
{
return;
}
int pcdone_old = proc->pcdone;
if (pcdone_new.empty())
proc->pcdone = -1;
else
proc->pcdone = atoi(pcdone_new.c_str());
if (pcdone_old != proc->pcdone)
{
status_updated = true;
}
proc->eta_ms = 0;
proc->last_pingtime = Server->getTimeMS();
#ifdef _WIN32
SetThreadExecutionState(ES_SYSTEM_REQUIRED);
#endif
}
void ClientConnector::CMD_PING_RUNNING2(const std::string &cmd)
{
std::string params_str = cmd.substr(14);
str_map params;
ParseParamStrHttp(params_str, ¶ms);
tcpstack.Send(pipe, "OK");
idle_timeout = 120000;
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
last_token_times[server_token] = Server->getTimeSeconds();
lasttime=Server->getTimeMS();
SRunningProcess* proc = getRunningBackupProcess(server_token, watoi64(params["status_id"]));
if (proc == NULL)
{
return;
}
std::string pcdone_new=params["pc_done"];
int pcdone_old = proc->pcdone;
if(pcdone_new.empty())
proc->pcdone =-1;
else
proc->pcdone =watoi(pcdone_new);
if(pcdone_old!= proc->pcdone)
{
status_updated = true;
}
proc->eta_ms = watoi64(params["eta_ms"]);
proc->last_pingtime = Server->getTimeMS();
proc->speed_bpms = atof(params["speed_bpms"].c_str());
proc->total_bytes = watoi64(params["total_bytes"]);
proc->done_bytes = watoi64(params["done_bytes"]);
#ifdef _WIN32
SetThreadExecutionState(ES_SYSTEM_REQUIRED);
#endif
}
void ClientConnector::CMD_CHANNEL(const std::string &cmd, IScopedLock *g_lock, const std::string& identity)
{
bool img_download_running = false;
{
IScopedLock lock(process_mutex);
SRunningProcess* proc = getRunningProcess(RUNNING_RESTORE_IMAGE, std::string());
img_download_running = proc != NULL;
}
if(!img_download_running)
{
g_lock->relock(backup_mutex);
std::string token;
std::string s_params=cmd.substr(9);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
int capa=watoi(params["capa"]);
token=params["token"];
channel_pipes.push_back(SChannel(pipe, internet_conn, endpoint_name, token,
&make_fileserv, identity, capa, watoi(params["restore_version"])));
is_channel=true;
state=CCSTATE_CHANNEL;
last_channel_ping=Server->getTimeMS();
lasttime=Server->getTimeMS();
Server->Log("New channel: Number of Channels: "+convert((int)channel_pipes.size()), LL_DEBUG);
}
}
void ClientConnector::CMD_CHANNEL_PONG(const std::string &cmd, const std::string& endpoint_name)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
SChannel* chan = getCurrChannel();
if (chan != NULL && chan->state == SChannel::EChannelState_Pinging)
{
chan->state = SChannel::EChannelState_Idle;
}
refreshSessionFromChannel(endpoint_name);
}
void ClientConnector::CMD_CHANNEL_PING(const std::string &cmd, const std::string& endpoint_name)
{
lasttime=Server->getTimeMS();
if(tcpstack.Send(pipe, "PONG")==0)
{
do_quit=true;
}
refreshSessionFromChannel(endpoint_name);
}
void ClientConnector::CMD_TOCHANNEL_START_INCR_FILEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_INCR_FILE);
}
void ClientConnector::CMD_TOCHANNEL_START_FULL_FILEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_FULL_FILE);
}
void ClientConnector::CMD_TOCHANNEL_START_FULL_IMAGEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_FULL_IMAGE);
}
void ClientConnector::CMD_TOCHANNEL_START_INCR_IMAGEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_INCR_IMAGE);
}
void ClientConnector::CMD_TOCHANNEL_UPDATE_SETTINGS(const std::string &cmd)
{
if(last_capa & DONT_SHOW_SETTINGS)
{
tcpstack.Send(pipe, "FAILED");
return;
}
std::string s_settings=cmd.substr(16);
lasttime=Server->getTimeMS();
unescapeMessage(s_settings);
replaceSettings( s_settings );
IScopedLock lock(backup_mutex);
bool ok=false;
for(size_t o=0;o<channel_pipes.size();++o)
{
CTCPStack tmpstack(channel_pipes[o].internet_connection);
_u32 rc=(_u32)tmpstack.Send(channel_pipes[o].pipe, "UPDATE SETTINGS");
if(rc!=0)
ok=true;
}
if(!ok)
{
tcpstack.Send(pipe, "NOSERVER");
}
else
{
tcpstack.Send(pipe, "OK");
}
}
void ClientConnector::CMD_LOGDATA(const std::string &cmd)
{
std::string ldata=cmd.substr(9);
size_t cpos=ldata.find(" ");
std::string created=getuntil(" ", ldata);
lasttime=Server->getTimeMS();
saveLogdata(created, getafter(" ",ldata));
tcpstack.Send(pipe, "OK");
}
void ClientConnector::CMD_PAUSE(const std::string &cmd)
{
lasttime=Server->getTimeMS();
std::string b=cmd.substr(6);
bool ok=false;
IScopedLock lock(backup_mutex);
status_updated = true;
if(b=="true")
{
ok=true;
IdleCheckerThread::setPause(true);
IndexThread::getFileSrv()->setPause(true);
}
else if(b=="false")
{
ok=true;
IdleCheckerThread::setPause(false);
IndexThread::getFileSrv()->setPause(false);
}
if(ok) tcpstack.Send(pipe, "OK");
else tcpstack.Send(pipe, "FAILED");
}
void ClientConnector::CMD_GET_LOGPOINTS(const std::string &cmd)
{
lasttime=Server->getTimeMS();
tcpstack.Send(pipe, getLogpoints() );
}
void ClientConnector::CMD_GET_LOGDATA(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
int logid=watoi(params["logid"]);
int loglevel=watoi(params["loglevel"]);
std::string ret;
getLogLevel(logid, loglevel, ret);
tcpstack.Send(pipe, ret);
}
void ClientConnector::CMD_FULL_IMAGE(const std::string &cmd, bool ident_ok)
{
if(ident_ok)
{
lasttime=Server->getTimeMS();
std::string s_params=cmd.substr(11);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
server_token=(params["token"]);
image_inf.image_letter=(params["letter"]);
image_inf.orig_image_letter = image_inf.image_letter;
image_inf.server_status_id = watoi(params["status_id"]);
image_inf.shadowdrive=(params["shadowdrive"]);
if(params.find("start")!=params.end())
{
image_inf.startpos=(uint64)_atoi64((params["start"]).c_str());
}
else
{
image_inf.startpos=0;
}
if(params.find("shadowid")!=params.end())
{
image_inf.shadow_id=watoi(params["shadowid"]);
}
else
{
image_inf.shadow_id=-1;
}
image_inf.with_checksum=false;
if(params.find("checksum")!=params.end())
{
if(params["checksum"]=="1")
image_inf.with_checksum=true;
}
image_inf.with_bitmap=false;
if(params.find("bitmap")!=params.end())
{
if(params["bitmap"]=="1")
image_inf.with_bitmap=true;
}
image_inf.no_shadowcopy=false;
image_inf.clientsubname = params["clientsubname"];
if(image_inf.image_letter=="SYSVOL"
|| image_inf.image_letter=="ESP")
{
std::string mpath;
std::string sysvol;
if(image_inf.image_letter=="SYSVOL")
{
sysvol=getSysVolumeCached(mpath);
}
else
{
sysvol=getEspVolumeCached(mpath);
}
if(!mpath.empty())
{
image_inf.image_letter=mpath;
}
else if(!sysvol.empty())
{
image_inf.image_letter=sysvol;
image_inf.no_shadowcopy=true;
}
else
{
ImageErr("Not found");
return;
}
}
if(image_inf.startpos==0 && !image_inf.no_shadowcopy)
{
CWData data;
data.addChar(IndexThread::IndexThreadAction_CreateShadowcopy);
data.addVoidPtr(mempipe);
data.addString(image_inf.image_letter);
data.addString(server_token);
data.addUChar(1); //full image backup
data.addUChar(0); //filesrv
data.addString(image_inf.clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
else if(image_inf.shadow_id!=-1)
{
image_inf.shadowdrive.clear();
CWData data;
data.addChar(4);
data.addVoidPtr(mempipe);
data.addInt(image_inf.shadow_id);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
if(image_inf.no_shadowcopy)
{
image_inf.shadowdrive=image_inf.image_letter;
if(!image_inf.shadowdrive.empty() && image_inf.shadowdrive[0]!='\\')
{
image_inf.shadowdrive="\\\\.\\"+image_inf.image_letter;
}
}
lasttime=Server->getTimeMS();
sendFullImage();
}
else
{
ImageErr("Ident reset (1)");
}
}
void ClientConnector::CMD_INCR_IMAGE(const std::string &cmd, bool ident_ok)
{
if(ident_ok)
{
lasttime=Server->getTimeMS();
std::string s_params=cmd.substr(11);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
server_token=(params["token"]);
str_map::iterator f_hashsize=params.find("hashsize");
if(f_hashsize!=params.end())
{
hashdataok=false;
hashdataleft=watoi(f_hashsize->second);
image_inf.image_letter=(params["letter"]);
image_inf.shadowdrive=(params["shadowdrive"]);
image_inf.server_status_id = watoi(params["status_id"]);
if(params.find("start")!=params.end())
{
image_inf.startpos=(uint64)_atoi64((params["start"]).c_str());
}
else
{
image_inf.startpos=0;
}
if(params.find("shadowid")!=params.end())
{
image_inf.shadow_id=watoi(params["shadowid"]);
}
else
{
image_inf.shadow_id=-1;
}
image_inf.with_checksum=false;
if(params.find("checksum")!=params.end())
{
if(params["checksum"]=="1")
image_inf.with_checksum=true;
}
image_inf.with_bitmap=false;
if(params.find("bitmap")!=params.end())
{
if(params["bitmap"]=="1")
image_inf.with_bitmap=true;
}
image_inf.no_shadowcopy=false;
image_inf.clientsubname = params["clientsubname"];
if(image_inf.startpos==0)
{
CWData data;
data.addChar(IndexThread::IndexThreadAction_CreateShadowcopy);
data.addVoidPtr(mempipe);
data.addString(image_inf.image_letter);
data.addString(server_token);
data.addUChar(2); //incr image backup
data.addUChar(0); //file serv?
data.addString(image_inf.clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
else if(image_inf.shadow_id!=-1)
{
image_inf.shadowdrive.clear();
CWData data;
data.addChar(4);
data.addVoidPtr(mempipe);
data.addInt(image_inf.shadow_id);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
hashdatafile=Server->openTemporaryFile();
if(hashdatafile==NULL)
{
Server->Log("Error creating temporary file in CMD_INCR_IMAGE", LL_ERROR);
do_quit=true;
return;
}
if(tcpstack.getBuffersize()>0)
{
if(hashdatafile->Write(tcpstack.getBuffer(), (_u32)tcpstack.getBuffersize())!=tcpstack.getBuffersize())
{
Server->Log("Error writing to hashdata temporary file in CMD_INCR_IMAGE", LL_ERROR);
do_quit=true;
return;
}
if(hashdataleft>=tcpstack.getBuffersize())
{
hashdataleft-=(_u32)tcpstack.getBuffersize();
//Server->Log("Hashdataleft: "+convert(hashdataleft), LL_DEBUG);
}
else
{
Server->Log("Too much hashdata - error in CMD_INCR_IMAGE", LL_ERROR);
}
tcpstack.reset();
if(hashdataleft==0)
{
hashdataok=true;
state=CCSTATE_IMAGE;
return;
}
}
lasttime=Server->getTimeMS();
sendIncrImage();
}
}
else
{
ImageErr("Ident reset (2)");
}
}
void ClientConnector::CMD_MBR(const std::string &cmd)
{
lasttime=Server->getTimeMS();
std::string s_params=cmd.substr(4);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
std::string dl=params["driveletter"];
if(dl=="SYSVOL")
{
std::string mpath;
dl=getSysVolumeCached(mpath);
}
else if(dl=="ESP")
{
std::string mpath;
dl=getEspVolumeCached(mpath);
}
bool b=false;
std::string errmsg;
if(!dl.empty())
{
b=sendMBR(dl, errmsg);
}
if(!b)
{
CWData r;
r.addChar(0);
r.addString((errmsg));
tcpstack.Send(pipe, r);
}
}
void ClientConnector::CMD_RESTORE_GET_BACKUPCLIENTS(const std::string &cmd)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "0");
}
else
{
std::string clients;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], "GET BACKUPCLIENTS");
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after request -1", LL_DEBUG);
std::string nc=receivePacket(channel_pipes[i]);
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after read -1", LL_DEBUG);
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+": --"+nc+"--", LL_DEBUG);
if(!nc.empty())
{
clients+=nc+"\n";
}
}
tcpstack.Send(pipe, "1"+clients);
}
}
void ClientConnector::CMD_RESTORE_GET_BACKUPIMAGES(const std::string &cmd)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "0");
}
else
{
std::string imgs;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], cmd);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty())
{
imgs+=nc+"\n";
}
}
tcpstack.Send(pipe, "1"+imgs);
}
}
void ClientConnector::CMD_RESTORE_GET_FILE_BACKUPS(const std::string &cmd)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "0");
}
else
{
std::string filebackups;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], cmd);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty())
{
filebackups+=nc+"\n";
}
}
tcpstack.Send(pipe, "1"+filebackups);
}
}
void ClientConnector::CMD_RESTORE_GET_FILE_BACKUPS_TOKENS( const std::string &cmd, str_map ¶ms )
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "1");
}
else
{
std::string utf8_tokens = (params["tokens"]);
std::string filebackups;
std::string accessparams;
if(channel_pipes.size()==1)
{
accessparams+=" with_id_offset=false";
}
bool has_token_params=false;
for(size_t i=0;i<channel_pipes.size();++i)
{
for(size_t j=0;j<2;++j)
{
if(channel_pipes[i].last_tokens!=utf8_tokens)
{
if(!has_token_params)
{
std::string token_params = getAccessTokensParams(params["tokens"], true);
if(token_params.empty())
{
tcpstack.Send(pipe, "2");
return;
}
if(accessparams.empty())
{
accessparams = token_params;
accessparams[0]=' ';
}
else
{
accessparams+=token_params;
}
has_token_params=true;
}
}
sendChannelPacket(channel_pipes[i], cmd+accessparams);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty() && nc!="err")
{
channel_pipes[i].last_tokens = utf8_tokens;
if(!filebackups.empty())
{
filebackups[filebackups.size()-1] = ',';
nc[0]=' ';
}
filebackups+=nc;
break;
}
else if(!has_token_params)
{
channel_pipes[i].last_tokens="";
}
else
{
break;
}
}
}
if(filebackups.empty())
{
tcpstack.Send(pipe, "3");
}
else
{
tcpstack.Send(pipe, "0"+filebackups);
}
}
}
void ClientConnector::CMD_GET_FILE_LIST_TOKENS(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "1");
}
else
{
std::string accessparams;
str_map::iterator it_path = params.find("path");
if(it_path!=params.end())
{
accessparams+="&path="+EscapeParamString((it_path->second));
}
str_map::iterator it_backupid = params.find("backupid");
if(it_backupid!=params.end())
{
accessparams+="&backupid="+EscapeParamString((it_backupid->second));
}
if(channel_pipes.size()==1)
{
accessparams+="&with_id_offset=false";
}
std::string filelist;
if(!accessparams.empty())
{
accessparams[0]=' ';
}
std::string utf8_tokens = (params["tokens"]);
bool has_token_params=false;
bool break_outer=false;
for(size_t i=0;i<channel_pipes.size();++i)
{
for(size_t j=0;j<2;++j)
{
if(channel_pipes[i].last_tokens!=utf8_tokens)
{
if(!has_token_params)
{
std::string token_params = getAccessTokensParams(params["tokens"], true);
if(token_params.empty())
{
tcpstack.Send(pipe, "2");
return;
}
if(accessparams.empty())
{
accessparams = token_params;
accessparams[0]=' ';
}
else
{
accessparams+=token_params;
}
has_token_params=true;
}
}
sendChannelPacket(channel_pipes[i], cmd+accessparams);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty() && nc!="err")
{
channel_pipes[i].last_tokens = utf8_tokens;
if(!filelist.empty())
{
filelist[filelist.size()-1] = ',';
nc[0]=' ';
}
filelist+=nc;
if(it_backupid!=params.end())
{
break_outer=true;
break;
}
break;
}
else if(!has_token_params)
{
channel_pipes[i].last_tokens="";
}
else
{
break;
}
}
if(break_outer)
{
break;
}
}
if(!filelist.empty())
{
tcpstack.Send(pipe, "0"+filelist);
}
else
{
tcpstack.Send(pipe, "3");
}
}
}
void ClientConnector::CMD_DOWNLOAD_FILES_TOKENS(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "1");
return;
}
std::string accessparams;
str_map::iterator it_path = params.find("path");
if(it_path==params.end())
{
tcpstack.Send(pipe, "2");
return;
}
accessparams+="&path="+EscapeParamString((it_path->second));
str_map::iterator it_backupid = params.find("backupid");
if(it_backupid==params.end())
{
tcpstack.Send(pipe, "3");
return;
}
accessparams+="&backupid="+EscapeParamString((it_backupid->second));
if(channel_pipes.size()==1)
{
accessparams+="&with_id_offset=false";
}
std::string restore_token_binary;
restore_token_binary.resize(16);
Server->secureRandomFill(&restore_token_binary[0], restore_token_binary.size());
restore_token.restore_token = bytesToHex(restore_token_binary);
restore_token.restore_token_time = Server->getTimeMS();
{
IScopedLock process_lock(process_mutex);
restore_token.process_id = ++curr_backup_running_id;
}
accessparams+="&restore_token="+ restore_token.restore_token+"&process_id="+convert(restore_token.process_id);
str_map::iterator it_clean_other = params.find("clean_other");
if (it_clean_other != params.end())
{
accessparams += "&clean_other=" + EscapeParamString(it_clean_other->second);
}
str_map::iterator it_ignore_other_fs = params.find("ignore_other_fs");
if (it_clean_other != params.end())
{
accessparams += "&ignore_other_fs=" + EscapeParamString(it_ignore_other_fs->second);
}
std::string filelist;
accessparams[0]=' ';
std::string utf8_tokens = params["tokens"];
bool has_token_params=false;
std::string last_err;
for(size_t i=0;i<channel_pipes.size();++i)
{
for(size_t j=0;j<2;++j)
{
if(channel_pipes[i].last_tokens!=utf8_tokens)
{
if(!has_token_params)
{
std::string token_params = getAccessTokensParams(params["tokens"], true);
if(token_params.empty())
{
tcpstack.Send(pipe, "error encrypting access tokens");
return;
}
if(accessparams.empty())
{
accessparams = token_params;
accessparams[0]=' ';
}
else
{
accessparams+=token_params;
}
has_token_params=true;
}
}
sendChannelPacket(channel_pipes[i], cmd+accessparams);
last_err=receivePacket(channel_pipes[i]);
if(!last_err.empty() && last_err!="err")
{
channel_pipes[i].last_tokens = utf8_tokens;
tcpstack.Send(pipe, "0" + last_err);
return;
}
else if(!has_token_params)
{
channel_pipes[i].last_tokens="";
}
else
{
break;
}
}
}
tcpstack.Send(pipe, last_err);
}
void ClientConnector::CMD_RESTORE_DOWNLOAD_IMAGE(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
Server->Log("Downloading image...", LL_DEBUG);
IScopedLock lock(backup_mutex);
waitForPings(&lock);
Server->Log("In mutex...",LL_DEBUG);
downloadImage(params);
Server->Log("Download done -2", LL_DEBUG);
do_quit=true;
}
void ClientConnector::CMD_RESTORE_DOWNLOAD_FILES(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
Server->Log("Downloading files...", LL_DEBUG);
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "No backup server found");
return;
}
std::string last_error;
for(size_t i=0;i<channel_pipes.size();++i)
{
IPipe *c=channel_pipes[i].pipe;
tcpstack.Send(c, "DOWNLOAD FILES backupid="+params["backupid"]+"&time="+params["time"]);
Server->Log("Start downloading files from channel "+convert((int)i), LL_DEBUG);
CTCPStack recv_stack;
int64 starttime = Server->getTimeMS();
while(Server->getTimeMS()-starttime<60000)
{
std::string msg;
if(c->Read(&msg, 60000)>0)
{
recv_stack.AddData(&msg[0], msg.size());
if(recv_stack.getPacket(msg) )
{
if(msg=="ok")
{
tcpstack.Send(pipe, "ok");
return;
}
else
{
last_error=msg;
}
break;
}
}
else
{
break;
}
}
}
if(!last_error.empty())
{
tcpstack.Send(pipe, last_error);
}
else
{
tcpstack.Send(pipe, "timeout");
}
}
void ClientConnector::CMD_RESTORE_DOWNLOADPROGRESS(const std::string &cmd)
{
Server->Log("Sending progress...", LL_DEBUG);
lasttime=Server->getTimeMS();
bool img_download_running = false;
{
IScopedLock lock(process_mutex);
SRunningProcess* proc = getRunningProcess(RUNNING_RESTORE_IMAGE, std::string());
img_download_running = proc != NULL;
}
if(!img_download_running)
{
pipe->Write("100");
do_quit=true;
}
else
{
while(true)
{
{
int progress=0;
{
IScopedLock lock(process_mutex);
SRunningProcess* proc = getRunningProcess(RUNNING_RESTORE_IMAGE, std::string());
if (proc != NULL)
{
progress = proc->pcdone;
}
else
{
break;
}
}
if(!pipe->Write(convert(progress)+"\n", 10000))
{
break;
}
}
{
Server->wait(1000);
}
}
do_quit=true;
}
}
void ClientConnector::CMD_RESTORE_LOGIN_FOR_DOWNLOAD(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "no channels available");
}
else
{
bool one_ok=false;
std::string errors;
for(size_t i=0;i<channel_pipes.size();++i)
{
if(params["username"].empty())
{
sendChannelPacket(channel_pipes[i], "LOGIN username=&password=");
}
else
{
sendChannelPacket(channel_pipes[i], "LOGIN username="+(params["username"])
+"&password="+(params["password"+convert(i)]));
}
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after request -1", LL_DEBUG);
std::string nc=receivePacket(channel_pipes[i]);
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after read -1", LL_DEBUG);
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+": --"+nc+"--", LL_DEBUG);
if(nc=="ok")
{
one_ok=true;
}
else
{
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+" ERROR: --"+nc+"--", LL_ERROR);
if(!errors.empty())
{
errors+=" -- ";
}
errors+=nc;
}
}
if(one_ok)
{
tcpstack.Send(pipe, "ok");
}
else
{
tcpstack.Send(pipe, errors);
}
}
}
void ClientConnector::CMD_RESTORE_GET_SALT(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "no channels available");
}
else
{
std::string salts;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], "SALT username="+(params["username"]));
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after request -1", LL_DEBUG);
std::string nc=receivePacket(channel_pipes[i]);
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after read -1", LL_DEBUG);
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+": --"+nc+"--", LL_DEBUG);
if(nc.find("ok;")==0)
{
if(!salts.empty())
{
salts+="/";
}
salts+=nc;
}
else
{
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+" ERROR: --"+nc+"--", LL_ERROR);
salts+="err;"+nc;
}
}
tcpstack.Send(pipe, salts);
}
}
void ClientConnector::CMD_VERSION_UPDATE(const std::string &cmd)
{
std::string server_version = cmd.substr(8);
#ifdef _WIN32
#define VERSION_FILE_PREFIX ""
#else
#define VERSION_FILE_PREFIX "urbackup/"
if (n_version < 125)
{
tcpstack.Send(pipe, "noop");
return;
}
#endif
#if defined(_WIN32) || defined(URB_WITH_CLIENTUPDATE)
std::string version_1=getFile(VERSION_FILE_PREFIX "version.txt");
std::string version_2=getFile(VERSION_FILE_PREFIX "curr_version.txt");
if(version_1.empty() ) version_1="0";
if(version_2.empty() ) version_2="0";
if(versionNeedsUpdate(version_1, server_version)
&& versionNeedsUpdate(version_2, server_version) )
{
tcpstack.Send(pipe, "update");
}
else
{
tcpstack.Send(pipe, "noop");
}
#else
tcpstack.Send(pipe, "noop");
return;
#endif
#undef VERSION_FILE_PREFIX
}
void ClientConnector::CMD_CLIENT_UPDATE(const std::string &cmd)
{
hashdatafile=Server->openTemporaryFile();
if(hashdatafile==NULL)
{
Server->Log("Error creating temporary file in CMD_CLIENT_UPDATE", LL_ERROR);
do_quit=true;
return;
}
str_map params;
ParseParamStrHttp(cmd.substr(14), ¶ms);
hashdataleft=watoi(params["size"]);
silent_update=(params["silent_update"]=="true");
hashdataok=false;
state=CCSTATE_UPDATE_DATA;
if(tcpstack.getBuffersize()>0)
{
if(hashdatafile->Write(tcpstack.getBuffer(), (_u32)tcpstack.getBuffersize())!=tcpstack.getBuffersize())
{
Server->Log("Error writing to hashdata temporary file -1update", LL_ERROR);
do_quit=true;
return;
}
if(hashdataleft>=tcpstack.getBuffersize())
{
hashdataleft-=(_u32)tcpstack.getBuffersize();
}
else
{
Server->Log("Too much hashdata - error -1update", LL_ERROR);
}
tcpstack.reset();
if(hashdataleft==0)
{
hashdataok=true;
state=CCSTATE_UPDATE_FINISH;
return;
}
}
return;
}
void ClientConnector::CMD_CAPA(const std::string &cmd)
{
std::string client_version_str=std::string(c_client_version);
std::string restore=Server->getServerParameter("allow_restore");
if(restore.empty() || restore=="default")
{
restore="client-confirms";
}
#ifdef _WIN32
std::string buf;
buf.resize(1024);
std::string os_version_str = get_windows_version();
std::string win_volumes;
std::string win_nonusb_volumes;
{
IScopedLock lock(backup_mutex);
win_volumes = get_all_volumes_list(false, volumes_cache);
win_nonusb_volumes = get_all_volumes_list(true, volumes_cache);
}
tcpstack.Send(pipe, "FILE=2&FILE2=1&IMAGE=1&UPDATE=1&MBR=1&FILESRV=3&SET_SETTINGS=1&IMAGE_VER=1&CLIENTUPDATE=2"
"&CLIENT_VERSION_STR="+EscapeParamString((client_version_str))+"&OS_VERSION_STR="+EscapeParamString(os_version_str)+
"&ALL_VOLUMES="+EscapeParamString(win_volumes)+"&ETA=1&CDP=0&ALL_NONUSB_VOLUMES="+EscapeParamString(win_nonusb_volumes)+"&EFI=1"
"&FILE_META=1&SELECT_SHA=1&RESTORE="+restore+"&CLIENT_BITMAP=1&CMD=1&OS_SIMPLE=windows");
#else
#ifdef __APPLE__
std::string os_simple = "osx";
#elif __linux__
std::string os_simple = "linux";
#else
std::string os_simple = "unknown";
#endif
std::string os_version_str=get_lin_os_version();
tcpstack.Send(pipe, "FILE=2&FILE2=1&FILESRV=3&SET_SETTINGS=1&CLIENTUPDATE=2"
"&CLIENT_VERSION_STR="+EscapeParamString((client_version_str))+"&OS_VERSION_STR="+EscapeParamString(os_version_str)
+"&ETA=1&CPD=0&FILE_META=1&SELECT_SHA=1&RESTORE="+restore+"&CMD=1&OS_SIMPLE="+os_simple);
#endif
}
void ClientConnector::CMD_NEW_SERVER(str_map ¶ms)
{
std::string ident=(params["ident"]);
if(!ident.empty())
{
ServerIdentityMgr::addServerIdentity(ident, SPublicKeys());
tcpstack.Send(pipe, "OK");
}
else
{
tcpstack.Send(pipe, "FAILED");
}
}
void ClientConnector::CMD_RESET_KEEP(str_map ¶ms)
{
std::string virtual_client = params["virtual_client"];
std::string folder_name = params["folder_name"];
int tgroup = watoi(params["tgroup"]);
IDatabase *db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
int group_offset = 0;
if (!virtual_client.empty())
{
IQuery *q = db->Prepare("SELECT group_offset FROM virtual_client_group_offsets WHERE virtual_client=?", false);
q->Bind(virtual_client);
db_results res = q->Read();
db->destroyQuery(q);
if (res.empty())
{
tcpstack.Send(pipe, "err_virtual_client_not_found");
return;
}
group_offset = watoi(res[0]["group_offset"]);
}
IQuery* q = db->Prepare(std::string("UPDATE backupdirs SET reset_keep=1 WHERE tgroup=?")
+ (folder_name.empty() ? "" : " AND name=?"), false);
q->Bind(tgroup + group_offset);
if (!folder_name.empty())
{
q->Bind(folder_name);
}
q->Write();
q->Reset();
if (db->getLastChanges() > 0)
{
tcpstack.Send(pipe, "OK");
}
else
{
tcpstack.Send(pipe, "err_backup_folder_not_found");
}
db->destroyQuery(q);
}
void ClientConnector::CMD_ENABLE_END_TO_END_FILE_BACKUP_VERIFICATION(const std::string &cmd)
{
IScopedLock lock(backup_mutex);
end_to_end_file_backup_verification_enabled=true;
tcpstack.Send(pipe, "OK");
}
void ClientConnector::CMD_GET_VSSLOG(const std::string &cmd)
{
CWData data;
IPipe* localpipe=Server->createMemoryPipe();
data.addChar(IndexThread::IndexThreadAction_GetLog);
data.addVoidPtr(localpipe);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
std::string ret;
localpipe->Read(&ret, 8000);
tcpstack.Send(pipe, ret);
localpipe->Write("exit");
}
void ClientConnector::CMD_GET_ACCESS_PARAMS(str_map ¶ms)
{
if(crypto_fak==NULL)
{
Server->Log("No cryptoplugin present. Action not possible.", LL_ERROR);
tcpstack.Send(pipe, "");
return;
}
std::string tokens=params["tokens"];
std::auto_ptr<ISettingsReader> settings(
Server->createFileSettingsReader("urbackup/data/settings.cfg"));
std::string server_url;
if( (!settings->getValue("server_url", &server_url)
&& !settings->getValue("server_url_def", &server_url) )
|| server_url.empty())
{
Server->Log("Server url empty", LL_ERROR);
tcpstack.Send(pipe, "");
return;
}
std::string ret = getAccessTokensParams(tokens, true);
if(!ret.empty())
{
ret[0]='#';
ret = server_url + ret;
}
else
{
tcpstack.Send(pipe, "");
return;
}
tcpstack.Send(pipe, ret);
}
void ClientConnector::CMD_CONTINUOUS_WATCH_START()
{
IScopedLock lock(backup_mutex);
tcpstack.Send(pipe, "OK");
}
void ClientConnector::CMD_SCRIPT_STDERR(const std::string& cmd)
{
std::string script_cmd = (cmd.substr(14));
if(next(script_cmd, 0, "SCRIPT|"))
{
script_cmd = script_cmd.substr(7);
}
std::string stderr_out;
int exit_code;
if(IndexThread::getFileSrv()->getExitInformation(script_cmd, stderr_out, exit_code))
{
tcpstack.Send(pipe, convert(exit_code)+" "+convert(Server->getTimeMS())+" "+stderr_out);
}
else
{
tcpstack.Send(pipe, "err");
}
}
void ClientConnector::CMD_FILE_RESTORE(const std::string& cmd)
{
str_map params;
ParseParamStrHttp(cmd, ¶ms);
int64 restore_process_id = 0;
bool has_restore_token = false;
if (!restore_token.restore_token.empty()
&& params["restore_token"] == restore_token.restore_token
&& Server->getTimeMS() - restore_token.restore_token_time<120 * 1000)
{
restore_token.restore_token = "";
has_restore_token = true;
restore_process_id = restore_token.process_id;
restore_token.process_id = 0;
}
std::string restore=Server->getServerParameter("allow_restore");
if(restore=="default")
{
restore="client-confirms";
}
if(restore!="client-confirms" && restore!="server-confirms"
&& !has_restore_token)
{
tcpstack.Send(pipe, "disabled");
return;
}
std::string client_token = (params["client_token"]);
std::string server_token=params["server_token"];
int64 restore_id=watoi64(params["id"]);
int64 status_id=watoi64(params["status_id"]);
int64 log_id=watoi64(params["log_id"]);
std::string restore_path = params["restore_path"];
bool single_file = params["single_file"]=="1";
bool clean_other = params["clean_other"] == "1";
bool ignore_other_fs = params["ignore_other_fs"] != "0";
int tgroup = watoi(params["tgroup"]);
std::string clientsubname = params["clientsubname"];
if(restore_process_id==0)
{
IScopedLock lock(process_mutex);
restore_process_id = ++curr_backup_running_id;
}
if (crypto_fak != NULL)
{
std::auto_ptr<ISettingsReader> access_keys(
Server->createFileSettingsReader("urbackup/access_keys.properties"));
if (access_keys.get() != NULL)
{
std::string access_key;
if (access_keys->getValue("key." + server_token, &access_key))
{
client_token = crypto_fak->decryptAuthenticatedAES(base64_decode_dash(client_token), access_key, 1);
if (client_token.empty())
{
Server->Log("Error decrypting server access token. Access key might be wrong.", LL_ERROR);
}
}
else
{
Server->Log("key."+ server_token+" not found in urbackup/access_keys.properties", LL_ERROR);
}
}
else
{
Server->Log("Error opening urbackup/access_keys.properties", LL_ERROR);
}
}
else
{
Server->Log("Error decrypting server access token. Crypto_fak not loaded.", LL_ERROR);
}
RestoreFiles* local_restore_files = new RestoreFiles(restore_process_id, restore_id, status_id, log_id,
client_token, server_token, restore_path, single_file, clean_other, ignore_other_fs,
tgroup, clientsubname);
if(restore == "client-confirms" && !has_restore_token)
{
IScopedLock lock(backup_mutex);
restore_ok_status = RestoreOk_Wait;
++ask_restore_ok;
status_updated = true;
if(restore_files!=NULL)
{
delete restore_files;
}
restore_files = local_restore_files;
}
else
{
Server->getThreadPool()->execute(local_restore_files, "file restore");
}
tcpstack.Send(pipe, "ok");
}
void ClientConnector::CMD_RESTORE_OK( str_map ¶ms )
{
IScopedLock lock(backup_mutex);
JSON::Object ret;
if(params["ok"]=="true")
{
restore_ok_status = RestoreOk_Ok;
ret.set("accepted", true);
if(restore_files!=NULL)
{
ret.set("process_id", restore_files->get_local_process_id());
Server->getThreadPool()->execute(restore_files, "file restore");
restore_files=NULL;
}
}
else
{
restore_ok_status = RestoreOk_Declined;
if (restore_files != NULL)
{
restore_files->set_restore_declined(true);
Server->getThreadPool()->execute(restore_files, "file restore");
restore_files = NULL;
}
}
delete restore_files;
restore_files=NULL;
ret.set("ok", true);
tcpstack.Send(pipe, ret.stringify(false));
}
Allow different versions for the different OS clients
/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "RestoreFiles.h"
#include "../Interface/Server.h"
#include "../Interface/SettingsReader.h"
#include "ClientService.h"
#include "InternetClient.h"
#include "ServerIdentityMgr.h"
#include "../common/data.h"
#include "../urbackupcommon/capa_bits.h"
#include "../urbackupcommon/escape.h"
#include "client.h"
#include "database.h"
#include "../stringtools.h"
#include "../urbackupcommon/json.h"
#include "../cryptoplugin/ICryptoFactory.h"
#ifdef _WIN32
#include "win_sysvol.h"
#include "win_ver.h"
#include "win_all_volumes.h"
#include "DirectoryWatcherThread.h"
#else
#include "lin_ver.h"
std::string getSysVolumeCached(std::string &mpath){ return ""; }
std::string getEspVolumeCached(std::string &mpath){ return ""; }
#endif
#include "../client_version.h"
#include <stdlib.h>
#include <limits.h>
#ifndef _WIN32
#define _atoi64 atoll
#endif
extern std::string time_format_str;
extern ICryptoFactory *crypto_fak;
void ClientConnector::CMD_ADD_IDENTITY(const std::string &identity, const std::string &cmd, bool ident_ok)
{
if(identity.empty())
{
tcpstack.Send(pipe, "Identity empty");
}
else
{
if(Server->getServerParameter("restore_mode")=="true" && !ident_ok )
{
ServerIdentityMgr::addServerIdentity(identity, SPublicKeys());
tcpstack.Send(pipe, "OK");
}
else if( ident_ok )
{
tcpstack.Send(pipe, "OK");
}
else
{
ServerIdentityMgr::loadServerIdentities();
if( ServerIdentityMgr::checkServerIdentity(identity) )
{
if(ServerIdentityMgr::hasPublicKey(identity))
{
tcpstack.Send(pipe, "needs certificate");
}
else
{
tcpstack.Send(pipe, "OK");
}
return;
}
if( ServerIdentityMgr::numServerIdentities()==0 )
{
ServerIdentityMgr::addServerIdentity(identity, SPublicKeys());
tcpstack.Send(pipe, "OK");
}
else
{
if( !ServerIdentityMgr::hasOnlineServer() && ServerIdentityMgr::isNewIdentity(identity) )
{
IScopedLock lock(ident_mutex);
new_server_idents.push_back(identity);
}
tcpstack.Send(pipe, "failed");
}
}
}
}
void ClientConnector::CMD_GET_CHALLENGE(const std::string &identity, const std::string& cmd)
{
if(identity.empty())
{
tcpstack.Send(pipe, "");
return;
}
std::string clientsubname;
if (cmd.size() > 14)
{
std::string s_params = cmd.substr(14);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
clientsubname = params["clientsubname"];
}
IScopedLock lock(ident_mutex);
std::string challenge = Server->secureRandomString(30)+"-"+convert(Server->getTimeSeconds())+"-"+convert(Server->getTimeMS());
challenges[std::make_pair(identity, clientsubname)]=challenge;
tcpstack.Send(pipe, challenge);
}
void ClientConnector::CMD_SIGNATURE(const std::string &identity, const std::string &cmd)
{
if(identity.empty())
{
Server->Log("Signature error: Empty identity", LL_ERROR);
tcpstack.Send(pipe, "empty identity");
return;
}
if(crypto_fak==NULL)
{
Server->Log("Signature error: No crypto module", LL_ERROR);
tcpstack.Send(pipe, "no crypto");
return;
}
size_t hashpos = cmd.find("#");
if (hashpos == std::string::npos)
{
Server->Log("Signature error: No parameters", LL_ERROR);
tcpstack.Send(pipe, "no parameters");
return;
}
str_map params;
ParseParamStrHttp(cmd.substr(hashpos + 1), ¶ms);
std::string clientsubname = params["clientsubname"];
std::map<std::pair<std::string, std::string>, std::string>::iterator challenge_it = challenges.find(std::make_pair(identity, clientsubname));
if(challenge_it==challenges.end() || challenge_it->second.empty())
{
Server->Log("Signature error: No challenge", LL_ERROR);
tcpstack.Send(pipe, "no challenge");
return;
}
const std::string& challenge = challenge_it->second;
std::string pubkey = base64_decode_dash(params["pubkey"]);
std::string pubkey_ecdsa409k1 = base64_decode_dash(params["pubkey_ecdsa409k1"]);
std::string signature = base64_decode_dash(params["signature"]);
std::string signature_ecdsa409k1 = base64_decode_dash(params["signature_ecdsa409k1"]);
std::string session_identity = params["session_identity"];
if(!ServerIdentityMgr::hasPublicKey(identity))
{
ServerIdentityMgr::setPublicKeys(identity, SPublicKeys(pubkey, pubkey_ecdsa409k1));
}
SPublicKeys pubkeys = ServerIdentityMgr::getPublicKeys(identity);
if( (!pubkeys.ecdsa409k1_key.empty() && crypto_fak->verifyData(pubkeys.ecdsa409k1_key, challenge, signature_ecdsa409k1))
|| (pubkeys.ecdsa409k1_key.empty() && !pubkeys.dsa_key.empty() && crypto_fak->verifyDataDSA(pubkeys.dsa_key, challenge, signature)) )
{
ServerIdentityMgr::addSessionIdentity(session_identity, endpoint_name);
ServerIdentityMgr::setPublicKeys(identity, SPublicKeys(pubkey, pubkey_ecdsa409k1));
tcpstack.Send(pipe, "ok");
challenges.erase(challenge_it);
}
else
{
Server->Log("Signature error: Verification failed", LL_ERROR);
tcpstack.Send(pipe, "signature verification failed");
}
}
void ClientConnector::CMD_START_INCR_FILEBACKUP(const std::string &cmd)
{
std::string s_params;
if(next(cmd, 0, "3START BACKUP"))
{
file_version=2;
if(cmd.size()>14)
s_params=cmd.substr(14);
}
else if(cmd=="2START BACKUP")
{
file_version=2;
}
str_map params;
if(!s_params.empty())
{
ParseParamStrHttp(s_params, ¶ms);
}
int64 server_id = watoi64(params["status_id"]);
std::string resume = params["resume"];
std::string sha_version_str = params["sha"];
int sha_version = 512;
if(!sha_version_str.empty())
{
sha_version = watoi(sha_version_str);
}
int group=c_group_default;
str_map::iterator it_group = params.find("group");
if(it_group!=params.end())
{
group = watoi(it_group->second);
}
std::string clientsubname;
str_map::iterator it_clientsubname = params.find("clientsubname");
if(it_clientsubname!=params.end())
{
clientsubname = conv_filename((it_clientsubname->second));
}
unsigned int flags = 0;
if(params.find("with_scripts")!=params.end())
{
flags |= flag_with_scripts;
}
if(params.find("with_orig_path")!=params.end())
{
flags |= flag_with_orig_path;
}
if(params.find("with_sequence")!=params.end())
{
flags |= flag_with_sequence;
}
if(params.find("with_proper_symlinks")!=params.end())
{
flags |= flag_with_proper_symlinks;
}
if(end_to_end_file_backup_verification_enabled)
{
flags |= flag_end_to_end_verification;
}
if(calculateFilehashesOnClient(clientsubname))
{
flags |= flag_calc_checksums;
}
state=CCSTATE_START_FILEBACKUP;
IScopedLock lock(backup_mutex);
CWData data;
data.addChar(IndexThread::IndexThreadAction_StartIncrFileBackup);
data.addVoidPtr(mempipe);
data.addString(server_token);
data.addInt(group);
data.addInt(flags);
data.addString(clientsubname);
data.addInt(sha_version);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
RunningAction action = RUNNING_NONE;
if(resume.empty())
{
action =RUNNING_INCR_FILE;
}
else if(resume=="full")
{
action =RUNNING_RESUME_FULL_FILE;
}
else if(resume=="incr")
{
action =RUNNING_RESUME_INCR_FILE;
}
SRunningProcess new_proc;
new_proc.action = action;
new_proc.server_id = server_id;
new_proc.id = ++curr_backup_running_id;
new_proc.server_token = server_token;
IScopedLock process_lock(process_mutex);
removeTimedOutProcesses(server_token, true);
running_processes.push_back(new_proc);
status_updated = true;
end_to_end_file_backup_verification_enabled=false;
}
void ClientConnector::CMD_START_FULL_FILEBACKUP(const std::string &cmd)
{
std::string s_params;
if(cmd=="2START FULL BACKUP")
{
file_version=2;
}
else if(next(cmd,0,"3START FULL BACKUP"))
{
file_version=2;
if(cmd.size()>19)
s_params=cmd.substr(19);
}
str_map params;
if(!s_params.empty())
{
ParseParamStrHttp(s_params, ¶ms);
}
int group=c_group_default;
str_map::iterator it_group = params.find("group");
if(it_group!=params.end())
{
group = watoi(it_group->second);
}
int64 server_id = watoi64(params["status_id"]);
std::string sha_version_str = params["sha"];
int sha_version = 512;
if(!sha_version_str.empty())
{
sha_version = watoi(sha_version_str);
}
std::string clientsubname;
str_map::iterator it_clientsubname = params.find("clientsubname");
if(it_clientsubname!=params.end())
{
clientsubname = conv_filename((it_clientsubname->second));
}
int flags = 0;
if(params.find("with_scripts")!=params.end())
{
flags |= flag_with_scripts;
}
if(params.find("with_orig_path")!=params.end())
{
flags |= flag_with_orig_path;
}
if(params.find("with_sequence")!=params.end())
{
flags |= flag_with_sequence;
}
if(params.find("with_proper_symlinks")!=params.end())
{
flags |= flag_with_proper_symlinks;
}
if(end_to_end_file_backup_verification_enabled)
{
flags |= flag_end_to_end_verification;
}
if(calculateFilehashesOnClient(clientsubname))
{
flags |= flag_calc_checksums;
}
state=CCSTATE_START_FILEBACKUP;
IScopedLock lock(backup_mutex);
CWData data;
data.addChar(IndexThread::IndexThreadAction_StartFullFileBackup);
data.addVoidPtr(mempipe);
data.addString(server_token);
data.addInt(group);
data.addInt(flags);
data.addString(clientsubname);
data.addInt(sha_version);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
end_to_end_file_backup_verification_enabled=false;
SRunningProcess new_proc;
new_proc.action = RUNNING_FULL_FILE;
new_proc.server_id = server_id;
new_proc.id = ++curr_backup_running_id;
new_proc.server_token = server_token;
IScopedLock process_lock(process_mutex);
removeTimedOutProcesses(server_token, true);
running_processes.push_back(new_proc);
status_updated = true;
}
void ClientConnector::CMD_START_SHADOWCOPY(const std::string &cmd)
{
if(cmd[cmd.size()-1]=='"')
{
state=CCSTATE_SHADOWCOPY;
std::string dir=cmd.substr(10, cmd.size()-11);
std::string clientsubname;
if (dir.find("/") != std::string::npos)
{
std::string str_params = getafter("/", dir);
dir = getuntil("/", dir);
str_map params;
ParseParamStrHttp(str_params, ¶ms);
clientsubname = params["clientsubname"];
}
CWData data;
data.addChar(IndexThread::IndexThreadAction_ReferenceShadowcopy);
data.addVoidPtr(mempipe);
data.addString(dir);
data.addString(server_token);
data.addUChar(0);
data.addUChar(1);
data.addString(clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
}
else
{
Server->Log("Invalid command", LL_ERROR);
}
}
void ClientConnector::CMD_STOP_SHADOWCOPY(const std::string &cmd)
{
if(cmd[cmd.size()-1]=='"')
{
state=CCSTATE_SHADOWCOPY;
std::string dir=cmd.substr(9, cmd.size()-10);
std::string clientsubname;
if (dir.find("/") != std::string::npos)
{
std::string str_params = getafter("/", dir);
dir = getuntil("/", dir);
str_map params;
ParseParamStrHttp(str_params, ¶ms);
clientsubname = params["clientsubname"];
}
CWData data;
data.addChar(IndexThread::IndexThreadAction_ReleaseShadowcopy);
data.addVoidPtr(mempipe);
data.addString(dir);
data.addString(server_token);
data.addUChar(0);
data.addInt(-1);
data.addString(clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
lasttime=Server->getTimeMS();
}
else
{
Server->Log("Invalid command", LL_ERROR);
}
}
void ClientConnector::CMD_SET_INCRINTERVAL(const std::string &cmd)
{
if(cmd[cmd.size()-1]=='"')
{
IScopedLock lock(backup_mutex);
std::string intervall=cmd.substr(15, cmd.size()-16);
bool update_db=false;
if(intervall.find("?")!=std::string::npos)
{
str_map params;
ParseParamStrHttp(getafter("?", intervall), ¶ms);
str_map::iterator it_startup_delay=params.find("startup_delay");
if(it_startup_delay!=params.end())
{
int new_waittime = watoi(it_startup_delay->second);
if(new_waittime>backup_alert_delay)
{
update_db=true;
backup_alert_delay = new_waittime;
}
}
}
int new_interval=atoi(intervall.c_str());
if(new_interval!=0 && new_interval!=backup_interval)
{
update_db=true;
backup_interval = new_interval;
}
tcpstack.Send(pipe, "OK");
lasttime=Server->getTimeMS();
if(update_db)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
ClientDAO dao(db);
dao.updateMiscValue("backup_interval", convert(backup_interval));
dao.updateMiscValue("backup_alert_delay", convert(backup_alert_delay));
}
}
else
{
Server->Log("Invalid command", LL_ERROR);
}
}
void ClientConnector::CMD_GET_BACKUPDIRS(const std::string &cmd)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
IQuery *q=db->Prepare("SELECT id,name,path,tgroup,optional FROM backupdirs WHERE symlinked=0");
int timeoutms=300;
db_results res=q->Read(&timeoutms);
IQuery* q_get_virtual_client = db->Prepare("SELECT virtual_client FROM virtual_client_group_offsets WHERE group_offset=?");
if(timeoutms==0)
{
JSON::Object ret;
JSON::Array dirs;
for(size_t i=0;i<res.size();++i)
{
if(res[i]["name"]=="*") continue;
JSON::Object cdir;
cdir.set("id", watoi(res[i]["id"]));
cdir.set("name", res[i]["name"]);
cdir.set("path", res[i]["path"]);
int tgroup = watoi(res[i]["tgroup"]);
cdir.set("group", tgroup%c_group_size);
if (tgroup >= c_group_size)
{
int offset = (tgroup / c_group_size)*c_group_size;
q_get_virtual_client->Bind(offset);
db_results res_vc = q_get_virtual_client->Read();
q_get_virtual_client->Reset();
if (!res_vc.empty())
{
cdir.set("virtual_client", res_vc[0]["virtual_client"]);
}
}
int flags = watoi(res[i]["optional"]);
std::vector<std::pair<int, std::string> > flag_mapping;
flag_mapping.push_back(std::make_pair(EBackupDirFlag_Optional, "optional"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_FollowSymlinks, "follow_symlinks"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_SymlinksOptional, "symlinks_optional"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_OneFilesystem, "one_filesystem"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_RequireSnapshot, "require_snapshot"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_KeepFiles, "keep"));
flag_mapping.push_back(std::make_pair(EBackupDirFlag_ShareHashes, "share_hashes"));
std::string str_flags;
for (size_t j = 0; j < flag_mapping.size(); ++j)
{
if (flags & flag_mapping[j].first)
{
if (!str_flags.empty()) str_flags += ",";
str_flags += flag_mapping[j].second;
}
}
cdir.set("flags", str_flags);
dirs.add(cdir);
}
ret.set("dirs", dirs);
tcpstack.Send(pipe, ret.stringify(false));
}
else
{
pipe->shutdown();
}
db->destroyAllQueries();
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_SAVE_BACKUPDIRS(const std::string &cmd, str_map ¶ms)
{
if(last_capa & DONT_ALLOW_CONFIG_PATHS)
{
tcpstack.Send(pipe, "FAILED");
return;
}
if(saveBackupDirs(params))
{
tcpstack.Send(pipe, "OK");
}
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_DID_BACKUP(const std::string &cmd)
{
updateLastBackup();
tcpstack.Send(pipe, "OK");
{
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
SRunningProcess* proc = getRunningFileBackupProcess(std::string(), 0);
if (proc != NULL)
{
removeRunningProcess(proc->id, true);
}
lasttime=Server->getTimeMS();
status_updated = true;
}
IndexThread::execute_postbackup_hook("postfilebackup");
}
void ClientConnector::CMD_DID_BACKUP2(const std::string &cmd)
{
std::string params_str = cmd.substr(12);
str_map params;
ParseParamStrHttp(params_str, ¶ms);
updateLastBackup();
tcpstack.Send(pipe, "OK");
std::string server_token = params["server_token"];
if (server_token.empty())
{
return;
}
{
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
SRunningProcess* proc = getRunningFileBackupProcess(server_token, watoi64(params["status_id"]));
if (proc != NULL)
{
removeRunningProcess(proc->id, true);
}
lasttime = Server->getTimeMS();
status_updated = true;
}
IndexThread::execute_postbackup_hook("postfilebackup");
}
int64 ClientConnector::getLastBackupTime()
{
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
IQuery *q=db->Prepare("SELECT strftime('%s',last_backup) AS last_backup FROM status", false);
if (q == NULL)
return 0;
int timeoutms=300;
db_results res=q->Read(&timeoutms);
if(timeoutms==1)
{
res=cached_status;
}
else
{
cached_status=res;
}
db->destroyQuery(q);
if(res.size()>0)
{
return watoi64(res[0]["last_backup"]);
}
else
{
return 0;
}
}
std::string ClientConnector::getCurrRunningJob(bool reset_done, int& pcdone)
{
SRunningProcess* proc = getActiveProcess(x_pingtimeout);
if(proc==NULL )
{
return getHasNoRecentBackup();
}
else
{
pcdone = proc->pcdone;
return actionToStr(proc->action);
}
}
SChannel * ClientConnector::getCurrChannel()
{
for (size_t i = 0; i < channel_pipes.size(); ++i)
{
if (channel_pipes[i].pipe == pipe)
{
return &channel_pipes[i];
}
}
return NULL;
}
void ClientConnector::CMD_STATUS(const std::string &cmd)
{
state=CCSTATE_STATUS;
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_STATUS_DETAIL(const std::string &cmd)
{
IScopedLock lock(backup_mutex);
JSON::Object ret;
ret.set("last_backup_time", getLastBackupTime());
JSON::Array j_running_processes;
for (size_t i = 0; i < running_processes.size(); ++i)
{
if (Server->getTimeMS() - running_processes[i].last_pingtime > x_pingtimeout)
{
continue;
}
JSON::Object obj;
obj.set("percent_done", running_processes[i].pcdone);
obj.set("action", actionToStr(running_processes[i].action));
obj.set("eta_ms", running_processes[i].eta_ms);
if (!running_processes[i].details.empty())
{
obj.set("details", running_processes[i].details);
}
if (running_processes[i].detail_pc != -1)
{
obj.set("detail_pc", running_processes[i].detail_pc);
}
if (running_processes[i].total_bytes >= 0)
{
obj.set("total_bytes", running_processes[i].total_bytes);
obj.set("done_bytes", running_processes[i].done_bytes);
}
obj.set("process_id", running_processes[i].id);
obj.set("server_status_id", running_processes[i].server_id);
obj.set("speed_bpms", running_processes[i].speed_bpms);
j_running_processes.add(obj);
}
ret.set("running_processes", j_running_processes);
JSON::Array j_finished_processes;
for (size_t i = 0; i < finished_processes.size(); ++i)
{
JSON::Object obj;
obj.set("process_id", finished_processes[i].id);
obj.set("success", finished_processes[i].success);
j_finished_processes.add(obj);
}
ret.set("finished_processes", j_finished_processes);
JSON::Array servers;
for(size_t i=0;i<channel_pipes.size();++i)
{
JSON::Object obj;
obj.set("internet_connection", channel_pipes[i].internet_connection);
obj.set("name", channel_pipes[i].endpoint_name);
servers.add(obj);
}
ret.set("servers", servers);
ret.set("time_since_last_lan_connection", InternetClient::timeSinceLastLanConnection());
ret.set("internet_connected", InternetClient::isConnected());
ret.set("internet_status", InternetClient::getStatusMsg());
ret.set("capability_bits", getCapabilities());
tcpstack.Send(pipe, ret.stringify(false));
IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
db->destroyAllQueries();
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_UPDATE_SETTINGS(const std::string &cmd)
{
std::string s_settings=cmd.substr(9);
unescapeMessage(s_settings);
updateSettings( s_settings );
tcpstack.Send(pipe, "OK");
lasttime=Server->getTimeMS();
}
void ClientConnector::CMD_PING_RUNNING(const std::string &cmd)
{
tcpstack.Send(pipe, "OK");
idle_timeout = 120000;
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
lasttime=Server->getTimeMS();
std::string pcdone_new = getbetween("-", "-", cmd);
last_token_times[server_token] = Server->getTimeSeconds();
SRunningProcess* proc = getRunningFileBackupProcess(server_token, 0);
if (proc == NULL)
{
return;
}
int pcdone_old = proc->pcdone;
if (pcdone_new.empty())
proc->pcdone = -1;
else
proc->pcdone = atoi(pcdone_new.c_str());
if (pcdone_old != proc->pcdone)
{
status_updated = true;
}
proc->eta_ms = 0;
proc->last_pingtime = Server->getTimeMS();
#ifdef _WIN32
SetThreadExecutionState(ES_SYSTEM_REQUIRED);
#endif
}
void ClientConnector::CMD_PING_RUNNING2(const std::string &cmd)
{
std::string params_str = cmd.substr(14);
str_map params;
ParseParamStrHttp(params_str, ¶ms);
tcpstack.Send(pipe, "OK");
idle_timeout = 120000;
IScopedLock lock(backup_mutex);
IScopedLock process_lock(process_mutex);
last_token_times[server_token] = Server->getTimeSeconds();
lasttime=Server->getTimeMS();
SRunningProcess* proc = getRunningBackupProcess(server_token, watoi64(params["status_id"]));
if (proc == NULL)
{
return;
}
std::string pcdone_new=params["pc_done"];
int pcdone_old = proc->pcdone;
if(pcdone_new.empty())
proc->pcdone =-1;
else
proc->pcdone =watoi(pcdone_new);
if(pcdone_old!= proc->pcdone)
{
status_updated = true;
}
proc->eta_ms = watoi64(params["eta_ms"]);
proc->last_pingtime = Server->getTimeMS();
proc->speed_bpms = atof(params["speed_bpms"].c_str());
proc->total_bytes = watoi64(params["total_bytes"]);
proc->done_bytes = watoi64(params["done_bytes"]);
#ifdef _WIN32
SetThreadExecutionState(ES_SYSTEM_REQUIRED);
#endif
}
void ClientConnector::CMD_CHANNEL(const std::string &cmd, IScopedLock *g_lock, const std::string& identity)
{
bool img_download_running = false;
{
IScopedLock lock(process_mutex);
SRunningProcess* proc = getRunningProcess(RUNNING_RESTORE_IMAGE, std::string());
img_download_running = proc != NULL;
}
if(!img_download_running)
{
g_lock->relock(backup_mutex);
std::string token;
std::string s_params=cmd.substr(9);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
int capa=watoi(params["capa"]);
token=params["token"];
channel_pipes.push_back(SChannel(pipe, internet_conn, endpoint_name, token,
&make_fileserv, identity, capa, watoi(params["restore_version"])));
is_channel=true;
state=CCSTATE_CHANNEL;
last_channel_ping=Server->getTimeMS();
lasttime=Server->getTimeMS();
Server->Log("New channel: Number of Channels: "+convert((int)channel_pipes.size()), LL_DEBUG);
}
}
void ClientConnector::CMD_CHANNEL_PONG(const std::string &cmd, const std::string& endpoint_name)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
SChannel* chan = getCurrChannel();
if (chan != NULL && chan->state == SChannel::EChannelState_Pinging)
{
chan->state = SChannel::EChannelState_Idle;
}
refreshSessionFromChannel(endpoint_name);
}
void ClientConnector::CMD_CHANNEL_PING(const std::string &cmd, const std::string& endpoint_name)
{
lasttime=Server->getTimeMS();
if(tcpstack.Send(pipe, "PONG")==0)
{
do_quit=true;
}
refreshSessionFromChannel(endpoint_name);
}
void ClientConnector::CMD_TOCHANNEL_START_INCR_FILEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_INCR_FILE);
}
void ClientConnector::CMD_TOCHANNEL_START_FULL_FILEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_FULL_FILE);
}
void ClientConnector::CMD_TOCHANNEL_START_FULL_IMAGEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_FULL_IMAGE);
}
void ClientConnector::CMD_TOCHANNEL_START_INCR_IMAGEBACKUP(const std::string &cmd)
{
tochannelSendStartbackup(RUNNING_INCR_IMAGE);
}
void ClientConnector::CMD_TOCHANNEL_UPDATE_SETTINGS(const std::string &cmd)
{
if(last_capa & DONT_SHOW_SETTINGS)
{
tcpstack.Send(pipe, "FAILED");
return;
}
std::string s_settings=cmd.substr(16);
lasttime=Server->getTimeMS();
unescapeMessage(s_settings);
replaceSettings( s_settings );
IScopedLock lock(backup_mutex);
bool ok=false;
for(size_t o=0;o<channel_pipes.size();++o)
{
CTCPStack tmpstack(channel_pipes[o].internet_connection);
_u32 rc=(_u32)tmpstack.Send(channel_pipes[o].pipe, "UPDATE SETTINGS");
if(rc!=0)
ok=true;
}
if(!ok)
{
tcpstack.Send(pipe, "NOSERVER");
}
else
{
tcpstack.Send(pipe, "OK");
}
}
void ClientConnector::CMD_LOGDATA(const std::string &cmd)
{
std::string ldata=cmd.substr(9);
size_t cpos=ldata.find(" ");
std::string created=getuntil(" ", ldata);
lasttime=Server->getTimeMS();
saveLogdata(created, getafter(" ",ldata));
tcpstack.Send(pipe, "OK");
}
void ClientConnector::CMD_PAUSE(const std::string &cmd)
{
lasttime=Server->getTimeMS();
std::string b=cmd.substr(6);
bool ok=false;
IScopedLock lock(backup_mutex);
status_updated = true;
if(b=="true")
{
ok=true;
IdleCheckerThread::setPause(true);
IndexThread::getFileSrv()->setPause(true);
}
else if(b=="false")
{
ok=true;
IdleCheckerThread::setPause(false);
IndexThread::getFileSrv()->setPause(false);
}
if(ok) tcpstack.Send(pipe, "OK");
else tcpstack.Send(pipe, "FAILED");
}
void ClientConnector::CMD_GET_LOGPOINTS(const std::string &cmd)
{
lasttime=Server->getTimeMS();
tcpstack.Send(pipe, getLogpoints() );
}
void ClientConnector::CMD_GET_LOGDATA(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
int logid=watoi(params["logid"]);
int loglevel=watoi(params["loglevel"]);
std::string ret;
getLogLevel(logid, loglevel, ret);
tcpstack.Send(pipe, ret);
}
void ClientConnector::CMD_FULL_IMAGE(const std::string &cmd, bool ident_ok)
{
if(ident_ok)
{
lasttime=Server->getTimeMS();
std::string s_params=cmd.substr(11);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
server_token=(params["token"]);
image_inf.image_letter=(params["letter"]);
image_inf.orig_image_letter = image_inf.image_letter;
image_inf.server_status_id = watoi(params["status_id"]);
image_inf.shadowdrive=(params["shadowdrive"]);
if(params.find("start")!=params.end())
{
image_inf.startpos=(uint64)_atoi64((params["start"]).c_str());
}
else
{
image_inf.startpos=0;
}
if(params.find("shadowid")!=params.end())
{
image_inf.shadow_id=watoi(params["shadowid"]);
}
else
{
image_inf.shadow_id=-1;
}
image_inf.with_checksum=false;
if(params.find("checksum")!=params.end())
{
if(params["checksum"]=="1")
image_inf.with_checksum=true;
}
image_inf.with_bitmap=false;
if(params.find("bitmap")!=params.end())
{
if(params["bitmap"]=="1")
image_inf.with_bitmap=true;
}
image_inf.no_shadowcopy=false;
image_inf.clientsubname = params["clientsubname"];
if(image_inf.image_letter=="SYSVOL"
|| image_inf.image_letter=="ESP")
{
std::string mpath;
std::string sysvol;
if(image_inf.image_letter=="SYSVOL")
{
sysvol=getSysVolumeCached(mpath);
}
else
{
sysvol=getEspVolumeCached(mpath);
}
if(!mpath.empty())
{
image_inf.image_letter=mpath;
}
else if(!sysvol.empty())
{
image_inf.image_letter=sysvol;
image_inf.no_shadowcopy=true;
}
else
{
ImageErr("Not found");
return;
}
}
if(image_inf.startpos==0 && !image_inf.no_shadowcopy)
{
CWData data;
data.addChar(IndexThread::IndexThreadAction_CreateShadowcopy);
data.addVoidPtr(mempipe);
data.addString(image_inf.image_letter);
data.addString(server_token);
data.addUChar(1); //full image backup
data.addUChar(0); //filesrv
data.addString(image_inf.clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
else if(image_inf.shadow_id!=-1)
{
image_inf.shadowdrive.clear();
CWData data;
data.addChar(4);
data.addVoidPtr(mempipe);
data.addInt(image_inf.shadow_id);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
if(image_inf.no_shadowcopy)
{
image_inf.shadowdrive=image_inf.image_letter;
if(!image_inf.shadowdrive.empty() && image_inf.shadowdrive[0]!='\\')
{
image_inf.shadowdrive="\\\\.\\"+image_inf.image_letter;
}
}
lasttime=Server->getTimeMS();
sendFullImage();
}
else
{
ImageErr("Ident reset (1)");
}
}
void ClientConnector::CMD_INCR_IMAGE(const std::string &cmd, bool ident_ok)
{
if(ident_ok)
{
lasttime=Server->getTimeMS();
std::string s_params=cmd.substr(11);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
server_token=(params["token"]);
str_map::iterator f_hashsize=params.find("hashsize");
if(f_hashsize!=params.end())
{
hashdataok=false;
hashdataleft=watoi(f_hashsize->second);
image_inf.image_letter=(params["letter"]);
image_inf.shadowdrive=(params["shadowdrive"]);
image_inf.server_status_id = watoi(params["status_id"]);
if(params.find("start")!=params.end())
{
image_inf.startpos=(uint64)_atoi64((params["start"]).c_str());
}
else
{
image_inf.startpos=0;
}
if(params.find("shadowid")!=params.end())
{
image_inf.shadow_id=watoi(params["shadowid"]);
}
else
{
image_inf.shadow_id=-1;
}
image_inf.with_checksum=false;
if(params.find("checksum")!=params.end())
{
if(params["checksum"]=="1")
image_inf.with_checksum=true;
}
image_inf.with_bitmap=false;
if(params.find("bitmap")!=params.end())
{
if(params["bitmap"]=="1")
image_inf.with_bitmap=true;
}
image_inf.no_shadowcopy=false;
image_inf.clientsubname = params["clientsubname"];
if(image_inf.startpos==0)
{
CWData data;
data.addChar(IndexThread::IndexThreadAction_CreateShadowcopy);
data.addVoidPtr(mempipe);
data.addString(image_inf.image_letter);
data.addString(server_token);
data.addUChar(2); //incr image backup
data.addUChar(0); //file serv?
data.addString(image_inf.clientsubname);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
else if(image_inf.shadow_id!=-1)
{
image_inf.shadowdrive.clear();
CWData data;
data.addChar(4);
data.addVoidPtr(mempipe);
data.addInt(image_inf.shadow_id);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
mempipe_owner=false;
}
hashdatafile=Server->openTemporaryFile();
if(hashdatafile==NULL)
{
Server->Log("Error creating temporary file in CMD_INCR_IMAGE", LL_ERROR);
do_quit=true;
return;
}
if(tcpstack.getBuffersize()>0)
{
if(hashdatafile->Write(tcpstack.getBuffer(), (_u32)tcpstack.getBuffersize())!=tcpstack.getBuffersize())
{
Server->Log("Error writing to hashdata temporary file in CMD_INCR_IMAGE", LL_ERROR);
do_quit=true;
return;
}
if(hashdataleft>=tcpstack.getBuffersize())
{
hashdataleft-=(_u32)tcpstack.getBuffersize();
//Server->Log("Hashdataleft: "+convert(hashdataleft), LL_DEBUG);
}
else
{
Server->Log("Too much hashdata - error in CMD_INCR_IMAGE", LL_ERROR);
}
tcpstack.reset();
if(hashdataleft==0)
{
hashdataok=true;
state=CCSTATE_IMAGE;
return;
}
}
lasttime=Server->getTimeMS();
sendIncrImage();
}
}
else
{
ImageErr("Ident reset (2)");
}
}
void ClientConnector::CMD_MBR(const std::string &cmd)
{
lasttime=Server->getTimeMS();
std::string s_params=cmd.substr(4);
str_map params;
ParseParamStrHttp(s_params, ¶ms);
std::string dl=params["driveletter"];
if(dl=="SYSVOL")
{
std::string mpath;
dl=getSysVolumeCached(mpath);
}
else if(dl=="ESP")
{
std::string mpath;
dl=getEspVolumeCached(mpath);
}
bool b=false;
std::string errmsg;
if(!dl.empty())
{
b=sendMBR(dl, errmsg);
}
if(!b)
{
CWData r;
r.addChar(0);
r.addString((errmsg));
tcpstack.Send(pipe, r);
}
}
void ClientConnector::CMD_RESTORE_GET_BACKUPCLIENTS(const std::string &cmd)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "0");
}
else
{
std::string clients;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], "GET BACKUPCLIENTS");
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after request -1", LL_DEBUG);
std::string nc=receivePacket(channel_pipes[i]);
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after read -1", LL_DEBUG);
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+": --"+nc+"--", LL_DEBUG);
if(!nc.empty())
{
clients+=nc+"\n";
}
}
tcpstack.Send(pipe, "1"+clients);
}
}
void ClientConnector::CMD_RESTORE_GET_BACKUPIMAGES(const std::string &cmd)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "0");
}
else
{
std::string imgs;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], cmd);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty())
{
imgs+=nc+"\n";
}
}
tcpstack.Send(pipe, "1"+imgs);
}
}
void ClientConnector::CMD_RESTORE_GET_FILE_BACKUPS(const std::string &cmd)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "0");
}
else
{
std::string filebackups;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], cmd);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty())
{
filebackups+=nc+"\n";
}
}
tcpstack.Send(pipe, "1"+filebackups);
}
}
void ClientConnector::CMD_RESTORE_GET_FILE_BACKUPS_TOKENS( const std::string &cmd, str_map ¶ms )
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "1");
}
else
{
std::string utf8_tokens = (params["tokens"]);
std::string filebackups;
std::string accessparams;
if(channel_pipes.size()==1)
{
accessparams+=" with_id_offset=false";
}
bool has_token_params=false;
for(size_t i=0;i<channel_pipes.size();++i)
{
for(size_t j=0;j<2;++j)
{
if(channel_pipes[i].last_tokens!=utf8_tokens)
{
if(!has_token_params)
{
std::string token_params = getAccessTokensParams(params["tokens"], true);
if(token_params.empty())
{
tcpstack.Send(pipe, "2");
return;
}
if(accessparams.empty())
{
accessparams = token_params;
accessparams[0]=' ';
}
else
{
accessparams+=token_params;
}
has_token_params=true;
}
}
sendChannelPacket(channel_pipes[i], cmd+accessparams);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty() && nc!="err")
{
channel_pipes[i].last_tokens = utf8_tokens;
if(!filebackups.empty())
{
filebackups[filebackups.size()-1] = ',';
nc[0]=' ';
}
filebackups+=nc;
break;
}
else if(!has_token_params)
{
channel_pipes[i].last_tokens="";
}
else
{
break;
}
}
}
if(filebackups.empty())
{
tcpstack.Send(pipe, "3");
}
else
{
tcpstack.Send(pipe, "0"+filebackups);
}
}
}
void ClientConnector::CMD_GET_FILE_LIST_TOKENS(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "1");
}
else
{
std::string accessparams;
str_map::iterator it_path = params.find("path");
if(it_path!=params.end())
{
accessparams+="&path="+EscapeParamString((it_path->second));
}
str_map::iterator it_backupid = params.find("backupid");
if(it_backupid!=params.end())
{
accessparams+="&backupid="+EscapeParamString((it_backupid->second));
}
if(channel_pipes.size()==1)
{
accessparams+="&with_id_offset=false";
}
std::string filelist;
if(!accessparams.empty())
{
accessparams[0]=' ';
}
std::string utf8_tokens = (params["tokens"]);
bool has_token_params=false;
bool break_outer=false;
for(size_t i=0;i<channel_pipes.size();++i)
{
for(size_t j=0;j<2;++j)
{
if(channel_pipes[i].last_tokens!=utf8_tokens)
{
if(!has_token_params)
{
std::string token_params = getAccessTokensParams(params["tokens"], true);
if(token_params.empty())
{
tcpstack.Send(pipe, "2");
return;
}
if(accessparams.empty())
{
accessparams = token_params;
accessparams[0]=' ';
}
else
{
accessparams+=token_params;
}
has_token_params=true;
}
}
sendChannelPacket(channel_pipes[i], cmd+accessparams);
std::string nc=receivePacket(channel_pipes[i]);
if(!nc.empty() && nc!="err")
{
channel_pipes[i].last_tokens = utf8_tokens;
if(!filelist.empty())
{
filelist[filelist.size()-1] = ',';
nc[0]=' ';
}
filelist+=nc;
if(it_backupid!=params.end())
{
break_outer=true;
break;
}
break;
}
else if(!has_token_params)
{
channel_pipes[i].last_tokens="";
}
else
{
break;
}
}
if(break_outer)
{
break;
}
}
if(!filelist.empty())
{
tcpstack.Send(pipe, "0"+filelist);
}
else
{
tcpstack.Send(pipe, "3");
}
}
}
void ClientConnector::CMD_DOWNLOAD_FILES_TOKENS(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "1");
return;
}
std::string accessparams;
str_map::iterator it_path = params.find("path");
if(it_path==params.end())
{
tcpstack.Send(pipe, "2");
return;
}
accessparams+="&path="+EscapeParamString((it_path->second));
str_map::iterator it_backupid = params.find("backupid");
if(it_backupid==params.end())
{
tcpstack.Send(pipe, "3");
return;
}
accessparams+="&backupid="+EscapeParamString((it_backupid->second));
if(channel_pipes.size()==1)
{
accessparams+="&with_id_offset=false";
}
std::string restore_token_binary;
restore_token_binary.resize(16);
Server->secureRandomFill(&restore_token_binary[0], restore_token_binary.size());
restore_token.restore_token = bytesToHex(restore_token_binary);
restore_token.restore_token_time = Server->getTimeMS();
{
IScopedLock process_lock(process_mutex);
restore_token.process_id = ++curr_backup_running_id;
}
accessparams+="&restore_token="+ restore_token.restore_token+"&process_id="+convert(restore_token.process_id);
str_map::iterator it_clean_other = params.find("clean_other");
if (it_clean_other != params.end())
{
accessparams += "&clean_other=" + EscapeParamString(it_clean_other->second);
}
str_map::iterator it_ignore_other_fs = params.find("ignore_other_fs");
if (it_clean_other != params.end())
{
accessparams += "&ignore_other_fs=" + EscapeParamString(it_ignore_other_fs->second);
}
std::string filelist;
accessparams[0]=' ';
std::string utf8_tokens = params["tokens"];
bool has_token_params=false;
std::string last_err;
for(size_t i=0;i<channel_pipes.size();++i)
{
for(size_t j=0;j<2;++j)
{
if(channel_pipes[i].last_tokens!=utf8_tokens)
{
if(!has_token_params)
{
std::string token_params = getAccessTokensParams(params["tokens"], true);
if(token_params.empty())
{
tcpstack.Send(pipe, "error encrypting access tokens");
return;
}
if(accessparams.empty())
{
accessparams = token_params;
accessparams[0]=' ';
}
else
{
accessparams+=token_params;
}
has_token_params=true;
}
}
sendChannelPacket(channel_pipes[i], cmd+accessparams);
last_err=receivePacket(channel_pipes[i]);
if(!last_err.empty() && last_err!="err")
{
channel_pipes[i].last_tokens = utf8_tokens;
tcpstack.Send(pipe, "0" + last_err);
return;
}
else if(!has_token_params)
{
channel_pipes[i].last_tokens="";
}
else
{
break;
}
}
}
tcpstack.Send(pipe, last_err);
}
void ClientConnector::CMD_RESTORE_DOWNLOAD_IMAGE(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
Server->Log("Downloading image...", LL_DEBUG);
IScopedLock lock(backup_mutex);
waitForPings(&lock);
Server->Log("In mutex...",LL_DEBUG);
downloadImage(params);
Server->Log("Download done -2", LL_DEBUG);
do_quit=true;
}
void ClientConnector::CMD_RESTORE_DOWNLOAD_FILES(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
Server->Log("Downloading files...", LL_DEBUG);
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "No backup server found");
return;
}
std::string last_error;
for(size_t i=0;i<channel_pipes.size();++i)
{
IPipe *c=channel_pipes[i].pipe;
tcpstack.Send(c, "DOWNLOAD FILES backupid="+params["backupid"]+"&time="+params["time"]);
Server->Log("Start downloading files from channel "+convert((int)i), LL_DEBUG);
CTCPStack recv_stack;
int64 starttime = Server->getTimeMS();
while(Server->getTimeMS()-starttime<60000)
{
std::string msg;
if(c->Read(&msg, 60000)>0)
{
recv_stack.AddData(&msg[0], msg.size());
if(recv_stack.getPacket(msg) )
{
if(msg=="ok")
{
tcpstack.Send(pipe, "ok");
return;
}
else
{
last_error=msg;
}
break;
}
}
else
{
break;
}
}
}
if(!last_error.empty())
{
tcpstack.Send(pipe, last_error);
}
else
{
tcpstack.Send(pipe, "timeout");
}
}
void ClientConnector::CMD_RESTORE_DOWNLOADPROGRESS(const std::string &cmd)
{
Server->Log("Sending progress...", LL_DEBUG);
lasttime=Server->getTimeMS();
bool img_download_running = false;
{
IScopedLock lock(process_mutex);
SRunningProcess* proc = getRunningProcess(RUNNING_RESTORE_IMAGE, std::string());
img_download_running = proc != NULL;
}
if(!img_download_running)
{
pipe->Write("100");
do_quit=true;
}
else
{
while(true)
{
{
int progress=0;
{
IScopedLock lock(process_mutex);
SRunningProcess* proc = getRunningProcess(RUNNING_RESTORE_IMAGE, std::string());
if (proc != NULL)
{
progress = proc->pcdone;
}
else
{
break;
}
}
if(!pipe->Write(convert(progress)+"\n", 10000))
{
break;
}
}
{
Server->wait(1000);
}
}
do_quit=true;
}
}
void ClientConnector::CMD_RESTORE_LOGIN_FOR_DOWNLOAD(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "no channels available");
}
else
{
bool one_ok=false;
std::string errors;
for(size_t i=0;i<channel_pipes.size();++i)
{
if(params["username"].empty())
{
sendChannelPacket(channel_pipes[i], "LOGIN username=&password=");
}
else
{
sendChannelPacket(channel_pipes[i], "LOGIN username="+(params["username"])
+"&password="+(params["password"+convert(i)]));
}
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after request -1", LL_DEBUG);
std::string nc=receivePacket(channel_pipes[i]);
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after read -1", LL_DEBUG);
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+": --"+nc+"--", LL_DEBUG);
if(nc=="ok")
{
one_ok=true;
}
else
{
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+" ERROR: --"+nc+"--", LL_ERROR);
if(!errors.empty())
{
errors+=" -- ";
}
errors+=nc;
}
}
if(one_ok)
{
tcpstack.Send(pipe, "ok");
}
else
{
tcpstack.Send(pipe, errors);
}
}
}
void ClientConnector::CMD_RESTORE_GET_SALT(const std::string &cmd, str_map ¶ms)
{
lasttime=Server->getTimeMS();
IScopedLock lock(backup_mutex);
waitForPings(&lock);
if(channel_pipes.size()==0)
{
tcpstack.Send(pipe, "no channels available");
}
else
{
std::string salts;
for(size_t i=0;i<channel_pipes.size();++i)
{
sendChannelPacket(channel_pipes[i], "SALT username="+(params["username"]));
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after request -1", LL_DEBUG);
std::string nc=receivePacket(channel_pipes[i]);
if(channel_pipes[i].pipe->hasError())
Server->Log("Channel has error after read -1", LL_DEBUG);
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+": --"+nc+"--", LL_DEBUG);
if(nc.find("ok;")==0)
{
if(!salts.empty())
{
salts+="/";
}
salts+=nc;
}
else
{
Server->Log("Client "+convert(i)+"/"+convert(channel_pipes.size())+" ERROR: --"+nc+"--", LL_ERROR);
salts+="err;"+nc;
}
}
tcpstack.Send(pipe, salts);
}
}
void ClientConnector::CMD_VERSION_UPDATE(const std::string &cmd)
{
std::string server_version = cmd.substr(8);
#ifdef _WIN32
#define VERSION_FILE_PREFIX ""
#else
#define VERSION_FILE_PREFIX "urbackup/"
if (atoi(server_version.c_str()) < 125)
{
tcpstack.Send(pipe, "noop");
return;
}
#endif
#if defined(_WIN32) || defined(URB_WITH_CLIENTUPDATE)
std::string version_1=getFile(VERSION_FILE_PREFIX "version.txt");
std::string version_2=getFile(VERSION_FILE_PREFIX "curr_version.txt");
if(version_1.empty() ) version_1="0";
if(version_2.empty() ) version_2="0";
if(versionNeedsUpdate(version_1, server_version)
&& versionNeedsUpdate(version_2, server_version) )
{
tcpstack.Send(pipe, "update");
}
else
{
tcpstack.Send(pipe, "noop");
}
#else
tcpstack.Send(pipe, "noop");
return;
#endif
#undef VERSION_FILE_PREFIX
}
void ClientConnector::CMD_CLIENT_UPDATE(const std::string &cmd)
{
hashdatafile=Server->openTemporaryFile();
if(hashdatafile==NULL)
{
Server->Log("Error creating temporary file in CMD_CLIENT_UPDATE", LL_ERROR);
do_quit=true;
return;
}
str_map params;
ParseParamStrHttp(cmd.substr(14), ¶ms);
hashdataleft=watoi(params["size"]);
silent_update=(params["silent_update"]=="true");
hashdataok=false;
state=CCSTATE_UPDATE_DATA;
if(tcpstack.getBuffersize()>0)
{
if(hashdatafile->Write(tcpstack.getBuffer(), (_u32)tcpstack.getBuffersize())!=tcpstack.getBuffersize())
{
Server->Log("Error writing to hashdata temporary file -1update", LL_ERROR);
do_quit=true;
return;
}
if(hashdataleft>=tcpstack.getBuffersize())
{
hashdataleft-=(_u32)tcpstack.getBuffersize();
}
else
{
Server->Log("Too much hashdata - error -1update", LL_ERROR);
}
tcpstack.reset();
if(hashdataleft==0)
{
hashdataok=true;
state=CCSTATE_UPDATE_FINISH;
return;
}
}
return;
}
void ClientConnector::CMD_CAPA(const std::string &cmd)
{
std::string client_version_str=std::string(c_client_version);
std::string restore=Server->getServerParameter("allow_restore");
if(restore.empty() || restore=="default")
{
restore="client-confirms";
}
#ifdef _WIN32
std::string buf;
buf.resize(1024);
std::string os_version_str = get_windows_version();
std::string win_volumes;
std::string win_nonusb_volumes;
{
IScopedLock lock(backup_mutex);
win_volumes = get_all_volumes_list(false, volumes_cache);
win_nonusb_volumes = get_all_volumes_list(true, volumes_cache);
}
tcpstack.Send(pipe, "FILE=2&FILE2=1&IMAGE=1&UPDATE=1&MBR=1&FILESRV=3&SET_SETTINGS=1&IMAGE_VER=1&CLIENTUPDATE=2"
"&CLIENT_VERSION_STR="+EscapeParamString((client_version_str))+"&OS_VERSION_STR="+EscapeParamString(os_version_str)+
"&ALL_VOLUMES="+EscapeParamString(win_volumes)+"&ETA=1&CDP=0&ALL_NONUSB_VOLUMES="+EscapeParamString(win_nonusb_volumes)+"&EFI=1"
"&FILE_META=1&SELECT_SHA=1&RESTORE="+restore+"&CLIENT_BITMAP=1&CMD=1&OS_SIMPLE=windows");
#else
#ifdef __APPLE__
std::string os_simple = "osx";
#elif __linux__
std::string os_simple = "linux";
#else
std::string os_simple = "unknown";
#endif
std::string os_version_str=get_lin_os_version();
tcpstack.Send(pipe, "FILE=2&FILE2=1&FILESRV=3&SET_SETTINGS=1&CLIENTUPDATE=2"
"&CLIENT_VERSION_STR="+EscapeParamString((client_version_str))+"&OS_VERSION_STR="+EscapeParamString(os_version_str)
+"&ETA=1&CPD=0&FILE_META=1&SELECT_SHA=1&RESTORE="+restore+"&CMD=1&OS_SIMPLE="+os_simple);
#endif
}
void ClientConnector::CMD_NEW_SERVER(str_map ¶ms)
{
std::string ident=(params["ident"]);
if(!ident.empty())
{
ServerIdentityMgr::addServerIdentity(ident, SPublicKeys());
tcpstack.Send(pipe, "OK");
}
else
{
tcpstack.Send(pipe, "FAILED");
}
}
void ClientConnector::CMD_RESET_KEEP(str_map ¶ms)
{
std::string virtual_client = params["virtual_client"];
std::string folder_name = params["folder_name"];
int tgroup = watoi(params["tgroup"]);
IDatabase *db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT);
int group_offset = 0;
if (!virtual_client.empty())
{
IQuery *q = db->Prepare("SELECT group_offset FROM virtual_client_group_offsets WHERE virtual_client=?", false);
q->Bind(virtual_client);
db_results res = q->Read();
db->destroyQuery(q);
if (res.empty())
{
tcpstack.Send(pipe, "err_virtual_client_not_found");
return;
}
group_offset = watoi(res[0]["group_offset"]);
}
IQuery* q = db->Prepare(std::string("UPDATE backupdirs SET reset_keep=1 WHERE tgroup=?")
+ (folder_name.empty() ? "" : " AND name=?"), false);
q->Bind(tgroup + group_offset);
if (!folder_name.empty())
{
q->Bind(folder_name);
}
q->Write();
q->Reset();
if (db->getLastChanges() > 0)
{
tcpstack.Send(pipe, "OK");
}
else
{
tcpstack.Send(pipe, "err_backup_folder_not_found");
}
db->destroyQuery(q);
}
void ClientConnector::CMD_ENABLE_END_TO_END_FILE_BACKUP_VERIFICATION(const std::string &cmd)
{
IScopedLock lock(backup_mutex);
end_to_end_file_backup_verification_enabled=true;
tcpstack.Send(pipe, "OK");
}
void ClientConnector::CMD_GET_VSSLOG(const std::string &cmd)
{
CWData data;
IPipe* localpipe=Server->createMemoryPipe();
data.addChar(IndexThread::IndexThreadAction_GetLog);
data.addVoidPtr(localpipe);
IndexThread::getMsgPipe()->Write(data.getDataPtr(), data.getDataSize());
std::string ret;
localpipe->Read(&ret, 8000);
tcpstack.Send(pipe, ret);
localpipe->Write("exit");
}
void ClientConnector::CMD_GET_ACCESS_PARAMS(str_map ¶ms)
{
if(crypto_fak==NULL)
{
Server->Log("No cryptoplugin present. Action not possible.", LL_ERROR);
tcpstack.Send(pipe, "");
return;
}
std::string tokens=params["tokens"];
std::auto_ptr<ISettingsReader> settings(
Server->createFileSettingsReader("urbackup/data/settings.cfg"));
std::string server_url;
if( (!settings->getValue("server_url", &server_url)
&& !settings->getValue("server_url_def", &server_url) )
|| server_url.empty())
{
Server->Log("Server url empty", LL_ERROR);
tcpstack.Send(pipe, "");
return;
}
std::string ret = getAccessTokensParams(tokens, true);
if(!ret.empty())
{
ret[0]='#';
ret = server_url + ret;
}
else
{
tcpstack.Send(pipe, "");
return;
}
tcpstack.Send(pipe, ret);
}
void ClientConnector::CMD_CONTINUOUS_WATCH_START()
{
IScopedLock lock(backup_mutex);
tcpstack.Send(pipe, "OK");
}
void ClientConnector::CMD_SCRIPT_STDERR(const std::string& cmd)
{
std::string script_cmd = (cmd.substr(14));
if(next(script_cmd, 0, "SCRIPT|"))
{
script_cmd = script_cmd.substr(7);
}
std::string stderr_out;
int exit_code;
if(IndexThread::getFileSrv()->getExitInformation(script_cmd, stderr_out, exit_code))
{
tcpstack.Send(pipe, convert(exit_code)+" "+convert(Server->getTimeMS())+" "+stderr_out);
}
else
{
tcpstack.Send(pipe, "err");
}
}
void ClientConnector::CMD_FILE_RESTORE(const std::string& cmd)
{
str_map params;
ParseParamStrHttp(cmd, ¶ms);
int64 restore_process_id = 0;
bool has_restore_token = false;
if (!restore_token.restore_token.empty()
&& params["restore_token"] == restore_token.restore_token
&& Server->getTimeMS() - restore_token.restore_token_time<120 * 1000)
{
restore_token.restore_token = "";
has_restore_token = true;
restore_process_id = restore_token.process_id;
restore_token.process_id = 0;
}
std::string restore=Server->getServerParameter("allow_restore");
if(restore=="default")
{
restore="client-confirms";
}
if(restore!="client-confirms" && restore!="server-confirms"
&& !has_restore_token)
{
tcpstack.Send(pipe, "disabled");
return;
}
std::string client_token = (params["client_token"]);
std::string server_token=params["server_token"];
int64 restore_id=watoi64(params["id"]);
int64 status_id=watoi64(params["status_id"]);
int64 log_id=watoi64(params["log_id"]);
std::string restore_path = params["restore_path"];
bool single_file = params["single_file"]=="1";
bool clean_other = params["clean_other"] == "1";
bool ignore_other_fs = params["ignore_other_fs"] != "0";
int tgroup = watoi(params["tgroup"]);
std::string clientsubname = params["clientsubname"];
if(restore_process_id==0)
{
IScopedLock lock(process_mutex);
restore_process_id = ++curr_backup_running_id;
}
if (crypto_fak != NULL)
{
std::auto_ptr<ISettingsReader> access_keys(
Server->createFileSettingsReader("urbackup/access_keys.properties"));
if (access_keys.get() != NULL)
{
std::string access_key;
if (access_keys->getValue("key." + server_token, &access_key))
{
client_token = crypto_fak->decryptAuthenticatedAES(base64_decode_dash(client_token), access_key, 1);
if (client_token.empty())
{
Server->Log("Error decrypting server access token. Access key might be wrong.", LL_ERROR);
}
}
else
{
Server->Log("key."+ server_token+" not found in urbackup/access_keys.properties", LL_ERROR);
}
}
else
{
Server->Log("Error opening urbackup/access_keys.properties", LL_ERROR);
}
}
else
{
Server->Log("Error decrypting server access token. Crypto_fak not loaded.", LL_ERROR);
}
RestoreFiles* local_restore_files = new RestoreFiles(restore_process_id, restore_id, status_id, log_id,
client_token, server_token, restore_path, single_file, clean_other, ignore_other_fs,
tgroup, clientsubname);
if(restore == "client-confirms" && !has_restore_token)
{
IScopedLock lock(backup_mutex);
restore_ok_status = RestoreOk_Wait;
++ask_restore_ok;
status_updated = true;
if(restore_files!=NULL)
{
delete restore_files;
}
restore_files = local_restore_files;
}
else
{
Server->getThreadPool()->execute(local_restore_files, "file restore");
}
tcpstack.Send(pipe, "ok");
}
void ClientConnector::CMD_RESTORE_OK( str_map ¶ms )
{
IScopedLock lock(backup_mutex);
JSON::Object ret;
if(params["ok"]=="true")
{
restore_ok_status = RestoreOk_Ok;
ret.set("accepted", true);
if(restore_files!=NULL)
{
ret.set("process_id", restore_files->get_local_process_id());
Server->getThreadPool()->execute(restore_files, "file restore");
restore_files=NULL;
}
}
else
{
restore_ok_status = RestoreOk_Declined;
if (restore_files != NULL)
{
restore_files->set_restore_declined(true);
Server->getThreadPool()->execute(restore_files, "file restore");
restore_files = NULL;
}
}
delete restore_files;
restore_files=NULL;
ret.set("ok", true);
tcpstack.Send(pipe, ret.stringify(false));
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <windows.ui.notifications.h>
#include <windows.data.xml.dom.h>
#include <wrl.h>
#include <wchar.h>
#include <vector>
#pragma comment(lib, "delayimp")
#pragma comment(lib, "runtimeobject")
using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::UI::Notifications;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
class ToastNotificationHandler;
static wchar_t* sAppId = nullptr;
static std::vector<ToastNotificationHandler*> sNotifications;
typedef bool (STDAPICALLTYPE *EventCallback)();
class ToastNotificationHandler {
typedef ABI::Windows::UI::Notifications::IToastNotification IToastNotification;
typedef ABI::Windows::UI::Notifications::IToastDismissedEventArgs IToastDismissedEventArgs;
typedef ABI::Windows::UI::Notifications::IToastNotificationManagerStatics IToastNotificationManagerStatics;
typedef ABI::Windows::UI::Notifications::ToastTemplateType ToastTemplateType;
typedef ABI::Windows::Data::Xml::Dom::IXmlNode IXmlNode;
typedef ABI::Windows::Data::Xml::Dom::IXmlDocument IXmlDocument;
typedef __FITypedEventHandler_2_Windows__CUI__CNotifications__CToastNotification_IInspectable_t ToastActivationHandler;
typedef __FITypedEventHandler_2_Windows__CUI__CNotifications__CToastNotification_Windows__CUI__CNotifications__CToastDismissedEventArgs ToastDismissHandler;
public:
ToastNotificationHandler() : mTitle(nullptr), mMessage(nullptr), mName(nullptr), mActivateCallback(nullptr), mDismissCallback(nullptr)
{
}
~ToastNotificationHandler();
bool Init(const wchar_t* aTitle, const wchar_t* aMessage, const wchar_t* aName);
bool DisplayNotification(EventCallback aActivate, EventCallback aDismiss);
bool CloseNotification();
const wchar_t* GetName() const { return mName; }
private:
ComPtr<IXmlDocument> ToastNotificationHandler::InitializeXmlForTemplate(ToastTemplateType templateType);
bool CreateWindowsNotificationFromXml(IXmlDocument* aXml);
HRESULT OnActivate(IToastNotification* aNotification, IInspectable* aInspectable);
HRESULT OnDismiss(IToastNotification* aNotification, IToastDismissedEventArgs* aInspectable);
ComPtr<IToastNotificationManagerStatics> mToastNotificationManagerStatics;
ComPtr<IToastNotification> mNotification;
ComPtr<IToastNotifier> mNotifier;
HSTRING mTitle;
HSTRING mMessage;
wchar_t* mName;
DWORD mThreadId;
EventCallback mActivateCallback;
EventCallback mDismissCallback;
};
ToastNotificationHandler::~ToastNotificationHandler()
{
std::vector<ToastNotificationHandler*>::iterator iter = sNotifications.begin();
while (sNotifications.end() != iter) {
if (*iter == this) {
sNotifications.erase(iter);
break;
}
iter++;
}
if (mTitle) {
WindowsDeleteString(mTitle);
}
if (mMessage) {
WindowsDeleteString(mMessage);
}
if (mName) {
free(mName);
}
}
bool
ToastNotificationHandler::Init(const wchar_t* aTitle, const wchar_t* aMessage, const wchar_t* aName)
{
HRESULT hr;
hr = WindowsCreateString(aTitle, (UINT32)wcslen(aTitle), &mTitle);
if (FAILED(hr)) {
return false;
}
hr = WindowsCreateString(aMessage, (UINT32)wcslen(aMessage), &mMessage);
if (FAILED(hr)) {
return false;
}
if (aName) {
mName = _wcsdup(aName);
if (!mName) {
return false;
}
}
mThreadId = GetCurrentThreadId();
return true;
}
static bool
SetNodeValueString(HSTRING inputString, ComPtr<IXmlNode> node, ComPtr<IXmlDocument> xml)
{
ComPtr<IXmlText> inputText;
HRESULT hr;
hr = xml->CreateTextNode(inputString, &inputText);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> inputTextNode;
hr = inputText.As(&inputTextNode);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> appendedChild;
hr = node->AppendChild(inputTextNode.Get(), &appendedChild);
if (FAILED(hr)) {
return false;
}
return true;
}
ComPtr<IXmlDocument>
ToastNotificationHandler::InitializeXmlForTemplate(ToastTemplateType templateType)
{
HRESULT hr;
hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_UI_Notifications_ToastNotificationManager).Get(), mToastNotificationManagerStatics.GetAddressOf());
if (FAILED(hr)) {
return nullptr;
}
ComPtr<IXmlDocument> toastXml;
mToastNotificationManagerStatics->GetTemplateContent(templateType, &toastXml);
return toastXml;
}
bool
ToastNotificationHandler::CreateWindowsNotificationFromXml(IXmlDocument* aXml)
{
ComPtr<IToastNotificationFactory> factory;
HRESULT hr;
hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_UI_Notifications_ToastNotification).Get(), factory.GetAddressOf());
if (FAILED(hr)) {
return false;
}
hr = factory->CreateToastNotification(aXml, &mNotification);
if (FAILED(hr)) {
return false;
}
if (mActivateCallback) {
EventRegistrationToken activatedToken;
hr = mNotification->add_Activated(Callback<ToastActivationHandler>(this, &ToastNotificationHandler::OnActivate).Get(), &activatedToken);
if (FAILED(hr)) {
return false;
}
}
EventRegistrationToken dismissedToken;
hr = mNotification->add_Dismissed(Callback<ToastDismissHandler>(this, &ToastNotificationHandler::OnDismiss).Get(), &dismissedToken);
if (FAILED(hr)) {
return false;
}
hr = mToastNotificationManagerStatics->CreateToastNotifierWithId(HStringReference(sAppId).Get(), mNotifier.GetAddressOf());
if (FAILED(hr)) {
return false;
}
hr = mNotifier->Show(mNotification.Get());
if (FAILED(hr)) {
return false;
}
return true;
}
bool
ToastNotificationHandler::DisplayNotification(EventCallback aActivate, EventCallback aDismiss)
{
ComPtr<IXmlDocument> toastXml = InitializeXmlForTemplate(ToastTemplateType::ToastTemplateType_ToastText03);
HRESULT hr;
ComPtr<IXmlNodeList> toastTextElements;
hr = toastXml->GetElementsByTagName(HStringReference(L"text").Get(), &toastTextElements);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> titleTextNodeRoot;
hr = toastTextElements->Item(0, &titleTextNodeRoot);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> msgTextNodeRoot;
hr = toastTextElements->Item(1, &msgTextNodeRoot);
if (FAILED(hr)) {
return false;
}
SetNodeValueString(mTitle, titleTextNodeRoot.Get(), toastXml.Get());
SetNodeValueString(mMessage, msgTextNodeRoot.Get(), toastXml.Get());
mActivateCallback = aActivate;
mDismissCallback = aDismiss;
return CreateWindowsNotificationFromXml(toastXml.Get());
}
bool
ToastNotificationHandler::CloseNotification()
{
if (mNotifier && mNotification) {
mNotifier->Hide(mNotification.Get());
}
return true;
}
HRESULT
ToastNotificationHandler::OnActivate(IToastNotification* aNotification, IInspectable* aInspectable)
{
if (mThreadId != GetCurrentThreadId()) {
return E_FAIL;
}
if (mActivateCallback) {
mActivateCallback();
}
return S_OK;
}
HRESULT
ToastNotificationHandler::OnDismiss(IToastNotification* aNotification, IToastDismissedEventArgs* aArgs)
{
if (mThreadId != GetCurrentThreadId()) {
return E_FAIL;
}
if (mDismissCallback) {
mDismissCallback();
}
delete this;
return S_OK;
}
extern "C"
bool WINAPI
SetAppId()
{
if (!sAppId) {
WCHAR wszFilename[MAX_PATH];
GetModuleFileNameW(NULL, wszFilename, MAX_PATH);
wchar_t* slash = wcsrchr(wszFilename, '\\');
if (slash) {
*slash = '\0';
}
HKEY key;
if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Mozilla\\Firefox\\TaskBarIDs", 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {
WCHAR value[MAX_PATH];
DWORD type = REG_SZ;
DWORD len = sizeof(value);
if (RegQueryValueExW(key, wszFilename, NULL, &type, (LPBYTE) value, &len) == ERROR_SUCCESS) {
sAppId = _wcsdup(value);
}
RegCloseKey(key);
}
}
return !!sAppId;
}
// external API to show toast notification via JS-CTYPES
extern "C"
bool WINAPI
DisplayToastNotification(const wchar_t* aTitle, const wchar_t* aMessage, const wchar_t* aName, void* aCallbackActive, void* aCallbackDismiss)
{
if (!sAppId) {
return false;
}
ToastNotificationHandler* handler = new ToastNotificationHandler();
if (!handler->Init(aTitle, aMessage, aName)) {
delete handler;
return false;
}
if (!handler->DisplayNotification((EventCallback) aCallbackActive, (EventCallback) aCallbackDismiss)) {
delete handler;
return false;
}
sNotifications.push_back(handler);
return true;
}
extern "C"
bool WINAPI
CloseToastNotification(const wchar_t* aName)
{
if (!aName) {
return false;
}
std::vector<ToastNotificationHandler*>::iterator iter = sNotifications.begin();
while (sNotifications.end() != iter) {
ToastNotificationHandler* handler = *iter;
if (handler) {
if (!wcscmp(handler->GetName(), aName)) {
sNotifications.erase(iter);
handler->CloseNotification();
delete handler;
return true;
}
}
iter++;
}
return false;
}
Change logic of remove handler
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <windows.ui.notifications.h>
#include <windows.data.xml.dom.h>
#include <wrl.h>
#include <wchar.h>
#include <vector>
#pragma comment(lib, "delayimp")
#pragma comment(lib, "runtimeobject")
using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::UI::Notifications;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
class ToastNotificationHandler;
static wchar_t* sAppId = nullptr;
static std::vector<ToastNotificationHandler*> sNotifications;
typedef bool (STDAPICALLTYPE *EventCallback)();
class ToastNotificationHandler {
typedef ABI::Windows::UI::Notifications::IToastNotification IToastNotification;
typedef ABI::Windows::UI::Notifications::IToastDismissedEventArgs IToastDismissedEventArgs;
typedef ABI::Windows::UI::Notifications::IToastNotificationManagerStatics IToastNotificationManagerStatics;
typedef ABI::Windows::UI::Notifications::ToastTemplateType ToastTemplateType;
typedef ABI::Windows::Data::Xml::Dom::IXmlNode IXmlNode;
typedef ABI::Windows::Data::Xml::Dom::IXmlDocument IXmlDocument;
typedef __FITypedEventHandler_2_Windows__CUI__CNotifications__CToastNotification_IInspectable_t ToastActivationHandler;
typedef __FITypedEventHandler_2_Windows__CUI__CNotifications__CToastNotification_Windows__CUI__CNotifications__CToastDismissedEventArgs ToastDismissHandler;
public:
ToastNotificationHandler() : mTitle(nullptr), mMessage(nullptr), mName(nullptr), mActivateCallback(nullptr), mDismissCallback(nullptr)
{
}
~ToastNotificationHandler();
bool Init(const wchar_t* aTitle, const wchar_t* aMessage, const wchar_t* aName);
bool DisplayNotification(EventCallback aActivate, EventCallback aDismiss);
bool CloseNotification();
const wchar_t* GetName() const { return mName; }
private:
ComPtr<IXmlDocument> ToastNotificationHandler::InitializeXmlForTemplate(ToastTemplateType templateType);
bool CreateWindowsNotificationFromXml(IXmlDocument* aXml);
HRESULT OnActivate(IToastNotification* aNotification, IInspectable* aInspectable);
HRESULT OnDismiss(IToastNotification* aNotification, IToastDismissedEventArgs* aInspectable);
ComPtr<IToastNotificationManagerStatics> mToastNotificationManagerStatics;
ComPtr<IToastNotification> mNotification;
ComPtr<IToastNotifier> mNotifier;
HSTRING mTitle;
HSTRING mMessage;
wchar_t* mName;
DWORD mThreadId;
EventCallback mActivateCallback;
EventCallback mDismissCallback;
};
ToastNotificationHandler::~ToastNotificationHandler()
{
if (mTitle) {
WindowsDeleteString(mTitle);
}
if (mMessage) {
WindowsDeleteString(mMessage);
}
if (mName) {
free(mName);
}
}
bool
ToastNotificationHandler::Init(const wchar_t* aTitle, const wchar_t* aMessage, const wchar_t* aName)
{
HRESULT hr;
hr = WindowsCreateString(aTitle, static_cast<UINT32>(wcslen(aTitle)), &mTitle);
if (FAILED(hr)) {
return false;
}
hr = WindowsCreateString(aMessage, static_cast<UINT32>(wcslen(aMessage)), &mMessage);
if (FAILED(hr)) {
return false;
}
if (aName) {
mName = _wcsdup(aName);
if (!mName) {
return false;
}
}
mThreadId = GetCurrentThreadId();
return true;
}
static bool
SetNodeValueString(HSTRING inputString, ComPtr<IXmlNode> node, ComPtr<IXmlDocument> xml)
{
ComPtr<IXmlText> inputText;
HRESULT hr;
hr = xml->CreateTextNode(inputString, &inputText);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> inputTextNode;
hr = inputText.As(&inputTextNode);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> appendedChild;
hr = node->AppendChild(inputTextNode.Get(), &appendedChild);
if (FAILED(hr)) {
return false;
}
return true;
}
ComPtr<IXmlDocument>
ToastNotificationHandler::InitializeXmlForTemplate(ToastTemplateType templateType)
{
HRESULT hr;
hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_UI_Notifications_ToastNotificationManager).Get(),
mToastNotificationManagerStatics.GetAddressOf());
if (FAILED(hr)) {
return nullptr;
}
ComPtr<IXmlDocument> toastXml;
mToastNotificationManagerStatics->GetTemplateContent(templateType, &toastXml);
return toastXml;
}
bool
ToastNotificationHandler::CreateWindowsNotificationFromXml(IXmlDocument* aXml)
{
ComPtr<IToastNotificationFactory> factory;
HRESULT hr;
hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_UI_Notifications_ToastNotification).Get(),
factory.GetAddressOf());
if (FAILED(hr)) {
return false;
}
hr = factory->CreateToastNotification(aXml, &mNotification);
if (FAILED(hr)) {
return false;
}
if (mActivateCallback) {
EventRegistrationToken activatedToken;
hr = mNotification->add_Activated(
Callback<ToastActivationHandler>(this, &ToastNotificationHandler::OnActivate).Get(),
&activatedToken);
if (FAILED(hr)) {
return false;
}
}
EventRegistrationToken dismissedToken;
hr = mNotification->add_Dismissed(
Callback<ToastDismissHandler>(this, &ToastNotificationHandler::OnDismiss).Get(),
&dismissedToken);
if (FAILED(hr)) {
return false;
}
hr = mToastNotificationManagerStatics->CreateToastNotifierWithId(
HStringReference(sAppId).Get(),
mNotifier.GetAddressOf());
if (FAILED(hr)) {
return false;
}
hr = mNotifier->Show(mNotification.Get());
if (FAILED(hr)) {
return false;
}
return true;
}
bool
ToastNotificationHandler::DisplayNotification(EventCallback aActivate, EventCallback aDismiss)
{
ComPtr<IXmlDocument> toastXml = InitializeXmlForTemplate(ToastTemplateType::ToastTemplateType_ToastText03);
HRESULT hr;
ComPtr<IXmlNodeList> toastTextElements;
hr = toastXml->GetElementsByTagName(HStringReference(L"text").Get(), &toastTextElements);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> titleTextNodeRoot;
hr = toastTextElements->Item(0, &titleTextNodeRoot);
if (FAILED(hr)) {
return false;
}
ComPtr<IXmlNode> msgTextNodeRoot;
hr = toastTextElements->Item(1, &msgTextNodeRoot);
if (FAILED(hr)) {
return false;
}
SetNodeValueString(mTitle, titleTextNodeRoot.Get(), toastXml.Get());
SetNodeValueString(mMessage, msgTextNodeRoot.Get(), toastXml.Get());
mActivateCallback = aActivate;
mDismissCallback = aDismiss;
return CreateWindowsNotificationFromXml(toastXml.Get());
}
bool
ToastNotificationHandler::CloseNotification()
{
if (mNotifier && mNotification) {
mNotifier->Hide(mNotification.Get());
}
return true;
}
HRESULT
ToastNotificationHandler::OnActivate(IToastNotification* aNotification, IInspectable* aInspectable)
{
if (mThreadId != GetCurrentThreadId()) {
return E_FAIL;
}
if (mActivateCallback) {
mActivateCallback();
}
return S_OK;
}
HRESULT
ToastNotificationHandler::OnDismiss(IToastNotification* aNotification, IToastDismissedEventArgs* aArgs)
{
if (mThreadId != GetCurrentThreadId()) {
return E_FAIL;
}
if (mDismissCallback) {
mDismissCallback();
}
auto iter = sNotifications.begin();
while (sNotifications.end() != iter) {
if (*iter == this) {
sNotifications.erase(iter);
break;
}
iter++;
}
delete this;
return S_OK;
}
extern "C"
bool WINAPI
SetAppId()
{
// If having -no-remote option, Firefox doesn't start DDE.
if (_wgetenv(L"MOZ_NO_REMOTE")) {
return false;
}
if (!sAppId) {
WCHAR wszFilename[MAX_PATH];
GetModuleFileNameW(NULL, wszFilename, MAX_PATH);
wchar_t* slash = wcsrchr(wszFilename, '\\');
if (slash) {
*slash = '\0';
}
HKEY key;
if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Mozilla\\Firefox\\TaskBarIDs", 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {
WCHAR value[MAX_PATH];
DWORD type = REG_SZ;
DWORD len = sizeof(value);
if (RegQueryValueExW(key, wszFilename, NULL, &type, (LPBYTE) value, &len) == ERROR_SUCCESS) {
sAppId = _wcsdup(value);
}
RegCloseKey(key);
}
}
return !!sAppId;
}
// external API to show toast notification via JS-CTYPES
extern "C"
bool WINAPI
DisplayToastNotification(const wchar_t* aTitle, const wchar_t* aMessage, const wchar_t* aName, void* aCallbackActive, void* aCallbackDismiss)
{
if (!sAppId) {
return false;
}
ToastNotificationHandler* handler = new ToastNotificationHandler();
if (!handler->Init(aTitle, aMessage, aName)) {
delete handler;
return false;
}
if (!handler->DisplayNotification((EventCallback) aCallbackActive, (EventCallback) aCallbackDismiss)) {
delete handler;
return false;
}
sNotifications.push_back(handler);
return true;
}
extern "C"
bool WINAPI
CloseToastNotification(const wchar_t* aName)
{
if (!aName || !*aName) {
return false;
}
auto iter = sNotifications.begin();
while (sNotifications.end() != iter) {
ToastNotificationHandler* handler = *iter;
if (handler) {
if (!wcscmp(handler->GetName(), aName)) {
handler->CloseNotification();
return true;
}
}
iter++;
}
return false;
}
|
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// StochasticTools includes
#include "SamplerTransientMultiApp.h"
#include "Sampler.h"
#include "StochasticToolsTransfer.h"
registerMooseObject("StochasticToolsApp", SamplerTransientMultiApp);
InputParameters
SamplerTransientMultiApp::validParams()
{
InputParameters params = TransientMultiApp::validParams();
params += SamplerInterface::validParams();
params.addClassDescription("Creates a sub-application for each row of each Sampler matrix.");
params.addParam<SamplerName>("sampler", "The Sampler object to utilize for creating MultiApps.");
params.suppressParameter<std::vector<Point>>("positions");
params.suppressParameter<bool>("output_in_position");
params.suppressParameter<std::vector<FileName>>("positions_file");
params.suppressParameter<Real>("move_time");
params.suppressParameter<std::vector<Point>>("move_positions");
params.suppressParameter<std::vector<unsigned int>>("move_apps");
params.set<bool>("use_positions") = false;
// use "batch-restore=2" to be consistent with SamplerFullSolveMultiApp and use the
// allow_out_of_range flag to allow the StochasticToolsTransfer object to inspect the MultiApp
// object parameters without triggering an assert.
MooseEnum modes("normal=0 batch-reset=1 batch-restore=2", "normal");
params.addParam<MooseEnum>(
"mode",
modes,
"The operation mode, 'normal' creates one sub-application for each row in the Sampler and "
"'batch' creates on sub-application for each processor and re-executes for each row.");
return params;
}
SamplerTransientMultiApp::SamplerTransientMultiApp(const InputParameters & parameters)
: TransientMultiApp(parameters),
SamplerInterface(this),
_sampler(SamplerInterface::getSampler("sampler")),
_mode(getParam<MooseEnum>("mode").getEnum<StochasticTools::MultiAppMode>()),
_number_of_sampler_rows(_sampler.getNumberOfRows()),
_perf_solve_step(registerTimedSection("solveStep", 1)),
_perf_solve_batch_step(registerTimedSection("solveStepBatch", 1)),
_perf_initial_setup(registerTimedSection("initialSetup", 2))
{
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
{
if (n_processors() > _sampler.getNumberOfRows())
paramError(
"mode",
"There appears to be more available processors (",
n_processors(),
") than samples (",
_sampler.getNumberOfRows(),
"), this is not supported in "
"batch mode. Consider switching to \'normal\' to allow multiple processors per sample.");
init(n_processors());
}
else if (_mode == StochasticTools::MultiAppMode::NORMAL)
init(_sampler.getNumberOfRows());
else
paramError("mode",
"The supplied mode, '",
getParam<MooseEnum>("mode"),
"', currently is not implemented for the SamplerTransientMultiApp, the available "
"options are 'normal' or 'batch-restore'.");
}
void
SamplerTransientMultiApp::initialSetup()
{
TIME_SECTION(_perf_initial_setup);
TransientMultiApp::initialSetup();
// Perform initial backup for the batch sub-applications
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
{
dof_id_type n = _sampler.getNumberOfLocalRows();
_batch_backup.resize(n);
for (MooseIndex(n) i = 0; i < n; ++i)
for (MooseIndex(_my_num_apps) j = 0; j < _my_num_apps; j++)
_batch_backup[i].emplace_back(_apps[j]->backup());
}
}
bool
SamplerTransientMultiApp::solveStep(Real dt, Real target_time, bool auto_advance)
{
TIME_SECTION(_perf_solve_step);
if (_sampler.getNumberOfRows() != _number_of_sampler_rows)
mooseError("The size of the sampler has changed; SamplerTransientMultiApp object do not "
"support dynamic Sampler output.");
bool last_solve_converged = true;
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
last_solve_converged = solveStepBatch(dt, target_time, auto_advance);
else
last_solve_converged = TransientMultiApp::solveStep(dt, target_time, auto_advance);
return last_solve_converged;
}
bool
SamplerTransientMultiApp::solveStepBatch(Real dt, Real target_time, bool auto_advance)
{
TIME_SECTION(_perf_solve_batch_step);
// Value to return
bool last_solve_converged = true;
// List of active relevant Transfer objects
std::vector<std::shared_ptr<StochasticToolsTransfer>> to_transfers =
getActiveStochasticToolsTransfers(MultiAppTransfer::TO_MULTIAPP);
std::vector<std::shared_ptr<StochasticToolsTransfer>> from_transfers =
getActiveStochasticToolsTransfers(MultiAppTransfer::FROM_MULTIAPP);
// Initialize to/from transfers
for (auto transfer : to_transfers)
transfer->initializeToMultiapp();
for (auto transfer : from_transfers)
transfer->initializeFromMultiapp();
// Perform batch MultiApp solves
dof_id_type num_items = _sampler.getNumberOfLocalRows();
for (MooseIndex(num_items) i = 0; i < num_items; ++i)
{
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
for (MooseIndex(_my_num_apps) j = 0; j < _my_num_apps; j++)
_apps[j]->restore(_batch_backup[i][j]);
for (auto transfer : to_transfers)
transfer->executeToMultiapp();
last_solve_converged = TransientMultiApp::solveStep(dt, target_time, auto_advance);
for (auto transfer : from_transfers)
transfer->executeFromMultiapp();
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
for (MooseIndex(_my_num_apps) j = 0; j < _my_num_apps; j++)
_batch_backup[i][j] = _apps[j]->backup();
}
// Finalize to/from transfers
for (auto transfer : to_transfers)
transfer->finalizeToMultiapp();
for (auto transfer : from_transfers)
transfer->finalizeFromMultiapp();
return last_solve_converged;
}
std::vector<std::shared_ptr<StochasticToolsTransfer>>
SamplerTransientMultiApp::getActiveStochasticToolsTransfers(Transfer::DIRECTION direction)
{
std::vector<std::shared_ptr<StochasticToolsTransfer>> output;
const ExecuteMooseObjectWarehouse<Transfer> & warehouse =
_fe_problem.getMultiAppTransferWarehouse(direction);
for (std::shared_ptr<Transfer> transfer : warehouse.getActiveObjects())
{
std::shared_ptr<StochasticToolsTransfer> ptr =
std::dynamic_pointer_cast<StochasticToolsTransfer>(transfer);
if (ptr && ptr->getMultiApp()->name() == this->name())
output.push_back(ptr);
}
return output;
}
Update modules/stochastic_tools/src/multiapps/SamplerTransientMultiApp.C
Co-authored-by: Logan Harbour <5e4f14c6ecc988d6c96b41b909ba6662bd5cbfac@gmail.com>
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// StochasticTools includes
#include "SamplerTransientMultiApp.h"
#include "Sampler.h"
#include "StochasticToolsTransfer.h"
registerMooseObject("StochasticToolsApp", SamplerTransientMultiApp);
InputParameters
SamplerTransientMultiApp::validParams()
{
InputParameters params = TransientMultiApp::validParams();
params += SamplerInterface::validParams();
params.addClassDescription("Creates a sub-application for each row of each Sampler matrix.");
params.addParam<SamplerName>("sampler", "The Sampler object to utilize for creating MultiApps.");
params.suppressParameter<std::vector<Point>>("positions");
params.suppressParameter<bool>("output_in_position");
params.suppressParameter<std::vector<FileName>>("positions_file");
params.suppressParameter<Real>("move_time");
params.suppressParameter<std::vector<Point>>("move_positions");
params.suppressParameter<std::vector<unsigned int>>("move_apps");
params.set<bool>("use_positions") = false;
// use "batch-restore=2" to be consistent with SamplerFullSolveMultiApp and use the
// allow_out_of_range flag to allow the StochasticToolsTransfer object to inspect the MultiApp
// object parameters without triggering an assert.
MooseEnum modes("normal=0 batch-reset=1 batch-restore=2", "normal");
params.addParam<MooseEnum>(
"mode",
modes,
"The operation mode, 'normal' creates one sub-application for each row in the Sampler and "
"'batch' creates on sub-application for each processor and re-executes for each row.");
return params;
}
SamplerTransientMultiApp::SamplerTransientMultiApp(const InputParameters & parameters)
: TransientMultiApp(parameters),
SamplerInterface(this),
_sampler(SamplerInterface::getSampler("sampler")),
_mode(getParam<MooseEnum>("mode").getEnum<StochasticTools::MultiAppMode>()),
_number_of_sampler_rows(_sampler.getNumberOfRows()),
_perf_solve_step(registerTimedSection("solveStep", 1)),
_perf_solve_batch_step(registerTimedSection("solveStepBatch", 1)),
_perf_initial_setup(registerTimedSection("initialSetup", 2))
{
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
{
if (n_processors() > _sampler.getNumberOfRows())
paramError(
"mode",
"There appears to be more available processors (",
n_processors(),
") than samples (",
_sampler.getNumberOfRows(),
"), this is not supported in "
"batch mode. Consider switching to \'normal\' to allow multiple processors per sample.");
init(n_processors());
}
else if (_mode == StochasticTools::MultiAppMode::NORMAL)
init(_sampler.getNumberOfRows());
else
paramError("mode",
"The supplied mode, '",
getParam<MooseEnum>("mode"),
"', currently is not implemented for the SamplerTransientMultiApp, the available "
"options are 'normal' or 'batch-restore'.");
}
void
SamplerTransientMultiApp::initialSetup()
{
TIME_SECTION(_perf_initial_setup);
TransientMultiApp::initialSetup();
// Perform initial backup for the batch sub-applications
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
{
dof_id_type n = _sampler.getNumberOfLocalRows();
_batch_backup.resize(n);
for (MooseIndex(n) i = 0; i < n; ++i)
for (MooseIndex(_my_num_apps) j = 0; j < _my_num_apps; j++)
_batch_backup[i].emplace_back(_apps[j]->backup());
}
}
bool
SamplerTransientMultiApp::solveStep(Real dt, Real target_time, bool auto_advance)
{
TIME_SECTION(_perf_solve_step);
if (_sampler.getNumberOfRows() != _number_of_sampler_rows)
mooseError("The size of the sampler has changed; SamplerTransientMultiApp object do not "
"support dynamic Sampler output.");
bool last_solve_converged = true;
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
last_solve_converged = solveStepBatch(dt, target_time, auto_advance);
else
last_solve_converged = TransientMultiApp::solveStep(dt, target_time, auto_advance);
return last_solve_converged;
}
bool
SamplerTransientMultiApp::solveStepBatch(Real dt, Real target_time, bool auto_advance)
{
TIME_SECTION(_perf_solve_batch_step);
// Value to return
bool last_solve_converged = true;
// List of active relevant Transfer objects
std::vector<std::shared_ptr<StochasticToolsTransfer>> to_transfers =
getActiveStochasticToolsTransfers(MultiAppTransfer::TO_MULTIAPP);
std::vector<std::shared_ptr<StochasticToolsTransfer>> from_transfers =
getActiveStochasticToolsTransfers(MultiAppTransfer::FROM_MULTIAPP);
// Initialize to/from transfers
for (auto transfer : to_transfers)
transfer->initializeToMultiapp();
for (auto transfer : from_transfers)
transfer->initializeFromMultiapp();
// Perform batch MultiApp solves
dof_id_type num_items = _sampler.getNumberOfLocalRows();
for (MooseIndex(num_items) i = 0; i < num_items; ++i)
{
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
for (MooseIndex(_my_num_apps) j = 0; j < _my_num_apps; j++)
_apps[j]->restore(_batch_backup[i][j]);
for (auto transfer : to_transfers)
transfer->executeToMultiapp();
last_solve_converged = TransientMultiApp::solveStep(dt, target_time, auto_advance);
for (auto transfer : from_transfers)
transfer->executeFromMultiapp();
if (_mode == StochasticTools::MultiAppMode::BATCH_RESTORE)
for (MooseIndex(_my_num_apps) j = 0; j < _my_num_apps; j++)
_batch_backup[i][j] = _apps[j]->backup();
}
// Finalize to/from transfers
for (auto transfer : to_transfers)
transfer->finalizeToMultiapp();
for (auto transfer : from_transfers)
transfer->finalizeFromMultiapp();
return last_solve_converged;
}
std::vector<std::shared_ptr<StochasticToolsTransfer>>
SamplerTransientMultiApp::getActiveStochasticToolsTransfers(Transfer::DIRECTION direction)
{
std::vector<std::shared_ptr<StochasticToolsTransfer>> output;
const ExecuteMooseObjectWarehouse<Transfer> & warehouse =
_fe_problem.getMultiAppTransferWarehouse(direction);
for (std::shared_ptr<Transfer> transfer : warehouse.getActiveObjects())
{
std::shared_ptr<StochasticToolsTransfer> ptr =
std::dynamic_pointer_cast<StochasticToolsTransfer>(transfer);
if (ptr && ptr->getMultiApp().get() == this)
output.push_back(ptr);
}
return output;
}
|
/*
Copyright (c) 2010 Michael Jansen <kde@michael-jansen>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "notificationsource.h"
#include <akdebug.h>
#include "notificationsourceadaptor.h"
#include "notificationmanager.h"
#include "collectionreferencemanager.h"
#include <libs/notificationmessagev2_p_p.h>
using namespace Akonadi;
using namespace Akonadi::Server;
template<typename T>
QVector<T> setToVector( const QSet<T> &set )
{
QVector<T> v( set.size() );
std::copy( set.constBegin(), set.constEnd(), v.begin() );
return v;
}
NotificationSource::NotificationSource( const QString &identifier, const QString &clientServiceName, NotificationManager *parent )
: QObject( parent )
, mManager( parent )
, mIdentifier( identifier )
, mDBusIdentifier( identifier )
, mClientWatcher( 0 )
, mServerSideMonitorEnabled( false )
, mAllMonitored( false )
, mExclusive( false )
{
new NotificationSourceAdaptor( this );
// Clean up for dbus usage: any non-alphanumeric char should be turned into '_'
const int len = mDBusIdentifier.length();
for ( int i = 0; i < len; ++i ) {
if ( !mDBusIdentifier[i].isLetterOrNumber() ) {
mDBusIdentifier[i] = QLatin1Char( '_' );
}
}
QDBusConnection::sessionBus().registerObject(
dbusPath().path(),
this,
QDBusConnection::ExportAdaptors );
mClientWatcher = new QDBusServiceWatcher( clientServiceName, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this );
connect( mClientWatcher, SIGNAL(serviceUnregistered(QString)), SLOT(serviceUnregistered(QString)) );
}
NotificationSource::~NotificationSource()
{
}
QDBusObjectPath NotificationSource::dbusPath() const
{
return QDBusObjectPath( QLatin1String( "/subscriber/" ) + mDBusIdentifier );
}
void NotificationSource::emitNotification( const NotificationMessage::List ¬ifications )
{
Q_EMIT notify( notifications );
}
void NotificationSource::emitNotification( const NotificationMessageV2::List ¬ifications )
{
Q_EMIT notifyV2( notifications );
}
void NotificationSource::emitNotification( const NotificationMessageV3::List ¬ifications )
{
Q_EMIT notifyV3( notifications );
}
QString NotificationSource::identifier() const
{
return mIdentifier;
}
void NotificationSource::unsubscribe()
{
mManager->unsubscribe( mIdentifier );
}
bool NotificationSource::isServerSideMonitorEnabled() const
{
return mServerSideMonitorEnabled;
}
void NotificationSource::setServerSideMonitorEnabled( bool enabled )
{
mServerSideMonitorEnabled = enabled;
}
bool NotificationSource::isExclusive() const
{
return mExclusive;
}
void NotificationSource::setExclusive( bool enabled )
{
mExclusive = enabled;
}
void NotificationSource::addClientServiceName( const QString &clientServiceName )
{
if ( mClientWatcher->watchedServices().contains( clientServiceName ) ) {
return;
}
mClientWatcher->addWatchedService( clientServiceName );
akDebug() << Q_FUNC_INFO << "Notification source" << mIdentifier << "now serving:" << mClientWatcher->watchedServices();
}
void NotificationSource::serviceUnregistered( const QString &serviceName )
{
mClientWatcher->removeWatchedService( serviceName );
akDebug() << Q_FUNC_INFO << "Notification source" << mIdentifier << "now serving:" << mClientWatcher->watchedServices();
if ( mClientWatcher->watchedServices().isEmpty() ) {
unsubscribe();
}
}
void NotificationSource::setMonitoredCollection( Entity::Id id, bool monitored )
{
if ( id < 0 || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredCollections.contains( id ) ) {
mMonitoredCollections.insert( id );
Q_EMIT monitoredCollectionsChanged();
} else if ( !monitored ) {
mMonitoredCollections.remove( id );
Q_EMIT monitoredCollectionsChanged();
}
}
QVector<Entity::Id> NotificationSource::monitoredCollections() const
{
return setToVector<Entity::Id>( mMonitoredCollections );
}
void NotificationSource::setMonitoredItem( Entity::Id id, bool monitored )
{
if ( id < 0 || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredItems.contains( id ) ) {
mMonitoredItems.insert( id );
Q_EMIT monitoredItemsChanged();
} else if ( !monitored ) {
mMonitoredItems.remove( id );
Q_EMIT monitoredItemsChanged();
}
}
QVector<Entity::Id> NotificationSource::monitoredItems() const
{
return setToVector<Entity::Id>( mMonitoredItems );
}
void NotificationSource::setMonitoredTag( Entity::Id id, bool monitored )
{
if ( id < 0 || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredTags.contains( id ) ) {
mMonitoredTags.insert( id );
Q_EMIT monitoredTagsChanged();
} else if ( !monitored ) {
mMonitoredTags.remove( id );
Q_EMIT monitoredTagsChanged();
}
}
QVector<Entity::Id> NotificationSource::monitoredTags() const
{
return setToVector<Entity::Id>( mMonitoredTags );
}
void NotificationSource::setMonitoredResource( const QByteArray &resource, bool monitored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredResources.contains( resource ) ) {
mMonitoredResources.insert( resource );
Q_EMIT monitoredResourcesChanged();
} else if ( !monitored ) {
mMonitoredResources.remove( resource );
Q_EMIT monitoredResourcesChanged();
}
}
QVector<QByteArray> NotificationSource::monitoredResources() const
{
return setToVector<QByteArray>( mMonitoredResources );
}
void NotificationSource::setMonitoredMimeType( const QString &mimeType, bool monitored )
{
if ( mimeType.isEmpty() || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredMimeTypes.contains( mimeType ) ) {
mMonitoredMimeTypes.insert( mimeType );
Q_EMIT monitoredMimeTypesChanged();
} else if ( !monitored ) {
mMonitoredMimeTypes.remove( mimeType );
Q_EMIT monitoredMimeTypesChanged();
}
}
QStringList NotificationSource::monitoredMimeTypes() const
{
return mMonitoredMimeTypes.toList();
}
void NotificationSource::setAllMonitored( bool allMonitored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( allMonitored && !mAllMonitored ) {
mAllMonitored = true;
Q_EMIT isAllMonitoredChanged();
} else if ( !allMonitored ) {
mAllMonitored = false;
Q_EMIT isAllMonitoredChanged();
}
}
bool NotificationSource::isAllMonitored() const
{
return mAllMonitored;
}
void NotificationSource::setIgnoredSession( const QByteArray &sessionId, bool ignored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( ignored && !mIgnoredSessions.contains( sessionId ) ) {
mIgnoredSessions.insert( sessionId );
Q_EMIT ignoredSessionsChanged();
} else if ( !ignored ) {
mIgnoredSessions.remove( sessionId );
Q_EMIT ignoredSessionsChanged();
}
}
QVector<QByteArray> NotificationSource::ignoredSessions() const
{
return setToVector<QByteArray>( mIgnoredSessions );
}
bool NotificationSource::isCollectionMonitored( Entity::Id id ) const
{
if ( id < 0 ) {
return false;
} else if ( mMonitoredCollections.contains( id ) ) {
return true;
} else if ( mMonitoredCollections.contains( 0 ) ) {
return true;
}
return false;
}
bool NotificationSource::isMimeTypeMonitored( const QString &mimeType ) const
{
return mMonitoredMimeTypes.contains( mimeType );
// FIXME: Handle mimetype aliases
}
bool NotificationSource::isMoveDestinationResourceMonitored( const NotificationMessageV3 &msg ) const
{
if ( msg.operation() != NotificationMessageV2::Move ) {
return false;
}
return mMonitoredResources.contains( msg.destinationResource() );
}
void NotificationSource::setMonitoredType( NotificationMessageV2::Type type, bool monitored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredTypes.contains( type ) ) {
mMonitoredTypes.insert( type );
Q_EMIT monitoredTypesChanged();
} else if ( !monitored ) {
mMonitoredTypes.remove( type );
Q_EMIT monitoredTypesChanged();
}
}
QVector<NotificationMessageV2::Type> NotificationSource::monitoredTypes() const
{
return setToVector<NotificationMessageV2::Type>( mMonitoredTypes );
}
bool NotificationSource::acceptsNotification( const NotificationMessageV3 ¬ification )
{
// session is ignored
if ( mIgnoredSessions.contains( notification.sessionId() ) ) {
return false;
}
if (notification.entities().count() == 0 && notification.type() != NotificationMessageV2::Relations) {
return false;
}
//Only emit notifications for referenced collections if the subscriber is exclusive or monitors the collection
if ( notification.type() == NotificationMessageV2::Collections ) {
// HACK: We need to dispatch notifications about disabled collections to SOME
// agents (that's what we have the exclusive subscription for) - but because
// querying each Collection from database would be expensive, we use the
// metadata hack to transfer this information from NotificationCollector
if ( notification.d->metadata.contains("DISABLED") ) {
// Exclusive subscriber always gets it
if ( mExclusive ) {
return true;
}
// Now let's see if the collection is referenced - then we still might need
// to accept it
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( CollectionReferenceManager::instance()->isReferenced( entity.id ) ) {
return ( mExclusive || isCollectionMonitored( entity.id ) );
}
}
// If the collection is not referenced, monitored or the subscriber is not
// exclusive (i.e. if we got here), then the subscriber does not care about
// this one, so drop it
return false;
}
} else if ( notification.type() == NotificationMessageV2::Items ) {
if ( CollectionReferenceManager::instance()->isReferenced( notification.parentCollection() ) ) {
return ( mExclusive || isCollectionMonitored( notification.parentCollection() ) || isMoveDestinationResourceMonitored( notification ) );
}
}
// user requested everything
if ( mAllMonitored && notification.type() != NotificationMessageV2::InvalidType ) {
return true;
}
switch ( notification.type() ) {
case NotificationMessageV2::InvalidType:
akDebug() << "Received invalid change notification!";
return false;
case NotificationMessageV2::Items:
if ( !mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains( NotificationMessageV2::Items ) ) {
return false;
}
// we have a resource or mimetype filter
if ( !mMonitoredResources.isEmpty() || !mMonitoredMimeTypes.isEmpty() ) {
if ( mMonitoredResources.contains( notification.resource() ) ) {
return true;
}
if ( isMoveDestinationResourceMonitored( notification ) ) {
return true;
}
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( isMimeTypeMonitored( entity.mimeType ) ) {
return true;
}
}
return false;
}
// we explicitly monitor that item or the collections it's in
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( mMonitoredItems.contains( entity.id ) ) {
return true;
}
}
return isCollectionMonitored( notification.parentCollection() )
|| isCollectionMonitored( notification.parentDestCollection() );
case NotificationMessageV2::Collections:
if ( !mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains( NotificationMessageV2::Collections ) ) {
return false;
}
// we have a resource filter
if ( !mMonitoredResources.isEmpty() ) {
const bool resourceMatches = mMonitoredResources.contains( notification.resource() )
|| isMoveDestinationResourceMonitored( notification );
// a bit hacky, but match the behaviour from the item case,
// if resource is the only thing we are filtering on, stop here, and if the resource filter matched, of course
if ( mMonitoredMimeTypes.isEmpty() || resourceMatches ) {
return resourceMatches;
}
// else continue
}
// we explicitly monitor that colleciton, or all of them
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( isCollectionMonitored( entity.id ) ) {
return true;
}
}
return isCollectionMonitored( notification.parentCollection() )
|| isCollectionMonitored( notification.parentDestCollection() );
case NotificationMessageV2::Tags:
if ( !mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains( NotificationMessageV2::Tags ) ) {
return false;
}
if ( mMonitoredTags.isEmpty() ) {
return true;
}
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( mMonitoredTags.contains( entity.id ) ) {
return true;
}
}
return false;
case NotificationMessageV2::Relations:
if (!mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains(NotificationMessageV2::Relations)) {
return false;
}
return true;
}
return false;
}
NotificationSource: Don't drop unsubscribe or enabled notifications
Since the collection is already disabled we require an exception for this.
Otherwise the monitortest doesn't pass.
/*
Copyright (c) 2010 Michael Jansen <kde@michael-jansen>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "notificationsource.h"
#include <akdebug.h>
#include "notificationsourceadaptor.h"
#include "notificationmanager.h"
#include "collectionreferencemanager.h"
#include <libs/notificationmessagev2_p_p.h>
using namespace Akonadi;
using namespace Akonadi::Server;
template<typename T>
QVector<T> setToVector( const QSet<T> &set )
{
QVector<T> v( set.size() );
std::copy( set.constBegin(), set.constEnd(), v.begin() );
return v;
}
NotificationSource::NotificationSource( const QString &identifier, const QString &clientServiceName, NotificationManager *parent )
: QObject( parent )
, mManager( parent )
, mIdentifier( identifier )
, mDBusIdentifier( identifier )
, mClientWatcher( 0 )
, mServerSideMonitorEnabled( false )
, mAllMonitored( false )
, mExclusive( false )
{
new NotificationSourceAdaptor( this );
// Clean up for dbus usage: any non-alphanumeric char should be turned into '_'
const int len = mDBusIdentifier.length();
for ( int i = 0; i < len; ++i ) {
if ( !mDBusIdentifier[i].isLetterOrNumber() ) {
mDBusIdentifier[i] = QLatin1Char( '_' );
}
}
QDBusConnection::sessionBus().registerObject(
dbusPath().path(),
this,
QDBusConnection::ExportAdaptors );
mClientWatcher = new QDBusServiceWatcher( clientServiceName, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this );
connect( mClientWatcher, SIGNAL(serviceUnregistered(QString)), SLOT(serviceUnregistered(QString)) );
}
NotificationSource::~NotificationSource()
{
}
QDBusObjectPath NotificationSource::dbusPath() const
{
return QDBusObjectPath( QLatin1String( "/subscriber/" ) + mDBusIdentifier );
}
void NotificationSource::emitNotification( const NotificationMessage::List ¬ifications )
{
Q_EMIT notify( notifications );
}
void NotificationSource::emitNotification( const NotificationMessageV2::List ¬ifications )
{
Q_EMIT notifyV2( notifications );
}
void NotificationSource::emitNotification( const NotificationMessageV3::List ¬ifications )
{
Q_EMIT notifyV3( notifications );
}
QString NotificationSource::identifier() const
{
return mIdentifier;
}
void NotificationSource::unsubscribe()
{
mManager->unsubscribe( mIdentifier );
}
bool NotificationSource::isServerSideMonitorEnabled() const
{
return mServerSideMonitorEnabled;
}
void NotificationSource::setServerSideMonitorEnabled( bool enabled )
{
mServerSideMonitorEnabled = enabled;
}
bool NotificationSource::isExclusive() const
{
return mExclusive;
}
void NotificationSource::setExclusive( bool enabled )
{
mExclusive = enabled;
}
void NotificationSource::addClientServiceName( const QString &clientServiceName )
{
if ( mClientWatcher->watchedServices().contains( clientServiceName ) ) {
return;
}
mClientWatcher->addWatchedService( clientServiceName );
akDebug() << Q_FUNC_INFO << "Notification source" << mIdentifier << "now serving:" << mClientWatcher->watchedServices();
}
void NotificationSource::serviceUnregistered( const QString &serviceName )
{
mClientWatcher->removeWatchedService( serviceName );
akDebug() << Q_FUNC_INFO << "Notification source" << mIdentifier << "now serving:" << mClientWatcher->watchedServices();
if ( mClientWatcher->watchedServices().isEmpty() ) {
unsubscribe();
}
}
void NotificationSource::setMonitoredCollection( Entity::Id id, bool monitored )
{
if ( id < 0 || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredCollections.contains( id ) ) {
mMonitoredCollections.insert( id );
Q_EMIT monitoredCollectionsChanged();
} else if ( !monitored ) {
mMonitoredCollections.remove( id );
Q_EMIT monitoredCollectionsChanged();
}
}
QVector<Entity::Id> NotificationSource::monitoredCollections() const
{
return setToVector<Entity::Id>( mMonitoredCollections );
}
void NotificationSource::setMonitoredItem( Entity::Id id, bool monitored )
{
if ( id < 0 || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredItems.contains( id ) ) {
mMonitoredItems.insert( id );
Q_EMIT monitoredItemsChanged();
} else if ( !monitored ) {
mMonitoredItems.remove( id );
Q_EMIT monitoredItemsChanged();
}
}
QVector<Entity::Id> NotificationSource::monitoredItems() const
{
return setToVector<Entity::Id>( mMonitoredItems );
}
void NotificationSource::setMonitoredTag( Entity::Id id, bool monitored )
{
if ( id < 0 || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredTags.contains( id ) ) {
mMonitoredTags.insert( id );
Q_EMIT monitoredTagsChanged();
} else if ( !monitored ) {
mMonitoredTags.remove( id );
Q_EMIT monitoredTagsChanged();
}
}
QVector<Entity::Id> NotificationSource::monitoredTags() const
{
return setToVector<Entity::Id>( mMonitoredTags );
}
void NotificationSource::setMonitoredResource( const QByteArray &resource, bool monitored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredResources.contains( resource ) ) {
mMonitoredResources.insert( resource );
Q_EMIT monitoredResourcesChanged();
} else if ( !monitored ) {
mMonitoredResources.remove( resource );
Q_EMIT monitoredResourcesChanged();
}
}
QVector<QByteArray> NotificationSource::monitoredResources() const
{
return setToVector<QByteArray>( mMonitoredResources );
}
void NotificationSource::setMonitoredMimeType( const QString &mimeType, bool monitored )
{
if ( mimeType.isEmpty() || !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredMimeTypes.contains( mimeType ) ) {
mMonitoredMimeTypes.insert( mimeType );
Q_EMIT monitoredMimeTypesChanged();
} else if ( !monitored ) {
mMonitoredMimeTypes.remove( mimeType );
Q_EMIT monitoredMimeTypesChanged();
}
}
QStringList NotificationSource::monitoredMimeTypes() const
{
return mMonitoredMimeTypes.toList();
}
void NotificationSource::setAllMonitored( bool allMonitored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( allMonitored && !mAllMonitored ) {
mAllMonitored = true;
Q_EMIT isAllMonitoredChanged();
} else if ( !allMonitored ) {
mAllMonitored = false;
Q_EMIT isAllMonitoredChanged();
}
}
bool NotificationSource::isAllMonitored() const
{
return mAllMonitored;
}
void NotificationSource::setIgnoredSession( const QByteArray &sessionId, bool ignored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( ignored && !mIgnoredSessions.contains( sessionId ) ) {
mIgnoredSessions.insert( sessionId );
Q_EMIT ignoredSessionsChanged();
} else if ( !ignored ) {
mIgnoredSessions.remove( sessionId );
Q_EMIT ignoredSessionsChanged();
}
}
QVector<QByteArray> NotificationSource::ignoredSessions() const
{
return setToVector<QByteArray>( mIgnoredSessions );
}
bool NotificationSource::isCollectionMonitored( Entity::Id id ) const
{
if ( id < 0 ) {
return false;
} else if ( mMonitoredCollections.contains( id ) ) {
return true;
} else if ( mMonitoredCollections.contains( 0 ) ) {
return true;
}
return false;
}
bool NotificationSource::isMimeTypeMonitored( const QString &mimeType ) const
{
return mMonitoredMimeTypes.contains( mimeType );
// FIXME: Handle mimetype aliases
}
bool NotificationSource::isMoveDestinationResourceMonitored( const NotificationMessageV3 &msg ) const
{
if ( msg.operation() != NotificationMessageV2::Move ) {
return false;
}
return mMonitoredResources.contains( msg.destinationResource() );
}
void NotificationSource::setMonitoredType( NotificationMessageV2::Type type, bool monitored )
{
if ( !isServerSideMonitorEnabled() ) {
return;
}
if ( monitored && !mMonitoredTypes.contains( type ) ) {
mMonitoredTypes.insert( type );
Q_EMIT monitoredTypesChanged();
} else if ( !monitored ) {
mMonitoredTypes.remove( type );
Q_EMIT monitoredTypesChanged();
}
}
QVector<NotificationMessageV2::Type> NotificationSource::monitoredTypes() const
{
return setToVector<NotificationMessageV2::Type>( mMonitoredTypes );
}
bool NotificationSource::acceptsNotification( const NotificationMessageV3 ¬ification )
{
// session is ignored
if ( mIgnoredSessions.contains( notification.sessionId() ) ) {
return false;
}
if (notification.entities().count() == 0 && notification.type() != NotificationMessageV2::Relations) {
return false;
}
//Only emit notifications for referenced collections if the subscriber is exclusive or monitors the collection
if ( notification.type() == NotificationMessageV2::Collections ) {
// HACK: We need to dispatch notifications about disabled collections to SOME
// agents (that's what we have the exclusive subscription for) - but because
// querying each Collection from database would be expensive, we use the
// metadata hack to transfer this information from NotificationCollector
if ( notification.d->metadata.contains("DISABLED") && (notification.operation() != NotificationMessageV2::Unsubscribe) && !notification.itemParts().contains("ENABLED") ) {
// Exclusive subscriber always gets it
if ( mExclusive ) {
return true;
}
// Now let's see if the collection is referenced - then we still might need
// to accept it
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( CollectionReferenceManager::instance()->isReferenced( entity.id ) ) {
return ( mExclusive || isCollectionMonitored( entity.id ) );
}
}
// If the collection is not referenced, monitored or the subscriber is not
// exclusive (i.e. if we got here), then the subscriber does not care about
// this one, so drop it
return false;
}
} else if ( notification.type() == NotificationMessageV2::Items ) {
if ( CollectionReferenceManager::instance()->isReferenced( notification.parentCollection() ) ) {
return ( mExclusive || isCollectionMonitored( notification.parentCollection() ) || isMoveDestinationResourceMonitored( notification ) );
}
}
// user requested everything
if ( mAllMonitored && notification.type() != NotificationMessageV2::InvalidType ) {
return true;
}
switch ( notification.type() ) {
case NotificationMessageV2::InvalidType:
akDebug() << "Received invalid change notification!";
return false;
case NotificationMessageV2::Items:
if ( !mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains( NotificationMessageV2::Items ) ) {
return false;
}
// we have a resource or mimetype filter
if ( !mMonitoredResources.isEmpty() || !mMonitoredMimeTypes.isEmpty() ) {
if ( mMonitoredResources.contains( notification.resource() ) ) {
return true;
}
if ( isMoveDestinationResourceMonitored( notification ) ) {
return true;
}
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( isMimeTypeMonitored( entity.mimeType ) ) {
return true;
}
}
return false;
}
// we explicitly monitor that item or the collections it's in
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( mMonitoredItems.contains( entity.id ) ) {
return true;
}
}
return isCollectionMonitored( notification.parentCollection() )
|| isCollectionMonitored( notification.parentDestCollection() );
case NotificationMessageV2::Collections:
if ( !mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains( NotificationMessageV2::Collections ) ) {
return false;
}
// we have a resource filter
if ( !mMonitoredResources.isEmpty() ) {
const bool resourceMatches = mMonitoredResources.contains( notification.resource() )
|| isMoveDestinationResourceMonitored( notification );
// a bit hacky, but match the behaviour from the item case,
// if resource is the only thing we are filtering on, stop here, and if the resource filter matched, of course
if ( mMonitoredMimeTypes.isEmpty() || resourceMatches ) {
return resourceMatches;
}
// else continue
}
// we explicitly monitor that colleciton, or all of them
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( isCollectionMonitored( entity.id ) ) {
return true;
}
}
return isCollectionMonitored( notification.parentCollection() )
|| isCollectionMonitored( notification.parentDestCollection() );
case NotificationMessageV2::Tags:
if ( !mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains( NotificationMessageV2::Tags ) ) {
return false;
}
if ( mMonitoredTags.isEmpty() ) {
return true;
}
Q_FOREACH ( const NotificationMessageV2::Entity &entity, notification.entities() ) {
if ( mMonitoredTags.contains( entity.id ) ) {
return true;
}
}
return false;
case NotificationMessageV2::Relations:
if (!mMonitoredTypes.isEmpty() && !mMonitoredTypes.contains(NotificationMessageV2::Relations)) {
return false;
}
return true;
}
return false;
}
|
/*
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Native glue for Java class org.conscrypt.NativeCrypto
*/
#define TO_STRING1(x) #x
#define TO_STRING(x) TO_STRING1(x)
#ifndef JNI_JARJAR_PREFIX
#define CONSCRYPT_UNBUNDLED
#define JNI_JARJAR_PREFIX
#endif
#define LOG_TAG "NativeCrypto"
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <jni.h>
#include <openssl/asn1t.h>
#include <openssl/dsa.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include "AsynchronousCloseMonitor.h"
#include "cutils/log.h"
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
#include "NetFd.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#undef WITH_JNI_TRACE
#undef WITH_JNI_TRACE_MD
#undef WITH_JNI_TRACE_DATA
/*
* How to use this for debugging with Wireshark:
*
* 1. Pull lines from logcat to a file that looks like (without quotes):
* "RSA Session-ID:... Master-Key:..." <CR>
* "RSA Session-ID:... Master-Key:..." <CR>
* <etc>
* 2. Start Wireshark
* 3. Go to Edit -> Preferences -> SSL -> (Pre-)Master-Key log and fill in
* the file you put the lines in above.
* 4. Follow the stream that corresponds to the desired "Session-ID" in
* the Server Hello.
*/
#undef WITH_JNI_TRACE_KEYS
#ifdef WITH_JNI_TRACE
#define JNI_TRACE(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__)); \
/*
((void)printf("I/" LOG_TAG "-jni:")); \
((void)printf(__VA_ARGS__)); \
((void)printf("\n"))
*/
#else
#define JNI_TRACE(...) ((void)0)
#endif
#ifdef WITH_JNI_TRACE_MD
#define JNI_TRACE_MD(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__));
#else
#define JNI_TRACE_MD(...) ((void)0)
#endif
// don't overwhelm logcat
#define WITH_JNI_TRACE_DATA_CHUNK_SIZE 512
static JavaVM* gJavaVM;
static jclass openSslOutputStreamClass;
static jclass openSslNativeReferenceClass;
static jclass byteArrayClass;
static jclass calendarClass;
static jclass objectClass;
static jclass objectArrayClass;
static jclass integerClass;
static jclass inputStreamClass;
static jclass outputStreamClass;
static jclass stringClass;
static jfieldID openSslNativeReference_context;
static jmethodID calendar_setMethod;
static jmethodID inputStream_readMethod;
static jmethodID integer_valueOfMethod;
static jmethodID openSslInputStream_readLineMethod;
static jmethodID outputStream_writeMethod;
static jmethodID outputStream_flushMethod;
struct OPENSSL_Delete {
void operator()(void* p) const {
OPENSSL_free(p);
}
};
typedef UniquePtr<unsigned char, OPENSSL_Delete> Unique_OPENSSL_str;
struct BIO_Delete {
void operator()(BIO* p) const {
BIO_free_all(p);
}
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
struct BIGNUM_Delete {
void operator()(BIGNUM* p) const {
BN_free(p);
}
};
typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
struct ASN1_INTEGER_Delete {
void operator()(ASN1_INTEGER* p) const {
ASN1_INTEGER_free(p);
}
};
typedef UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> Unique_ASN1_INTEGER;
struct DH_Delete {
void operator()(DH* p) const {
DH_free(p);
}
};
typedef UniquePtr<DH, DH_Delete> Unique_DH;
struct DSA_Delete {
void operator()(DSA* p) const {
DSA_free(p);
}
};
typedef UniquePtr<DSA, DSA_Delete> Unique_DSA;
struct EC_GROUP_Delete {
void operator()(EC_GROUP* p) const {
EC_GROUP_clear_free(p);
}
};
typedef UniquePtr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP;
struct EC_POINT_Delete {
void operator()(EC_POINT* p) const {
EC_POINT_clear_free(p);
}
};
typedef UniquePtr<EC_POINT, EC_POINT_Delete> Unique_EC_POINT;
struct EC_KEY_Delete {
void operator()(EC_KEY* p) const {
EC_KEY_free(p);
}
};
typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
struct EVP_MD_CTX_Delete {
void operator()(EVP_MD_CTX* p) const {
EVP_MD_CTX_destroy(p);
}
};
typedef UniquePtr<EVP_MD_CTX, EVP_MD_CTX_Delete> Unique_EVP_MD_CTX;
struct EVP_CIPHER_CTX_Delete {
void operator()(EVP_CIPHER_CTX* p) const {
EVP_CIPHER_CTX_free(p);
}
};
typedef UniquePtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_Delete> Unique_EVP_CIPHER_CTX;
struct EVP_PKEY_Delete {
void operator()(EVP_PKEY* p) const {
EVP_PKEY_free(p);
}
};
typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
struct PKCS8_PRIV_KEY_INFO_Delete {
void operator()(PKCS8_PRIV_KEY_INFO* p) const {
PKCS8_PRIV_KEY_INFO_free(p);
}
};
typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
struct RSA_Delete {
void operator()(RSA* p) const {
RSA_free(p);
}
};
typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
struct ASN1_BIT_STRING_Delete {
void operator()(ASN1_BIT_STRING* p) const {
ASN1_BIT_STRING_free(p);
}
};
typedef UniquePtr<ASN1_BIT_STRING, ASN1_BIT_STRING_Delete> Unique_ASN1_BIT_STRING;
struct ASN1_OBJECT_Delete {
void operator()(ASN1_OBJECT* p) const {
ASN1_OBJECT_free(p);
}
};
typedef UniquePtr<ASN1_OBJECT, ASN1_OBJECT_Delete> Unique_ASN1_OBJECT;
struct ASN1_GENERALIZEDTIME_Delete {
void operator()(ASN1_GENERALIZEDTIME* p) const {
ASN1_GENERALIZEDTIME_free(p);
}
};
typedef UniquePtr<ASN1_GENERALIZEDTIME, ASN1_GENERALIZEDTIME_Delete> Unique_ASN1_GENERALIZEDTIME;
struct SSL_Delete {
void operator()(SSL* p) const {
SSL_free(p);
}
};
typedef UniquePtr<SSL, SSL_Delete> Unique_SSL;
struct SSL_CTX_Delete {
void operator()(SSL_CTX* p) const {
SSL_CTX_free(p);
}
};
typedef UniquePtr<SSL_CTX, SSL_CTX_Delete> Unique_SSL_CTX;
struct X509_Delete {
void operator()(X509* p) const {
X509_free(p);
}
};
typedef UniquePtr<X509, X509_Delete> Unique_X509;
struct X509_NAME_Delete {
void operator()(X509_NAME* p) const {
X509_NAME_free(p);
}
};
typedef UniquePtr<X509_NAME, X509_NAME_Delete> Unique_X509_NAME;
struct PKCS7_Delete {
void operator()(PKCS7* p) const {
PKCS7_free(p);
}
};
typedef UniquePtr<PKCS7, PKCS7_Delete> Unique_PKCS7;
struct sk_SSL_CIPHER_Delete {
void operator()(STACK_OF(SSL_CIPHER)* p) const {
// We don't own SSL_CIPHER references, so no need for pop_free
sk_SSL_CIPHER_free(p);
}
};
typedef UniquePtr<STACK_OF(SSL_CIPHER), sk_SSL_CIPHER_Delete> Unique_sk_SSL_CIPHER;
struct sk_X509_Delete {
void operator()(STACK_OF(X509)* p) const {
sk_X509_pop_free(p, X509_free);
}
};
typedef UniquePtr<STACK_OF(X509), sk_X509_Delete> Unique_sk_X509;
struct sk_X509_NAME_Delete {
void operator()(STACK_OF(X509_NAME)* p) const {
sk_X509_NAME_pop_free(p, X509_NAME_free);
}
};
typedef UniquePtr<STACK_OF(X509_NAME), sk_X509_NAME_Delete> Unique_sk_X509_NAME;
struct sk_ASN1_OBJECT_Delete {
void operator()(STACK_OF(ASN1_OBJECT)* p) const {
sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
}
};
typedef UniquePtr<STACK_OF(ASN1_OBJECT), sk_ASN1_OBJECT_Delete> Unique_sk_ASN1_OBJECT;
struct sk_GENERAL_NAME_Delete {
void operator()(STACK_OF(GENERAL_NAME)* p) const {
sk_GENERAL_NAME_pop_free(p, GENERAL_NAME_free);
}
};
typedef UniquePtr<STACK_OF(GENERAL_NAME), sk_GENERAL_NAME_Delete> Unique_sk_GENERAL_NAME;
/**
* Many OpenSSL APIs take ownership of an argument on success but don't free the argument
* on failure. This means we need to tell our scoped pointers when we've transferred ownership,
* without triggering a warning by not using the result of release().
*/
#define OWNERSHIP_TRANSFERRED(obj) \
do { typeof (obj.release()) _dummy __attribute__((unused)) = obj.release(); } while(0)
/**
* Frees the SSL error state.
*
* OpenSSL keeps an "error stack" per thread, and given that this code
* can be called from arbitrary threads that we don't keep track of,
* we err on the side of freeing the error state promptly (instead of,
* say, at thread death).
*/
static void freeOpenSslErrorState(void) {
ERR_clear_error();
ERR_remove_state(0);
}
/**
* Throws a OutOfMemoryError with the given string as a message.
*/
static void jniThrowOutOfMemory(JNIEnv* env, const char* message) {
jniThrowException(env, "java/lang/OutOfMemoryError", message);
}
/**
* Throws a BadPaddingException with the given string as a message.
*/
static void throwBadPaddingException(JNIEnv* env, const char* message) {
JNI_TRACE("throwBadPaddingException %s", message);
jniThrowException(env, "javax/crypto/BadPaddingException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwSignatureException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSignatureException %s", message);
jniThrowException(env, "java/security/SignatureException", message);
}
/**
* Throws a InvalidKeyException with the given string as a message.
*/
static void throwInvalidKeyException(JNIEnv* env, const char* message) {
JNI_TRACE("throwInvalidKeyException %s", message);
jniThrowException(env, "java/security/InvalidKeyException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwIllegalBlockSizeException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalBlockSizeException %s", message);
jniThrowException(env, "javax/crypto/IllegalBlockSizeException", message);
}
/**
* Throws a NoSuchAlgorithmException with the given string as a message.
*/
static void throwNoSuchAlgorithmException(JNIEnv* env, const char* message) {
JNI_TRACE("throwUnknownAlgorithmException %s", message);
jniThrowException(env, "java/security/NoSuchAlgorithmException", message);
}
static void throwForAsn1Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case ASN1_R_UNABLE_TO_DECODE_RSA_KEY:
case ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY:
case ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE:
case ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE:
case ASN1_R_WRONG_PUBLIC_KEY_TYPE:
throwInvalidKeyException(env, message);
break;
case ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForEvpError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case EVP_R_BAD_DECRYPT:
throwBadPaddingException(env, message);
break;
case EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case EVP_R_WRONG_FINAL_BLOCK_LENGTH:
throwIllegalBlockSizeException(env, message);
break;
case EVP_R_BAD_KEY_LENGTH:
case EVP_R_BN_DECODE_ERROR:
case EVP_R_BN_PUBKEY_ERROR:
case EVP_R_INVALID_KEY_LENGTH:
case EVP_R_MISSING_PARAMETERS:
case EVP_R_UNSUPPORTED_KEY_SIZE:
case EVP_R_UNSUPPORTED_KEYLENGTH:
throwInvalidKeyException(env, message);
break;
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
throwSignatureException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForRsaError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case RSA_R_BLOCK_TYPE_IS_NOT_01:
case RSA_R_BLOCK_TYPE_IS_NOT_02:
throwBadPaddingException(env, message);
break;
case RSA_R_ALGORITHM_MISMATCH:
case RSA_R_BAD_SIGNATURE:
case RSA_R_DATA_GREATER_THAN_MOD_LEN:
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
case RSA_R_INVALID_MESSAGE_LENGTH:
case RSA_R_WRONG_SIGNATURE_LENGTH:
throwSignatureException(env, message);
break;
case RSA_R_UNKNOWN_ALGORITHM_TYPE:
throwNoSuchAlgorithmException(env, message);
break;
case RSA_R_MODULUS_TOO_LARGE:
case RSA_R_NO_PUBLIC_EXPONENT:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForX509Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case X509_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
/*
* Checks this thread's OpenSSL error queue and throws a RuntimeException if
* necessary.
*
* @return true if an exception was thrown, false if not.
*/
static bool throwExceptionIfNecessary(JNIEnv* env, const char* location __attribute__ ((unused))) {
const char* file;
int line;
const char* data;
int flags;
unsigned long error = ERR_get_error_line_data(&file, &line, &data, &flags);
int result = false;
if (error != 0) {
char message[256];
ERR_error_string_n(error, message, sizeof(message));
int library = ERR_GET_LIB(error);
int reason = ERR_GET_REASON(error);
JNI_TRACE("OpenSSL error in %s error=%lx library=%x reason=%x (%s:%d): %s %s",
location, error, library, reason, file, line, message,
(flags & ERR_TXT_STRING) ? data : "(no data)");
switch (library) {
case ERR_LIB_RSA:
throwForRsaError(env, reason, message);
break;
case ERR_LIB_ASN1:
throwForAsn1Error(env, reason, message);
break;
case ERR_LIB_EVP:
throwForEvpError(env, reason, message);
break;
case ERR_LIB_X509:
throwForX509Error(env, reason, message);
break;
case ERR_LIB_DSA:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
result = true;
}
freeOpenSslErrorState();
return result;
}
/**
* Throws an SocketTimeoutException with the given string as a message.
*/
static void throwSocketTimeoutException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSocketTimeoutException %s", message);
jniThrowException(env, "java/net/SocketTimeoutException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLHandshakeExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLHandshakeException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLException", message);
}
/**
* Throws a javax.net.ssl.SSLProcotolException with the given string as a message.
*/
static void throwSSLProtocolExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLProtocolExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLProtocolException", message);
}
/**
* Throws an SSLException with a message constructed from the current
* SSL errors. This will also log the errors.
*
* @param env the JNI environment
* @param ssl the possibly NULL SSL
* @param sslErrorCode error code returned from SSL_get_error() or
* SSL_ERROR_NONE to probe with ERR_get_error
* @param message null-ok; general error message
*/
static void throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCode,
const char* message, void (*actualThrow)(JNIEnv*, const char*) = throwSSLExceptionStr) {
if (message == NULL) {
message = "SSL error";
}
// First consult the SSL error code for the general message.
const char* sslErrorStr = NULL;
switch (sslErrorCode) {
case SSL_ERROR_NONE:
if (ERR_peek_error() == 0) {
sslErrorStr = "OK";
} else {
sslErrorStr = "";
}
break;
case SSL_ERROR_SSL:
sslErrorStr = "Failure in SSL library, usually a protocol error";
break;
case SSL_ERROR_WANT_READ:
sslErrorStr = "SSL_ERROR_WANT_READ occurred. You should never see this.";
break;
case SSL_ERROR_WANT_WRITE:
sslErrorStr = "SSL_ERROR_WANT_WRITE occurred. You should never see this.";
break;
case SSL_ERROR_WANT_X509_LOOKUP:
sslErrorStr = "SSL_ERROR_WANT_X509_LOOKUP occurred. You should never see this.";
break;
case SSL_ERROR_SYSCALL:
sslErrorStr = "I/O error during system call";
break;
case SSL_ERROR_ZERO_RETURN:
sslErrorStr = "SSL_ERROR_ZERO_RETURN occurred. You should never see this.";
break;
case SSL_ERROR_WANT_CONNECT:
sslErrorStr = "SSL_ERROR_WANT_CONNECT occurred. You should never see this.";
break;
case SSL_ERROR_WANT_ACCEPT:
sslErrorStr = "SSL_ERROR_WANT_ACCEPT occurred. You should never see this.";
break;
default:
sslErrorStr = "Unknown SSL error";
}
// Prepend either our explicit message or a default one.
char* str;
if (asprintf(&str, "%s: ssl=%p: %s", message, ssl, sslErrorStr) <= 0) {
// problem with asprintf, just throw argument message, log everything
actualThrow(env, message);
ALOGV("%s: ssl=%p: %s", message, ssl, sslErrorStr);
freeOpenSslErrorState();
return;
}
char* allocStr = str;
// For protocol errors, SSL might have more information.
if (sslErrorCode == SSL_ERROR_NONE || sslErrorCode == SSL_ERROR_SSL) {
// Append each error as an additional line to the message.
for (;;) {
char errStr[256];
const char* file;
int line;
const char* data;
int flags;
unsigned long err = ERR_get_error_line_data(&file, &line, &data, &flags);
if (err == 0) {
break;
}
ERR_error_string_n(err, errStr, sizeof(errStr));
int ret = asprintf(&str, "%s\n%s (%s:%d %p:0x%08x)",
(allocStr == NULL) ? "" : allocStr,
errStr,
file,
line,
(flags & ERR_TXT_STRING) ? data : "(no data)",
flags);
if (ret < 0) {
break;
}
free(allocStr);
allocStr = str;
}
// For errors during system calls, errno might be our friend.
} else if (sslErrorCode == SSL_ERROR_SYSCALL) {
if (asprintf(&str, "%s, %s", allocStr, strerror(errno)) >= 0) {
free(allocStr);
allocStr = str;
}
// If the error code is invalid, print it.
} else if (sslErrorCode > SSL_ERROR_WANT_ACCEPT) {
if (asprintf(&str, ", error code is %d", sslErrorCode) >= 0) {
free(allocStr);
allocStr = str;
}
}
if (sslErrorCode == SSL_ERROR_SSL) {
throwSSLProtocolExceptionStr(env, allocStr);
} else {
actualThrow(env, allocStr);
}
ALOGV("%s", allocStr);
free(allocStr);
freeOpenSslErrorState();
}
/**
* Helper function that grabs the casts an ssl pointer and then checks for nullness.
* If this function returns NULL and <code>throwIfNull</code> is
* passed as <code>true</code>, then this function will call
* <code>throwSSLExceptionStr</code> before returning, so in this case of
* NULL, a caller of this function should simply return and allow JNI
* to do its thing.
*
* @param env the JNI environment
* @param ssl_address; the ssl_address pointer as an integer
* @param throwIfNull whether to throw if the SSL pointer is NULL
* @returns the pointer, which may be NULL
*/
static SSL_CTX* to_SSL_CTX(JNIEnv* env, jlong ssl_ctx_address, bool throwIfNull) {
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
if ((ssl_ctx == NULL) && throwIfNull) {
JNI_TRACE("ssl_ctx == null");
jniThrowNullPointerException(env, "ssl_ctx == null");
}
return ssl_ctx;
}
static SSL* to_SSL(JNIEnv* env, jlong ssl_address, bool throwIfNull) {
SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
if ((ssl == NULL) && throwIfNull) {
JNI_TRACE("ssl == null");
jniThrowNullPointerException(env, "ssl == null");
}
return ssl;
}
static SSL_SESSION* to_SSL_SESSION(JNIEnv* env, jlong ssl_session_address, bool throwIfNull) {
SSL_SESSION* ssl_session
= reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
if ((ssl_session == NULL) && throwIfNull) {
JNI_TRACE("ssl_session == null");
jniThrowNullPointerException(env, "ssl_session == null");
}
return ssl_session;
}
static SSL_CIPHER* to_SSL_CIPHER(JNIEnv* env, jlong ssl_cipher_address, bool throwIfNull) {
SSL_CIPHER* ssl_cipher
= reinterpret_cast<SSL_CIPHER*>(static_cast<uintptr_t>(ssl_cipher_address));
if ((ssl_cipher == NULL) && throwIfNull) {
JNI_TRACE("ssl_cipher == null");
jniThrowNullPointerException(env, "ssl_cipher == null");
}
return ssl_cipher;
}
template<typename T>
static T* fromContextObject(JNIEnv* env, jobject contextObject) {
T* ref = reinterpret_cast<T*>(env->GetLongField(contextObject, openSslNativeReference_context));
if (ref == NULL) {
JNI_TRACE("ctx == null");
jniThrowNullPointerException(env, "ctx == null");
}
return ref;
}
/**
* Converts a Java byte[] two's complement to an OpenSSL BIGNUM. This will
* allocate the BIGNUM if *dest == NULL. Returns true on success. If the
* return value is false, there is a pending exception.
*/
static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
JNI_TRACE("arrayToBignum(%p, %p)", source, dest);
if (dest == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => dest is null!", source, dest);
jniThrowNullPointerException(env, "dest == null");
return false;
}
JNI_TRACE("arrayToBignum(%p, %p) *dest == %p", source, dest, *dest);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
/* if the array is empty, it is zero. */
if (tmpSize == 0) {
if (*dest == NULL) {
*dest = BN_new();
}
BN_zero(*dest);
return true;
}
UniquePtr<unsigned char[]> twosComplement;
bool negative = (tmp[0] & 0x80) != 0;
if (negative) {
// Need to convert to two's complement.
twosComplement.reset(new unsigned char[tmpSize]);
unsigned char* twosBytes = reinterpret_cast<unsigned char*>(twosComplement.get());
memcpy(twosBytes, tmp, tmpSize);
tmp = twosBytes;
bool carry = true;
for (ssize_t i = tmpSize - 1; i >= 0; i--) {
twosBytes[i] ^= 0xFF;
if (carry) {
carry = (++twosBytes[i]) == 0;
}
}
}
BIGNUM *ret = BN_bin2bn(tmp, tmpSize, *dest);
if (ret == NULL) {
jniThrowRuntimeException(env, "Conversion to BIGNUM failed");
JNI_TRACE("arrayToBignum(%p, %p) => threw exception", source, dest);
return false;
}
BN_set_negative(ret, negative ? 1 : 0);
*dest = ret;
JNI_TRACE("arrayToBignum(%p, %p) => *dest = %p", source, dest, ret);
return true;
}
/**
* Converts an OpenSSL BIGNUM to a Java byte[] array in two's complement.
*/
static jbyteArray bignumToArray(JNIEnv* env, const BIGNUM* source, const char* sourceName) {
JNI_TRACE("bignumToArray(%p, %s)", source, sourceName);
if (source == NULL) {
jniThrowNullPointerException(env, sourceName);
return NULL;
}
size_t numBytes = BN_num_bytes(source) + 1;
jbyteArray javaBytes = env->NewByteArray(numBytes);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bignumToArray(%p, %s) => NULL", source, sourceName);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
if (BN_num_bytes(source) > 0 && BN_bn2bin(source, tmp + 1) <= 0) {
throwExceptionIfNecessary(env, "bignumToArray");
return NULL;
}
// Set the sign and convert to two's complement if necessary for the Java code.
if (BN_is_negative(source)) {
bool carry = true;
for (ssize_t i = numBytes - 1; i >= 0; i--) {
tmp[i] ^= 0xFF;
if (carry) {
carry = (++tmp[i]) == 0;
}
}
*tmp |= 0x80;
} else {
*tmp = 0x00;
}
JNI_TRACE("bignumToArray(%p, %s) => %p", source, sourceName, javaBytes);
return javaBytes;
}
/**
* Converts various OpenSSL ASN.1 types to a jbyteArray with DER-encoded data
* inside. The "i2d_func" function pointer is a function of the "i2d_<TYPE>"
* from the OpenSSL ASN.1 API.
*/
template<typename T, int (*i2d_func)(T*, unsigned char**)>
jbyteArray ASN1ToByteArray(JNIEnv* env, T* obj) {
if (obj == NULL) {
jniThrowNullPointerException(env, "ASN1 input == null");
JNI_TRACE("ASN1ToByteArray(%p) => null input", obj);
return NULL;
}
int derLen = i2d_func(obj, NULL);
if (derLen < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => measurement failed", obj);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => creating byte array failed", obj);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => using byte array failed", obj);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
int ret = i2d_func(obj, &p);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => final conversion failed", obj);
return NULL;
}
JNI_TRACE("ASN1ToByteArray(%p) => success (%d bytes written)", obj, ret);
return byteArray.release();
}
template<typename T, T* (*d2i_func)(T**, const unsigned char**, long)>
T* ByteArrayToASN1(JNIEnv* env, jbyteArray byteArray) {
ScopedByteArrayRO bytes(env, byteArray);
if (bytes.get() == NULL) {
JNI_TRACE("ByteArrayToASN1(%p) => using byte array failed", byteArray);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
return d2i_func(NULL, &tmp, bytes.size());
}
/**
* Converts ASN.1 BIT STRING to a jbooleanArray.
*/
jbooleanArray ASN1BitStringToBooleanArray(JNIEnv* env, ASN1_BIT_STRING* bitStr) {
int size = bitStr->length * 8;
if (bitStr->flags & ASN1_STRING_FLAG_BITS_LEFT) {
size -= bitStr->flags & 0x07;
}
ScopedLocalRef<jbooleanArray> bitsRef(env, env->NewBooleanArray(size));
if (bitsRef.get() == NULL) {
return NULL;
}
ScopedBooleanArrayRW bitsArray(env, bitsRef.get());
for (int i = 0; i < static_cast<int>(bitsArray.size()); i++) {
bitsArray[i] = ASN1_BIT_STRING_get_bit(bitStr, i);
}
return bitsRef.release();
}
/**
* To avoid the round-trip to ASN.1 and back in X509_dup, we just up the reference count.
*/
static X509* X509_dup_nocopy(X509* x509) {
if (x509 == NULL) {
return NULL;
}
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509);
return x509;
}
/*
* Sets the read and write BIO for an SSL connection and removes it when it goes out of scope.
* We hang on to BIO with a JNI GlobalRef and we want to remove them as soon as possible.
*/
class ScopedSslBio {
public:
ScopedSslBio(SSL *ssl, BIO* rbio, BIO* wbio) : ssl_(ssl) {
SSL_set_bio(ssl_, rbio, wbio);
CRYPTO_add(&rbio->references,1,CRYPTO_LOCK_BIO);
CRYPTO_add(&wbio->references,1,CRYPTO_LOCK_BIO);
}
~ScopedSslBio() {
SSL_set_bio(ssl_, NULL, NULL);
}
private:
SSL* const ssl_;
};
/**
* BIO for InputStream
*/
class BIO_Stream {
public:
BIO_Stream(jobject stream) :
mEof(false) {
JNIEnv* env = getEnv();
mStream = env->NewGlobalRef(stream);
}
~BIO_Stream() {
JNIEnv* env = getEnv();
env->DeleteGlobalRef(mStream);
}
bool isEof() const {
JNI_TRACE("isEof? %s", mEof ? "yes" : "no");
return mEof;
}
int flush() {
JNIEnv* env = getEnv();
if (env == NULL) {
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_Stream::flush called with pending exception");
return -1;
}
env->CallVoidMethod(mStream, outputStream_flushMethod);
if (env->ExceptionCheck()) {
return -1;
}
return 1;
}
protected:
jobject getStream() {
return mStream;
}
void setEof(bool eof) {
mEof = eof;
}
JNIEnv* getEnv() {
JNIEnv* env;
if (gJavaVM->AttachCurrentThread(&env, NULL) < 0) {
return NULL;
}
return env;
}
private:
jobject mStream;
bool mEof;
};
class BIO_InputStream : public BIO_Stream {
public:
BIO_InputStream(jobject stream) :
BIO_Stream(stream) {
}
int read(char *buf, int len) {
return read_internal(buf, len, inputStream_readMethod);
}
int gets(char *buf, int len) {
if (len > PEM_LINE_LENGTH) {
len = PEM_LINE_LENGTH;
}
int read = read_internal(buf, len - 1, openSslInputStream_readLineMethod);
buf[read] = '\0';
JNI_TRACE("BIO::gets \"%s\"", buf);
return read;
}
private:
int read_internal(char *buf, int len, jmethodID method) {
JNIEnv* env = getEnv();
if (env == NULL) {
JNI_TRACE("BIO_InputStream::read could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_InputStream::read failed call to NewByteArray");
return -1;
}
jint read = env->CallIntMethod(getStream(), method, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read failed call to InputStream#read");
return -1;
}
/* Java uses -1 to indicate EOF condition. */
if (read == -1) {
setEof(true);
read = 0;
} else if (read > 0) {
env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast<jbyte*>(buf));
}
return read;
}
public:
/** Length of PEM-encoded line (64) plus CR plus NULL */
static const int PEM_LINE_LENGTH = 66;
};
class BIO_OutputStream : public BIO_Stream {
public:
BIO_OutputStream(jobject stream) :
BIO_Stream(stream) {
}
int write(const char *buf, int len) {
JNIEnv* env = getEnv();
if (env == NULL) {
JNI_TRACE("BIO_OutputStream::write => could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_OutputStream::write => failed call to NewByteArray");
return -1;
}
env->SetByteArrayRegion(javaBytes.get(), 0, len, reinterpret_cast<const jbyte*>(buf));
env->CallVoidMethod(getStream(), outputStream_writeMethod, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => failed call to OutputStream#write");
return -1;
}
return len;
}
};
static int bio_stream_create(BIO *b) {
b->init = 1;
b->num = 0;
b->ptr = NULL;
b->flags = 0;
return 1;
}
static int bio_stream_destroy(BIO *b) {
if (b == NULL) {
return 0;
}
if (b->ptr != NULL) {
delete static_cast<BIO_Stream*>(b->ptr);
b->ptr = NULL;
}
b->init = 0;
b->flags = 0;
return 1;
}
static int bio_stream_read(BIO *b, char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
int ret = stream->read(buf, len);
if (ret == 0) {
// EOF is indicated by -1 with a BIO flag.
BIO_set_retry_read(b);
return -1;
}
return ret;
}
static int bio_stream_write(BIO *b, const char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, len);
}
static int bio_stream_puts(BIO *b, const char *buf) {
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, strlen(buf));
}
static int bio_stream_gets(BIO *b, char *buf, int len) {
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
return stream->gets(buf, len);
}
static void bio_stream_assign(BIO *b, BIO_Stream* stream) {
b->ptr = static_cast<void*>(stream);
}
static long bio_stream_ctrl(BIO *b, int cmd, long, void *) {
BIO_Stream* stream = static_cast<BIO_Stream*>(b->ptr);
switch (cmd) {
case BIO_CTRL_EOF:
return stream->isEof() ? 1 : 0;
case BIO_CTRL_FLUSH:
return stream->flush();
default:
return 0;
}
}
static BIO_METHOD stream_bio_method = {
( 100 | 0x0400 ), /* source/sink BIO */
"InputStream/OutputStream BIO",
bio_stream_write, /* bio_write */
bio_stream_read, /* bio_read */
bio_stream_puts, /* bio_puts */
bio_stream_gets, /* bio_gets */
bio_stream_ctrl, /* bio_ctrl */
bio_stream_create, /* bio_create */
bio_stream_destroy, /* bio_free */
NULL, /* no bio_callback_ctrl */
};
/**
* Copied from libnativehelper NetworkUtilites.cpp
*/
static bool setBlocking(int fd, bool blocking) {
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
return false;
}
if (!blocking) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int rc = fcntl(fd, F_SETFL, flags);
return (rc != -1);
}
/**
* OpenSSL locking support. Taken from the O'Reilly book by Viega et al., but I
* suppose there are not many other ways to do this on a Linux system (modulo
* isomorphism).
*/
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#define THROW_SSLEXCEPTION (-2)
#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
#define THROWN_EXCEPTION (-4)
static MUTEX_TYPE* mutex_buf = NULL;
static void locking_function(int mode, int n, const char*, int) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(mutex_buf[n]);
} else {
MUTEX_UNLOCK(mutex_buf[n]);
}
}
static unsigned long id_function(void) {
return ((unsigned long)THREAD_ID);
}
int THREAD_setup(void) {
mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
if (!mutex_buf) {
return 0;
}
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
MUTEX_SETUP(mutex_buf[i]);
}
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int THREAD_cleanup(void) {
if (!mutex_buf) {
return 0;
}
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks( ); i++) {
MUTEX_CLEANUP(mutex_buf[i]);
}
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
/**
* Initialization phase for every OpenSSL job: Loads the Error strings, the
* crypto algorithms and reset the OpenSSL library
*/
static void NativeCrypto_clinit(JNIEnv*, jclass)
{
SSL_load_error_strings();
ERR_load_crypto_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
THREAD_setup();
}
static void NativeCrypto_ENGINE_load_dynamic(JNIEnv*, jclass) {
JNI_TRACE("ENGINE_load_dynamic()");
ENGINE_load_dynamic();
}
static jlong NativeCrypto_ENGINE_by_id(JNIEnv* env, jclass, jstring idJava) {
JNI_TRACE("ENGINE_by_id(%p)", idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
JNI_TRACE("ENGINE_by_id(%p) => id == null", idJava);
return 0;
}
JNI_TRACE("ENGINE_by_id(\"%s\")", id.c_str());
ENGINE* e = ENGINE_by_id(id.c_str());
if (e == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("ENGINE_by_id(\"%s\") => %p", id.c_str(), e);
return reinterpret_cast<uintptr_t>(e);
}
static jint NativeCrypto_ENGINE_add(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_add(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_add(e);
/*
* We tolerate errors, because the most likely error is that
* the ENGINE is already in the list.
*/
freeOpenSslErrorState();
JNI_TRACE("ENGINE_add(%p) => %d", e, ret);
return ret;
}
static jint NativeCrypto_ENGINE_init(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_init(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_init(e);
JNI_TRACE("ENGINE_init(%p) => %d", e, ret);
return ret;
}
static jint NativeCrypto_ENGINE_finish(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_finish(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_finish(e);
JNI_TRACE("ENGINE_finish(%p) => %d", e, ret);
return ret;
}
static jint NativeCrypto_ENGINE_free(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_free(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_free(e);
JNI_TRACE("ENGINE_free(%p) => %d", e, ret);
return ret;
}
static jlong NativeCrypto_ENGINE_load_private_key(JNIEnv* env, jclass, jlong engineRef,
jstring idJava) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_load_private_key(%p, %p)", e, idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "id == NULL");
return 0;
}
Unique_EVP_PKEY pkey(ENGINE_load_private_key(e, id.c_str(), NULL, NULL));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("ENGINE_load_private_key(%p, %p) => %p", e, idJava, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong engineRef)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_get_id(%p)", e);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_get_id(%p) => engine == null", e);
return NULL;
}
const char *id = ENGINE_get_id(e);
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF(id));
JNI_TRACE("ENGINE_get_id(%p) => \"%s\"", e, id);
return idJava.release();
}
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv* env, jclass, jlong engineRef,
jstring cmdJava, jstring argJava, jint cmd_optional)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d)", e, cmdJava, argJava, cmd_optional);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d) => engine == null", e, cmdJava, argJava,
cmd_optional);
return 0;
}
ScopedUtfChars cmdChars(env, cmdJava);
if (cmdChars.c_str() == NULL) {
return 0;
}
UniquePtr<ScopedUtfChars> arg;
const char* arg_c_str = NULL;
if (argJava != NULL) {
arg.reset(new ScopedUtfChars(env, argJava));
arg_c_str = arg->c_str();
if (arg_c_str == NULL) {
return 0;
}
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d)", e, cmdChars.c_str(), arg_c_str,
cmd_optional);
int ret = ENGINE_ctrl_cmd_string(e, cmdChars.c_str(), arg_c_str, cmd_optional);
if (ret != 1) {
throwExceptionIfNecessary(env, "ENGINE_ctrl_cmd_string");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => threw error", e,
cmdChars.c_str(), arg_c_str, cmd_optional);
return 0;
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => %d", e, cmdChars.c_str(),
arg_c_str, cmd_optional, ret);
return ret;
}
static jlong NativeCrypto_EVP_PKEY_new_DH(JNIEnv* env, jclass,
jbyteArray p, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p)",
p, g, pub_key, priv_key);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
jniThrowRuntimeException(env, "DH_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dh->p)) {
return 0;
}
if (!arrayToBignum(env, g, &dh->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dh->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dh->priv_key)) {
return 0;
}
if (dh->p == NULL || dh->g == NULL
|| (dh->pub_key == NULL && dh->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DH failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* public static native int EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g,
* byte[] pub_key, byte[] priv_key);
*/
static jlong NativeCrypto_EVP_PKEY_new_DSA(JNIEnv* env, jclass,
jbyteArray p, jbyteArray q, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DSA(p=%p, q=%p, g=%p, pub_key=%p, priv_key=%p)",
p, q, g, pub_key, priv_key);
Unique_DSA dsa(DSA_new());
if (dsa.get() == NULL) {
jniThrowRuntimeException(env, "DSA_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dsa->p)) {
return 0;
}
if (!arrayToBignum(env, q, &dsa->q)) {
return 0;
}
if (!arrayToBignum(env, g, &dsa->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dsa->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dsa->priv_key)) {
return 0;
}
if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL
|| (dsa->pub_key == NULL && dsa->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DSA(pkey.get(), dsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DSA failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dsa);
JNI_TRACE("EVP_PKEY_new_DSA(p=%p, q=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, q, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
*/
static jlong NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass,
jbyteArray n, jbyteArray e, jbyteArray d,
jbyteArray p, jbyteArray q,
jbyteArray dmp1, jbyteArray dmq1,
jbyteArray iqmp) {
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p, dmp1=%p, dmq1=%p, iqmp=%p)",
n, e, d, p, q, dmp1, dmq1, iqmp);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_new failed");
return 0;
}
if (e == NULL && d == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "e == NULL && d == NULL");
JNI_TRACE("NativeCrypto_EVP_PKEY_new_RSA => e == NULL && d == NULL");
return 0;
}
if (!arrayToBignum(env, n, &rsa->n)) {
return 0;
}
if (e != NULL && !arrayToBignum(env, e, &rsa->e)) {
return 0;
}
if (d != NULL && !arrayToBignum(env, d, &rsa->d)) {
return 0;
}
if (p != NULL && !arrayToBignum(env, p, &rsa->p)) {
return 0;
}
if (q != NULL && !arrayToBignum(env, q, &rsa->q)) {
return 0;
}
if (dmp1 != NULL && !arrayToBignum(env, dmp1, &rsa->dmp1)) {
return 0;
}
if (dmq1 != NULL && !arrayToBignum(env, dmq1, &rsa->dmq1)) {
return 0;
}
if (iqmp != NULL && !arrayToBignum(env, iqmp, &rsa->iqmp)) {
return 0;
}
#ifdef WITH_JNI_TRACE
if (p != NULL && q != NULL) {
int check = RSA_check_key(rsa.get());
JNI_TRACE("EVP_PKEY_new_RSA(...) RSA_check_key returns %d", check);
}
#endif
if (rsa->n == NULL || (rsa->e == NULL && rsa->d == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/*
* If the private exponent is available, there is the potential to do signing
* operations. If the public exponent is also available, OpenSSL will do RSA
* blinding. Enable it if possible.
*/
if (rsa->d != NULL) {
if (rsa->e != NULL) {
JNI_TRACE("EVP_PKEY_new_RSA(...) enabling RSA blinding => %p", rsa.get());
RSA_blinding_on(rsa.get(), NULL);
} else {
JNI_TRACE("EVP_PKEY_new_RSA(...) disabling RSA blinding => %p", rsa.get());
RSA_blinding_off(rsa.get());
}
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p dmp1=%p, dmq1=%p, iqmp=%p) => %p",
n, e, d, p, q, dmp1, dmq1, iqmp, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_EC_KEY(JNIEnv* env, jclass, jlong groupRef,
jlong pubkeyRef, jbyteArray keyJavaBytes) {
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
const EC_POINT* pubkey = reinterpret_cast<const EC_POINT*>(pubkeyRef);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p)", group, pubkey, keyJavaBytes);
Unique_BIGNUM key(NULL);
if (keyJavaBytes != NULL) {
BIGNUM* keyRef = NULL;
if (!arrayToBignum(env, keyJavaBytes, &keyRef)) {
return 0;
}
key.reset(keyRef);
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
jniThrowRuntimeException(env, "EC_KEY_new failed");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) > EC_KEY_set_group failed", group, pubkey,
keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (pubkey != NULL) {
if (EC_KEY_set_public_key(eckey.get(), pubkey) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_public_key");
return 0;
}
}
if (key.get() != NULL) {
if (EC_KEY_set_private_key(eckey.get(), key.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
if (pubkey == NULL) {
Unique_EC_POINT calcPubkey(EC_POINT_new(group));
if (!EC_POINT_mul(group, calcPubkey.get(), key.get(), NULL, NULL, NULL)) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => can't calulate public key", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
EC_KEY_set_public_key(eckey.get(), calcPubkey.get());
}
}
if (!EC_KEY_check_key(eckey.get())) {
JNI_TRACE("EVP_KEY_new_EC_KEY(%p, %p, %p) => invalid key created", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_check_key");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => %p", group, pubkey, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_mac_key(JNIEnv* env, jclass, jint pkeyType,
jbyteArray keyJavaBytes)
{
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p)", pkeyType, keyJavaBytes);
ScopedByteArrayRO key(env, keyJavaBytes);
if (key.get() == NULL) {
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(key.get());
Unique_EVP_PKEY pkey(EVP_PKEY_new_mac_key(pkeyType, (ENGINE *) NULL, tmp, key.size()));
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => threw error", pkeyType, keyJavaBytes);
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => %p", pkeyType, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static int NativeCrypto_EVP_PKEY_type(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_type(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_type(pkey->type);
JNI_TRACE("EVP_PKEY_type(%p) => %d", pkey, result);
return result;
}
/**
* private static native int EVP_PKEY_size(int pkey);
*/
static int NativeCrypto_EVP_PKEY_size(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_size(pkey);
JNI_TRACE("EVP_PKEY_size(%p) => %d", pkey, result);
return result;
}
static jstring NativeCrypto_EVP_PKEY_print_public(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_print_public(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_public(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_public");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_public(%p) => \"%s\"", pkey, tmp);
return description;
}
static jstring NativeCrypto_EVP_PKEY_print_private(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_print_private(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_private(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_private");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_private(%p) => \"%s\"", pkey, tmp);
return description;
}
static void NativeCrypto_EVP_PKEY_free(JNIEnv*, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_free(%p)", pkey);
if (pkey != NULL) {
EVP_PKEY_free(pkey);
}
}
static jint NativeCrypto_EVP_PKEY_cmp(JNIEnv* env, jclass, jlong pkey1Ref, jlong pkey2Ref) {
EVP_PKEY* pkey1 = reinterpret_cast<EVP_PKEY*>(pkey1Ref);
EVP_PKEY* pkey2 = reinterpret_cast<EVP_PKEY*>(pkey2Ref);
JNI_TRACE("EVP_PKEY_cmp(%p, %p)", pkey1, pkey2);
if (pkey1 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey1 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey1 == NULL");
return -1;
} else if (pkey2 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey2 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey2 == NULL");
return -1;
}
int result = EVP_PKEY_cmp(pkey1, pkey2);
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => %d", pkey1, pkey2, result);
return result;
}
/*
* static native byte[] i2d_PKCS8_PRIV_KEY_INFO(int, byte[])
*/
static jbyteArray NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("i2d_PKCS8_PRIV_KEY_INFO(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return NULL;
}
Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("key=%p i2d_PKCS8_PRIV_KEY_INFO => error from key to PKCS8", pkey);
return NULL;
}
return ASN1ToByteArray<PKCS8_PRIV_KEY_INFO, i2d_PKCS8_PRIV_KEY_INFO>(env, pkcs8.get());
}
/*
* static native int d2i_PKCS8_PRIV_KEY_INFO(byte[])
*/
static jlong NativeCrypto_d2i_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jbyteArray keyJavaBytes) {
JNI_TRACE("d2i_PKCS8_PRIV_KEY_INFO(%p)", keyJavaBytes);
ScopedByteArrayRO bytes(env, keyJavaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => threw exception", keyJavaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &tmp, bytes.size()));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from DER to PKCS8", keyJavaBytes);
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from PKCS8 to key", keyJavaBytes);
return 0;
}
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => %p", keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* static native byte[] i2d_PUBKEY(int)
*/
static jbyteArray NativeCrypto_i2d_PUBKEY(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("i2d_PUBKEY(%p)", pkey);
return ASN1ToByteArray<EVP_PKEY, i2d_PUBKEY>(env, pkey);
}
/*
* static native int d2i_PUBKEY(byte[])
*/
static jlong NativeCrypto_d2i_PUBKEY(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("d2i_PUBKEY(%p)", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("d2i_PUBKEY(%p) => threw error", javaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, bytes.size()));
if (pkey.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PUBKEY => threw exception", javaBytes);
throwExceptionIfNecessary(env, "d2i_PUBKEY");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native int RSA_generate_key(int modulusBits, byte[] publicExponent);
*/
static jlong NativeCrypto_RSA_generate_key_ex(JNIEnv* env, jclass, jint modulusBits,
jbyteArray publicExponent) {
JNI_TRACE("RSA_generate_key_ex(%d, %p)", modulusBits, publicExponent);
BIGNUM* eRef = NULL;
if (!arrayToBignum(env, publicExponent, &eRef)) {
return 0;
}
Unique_BIGNUM e(eRef);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
if (RSA_generate_key_ex(rsa.get(), modulusBits, e.get(), NULL) < 0) {
throwExceptionIfNecessary(env, "RSA_generate_key_ex");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("RSA_generate_key_ex(n=%d, e=%p) => %p", modulusBits, publicExponent, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jint NativeCrypto_RSA_size(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("RSA_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_size failed");
return 0;
}
return static_cast<jint>(RSA_size(rsa.get()));
}
typedef int RSACryptOperation(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
int padding);
static jint RSA_crypt_operation(RSACryptOperation operation,
const char* caller __attribute__ ((unused)), JNIEnv* env, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("%s(%d, %p, %p, %p)", caller, flen, fromJavaBytes, toJavaBytes, pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return -1;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
return -1;
}
ScopedByteArrayRO from(env, fromJavaBytes);
if (from.get() == NULL) {
return -1;
}
ScopedByteArrayRW to(env, toJavaBytes);
if (to.get() == NULL) {
return -1;
}
int resultSize = operation(static_cast<int>(flen),
reinterpret_cast<const unsigned char*>(from.get()),
reinterpret_cast<unsigned char*>(to.get()), rsa.get(), padding);
if (resultSize == -1) {
JNI_TRACE("%s => failed", caller);
throwExceptionIfNecessary(env, "RSA_crypt_operation");
return -1;
}
JNI_TRACE("%s(%d, %p, %p, %p) => %d", caller, flen, fromJavaBytes, toJavaBytes, pkey,
resultSize);
return static_cast<jint>(resultSize);
}
static jint NativeCrypto_RSA_private_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_private_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
/*
* public static native byte[][] get_RSA_public_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_public_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
return joa;
}
/*
* public static native byte[][] get_RSA_private_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_private_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(8, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
if (rsa->e != NULL) {
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
}
if (rsa->d != NULL) {
jbyteArray d = bignumToArray(env, rsa->d, "d");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, d);
}
if (rsa->p != NULL) {
jbyteArray p = bignumToArray(env, rsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, p);
}
if (rsa->q != NULL) {
jbyteArray q = bignumToArray(env, rsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, q);
}
if (rsa->dmp1 != NULL) {
jbyteArray dmp1 = bignumToArray(env, rsa->dmp1, "dmp1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 5, dmp1);
}
if (rsa->dmq1 != NULL) {
jbyteArray dmq1 = bignumToArray(env, rsa->dmq1, "dmq1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 6, dmq1);
}
if (rsa->iqmp != NULL) {
jbyteArray iqmp = bignumToArray(env, rsa->iqmp, "iqmp");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 7, iqmp);
}
return joa;
}
/*
* public static native int DSA_generate_key(int, byte[], byte[], byte[], byte[]);
*/
static jlong NativeCrypto_DSA_generate_key(JNIEnv* env, jclass, jint primeBits,
jbyteArray seedJavaBytes, jbyteArray gBytes, jbyteArray pBytes, jbyteArray qBytes) {
JNI_TRACE("DSA_generate_key(%d, %p, %p, %p, %p)", primeBits, seedJavaBytes,
gBytes, pBytes, qBytes);
UniquePtr<unsigned char[]> seedPtr;
unsigned long seedSize = 0;
if (seedJavaBytes != NULL) {
ScopedByteArrayRO seed(env, seedJavaBytes);
if (seed.get() == NULL) {
return 0;
}
seedSize = seed.size();
seedPtr.reset(new unsigned char[seedSize]);
memcpy(seedPtr.get(), seed.get(), seedSize);
}
Unique_DSA dsa(DSA_new());
if (dsa.get() == NULL) {
JNI_TRACE("DSA_generate_key failed");
jniThrowOutOfMemory(env, "Unable to allocate DSA key");
freeOpenSslErrorState();
return 0;
}
if (gBytes != NULL && pBytes != NULL && qBytes != NULL) {
JNI_TRACE("DSA_generate_key parameters specified");
if (!arrayToBignum(env, gBytes, &dsa->g)) {
return 0;
}
if (!arrayToBignum(env, pBytes, &dsa->p)) {
return 0;
}
if (!arrayToBignum(env, qBytes, &dsa->q)) {
return 0;
}
} else {
JNI_TRACE("DSA_generate_key generating parameters");
if (!DSA_generate_parameters_ex(dsa.get(), primeBits, seedPtr.get(), seedSize, NULL, NULL, NULL)) {
JNI_TRACE("DSA_generate_key => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DSA_generate_parameters_ex failed");
return 0;
}
}
if (!DSA_generate_key(dsa.get())) {
JNI_TRACE("DSA_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DSA_generate_key failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DSA_generate_key failed");
jniThrowRuntimeException(env, "NativeCrypto_DSA_generate_key failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DSA(pkey.get(), dsa.get()) != 1) {
JNI_TRACE("DSA_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DSA_generate_key failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dsa);
JNI_TRACE("DSA_generate_key(n=%d, e=%p) => %p", primeBits, seedPtr.get(), pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native byte[][] get_DSA_params(long);
*/
static jobjectArray NativeCrypto_get_DSA_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_DSA_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey));
if (dsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_DSA_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(5, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dsa->g != NULL) {
jbyteArray g = bignumToArray(env, dsa->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, g);
}
if (dsa->p != NULL) {
jbyteArray p = bignumToArray(env, dsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, p);
}
if (dsa->q != NULL) {
jbyteArray q = bignumToArray(env, dsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, q);
}
if (dsa->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dsa->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, pub_key);
}
if (dsa->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dsa->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, priv_key);
}
return joa;
}
static void NativeCrypto_set_DSA_flag_nonce_from_hash(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("set_DSA_flag_nonce_from_hash(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey));
if (dsa.get() == NULL) {
throwExceptionIfNecessary(env, "set_DSA_flag_nonce_from_hash failed");
return;
}
dsa->flags |= DSA_FLAG_NONCE_FROM_HASH;
}
static jlong NativeCrypto_DH_generate_key(JNIEnv* env, jclass, jint primeBits, jint generator) {
JNI_TRACE("DH_generate_key(%d, %d)", primeBits, generator);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
jniThrowOutOfMemory(env, "Unable to allocate DH key");
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("DH_generate_key generating parameters");
if (!DH_generate_parameters_ex(dh.get(), primeBits, generator, NULL)) {
JNI_TRACE("DH_generate_key => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
if (!DH_generate_key(dh.get())) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
jniThrowRuntimeException(env, "NativeCrypto_DH_generate_key failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("DH_generate_key(n=%d, g=%d) => %p", primeBits, generator, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jobjectArray NativeCrypto_get_DH_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_DH_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
throwExceptionIfNecessary(env, "get_DH_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(4, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dh->p != NULL) {
jbyteArray p = bignumToArray(env, dh->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, p);
}
if (dh->g != NULL) {
jbyteArray g = bignumToArray(env, dh->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, g);
}
if (dh->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dh->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, pub_key);
}
if (dh->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dh->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, priv_key);
}
return joa;
}
#define EC_CURVE_GFP 1
#define EC_CURVE_GF2M 2
/**
* Return group type or 0 if unknown group.
* EC_GROUP_GFP or EC_GROUP_GF2M
*/
static int get_EC_GROUP_type(const EC_GROUP* group)
{
const EC_METHOD* method = EC_GROUP_method_of(group);
if (method == EC_GFp_nist_method()
|| method == EC_GFp_mont_method()
|| method == EC_GFp_simple_method()) {
return EC_CURVE_GFP;
} else if (method == EC_GF2m_simple_method()) {
return EC_CURVE_GF2M;
}
return 0;
}
static jlong NativeCrypto_EC_GROUP_new_by_curve_name(JNIEnv* env, jclass, jstring curveNameJava)
{
JNI_TRACE("EC_GROUP_new_by_curve_name(%p)", curveNameJava);
ScopedUtfChars curveName(env, curveNameJava);
if (curveName.c_str() == NULL) {
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s)", curveName.c_str());
int nid = OBJ_sn2nid(curveName.c_str());
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID name", curveName.c_str());
return 0;
}
EC_GROUP* group = EC_GROUP_new_by_curve_name(nid);
if (group == NULL) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID %d", curveName.c_str(), nid);
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => %p", curveName.c_str(), group);
return reinterpret_cast<uintptr_t>(group);
}
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv* env, jclass, jlong groupRef,
jint flag)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d)", group, flag);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_asn1_flag => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_asn1_flag(group, flag);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d) => success", group, flag);
}
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv* env, jclass,
jlong groupRef, jint form)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d)", group, form);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_point_conversion_form => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_point_conversion_form(group, static_cast<point_conversion_form_t>(form));
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d) => success", group, form);
}
static jlong NativeCrypto_EC_GROUP_new_curve(JNIEnv* env, jclass, jint type, jbyteArray pJava,
jbyteArray aJava, jbyteArray bJava)
{
JNI_TRACE("EC_GROUP_new_curve(%d, %p, %p, %p)", type, pJava, aJava, bJava);
BIGNUM* pRef = NULL;
if (!arrayToBignum(env, pJava, &pRef)) {
return 0;
}
Unique_BIGNUM p(pRef);
BIGNUM* aRef = NULL;
if (!arrayToBignum(env, aJava, &aRef)) {
return 0;
}
Unique_BIGNUM a(aRef);
BIGNUM* bRef = NULL;
if (!arrayToBignum(env, bJava, &bRef)) {
return 0;
}
Unique_BIGNUM b(bRef);
EC_GROUP* group;
switch (type) {
case EC_CURVE_GFP:
group = EC_GROUP_new_curve_GFp(p.get(), a.get(), b.get(), (BN_CTX*) NULL);
break;
case EC_CURVE_GF2M:
group = EC_GROUP_new_curve_GF2m(p.get(), a.get(), b.get(), (BN_CTX*) NULL);
break;
default:
jniThrowRuntimeException(env, "invalid group");
return 0;
}
if (group == NULL) {
throwExceptionIfNecessary(env, "EC_GROUP_new_curve");
}
JNI_TRACE("EC_GROUP_new_curve(%d, %p, %p, %p) => %p", type, pJava, aJava, bJava, group);
return reinterpret_cast<uintptr_t>(group);
}
static jlong NativeCrypto_EC_GROUP_dup(JNIEnv* env, jclass, jlong groupRef) {
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_dup(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_dup => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
EC_GROUP* groupDup = EC_GROUP_dup(group);
JNI_TRACE("EC_GROUP_dup(%p) => %p", group, groupDup);
return reinterpret_cast<uintptr_t>(groupDup);
}
static jstring NativeCrypto_EC_GROUP_get_curve_name(JNIEnv* env, jclass, jlong groupRef) {
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
int nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_get_curve_name(%p) => unnamed curve", group);
return NULL;
}
const char* shortName = OBJ_nid2sn(nid);
JNI_TRACE("EC_GROUP_get_curve_name(%p) => \"%s\"", group, shortName);
return env->NewStringUTF(shortName);
}
static jobjectArray NativeCrypto_EC_GROUP_get_curve(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_curve(%p)", group);
Unique_BIGNUM p(BN_new());
Unique_BIGNUM a(BN_new());
Unique_BIGNUM b(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), (BN_CTX*) NULL);
break;
case EC_CURVE_GF2M:
ret = EC_GROUP_get_curve_GF2m(group, p.get(), a.get(), b.get(), (BN_CTX*)NULL);
break;
default:
jniThrowRuntimeException(env, "invalid group");
return NULL;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_GROUP_get_curve");
return NULL;
}
jobjectArray joa = env->NewObjectArray(3, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray pArray = bignumToArray(env, p.get(), "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, pArray);
jbyteArray aArray = bignumToArray(env, a.get(), "a");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, aArray);
jbyteArray bArray = bignumToArray(env, b.get(), "b");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, bArray);
JNI_TRACE("EC_GROUP_get_curve(%p) => %p", group, joa);
return joa;
}
static jbyteArray NativeCrypto_EC_GROUP_get_order(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_order(%p)", group);
Unique_BIGNUM order(BN_new());
if (order.get() == NULL) {
JNI_TRACE("EC_GROUP_get_order(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_order(group, order.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_order(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_order");
return NULL;
}
jbyteArray orderArray = bignumToArray(env, order.get(), "order");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_order(%p) => %p", group, orderArray);
return orderArray;
}
static jint NativeCrypto_EC_GROUP_get_degree(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_degree(%p)", group);
jint degree = EC_GROUP_get_degree(group);
if (degree == 0) {
JNI_TRACE("EC_GROUP_get_degree(%p) => unsupported", group);
jniThrowRuntimeException(env, "not supported");
return 0;
}
JNI_TRACE("EC_GROUP_get_degree(%p) => %d", group, degree);
return degree;
}
static jbyteArray NativeCrypto_EC_GROUP_get_cofactor(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_cofactor(%p)", group);
Unique_BIGNUM cofactor(BN_new());
if (cofactor.get() == NULL) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_cofactor(group, cofactor.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_cofactor");
return NULL;
}
jbyteArray cofactorArray = bignumToArray(env, cofactor.get(), "cofactor");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_cofactor(%p) => %p", group, cofactorArray);
return cofactorArray;
}
static jint NativeCrypto_get_EC_GROUP_type(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("get_EC_GROUP_type(%p)", group);
int type = get_EC_GROUP_type(group);
if (type == 0) {
JNI_TRACE("get_EC_GROUP_type(%p) => curve type", group);
jniThrowRuntimeException(env, "unknown curve type");
} else {
JNI_TRACE("get_EC_GROUP_type(%p) => %d", group, type);
}
return type;
}
static void NativeCrypto_EC_GROUP_clear_free(JNIEnv* env, jclass, jlong groupRef)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_clear_free(group);
JNI_TRACE("EC_GROUP_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_GROUP_cmp(JNIEnv* env, jclass, jlong group1Ref, jlong group2Ref)
{
const EC_GROUP* group1 = reinterpret_cast<const EC_GROUP*>(group1Ref);
const EC_GROUP* group2 = reinterpret_cast<const EC_GROUP*>(group2Ref);
JNI_TRACE("EC_GROUP_cmp(%p, %p)", group1, group2);
if (group1 == NULL || group2 == NULL) {
JNI_TRACE("EC_GROUP_cmp(%p, %p) => group1 == null || group2 == null", group1, group2);
jniThrowNullPointerException(env, "group1 == null || group2 == null");
return false;
}
int ret = EC_GROUP_cmp(group1, group2, (BN_CTX*)NULL);
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", group1, group2, ret);
return ret == 0;
}
static void NativeCrypto_EC_GROUP_set_generator(JNIEnv* env, jclass, jlong groupRef, jlong pointRef, jbyteArray njavaBytes, jbyteArray hjavaBytes)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
const EC_POINT* point = reinterpret_cast<const EC_POINT*>(pointRef);
JNI_TRACE("EC_GROUP_set_generator(%p, %p, %p, %p)", group, point, njavaBytes, hjavaBytes);
if (group == NULL || point == NULL) {
JNI_TRACE("EC_GROUP_set_generator(%p, %p, %p, %p) => group == null || point == null",
group, point, njavaBytes, hjavaBytes);
jniThrowNullPointerException(env, "group == null || point == null");
return;
}
BIGNUM* nRef = NULL;
if (!arrayToBignum(env, njavaBytes, &nRef)) {
return;
}
Unique_BIGNUM n(nRef);
BIGNUM* hRef = NULL;
if (!arrayToBignum(env, hjavaBytes, &hRef)) {
return;
}
Unique_BIGNUM h(hRef);
int ret = EC_GROUP_set_generator(group, point, n.get(), h.get());
if (ret == 0) {
throwExceptionIfNecessary(env, "EC_GROUP_set_generator");
}
JNI_TRACE("EC_GROUP_set_generator(%p, %p, %p, %p) => %d", group, point, njavaBytes, hjavaBytes, ret);
}
static jlong NativeCrypto_EC_GROUP_get_generator(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_generator(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_get_generator(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
const EC_POINT* generator = EC_GROUP_get0_generator(group);
Unique_EC_POINT dup(EC_POINT_dup(generator, group));
if (dup.get() == NULL) {
JNI_TRACE("EC_GROUP_get_generator(%p) => oom error", group);
jniThrowOutOfMemory(env, "unable to dupe generator");
return 0;
}
JNI_TRACE("EC_GROUP_get_generator(%p) => %p", group, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static jlong NativeCrypto_EC_POINT_new(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_POINT_new(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_new(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
EC_POINT* point = EC_POINT_new(group);
if (point == NULL) {
jniThrowOutOfMemory(env, "Unable create an EC_POINT");
return 0;
}
return reinterpret_cast<uintptr_t>(point);
}
static void NativeCrypto_EC_POINT_clear_free(JNIEnv* env, jclass, jlong groupRef) {
EC_POINT* group = reinterpret_cast<EC_POINT*>(groupRef);
JNI_TRACE("EC_POINT_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_POINT_clear_free(group);
JNI_TRACE("EC_POINT_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_POINT_cmp(JNIEnv* env, jclass, jlong groupRef, jlong point1Ref, jlong point2Ref)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
const EC_POINT* point1 = reinterpret_cast<const EC_POINT*>(point1Ref);
const EC_POINT* point2 = reinterpret_cast<const EC_POINT*>(point2Ref);
JNI_TRACE("EC_POINT_cmp(%p, %p, %p)", group, point1, point2);
if (group == NULL || point1 == NULL || point2 == NULL) {
JNI_TRACE("EC_POINT_cmp(%p, %p, %p) => group == null || point1 == null || point2 == null",
group, point1, point2);
jniThrowNullPointerException(env, "group == null || point1 == null || point2 == null");
return false;
}
int ret = EC_POINT_cmp(group, point1, point2, (BN_CTX*)NULL);
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", point1, point2, ret);
return ret == 0;
}
static void NativeCrypto_EC_POINT_set_affine_coordinates(JNIEnv* env, jclass,
jlong groupRef, jlong pointRef, jbyteArray xjavaBytes, jbyteArray yjavaBytes)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
EC_POINT* point = reinterpret_cast<EC_POINT*>(pointRef);
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p)", group, point, xjavaBytes,
yjavaBytes);
if (group == NULL || point == NULL) {
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => group == null || point == null",
group, point, xjavaBytes, yjavaBytes);
jniThrowNullPointerException(env, "group == null || point == null");
return;
}
BIGNUM* xRef = NULL;
if (!arrayToBignum(env, xjavaBytes, &xRef)) {
return;
}
Unique_BIGNUM x(xRef);
BIGNUM* yRef = NULL;
if (!arrayToBignum(env, yjavaBytes, &yRef)) {
return;
}
Unique_BIGNUM y(yRef);
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_set_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
case EC_CURVE_GF2M:
ret = EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates");
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => %d", group, point,
xjavaBytes, yjavaBytes, ret);
}
static jobjectArray NativeCrypto_EC_POINT_get_affine_coordinates(JNIEnv* env, jclass, jlong groupRef,
jlong pointRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
const EC_POINT* point = reinterpret_cast<const EC_POINT*>(pointRef);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
Unique_BIGNUM x(BN_new());
Unique_BIGNUM y(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_get_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
case EC_CURVE_GF2M:
ret = EC_POINT_get_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return NULL;
}
if (ret != 1) {
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
throwExceptionIfNecessary(env, "EC_POINT_get_affine_coordinates");
return NULL;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray xBytes = bignumToArray(env, x.get(), "x");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, xBytes);
jbyteArray yBytes = bignumToArray(env, y.get(), "y");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, yBytes);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) => %p", group, point, joa);
return joa;
}
static jlong NativeCrypto_EC_KEY_generate_key(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_KEY_generate_key(%p)", group);
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_new() oom", group);
jniThrowOutOfMemory(env, "Unable to create an EC_KEY");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_set_group error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (EC_KEY_generate_key(eckey.get()) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_generate_key error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_KEY_generate_key");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EC_KEY_generate_key(%p) => %p", group, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EC_KEY_get0_group(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_get0_group(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("EC_KEY_get0_group(%p) => pkey == null", pkey);
return 0;
}
if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
jniThrowRuntimeException(env, "not EC key");
JNI_TRACE("EC_KEY_get0_group(%p) => not EC key (type == %d)", pkey,
EVP_PKEY_type(pkey->type));
return 0;
}
const EC_GROUP* group = EC_KEY_get0_group(pkey->pkey.ec);
JNI_TRACE("EC_KEY_get0_group(%p) => %p", pkey, group);
return reinterpret_cast<uintptr_t>(group);
}
static jbyteArray NativeCrypto_EC_KEY_get_private_key(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_get_private_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return NULL;
}
const BIGNUM *privkey = EC_KEY_get0_private_key(eckey.get());
jbyteArray privBytes = bignumToArray(env, privkey, "privkey");
if (env->ExceptionCheck()) {
JNI_TRACE("EC_KEY_get_private_key(%p) => threw error", pkey);
return NULL;
}
JNI_TRACE("EC_KEY_get_private_key(%p) => %p", pkey, privBytes);
return privBytes;
}
static jlong NativeCrypto_EC_KEY_get_public_key(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_get_public_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return 0;
}
Unique_EC_POINT dup(EC_POINT_dup(EC_KEY_get0_public_key(eckey.get()),
EC_KEY_get0_group(eckey.get())));
if (dup.get() == NULL) {
JNI_TRACE("EC_KEY_get_public_key(%p) => can't dup public key", pkey);
jniThrowRuntimeException(env, "EC_POINT_dup");
return 0;
}
JNI_TRACE("EC_KEY_get_public_key(%p) => %p", pkey, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv* env, jclass, jlong pkeyRef,
jboolean enabled)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_set_nonce_from_hash(%p, %d)", pkey, enabled ? 1 : 0);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return;
}
EC_KEY_set_nonce_from_hash(eckey.get(), enabled ? 1 : 0);
}
static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass,
jbyteArray outArray, jint outOffset, jlong pubkeyRef, jlong privkeyRef)
{
EVP_PKEY* pubPkey = reinterpret_cast<EVP_PKEY*>(pubkeyRef);
EVP_PKEY* privPkey = reinterpret_cast<EVP_PKEY*>(privkeyRef);
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p)", outArray, outOffset, pubPkey, privPkey);
ScopedByteArrayRW out(env, outArray);
if (out.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) can't get output buffer",
outArray, outOffset, pubPkey, privPkey);
return -1;
}
if ((outOffset < 0) || ((size_t) outOffset >= out.size())) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
if (pubPkey == NULL) {
jniThrowNullPointerException(env, "pubPkey == null");
return -1;
}
Unique_EC_KEY pubkey(EVP_PKEY_get1_EC_KEY(pubPkey));
if (pubkey.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
const EC_POINT* pubkeyPoint = EC_KEY_get0_public_key(pubkey.get());
if (pubkeyPoint == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key point", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
if (privPkey == NULL) {
jniThrowNullPointerException(env, "privPkey == null");
return -1;
}
Unique_EC_KEY privkey(EVP_PKEY_get1_EC_KEY(privPkey));
if (privkey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY private");
return -1;
}
int outputLength = ECDH_compute_key(
&out[outOffset],
out.size() - outOffset,
pubkeyPoint,
privkey.get(),
NULL // No KDF
);
if (outputLength == -1) {
throwExceptionIfNecessary(env, "ECDH_compute_key");
return -1;
}
return outputLength;
}
static jlong NativeCrypto_EVP_MD_CTX_create(JNIEnv* env, jclass) {
JNI_TRACE_MD("EVP_MD_CTX_create()");
Unique_EVP_MD_CTX ctx(EVP_MD_CTX_create());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable create a EVP_MD_CTX");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_create() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static void NativeCrypto_EVP_MD_CTX_init(JNIEnv* env, jclass, jobject ctxRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_init(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_init(ctx);
}
}
static void NativeCrypto_EVP_MD_CTX_destroy(JNIEnv* env, jclass, jlong ctxRef) {
EVP_MD_CTX* ctx = reinterpret_cast<EVP_MD_CTX*>(ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_destroy(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_destroy(ctx);
}
}
static jint NativeCrypto_EVP_MD_CTX_copy(JNIEnv* env, jclass, jobject dstCtxRef, jobject srcCtxRef) {
EVP_MD_CTX* dst_ctx = fromContextObject<EVP_MD_CTX>(env, dstCtxRef);
const EVP_MD_CTX* src_ctx = fromContextObject<EVP_MD_CTX>(env, srcCtxRef);
JNI_TRACE_MD("EVP_MD_CTX_copy(%p. %p)", dst_ctx, src_ctx);
if (src_ctx == NULL) {
return 0;
} else if (dst_ctx == NULL) {
return 0;
}
int result = EVP_MD_CTX_copy_ex(dst_ctx, src_ctx);
if (result == 0) {
jniThrowRuntimeException(env, "Unable to copy EVP_MD_CTX");
freeOpenSslErrorState();
}
JNI_TRACE_MD("EVP_MD_CTX_copy(%p, %p) => %d", dst_ctx, src_ctx, result);
return result;
}
/*
* public static native int EVP_DigestFinal(long, byte[], int)
*/
static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray hash,
jint offset) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d)", ctx, hash, offset);
if (ctx == NULL) {
return -1;
} else if (hash == NULL) {
jniThrowNullPointerException(env, "ctx == null || hash == null");
return -1;
}
ScopedByteArrayRW hashBytes(env, hash);
if (hashBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_DigestFinal_ex(ctx,
reinterpret_cast<unsigned char*>(hashBytes.get() + offset),
&bytesWritten);
if (ok == 0) {
throwExceptionIfNecessary(env, "EVP_DigestFinal");
}
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d) => %d", ctx, hash, offset, bytesWritten);
return bytesWritten;
}
static jint evpInit(JNIEnv* env, jobject evpMdCtxRef, jlong evpMdRef, const char* jniName,
int (*init_func)(EVP_MD_CTX*, const EVP_MD*, ENGINE*)) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* evp_md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE_MD("%s(%p, %p)", jniName, ctx, evp_md);
if (ctx == NULL) {
return 0;
} else if (evp_md == NULL) {
jniThrowNullPointerException(env, "evp_md == null");
return 0;
}
int ok = init_func(ctx, evp_md, NULL);
if (ok == 0) {
bool exception = throwExceptionIfNecessary(env, jniName);
if (exception) {
JNI_TRACE("%s(%p) => threw exception", jniName, evp_md);
return 0;
}
}
JNI_TRACE_MD("%s(%p, %p) => %d", jniName, ctx, evp_md, ok);
return ok;
}
static jint NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_DigestInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_SignInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_SignInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_VerifyInit", EVP_DigestInit_ex);
}
/*
* public static native int EVP_get_digestbyname(java.lang.String)
*/
static jlong NativeCrypto_EVP_get_digestbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%p)", algorithm);
if (algorithm == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s)", algorithmChars.c_str());
const EVP_MD* evp_md = EVP_get_digestbyname(algorithmChars.c_str());
if (evp_md == NULL) {
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => %p", algorithmChars.c_str(), evp_md);
return reinterpret_cast<uintptr_t>(evp_md);
}
/*
* public static native int EVP_MD_size(long)
*/
static jint NativeCrypto_EVP_MD_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p) => %d", evp_md, result);
return result;
}
/*
* public static int void EVP_MD_block_size(long)
*/
static jint NativeCrypto_EVP_MD_block_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_block_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p) => %d", evp_md, result);
return result;
}
static void NativeCrypto_EVP_DigestSignInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jlong pkeyRef) {
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p)", mdCtx, md, pkey);
if (mdCtx == NULL) {
return;
}
if (md == NULL) {
jniThrowNullPointerException(env, "md == null");
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
if (EVP_DigestSignInit(mdCtx, (EVP_PKEY_CTX **) NULL, md, (ENGINE *) NULL, pkey) <= 0) {
JNI_TRACE("ctx=%p EVP_DigestSignInit => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignInit");
return;
}
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p) => success", mdCtx, md, pkey);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jbyteArray inJavaBytes, jint inOffset,
jint inLength, const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *,
size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE_MD("%s(%p, %p, %d, %d)", jniName, mdCtx, inJavaBytes, inOffset, inLength);
if (mdCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inJavaBytes);
if (inBytes.get() == NULL) {
return;
}
if (inOffset < 0 || size_t(inOffset) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inOffset");
return;
}
const ssize_t inEnd = inOffset + inLength;
if (inEnd < 0 || size_t(inEnd) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inLength");
return;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char *>(inBytes.get());
if (!update_func(mdCtx, tmp + inOffset, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d, %d) => success", jniName, mdCtx, inJavaBytes, inOffset, inLength);
}
static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestSignUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_SignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_SignUpdate",
EVP_DigestUpdate);
}
static jbyteArray NativeCrypto_EVP_DigestSignFinal(JNIEnv* env, jclass, jobject evpMdCtxRef)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestSignFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return NULL;
}
const size_t expectedSize = EVP_MD_CTX_size(mdCtx);
ScopedLocalRef<jbyteArray> outJavaBytes(env, env->NewByteArray(expectedSize));
if (outJavaBytes.get() == NULL) {
return NULL;
}
ScopedByteArrayRW outBytes(env, outJavaBytes.get());
if (outBytes.get() == NULL) {
return NULL;
}
unsigned char *tmp = reinterpret_cast<unsigned char*>(outBytes.get());
size_t len;
if (!EVP_DigestSignFinal(mdCtx, tmp, &len)) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return 0;
}
if (len != expectedSize) {
jniThrowRuntimeException(env, "hash size unexpected");
return 0;
}
JNI_TRACE("EVP_DigestSignFinal(%p) => %p", mdCtx, outJavaBytes.get());
return outJavaBytes.release();
}
/*
* public static native int EVP_SignFinal(long, byte[], int, long)
*/
static jint NativeCrypto_EVP_SignFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray signature,
jint offset, jlong pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p)", ctx, signature, offset, pkey);
if (ctx == NULL) {
return -1;
} else if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRW signatureBytes(env, signature);
if (signatureBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_SignFinal(ctx,
reinterpret_cast<unsigned char*>(signatureBytes.get() + offset),
&bytesWritten,
pkey);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_SignFinal");
}
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p) => %u",
ctx, signature, offset, pkey, bytesWritten);
return bytesWritten;
}
/*
* public static native void EVP_VerifyUpdate(long, byte[], int, int)
*/
static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray buffer, jint offset, jint length) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE("NativeCrypto_EVP_VerifyUpdate(%p, %p, %d, %d)", ctx, buffer, offset, length);
if (ctx == NULL) {
return;
} else if (buffer == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return;
}
if (bufferBytes.size() < static_cast<size_t>(offset + length)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
int ok = EVP_VerifyUpdate(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyUpdate");
}
}
/*
* public static native int EVP_VerifyFinal(long, byte[], int, int, long)
*/
static jint NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray buffer,
jint offset, jint length, jlong pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p)",
ctx, buffer, offset, length, pkey);
if (ctx == NULL) {
return -1;
} else if (buffer == NULL || pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return -1;
}
int ok = EVP_VerifyFinal(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length,
pkey);
if (ok < 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyFinal");
}
/*
* For DSA keys, OpenSSL appears to have a bug where it returns
* errors for any result != 1. See dsa_ossl.c in dsa_do_verify
*/
freeOpenSslErrorState();
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p) => %d",
ctx, buffer, offset, length, pkey, ok);
return ok;
}
static jlong NativeCrypto_EVP_get_cipherbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("EVP_get_cipherbyname(%p)", algorithm);
if (algorithm == NULL) {
JNI_TRACE("EVP_get_cipherbyname(%p) => threw exception algorithm == null", algorithm);
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("EVP_get_cipherbyname(%p) => algorithm = %s", algorithm, algorithmChars.c_str());
const EVP_CIPHER* evp_cipher = EVP_get_cipherbyname(algorithmChars.c_str());
if (evp_cipher == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("EVP_get_cipherbyname(%s) => %p", algorithmChars.c_str(), evp_cipher);
return reinterpret_cast<uintptr_t>(evp_cipher);
}
static void NativeCrypto_EVP_CipherInit_ex(JNIEnv* env, jclass, jlong ctxRef, jlong evpCipherRef,
jbyteArray keyArray, jbyteArray ivArray, jboolean encrypting) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d)", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("EVP_CipherUpdate => ctx == null");
return;
}
// The key can be null if we need to set extra parameters.
UniquePtr<unsigned char[]> keyPtr;
if (keyArray != NULL) {
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
keyPtr.reset(new unsigned char[keyBytes.size()]);
memcpy(keyPtr.get(), keyBytes.get(), keyBytes.size());
}
// The IV can be null if we're using ECB.
UniquePtr<unsigned char[]> ivPtr;
if (ivArray != NULL) {
ScopedByteArrayRO ivBytes(env, ivArray);
if (ivBytes.get() == NULL) {
return;
}
ivPtr.reset(new unsigned char[ivBytes.size()]);
memcpy(ivPtr.get(), ivBytes.get(), ivBytes.size());
}
if (!EVP_CipherInit_ex(ctx, evpCipher, NULL, keyPtr.get(), ivPtr.get(), encrypting ? 1 : 0)) {
throwExceptionIfNecessary(env, "EVP_CipherInit_ex");
JNI_TRACE("EVP_CipherInit_ex => error initializing cipher");
return;
}
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d) => success", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
}
/*
* public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
* int inOffset, int inLength);
*/
static jint NativeCrypto_EVP_CipherUpdate(JNIEnv* env, jclass, jlong ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray inArray, jint inOffset, jint inLength) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d)", ctx, outArray, outOffset, inArray, inOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherUpdate => ctx == null", ctx);
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
const size_t inSize = inBytes.size();
if (size_t(inOffset + inLength) > inSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"in.length < (inSize + inOffset)");
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
const size_t outSize = outBytes.size();
if (size_t(outOffset + inLength) > outSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"out.length < inSize + outOffset + blockSize - 1");
return 0;
}
JNI_TRACE("ctx=%p EVP_CipherUpdate in=%p in.length=%d inOffset=%d inLength=%d out=%p out.length=%d outOffset=%d",
ctx, inBytes.get(), inBytes.size(), inOffset, inLength, outBytes.get(), outBytes.size(), outOffset);
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
const unsigned char* in = reinterpret_cast<const unsigned char*>(inBytes.get());
int outl;
if (!EVP_CipherUpdate(ctx, out + outOffset, &outl, in + inOffset, inLength)) {
throwExceptionIfNecessary(env, "EVP_CipherUpdate");
JNI_TRACE("ctx=%p EVP_CipherUpdate => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d) => %d", ctx, outArray, outOffset, inArray,
inOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CipherFinal_ex(JNIEnv* env, jclass, jlong ctxRef, jbyteArray outArray,
jint outOffset) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CipherFinal_ex(%p, %p, %d)", ctx, outArray, outOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => ctx == null", ctx);
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
int outl;
if (!EVP_CipherFinal_ex(ctx, out + outOffset, &outl)) {
throwExceptionIfNecessary(env, "EVP_CipherFinal_ex");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherFinal(%p, %p, %d) => %d", ctx, outArray, outOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CIPHER_iv_length(JNIEnv* env, jclass, jlong evpCipherRef) {
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CIPHER_iv_length(%p)", evpCipher);
if (evpCipher == NULL) {
jniThrowNullPointerException(env, "evpCipher == null");
JNI_TRACE("EVP_CIPHER_iv_length => evpCipher == null");
return 0;
}
const int ivLength = EVP_CIPHER_iv_length(evpCipher);
JNI_TRACE("EVP_CIPHER_iv_length(%p) => %d", evpCipher, ivLength);
return ivLength;
}
static jlong NativeCrypto_EVP_CIPHER_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("EVP_CIPHER_CTX_new()");
Unique_EVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate cipher context");
JNI_TRACE("EVP_CipherInit_ex => context allocation error");
return 0;
}
JNI_TRACE("EVP_CIPHER_CTX_new() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static jint NativeCrypto_EVP_CIPHER_CTX_block_size(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_block_size => ctx == null", ctx);
return 0;
}
int blockSize = EVP_CIPHER_CTX_block_size(ctx);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p) => %d", ctx, blockSize);
return blockSize;
}
static jint NativeCrypto_get_EVP_CIPHER_CTX_buf_len(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_buf_len => ctx == null", ctx);
return 0;
}
int buf_len = ctx->buf_len;
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p) => %d", ctx, buf_len);
return buf_len;
}
static void NativeCrypto_EVP_CIPHER_CTX_set_padding(JNIEnv* env, jclass, jlong ctxRef, jboolean enablePaddingBool) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
jint enablePadding = enablePaddingBool ? 1 : 0;
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d)", ctx, enablePadding);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_padding => ctx == null", ctx);
return;
}
EVP_CIPHER_CTX_set_padding(ctx, enablePadding); // Not void, but always returns 1.
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d) => success", ctx, enablePadding);
}
static void NativeCrypto_EVP_CIPHER_CTX_set_key_length(JNIEnv* env, jclass, jlong ctxRef,
jint keySizeBits) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d)", ctx, keySizeBits);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_key_length => ctx == null", ctx);
return;
}
if (!EVP_CIPHER_CTX_set_key_length(ctx, keySizeBits)) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_CIPHER_CTX_set_key_length");
JNI_TRACE("NativeCrypto_EVP_CIPHER_CTX_set_key_length => threw error");
return;
}
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d) => success", ctx, keySizeBits);
}
static void NativeCrypto_EVP_CIPHER_CTX_cleanup(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p)", ctx);
if (ctx != NULL) {
if (!EVP_CIPHER_CTX_cleanup(ctx)) {
throwExceptionIfNecessary(env, "EVP_CIPHER_CTX_cleanup");
JNI_TRACE("EVP_CIPHER_CTX_cleanup => threw error");
return;
}
}
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p) => success", ctx);
}
/**
* public static native void RAND_seed(byte[]);
*/
static void NativeCrypto_RAND_seed(JNIEnv* env, jclass, jbyteArray seed) {
JNI_TRACE("NativeCrypto_RAND_seed seed=%p", seed);
ScopedByteArrayRO randseed(env, seed);
if (randseed.get() == NULL) {
return;
}
RAND_seed(randseed.get(), randseed.size());
}
static jint NativeCrypto_RAND_load_file(JNIEnv* env, jclass, jstring filename, jlong max_bytes) {
JNI_TRACE("NativeCrypto_RAND_load_file filename=%p max_bytes=%lld", filename, max_bytes);
ScopedUtfChars file(env, filename);
if (file.c_str() == NULL) {
return -1;
}
int result = RAND_load_file(file.c_str(), max_bytes);
JNI_TRACE("NativeCrypto_RAND_load_file file=%s => %d", file.c_str(), result);
return result;
}
static void NativeCrypto_RAND_bytes(JNIEnv* env, jclass, jbyteArray output) {
JNI_TRACE("NativeCrypto_RAND_bytes(%p)", output);
ScopedByteArrayRW outputBytes(env, output);
if (outputBytes.get() == NULL) {
return;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(outputBytes.get());
if (RAND_bytes(tmp, outputBytes.size()) <= 0) {
throwExceptionIfNecessary(env, "NativeCrypto_RAND_bytes");
JNI_TRACE("tmp=%p NativeCrypto_RAND_bytes => threw error", tmp);
return;
}
JNI_TRACE("NativeCrypto_RAND_bytes(%p) => success", output);
}
static jint NativeCrypto_OBJ_txt2nid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return 0;
}
int nid = OBJ_txt2nid(oid.c_str());
JNI_TRACE("OBJ_txt2nid(%s) => %d", oid.c_str(), nid);
return nid;
}
static jstring NativeCrypto_OBJ_txt2nid_longName(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_longName(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_longName(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_longName(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const char* longName = OBJ_nid2ln(nid);
JNI_TRACE("OBJ_txt2nid_longName(%s) => %s", oid.c_str(), longName);
return env->NewStringUTF(longName);
}
static jstring ASN1_OBJECT_to_OID_string(JNIEnv* env, ASN1_OBJECT* obj) {
/*
* The OBJ_obj2txt API doesn't "measure" if you pass in NULL as the buffer.
* Just make a buffer that's large enough here. The documentation recommends
* 80 characters.
*/
char output[128];
int ret = OBJ_obj2txt(output, sizeof(output), obj, 1);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1_OBJECT_to_OID_string");
return NULL;
} else if (size_t(ret) >= sizeof(output)) {
jniThrowRuntimeException(env, "ASN1_OBJECT_to_OID_string buffer too small");
return NULL;
}
JNI_TRACE("ASN1_OBJECT_to_OID_string(%p) => %s", obj, output);
return env->NewStringUTF(output);
}
static jlong NativeCrypto_create_BIO_InputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_InputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_InputStream(streamObj));
JNI_TRACE("create_BIO_InputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static jlong NativeCrypto_create_BIO_OutputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_OutputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_OutputStream(streamObj));
JNI_TRACE("create_BIO_OutputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static int NativeCrypto_BIO_read(JNIEnv* env, jclass, jlong bioRef, jbyteArray outputJavaBytes) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_read(%p, %p)", bio, outputJavaBytes);
if (outputJavaBytes == NULL) {
jniThrowNullPointerException(env, "output == null");
JNI_TRACE("BIO_read(%p, %p) => output == null", bio, outputJavaBytes);
return 0;
}
int outputSize = env->GetArrayLength(outputJavaBytes);
UniquePtr<unsigned char[]> buffer(new unsigned char[outputSize]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for read");
return 0;
}
int read = BIO_read(bio, buffer.get(), outputSize);
if (read <= 0) {
jniThrowException(env, "java/io/IOException", "BIO_read");
JNI_TRACE("BIO_read(%p, %p) => threw IO exception", bio, outputJavaBytes);
return 0;
}
env->SetByteArrayRegion(outputJavaBytes, 0, read, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("BIO_read(%p, %p) => %d", bio, outputJavaBytes, read);
return read;
}
static void NativeCrypto_BIO_write(JNIEnv* env, jclass, jlong bioRef, jbyteArray inputJavaBytes,
jint offset, jint length) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_write(%p, %p, %d, %d)", bio, inputJavaBytes, offset, length);
if (inputJavaBytes == NULL) {
jniThrowNullPointerException(env, "input == null");
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "offset < 0 || length < 0");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
int inputSize = env->GetArrayLength(inputJavaBytes);
if (inputSize < offset + length) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"input.length < offset + length");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[length]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for write");
return;
}
env->GetByteArrayRegion(inputJavaBytes, offset, length, reinterpret_cast<jbyte*>(buffer.get()));
if (BIO_write(bio, buffer.get(), length) != length) {
freeOpenSslErrorState();
jniThrowException(env, "java/io/IOException", "BIO_write");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IO error", bio, inputJavaBytes, offset, length);
return;
}
JNI_TRACE("BIO_write(%p, %p, %d, %d) => success", bio, inputJavaBytes, offset, length);
}
static void NativeCrypto_BIO_free_all(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_free_all(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return;
}
BIO_free_all(bio);
}
static jstring X509_NAME_to_jstring(JNIEnv* env, X509_NAME* name, unsigned long flags) {
JNI_TRACE("X509_NAME_to_jstring(%p)", name);
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
JNI_TRACE("X509_NAME_to_jstring(%p) => threw error", name);
return NULL;
}
/* Don't interpret the string. */
flags &= ~(ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_ESC_MSB);
/* Write in given format and null terminate. */
X509_NAME_print_ex(buffer.get(), name, 0, flags);
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
JNI_TRACE("X509_NAME_to_jstring(%p) => \"%s\"", name, tmp);
return env->NewStringUTF(tmp);
}
/**
* Converts GENERAL_NAME items to the output format expected in
* X509Certificate#getSubjectAlternativeNames and
* X509Certificate#getIssuerAlternativeNames return.
*/
static jobject GENERAL_NAME_to_jobject(JNIEnv* env, GENERAL_NAME* gen) {
switch (gen->type) {
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI: {
// This must not be a T61String and must not contain NULLs.
const char* data = reinterpret_cast<const char*>(ASN1_STRING_data(gen->d.ia5));
ssize_t len = ASN1_STRING_length(gen->d.ia5);
if ((len == static_cast<ssize_t>(strlen(data)))
&& (ASN1_PRINTABLE_type(ASN1_STRING_data(gen->d.ia5), len) != V_ASN1_T61STRING)) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI \"%s\"", gen, data);
return env->NewStringUTF(data);
} else {
jniThrowException(env, "java/security/cert/CertificateParsingException",
"Invalid dNSName encoding");
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI invalid", gen);
return NULL;
}
}
case GEN_DIRNAME:
/* Write in RFC 2253 format */
return X509_NAME_to_jstring(env, gen->d.directoryName, XN_FLAG_RFC2253);
case GEN_IPADD: {
const void *ip = reinterpret_cast<const void *>(gen->d.ip->data);
if (gen->d.ip->length == 4) {
// IPv4
UniquePtr<char[]> buffer(new char[INET_ADDRSTRLEN]);
if (inet_ntop(AF_INET, ip, buffer.get(), INET_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 failed %s", gen, strerror(errno));
}
} else if (gen->d.ip->length == 16) {
// IPv6
UniquePtr<char[]> buffer(new char[INET6_ADDRSTRLEN]);
if (inet_ntop(AF_INET6, ip, buffer.get(), INET6_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 failed %s", gen, strerror(errno));
}
}
/* Invalid IP encodings are pruned out without throwing an exception. */
return NULL;
}
case GEN_RID:
return ASN1_OBJECT_to_OID_string(env, gen->d.registeredID);
case GEN_OTHERNAME:
case GEN_X400:
default:
return ASN1ToByteArray<GENERAL_NAME, i2d_GENERAL_NAME>(env, gen);
}
return NULL;
}
#define GN_STACK_SUBJECT_ALT_NAME 1
#define GN_STACK_ISSUER_ALT_NAME 2
static jobjectArray NativeCrypto_get_X509_GENERAL_NAME_stack(JNIEnv* env, jclass, jlong x509Ref,
jint type) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d)", x509, type);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => x509 == null", x509, type);
return NULL;
}
X509_check_ca(x509);
STACK_OF(GENERAL_NAME)* gn_stack;
Unique_sk_GENERAL_NAME stackHolder;
if (type == GN_STACK_SUBJECT_ALT_NAME) {
gn_stack = x509->altname;
} else if (type == GN_STACK_ISSUER_ALT_NAME) {
stackHolder.reset(
static_cast<STACK_OF(GENERAL_NAME)*>(X509_get_ext_d2i(x509, NID_issuer_alt_name,
NULL, NULL)));
gn_stack = stackHolder.get();
} else {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => unknown type", x509, type);
return NULL;
}
int count = sk_GENERAL_NAME_num(gn_stack);
if (count <= 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no entries)", x509, type);
return NULL;
}
/*
* Keep track of how many originally so we can ignore any invalid
* values later.
*/
const int origCount = count;
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, objectArrayClass, NULL));
for (int i = 0, j = 0; i < origCount; i++, j++) {
GENERAL_NAME* gen = sk_GENERAL_NAME_value(gn_stack, i);
ScopedLocalRef<jobject> val(env, GENERAL_NAME_to_jobject(env, gen));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => threw exception parsing gen name",
x509, type);
return NULL;
}
/*
* If it's NULL, we'll have to skip this, reduce the number of total
* entries, and fix up the array later.
*/
if (val.get() == NULL) {
j--;
count--;
continue;
}
ScopedLocalRef<jobjectArray> item(env, env->NewObjectArray(2, objectClass, NULL));
ScopedLocalRef<jobject> type(env, env->CallStaticObjectMethod(integerClass,
integer_valueOfMethod, gen->type));
env->SetObjectArrayElement(item.get(), 0, type.get());
env->SetObjectArrayElement(item.get(), 1, val.get());
env->SetObjectArrayElement(joa.get(), j, item.get());
}
if (count == 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to 0; returning NULL",
x509, type, origCount);
joa.reset(NULL);
} else if (origCount != count) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to %d", x509, type,
origCount, count);
ScopedLocalRef<jobjectArray> joa_copy(env, env->NewObjectArray(count, objectArrayClass,
NULL));
for (int i = 0; i < count; i++) {
ScopedLocalRef<jobject> item(env, env->GetObjectArrayElement(joa.get(), i));
env->SetObjectArrayElement(joa_copy.get(), i, item.get());
}
joa.reset(joa_copy.release());
}
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => %d entries", x509, type, count);
return joa.release();
}
static jlong NativeCrypto_X509_get_notBefore(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notBefore(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notBefore(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notBefore = X509_get_notBefore(x509);
JNI_TRACE("X509_get_notBefore(%p) => %p", x509, notBefore);
return reinterpret_cast<uintptr_t>(notBefore);
}
static jlong NativeCrypto_X509_get_notAfter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notAfter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notAfter(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notAfter = X509_get_notAfter(x509);
JNI_TRACE("X509_get_notAfter(%p) => %p", x509, notAfter);
return reinterpret_cast<uintptr_t>(notAfter);
}
static long NativeCrypto_X509_get_version(JNIEnv*, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_version(%p)", x509);
long version = X509_get_version(x509);
JNI_TRACE("X509_get_version(%p) => %ld", x509, version);
return version;
}
template<typename T>
static jbyteArray get_X509Type_serialNumber(JNIEnv* env, T* x509Type, ASN1_INTEGER* (*get_serial_func)(T*)) {
JNI_TRACE("get_X509Type_serialNumber(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_serialNumber(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_INTEGER* serialNumber = get_serial_func(x509Type);
Unique_BIGNUM serialBn(ASN1_INTEGER_to_BN(serialNumber, NULL));
if (serialBn.get() == NULL) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
ScopedLocalRef<jbyteArray> serialArray(env, bignumToArray(env, serialBn.get(), "serialBn"));
if (env->ExceptionCheck()) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
JNI_TRACE("X509_get_serialNumber(%p) => %p", x509Type, serialArray.get());
return serialArray.release();
}
/* OpenSSL includes set_serialNumber but not get. */
#if !defined(X509_REVOKED_get_serialNumber)
static ASN1_INTEGER* X509_REVOKED_get_serialNumber(X509_REVOKED* x) {
return x->serialNumber;
}
#endif
static jbyteArray NativeCrypto_X509_get_serialNumber(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_serialNumber(%p)", x509);
return get_X509Type_serialNumber<X509>(env, x509, X509_get_serialNumber);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_serialNumber(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_serialNumber(%p)", revoked);
return get_X509Type_serialNumber<X509_REVOKED>(env, revoked, X509_REVOKED_get_serialNumber);
}
static void NativeCrypto_X509_verify(JNIEnv* env, jclass, jlong x509Ref, jlong pkeyRef) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("X509_verify(%p, %p)", x509, pkey);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_verify(%p, %p) => x509 == null", x509, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_verify(%p, %p) => pkey == null", x509, pkey);
return;
}
if (X509_verify(x509, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_verify");
JNI_TRACE("X509_verify(%p, %p) => verify failure", x509, pkey);
} else {
JNI_TRACE("X509_verify(%p, %p) => verify success", x509, pkey);
}
}
static jbyteArray NativeCrypto_get_X509_cert_info_enc(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_cert_info_enc(%p)", x509);
return ASN1ToByteArray<X509_CINF, i2d_X509_CINF>(env, x509->cert_info);
}
static jint NativeCrypto_get_X509_ex_flags(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_flags(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_flags(%p) => x509 == null", x509);
return 0;
}
X509_check_ca(x509);
return x509->ex_flags;
}
static jboolean NativeCrypto_X509_check_issued(JNIEnv*, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_check_issued(%p, %p)", x509_1, x509_2);
int ret = X509_check_issued(x509_1, x509_2);
JNI_TRACE("X509_check_issued(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void get_X509_signature(X509 *x509, ASN1_BIT_STRING** signature) {
*signature = x509->signature;
}
static void get_X509_CRL_signature(X509_CRL *crl, ASN1_BIT_STRING** signature) {
*signature = crl->signature;
}
template<typename T>
static jbyteArray get_X509Type_signature(JNIEnv* env, T* x509Type, void (*get_signature_func)(T*, ASN1_BIT_STRING**)) {
JNI_TRACE("get_X509Type_signature(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_signature(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_BIT_STRING* signature;
get_signature_func(x509Type, &signature);
ScopedLocalRef<jbyteArray> signatureArray(env, env->NewByteArray(signature->length));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509Type_signature(%p) => threw exception", x509Type);
return NULL;
}
ScopedByteArrayRW signatureBytes(env, signatureArray.get());
if (signatureBytes.get() == NULL) {
JNI_TRACE("get_X509Type_signature(%p) => using byte array failed", x509Type);
return NULL;
}
memcpy(signatureBytes.get(), signature->data, signature->length);
JNI_TRACE("get_X509Type_signature(%p) => %p (%d bytes)", x509Type, signatureArray.get(),
signature->length);
return signatureArray.release();
}
static jbyteArray NativeCrypto_get_X509_signature(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_signature(%p)", x509);
return get_X509Type_signature<X509>(env, x509, get_X509_signature);
}
static jbyteArray NativeCrypto_get_X509_CRL_signature(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_signature(%p)", crl);
return get_X509Type_signature<X509_CRL>(env, crl, get_X509_CRL_signature);
}
static jlong NativeCrypto_X509_CRL_get0_by_cert(JNIEnv* env, jclass, jlong x509crlRef, jlong x509Ref) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p)", x509crl, x509);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509crl == null", x509crl, x509);
return 0;
} else if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509 == null", x509crl, x509);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_cert(x509crl, &revoked, x509);
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => none", x509crl, x509);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, x509, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
static jlong NativeCrypto_X509_CRL_get0_by_serial(JNIEnv* env, jclass, jlong x509crlRef, jbyteArray serialArray) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p)", x509crl, serialArray);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => crl == null", x509crl, serialArray);
return 0;
}
Unique_BIGNUM serialBn(BN_new());
if (serialBn.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN allocation failed", x509crl, serialArray);
return 0;
}
BIGNUM* serialBare = serialBn.get();
if (!arrayToBignum(env, serialArray, &serialBare)) {
if (!env->ExceptionCheck()) {
jniThrowNullPointerException(env, "serial == null");
}
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
Unique_ASN1_INTEGER serialInteger(BN_to_ASN1_INTEGER(serialBn.get(), NULL));
if (serialInteger.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_serial(x509crl, &revoked, serialInteger.get());
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => none", x509crl, serialArray);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, serialArray, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
/* This appears to be missing from OpenSSL. */
#if !defined(X509_REVOKED_dup)
X509_REVOKED* X509_REVOKED_dup(X509_REVOKED* x) {
return reinterpret_cast<X509_REVOKED*>(ASN1_item_dup(ASN1_ITEM_rptr(X509_REVOKED), x));
}
#endif
static jlongArray NativeCrypto_X509_CRL_get_REVOKED(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_REVOKED(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
return NULL;
}
STACK_OF(X509_REVOKED)* stack = X509_CRL_get_REVOKED(crl);
if (stack == NULL) {
JNI_TRACE("X509_CRL_get_REVOKED(%p) => stack is null", crl);
return NULL;
}
size_t size = sk_X509_REVOKED_num(stack);
ScopedLocalRef<jlongArray> revokedArray(env, env->NewLongArray(size));
ScopedLongArrayRW revoked(env, revokedArray.get());
for (size_t i = 0; i < size; i++) {
X509_REVOKED* item = reinterpret_cast<X509_REVOKED*>(sk_X509_REVOKED_value(stack, i));
revoked[i] = reinterpret_cast<uintptr_t>(X509_REVOKED_dup(item));
}
JNI_TRACE("X509_CRL_get_REVOKED(%p) => %p [size=%d]", stack, revokedArray.get(), size);
return revokedArray.release();
}
static jbyteArray NativeCrypto_i2d_X509_CRL(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("i2d_X509_CRL(%p)", crl);
return ASN1ToByteArray<X509_CRL, i2d_X509_CRL>(env, crl);
}
static void NativeCrypto_X509_CRL_free(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_free(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_free(%p) => crl == null", crl);
return;
}
X509_CRL_free(crl);
}
static void NativeCrypto_X509_CRL_print(JNIEnv* env, jclass, jlong bioRef, jlong x509CrlRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_print(%p, %p)", bio, crl);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_CRL_print(%p, %p) => bio == null", bio, crl);
return;
}
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_print(%p, %p) => crl == null", bio, crl);
return;
}
if (!X509_CRL_print(bio, crl)) {
throwExceptionIfNecessary(env, "X509_CRL_print");
JNI_TRACE("X509_CRL_print(%p, %p) => threw error", bio, crl);
} else {
JNI_TRACE("X509_CRL_print(%p, %p) => success", bio, crl);
}
}
static jstring NativeCrypto_get_X509_CRL_sig_alg_oid(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p)", crl);
if (crl == NULL || crl->sig_alg == NULL) {
jniThrowNullPointerException(env, "crl == NULL || crl->sig_alg == NULL");
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p) => crl == NULL", crl);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, crl->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_CRL_sig_alg_parameter(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => crl == null", crl);
return NULL;
}
if (crl->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => null", crl);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE, i2d_ASN1_TYPE>(env, crl->sig_alg->parameter);
}
static jbyteArray NativeCrypto_X509_CRL_get_issuer_name(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_issuer_name(%p)", crl);
return ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env, X509_CRL_get_issuer(crl));
}
static long NativeCrypto_X509_CRL_get_version(JNIEnv*, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_version(%p)", crl);
long version = X509_CRL_get_version(crl);
JNI_TRACE("X509_CRL_get_version(%p) => %ld", crl, version);
return version;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static X509_EXTENSION *X509Type_get_ext(JNIEnv* env, T* x509Type, jstring oidString) {
JNI_TRACE("X509Type_get_ext(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509 == null");
return NULL;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
return NULL;
}
Unique_ASN1_OBJECT asn1(OBJ_txt2obj(oid.c_str(), 1));
if (asn1.get() == NULL) {
JNI_TRACE("X509Type_get_ext(%p, %s) => oid conversion failed", x509Type, oid.c_str());
freeOpenSslErrorState();
return NULL;
}
int extIndex = get_ext_by_OBJ_func(x509Type, asn1.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509Type_get_ext(%p, %s) => ext not found", x509Type, oid.c_str());
return NULL;
}
X509_EXTENSION* ext = get_ext_func(x509Type, extIndex);
JNI_TRACE("X509Type_get_ext(%p, %s) => %p", x509Type, oid.c_str(), ext);
return ext;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static jbyteArray X509Type_get_ext_oid(JNIEnv* env, T* x509Type, jstring oidString) {
X509_EXTENSION* ext = X509Type_get_ext<T, get_ext_by_OBJ_func, get_ext_func>(env, x509Type,
oidString);
if (ext == NULL) {
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => fetching extension failed", x509Type, oidString);
return NULL;
}
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => %p", x509Type, oidString, ext->value);
return ASN1ToByteArray<ASN1_OCTET_STRING, i2d_ASN1_OCTET_STRING>(env, ext->value);
}
static jint NativeCrypto_X509_CRL_get_ext(JNIEnv* env, jclass, jlong x509CrlRef, jstring oid) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext(%p, %p)", crl, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(
env, crl, oid);
JNI_TRACE("X509_CRL_get_ext(%p, %p) => %p", crl, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jint NativeCrypto_X509_REVOKED_get_ext(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oid) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext(%p, %p)", revoked, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ,
X509_REVOKED_get_ext>(env, revoked, oid);
JNI_TRACE("X509_REVOKED_get_ext(%p, %p) => %p", revoked, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_dup(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_dup(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_dup(%p) => revoked == null", revoked);
return 0;
}
X509_REVOKED* dup = X509_REVOKED_dup(revoked);
JNI_TRACE("X509_REVOKED_dup(%p) => %p", revoked, dup);
return reinterpret_cast<uintptr_t>(dup);
}
static jlong NativeCrypto_get_X509_REVOKED_revocationDate(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("get_X509_REVOKED_revocationDate(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => revoked == null", revoked);
return 0;
}
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => %p", revoked, revoked->revocationDate);
return reinterpret_cast<uintptr_t>(revoked->revocationDate);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
static void NativeCrypto_X509_REVOKED_print(JNIEnv* env, jclass, jlong bioRef, jlong x509RevokedRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_print(%p, %p)", bio, revoked);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => bio == null", bio, revoked);
return;
}
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => revoked == null", bio, revoked);
return;
}
BIO_printf(bio, "Serial Number: ");
i2a_ASN1_INTEGER(bio, revoked->serialNumber);
BIO_printf(bio, "\nRevocation Date: ");
ASN1_TIME_print(bio, revoked->revocationDate);
BIO_printf(bio, "\n");
X509V3_extensions_print(bio, "CRL entry extensions", revoked->extensions, 0, 0);
}
#pragma GCC diagnostic pop
static jbyteArray NativeCrypto_get_X509_CRL_crl_enc(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_crl_enc(%p)", crl);
return ASN1ToByteArray<X509_CRL_INFO, i2d_X509_CRL_INFO>(env, crl->crl);
}
static void NativeCrypto_X509_CRL_verify(JNIEnv* env, jclass, jlong x509CrlRef, jlong pkeyRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("X509_CRL_verify(%p, %p)", crl, pkey);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => crl == null", crl, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => pkey == null", crl, pkey);
return;
}
if (X509_CRL_verify(crl, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_CRL_verify");
JNI_TRACE("X509_CRL_verify(%p, %p) => verify failure", crl, pkey);
} else {
JNI_TRACE("X509_CRL_verify(%p, %p) => verify success", crl, pkey);
}
}
static jlong NativeCrypto_X509_CRL_get_lastUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_lastUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* lastUpdate = X509_CRL_get_lastUpdate(crl);
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => %p", crl, lastUpdate);
return reinterpret_cast<uintptr_t>(lastUpdate);
}
static jlong NativeCrypto_X509_CRL_get_nextUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_nextUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* nextUpdate = X509_CRL_get_nextUpdate(crl);
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => %p", crl, nextUpdate);
return reinterpret_cast<uintptr_t>(nextUpdate);
}
static jbyteArray NativeCrypto_i2d_X509_REVOKED(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* x509Revoked =
reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("i2d_X509_REVOKED(%p)", x509Revoked);
return ASN1ToByteArray<X509_REVOKED, i2d_X509_REVOKED>(env, x509Revoked);
}
static jint NativeCrypto_X509_supported_extension(JNIEnv* env, jclass, jlong x509ExtensionRef) {
X509_EXTENSION* ext = reinterpret_cast<X509_EXTENSION*>(static_cast<uintptr_t>(x509ExtensionRef));
if (ext == NULL) {
jniThrowNullPointerException(env, "ext == NULL");
return 0;
}
return X509_supported_extension(ext);
}
static inline void get_ASN1_TIME_data(char **data, int* output, size_t len) {
char c = **data;
**data = '\0';
*data -= len;
*output = atoi(*data);
*(*data + len) = c;
}
static void NativeCrypto_ASN1_TIME_to_Calendar(JNIEnv* env, jclass, jlong asn1TimeRef, jobject calendar) {
ASN1_TIME* asn1Time = reinterpret_cast<ASN1_TIME*>(static_cast<uintptr_t>(asn1TimeRef));
JNI_TRACE("ASN1_TIME_to_Calendar(%p, %p)", asn1Time, calendar);
if (asn1Time == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
Unique_ASN1_GENERALIZEDTIME gen(ASN1_TIME_to_generalizedtime(asn1Time, NULL));
if (gen.get() == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
if (gen->length < 14 || gen->data == NULL) {
jniThrowNullPointerException(env, "gen->length < 14 || gen->data == NULL");
return;
}
int sec, min, hour, mday, mon, year;
char *p = (char*) &gen->data[14];
get_ASN1_TIME_data(&p, &sec, 2);
get_ASN1_TIME_data(&p, &min, 2);
get_ASN1_TIME_data(&p, &hour, 2);
get_ASN1_TIME_data(&p, &mday, 2);
get_ASN1_TIME_data(&p, &mon, 2);
get_ASN1_TIME_data(&p, &year, 4);
env->CallVoidMethod(calendar, calendar_setMethod, year, mon - 1, mday, hour, min, sec);
}
static jstring NativeCrypto_OBJ_txt2nid_oid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_oid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_oid(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_oid(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
Unique_ASN1_OBJECT obj(OBJ_nid2obj(nid));
if (obj.get() == NULL) {
throwExceptionIfNecessary(env, "OBJ_nid2obj");
return NULL;
}
ScopedLocalRef<jstring> ouputStr(env, ASN1_OBJECT_to_OID_string(env, obj.get()));
JNI_TRACE("OBJ_txt2nid_oid(%s) => %p", oid.c_str(), ouputStr.get());
return ouputStr.release();
}
static jstring NativeCrypto_X509_NAME_print_ex(JNIEnv* env, jclass, jlong x509NameRef, jlong jflags) {
X509_NAME* x509name = reinterpret_cast<X509_NAME*>(static_cast<uintptr_t>(x509NameRef));
unsigned long flags = static_cast<unsigned long>(jflags);
JNI_TRACE("X509_NAME_print_ex(%p, %ld)", x509name, flags);
if (x509name == NULL) {
jniThrowNullPointerException(env, "x509name == null");
JNI_TRACE("X509_NAME_print_ex(%p, %ld) => x509name == null", x509name, flags);
return NULL;
}
return X509_NAME_to_jstring(env, x509name, flags);
}
template <typename T, T* (*d2i_func)(BIO*, T**)>
static jlong d2i_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return 0;
}
T* x = d2i_func(bio, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "d2i_ASN1Object_to_jlong");
return 0;
}
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_d2i_X509_CRL_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509_CRL, d2i_X509_CRL_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509, d2i_X509_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509(JNIEnv* env, jclass, jbyteArray certBytes) {
X509* x = ByteArrayToASN1<X509, d2i_X509>(env, certBytes);
return reinterpret_cast<uintptr_t>(x);
}
static jbyteArray NativeCrypto_i2d_X509(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509(%p)", x509);
return ASN1ToByteArray<X509, i2d_X509>(env, x509);
}
static jbyteArray NativeCrypto_i2d_X509_PUBKEY(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509_PUBKEY(%p)", x509);
return ASN1ToByteArray<X509_PUBKEY, i2d_X509_PUBKEY>(env, X509_get_X509_PUBKEY(x509));
}
template<typename T, T* (*PEM_read_func)(BIO*, T**, pem_password_cb*, void*)>
static jlong PEM_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => bio == null", bio);
return 0;
}
T* x = PEM_read_func(bio, NULL, NULL, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "PEM_ASN1Object_to_jlong");
// Sometimes the PEM functions fail without pushing an error
if (!env->ExceptionCheck()) {
jniThrowRuntimeException(env, "Failure parsing PEM");
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => threw exception", bio);
return 0;
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => %p", bio, x);
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_PEM_read_bio_X509(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509(0x%llx)", bioRef);
return PEM_ASN1Object_to_jlong<X509, PEM_read_bio_X509>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_X509_CRL(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509_CRL(0x%llx)", bioRef);
return PEM_ASN1Object_to_jlong<X509_CRL, PEM_read_bio_X509_CRL>(env, bioRef);
}
static STACK_OF(X509)* PKCS7_get_certs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->cert;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->cert;
} else {
JNI_TRACE("PKCS7_get_certs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
static STACK_OF(X509_CRL)* PKCS7_get_CRLs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->crl;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->crl;
} else {
JNI_TRACE("PKCS7_get_CRLs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
template <typename T, typename T_stack>
static jlongArray PKCS7_to_ItemArray(JNIEnv* env, T_stack* stack, T* (*dup_func)(T*))
{
if (stack == NULL) {
return NULL;
}
ScopedLocalRef<jlongArray> ref_array(env, NULL);
size_t size = sk_num(reinterpret_cast<_STACK*>(stack));
ref_array.reset(env->NewLongArray(size));
ScopedLongArrayRW items(env, ref_array.get());
for (size_t i = 0; i < size; i++) {
T* item = reinterpret_cast<T*>(sk_value(reinterpret_cast<_STACK*>(stack), i));
items[i] = reinterpret_cast<uintptr_t>(dup_func(item));
}
JNI_TRACE("PKCS7_to_ItemArray(%p) => %p [size=%d]", stack, ref_array.get(), size);
return ref_array.release();
}
#define PKCS7_CERTS 1
#define PKCS7_CRLS 2
static jlongArray NativeCrypto_PEM_read_bio_PKCS7(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => bio == null", bio);
return 0;
}
Unique_PKCS7 pkcs7(PEM_read_bio_PKCS7(bio, NULL, NULL, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "PEM_read_bio_PKCS7_CRLs");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => threw exception", bio);
return 0;
}
switch (which) {
case PKCS7_CERTS:
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
}
static jlongArray NativeCrypto_d2i_PKCS7_bio(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_PKCS7_bio(%p, %d)", bio, which);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => bio == null", bio, which);
return 0;
}
Unique_PKCS7 pkcs7(d2i_PKCS7_bio(bio, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS7_bio");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => threw exception", bio, which);
return 0;
}
switch (which) {
case PKCS7_CERTS:
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
}
static jbyteArray NativeCrypto_i2d_PKCS7(JNIEnv* env, jclass, jlongArray certsArray) {
JNI_TRACE("i2d_PKCS7(%p)", certsArray);
Unique_PKCS7 pkcs7(PKCS7_new());
if (pkcs7.get() == NULL) {
jniThrowNullPointerException(env, "pkcs7 == null");
JNI_TRACE("i2d_PKCS7(%p) => pkcs7 == null", certsArray);
return NULL;
}
if (PKCS7_set_type(pkcs7.get(), NID_pkcs7_signed) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type");
return NULL;
}
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (PKCS7_add_certificate(pkcs7.get(), item) != 1) {
throwExceptionIfNecessary(env, "i2d_PKCS7");
return NULL;
}
}
JNI_TRACE("i2d_PKCS7(%p) => %d certs", certsArray, certs.size());
return ASN1ToByteArray<PKCS7, i2d_PKCS7>(env, pkcs7.get());
}
typedef STACK_OF(X509) PKIPATH;
ASN1_ITEM_TEMPLATE(PKIPATH) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PkiPath, X509)
ASN1_ITEM_TEMPLATE_END(PKIPATH)
static jlongArray NativeCrypto_ASN1_seq_unpack_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p)", bio);
Unique_sk_X509 path((PKIPATH*) ASN1_item_d2i_bio(ASN1_ITEM_rptr(PKIPATH), bio, NULL));
if (path.get() == NULL) {
throwExceptionIfNecessary(env, "ASN1_seq_unpack_X509_bio");
return NULL;
}
size_t size = sk_X509_num(path.get());
ScopedLocalRef<jlongArray> certArray(env, env->NewLongArray(size));
ScopedLongArrayRW certs(env, certArray.get());
for (size_t i = 0; i < size; i++) {
X509* item = reinterpret_cast<X509*>(sk_X509_shift(path.get()));
certs[i] = reinterpret_cast<uintptr_t>(item);
}
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => returns %d items", bio, size);
return certArray.release();
}
static jbyteArray NativeCrypto_ASN1_seq_pack_X509(JNIEnv* env, jclass, jlongArray certs) {
JNI_TRACE("ASN1_seq_pack_X509(%p)", certs);
ScopedLongArrayRO certsArray(env, certs);
if (certsArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to get certs array", certs);
return NULL;
}
Unique_sk_X509 certStack(sk_X509_new_null());
if (certStack.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to make cert stack", certs);
return NULL;
}
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
sk_X509_push(certStack.get(), X509_dup_nocopy(x509));
}
int len;
Unique_OPENSSL_str encoded(ASN1_seq_pack(
reinterpret_cast<STACK_OF(OPENSSL_BLOCK)*>(
reinterpret_cast<uintptr_t>(certStack.get())),
reinterpret_cast<int (*)(void*, unsigned char**)>(i2d_X509), NULL, &len));
if (encoded.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => trouble encoding", certs);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(len));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => creating byte array failed", certs);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => using byte array failed", certs);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
memcpy(p, encoded.get(), len);
return byteArray.release();
}
static void NativeCrypto_X509_free(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_free(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_free(%p) => x509 == null", x509);
return;
}
X509_free(x509);
}
static jint NativeCrypto_X509_cmp(JNIEnv* env, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_cmp(%p, %p)", x509_1, x509_2);
if (x509_1 == NULL) {
jniThrowNullPointerException(env, "x509_1 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_1 == null", x509_1, x509_2);
return -1;
}
if (x509_2 == NULL) {
jniThrowNullPointerException(env, "x509_2 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_2 == null", x509_1, x509_2);
return -1;
}
int ret = X509_cmp(x509_1, x509_2);
JNI_TRACE("X509_cmp(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static jint NativeCrypto_get_X509_hashCode(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_hashCode(%p) => x509 == null", x509);
return 0;
}
// Force caching extensions.
X509_check_ca(x509);
jint hashCode = 0L;
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
hashCode = 31 * hashCode + x509->sha1_hash[i];
}
return hashCode;
}
static void NativeCrypto_X509_print_ex(JNIEnv* env, jclass, jlong bioRef, jlong x509Ref,
jlong nmflagJava, jlong certflagJava) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
long nmflag = static_cast<long>(nmflagJava);
long certflag = static_cast<long>(certflagJava);
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld)", bio, x509, nmflag, certflag);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => bio == null", bio, x509, nmflag, certflag);
return;
}
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => x509 == null", bio, x509, nmflag, certflag);
return;
}
if (!X509_print_ex(bio, x509, nmflag, certflag)) {
throwExceptionIfNecessary(env, "X509_print_ex");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => threw error", bio, x509, nmflag, certflag);
} else {
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => success", bio, x509, nmflag, certflag);
}
}
static jlong NativeCrypto_X509_get_pubkey(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_pubkey(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_pubkey(%p) => x509 == null", x509);
return 0;
}
Unique_EVP_PKEY pkey(X509_get_pubkey(x509));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "X509_get_pubkey");
return 0;
}
JNI_TRACE("X509_get_pubkey(%p) => %p", x509, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jbyteArray NativeCrypto_X509_get_issuer_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_issuer_name(%p)", x509);
return ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env, X509_get_issuer_name(x509));
}
static jbyteArray NativeCrypto_X509_get_subject_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_subject_name(%p)", x509);
return ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env, X509_get_subject_name(x509));
}
static jstring NativeCrypto_get_X509_pubkey_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_pubkey_oid(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_pubkey_oid(%p) => x509 == null", x509);
return NULL;
}
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
return ASN1_OBJECT_to_OID_string(env, pubkey->algor->algorithm);
}
static jstring NativeCrypto_get_X509_sig_alg_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_oid(%p)", x509);
if (x509 == NULL || x509->sig_alg == NULL) {
jniThrowNullPointerException(env, "x509 == NULL || x509->sig_alg == NULL");
JNI_TRACE("get_X509_sig_alg_oid(%p) => x509 == NULL", x509);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, x509->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_sig_alg_parameter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_parameter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_sig_alg_parameter(%p) => x509 == null", x509);
return NULL;
}
if (x509->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_sig_alg_parameter(%p) => null", x509);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE, i2d_ASN1_TYPE>(env, x509->sig_alg->parameter);
}
static jbooleanArray NativeCrypto_get_X509_issuerUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_issuerUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_issuerUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->issuerUID == NULL) {
JNI_TRACE("get_X509_issuerUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->issuerUID);
}
static jbooleanArray NativeCrypto_get_X509_subjectUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_subjectUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_subjectUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->subjectUID == NULL) {
JNI_TRACE("get_X509_subjectUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->subjectUID);
}
static jbooleanArray NativeCrypto_get_X509_ex_kusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_kusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_kusage(%p) => x509 == null", x509);
return NULL;
}
Unique_ASN1_BIT_STRING bitStr(static_cast<ASN1_BIT_STRING*>(
X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL)));
if (bitStr.get() == NULL) {
JNI_TRACE("get_X509_ex_kusage(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, bitStr.get());
}
static jobjectArray NativeCrypto_get_X509_ex_xkusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_xkusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_xkusage(%p) => x509 == null", x509);
return NULL;
}
Unique_sk_ASN1_OBJECT objArray(static_cast<STACK_OF(ASN1_OBJECT)*>(
X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL)));
if (objArray.get() == NULL) {
JNI_TRACE("get_X509_ex_xkusage(%p) => null", x509);
return NULL;
}
size_t size = sk_ASN1_OBJECT_num(objArray.get());
ScopedLocalRef<jobjectArray> exKeyUsage(env, env->NewObjectArray(size, stringClass, NULL));
if (exKeyUsage.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
ScopedLocalRef<jstring> oidStr(env, ASN1_OBJECT_to_OID_string(env,
sk_ASN1_OBJECT_value(objArray.get(), i)));
env->SetObjectArrayElement(exKeyUsage.get(), i, oidStr.get());
}
JNI_TRACE("get_X509_ex_xkusage(%p) => success (%d entries)", x509, size);
return exKeyUsage.release();
}
static jint NativeCrypto_get_X509_ex_pathlen(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_pathlen(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_pathlen(%p) => x509 == null", x509);
return 0;
}
/* Just need to do this to cache the ex_* values. */
X509_check_ca(x509);
JNI_TRACE("get_X509_ex_pathlen(%p) => %ld", x509, x509->ex_pathlen);
return x509->ex_pathlen;
}
static jbyteArray NativeCrypto_X509_get_ext_oid(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_ext_oid(%p, %p)", x509, oidString);
return X509Type_get_ext_oid<X509, X509_get_ext_by_OBJ, X509_get_ext>(env, x509, oidString);
}
static jbyteArray NativeCrypto_X509_CRL_get_ext_oid(JNIEnv* env, jclass, jlong x509CrlRef,
jstring oidString) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext_oid(%p, %p)", crl, oidString);
return X509Type_get_ext_oid<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(env, crl,
oidString);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_ext_oid(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oidString) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext_oid(%p, %p)", revoked, oidString);
return X509Type_get_ext_oid<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ, X509_REVOKED_get_ext>(
env, revoked, oidString);
}
template<typename T, int (*get_ext_by_critical_func)(T*, int, int), X509_EXTENSION* (*get_ext_func)(T*, int)>
static jobjectArray get_X509Type_ext_oids(JNIEnv* env, jlong x509Ref, jint critical) {
T* x509 = reinterpret_cast<T*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509Type_ext_oids(%p, %d)", x509, critical);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => x509 == null", x509, critical);
return NULL;
}
int lastPos = -1;
int count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
count++;
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) has %d entries", x509, critical, count);
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, stringClass, NULL));
if (joa.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => fail to allocate result array", x509, critical);
return NULL;
}
lastPos = -1;
count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
X509_EXTENSION* ext = get_ext_func(x509, lastPos);
ScopedLocalRef<jstring> extOid(env, ASN1_OBJECT_to_OID_string(env, ext->object));
if (extOid.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p) => couldn't get OID", x509);
return NULL;
}
env->SetObjectArrayElement(joa.get(), count++, extOid.get());
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => success", x509, critical);
return joa.release();
}
static jobjectArray NativeCrypto_get_X509_ext_oids(JNIEnv* env, jclass, jlong x509Ref,
jint critical) {
JNI_TRACE("get_X509_ext_oids(0x%llx, %d)", x509Ref, critical);
return get_X509Type_ext_oids<X509, X509_get_ext_by_critical, X509_get_ext>(env, x509Ref,
critical);
}
static jobjectArray NativeCrypto_get_X509_CRL_ext_oids(JNIEnv* env, jclass, jlong x509CrlRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", x509CrlRef, critical);
return get_X509Type_ext_oids<X509_CRL, X509_CRL_get_ext_by_critical, X509_CRL_get_ext>(env,
x509CrlRef, critical);
}
static jobjectArray NativeCrypto_get_X509_REVOKED_ext_oids(JNIEnv* env, jclass, jlong x509RevokedRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", x509RevokedRef, critical);
return get_X509Type_ext_oids<X509_REVOKED, X509_REVOKED_get_ext_by_critical,
X509_REVOKED_get_ext>(env, x509RevokedRef, critical);
}
#ifdef WITH_JNI_TRACE
/**
* Based on example logging call back from SSL_CTX_set_info_callback man page
*/
static void info_callback_LOG(const SSL* s __attribute__ ((unused)), int where, int ret)
{
int w = where & ~SSL_ST_MASK;
const char* str;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
} else {
str = "undefined";
}
if (where & SSL_CB_LOOP) {
JNI_TRACE("ssl=%p %s:%s %s", s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
JNI_TRACE("ssl=%p SSL3 alert %s:%s:%s %s %s",
s,
str,
SSL_alert_type_string(ret),
SSL_alert_desc_string(ret),
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
JNI_TRACE("ssl=%p %s:failed exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret < 0) {
JNI_TRACE("ssl=%p %s:error exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret == 1) {
JNI_TRACE("ssl=%p %s:ok exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown exit %d in %s %s",
s, str, ret, SSL_state_string(s), SSL_state_string_long(s));
}
} else if (where & SSL_CB_HANDSHAKE_START) {
JNI_TRACE("ssl=%p handshake start in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_HANDSHAKE_DONE) {
JNI_TRACE("ssl=%p handshake done in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown where %d in %s %s",
s, str, where, SSL_state_string(s), SSL_state_string_long(s));
}
}
#endif
/**
* Returns an array containing all the X509 certificate references
*/
static jlongArray getCertificateRefs(JNIEnv* env, const STACK_OF(X509)* chain)
{
if (chain == NULL) {
// Chain can be NULL if the associated cipher doesn't do certs.
return NULL;
}
ssize_t count = sk_X509_num(chain);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jlongArray> refArray(env, env->NewLongArray(count));
ScopedLongArrayRW refs(env, refArray.get());
if (refs.get() == NULL) {
return NULL;
}
for (ssize_t i = 0; i < count; i++) {
refs[i] = reinterpret_cast<uintptr_t>(X509_dup_nocopy(sk_X509_value(chain, i)));
}
return refArray.release();
}
/**
* Returns an array containing all the X500 principal's bytes.
*/
static jobjectArray getPrincipalBytes(JNIEnv* env, const STACK_OF(X509_NAME)* names)
{
if (names == NULL) {
return NULL;
}
int count = sk_X509_NAME_num(names);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, byteArrayClass, NULL));
if (joa.get() == NULL) {
return NULL;
}
for (int i = 0; i < count; i++) {
X509_NAME* principal = sk_X509_NAME_value(names, i);
ScopedLocalRef<jbyteArray> byteArray(env, ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env,
principal));
if (byteArray.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(joa.get(), i, byteArray.get());
}
return joa.release();
}
/**
* Our additional application data needed for getting synchronization right.
* This maybe warrants a bit of lengthy prose:
*
* (1) We use a flag to reflect whether we consider the SSL connection alive.
* Any read or write attempt loops will be cancelled once this flag becomes 0.
*
* (2) We use an int to count the number of threads that are blocked by the
* underlying socket. This may be at most two (one reader and one writer), since
* the Java layer ensures that no more threads will enter the native code at the
* same time.
*
* (3) The pipe is used primarily as a means of cancelling a blocking select()
* when we want to close the connection (aka "emergency button"). It is also
* necessary for dealing with a possible race condition situation: There might
* be cases where both threads see an SSL_ERROR_WANT_READ or
* SSL_ERROR_WANT_WRITE. Both will enter a select() with the proper argument.
* If one leaves the select() successfully before the other enters it, the
* "success" event is already consumed and the second thread will be blocked,
* possibly forever (depending on network conditions).
*
* The idea for solving the problem looks like this: Whenever a thread is
* successful in moving around data on the network, and it knows there is
* another thread stuck in a select(), it will write a byte to the pipe, waking
* up the other thread. A thread that returned from select(), on the other hand,
* knows whether it's been woken up by the pipe. If so, it will consume the
* byte, and the original state of affairs has been restored.
*
* The pipe may seem like a bit of overhead, but it fits in nicely with the
* other file descriptors of the select(), so there's only one condition to wait
* for.
*
* (4) Finally, a mutex is needed to make sure that at most one thread is in
* either SSL_read() or SSL_write() at any given time. This is an OpenSSL
* requirement. We use the same mutex to guard the field for counting the
* waiting threads.
*
* Note: The current implementation assumes that we don't have to deal with
* problems induced by multiple cores or processors and their respective
* memory caches. One possible problem is that of inconsistent views on the
* "aliveAndKicking" field. This could be worked around by also enclosing all
* accesses to that field inside a lock/unlock sequence of our mutex, but
* currently this seems a bit like overkill. Marking volatile at the very least.
*
* During handshaking, additional fields are used to up-call into
* Java to perform certificate verification and handshake
* completion. These are also used in any renegotiation.
*
* (5) the JNIEnv so we can invoke the Java callback
*
* (6) a NativeCrypto.SSLHandshakeCallbacks instance for callbacks from native to Java
*
* (7) a java.io.FileDescriptor wrapper to check for socket close
*
* We store the NPN protocols list so we can either send it (from the server) or
* select a protocol (on the client). We eagerly acquire a pointer to the array
* data so the callback doesn't need to acquire resources that it cannot
* release.
*
* Because renegotiation can be requested by the peer at any time,
* care should be taken to maintain an appropriate JNIEnv on any
* downcall to openssl since it could result in an upcall to Java. The
* current code does try to cover these cases by conditionally setting
* the JNIEnv on calls that can read and write to the SSL such as
* SSL_do_handshake, SSL_read, SSL_write, and SSL_shutdown.
*
* Finally, we have two emphemeral keys setup by OpenSSL callbacks:
*
* (8) a set of ephemeral RSA keys that is lazily generated if a peer
* wants to use an exportable RSA cipher suite.
*
* (9) a set of ephemeral EC keys that is lazily generated if a peer
* wants to use an TLS_ECDHE_* cipher suite.
*
*/
class AppData {
public:
volatile int aliveAndKicking;
int waitingThreads;
int fdsEmergency[2];
MUTEX_TYPE mutex;
JNIEnv* env;
jobject sslHandshakeCallbacks;
jbyteArray npnProtocolsArray;
jbyte* npnProtocolsData;
size_t npnProtocolsLength;
jbyteArray alpnProtocolsArray;
jbyte* alpnProtocolsData;
size_t alpnProtocolsLength;
Unique_RSA ephemeralRsa;
Unique_EC_KEY ephemeralEc;
/**
* Creates the application data context for the SSL*.
*/
public:
static AppData* create() {
UniquePtr<AppData> appData(new AppData());
if (pipe(appData.get()->fdsEmergency) == -1) {
ALOGE("AppData::create pipe(2) failed: %s", strerror(errno));
return NULL;
}
if (!setBlocking(appData.get()->fdsEmergency[0], false)) {
ALOGE("AppData::create fcntl(2) failed: %s", strerror(errno));
return NULL;
}
if (MUTEX_SETUP(appData.get()->mutex) == -1) {
ALOGE("pthread_mutex_init(3) failed: %s", strerror(errno));
return NULL;
}
return appData.release();
}
~AppData() {
aliveAndKicking = 0;
if (fdsEmergency[0] != -1) {
close(fdsEmergency[0]);
}
if (fdsEmergency[1] != -1) {
close(fdsEmergency[1]);
}
clearCallbackState();
MUTEX_CLEANUP(mutex);
}
private:
AppData() :
aliveAndKicking(1),
waitingThreads(0),
env(NULL),
sslHandshakeCallbacks(NULL),
npnProtocolsArray(NULL),
npnProtocolsData(NULL),
npnProtocolsLength(-1),
alpnProtocolsArray(NULL),
alpnProtocolsData(NULL),
alpnProtocolsLength(-1),
ephemeralRsa(NULL),
ephemeralEc(NULL) {
fdsEmergency[0] = -1;
fdsEmergency[1] = -1;
}
public:
/**
* Used to set the SSL-to-Java callback state before each SSL_*
* call that may result in a callback. It should be cleared after
* the operation returns with clearCallbackState.
*
* @param env The JNIEnv
* @param shc The SSLHandshakeCallbacks
* @param fd The FileDescriptor
* @param npnProtocols NPN protocols so that they may be advertised (by the
* server) or selected (by the client). Has no effect
* unless NPN is enabled.
* @param alpnProtocols ALPN protocols so that they may be advertised (by the
* server) or selected (by the client). Passing non-NULL
* enables ALPN.
*/
bool setCallbackState(JNIEnv* e, jobject shc, jobject fd, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
UniquePtr<NetFd> netFd;
if (fd != NULL) {
netFd.reset(new NetFd(e, fd));
if (netFd->isClosed()) {
return false;
}
}
env = e;
sslHandshakeCallbacks = shc;
if (npnProtocols != NULL) {
npnProtocolsData = e->GetByteArrayElements(npnProtocols, NULL);
if (npnProtocolsData == NULL) {
clearCallbackState();
return false;
}
npnProtocolsArray = npnProtocols;
npnProtocolsLength = e->GetArrayLength(npnProtocols);
}
if (alpnProtocols != NULL) {
alpnProtocolsData = e->GetByteArrayElements(alpnProtocols, NULL);
if (alpnProtocolsData == NULL) {
clearCallbackState();
return false;
}
alpnProtocolsArray = alpnProtocols;
alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
}
return true;
}
void clearCallbackState() {
sslHandshakeCallbacks = NULL;
if (npnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(npnProtocolsArray, npnProtocolsData, JNI_ABORT);
npnProtocolsArray = NULL;
npnProtocolsData = NULL;
npnProtocolsLength = -1;
}
if (alpnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(alpnProtocolsArray, alpnProtocolsData, JNI_ABORT);
alpnProtocolsArray = NULL;
alpnProtocolsData = NULL;
alpnProtocolsLength = -1;
}
env = NULL;
}
};
/**
* Dark magic helper function that checks, for a given SSL session, whether it
* can SSL_read() or SSL_write() without blocking. Takes into account any
* concurrent attempts to close the SSLSocket from the Java side. This is
* needed to get rid of the hangs that occur when thread #1 closes the SSLSocket
* while thread #2 is sitting in a blocking read or write. The type argument
* specifies whether we are waiting for readability or writability. It expects
* to be passed either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, since we
* only need to wait in case one of these problems occurs.
*
* @param env
* @param type Either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
* @param fdObject The FileDescriptor, since appData->fileDescriptor should be NULL
* @param appData The application data structure with mutex info etc.
* @param timeout_millis The timeout value for select call, with the special value
* 0 meaning no timeout at all (wait indefinitely). Note: This is
* the Java semantics of the timeout value, not the usual
* select() semantics.
* @return The result of the inner select() call,
* THROW_SOCKETEXCEPTION if a SocketException was thrown, -1 on
* additional errors
*/
static int sslSelect(JNIEnv* env, int type, jobject fdObject, AppData* appData, int timeout_millis) {
// This loop is an expanded version of the NET_FAILURE_RETRY
// macro. It cannot simply be used in this case because select
// cannot be restarted without recreating the fd_sets and timeout
// structure.
int result;
fd_set rfds;
fd_set wfds;
do {
NetFd fd(env, fdObject);
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
int intFd = fd.get();
JNI_TRACE("sslSelect type=%s fd=%d appData=%p timeout_millis=%d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE", intFd, appData, timeout_millis);
FD_ZERO(&rfds);
FD_ZERO(&wfds);
if (type == SSL_ERROR_WANT_READ) {
FD_SET(intFd, &rfds);
} else {
FD_SET(intFd, &wfds);
}
FD_SET(appData->fdsEmergency[0], &rfds);
int maxFd = (intFd > appData->fdsEmergency[0]) ? intFd : appData->fdsEmergency[0];
// Build a struct for the timeout data if we actually want a timeout.
timeval tv;
timeval* ptv;
if (timeout_millis > 0) {
tv.tv_sec = timeout_millis / 1000;
tv.tv_usec = (timeout_millis % 1000) * 1000;
ptv = &tv;
} else {
ptv = NULL;
}
AsynchronousCloseMonitor monitor(intFd);
result = select(maxFd + 1, &rfds, &wfds, NULL, ptv);
JNI_TRACE("sslSelect %s fd=%d appData=%p timeout_millis=%d => %d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE",
fd.get(), appData, timeout_millis, result);
if (result == -1) {
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
if (errno != EINTR) {
break;
}
}
} while (result == -1);
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (result > 0) {
// We have been woken up by a token in the emergency pipe. We
// can't be sure the token is still in the pipe at this point
// because it could have already been read by the thread that
// originally wrote it if it entered sslSelect and acquired
// the mutex before we did. Thus we cannot safely read from
// the pipe in a blocking way (so we make the pipe
// non-blocking at creation).
if (FD_ISSET(appData->fdsEmergency[0], &rfds)) {
char token;
do {
read(appData->fdsEmergency[0], &token, 1);
} while (errno == EINTR);
}
}
// Tell the world that there is now one thread less waiting for the
// underlying network.
appData->waitingThreads--;
MUTEX_UNLOCK(appData->mutex);
return result;
}
/**
* Helper function that wakes up a thread blocked in select(), in case there is
* one. Is being called by sslRead() and sslWrite() as well as by JNI glue
* before closing the connection.
*
* @param data The application data structure with mutex info etc.
*/
static void sslNotify(AppData* appData) {
// Write a byte to the emergency pipe, so a concurrent select() can return.
// Note we have to restore the errno of the original system call, since the
// caller relies on it for generating error messages.
int errnoBackup = errno;
char token = '*';
do {
errno = 0;
write(appData->fdsEmergency[1], &token, 1);
} while (errno == EINTR);
errno = errnoBackup;
}
static AppData* toAppData(const SSL* ssl) {
return reinterpret_cast<AppData*>(SSL_get_app_data(ssl));
}
/**
* Verify the X509 certificate via SSL_CTX_set_cert_verify_callback
*/
static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg __attribute__ ((unused)))
{
/* Get the correct index to the SSLobject stored into X509_STORE_CTX. */
SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_store_ctx,
SSL_get_ex_data_X509_STORE_CTX_idx()));
JNI_TRACE("ssl=%p cert_verify_callback x509_store_ctx=%p arg=%p", ssl, x509_store_ctx, arg);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in cert_verify_callback");
JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "verifyCertificateChain", "(J[JLjava/lang/String;)V");
jlongArray refArray = getCertificateRefs(env, x509_store_ctx->untrusted);
const char* authMethod = SSL_authentication_method(ssl);
JNI_TRACE("ssl=%p cert_verify_callback calling verifyCertificateChain authMethod=%s",
ssl, authMethod);
jstring authMethodString = env->NewStringUTF(authMethod);
env->CallVoidMethod(sslHandshakeCallbacks, methodID,
static_cast<jlong>(reinterpret_cast<uintptr_t>(SSL_get1_session(ssl))), refArray,
authMethodString);
int result = (env->ExceptionCheck()) ? 0 : 1;
JNI_TRACE("ssl=%p cert_verify_callback => %d", ssl, result);
return result;
}
/**
* Call back to watch for handshake to be completed. This is necessary
* for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake
* returns before the handshake is completed in this case.
*/
static void info_callback(const SSL* ssl, int where, int ret) {
JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret);
#ifdef WITH_JNI_TRACE
info_callback_LOG(ssl, where, ret);
#endif
if (!(where & SSL_CB_HANDSHAKE_DONE) && !(where & SSL_CB_HANDSHAKE_START)) {
JNI_TRACE("ssl=%p info_callback ignored", ssl);
return;
}
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in info_callback");
JNI_TRACE("ssl=%p info_callback env error", ssl);
return;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback already pending exception", ssl);
return;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(cls, "onSSLStateChange", "(JII)V");
JNI_TRACE("ssl=%p info_callback calling onSSLStateChange", ssl);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, reinterpret_cast<jlong>(ssl), where, ret);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback exception", ssl);
}
JNI_TRACE("ssl=%p info_callback completed", ssl);
}
/**
* Call back to ask for a client certificate. There are three possible exit codes:
*
* 1 is success. x509Out and pkeyOut should point to the correct private key and certificate.
* 0 is unable to find key. x509Out and pkeyOut should be NULL.
* -1 is error and it doesn't matter what x509Out and pkeyOut are.
*/
static int client_cert_cb(SSL* ssl, X509** x509Out, EVP_PKEY** pkeyOut) {
JNI_TRACE("ssl=%p client_cert_cb x509Out=%p pkeyOut=%p", ssl, x509Out, pkeyOut);
/* Clear output of key and certificate in case of early exit due to error. */
*x509Out = NULL;
*pkeyOut = NULL;
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in client_cert_cb");
JNI_TRACE("ssl=%p client_cert_cb env error => 0", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb already pending exception => 0", ssl);
return -1;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "clientCertificateRequested", "([B[[B)V");
// Call Java callback which can use SSL_use_certificate and SSL_use_PrivateKey to set values
char ssl2_ctype = SSL3_CT_RSA_SIGN;
const char* ctype = NULL;
int ctype_num = 0;
jobjectArray issuers = NULL;
switch (ssl->version) {
case SSL2_VERSION:
ctype = &ssl2_ctype;
ctype_num = 1;
break;
case SSL3_VERSION:
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
case DTLS1_VERSION:
ctype = ssl->s3->tmp.ctype;
ctype_num = ssl->s3->tmp.ctype_num;
issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
break;
}
#ifdef WITH_JNI_TRACE
for (int i = 0; i < ctype_num; i++) {
JNI_TRACE("ssl=%p clientCertificateRequested keyTypes[%d]=%d", ssl, i, ctype[i]);
}
#endif
jbyteArray keyTypes = env->NewByteArray(ctype_num);
if (keyTypes == NULL) {
JNI_TRACE("ssl=%p client_cert_cb bytes == null => 0", ssl);
return 0;
}
env->SetByteArrayRegion(keyTypes, 0, ctype_num, reinterpret_cast<const jbyte*>(ctype));
JNI_TRACE("ssl=%p clientCertificateRequested calling clientCertificateRequested "
"keyTypes=%p issuers=%p", ssl, keyTypes, issuers);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, keyTypes, issuers);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb exception => 0", ssl);
return -1;
}
// Check for values set from Java
X509* certificate = SSL_get_certificate(ssl);
EVP_PKEY* privatekey = SSL_get_privatekey(ssl);
int result = 0;
if (certificate != NULL && privatekey != NULL) {
*x509Out = certificate;
*pkeyOut = privatekey;
result = 1;
} else {
// Some error conditions return NULL, so make sure it doesn't linger.
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p client_cert_cb => *x509=%p *pkey=%p %d", ssl, *x509Out, *pkeyOut, result);
return result;
}
static RSA* rsaGenerateKey(int keylength) {
Unique_BIGNUM bn(BN_new());
if (bn.get() == NULL) {
return NULL;
}
int setWordResult = BN_set_word(bn.get(), RSA_F4);
if (setWordResult != 1) {
return NULL;
}
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
return NULL;
}
int generateResult = RSA_generate_key_ex(rsa.get(), keylength, bn.get(), NULL);
if (generateResult != 1) {
return NULL;
}
return rsa.release();
}
/**
* Call back to ask for an ephemeral RSA key for SSL_RSA_EXPORT_WITH_RC4_40_MD5 (aka EXP-RC4-MD5)
*/
static RSA* tmp_rsa_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_rsa_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralRsa.get() == NULL) {
JNI_TRACE("ssl=%p tmp_rsa_callback generating ephemeral RSA key", ssl);
appData->ephemeralRsa.reset(rsaGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_rsa_callback => %p", ssl, appData->ephemeralRsa.get());
return appData->ephemeralRsa.get();
}
static DH* dhGenerateParameters(int keylength) {
/*
* The SSL_CTX_set_tmp_dh_callback(3SSL) man page discusses two
* different options for generating DH keys. One is generating the
* keys using a single set of DH parameters. However, generating
* DH parameters is slow enough (minutes) that they suggest doing
* it once at install time. The other is to generate DH keys from
* DSA parameters. Generating DSA parameters is faster than DH
* parameters, but to prevent small subgroup attacks, they needed
* to be regenerated for each set of DH keys. Setting the
* SSL_OP_SINGLE_DH_USE option make sure OpenSSL will call back
* for new DH parameters every type it needs to generate DH keys.
*/
#if 0
// Slow path that takes minutes but could be cached
Unique_DH dh(DH_new());
if (!DH_generate_parameters_ex(dh.get(), keylength, 2, NULL)) {
return NULL;
}
return dh.release();
#else
// Faster path but must have SSL_OP_SINGLE_DH_USE set
Unique_DSA dsa(DSA_new());
if (!DSA_generate_parameters_ex(dsa.get(), keylength, NULL, 0, NULL, NULL, NULL)) {
return NULL;
}
DH* dh = DSA_dup_DH(dsa.get());
return dh;
#endif
}
/**
* Call back to ask for Diffie-Hellman parameters
*/
static DH* tmp_dh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_dh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
DH* tmp_dh = dhGenerateParameters(keylength);
JNI_TRACE("ssl=%p tmp_dh_callback => %p", ssl, tmp_dh);
return tmp_dh;
}
static EC_KEY* ecGenerateKey(int keylength __attribute__ ((unused))) {
// TODO selected curve based on keylength
Unique_EC_KEY ec(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (ec.get() == NULL) {
return NULL;
}
return ec.release();
}
/**
* Call back to ask for an ephemeral EC key for TLS_ECDHE_* cipher suites
*/
static EC_KEY* tmp_ecdh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_ecdh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralEc.get() == NULL) {
JNI_TRACE("ssl=%p tmp_ecdh_callback generating ephemeral EC key", ssl);
appData->ephemeralEc.reset(ecGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_ecdh_callback => %p", ssl, appData->ephemeralEc.get());
return appData->ephemeralEc.get();
}
/*
* public static native int SSL_CTX_new();
*/
static jlong NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass) {
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
if (sslCtx.get() == NULL) {
throwExceptionIfNecessary(env, "SSL_CTX_new");
return 0;
}
SSL_CTX_set_options(sslCtx.get(),
SSL_OP_ALL
// Note: We explicitly do not allow SSLv2 to be used.
| SSL_OP_NO_SSLv2
// We also disable session tickets for better compatibility b/2682876
| SSL_OP_NO_TICKET
// We also disable compression for better compatibility b/2710492 b/2710497
| SSL_OP_NO_COMPRESSION
// Because dhGenerateParameters uses DSA_generate_parameters_ex
| SSL_OP_SINGLE_DH_USE
// Because ecGenerateParameters uses a fixed named curve
| SSL_OP_SINGLE_ECDH_USE);
int mode = SSL_CTX_get_mode(sslCtx.get());
/*
* Turn on "partial write" mode. This means that SSL_write() will
* behave like Posix write() and possibly return after only
* writing a partial buffer. Note: The alternative, perhaps
* surprisingly, is not that SSL_write() always does full writes
* but that it will force you to retry write calls having
* preserved the full state of the original call. (This is icky
* and undesirable.)
*/
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
// Reuse empty buffers within the SSL_CTX to save memory
mode |= SSL_MODE_RELEASE_BUFFERS;
SSL_CTX_set_mode(sslCtx.get(), mode);
SSL_CTX_set_cert_verify_callback(sslCtx.get(), cert_verify_callback, NULL);
SSL_CTX_set_info_callback(sslCtx.get(), info_callback);
SSL_CTX_set_client_cert_cb(sslCtx.get(), client_cert_cb);
SSL_CTX_set_tmp_rsa_callback(sslCtx.get(), tmp_rsa_callback);
SSL_CTX_set_tmp_dh_callback(sslCtx.get(), tmp_dh_callback);
SSL_CTX_set_tmp_ecdh_callback(sslCtx.get(), tmp_ecdh_callback);
JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx.get());
return (jlong) sslCtx.release();
}
/**
* public static native void SSL_CTX_free(long ssl_ctx)
*/
static void NativeCrypto_SSL_CTX_free(JNIEnv* env,
jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_free(ssl_ctx);
}
static void NativeCrypto_SSL_CTX_set_session_id_context(JNIEnv* env, jclass,
jlong ssl_ctx_address, jbyteArray sid_ctx)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context sid_ctx=%p", ssl_ctx, sid_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO buf(env, sid_ctx);
if (buf.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => threw exception", ssl_ctx);
return;
}
unsigned int length = buf.size();
if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"length > SSL_MAX_SSL_SESSION_ID_LENGTH");
JNI_TRACE("NativeCrypto_SSL_CTX_set_session_id_context => length = %d", length);
return;
}
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buf.get());
int result = SSL_CTX_set_session_id_context(ssl_ctx, bytes, length);
if (result == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_SSL_CTX_set_session_id_context");
return;
}
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => ok", ssl_ctx);
}
/**
* public static native int SSL_new(long ssl_ctx) throws SSLException;
*/
static jlong NativeCrypto_SSL_new(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new", ssl_ctx);
if (ssl_ctx == NULL) {
return 0;
}
Unique_SSL ssl(SSL_new(ssl_ctx));
if (ssl.get() == NULL) {
throwSSLExceptionWithSslErrors(env, NULL, SSL_ERROR_NONE,
"Unable to create SSL structure");
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
return 0;
}
/*
* Create our special application data.
*/
AppData* appData = AppData::create();
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to create application data");
freeOpenSslErrorState();
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new appData => 0", ssl_ctx);
return 0;
}
SSL_set_app_data(ssl.get(), reinterpret_cast<char*>(appData));
/*
* Java code in class OpenSSLSocketImpl does the verification. Since
* the callbacks do all the verification of the chain, this flag
* simply controls whether to send protocol-level alerts or not.
* SSL_VERIFY_NONE means don't send alerts and anything else means send
* alerts.
*/
SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => ssl=%p appData=%p", ssl_ctx, ssl.get(), appData);
return (jlong) ssl.release();
}
static void NativeCrypto_SSL_enable_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_enable_tls_channel_id", ssl);
if (ssl == NULL) {
return;
}
long ret = SSL_enable_tls_channel_id(ssl);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error enabling Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_tls_channel_id => error", ssl);
return;
}
}
static jbyteArray NativeCrypto_SSL_get_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id", ssl);
if (ssl == NULL) {
return NULL;
}
// Channel ID is 64 bytes long. Unfortunately, OpenSSL doesn't declare this length
// as a constant anywhere.
jbyteArray javaBytes = env->NewByteArray(64);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => NULL", ssl);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
// Unfortunately, the SSL_get_tls_channel_id method below always returns 64 (upon success)
// regardless of the number of bytes copied into the output buffer "tmp". Thus, the correctness
// of this code currently relies on the "tmp" buffer being exactly 64 bytes long.
long ret = SSL_get_tls_channel_id(ssl, tmp, 64);
if (ret == 0) {
// Channel ID either not set or did not verify
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => not available", ssl);
return NULL;
} else if (ret != 64) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error getting Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_tls_channel_id => error, returned %ld", ssl, ret);
return NULL;
}
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id() => %p", ssl, javaBytes);
return javaBytes;
}
static void NativeCrypto_SSL_set1_tls_channel_id(JNIEnv* env, jclass,
jlong ssl_address, jlong pkeyRef)
{
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => pkey == null", ssl);
return;
}
// SSL_set1_tls_channel_id requires ssl->server to be set to 0.
// Unfortunately, the default value is 1 and it's only changed to 0 just
// before the handshake starts (see NativeCrypto_SSL_do_handshake).
ssl->server = 0;
long ret = SSL_set1_tls_channel_id(ssl, pkey);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(
env, ssl, SSL_ERROR_NONE, "Error setting private key for Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => error", ssl);
return;
}
// SSL_set1_tls_channel_id expects to take ownership of the EVP_PKEY, but
// we have an external reference from the caller such as an OpenSSLKey,
// so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => ok", ssl);
}
static void NativeCrypto_SSL_use_PrivateKey(JNIEnv* env, jclass, jlong ssl_address, jlong pkeyRef) {
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("ssl=%p SSL_use_PrivateKey privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_use_PrivateKey => pkey == null", ssl);
return;
}
int ret = SSL_use_PrivateKey(ssl, pkey);
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting private key");
SSL_clear(ssl);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => error", ssl);
return;
}
// SSL_use_PrivateKey expects to take ownership of the EVP_PKEY,
// but we have an external reference from the caller such as an
// OpenSSLKey, so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => ok", ssl);
}
static void NativeCrypto_SSL_use_certificate(JNIEnv* env, jclass,
jlong ssl_address, jlongArray certificatesJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate certificates=%p", ssl, certificatesJava);
if (ssl == NULL) {
return;
}
if (certificatesJava == NULL) {
jniThrowNullPointerException(env, "certificates == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
size_t length = env->GetArrayLength(certificatesJava);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "certificates.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates.length == 0", ssl);
return;
}
ScopedLongArrayRO certificates(env, certificatesJava);
if (certificates.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
Unique_X509 serverCert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[0]))));
if (serverCert.get() == NULL) {
// Note this shouldn't happen since we checked the number of certificates above.
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !sk_X509_push(chain.get(), cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
int ret = SSL_use_certificate(ssl, serverCert.get());
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(serverCert);
int chainResult = SSL_use_certificate_chain(ssl, chain.get());
if (chainResult == 0) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate_chain error",
ssl);
return;
}
OWNERSHIP_TRANSFERRED(chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => ok", ssl);
}
static void NativeCrypto_SSL_check_private_key(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key", ssl);
if (ssl == NULL) {
return;
}
int ret = SSL_check_private_key(ssl);
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error checking private key");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => ok", ssl);
}
static void NativeCrypto_SSL_set_client_CA_list(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray principals)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list principals=%p", ssl, principals);
if (ssl == NULL) {
return;
}
if (principals == NULL) {
jniThrowNullPointerException(env, "principals == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals == null", ssl);
return;
}
int length = env->GetArrayLength(principals);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "principals.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals.length == 0", ssl);
return;
}
Unique_sk_X509_NAME principalsStack(sk_X509_NAME_new_null());
if (principalsStack.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate principal stack");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => stack allocation error", ssl);
return;
}
for (int i = 0; i < length; i++) {
ScopedLocalRef<jbyteArray> principal(env,
reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(principals, i)));
if (principal.get() == NULL) {
jniThrowNullPointerException(env, "principals element == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals element null", ssl);
return;
}
ScopedByteArrayRO buf(env, principal.get());
if (buf.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => threw exception", ssl);
return;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(buf.get());
Unique_X509_NAME principalX509Name(d2i_X509_NAME(NULL, &tmp, buf.size()));
if (principalX509Name.get() == NULL) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing principal");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals parsing error",
ssl);
return;
}
if (!sk_X509_NAME_push(principalsStack.get(), principalX509Name.release())) {
jniThrowOutOfMemory(env, "Unable to push principal");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principal push error", ssl);
return;
}
}
SSL_set_client_CA_list(ssl, principalsStack.release());
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => ok", ssl);
}
/**
* public static native long SSL_get_mode(long ssl);
*/
static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl);
if (ssl == NULL) {
return 0;
}
long mode = SSL_get_mode(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0x%lx", ssl, mode);
return mode;
}
/**
* public static native long SSL_set_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_get_options(long ssl);
*/
static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl);
if (ssl == NULL) {
return 0;
}
long options = SSL_get_options(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0x%lx", ssl, options);
return options;
}
/**
* public static native long SSL_set_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, options);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, options);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options => 0x%lx", ssl, result);
return result;
}
static jlongArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl);
STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl);
int count = (cipherStack != NULL) ? sk_SSL_CIPHER_num(cipherStack) : 0;
ScopedLocalRef<jlongArray> ciphersArray(env, env->NewLongArray(count));
ScopedLongArrayRW ciphers(env, ciphersArray.get());
for (int i = 0; i < count; i++) {
ciphers[i] = reinterpret_cast<jlong>(sk_SSL_CIPHER_value(cipherStack, i));
}
JNI_TRACE("NativeCrypto_SSL_get_ciphers(%p) => %p [size=%d]", ssl, ciphersArray.get(), count);
return ciphersArray.release();
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_mkey(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_mkey => %ld", cipher, cipher->algorithm_mkey);
return cipher->algorithm_mkey;
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_auth(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_auth => %ld", cipher, cipher->algorithm_auth);
return cipher->algorithm_auth;
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_cipher_lists(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray cipherSuites)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%p", ssl, cipherSuites);
if (ssl == NULL) {
return;
}
if (cipherSuites == NULL) {
jniThrowNullPointerException(env, "cipherSuites == null");
return;
}
Unique_sk_SSL_CIPHER cipherstack(sk_SSL_CIPHER_new_null());
if (cipherstack.get() == NULL) {
jniThrowRuntimeException(env, "sk_SSL_CIPHER_new_null failed");
return;
}
const SSL_METHOD* ssl_method = ssl->method;
int num_ciphers = ssl_method->num_ciphers();
int length = env->GetArrayLength(cipherSuites);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists length=%d", ssl, length);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
if (c.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuite=%s", ssl, c.c_str());
bool found = false;
for (int j = 0; j < num_ciphers; j++) {
const SSL_CIPHER* cipher = ssl_method->get_cipher(j);
if ((strcmp(c.c_str(), cipher->name) == 0)
&& (strcmp(SSL_CIPHER_get_version(cipher), "SSLv2"))) {
if (!sk_SSL_CIPHER_push(cipherstack.get(), cipher)) {
jniThrowOutOfMemory(env, "Unable to push cipher");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists => cipher push error", ssl);
return;
}
found = true;
}
}
if (!found) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Could not find cipher suite.");
return;
}
}
int rc = SSL_set_cipher_lists(ssl, cipherstack.get());
if (rc == 0) {
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Illegal cipher suite strings.");
} else {
OWNERSHIP_TRANSFERRED(cipherstack);
}
}
static void NativeCrypto_SSL_set_accept_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_accept_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_accept_state(ssl);
}
static void NativeCrypto_SSL_set_connect_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_connect_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_connect_state(ssl);
}
/**
* Sets certificate expectations, especially for server to request client auth
*/
static void NativeCrypto_SSL_set_verify(JNIEnv* env,
jclass, jlong ssl_address, jint mode)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify mode=%x", ssl, mode);
if (ssl == NULL) {
return;
}
SSL_set_verify(ssl, (int)mode, NULL);
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass,
jlong ssl_address, jlong ssl_session_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session);
if (ssl == NULL) {
return;
}
int ret = SSL_set_session(ssl, ssl_session);
if (ret != 1) {
/*
* Translate the error, and throw if it turns out to be a real
* problem.
*/
int sslErrorCode = SSL_get_error(ssl, ret);
if (sslErrorCode != SSL_ERROR_ZERO_RETURN) {
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "SSL session set");
SSL_clear(ssl);
}
}
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean creation_enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d",
ssl, creation_enabled);
if (ssl == NULL) {
return;
}
SSL_set_session_creation_enabled(ssl, creation_enabled);
}
static void NativeCrypto_SSL_set_tlsext_host_name(JNIEnv* env, jclass,
jlong ssl_address, jstring hostname)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostname=%p",
ssl, hostname);
if (ssl == NULL) {
return;
}
ScopedUtfChars hostnameChars(env, hostname);
if (hostnameChars.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostnameChars=%s",
ssl, hostnameChars.c_str());
int ret = SSL_set_tlsext_host_name(ssl, hostnameChars.c_str());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting host name");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => ok", ssl);
}
static jstring NativeCrypto_SSL_get_servername(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername", ssl);
if (ssl == NULL) {
return NULL;
}
const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername => %s", ssl, servername);
return env->NewStringUTF(servername);
}
/**
* A common selection path for both NPN and ALPN since they're essentially the
* same protocol. The list of protocols in "primary" is considered the order
* which should take precedence.
*/
static int proto_select(SSL* ssl __attribute__ ((unused)),
unsigned char **out, unsigned char *outLength,
const unsigned char *primary, const unsigned int primaryLength,
const unsigned char *secondary, const unsigned int secondaryLength) {
if (primary != NULL) {
JNI_TRACE("primary=%p, length=%d", primary, primaryLength);
int status = SSL_select_next_proto(out, outLength, primary, primaryLength, secondary,
secondaryLength);
switch (status) {
case OPENSSL_NPN_NEGOTIATED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN negotiated", ssl);
return SSL_TLSEXT_ERR_OK;
break;
case OPENSSL_NPN_UNSUPPORTED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN unsupported", ssl);
break;
case OPENSSL_NPN_NO_OVERLAP:
JNI_TRACE("ssl=%p proto_select NPN/ALPN no overlap", ssl);
break;
}
} else {
if (out != NULL && outLength != NULL) {
*out = NULL;
*outLength = 0;
}
JNI_TRACE("protocols=NULL");
}
return SSL_TLSEXT_ERR_NOACK;
}
/**
* Callback for the server to select an ALPN protocol.
*/
static int alpn_select_callback(SSL* ssl, const unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen, void *) {
JNI_TRACE("ssl=%p alpn_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
return proto_select(ssl, const_cast<unsigned char **>(out), outlen,
reinterpret_cast<unsigned char*>(appData->alpnProtocolsData),
appData->alpnProtocolsLength, in, inlen);
}
/**
* Callback for the client to select an NPN protocol.
*/
static int next_proto_select_callback(SSL* ssl, unsigned char** out, unsigned char* outlen,
const unsigned char* in, unsigned int inlen, void*)
{
JNI_TRACE("ssl=%p next_proto_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
// Enable False Start on the client if the server understands NPN
// http://www.imperialviolet.org/2012/04/11/falsestart.html
SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
return proto_select(ssl, out, outlen, in, inlen,
reinterpret_cast<unsigned char*>(appData->npnProtocolsData),
appData->npnProtocolsLength);
}
/**
* Callback for the server to advertise available protocols.
*/
static int next_protos_advertised_callback(SSL* ssl,
const unsigned char **out, unsigned int *outlen, void *)
{
JNI_TRACE("ssl=%p next_protos_advertised_callback", ssl);
AppData* appData = toAppData(ssl);
unsigned char* npnProtocols = reinterpret_cast<unsigned char*>(appData->npnProtocolsData);
if (npnProtocols != NULL) {
*out = npnProtocols;
*outlen = appData->npnProtocolsLength;
return SSL_TLSEXT_ERR_OK;
} else {
*out = NULL;
*outlen = 0;
return SSL_TLSEXT_ERR_NOACK;
}
}
static void NativeCrypto_SSL_CTX_enable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_callback, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_protos_advertised_callback, NULL); // server
}
static void NativeCrypto_SSL_CTX_disable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, NULL, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, NULL, NULL); // server
}
static jbyteArray NativeCrypto_SSL_get_npn_negotiated_protocol(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_npn_negotiated_protocol", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_next_proto_negotiated(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
static int NativeCrypto_SSL_set_alpn_protos(JNIEnv* env, jclass, jlong ssl_address,
jbyteArray protos) {
SSL* ssl = to_SSL(env, ssl_address, true);
if (ssl == NULL) {
return 0;
}
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p", ssl, protos);
if (protos == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=NULL", ssl);
return 1;
}
ScopedByteArrayRO protosBytes(env, protos);
if (protosBytes.get() == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => protosBytes == NULL", ssl,
protos);
return 0;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char*>(protosBytes.get());
int ret = SSL_set_alpn_protos(ssl, tmp, protosBytes.size());
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => ret=%d", ssl, protos, ret);
return ret;
}
static jbyteArray NativeCrypto_SSL_get0_alpn_selected(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p SSL_get0_alpn_selected", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_alpn_selected(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
#ifdef WITH_JNI_TRACE_KEYS
static inline char hex_char(unsigned char in)
{
if (in < 10) {
return '0' + in;
} else if (in <= 0xF0) {
return 'A' + in - 10;
} else {
return '?';
}
}
static void hex_string(char **dest, unsigned char* input, int len)
{
*dest = (char*) malloc(len * 2 + 1);
char *output = *dest;
for (int i = 0; i < len; i++) {
*output++ = hex_char(input[i] >> 4);
*output++ = hex_char(input[i] & 0xF);
}
*output = '\0';
}
static void debug_print_session_key(SSL_SESSION* session)
{
char *session_id_str;
char *master_key_str;
const char *key_type;
char *keyline;
hex_string(&session_id_str, session->session_id, session->session_id_length);
hex_string(&master_key_str, session->master_key, session->master_key_length);
X509* peer = SSL_SESSION_get0_peer(session);
EVP_PKEY* pkey = X509_PUBKEY_get(peer->cert_info->key);
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
key_type = "RSA";
break;
case EVP_PKEY_DSA:
key_type = "DSA";
break;
case EVP_PKEY_EC:
key_type = "EC";
break;
default:
key_type = "Unknown";
break;
}
asprintf(&keyline, "%s Session-ID:%s Master-Key:%s\n", key_type, session_id_str,
master_key_str);
JNI_TRACE("ssl_session=%p %s", session, keyline);
free(session_id_str);
free(master_key_str);
free(keyline);
}
#endif /* WITH_JNI_TRACE_KEYS */
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake_bio(JNIEnv* env, jclass, jlong ssl_address,
jlong rbioRef, jlong wbioRef, jobject shc, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
BIO* rbio = reinterpret_cast<BIO*>(rbioRef);
BIO* wbio = reinterpret_cast<BIO*>(wbioRef);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio rbio=%p wbio=%p shc=%p client_mode=%d npn=%p",
ssl, rbio, wbio, shc, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => rbio == null || wbio == NULL", ssl);
return 0;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (!client_mode && alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
int ret = 0;
errno = 0;
if (!appData->setCallbackState(env, shc, NULL, npnProtocols, alpnProtocols)) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio exception => 0", ssl);
return 0;
}
if (ret <= 0) { // error. See SSL_do_handshake(3SSL) man page.
// error case
int sslError = SSL_get_error(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio ret=%d errno=%d sslError=%d",
ssl, ret, errno, sslError);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we need to exit to allow
* the SSLEngine code to wrap or unwrap.
*/
if (sslError == SSL_ERROR_NONE || (sslError == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
SSL_clear(ssl);
freeOpenSslErrorState();
} else if (sslError != SSL_ERROR_WANT_READ && sslError != SSL_ERROR_WANT_WRITE) {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL handshake terminated",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio error => 0", ssl);
return 0;
}
// success. handshake completed
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return reinterpret_cast<uintptr_t>(ssl_session);
}
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jint timeout_millis, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd=%p shc=%p timeout_millis=%d client_mode=%d npn=%p",
ssl, fdObject, shc, timeout_millis, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd == null => 0", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
NetFd fd(env, fdObject);
if (fd.isClosed()) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd.isClosed() => 0", ssl);
return 0;
}
int ret = SSL_set_fd(ssl, fd.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd.get());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE,
"Error setting the file descriptor");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake SSL_set_fd => 0", ssl);
return 0;
}
/*
* Make socket non-blocking, so SSL_connect SSL_read() and SSL_write() don't hang
* forever and we can use select() to find out if the socket is ready.
*/
if (!setBlocking(fd.get(), false)) {
throwSSLExceptionStr(env, "Unable to make socket non blocking");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setBlocking => 0", ssl);
return 0;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (client_mode) {
SSL_set_connect_state(ssl);
} else {
SSL_set_accept_state(ssl);
if (alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
}
ret = 0;
while (appData->aliveAndKicking) {
errno = 0;
if (!appData->setCallbackState(env, shc, fdObject, npnProtocols, alpnProtocols)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake exception => 0", ssl);
return 0;
}
// success case
if (ret == 1) {
break;
}
// retry case
if (errno == EINTR) {
continue;
}
// error case
int sslError = SSL_get_error(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake ret=%d errno=%d sslError=%d timeout_millis=%d",
ssl, ret, errno, sslError, timeout_millis);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we use sslSelect to
* wait for it to become ready. If that doesn't happen
* before the specified timeout or an error occurs, we
* cancel the handshake. Otherwise we try the SSL_connect
* again.
*/
if (sslError == SSL_ERROR_WANT_READ || sslError == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
int selectResult = sslSelect(env, sslError, fdObject, appData, timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslSelect => 0", ssl);
return 0;
}
if (selectResult == -1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_SYSCALL, "handshake error",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == -1 => 0", ssl);
return 0;
}
if (selectResult == 0) {
throwSocketTimeoutException(env, "SSL handshake timed out");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == 0 => 0", ssl);
return 0;
}
} else {
// ALOGE("Unknown error %d during handshake", error);
break;
}
}
// clean error. See SSL_do_handshake(3SSL) man page.
if (ret == 0) {
/*
* The other side closed the socket before the handshake could be
* completed, but everything is within the bounds of the TLS protocol.
* We still might want to find out the real reason of the failure.
*/
int sslError = SSL_get_error(ssl, ret);
if (sslError == SSL_ERROR_NONE || (sslError == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
} else {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL handshake terminated",
throwSSLHandshakeExceptionStr);
}
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake clean error => 0", ssl);
return 0;
}
// unclean error. See SSL_do_handshake(3SSL) man page.
if (ret < 0) {
/*
* Translate the error and throw exception. We are sure it is an error
* at this point.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL handshake aborted",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake unclean error => 0", ssl);
return 0;
}
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return (jlong) ssl_session;
}
/**
* Perform SSL renegotiation
*/
static void NativeCrypto_SSL_renegotiate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate", ssl);
if (ssl == NULL) {
return;
}
int result = SSL_renegotiate(ssl);
if (result != 1) {
throwSSLExceptionStr(env, "Problem with SSL_renegotiate");
return;
}
// first call asks client to perform renegotiation
int ret = SSL_do_handshake(ssl);
if (ret != 1) {
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError,
"Problem with SSL_do_handshake after SSL_renegotiate");
return;
}
// if client agrees, set ssl state and perform renegotiation
ssl->state = SSL_ST_ACCEPT;
SSL_do_handshake(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate =>", ssl);
}
/**
* public static native byte[][] SSL_get_certificate(long ssl);
*/
static jlongArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl);
if (ssl == NULL) {
return NULL;
}
X509* certificate = SSL_get_certificate(ssl);
if (certificate == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
// SSL_get_certificate can return NULL during an error as well.
freeOpenSslErrorState();
return NULL;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => threw exception", ssl);
return NULL;
}
if (!sk_X509_push(chain.get(), X509_dup_nocopy(certificate))) {
jniThrowOutOfMemory(env, "Unable to push local certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
STACK_OF(X509)* cert_chain = SSL_get_certificate_chain(ssl, certificate);
for (int i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
jlongArray refArray = getCertificateRefs(env, chain.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => %p", ssl, refArray);
return refArray;
}
// Fills a long[] with the peer certificates in the chain.
static jlongArray NativeCrypto_SSL_get_peer_cert_chain(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain", ssl);
if (ssl == NULL) {
return NULL;
}
STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl);
Unique_sk_X509 chain_copy(NULL);
if (ssl->server) {
X509* x509 = SSL_get_peer_certificate(ssl);
if (x509 == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => NULL", ssl);
return NULL;
}
chain_copy.reset(sk_X509_new_null());
if (chain_copy.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate dup error", ssl);
return NULL;
}
size_t chain_size = sk_X509_num(chain);
for (size_t i = 0; i < chain_size; i++) {
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(sk_X509_value(chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate chain push error", ssl);
return NULL;
}
}
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(x509))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate push error", ssl);
return NULL;
}
chain = chain_copy.get();
}
jlongArray refArray = getCertificateRefs(env, chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => %p", ssl, refArray);
return refArray;
}
static int sslRead(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, char* buf, jint len,
int* sslReturnCode, int* sslErrorCode, int read_timeout_millis) {
JNI_TRACE("ssl=%p sslRead buf=%p len=%d", ssl, buf, len);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
} else if (!SSL_is_init_finished(ssl)) {
return THROW_SSLEXCEPTION;
}
while (appData->aliveAndKicking) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
int result = SSL_read(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p sslRead => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p sslRead SSL_read result=%d sslError=%d", ssl, result, sslError);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslRead data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError == SSL_ERROR_WANT_READ || sslError == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
// Successfully read at least one byte.
case SSL_ERROR_NONE: {
return result;
}
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError, fdObject, appData, read_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
*sslReturnCode = -1;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
*sslReturnCode = result;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
}
}
return -1;
}
static jint NativeCrypto_SSL_read_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray destJava,
jlong sourceBioRef, jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sourceBioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO dest=%p sourceBio=%p sinkBio=%p shc=%p",
ssl, destJava, rbio, wbio, shc);
if (ssl == NULL) {
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => rbio == null || wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
ScopedByteArrayRW dest(env, destJava);
if (dest.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => appData == NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set callback state");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => set callback state failed", ssl);
return -1;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
int result = SSL_read(ssl, dest.get(), dest.size());
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return THROWN_EXCEPTION;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO SSL_read result=%d sslError=%d", ssl, result, sslError);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
// Successfully read at least one byte.
case SSL_ERROR_NONE:
break;
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
result = -1;
break;
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
result = 0;
break;
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
result = -1;
break;
} else if (errno == EINTR) {
// System call has been interrupted. Simply retry.
result = 0;
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "Read error");
return -1;
}
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => %d", ssl, result);
return result;
}
/**
* OpenSSL read function (2): read into buffer at offset n chunks.
* Returns 1 (success) or value <= 0 (failure).
*/
static jint NativeCrypto_SSL_read(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len,
jint read_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read fd=%p shc=%p b=%p offset=%d len=%d read_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, read_timeout_millis);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => fd == null", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => sslHandshakeCallbacks == null", ssl);
return 0;
}
ScopedByteArrayRW bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => threw exception", ssl);
return 0;
}
int returnCode = 0;
int sslErrorCode = SSL_ERROR_NONE;;
int ret = sslRead(env, ssl, fdObject, shc, reinterpret_cast<char*>(bytes.get() + offset), len,
&returnCode, &sslErrorCode, read_timeout_millis);
int result;
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslRead() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Read error");
result = -1;
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Read timed out");
result = -1;
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
// or RuntimeException thrown by callback
result = -1;
break;
default:
result = ret;
break;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => %d", ssl, result);
return result;
}
static int sslWrite(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, const char* buf, jint len,
int* sslReturnCode, int* sslErrorCode, int write_timeout_millis) {
JNI_TRACE("ssl=%p sslWrite buf=%p len=%d write_timeout_millis=%d",
ssl, buf, len, write_timeout_millis);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
} else if (!SSL_is_init_finished(ssl)) {
return THROW_SSLEXCEPTION;
}
int count = len;
while (appData->aliveAndKicking && ((len > 0) || (ssl->s3->wbuf.left > 0))) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
JNI_TRACE("ssl=%p sslWrite SSL_write len=%d left=%d", ssl, len, ssl->s3->wbuf.left);
int result = SSL_write(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p sslWrite exception => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p sslWrite SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError, ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslWrite data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError == SSL_ERROR_WANT_READ || sslError == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
// Successfully wrote at least one byte.
case SSL_ERROR_NONE: {
buf += result;
len -= result;
break;
}
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
// The concept of a write timeout doesn't really make sense, and
// it's also not standard Java behavior, so we wait forever here.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError, fdObject, appData, write_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
*sslReturnCode = -1;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
*sslReturnCode = result;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
}
}
JNI_TRACE("ssl=%p sslWrite => count=%d", ssl, count);
return count;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static int NativeCrypto_SSL_write_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray sourceJava, jint len,
jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO source=%p len=%d wbio=%p shc=%p",
ssl, sourceJava, len, wbio, shc);
if (ssl == NULL) {
return -1;
}
if (wbio == NULL) {
jniThrowNullPointerException(env, "wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO appData => NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return 0;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set appdata callback");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => appData can't set callback", ssl);
return -1;
}
ScopedByteArrayRO source(env, sourceJava);
if (source.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => threw exception", ssl);
return -1;
}
Unique_BIO nullBio(BIO_new(BIO_s_null()));
ScopedSslBio sslBio(ssl, nullBio.get(), wbio);
int result = SSL_write(ssl, reinterpret_cast<const char*>(source.get()), len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO exception => exception pending (reneg)", ssl);
return -1;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError, ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
case SSL_ERROR_NONE:
return result;
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
return -1;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return 0;
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
return 0;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "Write error");
break;
}
}
return -1;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static void NativeCrypto_SSL_write(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len, jint write_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write fd=%p shc=%p b=%p offset=%d len=%d write_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, write_timeout_millis);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => sslHandshakeCallbacks == null", ssl);
return;
}
ScopedByteArrayRO bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => threw exception", ssl);
return;
}
int returnCode = 0;
int sslErrorCode = SSL_ERROR_NONE;
int ret = sslWrite(env, ssl, fdObject, shc, reinterpret_cast<const char*>(bytes.get() + offset),
len, &returnCode, &sslErrorCode, write_timeout_millis);
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslWrite() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Write error");
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Write timed out");
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
break;
default:
break;
}
}
/**
* Interrupt any pending I/O before closing the socket.
*/
static void NativeCrypto_SSL_interrupt(
JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_interrupt", ssl);
if (ssl == NULL) {
return;
}
/*
* Mark the connection as quasi-dead, then send something to the emergency
* file descriptor, so any blocking select() calls are woken up.
*/
AppData* appData = toAppData(ssl);
if (appData != NULL) {
appData->aliveAndKicking = 0;
// At most two threads can be waiting.
sslNotify(appData);
sslNotify(appData);
}
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown(JNIEnv* env, jclass, jlong ssl_address,
jobject fdObject, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown fd=%p shc=%p", ssl, fdObject, shc);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
freeOpenSslErrorState();
return;
}
/*
* Try to make socket blocking again. OpenSSL literature recommends this.
*/
int fd = SSL_get_fd(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown s=%d", ssl, fd);
if (fd != -1) {
setBlocking(fd, true);
}
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
SSL_clear(ssl);
freeOpenSslErrorState();
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown_BIO(JNIEnv* env, jclass, jlong ssl_address, jlong rbioRef,
jlong wbioRef, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(rbioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(wbioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown rbio=%p wbio=%p shc=%p", ssl, rbio, wbio, shc);
if (ssl == NULL) {
return;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => rbio == null || wbio == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
freeOpenSslErrorState();
return;
}
ScopedSslBio scopedBio(ssl, rbio, wbio);
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
SSL_clear(ssl);
freeOpenSslErrorState();
}
static jint NativeCrypto_SSL_get_shutdown(JNIEnv* env, jclass, jlong ssl_address) {
const SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown", ssl);
if (ssl == NULL) {
jniThrowNullPointerException(env, "ssl == null");
return 0;
}
int status = SSL_get_shutdown(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown => %d", ssl, status);
return static_cast<jint>(status);
}
/**
* public static native void SSL_free(long ssl);
*/
static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl);
if (ssl == NULL) {
return;
}
AppData* appData = toAppData(ssl);
SSL_set_app_data(ssl, NULL);
delete appData;
SSL_free(ssl);
}
/**
* Gets and returns in a byte array the ID of the actual SSL session.
*/
static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass,
jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
jbyteArray result = env->NewByteArray(ssl_session->session_id_length);
if (result != NULL) {
jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id);
env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src);
}
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d",
ssl_session, result, ssl_session->session_id_length);
return result;
}
/**
* Gets and returns in a long integer the creation's time of the
* actual SSL session.
*/
static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session);
if (ssl_session == NULL) {
return 0;
}
// result must be jlong, not long or *1000 will overflow
jlong result = SSL_SESSION_get_time(ssl_session);
result *= 1000; // OpenSSL uses seconds, Java uses milliseconds.
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, result);
return result;
}
/**
* Gets and returns in a string the version of the SSL protocol. If it
* returns the string "unknown" it means that no connection is established.
*/
static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const char* protocol = SSL_SESSION_get_version(ssl_session);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol);
return env->NewStringUTF(protocol);
}
/**
* Gets and returns in a string the cipher negotiated for the SSL session.
*/
static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const SSL_CIPHER* cipher = ssl_session->cipher;
const char* name = SSL_CIPHER_get_name(cipher);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name);
return env->NewStringUTF(name);
}
/**
* Frees the SSL session.
*/
static void NativeCrypto_SSL_SESSION_free(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session);
if (ssl_session == NULL) {
return;
}
SSL_SESSION_free(ssl_session);
}
/**
* Serializes the native state of the session (ID, cipher, and keys but
* not certificates). Returns a byte[] containing the DER-encoded state.
* See apache mod_ssl.
*/
static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
return ASN1ToByteArray<SSL_SESSION, i2d_SSL_SESSION>(env, ssl_session);
}
/**
* Deserialize the session.
*/
static jlong NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => threw exception");
return 0;
}
const unsigned char* ucp = reinterpret_cast<const unsigned char*>(bytes.get());
SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, bytes.size());
// Initialize SSL_SESSION cipher field based on cipher_id http://b/7091840
if (ssl_session != NULL) {
// based on ssl_get_prev_session
uint32_t cipher_id_network_order = htonl(ssl_session->cipher_id);
uint8_t* cipher_id_byte_pointer = reinterpret_cast<uint8_t*>(&cipher_id_network_order);
if (ssl_session->ssl_version >= SSL3_VERSION_MAJOR) {
cipher_id_byte_pointer += 2; // skip first two bytes for SSL3+
} else {
cipher_id_byte_pointer += 1; // skip first byte for SSL2
}
ssl_session->cipher = SSLv23_method()->get_cipher_by_char(cipher_id_byte_pointer);
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION cipher_id=%lx hton=%x 0=%x 1=%x cipher=%s",
ssl_session->cipher_id, cipher_id_network_order,
cipher_id_byte_pointer[0], cipher_id_byte_pointer[1],
SSL_CIPHER_get_name(ssl_session->cipher));
} else {
freeOpenSslErrorState();
}
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session);
return reinterpret_cast<uintptr_t>(ssl_session);
}
static jlong NativeCrypto_ERR_peek_last_error(JNIEnv*, jclass) {
return ERR_peek_last_error();
}
#define FILE_DESCRIPTOR "Ljava/io/FileDescriptor;"
#define SSL_CALLBACKS "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto$SSLHandshakeCallbacks;"
static JNINativeMethod sNativeCryptoMethods[] = {
NATIVE_METHOD(NativeCrypto, clinit, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_dynamic, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_by_id, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_add, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_init, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_finish, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_free, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_private_key, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_get_id, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, ENGINE_ctrl_cmd_string, "(JLjava/lang/String;Ljava/lang/String;I)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DH, "([B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DSA, "([B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_RSA, "([B[B[B[B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_EC_KEY, "(JJ[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_mac_key, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_type, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_public, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_private, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS8_PRIV_KEY_INFO, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS8_PRIV_KEY_INFO, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_PUBKEY, "([B)J"),
NATIVE_METHOD(NativeCrypto, RSA_generate_key_ex, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, RSA_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_encrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_decrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_encrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_decrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, get_RSA_private_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, get_RSA_public_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, DSA_generate_key, "(I[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, get_DSA_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, set_DSA_flag_nonce_from_hash, "(J)V"),
NATIVE_METHOD(NativeCrypto, DH_generate_key, "(II)J"),
NATIVE_METHOD(NativeCrypto, get_DH_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_by_curve_name, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_curve, "(I[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_asn1_flag, "(JI)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_point_conversion_form, "(JI)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve_name, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_order, "(J)[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_degree, "(J)I"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_cofactor, "(J)[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_cmp, "(JJ)Z"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_generator, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_generator, "(JJ[B[B)V"),
NATIVE_METHOD(NativeCrypto, get_EC_GROUP_type, "(J)I"),
NATIVE_METHOD(NativeCrypto, EC_POINT_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_POINT_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_cmp, "(JJJ)Z"),
NATIVE_METHOD(NativeCrypto, EC_POINT_set_affine_coordinates, "(JJ[B[B)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_get_affine_coordinates, "(JJ)[[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_generate_key, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get0_group, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_private_key, "(J)[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_public_key, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_set_nonce_from_hash, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, ECDH_compute_key, "([BIJJ)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_create, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_init, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_destroy, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_copy, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_get_digestbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_SignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BIJ)I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BIIJ)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;JJ)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[B)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;)[B"),
NATIVE_METHOD(NativeCrypto, EVP_get_cipherbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_CipherInit_ex, "(JJ[B[BZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CipherUpdate, "(J[BI[BII)I"),
NATIVE_METHOD(NativeCrypto, EVP_CipherFinal_ex, "(J[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_iv_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_buf_len, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_padding, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_key_length, "(JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_cleanup, "(J)V"),
NATIVE_METHOD(NativeCrypto, RAND_seed, "([B)V"),
NATIVE_METHOD(NativeCrypto, RAND_load_file, "(Ljava/lang/String;J)I"),
NATIVE_METHOD(NativeCrypto, RAND_bytes, "([B)V"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid, "(Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_longName, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_oid, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, create_BIO_InputStream, ("(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream;)J")),
NATIVE_METHOD(NativeCrypto, create_BIO_OutputStream, "(Ljava/io/OutputStream;)J"),
NATIVE_METHOD(NativeCrypto, BIO_read, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, BIO_write, "(J[BII)V"),
NATIVE_METHOD(NativeCrypto, BIO_free_all, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_NAME_print_ex, "(JJ)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, d2i_X509_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, d2i_X509, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509, "(J)[B"),
NATIVE_METHOD(NativeCrypto, i2d_X509_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PKCS7, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS7_bio, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS7, "([J)[B"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_unpack_X509_bio, "(J)[J"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_pack_X509, "([J)[B"),
NATIVE_METHOD(NativeCrypto, X509_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, get_X509_hashCode, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_print_ex, "(JJJJ)V"),
NATIVE_METHOD(NativeCrypto, X509_get_pubkey, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_get_subject_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_pubkey_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_issuerUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_subjectUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_kusage, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_xkusage, "(J)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_pathlen, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_crl_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_verify, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_lastUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_nextUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_revocationDate, "(J)J"),
NATIVE_METHOD(NativeCrypto, get_X509_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_GENERAL_NAME_stack, "(JI)[[Ljava/lang/Object;"),
NATIVE_METHOD(NativeCrypto, X509_get_notBefore, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_notAfter, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_verify, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_cert_info_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_flags, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_check_issued, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, d2i_X509_CRL_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509_CRL, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_cert, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_serial, "(J[B)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_REVOKED, "(J)[J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_CRL, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_REVOKED, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_supported_extension, "(J)I"),
NATIVE_METHOD(NativeCrypto, ASN1_TIME_to_Calendar, "(JLjava/util/Calendar;)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_session_id_context, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_tls_channel_id, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_tls_channel_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set1_tls_channel_id, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_use_PrivateKey, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_use_certificate, "(J[J)V"),
NATIVE_METHOD(NativeCrypto, SSL_check_private_key, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_client_CA_list, "(J[[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_mode, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_get_options, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_cipher_lists, "(J[Ljava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ciphers, "(J)[J"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_auth, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_mkey, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_set_accept_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_connect_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_verify, "(JI)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session_creation_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_tlsext_host_name, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_servername, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "IZ[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake_bio, "(JJJ" SSL_CALLBACKS "Z[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_renegotiate, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_certificate, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_get_peer_cert_chain, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_read, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)I"),
NATIVE_METHOD(NativeCrypto, SSL_read_BIO, "(J[BJJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_write, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)V"),
NATIVE_METHOD(NativeCrypto, SSL_write_BIO, "(J[BIJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_interrupt, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown, "(J" FILE_DESCRIPTOR SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown_BIO, "(JJJ" SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_get_shutdown, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_session_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_time, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_version, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_cipher, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, i2d_SSL_SESSION, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_SSL_SESSION, "([B)J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_enable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_disable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_npn_negotiated_protocol, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set_alpn_protos, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, SSL_get0_alpn_selected, "(J)[B"),
NATIVE_METHOD(NativeCrypto, ERR_peek_last_error, "()J"),
};
static jclass getGlobalRefToClass(JNIEnv* env, const char* className) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(className));
jclass globalRef = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (globalRef == NULL) {
ALOGE("failed to find class %s", className);
abort();
}
return globalRef;
}
static void initialize_conscrypt(JNIEnv* env) {
jniRegisterNativeMethods(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto",
sNativeCryptoMethods, NELEM(sNativeCryptoMethods));
openSslNativeReferenceClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLNativeReference");
openSslOutputStreamClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream");
openSslNativeReference_context = env->GetFieldID(openSslNativeReferenceClass, "context", "J");
calendar_setMethod = env->GetMethodID(calendarClass, "set", "(IIIIII)V");
inputStream_readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
integer_valueOfMethod = env->GetStaticMethodID(integerClass, "valueOf",
"(I)Ljava/lang/Integer;");
openSslInputStream_readLineMethod = env->GetMethodID(openSslOutputStreamClass, "gets",
"([B)I");
outputStream_writeMethod = env->GetMethodID(outputStreamClass, "write", "([B)V");
outputStream_flushMethod = env->GetMethodID(outputStreamClass, "flush", "()V");
}
static jclass findClass(JNIEnv* env, const char* name) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(name));
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (result == NULL) {
ALOGE("failed to find class '%s'", name);
abort();
}
return result;
}
// Use JNI_OnLoad for when we're standalone
int JNI_OnLoad(JavaVM *vm, void*) {
JNI_TRACE("JNI_OnLoad NativeCrypto");
gJavaVM = vm;
JNIEnv *env;
if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
ALOGE("Could not get JNIEnv");
return JNI_ERR;
}
byteArrayClass = findClass(env, "[B");
calendarClass = findClass(env, "java/util/Calendar");
inputStreamClass = findClass(env, "java/io/InputStream");
integerClass = findClass(env, "java/lang/Integer");
objectClass = findClass(env, "java/lang/Object");
objectArrayClass = findClass(env, "[Ljava/lang/Object;");
outputStreamClass = findClass(env, "java/io/OutputStream");
stringClass = findClass(env, "java/lang/String");
initialize_conscrypt(env);
return JNI_VERSION_1_6;
}
Check for renegotiate_pending for tests
Tests call SSL_renegotiate to force a renegotiation, but was relying on
AppData being unset in this function. Instead we check that both
SSL_is_init_finished is false and SSL_renegotiation_pending is false.
Renegotiation is handled by SSL_write implicitly instead of explicitly
like the wrapper around SSL_do_handshake does.
Change-Id: I7e761afa718503933334cc19fbc696d714eca500
/*
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Native glue for Java class org.conscrypt.NativeCrypto
*/
#define TO_STRING1(x) #x
#define TO_STRING(x) TO_STRING1(x)
#ifndef JNI_JARJAR_PREFIX
#define CONSCRYPT_UNBUNDLED
#define JNI_JARJAR_PREFIX
#endif
#define LOG_TAG "NativeCrypto"
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <jni.h>
#include <openssl/asn1t.h>
#include <openssl/dsa.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include "AsynchronousCloseMonitor.h"
#include "cutils/log.h"
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
#include "NetFd.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#undef WITH_JNI_TRACE
#undef WITH_JNI_TRACE_MD
#undef WITH_JNI_TRACE_DATA
/*
* How to use this for debugging with Wireshark:
*
* 1. Pull lines from logcat to a file that looks like (without quotes):
* "RSA Session-ID:... Master-Key:..." <CR>
* "RSA Session-ID:... Master-Key:..." <CR>
* <etc>
* 2. Start Wireshark
* 3. Go to Edit -> Preferences -> SSL -> (Pre-)Master-Key log and fill in
* the file you put the lines in above.
* 4. Follow the stream that corresponds to the desired "Session-ID" in
* the Server Hello.
*/
#undef WITH_JNI_TRACE_KEYS
#ifdef WITH_JNI_TRACE
#define JNI_TRACE(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__)); \
/*
((void)printf("I/" LOG_TAG "-jni:")); \
((void)printf(__VA_ARGS__)); \
((void)printf("\n"))
*/
#else
#define JNI_TRACE(...) ((void)0)
#endif
#ifdef WITH_JNI_TRACE_MD
#define JNI_TRACE_MD(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__));
#else
#define JNI_TRACE_MD(...) ((void)0)
#endif
// don't overwhelm logcat
#define WITH_JNI_TRACE_DATA_CHUNK_SIZE 512
static JavaVM* gJavaVM;
static jclass openSslOutputStreamClass;
static jclass openSslNativeReferenceClass;
static jclass byteArrayClass;
static jclass calendarClass;
static jclass objectClass;
static jclass objectArrayClass;
static jclass integerClass;
static jclass inputStreamClass;
static jclass outputStreamClass;
static jclass stringClass;
static jfieldID openSslNativeReference_context;
static jmethodID calendar_setMethod;
static jmethodID inputStream_readMethod;
static jmethodID integer_valueOfMethod;
static jmethodID openSslInputStream_readLineMethod;
static jmethodID outputStream_writeMethod;
static jmethodID outputStream_flushMethod;
struct OPENSSL_Delete {
void operator()(void* p) const {
OPENSSL_free(p);
}
};
typedef UniquePtr<unsigned char, OPENSSL_Delete> Unique_OPENSSL_str;
struct BIO_Delete {
void operator()(BIO* p) const {
BIO_free_all(p);
}
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
struct BIGNUM_Delete {
void operator()(BIGNUM* p) const {
BN_free(p);
}
};
typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
struct ASN1_INTEGER_Delete {
void operator()(ASN1_INTEGER* p) const {
ASN1_INTEGER_free(p);
}
};
typedef UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> Unique_ASN1_INTEGER;
struct DH_Delete {
void operator()(DH* p) const {
DH_free(p);
}
};
typedef UniquePtr<DH, DH_Delete> Unique_DH;
struct DSA_Delete {
void operator()(DSA* p) const {
DSA_free(p);
}
};
typedef UniquePtr<DSA, DSA_Delete> Unique_DSA;
struct EC_GROUP_Delete {
void operator()(EC_GROUP* p) const {
EC_GROUP_clear_free(p);
}
};
typedef UniquePtr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP;
struct EC_POINT_Delete {
void operator()(EC_POINT* p) const {
EC_POINT_clear_free(p);
}
};
typedef UniquePtr<EC_POINT, EC_POINT_Delete> Unique_EC_POINT;
struct EC_KEY_Delete {
void operator()(EC_KEY* p) const {
EC_KEY_free(p);
}
};
typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
struct EVP_MD_CTX_Delete {
void operator()(EVP_MD_CTX* p) const {
EVP_MD_CTX_destroy(p);
}
};
typedef UniquePtr<EVP_MD_CTX, EVP_MD_CTX_Delete> Unique_EVP_MD_CTX;
struct EVP_CIPHER_CTX_Delete {
void operator()(EVP_CIPHER_CTX* p) const {
EVP_CIPHER_CTX_free(p);
}
};
typedef UniquePtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_Delete> Unique_EVP_CIPHER_CTX;
struct EVP_PKEY_Delete {
void operator()(EVP_PKEY* p) const {
EVP_PKEY_free(p);
}
};
typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
struct PKCS8_PRIV_KEY_INFO_Delete {
void operator()(PKCS8_PRIV_KEY_INFO* p) const {
PKCS8_PRIV_KEY_INFO_free(p);
}
};
typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
struct RSA_Delete {
void operator()(RSA* p) const {
RSA_free(p);
}
};
typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
struct ASN1_BIT_STRING_Delete {
void operator()(ASN1_BIT_STRING* p) const {
ASN1_BIT_STRING_free(p);
}
};
typedef UniquePtr<ASN1_BIT_STRING, ASN1_BIT_STRING_Delete> Unique_ASN1_BIT_STRING;
struct ASN1_OBJECT_Delete {
void operator()(ASN1_OBJECT* p) const {
ASN1_OBJECT_free(p);
}
};
typedef UniquePtr<ASN1_OBJECT, ASN1_OBJECT_Delete> Unique_ASN1_OBJECT;
struct ASN1_GENERALIZEDTIME_Delete {
void operator()(ASN1_GENERALIZEDTIME* p) const {
ASN1_GENERALIZEDTIME_free(p);
}
};
typedef UniquePtr<ASN1_GENERALIZEDTIME, ASN1_GENERALIZEDTIME_Delete> Unique_ASN1_GENERALIZEDTIME;
struct SSL_Delete {
void operator()(SSL* p) const {
SSL_free(p);
}
};
typedef UniquePtr<SSL, SSL_Delete> Unique_SSL;
struct SSL_CTX_Delete {
void operator()(SSL_CTX* p) const {
SSL_CTX_free(p);
}
};
typedef UniquePtr<SSL_CTX, SSL_CTX_Delete> Unique_SSL_CTX;
struct X509_Delete {
void operator()(X509* p) const {
X509_free(p);
}
};
typedef UniquePtr<X509, X509_Delete> Unique_X509;
struct X509_NAME_Delete {
void operator()(X509_NAME* p) const {
X509_NAME_free(p);
}
};
typedef UniquePtr<X509_NAME, X509_NAME_Delete> Unique_X509_NAME;
struct PKCS7_Delete {
void operator()(PKCS7* p) const {
PKCS7_free(p);
}
};
typedef UniquePtr<PKCS7, PKCS7_Delete> Unique_PKCS7;
struct sk_SSL_CIPHER_Delete {
void operator()(STACK_OF(SSL_CIPHER)* p) const {
// We don't own SSL_CIPHER references, so no need for pop_free
sk_SSL_CIPHER_free(p);
}
};
typedef UniquePtr<STACK_OF(SSL_CIPHER), sk_SSL_CIPHER_Delete> Unique_sk_SSL_CIPHER;
struct sk_X509_Delete {
void operator()(STACK_OF(X509)* p) const {
sk_X509_pop_free(p, X509_free);
}
};
typedef UniquePtr<STACK_OF(X509), sk_X509_Delete> Unique_sk_X509;
struct sk_X509_NAME_Delete {
void operator()(STACK_OF(X509_NAME)* p) const {
sk_X509_NAME_pop_free(p, X509_NAME_free);
}
};
typedef UniquePtr<STACK_OF(X509_NAME), sk_X509_NAME_Delete> Unique_sk_X509_NAME;
struct sk_ASN1_OBJECT_Delete {
void operator()(STACK_OF(ASN1_OBJECT)* p) const {
sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
}
};
typedef UniquePtr<STACK_OF(ASN1_OBJECT), sk_ASN1_OBJECT_Delete> Unique_sk_ASN1_OBJECT;
struct sk_GENERAL_NAME_Delete {
void operator()(STACK_OF(GENERAL_NAME)* p) const {
sk_GENERAL_NAME_pop_free(p, GENERAL_NAME_free);
}
};
typedef UniquePtr<STACK_OF(GENERAL_NAME), sk_GENERAL_NAME_Delete> Unique_sk_GENERAL_NAME;
/**
* Many OpenSSL APIs take ownership of an argument on success but don't free the argument
* on failure. This means we need to tell our scoped pointers when we've transferred ownership,
* without triggering a warning by not using the result of release().
*/
#define OWNERSHIP_TRANSFERRED(obj) \
do { typeof (obj.release()) _dummy __attribute__((unused)) = obj.release(); } while(0)
/**
* Frees the SSL error state.
*
* OpenSSL keeps an "error stack" per thread, and given that this code
* can be called from arbitrary threads that we don't keep track of,
* we err on the side of freeing the error state promptly (instead of,
* say, at thread death).
*/
static void freeOpenSslErrorState(void) {
ERR_clear_error();
ERR_remove_state(0);
}
/**
* Throws a OutOfMemoryError with the given string as a message.
*/
static void jniThrowOutOfMemory(JNIEnv* env, const char* message) {
jniThrowException(env, "java/lang/OutOfMemoryError", message);
}
/**
* Throws a BadPaddingException with the given string as a message.
*/
static void throwBadPaddingException(JNIEnv* env, const char* message) {
JNI_TRACE("throwBadPaddingException %s", message);
jniThrowException(env, "javax/crypto/BadPaddingException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwSignatureException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSignatureException %s", message);
jniThrowException(env, "java/security/SignatureException", message);
}
/**
* Throws a InvalidKeyException with the given string as a message.
*/
static void throwInvalidKeyException(JNIEnv* env, const char* message) {
JNI_TRACE("throwInvalidKeyException %s", message);
jniThrowException(env, "java/security/InvalidKeyException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwIllegalBlockSizeException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalBlockSizeException %s", message);
jniThrowException(env, "javax/crypto/IllegalBlockSizeException", message);
}
/**
* Throws a NoSuchAlgorithmException with the given string as a message.
*/
static void throwNoSuchAlgorithmException(JNIEnv* env, const char* message) {
JNI_TRACE("throwUnknownAlgorithmException %s", message);
jniThrowException(env, "java/security/NoSuchAlgorithmException", message);
}
static void throwForAsn1Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case ASN1_R_UNABLE_TO_DECODE_RSA_KEY:
case ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY:
case ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE:
case ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE:
case ASN1_R_WRONG_PUBLIC_KEY_TYPE:
throwInvalidKeyException(env, message);
break;
case ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForEvpError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case EVP_R_BAD_DECRYPT:
throwBadPaddingException(env, message);
break;
case EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case EVP_R_WRONG_FINAL_BLOCK_LENGTH:
throwIllegalBlockSizeException(env, message);
break;
case EVP_R_BAD_KEY_LENGTH:
case EVP_R_BN_DECODE_ERROR:
case EVP_R_BN_PUBKEY_ERROR:
case EVP_R_INVALID_KEY_LENGTH:
case EVP_R_MISSING_PARAMETERS:
case EVP_R_UNSUPPORTED_KEY_SIZE:
case EVP_R_UNSUPPORTED_KEYLENGTH:
throwInvalidKeyException(env, message);
break;
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
throwSignatureException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForRsaError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case RSA_R_BLOCK_TYPE_IS_NOT_01:
case RSA_R_BLOCK_TYPE_IS_NOT_02:
throwBadPaddingException(env, message);
break;
case RSA_R_ALGORITHM_MISMATCH:
case RSA_R_BAD_SIGNATURE:
case RSA_R_DATA_GREATER_THAN_MOD_LEN:
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
case RSA_R_INVALID_MESSAGE_LENGTH:
case RSA_R_WRONG_SIGNATURE_LENGTH:
throwSignatureException(env, message);
break;
case RSA_R_UNKNOWN_ALGORITHM_TYPE:
throwNoSuchAlgorithmException(env, message);
break;
case RSA_R_MODULUS_TOO_LARGE:
case RSA_R_NO_PUBLIC_EXPONENT:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForX509Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case X509_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
/*
* Checks this thread's OpenSSL error queue and throws a RuntimeException if
* necessary.
*
* @return true if an exception was thrown, false if not.
*/
static bool throwExceptionIfNecessary(JNIEnv* env, const char* location __attribute__ ((unused))) {
const char* file;
int line;
const char* data;
int flags;
unsigned long error = ERR_get_error_line_data(&file, &line, &data, &flags);
int result = false;
if (error != 0) {
char message[256];
ERR_error_string_n(error, message, sizeof(message));
int library = ERR_GET_LIB(error);
int reason = ERR_GET_REASON(error);
JNI_TRACE("OpenSSL error in %s error=%lx library=%x reason=%x (%s:%d): %s %s",
location, error, library, reason, file, line, message,
(flags & ERR_TXT_STRING) ? data : "(no data)");
switch (library) {
case ERR_LIB_RSA:
throwForRsaError(env, reason, message);
break;
case ERR_LIB_ASN1:
throwForAsn1Error(env, reason, message);
break;
case ERR_LIB_EVP:
throwForEvpError(env, reason, message);
break;
case ERR_LIB_X509:
throwForX509Error(env, reason, message);
break;
case ERR_LIB_DSA:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
result = true;
}
freeOpenSslErrorState();
return result;
}
/**
* Throws an SocketTimeoutException with the given string as a message.
*/
static void throwSocketTimeoutException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSocketTimeoutException %s", message);
jniThrowException(env, "java/net/SocketTimeoutException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLHandshakeExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLHandshakeException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLException", message);
}
/**
* Throws a javax.net.ssl.SSLProcotolException with the given string as a message.
*/
static void throwSSLProtocolExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLProtocolExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLProtocolException", message);
}
/**
* Throws an SSLException with a message constructed from the current
* SSL errors. This will also log the errors.
*
* @param env the JNI environment
* @param ssl the possibly NULL SSL
* @param sslErrorCode error code returned from SSL_get_error() or
* SSL_ERROR_NONE to probe with ERR_get_error
* @param message null-ok; general error message
*/
static void throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCode,
const char* message, void (*actualThrow)(JNIEnv*, const char*) = throwSSLExceptionStr) {
if (message == NULL) {
message = "SSL error";
}
// First consult the SSL error code for the general message.
const char* sslErrorStr = NULL;
switch (sslErrorCode) {
case SSL_ERROR_NONE:
if (ERR_peek_error() == 0) {
sslErrorStr = "OK";
} else {
sslErrorStr = "";
}
break;
case SSL_ERROR_SSL:
sslErrorStr = "Failure in SSL library, usually a protocol error";
break;
case SSL_ERROR_WANT_READ:
sslErrorStr = "SSL_ERROR_WANT_READ occurred. You should never see this.";
break;
case SSL_ERROR_WANT_WRITE:
sslErrorStr = "SSL_ERROR_WANT_WRITE occurred. You should never see this.";
break;
case SSL_ERROR_WANT_X509_LOOKUP:
sslErrorStr = "SSL_ERROR_WANT_X509_LOOKUP occurred. You should never see this.";
break;
case SSL_ERROR_SYSCALL:
sslErrorStr = "I/O error during system call";
break;
case SSL_ERROR_ZERO_RETURN:
sslErrorStr = "SSL_ERROR_ZERO_RETURN occurred. You should never see this.";
break;
case SSL_ERROR_WANT_CONNECT:
sslErrorStr = "SSL_ERROR_WANT_CONNECT occurred. You should never see this.";
break;
case SSL_ERROR_WANT_ACCEPT:
sslErrorStr = "SSL_ERROR_WANT_ACCEPT occurred. You should never see this.";
break;
default:
sslErrorStr = "Unknown SSL error";
}
// Prepend either our explicit message or a default one.
char* str;
if (asprintf(&str, "%s: ssl=%p: %s", message, ssl, sslErrorStr) <= 0) {
// problem with asprintf, just throw argument message, log everything
actualThrow(env, message);
ALOGV("%s: ssl=%p: %s", message, ssl, sslErrorStr);
freeOpenSslErrorState();
return;
}
char* allocStr = str;
// For protocol errors, SSL might have more information.
if (sslErrorCode == SSL_ERROR_NONE || sslErrorCode == SSL_ERROR_SSL) {
// Append each error as an additional line to the message.
for (;;) {
char errStr[256];
const char* file;
int line;
const char* data;
int flags;
unsigned long err = ERR_get_error_line_data(&file, &line, &data, &flags);
if (err == 0) {
break;
}
ERR_error_string_n(err, errStr, sizeof(errStr));
int ret = asprintf(&str, "%s\n%s (%s:%d %p:0x%08x)",
(allocStr == NULL) ? "" : allocStr,
errStr,
file,
line,
(flags & ERR_TXT_STRING) ? data : "(no data)",
flags);
if (ret < 0) {
break;
}
free(allocStr);
allocStr = str;
}
// For errors during system calls, errno might be our friend.
} else if (sslErrorCode == SSL_ERROR_SYSCALL) {
if (asprintf(&str, "%s, %s", allocStr, strerror(errno)) >= 0) {
free(allocStr);
allocStr = str;
}
// If the error code is invalid, print it.
} else if (sslErrorCode > SSL_ERROR_WANT_ACCEPT) {
if (asprintf(&str, ", error code is %d", sslErrorCode) >= 0) {
free(allocStr);
allocStr = str;
}
}
if (sslErrorCode == SSL_ERROR_SSL) {
throwSSLProtocolExceptionStr(env, allocStr);
} else {
actualThrow(env, allocStr);
}
ALOGV("%s", allocStr);
free(allocStr);
freeOpenSslErrorState();
}
/**
* Helper function that grabs the casts an ssl pointer and then checks for nullness.
* If this function returns NULL and <code>throwIfNull</code> is
* passed as <code>true</code>, then this function will call
* <code>throwSSLExceptionStr</code> before returning, so in this case of
* NULL, a caller of this function should simply return and allow JNI
* to do its thing.
*
* @param env the JNI environment
* @param ssl_address; the ssl_address pointer as an integer
* @param throwIfNull whether to throw if the SSL pointer is NULL
* @returns the pointer, which may be NULL
*/
static SSL_CTX* to_SSL_CTX(JNIEnv* env, jlong ssl_ctx_address, bool throwIfNull) {
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
if ((ssl_ctx == NULL) && throwIfNull) {
JNI_TRACE("ssl_ctx == null");
jniThrowNullPointerException(env, "ssl_ctx == null");
}
return ssl_ctx;
}
static SSL* to_SSL(JNIEnv* env, jlong ssl_address, bool throwIfNull) {
SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
if ((ssl == NULL) && throwIfNull) {
JNI_TRACE("ssl == null");
jniThrowNullPointerException(env, "ssl == null");
}
return ssl;
}
static SSL_SESSION* to_SSL_SESSION(JNIEnv* env, jlong ssl_session_address, bool throwIfNull) {
SSL_SESSION* ssl_session
= reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
if ((ssl_session == NULL) && throwIfNull) {
JNI_TRACE("ssl_session == null");
jniThrowNullPointerException(env, "ssl_session == null");
}
return ssl_session;
}
static SSL_CIPHER* to_SSL_CIPHER(JNIEnv* env, jlong ssl_cipher_address, bool throwIfNull) {
SSL_CIPHER* ssl_cipher
= reinterpret_cast<SSL_CIPHER*>(static_cast<uintptr_t>(ssl_cipher_address));
if ((ssl_cipher == NULL) && throwIfNull) {
JNI_TRACE("ssl_cipher == null");
jniThrowNullPointerException(env, "ssl_cipher == null");
}
return ssl_cipher;
}
template<typename T>
static T* fromContextObject(JNIEnv* env, jobject contextObject) {
T* ref = reinterpret_cast<T*>(env->GetLongField(contextObject, openSslNativeReference_context));
if (ref == NULL) {
JNI_TRACE("ctx == null");
jniThrowNullPointerException(env, "ctx == null");
}
return ref;
}
/**
* Converts a Java byte[] two's complement to an OpenSSL BIGNUM. This will
* allocate the BIGNUM if *dest == NULL. Returns true on success. If the
* return value is false, there is a pending exception.
*/
static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
JNI_TRACE("arrayToBignum(%p, %p)", source, dest);
if (dest == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => dest is null!", source, dest);
jniThrowNullPointerException(env, "dest == null");
return false;
}
JNI_TRACE("arrayToBignum(%p, %p) *dest == %p", source, dest, *dest);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
/* if the array is empty, it is zero. */
if (tmpSize == 0) {
if (*dest == NULL) {
*dest = BN_new();
}
BN_zero(*dest);
return true;
}
UniquePtr<unsigned char[]> twosComplement;
bool negative = (tmp[0] & 0x80) != 0;
if (negative) {
// Need to convert to two's complement.
twosComplement.reset(new unsigned char[tmpSize]);
unsigned char* twosBytes = reinterpret_cast<unsigned char*>(twosComplement.get());
memcpy(twosBytes, tmp, tmpSize);
tmp = twosBytes;
bool carry = true;
for (ssize_t i = tmpSize - 1; i >= 0; i--) {
twosBytes[i] ^= 0xFF;
if (carry) {
carry = (++twosBytes[i]) == 0;
}
}
}
BIGNUM *ret = BN_bin2bn(tmp, tmpSize, *dest);
if (ret == NULL) {
jniThrowRuntimeException(env, "Conversion to BIGNUM failed");
JNI_TRACE("arrayToBignum(%p, %p) => threw exception", source, dest);
return false;
}
BN_set_negative(ret, negative ? 1 : 0);
*dest = ret;
JNI_TRACE("arrayToBignum(%p, %p) => *dest = %p", source, dest, ret);
return true;
}
/**
* Converts an OpenSSL BIGNUM to a Java byte[] array in two's complement.
*/
static jbyteArray bignumToArray(JNIEnv* env, const BIGNUM* source, const char* sourceName) {
JNI_TRACE("bignumToArray(%p, %s)", source, sourceName);
if (source == NULL) {
jniThrowNullPointerException(env, sourceName);
return NULL;
}
size_t numBytes = BN_num_bytes(source) + 1;
jbyteArray javaBytes = env->NewByteArray(numBytes);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bignumToArray(%p, %s) => NULL", source, sourceName);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
if (BN_num_bytes(source) > 0 && BN_bn2bin(source, tmp + 1) <= 0) {
throwExceptionIfNecessary(env, "bignumToArray");
return NULL;
}
// Set the sign and convert to two's complement if necessary for the Java code.
if (BN_is_negative(source)) {
bool carry = true;
for (ssize_t i = numBytes - 1; i >= 0; i--) {
tmp[i] ^= 0xFF;
if (carry) {
carry = (++tmp[i]) == 0;
}
}
*tmp |= 0x80;
} else {
*tmp = 0x00;
}
JNI_TRACE("bignumToArray(%p, %s) => %p", source, sourceName, javaBytes);
return javaBytes;
}
/**
* Converts various OpenSSL ASN.1 types to a jbyteArray with DER-encoded data
* inside. The "i2d_func" function pointer is a function of the "i2d_<TYPE>"
* from the OpenSSL ASN.1 API.
*/
template<typename T, int (*i2d_func)(T*, unsigned char**)>
jbyteArray ASN1ToByteArray(JNIEnv* env, T* obj) {
if (obj == NULL) {
jniThrowNullPointerException(env, "ASN1 input == null");
JNI_TRACE("ASN1ToByteArray(%p) => null input", obj);
return NULL;
}
int derLen = i2d_func(obj, NULL);
if (derLen < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => measurement failed", obj);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => creating byte array failed", obj);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => using byte array failed", obj);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
int ret = i2d_func(obj, &p);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => final conversion failed", obj);
return NULL;
}
JNI_TRACE("ASN1ToByteArray(%p) => success (%d bytes written)", obj, ret);
return byteArray.release();
}
template<typename T, T* (*d2i_func)(T**, const unsigned char**, long)>
T* ByteArrayToASN1(JNIEnv* env, jbyteArray byteArray) {
ScopedByteArrayRO bytes(env, byteArray);
if (bytes.get() == NULL) {
JNI_TRACE("ByteArrayToASN1(%p) => using byte array failed", byteArray);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
return d2i_func(NULL, &tmp, bytes.size());
}
/**
* Converts ASN.1 BIT STRING to a jbooleanArray.
*/
jbooleanArray ASN1BitStringToBooleanArray(JNIEnv* env, ASN1_BIT_STRING* bitStr) {
int size = bitStr->length * 8;
if (bitStr->flags & ASN1_STRING_FLAG_BITS_LEFT) {
size -= bitStr->flags & 0x07;
}
ScopedLocalRef<jbooleanArray> bitsRef(env, env->NewBooleanArray(size));
if (bitsRef.get() == NULL) {
return NULL;
}
ScopedBooleanArrayRW bitsArray(env, bitsRef.get());
for (int i = 0; i < static_cast<int>(bitsArray.size()); i++) {
bitsArray[i] = ASN1_BIT_STRING_get_bit(bitStr, i);
}
return bitsRef.release();
}
/**
* To avoid the round-trip to ASN.1 and back in X509_dup, we just up the reference count.
*/
static X509* X509_dup_nocopy(X509* x509) {
if (x509 == NULL) {
return NULL;
}
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509);
return x509;
}
/*
* Sets the read and write BIO for an SSL connection and removes it when it goes out of scope.
* We hang on to BIO with a JNI GlobalRef and we want to remove them as soon as possible.
*/
class ScopedSslBio {
public:
ScopedSslBio(SSL *ssl, BIO* rbio, BIO* wbio) : ssl_(ssl) {
SSL_set_bio(ssl_, rbio, wbio);
CRYPTO_add(&rbio->references,1,CRYPTO_LOCK_BIO);
CRYPTO_add(&wbio->references,1,CRYPTO_LOCK_BIO);
}
~ScopedSslBio() {
SSL_set_bio(ssl_, NULL, NULL);
}
private:
SSL* const ssl_;
};
/**
* BIO for InputStream
*/
class BIO_Stream {
public:
BIO_Stream(jobject stream) :
mEof(false) {
JNIEnv* env = getEnv();
mStream = env->NewGlobalRef(stream);
}
~BIO_Stream() {
JNIEnv* env = getEnv();
env->DeleteGlobalRef(mStream);
}
bool isEof() const {
JNI_TRACE("isEof? %s", mEof ? "yes" : "no");
return mEof;
}
int flush() {
JNIEnv* env = getEnv();
if (env == NULL) {
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_Stream::flush called with pending exception");
return -1;
}
env->CallVoidMethod(mStream, outputStream_flushMethod);
if (env->ExceptionCheck()) {
return -1;
}
return 1;
}
protected:
jobject getStream() {
return mStream;
}
void setEof(bool eof) {
mEof = eof;
}
JNIEnv* getEnv() {
JNIEnv* env;
if (gJavaVM->AttachCurrentThread(&env, NULL) < 0) {
return NULL;
}
return env;
}
private:
jobject mStream;
bool mEof;
};
class BIO_InputStream : public BIO_Stream {
public:
BIO_InputStream(jobject stream) :
BIO_Stream(stream) {
}
int read(char *buf, int len) {
return read_internal(buf, len, inputStream_readMethod);
}
int gets(char *buf, int len) {
if (len > PEM_LINE_LENGTH) {
len = PEM_LINE_LENGTH;
}
int read = read_internal(buf, len - 1, openSslInputStream_readLineMethod);
buf[read] = '\0';
JNI_TRACE("BIO::gets \"%s\"", buf);
return read;
}
private:
int read_internal(char *buf, int len, jmethodID method) {
JNIEnv* env = getEnv();
if (env == NULL) {
JNI_TRACE("BIO_InputStream::read could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_InputStream::read failed call to NewByteArray");
return -1;
}
jint read = env->CallIntMethod(getStream(), method, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read failed call to InputStream#read");
return -1;
}
/* Java uses -1 to indicate EOF condition. */
if (read == -1) {
setEof(true);
read = 0;
} else if (read > 0) {
env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast<jbyte*>(buf));
}
return read;
}
public:
/** Length of PEM-encoded line (64) plus CR plus NULL */
static const int PEM_LINE_LENGTH = 66;
};
class BIO_OutputStream : public BIO_Stream {
public:
BIO_OutputStream(jobject stream) :
BIO_Stream(stream) {
}
int write(const char *buf, int len) {
JNIEnv* env = getEnv();
if (env == NULL) {
JNI_TRACE("BIO_OutputStream::write => could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_OutputStream::write => failed call to NewByteArray");
return -1;
}
env->SetByteArrayRegion(javaBytes.get(), 0, len, reinterpret_cast<const jbyte*>(buf));
env->CallVoidMethod(getStream(), outputStream_writeMethod, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => failed call to OutputStream#write");
return -1;
}
return len;
}
};
static int bio_stream_create(BIO *b) {
b->init = 1;
b->num = 0;
b->ptr = NULL;
b->flags = 0;
return 1;
}
static int bio_stream_destroy(BIO *b) {
if (b == NULL) {
return 0;
}
if (b->ptr != NULL) {
delete static_cast<BIO_Stream*>(b->ptr);
b->ptr = NULL;
}
b->init = 0;
b->flags = 0;
return 1;
}
static int bio_stream_read(BIO *b, char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
int ret = stream->read(buf, len);
if (ret == 0) {
// EOF is indicated by -1 with a BIO flag.
BIO_set_retry_read(b);
return -1;
}
return ret;
}
static int bio_stream_write(BIO *b, const char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, len);
}
static int bio_stream_puts(BIO *b, const char *buf) {
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, strlen(buf));
}
static int bio_stream_gets(BIO *b, char *buf, int len) {
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
return stream->gets(buf, len);
}
static void bio_stream_assign(BIO *b, BIO_Stream* stream) {
b->ptr = static_cast<void*>(stream);
}
static long bio_stream_ctrl(BIO *b, int cmd, long, void *) {
BIO_Stream* stream = static_cast<BIO_Stream*>(b->ptr);
switch (cmd) {
case BIO_CTRL_EOF:
return stream->isEof() ? 1 : 0;
case BIO_CTRL_FLUSH:
return stream->flush();
default:
return 0;
}
}
static BIO_METHOD stream_bio_method = {
( 100 | 0x0400 ), /* source/sink BIO */
"InputStream/OutputStream BIO",
bio_stream_write, /* bio_write */
bio_stream_read, /* bio_read */
bio_stream_puts, /* bio_puts */
bio_stream_gets, /* bio_gets */
bio_stream_ctrl, /* bio_ctrl */
bio_stream_create, /* bio_create */
bio_stream_destroy, /* bio_free */
NULL, /* no bio_callback_ctrl */
};
/**
* Copied from libnativehelper NetworkUtilites.cpp
*/
static bool setBlocking(int fd, bool blocking) {
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
return false;
}
if (!blocking) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int rc = fcntl(fd, F_SETFL, flags);
return (rc != -1);
}
/**
* OpenSSL locking support. Taken from the O'Reilly book by Viega et al., but I
* suppose there are not many other ways to do this on a Linux system (modulo
* isomorphism).
*/
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#define THROW_SSLEXCEPTION (-2)
#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
#define THROWN_EXCEPTION (-4)
static MUTEX_TYPE* mutex_buf = NULL;
static void locking_function(int mode, int n, const char*, int) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(mutex_buf[n]);
} else {
MUTEX_UNLOCK(mutex_buf[n]);
}
}
static unsigned long id_function(void) {
return ((unsigned long)THREAD_ID);
}
int THREAD_setup(void) {
mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
if (!mutex_buf) {
return 0;
}
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
MUTEX_SETUP(mutex_buf[i]);
}
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int THREAD_cleanup(void) {
if (!mutex_buf) {
return 0;
}
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks( ); i++) {
MUTEX_CLEANUP(mutex_buf[i]);
}
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
/**
* Initialization phase for every OpenSSL job: Loads the Error strings, the
* crypto algorithms and reset the OpenSSL library
*/
static void NativeCrypto_clinit(JNIEnv*, jclass)
{
SSL_load_error_strings();
ERR_load_crypto_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
THREAD_setup();
}
static void NativeCrypto_ENGINE_load_dynamic(JNIEnv*, jclass) {
JNI_TRACE("ENGINE_load_dynamic()");
ENGINE_load_dynamic();
}
static jlong NativeCrypto_ENGINE_by_id(JNIEnv* env, jclass, jstring idJava) {
JNI_TRACE("ENGINE_by_id(%p)", idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
JNI_TRACE("ENGINE_by_id(%p) => id == null", idJava);
return 0;
}
JNI_TRACE("ENGINE_by_id(\"%s\")", id.c_str());
ENGINE* e = ENGINE_by_id(id.c_str());
if (e == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("ENGINE_by_id(\"%s\") => %p", id.c_str(), e);
return reinterpret_cast<uintptr_t>(e);
}
static jint NativeCrypto_ENGINE_add(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_add(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_add(e);
/*
* We tolerate errors, because the most likely error is that
* the ENGINE is already in the list.
*/
freeOpenSslErrorState();
JNI_TRACE("ENGINE_add(%p) => %d", e, ret);
return ret;
}
static jint NativeCrypto_ENGINE_init(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_init(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_init(e);
JNI_TRACE("ENGINE_init(%p) => %d", e, ret);
return ret;
}
static jint NativeCrypto_ENGINE_finish(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_finish(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_finish(e);
JNI_TRACE("ENGINE_finish(%p) => %d", e, ret);
return ret;
}
static jint NativeCrypto_ENGINE_free(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_free(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_free(e);
JNI_TRACE("ENGINE_free(%p) => %d", e, ret);
return ret;
}
static jlong NativeCrypto_ENGINE_load_private_key(JNIEnv* env, jclass, jlong engineRef,
jstring idJava) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_load_private_key(%p, %p)", e, idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "id == NULL");
return 0;
}
Unique_EVP_PKEY pkey(ENGINE_load_private_key(e, id.c_str(), NULL, NULL));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("ENGINE_load_private_key(%p, %p) => %p", e, idJava, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong engineRef)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_get_id(%p)", e);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_get_id(%p) => engine == null", e);
return NULL;
}
const char *id = ENGINE_get_id(e);
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF(id));
JNI_TRACE("ENGINE_get_id(%p) => \"%s\"", e, id);
return idJava.release();
}
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv* env, jclass, jlong engineRef,
jstring cmdJava, jstring argJava, jint cmd_optional)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d)", e, cmdJava, argJava, cmd_optional);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d) => engine == null", e, cmdJava, argJava,
cmd_optional);
return 0;
}
ScopedUtfChars cmdChars(env, cmdJava);
if (cmdChars.c_str() == NULL) {
return 0;
}
UniquePtr<ScopedUtfChars> arg;
const char* arg_c_str = NULL;
if (argJava != NULL) {
arg.reset(new ScopedUtfChars(env, argJava));
arg_c_str = arg->c_str();
if (arg_c_str == NULL) {
return 0;
}
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d)", e, cmdChars.c_str(), arg_c_str,
cmd_optional);
int ret = ENGINE_ctrl_cmd_string(e, cmdChars.c_str(), arg_c_str, cmd_optional);
if (ret != 1) {
throwExceptionIfNecessary(env, "ENGINE_ctrl_cmd_string");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => threw error", e,
cmdChars.c_str(), arg_c_str, cmd_optional);
return 0;
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => %d", e, cmdChars.c_str(),
arg_c_str, cmd_optional, ret);
return ret;
}
static jlong NativeCrypto_EVP_PKEY_new_DH(JNIEnv* env, jclass,
jbyteArray p, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p)",
p, g, pub_key, priv_key);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
jniThrowRuntimeException(env, "DH_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dh->p)) {
return 0;
}
if (!arrayToBignum(env, g, &dh->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dh->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dh->priv_key)) {
return 0;
}
if (dh->p == NULL || dh->g == NULL
|| (dh->pub_key == NULL && dh->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DH failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* public static native int EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g,
* byte[] pub_key, byte[] priv_key);
*/
static jlong NativeCrypto_EVP_PKEY_new_DSA(JNIEnv* env, jclass,
jbyteArray p, jbyteArray q, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DSA(p=%p, q=%p, g=%p, pub_key=%p, priv_key=%p)",
p, q, g, pub_key, priv_key);
Unique_DSA dsa(DSA_new());
if (dsa.get() == NULL) {
jniThrowRuntimeException(env, "DSA_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dsa->p)) {
return 0;
}
if (!arrayToBignum(env, q, &dsa->q)) {
return 0;
}
if (!arrayToBignum(env, g, &dsa->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dsa->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dsa->priv_key)) {
return 0;
}
if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL
|| (dsa->pub_key == NULL && dsa->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DSA(pkey.get(), dsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DSA failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dsa);
JNI_TRACE("EVP_PKEY_new_DSA(p=%p, q=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, q, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
*/
static jlong NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass,
jbyteArray n, jbyteArray e, jbyteArray d,
jbyteArray p, jbyteArray q,
jbyteArray dmp1, jbyteArray dmq1,
jbyteArray iqmp) {
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p, dmp1=%p, dmq1=%p, iqmp=%p)",
n, e, d, p, q, dmp1, dmq1, iqmp);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_new failed");
return 0;
}
if (e == NULL && d == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "e == NULL && d == NULL");
JNI_TRACE("NativeCrypto_EVP_PKEY_new_RSA => e == NULL && d == NULL");
return 0;
}
if (!arrayToBignum(env, n, &rsa->n)) {
return 0;
}
if (e != NULL && !arrayToBignum(env, e, &rsa->e)) {
return 0;
}
if (d != NULL && !arrayToBignum(env, d, &rsa->d)) {
return 0;
}
if (p != NULL && !arrayToBignum(env, p, &rsa->p)) {
return 0;
}
if (q != NULL && !arrayToBignum(env, q, &rsa->q)) {
return 0;
}
if (dmp1 != NULL && !arrayToBignum(env, dmp1, &rsa->dmp1)) {
return 0;
}
if (dmq1 != NULL && !arrayToBignum(env, dmq1, &rsa->dmq1)) {
return 0;
}
if (iqmp != NULL && !arrayToBignum(env, iqmp, &rsa->iqmp)) {
return 0;
}
#ifdef WITH_JNI_TRACE
if (p != NULL && q != NULL) {
int check = RSA_check_key(rsa.get());
JNI_TRACE("EVP_PKEY_new_RSA(...) RSA_check_key returns %d", check);
}
#endif
if (rsa->n == NULL || (rsa->e == NULL && rsa->d == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/*
* If the private exponent is available, there is the potential to do signing
* operations. If the public exponent is also available, OpenSSL will do RSA
* blinding. Enable it if possible.
*/
if (rsa->d != NULL) {
if (rsa->e != NULL) {
JNI_TRACE("EVP_PKEY_new_RSA(...) enabling RSA blinding => %p", rsa.get());
RSA_blinding_on(rsa.get(), NULL);
} else {
JNI_TRACE("EVP_PKEY_new_RSA(...) disabling RSA blinding => %p", rsa.get());
RSA_blinding_off(rsa.get());
}
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p dmp1=%p, dmq1=%p, iqmp=%p) => %p",
n, e, d, p, q, dmp1, dmq1, iqmp, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_EC_KEY(JNIEnv* env, jclass, jlong groupRef,
jlong pubkeyRef, jbyteArray keyJavaBytes) {
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
const EC_POINT* pubkey = reinterpret_cast<const EC_POINT*>(pubkeyRef);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p)", group, pubkey, keyJavaBytes);
Unique_BIGNUM key(NULL);
if (keyJavaBytes != NULL) {
BIGNUM* keyRef = NULL;
if (!arrayToBignum(env, keyJavaBytes, &keyRef)) {
return 0;
}
key.reset(keyRef);
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
jniThrowRuntimeException(env, "EC_KEY_new failed");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) > EC_KEY_set_group failed", group, pubkey,
keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (pubkey != NULL) {
if (EC_KEY_set_public_key(eckey.get(), pubkey) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_public_key");
return 0;
}
}
if (key.get() != NULL) {
if (EC_KEY_set_private_key(eckey.get(), key.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
if (pubkey == NULL) {
Unique_EC_POINT calcPubkey(EC_POINT_new(group));
if (!EC_POINT_mul(group, calcPubkey.get(), key.get(), NULL, NULL, NULL)) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => can't calulate public key", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
EC_KEY_set_public_key(eckey.get(), calcPubkey.get());
}
}
if (!EC_KEY_check_key(eckey.get())) {
JNI_TRACE("EVP_KEY_new_EC_KEY(%p, %p, %p) => invalid key created", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_check_key");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => %p", group, pubkey, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_mac_key(JNIEnv* env, jclass, jint pkeyType,
jbyteArray keyJavaBytes)
{
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p)", pkeyType, keyJavaBytes);
ScopedByteArrayRO key(env, keyJavaBytes);
if (key.get() == NULL) {
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(key.get());
Unique_EVP_PKEY pkey(EVP_PKEY_new_mac_key(pkeyType, (ENGINE *) NULL, tmp, key.size()));
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => threw error", pkeyType, keyJavaBytes);
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => %p", pkeyType, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static int NativeCrypto_EVP_PKEY_type(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_type(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_type(pkey->type);
JNI_TRACE("EVP_PKEY_type(%p) => %d", pkey, result);
return result;
}
/**
* private static native int EVP_PKEY_size(int pkey);
*/
static int NativeCrypto_EVP_PKEY_size(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_size(pkey);
JNI_TRACE("EVP_PKEY_size(%p) => %d", pkey, result);
return result;
}
static jstring NativeCrypto_EVP_PKEY_print_public(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_print_public(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_public(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_public");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_public(%p) => \"%s\"", pkey, tmp);
return description;
}
static jstring NativeCrypto_EVP_PKEY_print_private(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_print_private(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_private(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_private");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_private(%p) => \"%s\"", pkey, tmp);
return description;
}
static void NativeCrypto_EVP_PKEY_free(JNIEnv*, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_free(%p)", pkey);
if (pkey != NULL) {
EVP_PKEY_free(pkey);
}
}
static jint NativeCrypto_EVP_PKEY_cmp(JNIEnv* env, jclass, jlong pkey1Ref, jlong pkey2Ref) {
EVP_PKEY* pkey1 = reinterpret_cast<EVP_PKEY*>(pkey1Ref);
EVP_PKEY* pkey2 = reinterpret_cast<EVP_PKEY*>(pkey2Ref);
JNI_TRACE("EVP_PKEY_cmp(%p, %p)", pkey1, pkey2);
if (pkey1 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey1 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey1 == NULL");
return -1;
} else if (pkey2 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey2 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey2 == NULL");
return -1;
}
int result = EVP_PKEY_cmp(pkey1, pkey2);
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => %d", pkey1, pkey2, result);
return result;
}
/*
* static native byte[] i2d_PKCS8_PRIV_KEY_INFO(int, byte[])
*/
static jbyteArray NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("i2d_PKCS8_PRIV_KEY_INFO(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return NULL;
}
Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("key=%p i2d_PKCS8_PRIV_KEY_INFO => error from key to PKCS8", pkey);
return NULL;
}
return ASN1ToByteArray<PKCS8_PRIV_KEY_INFO, i2d_PKCS8_PRIV_KEY_INFO>(env, pkcs8.get());
}
/*
* static native int d2i_PKCS8_PRIV_KEY_INFO(byte[])
*/
static jlong NativeCrypto_d2i_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jbyteArray keyJavaBytes) {
JNI_TRACE("d2i_PKCS8_PRIV_KEY_INFO(%p)", keyJavaBytes);
ScopedByteArrayRO bytes(env, keyJavaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => threw exception", keyJavaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &tmp, bytes.size()));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from DER to PKCS8", keyJavaBytes);
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from PKCS8 to key", keyJavaBytes);
return 0;
}
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => %p", keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* static native byte[] i2d_PUBKEY(int)
*/
static jbyteArray NativeCrypto_i2d_PUBKEY(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("i2d_PUBKEY(%p)", pkey);
return ASN1ToByteArray<EVP_PKEY, i2d_PUBKEY>(env, pkey);
}
/*
* static native int d2i_PUBKEY(byte[])
*/
static jlong NativeCrypto_d2i_PUBKEY(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("d2i_PUBKEY(%p)", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("d2i_PUBKEY(%p) => threw error", javaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, bytes.size()));
if (pkey.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PUBKEY => threw exception", javaBytes);
throwExceptionIfNecessary(env, "d2i_PUBKEY");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native int RSA_generate_key(int modulusBits, byte[] publicExponent);
*/
static jlong NativeCrypto_RSA_generate_key_ex(JNIEnv* env, jclass, jint modulusBits,
jbyteArray publicExponent) {
JNI_TRACE("RSA_generate_key_ex(%d, %p)", modulusBits, publicExponent);
BIGNUM* eRef = NULL;
if (!arrayToBignum(env, publicExponent, &eRef)) {
return 0;
}
Unique_BIGNUM e(eRef);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
if (RSA_generate_key_ex(rsa.get(), modulusBits, e.get(), NULL) < 0) {
throwExceptionIfNecessary(env, "RSA_generate_key_ex");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("RSA_generate_key_ex(n=%d, e=%p) => %p", modulusBits, publicExponent, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jint NativeCrypto_RSA_size(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("RSA_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_size failed");
return 0;
}
return static_cast<jint>(RSA_size(rsa.get()));
}
typedef int RSACryptOperation(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
int padding);
static jint RSA_crypt_operation(RSACryptOperation operation,
const char* caller __attribute__ ((unused)), JNIEnv* env, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("%s(%d, %p, %p, %p)", caller, flen, fromJavaBytes, toJavaBytes, pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return -1;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
return -1;
}
ScopedByteArrayRO from(env, fromJavaBytes);
if (from.get() == NULL) {
return -1;
}
ScopedByteArrayRW to(env, toJavaBytes);
if (to.get() == NULL) {
return -1;
}
int resultSize = operation(static_cast<int>(flen),
reinterpret_cast<const unsigned char*>(from.get()),
reinterpret_cast<unsigned char*>(to.get()), rsa.get(), padding);
if (resultSize == -1) {
JNI_TRACE("%s => failed", caller);
throwExceptionIfNecessary(env, "RSA_crypt_operation");
return -1;
}
JNI_TRACE("%s(%d, %p, %p, %p) => %d", caller, flen, fromJavaBytes, toJavaBytes, pkey,
resultSize);
return static_cast<jint>(resultSize);
}
static jint NativeCrypto_RSA_private_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_private_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jlong pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
/*
* public static native byte[][] get_RSA_public_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_public_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
return joa;
}
/*
* public static native byte[][] get_RSA_private_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_private_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(8, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
if (rsa->e != NULL) {
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
}
if (rsa->d != NULL) {
jbyteArray d = bignumToArray(env, rsa->d, "d");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, d);
}
if (rsa->p != NULL) {
jbyteArray p = bignumToArray(env, rsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, p);
}
if (rsa->q != NULL) {
jbyteArray q = bignumToArray(env, rsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, q);
}
if (rsa->dmp1 != NULL) {
jbyteArray dmp1 = bignumToArray(env, rsa->dmp1, "dmp1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 5, dmp1);
}
if (rsa->dmq1 != NULL) {
jbyteArray dmq1 = bignumToArray(env, rsa->dmq1, "dmq1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 6, dmq1);
}
if (rsa->iqmp != NULL) {
jbyteArray iqmp = bignumToArray(env, rsa->iqmp, "iqmp");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 7, iqmp);
}
return joa;
}
/*
* public static native int DSA_generate_key(int, byte[], byte[], byte[], byte[]);
*/
static jlong NativeCrypto_DSA_generate_key(JNIEnv* env, jclass, jint primeBits,
jbyteArray seedJavaBytes, jbyteArray gBytes, jbyteArray pBytes, jbyteArray qBytes) {
JNI_TRACE("DSA_generate_key(%d, %p, %p, %p, %p)", primeBits, seedJavaBytes,
gBytes, pBytes, qBytes);
UniquePtr<unsigned char[]> seedPtr;
unsigned long seedSize = 0;
if (seedJavaBytes != NULL) {
ScopedByteArrayRO seed(env, seedJavaBytes);
if (seed.get() == NULL) {
return 0;
}
seedSize = seed.size();
seedPtr.reset(new unsigned char[seedSize]);
memcpy(seedPtr.get(), seed.get(), seedSize);
}
Unique_DSA dsa(DSA_new());
if (dsa.get() == NULL) {
JNI_TRACE("DSA_generate_key failed");
jniThrowOutOfMemory(env, "Unable to allocate DSA key");
freeOpenSslErrorState();
return 0;
}
if (gBytes != NULL && pBytes != NULL && qBytes != NULL) {
JNI_TRACE("DSA_generate_key parameters specified");
if (!arrayToBignum(env, gBytes, &dsa->g)) {
return 0;
}
if (!arrayToBignum(env, pBytes, &dsa->p)) {
return 0;
}
if (!arrayToBignum(env, qBytes, &dsa->q)) {
return 0;
}
} else {
JNI_TRACE("DSA_generate_key generating parameters");
if (!DSA_generate_parameters_ex(dsa.get(), primeBits, seedPtr.get(), seedSize, NULL, NULL, NULL)) {
JNI_TRACE("DSA_generate_key => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DSA_generate_parameters_ex failed");
return 0;
}
}
if (!DSA_generate_key(dsa.get())) {
JNI_TRACE("DSA_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DSA_generate_key failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DSA_generate_key failed");
jniThrowRuntimeException(env, "NativeCrypto_DSA_generate_key failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DSA(pkey.get(), dsa.get()) != 1) {
JNI_TRACE("DSA_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DSA_generate_key failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dsa);
JNI_TRACE("DSA_generate_key(n=%d, e=%p) => %p", primeBits, seedPtr.get(), pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native byte[][] get_DSA_params(long);
*/
static jobjectArray NativeCrypto_get_DSA_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_DSA_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey));
if (dsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_DSA_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(5, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dsa->g != NULL) {
jbyteArray g = bignumToArray(env, dsa->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, g);
}
if (dsa->p != NULL) {
jbyteArray p = bignumToArray(env, dsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, p);
}
if (dsa->q != NULL) {
jbyteArray q = bignumToArray(env, dsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, q);
}
if (dsa->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dsa->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, pub_key);
}
if (dsa->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dsa->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, priv_key);
}
return joa;
}
static void NativeCrypto_set_DSA_flag_nonce_from_hash(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("set_DSA_flag_nonce_from_hash(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey));
if (dsa.get() == NULL) {
throwExceptionIfNecessary(env, "set_DSA_flag_nonce_from_hash failed");
return;
}
dsa->flags |= DSA_FLAG_NONCE_FROM_HASH;
}
static jlong NativeCrypto_DH_generate_key(JNIEnv* env, jclass, jint primeBits, jint generator) {
JNI_TRACE("DH_generate_key(%d, %d)", primeBits, generator);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
jniThrowOutOfMemory(env, "Unable to allocate DH key");
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("DH_generate_key generating parameters");
if (!DH_generate_parameters_ex(dh.get(), primeBits, generator, NULL)) {
JNI_TRACE("DH_generate_key => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
if (!DH_generate_key(dh.get())) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
jniThrowRuntimeException(env, "NativeCrypto_DH_generate_key failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("DH_generate_key(n=%d, g=%d) => %p", primeBits, generator, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jobjectArray NativeCrypto_get_DH_params(JNIEnv* env, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("get_DH_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
throwExceptionIfNecessary(env, "get_DH_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(4, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dh->p != NULL) {
jbyteArray p = bignumToArray(env, dh->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, p);
}
if (dh->g != NULL) {
jbyteArray g = bignumToArray(env, dh->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, g);
}
if (dh->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dh->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, pub_key);
}
if (dh->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dh->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, priv_key);
}
return joa;
}
#define EC_CURVE_GFP 1
#define EC_CURVE_GF2M 2
/**
* Return group type or 0 if unknown group.
* EC_GROUP_GFP or EC_GROUP_GF2M
*/
static int get_EC_GROUP_type(const EC_GROUP* group)
{
const EC_METHOD* method = EC_GROUP_method_of(group);
if (method == EC_GFp_nist_method()
|| method == EC_GFp_mont_method()
|| method == EC_GFp_simple_method()) {
return EC_CURVE_GFP;
} else if (method == EC_GF2m_simple_method()) {
return EC_CURVE_GF2M;
}
return 0;
}
static jlong NativeCrypto_EC_GROUP_new_by_curve_name(JNIEnv* env, jclass, jstring curveNameJava)
{
JNI_TRACE("EC_GROUP_new_by_curve_name(%p)", curveNameJava);
ScopedUtfChars curveName(env, curveNameJava);
if (curveName.c_str() == NULL) {
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s)", curveName.c_str());
int nid = OBJ_sn2nid(curveName.c_str());
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID name", curveName.c_str());
return 0;
}
EC_GROUP* group = EC_GROUP_new_by_curve_name(nid);
if (group == NULL) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID %d", curveName.c_str(), nid);
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => %p", curveName.c_str(), group);
return reinterpret_cast<uintptr_t>(group);
}
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv* env, jclass, jlong groupRef,
jint flag)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d)", group, flag);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_asn1_flag => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_asn1_flag(group, flag);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d) => success", group, flag);
}
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv* env, jclass,
jlong groupRef, jint form)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d)", group, form);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_point_conversion_form => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_point_conversion_form(group, static_cast<point_conversion_form_t>(form));
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d) => success", group, form);
}
static jlong NativeCrypto_EC_GROUP_new_curve(JNIEnv* env, jclass, jint type, jbyteArray pJava,
jbyteArray aJava, jbyteArray bJava)
{
JNI_TRACE("EC_GROUP_new_curve(%d, %p, %p, %p)", type, pJava, aJava, bJava);
BIGNUM* pRef = NULL;
if (!arrayToBignum(env, pJava, &pRef)) {
return 0;
}
Unique_BIGNUM p(pRef);
BIGNUM* aRef = NULL;
if (!arrayToBignum(env, aJava, &aRef)) {
return 0;
}
Unique_BIGNUM a(aRef);
BIGNUM* bRef = NULL;
if (!arrayToBignum(env, bJava, &bRef)) {
return 0;
}
Unique_BIGNUM b(bRef);
EC_GROUP* group;
switch (type) {
case EC_CURVE_GFP:
group = EC_GROUP_new_curve_GFp(p.get(), a.get(), b.get(), (BN_CTX*) NULL);
break;
case EC_CURVE_GF2M:
group = EC_GROUP_new_curve_GF2m(p.get(), a.get(), b.get(), (BN_CTX*) NULL);
break;
default:
jniThrowRuntimeException(env, "invalid group");
return 0;
}
if (group == NULL) {
throwExceptionIfNecessary(env, "EC_GROUP_new_curve");
}
JNI_TRACE("EC_GROUP_new_curve(%d, %p, %p, %p) => %p", type, pJava, aJava, bJava, group);
return reinterpret_cast<uintptr_t>(group);
}
static jlong NativeCrypto_EC_GROUP_dup(JNIEnv* env, jclass, jlong groupRef) {
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_dup(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_dup => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
EC_GROUP* groupDup = EC_GROUP_dup(group);
JNI_TRACE("EC_GROUP_dup(%p) => %p", group, groupDup);
return reinterpret_cast<uintptr_t>(groupDup);
}
static jstring NativeCrypto_EC_GROUP_get_curve_name(JNIEnv* env, jclass, jlong groupRef) {
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
int nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_get_curve_name(%p) => unnamed curve", group);
return NULL;
}
const char* shortName = OBJ_nid2sn(nid);
JNI_TRACE("EC_GROUP_get_curve_name(%p) => \"%s\"", group, shortName);
return env->NewStringUTF(shortName);
}
static jobjectArray NativeCrypto_EC_GROUP_get_curve(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_curve(%p)", group);
Unique_BIGNUM p(BN_new());
Unique_BIGNUM a(BN_new());
Unique_BIGNUM b(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), (BN_CTX*) NULL);
break;
case EC_CURVE_GF2M:
ret = EC_GROUP_get_curve_GF2m(group, p.get(), a.get(), b.get(), (BN_CTX*)NULL);
break;
default:
jniThrowRuntimeException(env, "invalid group");
return NULL;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_GROUP_get_curve");
return NULL;
}
jobjectArray joa = env->NewObjectArray(3, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray pArray = bignumToArray(env, p.get(), "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, pArray);
jbyteArray aArray = bignumToArray(env, a.get(), "a");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, aArray);
jbyteArray bArray = bignumToArray(env, b.get(), "b");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, bArray);
JNI_TRACE("EC_GROUP_get_curve(%p) => %p", group, joa);
return joa;
}
static jbyteArray NativeCrypto_EC_GROUP_get_order(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_order(%p)", group);
Unique_BIGNUM order(BN_new());
if (order.get() == NULL) {
JNI_TRACE("EC_GROUP_get_order(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_order(group, order.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_order(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_order");
return NULL;
}
jbyteArray orderArray = bignumToArray(env, order.get(), "order");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_order(%p) => %p", group, orderArray);
return orderArray;
}
static jint NativeCrypto_EC_GROUP_get_degree(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_degree(%p)", group);
jint degree = EC_GROUP_get_degree(group);
if (degree == 0) {
JNI_TRACE("EC_GROUP_get_degree(%p) => unsupported", group);
jniThrowRuntimeException(env, "not supported");
return 0;
}
JNI_TRACE("EC_GROUP_get_degree(%p) => %d", group, degree);
return degree;
}
static jbyteArray NativeCrypto_EC_GROUP_get_cofactor(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_cofactor(%p)", group);
Unique_BIGNUM cofactor(BN_new());
if (cofactor.get() == NULL) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_cofactor(group, cofactor.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_cofactor");
return NULL;
}
jbyteArray cofactorArray = bignumToArray(env, cofactor.get(), "cofactor");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_cofactor(%p) => %p", group, cofactorArray);
return cofactorArray;
}
static jint NativeCrypto_get_EC_GROUP_type(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("get_EC_GROUP_type(%p)", group);
int type = get_EC_GROUP_type(group);
if (type == 0) {
JNI_TRACE("get_EC_GROUP_type(%p) => curve type", group);
jniThrowRuntimeException(env, "unknown curve type");
} else {
JNI_TRACE("get_EC_GROUP_type(%p) => %d", group, type);
}
return type;
}
static void NativeCrypto_EC_GROUP_clear_free(JNIEnv* env, jclass, jlong groupRef)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_clear_free(group);
JNI_TRACE("EC_GROUP_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_GROUP_cmp(JNIEnv* env, jclass, jlong group1Ref, jlong group2Ref)
{
const EC_GROUP* group1 = reinterpret_cast<const EC_GROUP*>(group1Ref);
const EC_GROUP* group2 = reinterpret_cast<const EC_GROUP*>(group2Ref);
JNI_TRACE("EC_GROUP_cmp(%p, %p)", group1, group2);
if (group1 == NULL || group2 == NULL) {
JNI_TRACE("EC_GROUP_cmp(%p, %p) => group1 == null || group2 == null", group1, group2);
jniThrowNullPointerException(env, "group1 == null || group2 == null");
return false;
}
int ret = EC_GROUP_cmp(group1, group2, (BN_CTX*)NULL);
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", group1, group2, ret);
return ret == 0;
}
static void NativeCrypto_EC_GROUP_set_generator(JNIEnv* env, jclass, jlong groupRef, jlong pointRef, jbyteArray njavaBytes, jbyteArray hjavaBytes)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
const EC_POINT* point = reinterpret_cast<const EC_POINT*>(pointRef);
JNI_TRACE("EC_GROUP_set_generator(%p, %p, %p, %p)", group, point, njavaBytes, hjavaBytes);
if (group == NULL || point == NULL) {
JNI_TRACE("EC_GROUP_set_generator(%p, %p, %p, %p) => group == null || point == null",
group, point, njavaBytes, hjavaBytes);
jniThrowNullPointerException(env, "group == null || point == null");
return;
}
BIGNUM* nRef = NULL;
if (!arrayToBignum(env, njavaBytes, &nRef)) {
return;
}
Unique_BIGNUM n(nRef);
BIGNUM* hRef = NULL;
if (!arrayToBignum(env, hjavaBytes, &hRef)) {
return;
}
Unique_BIGNUM h(hRef);
int ret = EC_GROUP_set_generator(group, point, n.get(), h.get());
if (ret == 0) {
throwExceptionIfNecessary(env, "EC_GROUP_set_generator");
}
JNI_TRACE("EC_GROUP_set_generator(%p, %p, %p, %p) => %d", group, point, njavaBytes, hjavaBytes, ret);
}
static jlong NativeCrypto_EC_GROUP_get_generator(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_get_generator(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_get_generator(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
const EC_POINT* generator = EC_GROUP_get0_generator(group);
Unique_EC_POINT dup(EC_POINT_dup(generator, group));
if (dup.get() == NULL) {
JNI_TRACE("EC_GROUP_get_generator(%p) => oom error", group);
jniThrowOutOfMemory(env, "unable to dupe generator");
return 0;
}
JNI_TRACE("EC_GROUP_get_generator(%p) => %p", group, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static jlong NativeCrypto_EC_POINT_new(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_POINT_new(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_new(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
EC_POINT* point = EC_POINT_new(group);
if (point == NULL) {
jniThrowOutOfMemory(env, "Unable create an EC_POINT");
return 0;
}
return reinterpret_cast<uintptr_t>(point);
}
static void NativeCrypto_EC_POINT_clear_free(JNIEnv* env, jclass, jlong groupRef) {
EC_POINT* group = reinterpret_cast<EC_POINT*>(groupRef);
JNI_TRACE("EC_POINT_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_POINT_clear_free(group);
JNI_TRACE("EC_POINT_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_POINT_cmp(JNIEnv* env, jclass, jlong groupRef, jlong point1Ref, jlong point2Ref)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
const EC_POINT* point1 = reinterpret_cast<const EC_POINT*>(point1Ref);
const EC_POINT* point2 = reinterpret_cast<const EC_POINT*>(point2Ref);
JNI_TRACE("EC_POINT_cmp(%p, %p, %p)", group, point1, point2);
if (group == NULL || point1 == NULL || point2 == NULL) {
JNI_TRACE("EC_POINT_cmp(%p, %p, %p) => group == null || point1 == null || point2 == null",
group, point1, point2);
jniThrowNullPointerException(env, "group == null || point1 == null || point2 == null");
return false;
}
int ret = EC_POINT_cmp(group, point1, point2, (BN_CTX*)NULL);
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", point1, point2, ret);
return ret == 0;
}
static void NativeCrypto_EC_POINT_set_affine_coordinates(JNIEnv* env, jclass,
jlong groupRef, jlong pointRef, jbyteArray xjavaBytes, jbyteArray yjavaBytes)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
EC_POINT* point = reinterpret_cast<EC_POINT*>(pointRef);
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p)", group, point, xjavaBytes,
yjavaBytes);
if (group == NULL || point == NULL) {
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => group == null || point == null",
group, point, xjavaBytes, yjavaBytes);
jniThrowNullPointerException(env, "group == null || point == null");
return;
}
BIGNUM* xRef = NULL;
if (!arrayToBignum(env, xjavaBytes, &xRef)) {
return;
}
Unique_BIGNUM x(xRef);
BIGNUM* yRef = NULL;
if (!arrayToBignum(env, yjavaBytes, &yRef)) {
return;
}
Unique_BIGNUM y(yRef);
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_set_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
case EC_CURVE_GF2M:
ret = EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates");
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => %d", group, point,
xjavaBytes, yjavaBytes, ret);
}
static jobjectArray NativeCrypto_EC_POINT_get_affine_coordinates(JNIEnv* env, jclass, jlong groupRef,
jlong pointRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
const EC_POINT* point = reinterpret_cast<const EC_POINT*>(pointRef);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
Unique_BIGNUM x(BN_new());
Unique_BIGNUM y(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_get_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
case EC_CURVE_GF2M:
ret = EC_POINT_get_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return NULL;
}
if (ret != 1) {
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
throwExceptionIfNecessary(env, "EC_POINT_get_affine_coordinates");
return NULL;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray xBytes = bignumToArray(env, x.get(), "x");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, xBytes);
jbyteArray yBytes = bignumToArray(env, y.get(), "y");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, yBytes);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) => %p", group, point, joa);
return joa;
}
static jlong NativeCrypto_EC_KEY_generate_key(JNIEnv* env, jclass, jlong groupRef)
{
const EC_GROUP* group = reinterpret_cast<const EC_GROUP*>(groupRef);
JNI_TRACE("EC_KEY_generate_key(%p)", group);
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_new() oom", group);
jniThrowOutOfMemory(env, "Unable to create an EC_KEY");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_set_group error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (EC_KEY_generate_key(eckey.get()) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_generate_key error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_KEY_generate_key");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EC_KEY_generate_key(%p) => %p", group, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EC_KEY_get0_group(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_get0_group(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("EC_KEY_get0_group(%p) => pkey == null", pkey);
return 0;
}
if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
jniThrowRuntimeException(env, "not EC key");
JNI_TRACE("EC_KEY_get0_group(%p) => not EC key (type == %d)", pkey,
EVP_PKEY_type(pkey->type));
return 0;
}
const EC_GROUP* group = EC_KEY_get0_group(pkey->pkey.ec);
JNI_TRACE("EC_KEY_get0_group(%p) => %p", pkey, group);
return reinterpret_cast<uintptr_t>(group);
}
static jbyteArray NativeCrypto_EC_KEY_get_private_key(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_get_private_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return NULL;
}
const BIGNUM *privkey = EC_KEY_get0_private_key(eckey.get());
jbyteArray privBytes = bignumToArray(env, privkey, "privkey");
if (env->ExceptionCheck()) {
JNI_TRACE("EC_KEY_get_private_key(%p) => threw error", pkey);
return NULL;
}
JNI_TRACE("EC_KEY_get_private_key(%p) => %p", pkey, privBytes);
return privBytes;
}
static jlong NativeCrypto_EC_KEY_get_public_key(JNIEnv* env, jclass, jlong pkeyRef)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_get_public_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return 0;
}
Unique_EC_POINT dup(EC_POINT_dup(EC_KEY_get0_public_key(eckey.get()),
EC_KEY_get0_group(eckey.get())));
if (dup.get() == NULL) {
JNI_TRACE("EC_KEY_get_public_key(%p) => can't dup public key", pkey);
jniThrowRuntimeException(env, "EC_POINT_dup");
return 0;
}
JNI_TRACE("EC_KEY_get_public_key(%p) => %p", pkey, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv* env, jclass, jlong pkeyRef,
jboolean enabled)
{
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EC_KEY_set_nonce_from_hash(%p, %d)", pkey, enabled ? 1 : 0);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return;
}
EC_KEY_set_nonce_from_hash(eckey.get(), enabled ? 1 : 0);
}
static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass,
jbyteArray outArray, jint outOffset, jlong pubkeyRef, jlong privkeyRef)
{
EVP_PKEY* pubPkey = reinterpret_cast<EVP_PKEY*>(pubkeyRef);
EVP_PKEY* privPkey = reinterpret_cast<EVP_PKEY*>(privkeyRef);
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p)", outArray, outOffset, pubPkey, privPkey);
ScopedByteArrayRW out(env, outArray);
if (out.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) can't get output buffer",
outArray, outOffset, pubPkey, privPkey);
return -1;
}
if ((outOffset < 0) || ((size_t) outOffset >= out.size())) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
if (pubPkey == NULL) {
jniThrowNullPointerException(env, "pubPkey == null");
return -1;
}
Unique_EC_KEY pubkey(EVP_PKEY_get1_EC_KEY(pubPkey));
if (pubkey.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
const EC_POINT* pubkeyPoint = EC_KEY_get0_public_key(pubkey.get());
if (pubkeyPoint == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key point", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
if (privPkey == NULL) {
jniThrowNullPointerException(env, "privPkey == null");
return -1;
}
Unique_EC_KEY privkey(EVP_PKEY_get1_EC_KEY(privPkey));
if (privkey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY private");
return -1;
}
int outputLength = ECDH_compute_key(
&out[outOffset],
out.size() - outOffset,
pubkeyPoint,
privkey.get(),
NULL // No KDF
);
if (outputLength == -1) {
throwExceptionIfNecessary(env, "ECDH_compute_key");
return -1;
}
return outputLength;
}
static jlong NativeCrypto_EVP_MD_CTX_create(JNIEnv* env, jclass) {
JNI_TRACE_MD("EVP_MD_CTX_create()");
Unique_EVP_MD_CTX ctx(EVP_MD_CTX_create());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable create a EVP_MD_CTX");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_create() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static void NativeCrypto_EVP_MD_CTX_init(JNIEnv* env, jclass, jobject ctxRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_init(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_init(ctx);
}
}
static void NativeCrypto_EVP_MD_CTX_destroy(JNIEnv* env, jclass, jlong ctxRef) {
EVP_MD_CTX* ctx = reinterpret_cast<EVP_MD_CTX*>(ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_destroy(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_destroy(ctx);
}
}
static jint NativeCrypto_EVP_MD_CTX_copy(JNIEnv* env, jclass, jobject dstCtxRef, jobject srcCtxRef) {
EVP_MD_CTX* dst_ctx = fromContextObject<EVP_MD_CTX>(env, dstCtxRef);
const EVP_MD_CTX* src_ctx = fromContextObject<EVP_MD_CTX>(env, srcCtxRef);
JNI_TRACE_MD("EVP_MD_CTX_copy(%p. %p)", dst_ctx, src_ctx);
if (src_ctx == NULL) {
return 0;
} else if (dst_ctx == NULL) {
return 0;
}
int result = EVP_MD_CTX_copy_ex(dst_ctx, src_ctx);
if (result == 0) {
jniThrowRuntimeException(env, "Unable to copy EVP_MD_CTX");
freeOpenSslErrorState();
}
JNI_TRACE_MD("EVP_MD_CTX_copy(%p, %p) => %d", dst_ctx, src_ctx, result);
return result;
}
/*
* public static native int EVP_DigestFinal(long, byte[], int)
*/
static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray hash,
jint offset) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d)", ctx, hash, offset);
if (ctx == NULL) {
return -1;
} else if (hash == NULL) {
jniThrowNullPointerException(env, "ctx == null || hash == null");
return -1;
}
ScopedByteArrayRW hashBytes(env, hash);
if (hashBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_DigestFinal_ex(ctx,
reinterpret_cast<unsigned char*>(hashBytes.get() + offset),
&bytesWritten);
if (ok == 0) {
throwExceptionIfNecessary(env, "EVP_DigestFinal");
}
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d) => %d", ctx, hash, offset, bytesWritten);
return bytesWritten;
}
static jint evpInit(JNIEnv* env, jobject evpMdCtxRef, jlong evpMdRef, const char* jniName,
int (*init_func)(EVP_MD_CTX*, const EVP_MD*, ENGINE*)) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* evp_md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE_MD("%s(%p, %p)", jniName, ctx, evp_md);
if (ctx == NULL) {
return 0;
} else if (evp_md == NULL) {
jniThrowNullPointerException(env, "evp_md == null");
return 0;
}
int ok = init_func(ctx, evp_md, NULL);
if (ok == 0) {
bool exception = throwExceptionIfNecessary(env, jniName);
if (exception) {
JNI_TRACE("%s(%p) => threw exception", jniName, evp_md);
return 0;
}
}
JNI_TRACE_MD("%s(%p, %p) => %d", jniName, ctx, evp_md, ok);
return ok;
}
static jint NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_DigestInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_SignInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_SignInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_VerifyInit", EVP_DigestInit_ex);
}
/*
* public static native int EVP_get_digestbyname(java.lang.String)
*/
static jlong NativeCrypto_EVP_get_digestbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%p)", algorithm);
if (algorithm == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s)", algorithmChars.c_str());
const EVP_MD* evp_md = EVP_get_digestbyname(algorithmChars.c_str());
if (evp_md == NULL) {
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => %p", algorithmChars.c_str(), evp_md);
return reinterpret_cast<uintptr_t>(evp_md);
}
/*
* public static native int EVP_MD_size(long)
*/
static jint NativeCrypto_EVP_MD_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p) => %d", evp_md, result);
return result;
}
/*
* public static int void EVP_MD_block_size(long)
*/
static jint NativeCrypto_EVP_MD_block_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_block_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p) => %d", evp_md, result);
return result;
}
static void NativeCrypto_EVP_DigestSignInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jlong pkeyRef) {
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p)", mdCtx, md, pkey);
if (mdCtx == NULL) {
return;
}
if (md == NULL) {
jniThrowNullPointerException(env, "md == null");
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
if (EVP_DigestSignInit(mdCtx, (EVP_PKEY_CTX **) NULL, md, (ENGINE *) NULL, pkey) <= 0) {
JNI_TRACE("ctx=%p EVP_DigestSignInit => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignInit");
return;
}
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p) => success", mdCtx, md, pkey);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jbyteArray inJavaBytes, jint inOffset,
jint inLength, const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *,
size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE_MD("%s(%p, %p, %d, %d)", jniName, mdCtx, inJavaBytes, inOffset, inLength);
if (mdCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inJavaBytes);
if (inBytes.get() == NULL) {
return;
}
if (inOffset < 0 || size_t(inOffset) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inOffset");
return;
}
const ssize_t inEnd = inOffset + inLength;
if (inEnd < 0 || size_t(inEnd) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inLength");
return;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char *>(inBytes.get());
if (!update_func(mdCtx, tmp + inOffset, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d, %d) => success", jniName, mdCtx, inJavaBytes, inOffset, inLength);
}
static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestSignUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_SignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_SignUpdate",
EVP_DigestUpdate);
}
static jbyteArray NativeCrypto_EVP_DigestSignFinal(JNIEnv* env, jclass, jobject evpMdCtxRef)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestSignFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return NULL;
}
const size_t expectedSize = EVP_MD_CTX_size(mdCtx);
ScopedLocalRef<jbyteArray> outJavaBytes(env, env->NewByteArray(expectedSize));
if (outJavaBytes.get() == NULL) {
return NULL;
}
ScopedByteArrayRW outBytes(env, outJavaBytes.get());
if (outBytes.get() == NULL) {
return NULL;
}
unsigned char *tmp = reinterpret_cast<unsigned char*>(outBytes.get());
size_t len;
if (!EVP_DigestSignFinal(mdCtx, tmp, &len)) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return 0;
}
if (len != expectedSize) {
jniThrowRuntimeException(env, "hash size unexpected");
return 0;
}
JNI_TRACE("EVP_DigestSignFinal(%p) => %p", mdCtx, outJavaBytes.get());
return outJavaBytes.release();
}
/*
* public static native int EVP_SignFinal(long, byte[], int, long)
*/
static jint NativeCrypto_EVP_SignFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray signature,
jint offset, jlong pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p)", ctx, signature, offset, pkey);
if (ctx == NULL) {
return -1;
} else if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRW signatureBytes(env, signature);
if (signatureBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_SignFinal(ctx,
reinterpret_cast<unsigned char*>(signatureBytes.get() + offset),
&bytesWritten,
pkey);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_SignFinal");
}
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p) => %u",
ctx, signature, offset, pkey, bytesWritten);
return bytesWritten;
}
/*
* public static native void EVP_VerifyUpdate(long, byte[], int, int)
*/
static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray buffer, jint offset, jint length) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE("NativeCrypto_EVP_VerifyUpdate(%p, %p, %d, %d)", ctx, buffer, offset, length);
if (ctx == NULL) {
return;
} else if (buffer == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return;
}
if (bufferBytes.size() < static_cast<size_t>(offset + length)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
int ok = EVP_VerifyUpdate(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyUpdate");
}
}
/*
* public static native int EVP_VerifyFinal(long, byte[], int, int, long)
*/
static jint NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray buffer,
jint offset, jint length, jlong pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p)",
ctx, buffer, offset, length, pkey);
if (ctx == NULL) {
return -1;
} else if (buffer == NULL || pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return -1;
}
int ok = EVP_VerifyFinal(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length,
pkey);
if (ok < 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyFinal");
}
/*
* For DSA keys, OpenSSL appears to have a bug where it returns
* errors for any result != 1. See dsa_ossl.c in dsa_do_verify
*/
freeOpenSslErrorState();
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p) => %d",
ctx, buffer, offset, length, pkey, ok);
return ok;
}
static jlong NativeCrypto_EVP_get_cipherbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("EVP_get_cipherbyname(%p)", algorithm);
if (algorithm == NULL) {
JNI_TRACE("EVP_get_cipherbyname(%p) => threw exception algorithm == null", algorithm);
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("EVP_get_cipherbyname(%p) => algorithm = %s", algorithm, algorithmChars.c_str());
const EVP_CIPHER* evp_cipher = EVP_get_cipherbyname(algorithmChars.c_str());
if (evp_cipher == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("EVP_get_cipherbyname(%s) => %p", algorithmChars.c_str(), evp_cipher);
return reinterpret_cast<uintptr_t>(evp_cipher);
}
static void NativeCrypto_EVP_CipherInit_ex(JNIEnv* env, jclass, jlong ctxRef, jlong evpCipherRef,
jbyteArray keyArray, jbyteArray ivArray, jboolean encrypting) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d)", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("EVP_CipherUpdate => ctx == null");
return;
}
// The key can be null if we need to set extra parameters.
UniquePtr<unsigned char[]> keyPtr;
if (keyArray != NULL) {
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
keyPtr.reset(new unsigned char[keyBytes.size()]);
memcpy(keyPtr.get(), keyBytes.get(), keyBytes.size());
}
// The IV can be null if we're using ECB.
UniquePtr<unsigned char[]> ivPtr;
if (ivArray != NULL) {
ScopedByteArrayRO ivBytes(env, ivArray);
if (ivBytes.get() == NULL) {
return;
}
ivPtr.reset(new unsigned char[ivBytes.size()]);
memcpy(ivPtr.get(), ivBytes.get(), ivBytes.size());
}
if (!EVP_CipherInit_ex(ctx, evpCipher, NULL, keyPtr.get(), ivPtr.get(), encrypting ? 1 : 0)) {
throwExceptionIfNecessary(env, "EVP_CipherInit_ex");
JNI_TRACE("EVP_CipherInit_ex => error initializing cipher");
return;
}
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d) => success", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
}
/*
* public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
* int inOffset, int inLength);
*/
static jint NativeCrypto_EVP_CipherUpdate(JNIEnv* env, jclass, jlong ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray inArray, jint inOffset, jint inLength) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d)", ctx, outArray, outOffset, inArray, inOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherUpdate => ctx == null", ctx);
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
const size_t inSize = inBytes.size();
if (size_t(inOffset + inLength) > inSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"in.length < (inSize + inOffset)");
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
const size_t outSize = outBytes.size();
if (size_t(outOffset + inLength) > outSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"out.length < inSize + outOffset + blockSize - 1");
return 0;
}
JNI_TRACE("ctx=%p EVP_CipherUpdate in=%p in.length=%d inOffset=%d inLength=%d out=%p out.length=%d outOffset=%d",
ctx, inBytes.get(), inBytes.size(), inOffset, inLength, outBytes.get(), outBytes.size(), outOffset);
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
const unsigned char* in = reinterpret_cast<const unsigned char*>(inBytes.get());
int outl;
if (!EVP_CipherUpdate(ctx, out + outOffset, &outl, in + inOffset, inLength)) {
throwExceptionIfNecessary(env, "EVP_CipherUpdate");
JNI_TRACE("ctx=%p EVP_CipherUpdate => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d) => %d", ctx, outArray, outOffset, inArray,
inOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CipherFinal_ex(JNIEnv* env, jclass, jlong ctxRef, jbyteArray outArray,
jint outOffset) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CipherFinal_ex(%p, %p, %d)", ctx, outArray, outOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => ctx == null", ctx);
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
int outl;
if (!EVP_CipherFinal_ex(ctx, out + outOffset, &outl)) {
throwExceptionIfNecessary(env, "EVP_CipherFinal_ex");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherFinal(%p, %p, %d) => %d", ctx, outArray, outOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CIPHER_iv_length(JNIEnv* env, jclass, jlong evpCipherRef) {
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CIPHER_iv_length(%p)", evpCipher);
if (evpCipher == NULL) {
jniThrowNullPointerException(env, "evpCipher == null");
JNI_TRACE("EVP_CIPHER_iv_length => evpCipher == null");
return 0;
}
const int ivLength = EVP_CIPHER_iv_length(evpCipher);
JNI_TRACE("EVP_CIPHER_iv_length(%p) => %d", evpCipher, ivLength);
return ivLength;
}
static jlong NativeCrypto_EVP_CIPHER_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("EVP_CIPHER_CTX_new()");
Unique_EVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate cipher context");
JNI_TRACE("EVP_CipherInit_ex => context allocation error");
return 0;
}
JNI_TRACE("EVP_CIPHER_CTX_new() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static jint NativeCrypto_EVP_CIPHER_CTX_block_size(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_block_size => ctx == null", ctx);
return 0;
}
int blockSize = EVP_CIPHER_CTX_block_size(ctx);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p) => %d", ctx, blockSize);
return blockSize;
}
static jint NativeCrypto_get_EVP_CIPHER_CTX_buf_len(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_buf_len => ctx == null", ctx);
return 0;
}
int buf_len = ctx->buf_len;
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p) => %d", ctx, buf_len);
return buf_len;
}
static void NativeCrypto_EVP_CIPHER_CTX_set_padding(JNIEnv* env, jclass, jlong ctxRef, jboolean enablePaddingBool) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
jint enablePadding = enablePaddingBool ? 1 : 0;
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d)", ctx, enablePadding);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_padding => ctx == null", ctx);
return;
}
EVP_CIPHER_CTX_set_padding(ctx, enablePadding); // Not void, but always returns 1.
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d) => success", ctx, enablePadding);
}
static void NativeCrypto_EVP_CIPHER_CTX_set_key_length(JNIEnv* env, jclass, jlong ctxRef,
jint keySizeBits) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d)", ctx, keySizeBits);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_key_length => ctx == null", ctx);
return;
}
if (!EVP_CIPHER_CTX_set_key_length(ctx, keySizeBits)) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_CIPHER_CTX_set_key_length");
JNI_TRACE("NativeCrypto_EVP_CIPHER_CTX_set_key_length => threw error");
return;
}
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d) => success", ctx, keySizeBits);
}
static void NativeCrypto_EVP_CIPHER_CTX_cleanup(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p)", ctx);
if (ctx != NULL) {
if (!EVP_CIPHER_CTX_cleanup(ctx)) {
throwExceptionIfNecessary(env, "EVP_CIPHER_CTX_cleanup");
JNI_TRACE("EVP_CIPHER_CTX_cleanup => threw error");
return;
}
}
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p) => success", ctx);
}
/**
* public static native void RAND_seed(byte[]);
*/
static void NativeCrypto_RAND_seed(JNIEnv* env, jclass, jbyteArray seed) {
JNI_TRACE("NativeCrypto_RAND_seed seed=%p", seed);
ScopedByteArrayRO randseed(env, seed);
if (randseed.get() == NULL) {
return;
}
RAND_seed(randseed.get(), randseed.size());
}
static jint NativeCrypto_RAND_load_file(JNIEnv* env, jclass, jstring filename, jlong max_bytes) {
JNI_TRACE("NativeCrypto_RAND_load_file filename=%p max_bytes=%lld", filename, max_bytes);
ScopedUtfChars file(env, filename);
if (file.c_str() == NULL) {
return -1;
}
int result = RAND_load_file(file.c_str(), max_bytes);
JNI_TRACE("NativeCrypto_RAND_load_file file=%s => %d", file.c_str(), result);
return result;
}
static void NativeCrypto_RAND_bytes(JNIEnv* env, jclass, jbyteArray output) {
JNI_TRACE("NativeCrypto_RAND_bytes(%p)", output);
ScopedByteArrayRW outputBytes(env, output);
if (outputBytes.get() == NULL) {
return;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(outputBytes.get());
if (RAND_bytes(tmp, outputBytes.size()) <= 0) {
throwExceptionIfNecessary(env, "NativeCrypto_RAND_bytes");
JNI_TRACE("tmp=%p NativeCrypto_RAND_bytes => threw error", tmp);
return;
}
JNI_TRACE("NativeCrypto_RAND_bytes(%p) => success", output);
}
static jint NativeCrypto_OBJ_txt2nid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return 0;
}
int nid = OBJ_txt2nid(oid.c_str());
JNI_TRACE("OBJ_txt2nid(%s) => %d", oid.c_str(), nid);
return nid;
}
static jstring NativeCrypto_OBJ_txt2nid_longName(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_longName(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_longName(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_longName(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const char* longName = OBJ_nid2ln(nid);
JNI_TRACE("OBJ_txt2nid_longName(%s) => %s", oid.c_str(), longName);
return env->NewStringUTF(longName);
}
static jstring ASN1_OBJECT_to_OID_string(JNIEnv* env, ASN1_OBJECT* obj) {
/*
* The OBJ_obj2txt API doesn't "measure" if you pass in NULL as the buffer.
* Just make a buffer that's large enough here. The documentation recommends
* 80 characters.
*/
char output[128];
int ret = OBJ_obj2txt(output, sizeof(output), obj, 1);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1_OBJECT_to_OID_string");
return NULL;
} else if (size_t(ret) >= sizeof(output)) {
jniThrowRuntimeException(env, "ASN1_OBJECT_to_OID_string buffer too small");
return NULL;
}
JNI_TRACE("ASN1_OBJECT_to_OID_string(%p) => %s", obj, output);
return env->NewStringUTF(output);
}
static jlong NativeCrypto_create_BIO_InputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_InputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_InputStream(streamObj));
JNI_TRACE("create_BIO_InputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static jlong NativeCrypto_create_BIO_OutputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_OutputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_OutputStream(streamObj));
JNI_TRACE("create_BIO_OutputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static int NativeCrypto_BIO_read(JNIEnv* env, jclass, jlong bioRef, jbyteArray outputJavaBytes) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_read(%p, %p)", bio, outputJavaBytes);
if (outputJavaBytes == NULL) {
jniThrowNullPointerException(env, "output == null");
JNI_TRACE("BIO_read(%p, %p) => output == null", bio, outputJavaBytes);
return 0;
}
int outputSize = env->GetArrayLength(outputJavaBytes);
UniquePtr<unsigned char[]> buffer(new unsigned char[outputSize]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for read");
return 0;
}
int read = BIO_read(bio, buffer.get(), outputSize);
if (read <= 0) {
jniThrowException(env, "java/io/IOException", "BIO_read");
JNI_TRACE("BIO_read(%p, %p) => threw IO exception", bio, outputJavaBytes);
return 0;
}
env->SetByteArrayRegion(outputJavaBytes, 0, read, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("BIO_read(%p, %p) => %d", bio, outputJavaBytes, read);
return read;
}
static void NativeCrypto_BIO_write(JNIEnv* env, jclass, jlong bioRef, jbyteArray inputJavaBytes,
jint offset, jint length) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_write(%p, %p, %d, %d)", bio, inputJavaBytes, offset, length);
if (inputJavaBytes == NULL) {
jniThrowNullPointerException(env, "input == null");
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "offset < 0 || length < 0");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
int inputSize = env->GetArrayLength(inputJavaBytes);
if (inputSize < offset + length) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"input.length < offset + length");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[length]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for write");
return;
}
env->GetByteArrayRegion(inputJavaBytes, offset, length, reinterpret_cast<jbyte*>(buffer.get()));
if (BIO_write(bio, buffer.get(), length) != length) {
freeOpenSslErrorState();
jniThrowException(env, "java/io/IOException", "BIO_write");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IO error", bio, inputJavaBytes, offset, length);
return;
}
JNI_TRACE("BIO_write(%p, %p, %d, %d) => success", bio, inputJavaBytes, offset, length);
}
static void NativeCrypto_BIO_free_all(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_free_all(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return;
}
BIO_free_all(bio);
}
static jstring X509_NAME_to_jstring(JNIEnv* env, X509_NAME* name, unsigned long flags) {
JNI_TRACE("X509_NAME_to_jstring(%p)", name);
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
JNI_TRACE("X509_NAME_to_jstring(%p) => threw error", name);
return NULL;
}
/* Don't interpret the string. */
flags &= ~(ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_ESC_MSB);
/* Write in given format and null terminate. */
X509_NAME_print_ex(buffer.get(), name, 0, flags);
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
JNI_TRACE("X509_NAME_to_jstring(%p) => \"%s\"", name, tmp);
return env->NewStringUTF(tmp);
}
/**
* Converts GENERAL_NAME items to the output format expected in
* X509Certificate#getSubjectAlternativeNames and
* X509Certificate#getIssuerAlternativeNames return.
*/
static jobject GENERAL_NAME_to_jobject(JNIEnv* env, GENERAL_NAME* gen) {
switch (gen->type) {
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI: {
// This must not be a T61String and must not contain NULLs.
const char* data = reinterpret_cast<const char*>(ASN1_STRING_data(gen->d.ia5));
ssize_t len = ASN1_STRING_length(gen->d.ia5);
if ((len == static_cast<ssize_t>(strlen(data)))
&& (ASN1_PRINTABLE_type(ASN1_STRING_data(gen->d.ia5), len) != V_ASN1_T61STRING)) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI \"%s\"", gen, data);
return env->NewStringUTF(data);
} else {
jniThrowException(env, "java/security/cert/CertificateParsingException",
"Invalid dNSName encoding");
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI invalid", gen);
return NULL;
}
}
case GEN_DIRNAME:
/* Write in RFC 2253 format */
return X509_NAME_to_jstring(env, gen->d.directoryName, XN_FLAG_RFC2253);
case GEN_IPADD: {
const void *ip = reinterpret_cast<const void *>(gen->d.ip->data);
if (gen->d.ip->length == 4) {
// IPv4
UniquePtr<char[]> buffer(new char[INET_ADDRSTRLEN]);
if (inet_ntop(AF_INET, ip, buffer.get(), INET_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 failed %s", gen, strerror(errno));
}
} else if (gen->d.ip->length == 16) {
// IPv6
UniquePtr<char[]> buffer(new char[INET6_ADDRSTRLEN]);
if (inet_ntop(AF_INET6, ip, buffer.get(), INET6_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 failed %s", gen, strerror(errno));
}
}
/* Invalid IP encodings are pruned out without throwing an exception. */
return NULL;
}
case GEN_RID:
return ASN1_OBJECT_to_OID_string(env, gen->d.registeredID);
case GEN_OTHERNAME:
case GEN_X400:
default:
return ASN1ToByteArray<GENERAL_NAME, i2d_GENERAL_NAME>(env, gen);
}
return NULL;
}
#define GN_STACK_SUBJECT_ALT_NAME 1
#define GN_STACK_ISSUER_ALT_NAME 2
static jobjectArray NativeCrypto_get_X509_GENERAL_NAME_stack(JNIEnv* env, jclass, jlong x509Ref,
jint type) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d)", x509, type);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => x509 == null", x509, type);
return NULL;
}
X509_check_ca(x509);
STACK_OF(GENERAL_NAME)* gn_stack;
Unique_sk_GENERAL_NAME stackHolder;
if (type == GN_STACK_SUBJECT_ALT_NAME) {
gn_stack = x509->altname;
} else if (type == GN_STACK_ISSUER_ALT_NAME) {
stackHolder.reset(
static_cast<STACK_OF(GENERAL_NAME)*>(X509_get_ext_d2i(x509, NID_issuer_alt_name,
NULL, NULL)));
gn_stack = stackHolder.get();
} else {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => unknown type", x509, type);
return NULL;
}
int count = sk_GENERAL_NAME_num(gn_stack);
if (count <= 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no entries)", x509, type);
return NULL;
}
/*
* Keep track of how many originally so we can ignore any invalid
* values later.
*/
const int origCount = count;
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, objectArrayClass, NULL));
for (int i = 0, j = 0; i < origCount; i++, j++) {
GENERAL_NAME* gen = sk_GENERAL_NAME_value(gn_stack, i);
ScopedLocalRef<jobject> val(env, GENERAL_NAME_to_jobject(env, gen));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => threw exception parsing gen name",
x509, type);
return NULL;
}
/*
* If it's NULL, we'll have to skip this, reduce the number of total
* entries, and fix up the array later.
*/
if (val.get() == NULL) {
j--;
count--;
continue;
}
ScopedLocalRef<jobjectArray> item(env, env->NewObjectArray(2, objectClass, NULL));
ScopedLocalRef<jobject> type(env, env->CallStaticObjectMethod(integerClass,
integer_valueOfMethod, gen->type));
env->SetObjectArrayElement(item.get(), 0, type.get());
env->SetObjectArrayElement(item.get(), 1, val.get());
env->SetObjectArrayElement(joa.get(), j, item.get());
}
if (count == 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to 0; returning NULL",
x509, type, origCount);
joa.reset(NULL);
} else if (origCount != count) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to %d", x509, type,
origCount, count);
ScopedLocalRef<jobjectArray> joa_copy(env, env->NewObjectArray(count, objectArrayClass,
NULL));
for (int i = 0; i < count; i++) {
ScopedLocalRef<jobject> item(env, env->GetObjectArrayElement(joa.get(), i));
env->SetObjectArrayElement(joa_copy.get(), i, item.get());
}
joa.reset(joa_copy.release());
}
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => %d entries", x509, type, count);
return joa.release();
}
static jlong NativeCrypto_X509_get_notBefore(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notBefore(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notBefore(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notBefore = X509_get_notBefore(x509);
JNI_TRACE("X509_get_notBefore(%p) => %p", x509, notBefore);
return reinterpret_cast<uintptr_t>(notBefore);
}
static jlong NativeCrypto_X509_get_notAfter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notAfter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notAfter(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notAfter = X509_get_notAfter(x509);
JNI_TRACE("X509_get_notAfter(%p) => %p", x509, notAfter);
return reinterpret_cast<uintptr_t>(notAfter);
}
static long NativeCrypto_X509_get_version(JNIEnv*, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_version(%p)", x509);
long version = X509_get_version(x509);
JNI_TRACE("X509_get_version(%p) => %ld", x509, version);
return version;
}
template<typename T>
static jbyteArray get_X509Type_serialNumber(JNIEnv* env, T* x509Type, ASN1_INTEGER* (*get_serial_func)(T*)) {
JNI_TRACE("get_X509Type_serialNumber(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_serialNumber(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_INTEGER* serialNumber = get_serial_func(x509Type);
Unique_BIGNUM serialBn(ASN1_INTEGER_to_BN(serialNumber, NULL));
if (serialBn.get() == NULL) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
ScopedLocalRef<jbyteArray> serialArray(env, bignumToArray(env, serialBn.get(), "serialBn"));
if (env->ExceptionCheck()) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
JNI_TRACE("X509_get_serialNumber(%p) => %p", x509Type, serialArray.get());
return serialArray.release();
}
/* OpenSSL includes set_serialNumber but not get. */
#if !defined(X509_REVOKED_get_serialNumber)
static ASN1_INTEGER* X509_REVOKED_get_serialNumber(X509_REVOKED* x) {
return x->serialNumber;
}
#endif
static jbyteArray NativeCrypto_X509_get_serialNumber(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_serialNumber(%p)", x509);
return get_X509Type_serialNumber<X509>(env, x509, X509_get_serialNumber);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_serialNumber(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_serialNumber(%p)", revoked);
return get_X509Type_serialNumber<X509_REVOKED>(env, revoked, X509_REVOKED_get_serialNumber);
}
static void NativeCrypto_X509_verify(JNIEnv* env, jclass, jlong x509Ref, jlong pkeyRef) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("X509_verify(%p, %p)", x509, pkey);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_verify(%p, %p) => x509 == null", x509, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_verify(%p, %p) => pkey == null", x509, pkey);
return;
}
if (X509_verify(x509, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_verify");
JNI_TRACE("X509_verify(%p, %p) => verify failure", x509, pkey);
} else {
JNI_TRACE("X509_verify(%p, %p) => verify success", x509, pkey);
}
}
static jbyteArray NativeCrypto_get_X509_cert_info_enc(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_cert_info_enc(%p)", x509);
return ASN1ToByteArray<X509_CINF, i2d_X509_CINF>(env, x509->cert_info);
}
static jint NativeCrypto_get_X509_ex_flags(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_flags(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_flags(%p) => x509 == null", x509);
return 0;
}
X509_check_ca(x509);
return x509->ex_flags;
}
static jboolean NativeCrypto_X509_check_issued(JNIEnv*, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_check_issued(%p, %p)", x509_1, x509_2);
int ret = X509_check_issued(x509_1, x509_2);
JNI_TRACE("X509_check_issued(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void get_X509_signature(X509 *x509, ASN1_BIT_STRING** signature) {
*signature = x509->signature;
}
static void get_X509_CRL_signature(X509_CRL *crl, ASN1_BIT_STRING** signature) {
*signature = crl->signature;
}
template<typename T>
static jbyteArray get_X509Type_signature(JNIEnv* env, T* x509Type, void (*get_signature_func)(T*, ASN1_BIT_STRING**)) {
JNI_TRACE("get_X509Type_signature(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_signature(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_BIT_STRING* signature;
get_signature_func(x509Type, &signature);
ScopedLocalRef<jbyteArray> signatureArray(env, env->NewByteArray(signature->length));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509Type_signature(%p) => threw exception", x509Type);
return NULL;
}
ScopedByteArrayRW signatureBytes(env, signatureArray.get());
if (signatureBytes.get() == NULL) {
JNI_TRACE("get_X509Type_signature(%p) => using byte array failed", x509Type);
return NULL;
}
memcpy(signatureBytes.get(), signature->data, signature->length);
JNI_TRACE("get_X509Type_signature(%p) => %p (%d bytes)", x509Type, signatureArray.get(),
signature->length);
return signatureArray.release();
}
static jbyteArray NativeCrypto_get_X509_signature(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_signature(%p)", x509);
return get_X509Type_signature<X509>(env, x509, get_X509_signature);
}
static jbyteArray NativeCrypto_get_X509_CRL_signature(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_signature(%p)", crl);
return get_X509Type_signature<X509_CRL>(env, crl, get_X509_CRL_signature);
}
static jlong NativeCrypto_X509_CRL_get0_by_cert(JNIEnv* env, jclass, jlong x509crlRef, jlong x509Ref) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p)", x509crl, x509);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509crl == null", x509crl, x509);
return 0;
} else if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509 == null", x509crl, x509);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_cert(x509crl, &revoked, x509);
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => none", x509crl, x509);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, x509, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
static jlong NativeCrypto_X509_CRL_get0_by_serial(JNIEnv* env, jclass, jlong x509crlRef, jbyteArray serialArray) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p)", x509crl, serialArray);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => crl == null", x509crl, serialArray);
return 0;
}
Unique_BIGNUM serialBn(BN_new());
if (serialBn.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN allocation failed", x509crl, serialArray);
return 0;
}
BIGNUM* serialBare = serialBn.get();
if (!arrayToBignum(env, serialArray, &serialBare)) {
if (!env->ExceptionCheck()) {
jniThrowNullPointerException(env, "serial == null");
}
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
Unique_ASN1_INTEGER serialInteger(BN_to_ASN1_INTEGER(serialBn.get(), NULL));
if (serialInteger.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_serial(x509crl, &revoked, serialInteger.get());
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => none", x509crl, serialArray);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, serialArray, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
/* This appears to be missing from OpenSSL. */
#if !defined(X509_REVOKED_dup)
X509_REVOKED* X509_REVOKED_dup(X509_REVOKED* x) {
return reinterpret_cast<X509_REVOKED*>(ASN1_item_dup(ASN1_ITEM_rptr(X509_REVOKED), x));
}
#endif
static jlongArray NativeCrypto_X509_CRL_get_REVOKED(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_REVOKED(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
return NULL;
}
STACK_OF(X509_REVOKED)* stack = X509_CRL_get_REVOKED(crl);
if (stack == NULL) {
JNI_TRACE("X509_CRL_get_REVOKED(%p) => stack is null", crl);
return NULL;
}
size_t size = sk_X509_REVOKED_num(stack);
ScopedLocalRef<jlongArray> revokedArray(env, env->NewLongArray(size));
ScopedLongArrayRW revoked(env, revokedArray.get());
for (size_t i = 0; i < size; i++) {
X509_REVOKED* item = reinterpret_cast<X509_REVOKED*>(sk_X509_REVOKED_value(stack, i));
revoked[i] = reinterpret_cast<uintptr_t>(X509_REVOKED_dup(item));
}
JNI_TRACE("X509_CRL_get_REVOKED(%p) => %p [size=%d]", stack, revokedArray.get(), size);
return revokedArray.release();
}
static jbyteArray NativeCrypto_i2d_X509_CRL(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("i2d_X509_CRL(%p)", crl);
return ASN1ToByteArray<X509_CRL, i2d_X509_CRL>(env, crl);
}
static void NativeCrypto_X509_CRL_free(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_free(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_free(%p) => crl == null", crl);
return;
}
X509_CRL_free(crl);
}
static void NativeCrypto_X509_CRL_print(JNIEnv* env, jclass, jlong bioRef, jlong x509CrlRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_print(%p, %p)", bio, crl);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_CRL_print(%p, %p) => bio == null", bio, crl);
return;
}
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_print(%p, %p) => crl == null", bio, crl);
return;
}
if (!X509_CRL_print(bio, crl)) {
throwExceptionIfNecessary(env, "X509_CRL_print");
JNI_TRACE("X509_CRL_print(%p, %p) => threw error", bio, crl);
} else {
JNI_TRACE("X509_CRL_print(%p, %p) => success", bio, crl);
}
}
static jstring NativeCrypto_get_X509_CRL_sig_alg_oid(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p)", crl);
if (crl == NULL || crl->sig_alg == NULL) {
jniThrowNullPointerException(env, "crl == NULL || crl->sig_alg == NULL");
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p) => crl == NULL", crl);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, crl->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_CRL_sig_alg_parameter(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => crl == null", crl);
return NULL;
}
if (crl->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => null", crl);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE, i2d_ASN1_TYPE>(env, crl->sig_alg->parameter);
}
static jbyteArray NativeCrypto_X509_CRL_get_issuer_name(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_issuer_name(%p)", crl);
return ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env, X509_CRL_get_issuer(crl));
}
static long NativeCrypto_X509_CRL_get_version(JNIEnv*, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_version(%p)", crl);
long version = X509_CRL_get_version(crl);
JNI_TRACE("X509_CRL_get_version(%p) => %ld", crl, version);
return version;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static X509_EXTENSION *X509Type_get_ext(JNIEnv* env, T* x509Type, jstring oidString) {
JNI_TRACE("X509Type_get_ext(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509 == null");
return NULL;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
return NULL;
}
Unique_ASN1_OBJECT asn1(OBJ_txt2obj(oid.c_str(), 1));
if (asn1.get() == NULL) {
JNI_TRACE("X509Type_get_ext(%p, %s) => oid conversion failed", x509Type, oid.c_str());
freeOpenSslErrorState();
return NULL;
}
int extIndex = get_ext_by_OBJ_func(x509Type, asn1.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509Type_get_ext(%p, %s) => ext not found", x509Type, oid.c_str());
return NULL;
}
X509_EXTENSION* ext = get_ext_func(x509Type, extIndex);
JNI_TRACE("X509Type_get_ext(%p, %s) => %p", x509Type, oid.c_str(), ext);
return ext;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static jbyteArray X509Type_get_ext_oid(JNIEnv* env, T* x509Type, jstring oidString) {
X509_EXTENSION* ext = X509Type_get_ext<T, get_ext_by_OBJ_func, get_ext_func>(env, x509Type,
oidString);
if (ext == NULL) {
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => fetching extension failed", x509Type, oidString);
return NULL;
}
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => %p", x509Type, oidString, ext->value);
return ASN1ToByteArray<ASN1_OCTET_STRING, i2d_ASN1_OCTET_STRING>(env, ext->value);
}
static jint NativeCrypto_X509_CRL_get_ext(JNIEnv* env, jclass, jlong x509CrlRef, jstring oid) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext(%p, %p)", crl, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(
env, crl, oid);
JNI_TRACE("X509_CRL_get_ext(%p, %p) => %p", crl, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jint NativeCrypto_X509_REVOKED_get_ext(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oid) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext(%p, %p)", revoked, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ,
X509_REVOKED_get_ext>(env, revoked, oid);
JNI_TRACE("X509_REVOKED_get_ext(%p, %p) => %p", revoked, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_dup(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_dup(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_dup(%p) => revoked == null", revoked);
return 0;
}
X509_REVOKED* dup = X509_REVOKED_dup(revoked);
JNI_TRACE("X509_REVOKED_dup(%p) => %p", revoked, dup);
return reinterpret_cast<uintptr_t>(dup);
}
static jlong NativeCrypto_get_X509_REVOKED_revocationDate(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("get_X509_REVOKED_revocationDate(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => revoked == null", revoked);
return 0;
}
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => %p", revoked, revoked->revocationDate);
return reinterpret_cast<uintptr_t>(revoked->revocationDate);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
static void NativeCrypto_X509_REVOKED_print(JNIEnv* env, jclass, jlong bioRef, jlong x509RevokedRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_print(%p, %p)", bio, revoked);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => bio == null", bio, revoked);
return;
}
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => revoked == null", bio, revoked);
return;
}
BIO_printf(bio, "Serial Number: ");
i2a_ASN1_INTEGER(bio, revoked->serialNumber);
BIO_printf(bio, "\nRevocation Date: ");
ASN1_TIME_print(bio, revoked->revocationDate);
BIO_printf(bio, "\n");
X509V3_extensions_print(bio, "CRL entry extensions", revoked->extensions, 0, 0);
}
#pragma GCC diagnostic pop
static jbyteArray NativeCrypto_get_X509_CRL_crl_enc(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_crl_enc(%p)", crl);
return ASN1ToByteArray<X509_CRL_INFO, i2d_X509_CRL_INFO>(env, crl->crl);
}
static void NativeCrypto_X509_CRL_verify(JNIEnv* env, jclass, jlong x509CrlRef, jlong pkeyRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("X509_CRL_verify(%p, %p)", crl, pkey);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => crl == null", crl, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => pkey == null", crl, pkey);
return;
}
if (X509_CRL_verify(crl, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_CRL_verify");
JNI_TRACE("X509_CRL_verify(%p, %p) => verify failure", crl, pkey);
} else {
JNI_TRACE("X509_CRL_verify(%p, %p) => verify success", crl, pkey);
}
}
static jlong NativeCrypto_X509_CRL_get_lastUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_lastUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* lastUpdate = X509_CRL_get_lastUpdate(crl);
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => %p", crl, lastUpdate);
return reinterpret_cast<uintptr_t>(lastUpdate);
}
static jlong NativeCrypto_X509_CRL_get_nextUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_nextUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* nextUpdate = X509_CRL_get_nextUpdate(crl);
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => %p", crl, nextUpdate);
return reinterpret_cast<uintptr_t>(nextUpdate);
}
static jbyteArray NativeCrypto_i2d_X509_REVOKED(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* x509Revoked =
reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("i2d_X509_REVOKED(%p)", x509Revoked);
return ASN1ToByteArray<X509_REVOKED, i2d_X509_REVOKED>(env, x509Revoked);
}
static jint NativeCrypto_X509_supported_extension(JNIEnv* env, jclass, jlong x509ExtensionRef) {
X509_EXTENSION* ext = reinterpret_cast<X509_EXTENSION*>(static_cast<uintptr_t>(x509ExtensionRef));
if (ext == NULL) {
jniThrowNullPointerException(env, "ext == NULL");
return 0;
}
return X509_supported_extension(ext);
}
static inline void get_ASN1_TIME_data(char **data, int* output, size_t len) {
char c = **data;
**data = '\0';
*data -= len;
*output = atoi(*data);
*(*data + len) = c;
}
static void NativeCrypto_ASN1_TIME_to_Calendar(JNIEnv* env, jclass, jlong asn1TimeRef, jobject calendar) {
ASN1_TIME* asn1Time = reinterpret_cast<ASN1_TIME*>(static_cast<uintptr_t>(asn1TimeRef));
JNI_TRACE("ASN1_TIME_to_Calendar(%p, %p)", asn1Time, calendar);
if (asn1Time == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
Unique_ASN1_GENERALIZEDTIME gen(ASN1_TIME_to_generalizedtime(asn1Time, NULL));
if (gen.get() == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
if (gen->length < 14 || gen->data == NULL) {
jniThrowNullPointerException(env, "gen->length < 14 || gen->data == NULL");
return;
}
int sec, min, hour, mday, mon, year;
char *p = (char*) &gen->data[14];
get_ASN1_TIME_data(&p, &sec, 2);
get_ASN1_TIME_data(&p, &min, 2);
get_ASN1_TIME_data(&p, &hour, 2);
get_ASN1_TIME_data(&p, &mday, 2);
get_ASN1_TIME_data(&p, &mon, 2);
get_ASN1_TIME_data(&p, &year, 4);
env->CallVoidMethod(calendar, calendar_setMethod, year, mon - 1, mday, hour, min, sec);
}
static jstring NativeCrypto_OBJ_txt2nid_oid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_oid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_oid(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_oid(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
Unique_ASN1_OBJECT obj(OBJ_nid2obj(nid));
if (obj.get() == NULL) {
throwExceptionIfNecessary(env, "OBJ_nid2obj");
return NULL;
}
ScopedLocalRef<jstring> ouputStr(env, ASN1_OBJECT_to_OID_string(env, obj.get()));
JNI_TRACE("OBJ_txt2nid_oid(%s) => %p", oid.c_str(), ouputStr.get());
return ouputStr.release();
}
static jstring NativeCrypto_X509_NAME_print_ex(JNIEnv* env, jclass, jlong x509NameRef, jlong jflags) {
X509_NAME* x509name = reinterpret_cast<X509_NAME*>(static_cast<uintptr_t>(x509NameRef));
unsigned long flags = static_cast<unsigned long>(jflags);
JNI_TRACE("X509_NAME_print_ex(%p, %ld)", x509name, flags);
if (x509name == NULL) {
jniThrowNullPointerException(env, "x509name == null");
JNI_TRACE("X509_NAME_print_ex(%p, %ld) => x509name == null", x509name, flags);
return NULL;
}
return X509_NAME_to_jstring(env, x509name, flags);
}
template <typename T, T* (*d2i_func)(BIO*, T**)>
static jlong d2i_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return 0;
}
T* x = d2i_func(bio, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "d2i_ASN1Object_to_jlong");
return 0;
}
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_d2i_X509_CRL_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509_CRL, d2i_X509_CRL_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509, d2i_X509_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509(JNIEnv* env, jclass, jbyteArray certBytes) {
X509* x = ByteArrayToASN1<X509, d2i_X509>(env, certBytes);
return reinterpret_cast<uintptr_t>(x);
}
static jbyteArray NativeCrypto_i2d_X509(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509(%p)", x509);
return ASN1ToByteArray<X509, i2d_X509>(env, x509);
}
static jbyteArray NativeCrypto_i2d_X509_PUBKEY(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509_PUBKEY(%p)", x509);
return ASN1ToByteArray<X509_PUBKEY, i2d_X509_PUBKEY>(env, X509_get_X509_PUBKEY(x509));
}
template<typename T, T* (*PEM_read_func)(BIO*, T**, pem_password_cb*, void*)>
static jlong PEM_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => bio == null", bio);
return 0;
}
T* x = PEM_read_func(bio, NULL, NULL, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "PEM_ASN1Object_to_jlong");
// Sometimes the PEM functions fail without pushing an error
if (!env->ExceptionCheck()) {
jniThrowRuntimeException(env, "Failure parsing PEM");
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => threw exception", bio);
return 0;
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => %p", bio, x);
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_PEM_read_bio_X509(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509(0x%llx)", bioRef);
return PEM_ASN1Object_to_jlong<X509, PEM_read_bio_X509>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_X509_CRL(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509_CRL(0x%llx)", bioRef);
return PEM_ASN1Object_to_jlong<X509_CRL, PEM_read_bio_X509_CRL>(env, bioRef);
}
static STACK_OF(X509)* PKCS7_get_certs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->cert;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->cert;
} else {
JNI_TRACE("PKCS7_get_certs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
static STACK_OF(X509_CRL)* PKCS7_get_CRLs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->crl;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->crl;
} else {
JNI_TRACE("PKCS7_get_CRLs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
template <typename T, typename T_stack>
static jlongArray PKCS7_to_ItemArray(JNIEnv* env, T_stack* stack, T* (*dup_func)(T*))
{
if (stack == NULL) {
return NULL;
}
ScopedLocalRef<jlongArray> ref_array(env, NULL);
size_t size = sk_num(reinterpret_cast<_STACK*>(stack));
ref_array.reset(env->NewLongArray(size));
ScopedLongArrayRW items(env, ref_array.get());
for (size_t i = 0; i < size; i++) {
T* item = reinterpret_cast<T*>(sk_value(reinterpret_cast<_STACK*>(stack), i));
items[i] = reinterpret_cast<uintptr_t>(dup_func(item));
}
JNI_TRACE("PKCS7_to_ItemArray(%p) => %p [size=%d]", stack, ref_array.get(), size);
return ref_array.release();
}
#define PKCS7_CERTS 1
#define PKCS7_CRLS 2
static jlongArray NativeCrypto_PEM_read_bio_PKCS7(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => bio == null", bio);
return 0;
}
Unique_PKCS7 pkcs7(PEM_read_bio_PKCS7(bio, NULL, NULL, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "PEM_read_bio_PKCS7_CRLs");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => threw exception", bio);
return 0;
}
switch (which) {
case PKCS7_CERTS:
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
}
static jlongArray NativeCrypto_d2i_PKCS7_bio(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_PKCS7_bio(%p, %d)", bio, which);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => bio == null", bio, which);
return 0;
}
Unique_PKCS7 pkcs7(d2i_PKCS7_bio(bio, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS7_bio");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => threw exception", bio, which);
return 0;
}
switch (which) {
case PKCS7_CERTS:
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
}
static jbyteArray NativeCrypto_i2d_PKCS7(JNIEnv* env, jclass, jlongArray certsArray) {
JNI_TRACE("i2d_PKCS7(%p)", certsArray);
Unique_PKCS7 pkcs7(PKCS7_new());
if (pkcs7.get() == NULL) {
jniThrowNullPointerException(env, "pkcs7 == null");
JNI_TRACE("i2d_PKCS7(%p) => pkcs7 == null", certsArray);
return NULL;
}
if (PKCS7_set_type(pkcs7.get(), NID_pkcs7_signed) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type");
return NULL;
}
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (PKCS7_add_certificate(pkcs7.get(), item) != 1) {
throwExceptionIfNecessary(env, "i2d_PKCS7");
return NULL;
}
}
JNI_TRACE("i2d_PKCS7(%p) => %d certs", certsArray, certs.size());
return ASN1ToByteArray<PKCS7, i2d_PKCS7>(env, pkcs7.get());
}
typedef STACK_OF(X509) PKIPATH;
ASN1_ITEM_TEMPLATE(PKIPATH) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PkiPath, X509)
ASN1_ITEM_TEMPLATE_END(PKIPATH)
static jlongArray NativeCrypto_ASN1_seq_unpack_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p)", bio);
Unique_sk_X509 path((PKIPATH*) ASN1_item_d2i_bio(ASN1_ITEM_rptr(PKIPATH), bio, NULL));
if (path.get() == NULL) {
throwExceptionIfNecessary(env, "ASN1_seq_unpack_X509_bio");
return NULL;
}
size_t size = sk_X509_num(path.get());
ScopedLocalRef<jlongArray> certArray(env, env->NewLongArray(size));
ScopedLongArrayRW certs(env, certArray.get());
for (size_t i = 0; i < size; i++) {
X509* item = reinterpret_cast<X509*>(sk_X509_shift(path.get()));
certs[i] = reinterpret_cast<uintptr_t>(item);
}
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => returns %d items", bio, size);
return certArray.release();
}
static jbyteArray NativeCrypto_ASN1_seq_pack_X509(JNIEnv* env, jclass, jlongArray certs) {
JNI_TRACE("ASN1_seq_pack_X509(%p)", certs);
ScopedLongArrayRO certsArray(env, certs);
if (certsArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to get certs array", certs);
return NULL;
}
Unique_sk_X509 certStack(sk_X509_new_null());
if (certStack.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to make cert stack", certs);
return NULL;
}
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
sk_X509_push(certStack.get(), X509_dup_nocopy(x509));
}
int len;
Unique_OPENSSL_str encoded(ASN1_seq_pack(
reinterpret_cast<STACK_OF(OPENSSL_BLOCK)*>(
reinterpret_cast<uintptr_t>(certStack.get())),
reinterpret_cast<int (*)(void*, unsigned char**)>(i2d_X509), NULL, &len));
if (encoded.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => trouble encoding", certs);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(len));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => creating byte array failed", certs);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => using byte array failed", certs);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
memcpy(p, encoded.get(), len);
return byteArray.release();
}
static void NativeCrypto_X509_free(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_free(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_free(%p) => x509 == null", x509);
return;
}
X509_free(x509);
}
static jint NativeCrypto_X509_cmp(JNIEnv* env, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_cmp(%p, %p)", x509_1, x509_2);
if (x509_1 == NULL) {
jniThrowNullPointerException(env, "x509_1 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_1 == null", x509_1, x509_2);
return -1;
}
if (x509_2 == NULL) {
jniThrowNullPointerException(env, "x509_2 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_2 == null", x509_1, x509_2);
return -1;
}
int ret = X509_cmp(x509_1, x509_2);
JNI_TRACE("X509_cmp(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static jint NativeCrypto_get_X509_hashCode(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_hashCode(%p) => x509 == null", x509);
return 0;
}
// Force caching extensions.
X509_check_ca(x509);
jint hashCode = 0L;
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
hashCode = 31 * hashCode + x509->sha1_hash[i];
}
return hashCode;
}
static void NativeCrypto_X509_print_ex(JNIEnv* env, jclass, jlong bioRef, jlong x509Ref,
jlong nmflagJava, jlong certflagJava) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
long nmflag = static_cast<long>(nmflagJava);
long certflag = static_cast<long>(certflagJava);
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld)", bio, x509, nmflag, certflag);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => bio == null", bio, x509, nmflag, certflag);
return;
}
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => x509 == null", bio, x509, nmflag, certflag);
return;
}
if (!X509_print_ex(bio, x509, nmflag, certflag)) {
throwExceptionIfNecessary(env, "X509_print_ex");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => threw error", bio, x509, nmflag, certflag);
} else {
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => success", bio, x509, nmflag, certflag);
}
}
static jlong NativeCrypto_X509_get_pubkey(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_pubkey(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_pubkey(%p) => x509 == null", x509);
return 0;
}
Unique_EVP_PKEY pkey(X509_get_pubkey(x509));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "X509_get_pubkey");
return 0;
}
JNI_TRACE("X509_get_pubkey(%p) => %p", x509, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jbyteArray NativeCrypto_X509_get_issuer_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_issuer_name(%p)", x509);
return ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env, X509_get_issuer_name(x509));
}
static jbyteArray NativeCrypto_X509_get_subject_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_subject_name(%p)", x509);
return ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env, X509_get_subject_name(x509));
}
static jstring NativeCrypto_get_X509_pubkey_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_pubkey_oid(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_pubkey_oid(%p) => x509 == null", x509);
return NULL;
}
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
return ASN1_OBJECT_to_OID_string(env, pubkey->algor->algorithm);
}
static jstring NativeCrypto_get_X509_sig_alg_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_oid(%p)", x509);
if (x509 == NULL || x509->sig_alg == NULL) {
jniThrowNullPointerException(env, "x509 == NULL || x509->sig_alg == NULL");
JNI_TRACE("get_X509_sig_alg_oid(%p) => x509 == NULL", x509);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, x509->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_sig_alg_parameter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_parameter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_sig_alg_parameter(%p) => x509 == null", x509);
return NULL;
}
if (x509->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_sig_alg_parameter(%p) => null", x509);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE, i2d_ASN1_TYPE>(env, x509->sig_alg->parameter);
}
static jbooleanArray NativeCrypto_get_X509_issuerUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_issuerUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_issuerUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->issuerUID == NULL) {
JNI_TRACE("get_X509_issuerUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->issuerUID);
}
static jbooleanArray NativeCrypto_get_X509_subjectUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_subjectUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_subjectUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->subjectUID == NULL) {
JNI_TRACE("get_X509_subjectUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->subjectUID);
}
static jbooleanArray NativeCrypto_get_X509_ex_kusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_kusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_kusage(%p) => x509 == null", x509);
return NULL;
}
Unique_ASN1_BIT_STRING bitStr(static_cast<ASN1_BIT_STRING*>(
X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL)));
if (bitStr.get() == NULL) {
JNI_TRACE("get_X509_ex_kusage(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, bitStr.get());
}
static jobjectArray NativeCrypto_get_X509_ex_xkusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_xkusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_xkusage(%p) => x509 == null", x509);
return NULL;
}
Unique_sk_ASN1_OBJECT objArray(static_cast<STACK_OF(ASN1_OBJECT)*>(
X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL)));
if (objArray.get() == NULL) {
JNI_TRACE("get_X509_ex_xkusage(%p) => null", x509);
return NULL;
}
size_t size = sk_ASN1_OBJECT_num(objArray.get());
ScopedLocalRef<jobjectArray> exKeyUsage(env, env->NewObjectArray(size, stringClass, NULL));
if (exKeyUsage.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
ScopedLocalRef<jstring> oidStr(env, ASN1_OBJECT_to_OID_string(env,
sk_ASN1_OBJECT_value(objArray.get(), i)));
env->SetObjectArrayElement(exKeyUsage.get(), i, oidStr.get());
}
JNI_TRACE("get_X509_ex_xkusage(%p) => success (%d entries)", x509, size);
return exKeyUsage.release();
}
static jint NativeCrypto_get_X509_ex_pathlen(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_pathlen(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_pathlen(%p) => x509 == null", x509);
return 0;
}
/* Just need to do this to cache the ex_* values. */
X509_check_ca(x509);
JNI_TRACE("get_X509_ex_pathlen(%p) => %ld", x509, x509->ex_pathlen);
return x509->ex_pathlen;
}
static jbyteArray NativeCrypto_X509_get_ext_oid(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_ext_oid(%p, %p)", x509, oidString);
return X509Type_get_ext_oid<X509, X509_get_ext_by_OBJ, X509_get_ext>(env, x509, oidString);
}
static jbyteArray NativeCrypto_X509_CRL_get_ext_oid(JNIEnv* env, jclass, jlong x509CrlRef,
jstring oidString) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext_oid(%p, %p)", crl, oidString);
return X509Type_get_ext_oid<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(env, crl,
oidString);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_ext_oid(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oidString) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext_oid(%p, %p)", revoked, oidString);
return X509Type_get_ext_oid<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ, X509_REVOKED_get_ext>(
env, revoked, oidString);
}
template<typename T, int (*get_ext_by_critical_func)(T*, int, int), X509_EXTENSION* (*get_ext_func)(T*, int)>
static jobjectArray get_X509Type_ext_oids(JNIEnv* env, jlong x509Ref, jint critical) {
T* x509 = reinterpret_cast<T*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509Type_ext_oids(%p, %d)", x509, critical);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => x509 == null", x509, critical);
return NULL;
}
int lastPos = -1;
int count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
count++;
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) has %d entries", x509, critical, count);
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, stringClass, NULL));
if (joa.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => fail to allocate result array", x509, critical);
return NULL;
}
lastPos = -1;
count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
X509_EXTENSION* ext = get_ext_func(x509, lastPos);
ScopedLocalRef<jstring> extOid(env, ASN1_OBJECT_to_OID_string(env, ext->object));
if (extOid.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p) => couldn't get OID", x509);
return NULL;
}
env->SetObjectArrayElement(joa.get(), count++, extOid.get());
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => success", x509, critical);
return joa.release();
}
static jobjectArray NativeCrypto_get_X509_ext_oids(JNIEnv* env, jclass, jlong x509Ref,
jint critical) {
JNI_TRACE("get_X509_ext_oids(0x%llx, %d)", x509Ref, critical);
return get_X509Type_ext_oids<X509, X509_get_ext_by_critical, X509_get_ext>(env, x509Ref,
critical);
}
static jobjectArray NativeCrypto_get_X509_CRL_ext_oids(JNIEnv* env, jclass, jlong x509CrlRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", x509CrlRef, critical);
return get_X509Type_ext_oids<X509_CRL, X509_CRL_get_ext_by_critical, X509_CRL_get_ext>(env,
x509CrlRef, critical);
}
static jobjectArray NativeCrypto_get_X509_REVOKED_ext_oids(JNIEnv* env, jclass, jlong x509RevokedRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", x509RevokedRef, critical);
return get_X509Type_ext_oids<X509_REVOKED, X509_REVOKED_get_ext_by_critical,
X509_REVOKED_get_ext>(env, x509RevokedRef, critical);
}
#ifdef WITH_JNI_TRACE
/**
* Based on example logging call back from SSL_CTX_set_info_callback man page
*/
static void info_callback_LOG(const SSL* s __attribute__ ((unused)), int where, int ret)
{
int w = where & ~SSL_ST_MASK;
const char* str;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
} else {
str = "undefined";
}
if (where & SSL_CB_LOOP) {
JNI_TRACE("ssl=%p %s:%s %s", s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
JNI_TRACE("ssl=%p SSL3 alert %s:%s:%s %s %s",
s,
str,
SSL_alert_type_string(ret),
SSL_alert_desc_string(ret),
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
JNI_TRACE("ssl=%p %s:failed exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret < 0) {
JNI_TRACE("ssl=%p %s:error exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret == 1) {
JNI_TRACE("ssl=%p %s:ok exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown exit %d in %s %s",
s, str, ret, SSL_state_string(s), SSL_state_string_long(s));
}
} else if (where & SSL_CB_HANDSHAKE_START) {
JNI_TRACE("ssl=%p handshake start in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_HANDSHAKE_DONE) {
JNI_TRACE("ssl=%p handshake done in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown where %d in %s %s",
s, str, where, SSL_state_string(s), SSL_state_string_long(s));
}
}
#endif
/**
* Returns an array containing all the X509 certificate references
*/
static jlongArray getCertificateRefs(JNIEnv* env, const STACK_OF(X509)* chain)
{
if (chain == NULL) {
// Chain can be NULL if the associated cipher doesn't do certs.
return NULL;
}
ssize_t count = sk_X509_num(chain);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jlongArray> refArray(env, env->NewLongArray(count));
ScopedLongArrayRW refs(env, refArray.get());
if (refs.get() == NULL) {
return NULL;
}
for (ssize_t i = 0; i < count; i++) {
refs[i] = reinterpret_cast<uintptr_t>(X509_dup_nocopy(sk_X509_value(chain, i)));
}
return refArray.release();
}
/**
* Returns an array containing all the X500 principal's bytes.
*/
static jobjectArray getPrincipalBytes(JNIEnv* env, const STACK_OF(X509_NAME)* names)
{
if (names == NULL) {
return NULL;
}
int count = sk_X509_NAME_num(names);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, byteArrayClass, NULL));
if (joa.get() == NULL) {
return NULL;
}
for (int i = 0; i < count; i++) {
X509_NAME* principal = sk_X509_NAME_value(names, i);
ScopedLocalRef<jbyteArray> byteArray(env, ASN1ToByteArray<X509_NAME, i2d_X509_NAME>(env,
principal));
if (byteArray.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(joa.get(), i, byteArray.get());
}
return joa.release();
}
/**
* Our additional application data needed for getting synchronization right.
* This maybe warrants a bit of lengthy prose:
*
* (1) We use a flag to reflect whether we consider the SSL connection alive.
* Any read or write attempt loops will be cancelled once this flag becomes 0.
*
* (2) We use an int to count the number of threads that are blocked by the
* underlying socket. This may be at most two (one reader and one writer), since
* the Java layer ensures that no more threads will enter the native code at the
* same time.
*
* (3) The pipe is used primarily as a means of cancelling a blocking select()
* when we want to close the connection (aka "emergency button"). It is also
* necessary for dealing with a possible race condition situation: There might
* be cases where both threads see an SSL_ERROR_WANT_READ or
* SSL_ERROR_WANT_WRITE. Both will enter a select() with the proper argument.
* If one leaves the select() successfully before the other enters it, the
* "success" event is already consumed and the second thread will be blocked,
* possibly forever (depending on network conditions).
*
* The idea for solving the problem looks like this: Whenever a thread is
* successful in moving around data on the network, and it knows there is
* another thread stuck in a select(), it will write a byte to the pipe, waking
* up the other thread. A thread that returned from select(), on the other hand,
* knows whether it's been woken up by the pipe. If so, it will consume the
* byte, and the original state of affairs has been restored.
*
* The pipe may seem like a bit of overhead, but it fits in nicely with the
* other file descriptors of the select(), so there's only one condition to wait
* for.
*
* (4) Finally, a mutex is needed to make sure that at most one thread is in
* either SSL_read() or SSL_write() at any given time. This is an OpenSSL
* requirement. We use the same mutex to guard the field for counting the
* waiting threads.
*
* Note: The current implementation assumes that we don't have to deal with
* problems induced by multiple cores or processors and their respective
* memory caches. One possible problem is that of inconsistent views on the
* "aliveAndKicking" field. This could be worked around by also enclosing all
* accesses to that field inside a lock/unlock sequence of our mutex, but
* currently this seems a bit like overkill. Marking volatile at the very least.
*
* During handshaking, additional fields are used to up-call into
* Java to perform certificate verification and handshake
* completion. These are also used in any renegotiation.
*
* (5) the JNIEnv so we can invoke the Java callback
*
* (6) a NativeCrypto.SSLHandshakeCallbacks instance for callbacks from native to Java
*
* (7) a java.io.FileDescriptor wrapper to check for socket close
*
* We store the NPN protocols list so we can either send it (from the server) or
* select a protocol (on the client). We eagerly acquire a pointer to the array
* data so the callback doesn't need to acquire resources that it cannot
* release.
*
* Because renegotiation can be requested by the peer at any time,
* care should be taken to maintain an appropriate JNIEnv on any
* downcall to openssl since it could result in an upcall to Java. The
* current code does try to cover these cases by conditionally setting
* the JNIEnv on calls that can read and write to the SSL such as
* SSL_do_handshake, SSL_read, SSL_write, and SSL_shutdown.
*
* Finally, we have two emphemeral keys setup by OpenSSL callbacks:
*
* (8) a set of ephemeral RSA keys that is lazily generated if a peer
* wants to use an exportable RSA cipher suite.
*
* (9) a set of ephemeral EC keys that is lazily generated if a peer
* wants to use an TLS_ECDHE_* cipher suite.
*
*/
class AppData {
public:
volatile int aliveAndKicking;
int waitingThreads;
int fdsEmergency[2];
MUTEX_TYPE mutex;
JNIEnv* env;
jobject sslHandshakeCallbacks;
jbyteArray npnProtocolsArray;
jbyte* npnProtocolsData;
size_t npnProtocolsLength;
jbyteArray alpnProtocolsArray;
jbyte* alpnProtocolsData;
size_t alpnProtocolsLength;
Unique_RSA ephemeralRsa;
Unique_EC_KEY ephemeralEc;
/**
* Creates the application data context for the SSL*.
*/
public:
static AppData* create() {
UniquePtr<AppData> appData(new AppData());
if (pipe(appData.get()->fdsEmergency) == -1) {
ALOGE("AppData::create pipe(2) failed: %s", strerror(errno));
return NULL;
}
if (!setBlocking(appData.get()->fdsEmergency[0], false)) {
ALOGE("AppData::create fcntl(2) failed: %s", strerror(errno));
return NULL;
}
if (MUTEX_SETUP(appData.get()->mutex) == -1) {
ALOGE("pthread_mutex_init(3) failed: %s", strerror(errno));
return NULL;
}
return appData.release();
}
~AppData() {
aliveAndKicking = 0;
if (fdsEmergency[0] != -1) {
close(fdsEmergency[0]);
}
if (fdsEmergency[1] != -1) {
close(fdsEmergency[1]);
}
clearCallbackState();
MUTEX_CLEANUP(mutex);
}
private:
AppData() :
aliveAndKicking(1),
waitingThreads(0),
env(NULL),
sslHandshakeCallbacks(NULL),
npnProtocolsArray(NULL),
npnProtocolsData(NULL),
npnProtocolsLength(-1),
alpnProtocolsArray(NULL),
alpnProtocolsData(NULL),
alpnProtocolsLength(-1),
ephemeralRsa(NULL),
ephemeralEc(NULL) {
fdsEmergency[0] = -1;
fdsEmergency[1] = -1;
}
public:
/**
* Used to set the SSL-to-Java callback state before each SSL_*
* call that may result in a callback. It should be cleared after
* the operation returns with clearCallbackState.
*
* @param env The JNIEnv
* @param shc The SSLHandshakeCallbacks
* @param fd The FileDescriptor
* @param npnProtocols NPN protocols so that they may be advertised (by the
* server) or selected (by the client). Has no effect
* unless NPN is enabled.
* @param alpnProtocols ALPN protocols so that they may be advertised (by the
* server) or selected (by the client). Passing non-NULL
* enables ALPN.
*/
bool setCallbackState(JNIEnv* e, jobject shc, jobject fd, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
UniquePtr<NetFd> netFd;
if (fd != NULL) {
netFd.reset(new NetFd(e, fd));
if (netFd->isClosed()) {
return false;
}
}
env = e;
sslHandshakeCallbacks = shc;
if (npnProtocols != NULL) {
npnProtocolsData = e->GetByteArrayElements(npnProtocols, NULL);
if (npnProtocolsData == NULL) {
clearCallbackState();
return false;
}
npnProtocolsArray = npnProtocols;
npnProtocolsLength = e->GetArrayLength(npnProtocols);
}
if (alpnProtocols != NULL) {
alpnProtocolsData = e->GetByteArrayElements(alpnProtocols, NULL);
if (alpnProtocolsData == NULL) {
clearCallbackState();
return false;
}
alpnProtocolsArray = alpnProtocols;
alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
}
return true;
}
void clearCallbackState() {
sslHandshakeCallbacks = NULL;
if (npnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(npnProtocolsArray, npnProtocolsData, JNI_ABORT);
npnProtocolsArray = NULL;
npnProtocolsData = NULL;
npnProtocolsLength = -1;
}
if (alpnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(alpnProtocolsArray, alpnProtocolsData, JNI_ABORT);
alpnProtocolsArray = NULL;
alpnProtocolsData = NULL;
alpnProtocolsLength = -1;
}
env = NULL;
}
};
/**
* Dark magic helper function that checks, for a given SSL session, whether it
* can SSL_read() or SSL_write() without blocking. Takes into account any
* concurrent attempts to close the SSLSocket from the Java side. This is
* needed to get rid of the hangs that occur when thread #1 closes the SSLSocket
* while thread #2 is sitting in a blocking read or write. The type argument
* specifies whether we are waiting for readability or writability. It expects
* to be passed either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, since we
* only need to wait in case one of these problems occurs.
*
* @param env
* @param type Either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
* @param fdObject The FileDescriptor, since appData->fileDescriptor should be NULL
* @param appData The application data structure with mutex info etc.
* @param timeout_millis The timeout value for select call, with the special value
* 0 meaning no timeout at all (wait indefinitely). Note: This is
* the Java semantics of the timeout value, not the usual
* select() semantics.
* @return The result of the inner select() call,
* THROW_SOCKETEXCEPTION if a SocketException was thrown, -1 on
* additional errors
*/
static int sslSelect(JNIEnv* env, int type, jobject fdObject, AppData* appData, int timeout_millis) {
// This loop is an expanded version of the NET_FAILURE_RETRY
// macro. It cannot simply be used in this case because select
// cannot be restarted without recreating the fd_sets and timeout
// structure.
int result;
fd_set rfds;
fd_set wfds;
do {
NetFd fd(env, fdObject);
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
int intFd = fd.get();
JNI_TRACE("sslSelect type=%s fd=%d appData=%p timeout_millis=%d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE", intFd, appData, timeout_millis);
FD_ZERO(&rfds);
FD_ZERO(&wfds);
if (type == SSL_ERROR_WANT_READ) {
FD_SET(intFd, &rfds);
} else {
FD_SET(intFd, &wfds);
}
FD_SET(appData->fdsEmergency[0], &rfds);
int maxFd = (intFd > appData->fdsEmergency[0]) ? intFd : appData->fdsEmergency[0];
// Build a struct for the timeout data if we actually want a timeout.
timeval tv;
timeval* ptv;
if (timeout_millis > 0) {
tv.tv_sec = timeout_millis / 1000;
tv.tv_usec = (timeout_millis % 1000) * 1000;
ptv = &tv;
} else {
ptv = NULL;
}
AsynchronousCloseMonitor monitor(intFd);
result = select(maxFd + 1, &rfds, &wfds, NULL, ptv);
JNI_TRACE("sslSelect %s fd=%d appData=%p timeout_millis=%d => %d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE",
fd.get(), appData, timeout_millis, result);
if (result == -1) {
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
if (errno != EINTR) {
break;
}
}
} while (result == -1);
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (result > 0) {
// We have been woken up by a token in the emergency pipe. We
// can't be sure the token is still in the pipe at this point
// because it could have already been read by the thread that
// originally wrote it if it entered sslSelect and acquired
// the mutex before we did. Thus we cannot safely read from
// the pipe in a blocking way (so we make the pipe
// non-blocking at creation).
if (FD_ISSET(appData->fdsEmergency[0], &rfds)) {
char token;
do {
read(appData->fdsEmergency[0], &token, 1);
} while (errno == EINTR);
}
}
// Tell the world that there is now one thread less waiting for the
// underlying network.
appData->waitingThreads--;
MUTEX_UNLOCK(appData->mutex);
return result;
}
/**
* Helper function that wakes up a thread blocked in select(), in case there is
* one. Is being called by sslRead() and sslWrite() as well as by JNI glue
* before closing the connection.
*
* @param data The application data structure with mutex info etc.
*/
static void sslNotify(AppData* appData) {
// Write a byte to the emergency pipe, so a concurrent select() can return.
// Note we have to restore the errno of the original system call, since the
// caller relies on it for generating error messages.
int errnoBackup = errno;
char token = '*';
do {
errno = 0;
write(appData->fdsEmergency[1], &token, 1);
} while (errno == EINTR);
errno = errnoBackup;
}
static AppData* toAppData(const SSL* ssl) {
return reinterpret_cast<AppData*>(SSL_get_app_data(ssl));
}
/**
* Verify the X509 certificate via SSL_CTX_set_cert_verify_callback
*/
static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg __attribute__ ((unused)))
{
/* Get the correct index to the SSLobject stored into X509_STORE_CTX. */
SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_store_ctx,
SSL_get_ex_data_X509_STORE_CTX_idx()));
JNI_TRACE("ssl=%p cert_verify_callback x509_store_ctx=%p arg=%p", ssl, x509_store_ctx, arg);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in cert_verify_callback");
JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "verifyCertificateChain", "(J[JLjava/lang/String;)V");
jlongArray refArray = getCertificateRefs(env, x509_store_ctx->untrusted);
const char* authMethod = SSL_authentication_method(ssl);
JNI_TRACE("ssl=%p cert_verify_callback calling verifyCertificateChain authMethod=%s",
ssl, authMethod);
jstring authMethodString = env->NewStringUTF(authMethod);
env->CallVoidMethod(sslHandshakeCallbacks, methodID,
static_cast<jlong>(reinterpret_cast<uintptr_t>(SSL_get1_session(ssl))), refArray,
authMethodString);
int result = (env->ExceptionCheck()) ? 0 : 1;
JNI_TRACE("ssl=%p cert_verify_callback => %d", ssl, result);
return result;
}
/**
* Call back to watch for handshake to be completed. This is necessary
* for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake
* returns before the handshake is completed in this case.
*/
static void info_callback(const SSL* ssl, int where, int ret) {
JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret);
#ifdef WITH_JNI_TRACE
info_callback_LOG(ssl, where, ret);
#endif
if (!(where & SSL_CB_HANDSHAKE_DONE) && !(where & SSL_CB_HANDSHAKE_START)) {
JNI_TRACE("ssl=%p info_callback ignored", ssl);
return;
}
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in info_callback");
JNI_TRACE("ssl=%p info_callback env error", ssl);
return;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback already pending exception", ssl);
return;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(cls, "onSSLStateChange", "(JII)V");
JNI_TRACE("ssl=%p info_callback calling onSSLStateChange", ssl);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, reinterpret_cast<jlong>(ssl), where, ret);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback exception", ssl);
}
JNI_TRACE("ssl=%p info_callback completed", ssl);
}
/**
* Call back to ask for a client certificate. There are three possible exit codes:
*
* 1 is success. x509Out and pkeyOut should point to the correct private key and certificate.
* 0 is unable to find key. x509Out and pkeyOut should be NULL.
* -1 is error and it doesn't matter what x509Out and pkeyOut are.
*/
static int client_cert_cb(SSL* ssl, X509** x509Out, EVP_PKEY** pkeyOut) {
JNI_TRACE("ssl=%p client_cert_cb x509Out=%p pkeyOut=%p", ssl, x509Out, pkeyOut);
/* Clear output of key and certificate in case of early exit due to error. */
*x509Out = NULL;
*pkeyOut = NULL;
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in client_cert_cb");
JNI_TRACE("ssl=%p client_cert_cb env error => 0", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb already pending exception => 0", ssl);
return -1;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "clientCertificateRequested", "([B[[B)V");
// Call Java callback which can use SSL_use_certificate and SSL_use_PrivateKey to set values
char ssl2_ctype = SSL3_CT_RSA_SIGN;
const char* ctype = NULL;
int ctype_num = 0;
jobjectArray issuers = NULL;
switch (ssl->version) {
case SSL2_VERSION:
ctype = &ssl2_ctype;
ctype_num = 1;
break;
case SSL3_VERSION:
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
case DTLS1_VERSION:
ctype = ssl->s3->tmp.ctype;
ctype_num = ssl->s3->tmp.ctype_num;
issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
break;
}
#ifdef WITH_JNI_TRACE
for (int i = 0; i < ctype_num; i++) {
JNI_TRACE("ssl=%p clientCertificateRequested keyTypes[%d]=%d", ssl, i, ctype[i]);
}
#endif
jbyteArray keyTypes = env->NewByteArray(ctype_num);
if (keyTypes == NULL) {
JNI_TRACE("ssl=%p client_cert_cb bytes == null => 0", ssl);
return 0;
}
env->SetByteArrayRegion(keyTypes, 0, ctype_num, reinterpret_cast<const jbyte*>(ctype));
JNI_TRACE("ssl=%p clientCertificateRequested calling clientCertificateRequested "
"keyTypes=%p issuers=%p", ssl, keyTypes, issuers);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, keyTypes, issuers);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb exception => 0", ssl);
return -1;
}
// Check for values set from Java
X509* certificate = SSL_get_certificate(ssl);
EVP_PKEY* privatekey = SSL_get_privatekey(ssl);
int result = 0;
if (certificate != NULL && privatekey != NULL) {
*x509Out = certificate;
*pkeyOut = privatekey;
result = 1;
} else {
// Some error conditions return NULL, so make sure it doesn't linger.
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p client_cert_cb => *x509=%p *pkey=%p %d", ssl, *x509Out, *pkeyOut, result);
return result;
}
static RSA* rsaGenerateKey(int keylength) {
Unique_BIGNUM bn(BN_new());
if (bn.get() == NULL) {
return NULL;
}
int setWordResult = BN_set_word(bn.get(), RSA_F4);
if (setWordResult != 1) {
return NULL;
}
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
return NULL;
}
int generateResult = RSA_generate_key_ex(rsa.get(), keylength, bn.get(), NULL);
if (generateResult != 1) {
return NULL;
}
return rsa.release();
}
/**
* Call back to ask for an ephemeral RSA key for SSL_RSA_EXPORT_WITH_RC4_40_MD5 (aka EXP-RC4-MD5)
*/
static RSA* tmp_rsa_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_rsa_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralRsa.get() == NULL) {
JNI_TRACE("ssl=%p tmp_rsa_callback generating ephemeral RSA key", ssl);
appData->ephemeralRsa.reset(rsaGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_rsa_callback => %p", ssl, appData->ephemeralRsa.get());
return appData->ephemeralRsa.get();
}
static DH* dhGenerateParameters(int keylength) {
/*
* The SSL_CTX_set_tmp_dh_callback(3SSL) man page discusses two
* different options for generating DH keys. One is generating the
* keys using a single set of DH parameters. However, generating
* DH parameters is slow enough (minutes) that they suggest doing
* it once at install time. The other is to generate DH keys from
* DSA parameters. Generating DSA parameters is faster than DH
* parameters, but to prevent small subgroup attacks, they needed
* to be regenerated for each set of DH keys. Setting the
* SSL_OP_SINGLE_DH_USE option make sure OpenSSL will call back
* for new DH parameters every type it needs to generate DH keys.
*/
#if 0
// Slow path that takes minutes but could be cached
Unique_DH dh(DH_new());
if (!DH_generate_parameters_ex(dh.get(), keylength, 2, NULL)) {
return NULL;
}
return dh.release();
#else
// Faster path but must have SSL_OP_SINGLE_DH_USE set
Unique_DSA dsa(DSA_new());
if (!DSA_generate_parameters_ex(dsa.get(), keylength, NULL, 0, NULL, NULL, NULL)) {
return NULL;
}
DH* dh = DSA_dup_DH(dsa.get());
return dh;
#endif
}
/**
* Call back to ask for Diffie-Hellman parameters
*/
static DH* tmp_dh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_dh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
DH* tmp_dh = dhGenerateParameters(keylength);
JNI_TRACE("ssl=%p tmp_dh_callback => %p", ssl, tmp_dh);
return tmp_dh;
}
static EC_KEY* ecGenerateKey(int keylength __attribute__ ((unused))) {
// TODO selected curve based on keylength
Unique_EC_KEY ec(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (ec.get() == NULL) {
return NULL;
}
return ec.release();
}
/**
* Call back to ask for an ephemeral EC key for TLS_ECDHE_* cipher suites
*/
static EC_KEY* tmp_ecdh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_ecdh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralEc.get() == NULL) {
JNI_TRACE("ssl=%p tmp_ecdh_callback generating ephemeral EC key", ssl);
appData->ephemeralEc.reset(ecGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_ecdh_callback => %p", ssl, appData->ephemeralEc.get());
return appData->ephemeralEc.get();
}
/*
* public static native int SSL_CTX_new();
*/
static jlong NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass) {
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
if (sslCtx.get() == NULL) {
throwExceptionIfNecessary(env, "SSL_CTX_new");
return 0;
}
SSL_CTX_set_options(sslCtx.get(),
SSL_OP_ALL
// Note: We explicitly do not allow SSLv2 to be used.
| SSL_OP_NO_SSLv2
// We also disable session tickets for better compatibility b/2682876
| SSL_OP_NO_TICKET
// We also disable compression for better compatibility b/2710492 b/2710497
| SSL_OP_NO_COMPRESSION
// Because dhGenerateParameters uses DSA_generate_parameters_ex
| SSL_OP_SINGLE_DH_USE
// Because ecGenerateParameters uses a fixed named curve
| SSL_OP_SINGLE_ECDH_USE);
int mode = SSL_CTX_get_mode(sslCtx.get());
/*
* Turn on "partial write" mode. This means that SSL_write() will
* behave like Posix write() and possibly return after only
* writing a partial buffer. Note: The alternative, perhaps
* surprisingly, is not that SSL_write() always does full writes
* but that it will force you to retry write calls having
* preserved the full state of the original call. (This is icky
* and undesirable.)
*/
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
// Reuse empty buffers within the SSL_CTX to save memory
mode |= SSL_MODE_RELEASE_BUFFERS;
SSL_CTX_set_mode(sslCtx.get(), mode);
SSL_CTX_set_cert_verify_callback(sslCtx.get(), cert_verify_callback, NULL);
SSL_CTX_set_info_callback(sslCtx.get(), info_callback);
SSL_CTX_set_client_cert_cb(sslCtx.get(), client_cert_cb);
SSL_CTX_set_tmp_rsa_callback(sslCtx.get(), tmp_rsa_callback);
SSL_CTX_set_tmp_dh_callback(sslCtx.get(), tmp_dh_callback);
SSL_CTX_set_tmp_ecdh_callback(sslCtx.get(), tmp_ecdh_callback);
JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx.get());
return (jlong) sslCtx.release();
}
/**
* public static native void SSL_CTX_free(long ssl_ctx)
*/
static void NativeCrypto_SSL_CTX_free(JNIEnv* env,
jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_free(ssl_ctx);
}
static void NativeCrypto_SSL_CTX_set_session_id_context(JNIEnv* env, jclass,
jlong ssl_ctx_address, jbyteArray sid_ctx)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context sid_ctx=%p", ssl_ctx, sid_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO buf(env, sid_ctx);
if (buf.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => threw exception", ssl_ctx);
return;
}
unsigned int length = buf.size();
if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"length > SSL_MAX_SSL_SESSION_ID_LENGTH");
JNI_TRACE("NativeCrypto_SSL_CTX_set_session_id_context => length = %d", length);
return;
}
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buf.get());
int result = SSL_CTX_set_session_id_context(ssl_ctx, bytes, length);
if (result == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_SSL_CTX_set_session_id_context");
return;
}
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => ok", ssl_ctx);
}
/**
* public static native int SSL_new(long ssl_ctx) throws SSLException;
*/
static jlong NativeCrypto_SSL_new(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new", ssl_ctx);
if (ssl_ctx == NULL) {
return 0;
}
Unique_SSL ssl(SSL_new(ssl_ctx));
if (ssl.get() == NULL) {
throwSSLExceptionWithSslErrors(env, NULL, SSL_ERROR_NONE,
"Unable to create SSL structure");
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
return 0;
}
/*
* Create our special application data.
*/
AppData* appData = AppData::create();
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to create application data");
freeOpenSslErrorState();
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new appData => 0", ssl_ctx);
return 0;
}
SSL_set_app_data(ssl.get(), reinterpret_cast<char*>(appData));
/*
* Java code in class OpenSSLSocketImpl does the verification. Since
* the callbacks do all the verification of the chain, this flag
* simply controls whether to send protocol-level alerts or not.
* SSL_VERIFY_NONE means don't send alerts and anything else means send
* alerts.
*/
SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => ssl=%p appData=%p", ssl_ctx, ssl.get(), appData);
return (jlong) ssl.release();
}
static void NativeCrypto_SSL_enable_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_enable_tls_channel_id", ssl);
if (ssl == NULL) {
return;
}
long ret = SSL_enable_tls_channel_id(ssl);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error enabling Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_tls_channel_id => error", ssl);
return;
}
}
static jbyteArray NativeCrypto_SSL_get_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id", ssl);
if (ssl == NULL) {
return NULL;
}
// Channel ID is 64 bytes long. Unfortunately, OpenSSL doesn't declare this length
// as a constant anywhere.
jbyteArray javaBytes = env->NewByteArray(64);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => NULL", ssl);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
// Unfortunately, the SSL_get_tls_channel_id method below always returns 64 (upon success)
// regardless of the number of bytes copied into the output buffer "tmp". Thus, the correctness
// of this code currently relies on the "tmp" buffer being exactly 64 bytes long.
long ret = SSL_get_tls_channel_id(ssl, tmp, 64);
if (ret == 0) {
// Channel ID either not set or did not verify
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => not available", ssl);
return NULL;
} else if (ret != 64) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error getting Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_tls_channel_id => error, returned %ld", ssl, ret);
return NULL;
}
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id() => %p", ssl, javaBytes);
return javaBytes;
}
static void NativeCrypto_SSL_set1_tls_channel_id(JNIEnv* env, jclass,
jlong ssl_address, jlong pkeyRef)
{
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => pkey == null", ssl);
return;
}
// SSL_set1_tls_channel_id requires ssl->server to be set to 0.
// Unfortunately, the default value is 1 and it's only changed to 0 just
// before the handshake starts (see NativeCrypto_SSL_do_handshake).
ssl->server = 0;
long ret = SSL_set1_tls_channel_id(ssl, pkey);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(
env, ssl, SSL_ERROR_NONE, "Error setting private key for Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => error", ssl);
return;
}
// SSL_set1_tls_channel_id expects to take ownership of the EVP_PKEY, but
// we have an external reference from the caller such as an OpenSSLKey,
// so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => ok", ssl);
}
static void NativeCrypto_SSL_use_PrivateKey(JNIEnv* env, jclass, jlong ssl_address, jlong pkeyRef) {
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("ssl=%p SSL_use_PrivateKey privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_use_PrivateKey => pkey == null", ssl);
return;
}
int ret = SSL_use_PrivateKey(ssl, pkey);
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting private key");
SSL_clear(ssl);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => error", ssl);
return;
}
// SSL_use_PrivateKey expects to take ownership of the EVP_PKEY,
// but we have an external reference from the caller such as an
// OpenSSLKey, so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => ok", ssl);
}
static void NativeCrypto_SSL_use_certificate(JNIEnv* env, jclass,
jlong ssl_address, jlongArray certificatesJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate certificates=%p", ssl, certificatesJava);
if (ssl == NULL) {
return;
}
if (certificatesJava == NULL) {
jniThrowNullPointerException(env, "certificates == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
size_t length = env->GetArrayLength(certificatesJava);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "certificates.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates.length == 0", ssl);
return;
}
ScopedLongArrayRO certificates(env, certificatesJava);
if (certificates.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
Unique_X509 serverCert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[0]))));
if (serverCert.get() == NULL) {
// Note this shouldn't happen since we checked the number of certificates above.
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !sk_X509_push(chain.get(), cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
int ret = SSL_use_certificate(ssl, serverCert.get());
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(serverCert);
int chainResult = SSL_use_certificate_chain(ssl, chain.get());
if (chainResult == 0) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate_chain error",
ssl);
return;
}
OWNERSHIP_TRANSFERRED(chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => ok", ssl);
}
static void NativeCrypto_SSL_check_private_key(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key", ssl);
if (ssl == NULL) {
return;
}
int ret = SSL_check_private_key(ssl);
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error checking private key");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => ok", ssl);
}
static void NativeCrypto_SSL_set_client_CA_list(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray principals)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list principals=%p", ssl, principals);
if (ssl == NULL) {
return;
}
if (principals == NULL) {
jniThrowNullPointerException(env, "principals == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals == null", ssl);
return;
}
int length = env->GetArrayLength(principals);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "principals.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals.length == 0", ssl);
return;
}
Unique_sk_X509_NAME principalsStack(sk_X509_NAME_new_null());
if (principalsStack.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate principal stack");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => stack allocation error", ssl);
return;
}
for (int i = 0; i < length; i++) {
ScopedLocalRef<jbyteArray> principal(env,
reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(principals, i)));
if (principal.get() == NULL) {
jniThrowNullPointerException(env, "principals element == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals element null", ssl);
return;
}
ScopedByteArrayRO buf(env, principal.get());
if (buf.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => threw exception", ssl);
return;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(buf.get());
Unique_X509_NAME principalX509Name(d2i_X509_NAME(NULL, &tmp, buf.size()));
if (principalX509Name.get() == NULL) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing principal");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals parsing error",
ssl);
return;
}
if (!sk_X509_NAME_push(principalsStack.get(), principalX509Name.release())) {
jniThrowOutOfMemory(env, "Unable to push principal");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principal push error", ssl);
return;
}
}
SSL_set_client_CA_list(ssl, principalsStack.release());
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => ok", ssl);
}
/**
* public static native long SSL_get_mode(long ssl);
*/
static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl);
if (ssl == NULL) {
return 0;
}
long mode = SSL_get_mode(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0x%lx", ssl, mode);
return mode;
}
/**
* public static native long SSL_set_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_get_options(long ssl);
*/
static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl);
if (ssl == NULL) {
return 0;
}
long options = SSL_get_options(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0x%lx", ssl, options);
return options;
}
/**
* public static native long SSL_set_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, options);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, options);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options => 0x%lx", ssl, result);
return result;
}
static jlongArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl);
STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl);
int count = (cipherStack != NULL) ? sk_SSL_CIPHER_num(cipherStack) : 0;
ScopedLocalRef<jlongArray> ciphersArray(env, env->NewLongArray(count));
ScopedLongArrayRW ciphers(env, ciphersArray.get());
for (int i = 0; i < count; i++) {
ciphers[i] = reinterpret_cast<jlong>(sk_SSL_CIPHER_value(cipherStack, i));
}
JNI_TRACE("NativeCrypto_SSL_get_ciphers(%p) => %p [size=%d]", ssl, ciphersArray.get(), count);
return ciphersArray.release();
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_mkey(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_mkey => %ld", cipher, cipher->algorithm_mkey);
return cipher->algorithm_mkey;
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_auth(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_auth => %ld", cipher, cipher->algorithm_auth);
return cipher->algorithm_auth;
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_cipher_lists(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray cipherSuites)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%p", ssl, cipherSuites);
if (ssl == NULL) {
return;
}
if (cipherSuites == NULL) {
jniThrowNullPointerException(env, "cipherSuites == null");
return;
}
Unique_sk_SSL_CIPHER cipherstack(sk_SSL_CIPHER_new_null());
if (cipherstack.get() == NULL) {
jniThrowRuntimeException(env, "sk_SSL_CIPHER_new_null failed");
return;
}
const SSL_METHOD* ssl_method = ssl->method;
int num_ciphers = ssl_method->num_ciphers();
int length = env->GetArrayLength(cipherSuites);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists length=%d", ssl, length);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
if (c.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuite=%s", ssl, c.c_str());
bool found = false;
for (int j = 0; j < num_ciphers; j++) {
const SSL_CIPHER* cipher = ssl_method->get_cipher(j);
if ((strcmp(c.c_str(), cipher->name) == 0)
&& (strcmp(SSL_CIPHER_get_version(cipher), "SSLv2"))) {
if (!sk_SSL_CIPHER_push(cipherstack.get(), cipher)) {
jniThrowOutOfMemory(env, "Unable to push cipher");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists => cipher push error", ssl);
return;
}
found = true;
}
}
if (!found) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Could not find cipher suite.");
return;
}
}
int rc = SSL_set_cipher_lists(ssl, cipherstack.get());
if (rc == 0) {
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Illegal cipher suite strings.");
} else {
OWNERSHIP_TRANSFERRED(cipherstack);
}
}
static void NativeCrypto_SSL_set_accept_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_accept_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_accept_state(ssl);
}
static void NativeCrypto_SSL_set_connect_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_connect_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_connect_state(ssl);
}
/**
* Sets certificate expectations, especially for server to request client auth
*/
static void NativeCrypto_SSL_set_verify(JNIEnv* env,
jclass, jlong ssl_address, jint mode)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify mode=%x", ssl, mode);
if (ssl == NULL) {
return;
}
SSL_set_verify(ssl, (int)mode, NULL);
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass,
jlong ssl_address, jlong ssl_session_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session);
if (ssl == NULL) {
return;
}
int ret = SSL_set_session(ssl, ssl_session);
if (ret != 1) {
/*
* Translate the error, and throw if it turns out to be a real
* problem.
*/
int sslErrorCode = SSL_get_error(ssl, ret);
if (sslErrorCode != SSL_ERROR_ZERO_RETURN) {
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "SSL session set");
SSL_clear(ssl);
}
}
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean creation_enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d",
ssl, creation_enabled);
if (ssl == NULL) {
return;
}
SSL_set_session_creation_enabled(ssl, creation_enabled);
}
static void NativeCrypto_SSL_set_tlsext_host_name(JNIEnv* env, jclass,
jlong ssl_address, jstring hostname)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostname=%p",
ssl, hostname);
if (ssl == NULL) {
return;
}
ScopedUtfChars hostnameChars(env, hostname);
if (hostnameChars.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostnameChars=%s",
ssl, hostnameChars.c_str());
int ret = SSL_set_tlsext_host_name(ssl, hostnameChars.c_str());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting host name");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => ok", ssl);
}
static jstring NativeCrypto_SSL_get_servername(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername", ssl);
if (ssl == NULL) {
return NULL;
}
const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername => %s", ssl, servername);
return env->NewStringUTF(servername);
}
/**
* A common selection path for both NPN and ALPN since they're essentially the
* same protocol. The list of protocols in "primary" is considered the order
* which should take precedence.
*/
static int proto_select(SSL* ssl __attribute__ ((unused)),
unsigned char **out, unsigned char *outLength,
const unsigned char *primary, const unsigned int primaryLength,
const unsigned char *secondary, const unsigned int secondaryLength) {
if (primary != NULL) {
JNI_TRACE("primary=%p, length=%d", primary, primaryLength);
int status = SSL_select_next_proto(out, outLength, primary, primaryLength, secondary,
secondaryLength);
switch (status) {
case OPENSSL_NPN_NEGOTIATED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN negotiated", ssl);
return SSL_TLSEXT_ERR_OK;
break;
case OPENSSL_NPN_UNSUPPORTED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN unsupported", ssl);
break;
case OPENSSL_NPN_NO_OVERLAP:
JNI_TRACE("ssl=%p proto_select NPN/ALPN no overlap", ssl);
break;
}
} else {
if (out != NULL && outLength != NULL) {
*out = NULL;
*outLength = 0;
}
JNI_TRACE("protocols=NULL");
}
return SSL_TLSEXT_ERR_NOACK;
}
/**
* Callback for the server to select an ALPN protocol.
*/
static int alpn_select_callback(SSL* ssl, const unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen, void *) {
JNI_TRACE("ssl=%p alpn_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
return proto_select(ssl, const_cast<unsigned char **>(out), outlen,
reinterpret_cast<unsigned char*>(appData->alpnProtocolsData),
appData->alpnProtocolsLength, in, inlen);
}
/**
* Callback for the client to select an NPN protocol.
*/
static int next_proto_select_callback(SSL* ssl, unsigned char** out, unsigned char* outlen,
const unsigned char* in, unsigned int inlen, void*)
{
JNI_TRACE("ssl=%p next_proto_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
// Enable False Start on the client if the server understands NPN
// http://www.imperialviolet.org/2012/04/11/falsestart.html
SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
return proto_select(ssl, out, outlen, in, inlen,
reinterpret_cast<unsigned char*>(appData->npnProtocolsData),
appData->npnProtocolsLength);
}
/**
* Callback for the server to advertise available protocols.
*/
static int next_protos_advertised_callback(SSL* ssl,
const unsigned char **out, unsigned int *outlen, void *)
{
JNI_TRACE("ssl=%p next_protos_advertised_callback", ssl);
AppData* appData = toAppData(ssl);
unsigned char* npnProtocols = reinterpret_cast<unsigned char*>(appData->npnProtocolsData);
if (npnProtocols != NULL) {
*out = npnProtocols;
*outlen = appData->npnProtocolsLength;
return SSL_TLSEXT_ERR_OK;
} else {
*out = NULL;
*outlen = 0;
return SSL_TLSEXT_ERR_NOACK;
}
}
static void NativeCrypto_SSL_CTX_enable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_callback, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_protos_advertised_callback, NULL); // server
}
static void NativeCrypto_SSL_CTX_disable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, NULL, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, NULL, NULL); // server
}
static jbyteArray NativeCrypto_SSL_get_npn_negotiated_protocol(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_npn_negotiated_protocol", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_next_proto_negotiated(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
static int NativeCrypto_SSL_set_alpn_protos(JNIEnv* env, jclass, jlong ssl_address,
jbyteArray protos) {
SSL* ssl = to_SSL(env, ssl_address, true);
if (ssl == NULL) {
return 0;
}
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p", ssl, protos);
if (protos == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=NULL", ssl);
return 1;
}
ScopedByteArrayRO protosBytes(env, protos);
if (protosBytes.get() == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => protosBytes == NULL", ssl,
protos);
return 0;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char*>(protosBytes.get());
int ret = SSL_set_alpn_protos(ssl, tmp, protosBytes.size());
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => ret=%d", ssl, protos, ret);
return ret;
}
static jbyteArray NativeCrypto_SSL_get0_alpn_selected(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p SSL_get0_alpn_selected", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_alpn_selected(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
#ifdef WITH_JNI_TRACE_KEYS
static inline char hex_char(unsigned char in)
{
if (in < 10) {
return '0' + in;
} else if (in <= 0xF0) {
return 'A' + in - 10;
} else {
return '?';
}
}
static void hex_string(char **dest, unsigned char* input, int len)
{
*dest = (char*) malloc(len * 2 + 1);
char *output = *dest;
for (int i = 0; i < len; i++) {
*output++ = hex_char(input[i] >> 4);
*output++ = hex_char(input[i] & 0xF);
}
*output = '\0';
}
static void debug_print_session_key(SSL_SESSION* session)
{
char *session_id_str;
char *master_key_str;
const char *key_type;
char *keyline;
hex_string(&session_id_str, session->session_id, session->session_id_length);
hex_string(&master_key_str, session->master_key, session->master_key_length);
X509* peer = SSL_SESSION_get0_peer(session);
EVP_PKEY* pkey = X509_PUBKEY_get(peer->cert_info->key);
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
key_type = "RSA";
break;
case EVP_PKEY_DSA:
key_type = "DSA";
break;
case EVP_PKEY_EC:
key_type = "EC";
break;
default:
key_type = "Unknown";
break;
}
asprintf(&keyline, "%s Session-ID:%s Master-Key:%s\n", key_type, session_id_str,
master_key_str);
JNI_TRACE("ssl_session=%p %s", session, keyline);
free(session_id_str);
free(master_key_str);
free(keyline);
}
#endif /* WITH_JNI_TRACE_KEYS */
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake_bio(JNIEnv* env, jclass, jlong ssl_address,
jlong rbioRef, jlong wbioRef, jobject shc, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
BIO* rbio = reinterpret_cast<BIO*>(rbioRef);
BIO* wbio = reinterpret_cast<BIO*>(wbioRef);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio rbio=%p wbio=%p shc=%p client_mode=%d npn=%p",
ssl, rbio, wbio, shc, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => rbio == null || wbio == NULL", ssl);
return 0;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (!client_mode && alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
int ret = 0;
errno = 0;
if (!appData->setCallbackState(env, shc, NULL, npnProtocols, alpnProtocols)) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio exception => 0", ssl);
return 0;
}
if (ret <= 0) { // error. See SSL_do_handshake(3SSL) man page.
// error case
int sslError = SSL_get_error(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio ret=%d errno=%d sslError=%d",
ssl, ret, errno, sslError);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we need to exit to allow
* the SSLEngine code to wrap or unwrap.
*/
if (sslError == SSL_ERROR_NONE || (sslError == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
SSL_clear(ssl);
freeOpenSslErrorState();
} else if (sslError != SSL_ERROR_WANT_READ && sslError != SSL_ERROR_WANT_WRITE) {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL handshake terminated",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio error => 0", ssl);
return 0;
}
// success. handshake completed
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return reinterpret_cast<uintptr_t>(ssl_session);
}
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jint timeout_millis, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd=%p shc=%p timeout_millis=%d client_mode=%d npn=%p",
ssl, fdObject, shc, timeout_millis, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd == null => 0", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
NetFd fd(env, fdObject);
if (fd.isClosed()) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd.isClosed() => 0", ssl);
return 0;
}
int ret = SSL_set_fd(ssl, fd.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd.get());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE,
"Error setting the file descriptor");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake SSL_set_fd => 0", ssl);
return 0;
}
/*
* Make socket non-blocking, so SSL_connect SSL_read() and SSL_write() don't hang
* forever and we can use select() to find out if the socket is ready.
*/
if (!setBlocking(fd.get(), false)) {
throwSSLExceptionStr(env, "Unable to make socket non blocking");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setBlocking => 0", ssl);
return 0;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (client_mode) {
SSL_set_connect_state(ssl);
} else {
SSL_set_accept_state(ssl);
if (alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
}
ret = 0;
while (appData->aliveAndKicking) {
errno = 0;
if (!appData->setCallbackState(env, shc, fdObject, npnProtocols, alpnProtocols)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake exception => 0", ssl);
return 0;
}
// success case
if (ret == 1) {
break;
}
// retry case
if (errno == EINTR) {
continue;
}
// error case
int sslError = SSL_get_error(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake ret=%d errno=%d sslError=%d timeout_millis=%d",
ssl, ret, errno, sslError, timeout_millis);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we use sslSelect to
* wait for it to become ready. If that doesn't happen
* before the specified timeout or an error occurs, we
* cancel the handshake. Otherwise we try the SSL_connect
* again.
*/
if (sslError == SSL_ERROR_WANT_READ || sslError == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
int selectResult = sslSelect(env, sslError, fdObject, appData, timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslSelect => 0", ssl);
return 0;
}
if (selectResult == -1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_SYSCALL, "handshake error",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == -1 => 0", ssl);
return 0;
}
if (selectResult == 0) {
throwSocketTimeoutException(env, "SSL handshake timed out");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == 0 => 0", ssl);
return 0;
}
} else {
// ALOGE("Unknown error %d during handshake", error);
break;
}
}
// clean error. See SSL_do_handshake(3SSL) man page.
if (ret == 0) {
/*
* The other side closed the socket before the handshake could be
* completed, but everything is within the bounds of the TLS protocol.
* We still might want to find out the real reason of the failure.
*/
int sslError = SSL_get_error(ssl, ret);
if (sslError == SSL_ERROR_NONE || (sslError == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
} else {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL handshake terminated",
throwSSLHandshakeExceptionStr);
}
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake clean error => 0", ssl);
return 0;
}
// unclean error. See SSL_do_handshake(3SSL) man page.
if (ret < 0) {
/*
* Translate the error and throw exception. We are sure it is an error
* at this point.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL handshake aborted",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake unclean error => 0", ssl);
return 0;
}
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return (jlong) ssl_session;
}
/**
* Perform SSL renegotiation
*/
static void NativeCrypto_SSL_renegotiate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate", ssl);
if (ssl == NULL) {
return;
}
int result = SSL_renegotiate(ssl);
if (result != 1) {
throwSSLExceptionStr(env, "Problem with SSL_renegotiate");
return;
}
// first call asks client to perform renegotiation
int ret = SSL_do_handshake(ssl);
if (ret != 1) {
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError,
"Problem with SSL_do_handshake after SSL_renegotiate");
return;
}
// if client agrees, set ssl state and perform renegotiation
ssl->state = SSL_ST_ACCEPT;
SSL_do_handshake(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate =>", ssl);
}
/**
* public static native byte[][] SSL_get_certificate(long ssl);
*/
static jlongArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl);
if (ssl == NULL) {
return NULL;
}
X509* certificate = SSL_get_certificate(ssl);
if (certificate == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
// SSL_get_certificate can return NULL during an error as well.
freeOpenSslErrorState();
return NULL;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => threw exception", ssl);
return NULL;
}
if (!sk_X509_push(chain.get(), X509_dup_nocopy(certificate))) {
jniThrowOutOfMemory(env, "Unable to push local certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
STACK_OF(X509)* cert_chain = SSL_get_certificate_chain(ssl, certificate);
for (int i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
jlongArray refArray = getCertificateRefs(env, chain.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => %p", ssl, refArray);
return refArray;
}
// Fills a long[] with the peer certificates in the chain.
static jlongArray NativeCrypto_SSL_get_peer_cert_chain(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain", ssl);
if (ssl == NULL) {
return NULL;
}
STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl);
Unique_sk_X509 chain_copy(NULL);
if (ssl->server) {
X509* x509 = SSL_get_peer_certificate(ssl);
if (x509 == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => NULL", ssl);
return NULL;
}
chain_copy.reset(sk_X509_new_null());
if (chain_copy.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate dup error", ssl);
return NULL;
}
size_t chain_size = sk_X509_num(chain);
for (size_t i = 0; i < chain_size; i++) {
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(sk_X509_value(chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate chain push error", ssl);
return NULL;
}
}
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(x509))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate push error", ssl);
return NULL;
}
chain = chain_copy.get();
}
jlongArray refArray = getCertificateRefs(env, chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => %p", ssl, refArray);
return refArray;
}
static int sslRead(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, char* buf, jint len,
int* sslReturnCode, int* sslErrorCode, int read_timeout_millis) {
JNI_TRACE("ssl=%p sslRead buf=%p len=%d", ssl, buf, len);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslRead appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
} else if (!SSL_is_init_finished(ssl) && !SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslRead => init is not finished", ssl);
return THROW_SSLEXCEPTION;
}
while (appData->aliveAndKicking) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
int result = SSL_read(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p sslRead => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p sslRead SSL_read result=%d sslError=%d", ssl, result, sslError);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslRead data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError == SSL_ERROR_WANT_READ || sslError == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
// Successfully read at least one byte.
case SSL_ERROR_NONE: {
return result;
}
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError, fdObject, appData, read_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
*sslReturnCode = -1;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
*sslReturnCode = result;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
}
}
return -1;
}
static jint NativeCrypto_SSL_read_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray destJava,
jlong sourceBioRef, jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sourceBioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO dest=%p sourceBio=%p sinkBio=%p shc=%p",
ssl, destJava, rbio, wbio, shc);
if (ssl == NULL) {
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => rbio == null || wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
ScopedByteArrayRW dest(env, destJava);
if (dest.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => appData == NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set callback state");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => set callback state failed", ssl);
return -1;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
int result = SSL_read(ssl, dest.get(), dest.size());
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return THROWN_EXCEPTION;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO SSL_read result=%d sslError=%d", ssl, result, sslError);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
// Successfully read at least one byte.
case SSL_ERROR_NONE:
break;
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
result = -1;
break;
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
result = 0;
break;
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
result = -1;
break;
} else if (errno == EINTR) {
// System call has been interrupted. Simply retry.
result = 0;
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "Read error");
return -1;
}
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => %d", ssl, result);
return result;
}
/**
* OpenSSL read function (2): read into buffer at offset n chunks.
* Returns 1 (success) or value <= 0 (failure).
*/
static jint NativeCrypto_SSL_read(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len,
jint read_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read fd=%p shc=%p b=%p offset=%d len=%d read_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, read_timeout_millis);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => fd == null", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => sslHandshakeCallbacks == null", ssl);
return 0;
}
ScopedByteArrayRW bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => threw exception", ssl);
return 0;
}
int returnCode = 0;
int sslErrorCode = SSL_ERROR_NONE;;
int ret = sslRead(env, ssl, fdObject, shc, reinterpret_cast<char*>(bytes.get() + offset), len,
&returnCode, &sslErrorCode, read_timeout_millis);
int result;
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslRead() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Read error");
result = -1;
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Read timed out");
result = -1;
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
// or RuntimeException thrown by callback
result = -1;
break;
default:
result = ret;
break;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => %d", ssl, result);
return result;
}
static int sslWrite(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, const char* buf, jint len,
int* sslReturnCode, int* sslErrorCode, int write_timeout_millis) {
JNI_TRACE("ssl=%p sslWrite buf=%p len=%d write_timeout_millis=%d",
ssl, buf, len, write_timeout_millis);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslWrite appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
} else if (!SSL_is_init_finished(ssl) && !SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslWrite => init is not finished", ssl);
return THROW_SSLEXCEPTION;
}
int count = len;
while (appData->aliveAndKicking && ((len > 0) || (ssl->s3->wbuf.left > 0))) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
JNI_TRACE("ssl=%p sslWrite SSL_write len=%d left=%d", ssl, len, ssl->s3->wbuf.left);
int result = SSL_write(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p sslWrite exception => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p sslWrite SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError, ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslWrite data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError == SSL_ERROR_WANT_READ || sslError == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
// Successfully wrote at least one byte.
case SSL_ERROR_NONE: {
buf += result;
len -= result;
break;
}
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
// The concept of a write timeout doesn't really make sense, and
// it's also not standard Java behavior, so we wait forever here.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError, fdObject, appData, write_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
*sslReturnCode = -1;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
*sslReturnCode = result;
*sslErrorCode = sslError;
return THROW_SSLEXCEPTION;
}
}
}
JNI_TRACE("ssl=%p sslWrite => count=%d", ssl, count);
return count;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static int NativeCrypto_SSL_write_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray sourceJava, jint len,
jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO source=%p len=%d wbio=%p shc=%p",
ssl, sourceJava, len, wbio, shc);
if (ssl == NULL) {
return -1;
}
if (wbio == NULL) {
jniThrowNullPointerException(env, "wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO appData => NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return 0;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set appdata callback");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => appData can't set callback", ssl);
return -1;
}
ScopedByteArrayRO source(env, sourceJava);
if (source.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => threw exception", ssl);
return -1;
}
Unique_BIO nullBio(BIO_new(BIO_s_null()));
ScopedSslBio sslBio(ssl, nullBio.get(), wbio);
int result = SSL_write(ssl, reinterpret_cast<const char*>(source.get()), len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO exception => exception pending (reneg)", ssl);
return -1;
}
int sslError = SSL_ERROR_NONE;
if (result <= 0) {
sslError = SSL_get_error(ssl, result);
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError, ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError) {
case SSL_ERROR_NONE:
return result;
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
return -1;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return 0;
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
return 0;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError, "Write error");
break;
}
}
return -1;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static void NativeCrypto_SSL_write(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len, jint write_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write fd=%p shc=%p b=%p offset=%d len=%d write_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, write_timeout_millis);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => sslHandshakeCallbacks == null", ssl);
return;
}
ScopedByteArrayRO bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => threw exception", ssl);
return;
}
int returnCode = 0;
int sslErrorCode = SSL_ERROR_NONE;
int ret = sslWrite(env, ssl, fdObject, shc, reinterpret_cast<const char*>(bytes.get() + offset),
len, &returnCode, &sslErrorCode, write_timeout_millis);
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslWrite() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Write error");
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Write timed out");
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
break;
default:
break;
}
}
/**
* Interrupt any pending I/O before closing the socket.
*/
static void NativeCrypto_SSL_interrupt(
JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_interrupt", ssl);
if (ssl == NULL) {
return;
}
/*
* Mark the connection as quasi-dead, then send something to the emergency
* file descriptor, so any blocking select() calls are woken up.
*/
AppData* appData = toAppData(ssl);
if (appData != NULL) {
appData->aliveAndKicking = 0;
// At most two threads can be waiting.
sslNotify(appData);
sslNotify(appData);
}
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown(JNIEnv* env, jclass, jlong ssl_address,
jobject fdObject, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown fd=%p shc=%p", ssl, fdObject, shc);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
freeOpenSslErrorState();
return;
}
/*
* Try to make socket blocking again. OpenSSL literature recommends this.
*/
int fd = SSL_get_fd(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown s=%d", ssl, fd);
if (fd != -1) {
setBlocking(fd, true);
}
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
SSL_clear(ssl);
freeOpenSslErrorState();
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown_BIO(JNIEnv* env, jclass, jlong ssl_address, jlong rbioRef,
jlong wbioRef, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(rbioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(wbioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown rbio=%p wbio=%p shc=%p", ssl, rbio, wbio, shc);
if (ssl == NULL) {
return;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => rbio == null || wbio == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
freeOpenSslErrorState();
return;
}
ScopedSslBio scopedBio(ssl, rbio, wbio);
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
SSL_clear(ssl);
freeOpenSslErrorState();
}
static jint NativeCrypto_SSL_get_shutdown(JNIEnv* env, jclass, jlong ssl_address) {
const SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown", ssl);
if (ssl == NULL) {
jniThrowNullPointerException(env, "ssl == null");
return 0;
}
int status = SSL_get_shutdown(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown => %d", ssl, status);
return static_cast<jint>(status);
}
/**
* public static native void SSL_free(long ssl);
*/
static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl);
if (ssl == NULL) {
return;
}
AppData* appData = toAppData(ssl);
SSL_set_app_data(ssl, NULL);
delete appData;
SSL_free(ssl);
}
/**
* Gets and returns in a byte array the ID of the actual SSL session.
*/
static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass,
jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
jbyteArray result = env->NewByteArray(ssl_session->session_id_length);
if (result != NULL) {
jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id);
env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src);
}
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d",
ssl_session, result, ssl_session->session_id_length);
return result;
}
/**
* Gets and returns in a long integer the creation's time of the
* actual SSL session.
*/
static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session);
if (ssl_session == NULL) {
return 0;
}
// result must be jlong, not long or *1000 will overflow
jlong result = SSL_SESSION_get_time(ssl_session);
result *= 1000; // OpenSSL uses seconds, Java uses milliseconds.
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, result);
return result;
}
/**
* Gets and returns in a string the version of the SSL protocol. If it
* returns the string "unknown" it means that no connection is established.
*/
static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const char* protocol = SSL_SESSION_get_version(ssl_session);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol);
return env->NewStringUTF(protocol);
}
/**
* Gets and returns in a string the cipher negotiated for the SSL session.
*/
static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const SSL_CIPHER* cipher = ssl_session->cipher;
const char* name = SSL_CIPHER_get_name(cipher);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name);
return env->NewStringUTF(name);
}
/**
* Frees the SSL session.
*/
static void NativeCrypto_SSL_SESSION_free(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session);
if (ssl_session == NULL) {
return;
}
SSL_SESSION_free(ssl_session);
}
/**
* Serializes the native state of the session (ID, cipher, and keys but
* not certificates). Returns a byte[] containing the DER-encoded state.
* See apache mod_ssl.
*/
static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
return ASN1ToByteArray<SSL_SESSION, i2d_SSL_SESSION>(env, ssl_session);
}
/**
* Deserialize the session.
*/
static jlong NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => threw exception");
return 0;
}
const unsigned char* ucp = reinterpret_cast<const unsigned char*>(bytes.get());
SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, bytes.size());
// Initialize SSL_SESSION cipher field based on cipher_id http://b/7091840
if (ssl_session != NULL) {
// based on ssl_get_prev_session
uint32_t cipher_id_network_order = htonl(ssl_session->cipher_id);
uint8_t* cipher_id_byte_pointer = reinterpret_cast<uint8_t*>(&cipher_id_network_order);
if (ssl_session->ssl_version >= SSL3_VERSION_MAJOR) {
cipher_id_byte_pointer += 2; // skip first two bytes for SSL3+
} else {
cipher_id_byte_pointer += 1; // skip first byte for SSL2
}
ssl_session->cipher = SSLv23_method()->get_cipher_by_char(cipher_id_byte_pointer);
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION cipher_id=%lx hton=%x 0=%x 1=%x cipher=%s",
ssl_session->cipher_id, cipher_id_network_order,
cipher_id_byte_pointer[0], cipher_id_byte_pointer[1],
SSL_CIPHER_get_name(ssl_session->cipher));
} else {
freeOpenSslErrorState();
}
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session);
return reinterpret_cast<uintptr_t>(ssl_session);
}
static jlong NativeCrypto_ERR_peek_last_error(JNIEnv*, jclass) {
return ERR_peek_last_error();
}
#define FILE_DESCRIPTOR "Ljava/io/FileDescriptor;"
#define SSL_CALLBACKS "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto$SSLHandshakeCallbacks;"
static JNINativeMethod sNativeCryptoMethods[] = {
NATIVE_METHOD(NativeCrypto, clinit, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_dynamic, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_by_id, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_add, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_init, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_finish, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_free, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_private_key, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_get_id, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, ENGINE_ctrl_cmd_string, "(JLjava/lang/String;Ljava/lang/String;I)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DH, "([B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DSA, "([B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_RSA, "([B[B[B[B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_EC_KEY, "(JJ[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_mac_key, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_type, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_public, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_private, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS8_PRIV_KEY_INFO, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS8_PRIV_KEY_INFO, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_PUBKEY, "([B)J"),
NATIVE_METHOD(NativeCrypto, RSA_generate_key_ex, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, RSA_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_encrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_decrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_encrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_decrypt, "(I[B[BJI)I"),
NATIVE_METHOD(NativeCrypto, get_RSA_private_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, get_RSA_public_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, DSA_generate_key, "(I[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, get_DSA_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, set_DSA_flag_nonce_from_hash, "(J)V"),
NATIVE_METHOD(NativeCrypto, DH_generate_key, "(II)J"),
NATIVE_METHOD(NativeCrypto, get_DH_params, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_by_curve_name, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_curve, "(I[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_asn1_flag, "(JI)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_point_conversion_form, "(JI)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve_name, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve, "(J)[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_order, "(J)[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_degree, "(J)I"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_cofactor, "(J)[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_cmp, "(JJ)Z"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_generator, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_generator, "(JJ[B[B)V"),
NATIVE_METHOD(NativeCrypto, get_EC_GROUP_type, "(J)I"),
NATIVE_METHOD(NativeCrypto, EC_POINT_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_POINT_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_cmp, "(JJJ)Z"),
NATIVE_METHOD(NativeCrypto, EC_POINT_set_affine_coordinates, "(JJ[B[B)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_get_affine_coordinates, "(JJ)[[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_generate_key, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get0_group, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_private_key, "(J)[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_public_key, "(J)J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_set_nonce_from_hash, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, ECDH_compute_key, "([BIJJ)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_create, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_init, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_destroy, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_copy, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_get_digestbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_SignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BIJ)I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[BIIJ)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;JJ)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;[B)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLDigestContext;)[B"),
NATIVE_METHOD(NativeCrypto, EVP_get_cipherbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_CipherInit_ex, "(JJ[B[BZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CipherUpdate, "(J[BI[BII)I"),
NATIVE_METHOD(NativeCrypto, EVP_CipherFinal_ex, "(J[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_iv_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_buf_len, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_padding, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_key_length, "(JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_cleanup, "(J)V"),
NATIVE_METHOD(NativeCrypto, RAND_seed, "([B)V"),
NATIVE_METHOD(NativeCrypto, RAND_load_file, "(Ljava/lang/String;J)I"),
NATIVE_METHOD(NativeCrypto, RAND_bytes, "([B)V"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid, "(Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_longName, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_oid, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, create_BIO_InputStream, ("(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream;)J")),
NATIVE_METHOD(NativeCrypto, create_BIO_OutputStream, "(Ljava/io/OutputStream;)J"),
NATIVE_METHOD(NativeCrypto, BIO_read, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, BIO_write, "(J[BII)V"),
NATIVE_METHOD(NativeCrypto, BIO_free_all, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_NAME_print_ex, "(JJ)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, d2i_X509_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, d2i_X509, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509, "(J)[B"),
NATIVE_METHOD(NativeCrypto, i2d_X509_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PKCS7, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS7_bio, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS7, "([J)[B"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_unpack_X509_bio, "(J)[J"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_pack_X509, "([J)[B"),
NATIVE_METHOD(NativeCrypto, X509_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, get_X509_hashCode, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_print_ex, "(JJJJ)V"),
NATIVE_METHOD(NativeCrypto, X509_get_pubkey, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_get_subject_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_pubkey_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_issuerUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_subjectUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_kusage, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_xkusage, "(J)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_pathlen, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_crl_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_verify, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_lastUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_nextUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_revocationDate, "(J)J"),
NATIVE_METHOD(NativeCrypto, get_X509_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_GENERAL_NAME_stack, "(JI)[[Ljava/lang/Object;"),
NATIVE_METHOD(NativeCrypto, X509_get_notBefore, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_notAfter, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_verify, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_cert_info_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_flags, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_check_issued, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, d2i_X509_CRL_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509_CRL, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_cert, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_serial, "(J[B)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_REVOKED, "(J)[J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_CRL, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_REVOKED, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_supported_extension, "(J)I"),
NATIVE_METHOD(NativeCrypto, ASN1_TIME_to_Calendar, "(JLjava/util/Calendar;)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_session_id_context, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_tls_channel_id, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_tls_channel_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set1_tls_channel_id, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_use_PrivateKey, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_use_certificate, "(J[J)V"),
NATIVE_METHOD(NativeCrypto, SSL_check_private_key, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_client_CA_list, "(J[[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_mode, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_get_options, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_cipher_lists, "(J[Ljava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ciphers, "(J)[J"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_auth, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_mkey, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_set_accept_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_connect_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_verify, "(JI)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session_creation_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_tlsext_host_name, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_servername, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "IZ[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake_bio, "(JJJ" SSL_CALLBACKS "Z[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_renegotiate, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_certificate, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_get_peer_cert_chain, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_read, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)I"),
NATIVE_METHOD(NativeCrypto, SSL_read_BIO, "(J[BJJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_write, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)V"),
NATIVE_METHOD(NativeCrypto, SSL_write_BIO, "(J[BIJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_interrupt, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown, "(J" FILE_DESCRIPTOR SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown_BIO, "(JJJ" SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_get_shutdown, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_session_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_time, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_version, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_cipher, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, i2d_SSL_SESSION, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_SSL_SESSION, "([B)J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_enable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_disable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_npn_negotiated_protocol, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set_alpn_protos, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, SSL_get0_alpn_selected, "(J)[B"),
NATIVE_METHOD(NativeCrypto, ERR_peek_last_error, "()J"),
};
static jclass getGlobalRefToClass(JNIEnv* env, const char* className) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(className));
jclass globalRef = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (globalRef == NULL) {
ALOGE("failed to find class %s", className);
abort();
}
return globalRef;
}
static void initialize_conscrypt(JNIEnv* env) {
jniRegisterNativeMethods(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto",
sNativeCryptoMethods, NELEM(sNativeCryptoMethods));
openSslNativeReferenceClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLNativeReference");
openSslOutputStreamClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream");
openSslNativeReference_context = env->GetFieldID(openSslNativeReferenceClass, "context", "J");
calendar_setMethod = env->GetMethodID(calendarClass, "set", "(IIIIII)V");
inputStream_readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
integer_valueOfMethod = env->GetStaticMethodID(integerClass, "valueOf",
"(I)Ljava/lang/Integer;");
openSslInputStream_readLineMethod = env->GetMethodID(openSslOutputStreamClass, "gets",
"([B)I");
outputStream_writeMethod = env->GetMethodID(outputStreamClass, "write", "([B)V");
outputStream_flushMethod = env->GetMethodID(outputStreamClass, "flush", "()V");
}
static jclass findClass(JNIEnv* env, const char* name) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(name));
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (result == NULL) {
ALOGE("failed to find class '%s'", name);
abort();
}
return result;
}
// Use JNI_OnLoad for when we're standalone
int JNI_OnLoad(JavaVM *vm, void*) {
JNI_TRACE("JNI_OnLoad NativeCrypto");
gJavaVM = vm;
JNIEnv *env;
if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
ALOGE("Could not get JNIEnv");
return JNI_ERR;
}
byteArrayClass = findClass(env, "[B");
calendarClass = findClass(env, "java/util/Calendar");
inputStreamClass = findClass(env, "java/io/InputStream");
integerClass = findClass(env, "java/lang/Integer");
objectClass = findClass(env, "java/lang/Object");
objectArrayClass = findClass(env, "[Ljava/lang/Object;");
outputStreamClass = findClass(env, "java/io/OutputStream");
stringClass = findClass(env, "java/lang/String");
initialize_conscrypt(env);
return JNI_VERSION_1_6;
}
|
/*VRP*********************************************************************
*
* vehicle routing problems
* A collection of C++ classes for developing VRP solutions
* and specific solutions developed using these classes.
*
* Copyright 2014 Stephen Woodbridge <woodbri@imaptools.com>
* Copyright 2014 Vicky Vergara <vicky_vergara@hotmail.com>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the MIT License. Please file LICENSE for details.
*
********************************************************************VRP*/
#include <stdexcept>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdio.h>
#ifdef DOVRPLOG
#include "logger.h"
#endif
#ifdef DOSTATS
#include "timer.h"
#include "stats.h"
#endif
#include "trashconfig.h"
#include "truckManyVisitsDump.h"
#include "tabuopt.h"
void Usage()
{
std::cout << "Usage: trash file (no extension)\n";
}
/* Logging Severity Levels
0 INFO
1 WARNING
2 ERROR
3 FATAL NOTE FATAL is converted to ERROR when NDEBUG is defined
DLOG(<level>) << "message";
DLOG_IF(<level>, <cond>) << "message";
DLOG_EVERY_N(<level>, <n>) << "message";
CHECK(<cond>) << "message"; // print "message" and FATAL if false
http://google-glog.googlecode.com/svn/trunk/doc/glog.html
GLOG_logtostderr=1 ./bin/trash ... // to get output to terminal
*/
int main(int argc, char **argv)
{
#ifdef DOVRPLOG
if ( not google::IsGoogleLoggingInitialized() ) {
FLAGS_log_dir = "./logs/";
google::InitGoogleLogging( "vrp_trash_collection" );
FLAGS_logtostderr = 0;
FLAGS_stderrthreshold = google::FATAL;
FLAGS_minloglevel = google::INFO;
}
#endif
if (argc < 2) {
Usage();
return 1;
}
std::string infile = argv[1];
try {
#ifdef DOSTATS
Timer starttime;
#endif
#ifdef VRPMINTRACE
//CONFIG->dump("CONFIG");
#endif
#ifdef OSRMCLIENT
osrmi->useOsrm(true);
bool testResult = osrmi->testOsrmClient(
-34.905113, -56.157043,
-34.906807, -56.158463,
-34.9076, -56.157028);
// remove the following comment when testing OSRM only
// assert(true==false);
#ifdef VRPMINTRACE
if (testResult)
DLOG(INFO) << "osrm test passed";
else
DLOG(INFO) << "osrm test FAIL";
#endif // VRPMINTRACE
#endif // OSRMCLIENT
int iteration = 3;
double best_cost = 9999999;
TruckManyVisitsDump tp(infile);
tp.process(0);
DLOG(INFO) << "Initial solution: 0 is best";
Solution best_sol(tp);
best_cost = best_sol.getCostOsrm();
TabuOpt tsi(tp, iteration);
Solution opt_sol = tsi.getBestSolution();
if (best_cost < opt_sol.getCostOsrm()) {
DLOG(INFO) << "Optimization: 0 is best";
best_cost = opt_sol.getCost();
best_sol = opt_sol;
}
for (int icase = 1; icase < 2; ++icase) {
DLOG(INFO) << "initial solution: " << icase;
tp.process(icase);
if (best_cost < tp.getCostOsrm()) {
DLOG(INFO) << "initial solution: " << icase << " is best";
best_cost = tp.getCost();
best_sol = tp;
}
TabuOpt ts(tp, iteration);
DLOG(INFO) << "optimization: " << icase;
if (best_cost < ts.getBestSolution().getCostOsrm()) {
DLOG(INFO) << "Optimization: " << icase << " is best";
best_cost = ts.getBestSolution().getCost();
best_sol = ts.getBestSolution();
}
assert(true==false);
}
#ifdef VRPMINTRACE
best_sol.dumpCostValues();
best_sol.tau();
#endif
best_sol.dumpSolutionForPg();
twc->cleanUp();
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
fixed condition
/*VRP*********************************************************************
*
* vehicle routing problems
* A collection of C++ classes for developing VRP solutions
* and specific solutions developed using these classes.
*
* Copyright 2014 Stephen Woodbridge <woodbri@imaptools.com>
* Copyright 2014 Vicky Vergara <vicky_vergara@hotmail.com>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the MIT License. Please file LICENSE for details.
*
********************************************************************VRP*/
#include <stdexcept>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdio.h>
#ifdef DOVRPLOG
#include "logger.h"
#endif
#ifdef DOSTATS
#include "timer.h"
#include "stats.h"
#endif
#include "trashconfig.h"
#include "truckManyVisitsDump.h"
#include "tabuopt.h"
void Usage()
{
std::cout << "Usage: trash file (no extension)\n";
}
/* Logging Severity Levels
0 INFO
1 WARNING
2 ERROR
3 FATAL NOTE FATAL is converted to ERROR when NDEBUG is defined
DLOG(<level>) << "message";
DLOG_IF(<level>, <cond>) << "message";
DLOG_EVERY_N(<level>, <n>) << "message";
CHECK(<cond>) << "message"; // print "message" and FATAL if false
http://google-glog.googlecode.com/svn/trunk/doc/glog.html
GLOG_logtostderr=1 ./bin/trash ... // to get output to terminal
*/
int main(int argc, char **argv)
{
#ifdef DOVRPLOG
if ( not google::IsGoogleLoggingInitialized() ) {
FLAGS_log_dir = "./logs/";
google::InitGoogleLogging( "vrp_trash_collection" );
FLAGS_logtostderr = 0;
FLAGS_stderrthreshold = google::FATAL;
FLAGS_minloglevel = google::INFO;
}
#endif
if (argc < 2) {
Usage();
return 1;
}
std::string infile = argv[1];
try {
#ifdef DOSTATS
Timer starttime;
#endif
#ifdef VRPMINTRACE
//CONFIG->dump("CONFIG");
#endif
#ifdef OSRMCLIENT
osrmi->useOsrm(true);
bool testResult = osrmi->testOsrmClient(
-34.905113, -56.157043,
-34.906807, -56.158463,
-34.9076, -56.157028);
// remove the following comment when testing OSRM only
// assert(true==false);
#ifdef VRPMINTRACE
if (testResult)
DLOG(INFO) << "osrm test passed";
else
DLOG(INFO) << "osrm test FAIL";
#endif // VRPMINTRACE
#endif // OSRMCLIENT
int iteration = 3;
double best_cost = 9999999;
TruckManyVisitsDump tp(infile);
tp.process(0);
DLOG(INFO) << "Initial solution: 0 is best";
Solution best_sol(tp);
best_cost = best_sol.getCostOsrm();
TabuOpt tsi(tp, iteration);
Solution opt_sol = tsi.getBestSolution();
if (best_cost > opt_sol.getCostOsrm()) {
DLOG(INFO) << "Optimization: 0 is best";
best_cost = opt_sol.getCost();
best_sol = opt_sol;
}
for (int icase = 1; icase < 2; ++icase) {
DLOG(INFO) << "initial solution: " << icase;
tp.process(icase);
if (best_cost < tp.getCostOsrm()) {
DLOG(INFO) << "initial solution: " << icase << " is best";
best_cost = tp.getCost();
best_sol = tp;
}
TabuOpt ts(tp, iteration);
DLOG(INFO) << "optimization: " << icase;
if (best_cost > ts.getBestSolution().getCostOsrm()) {
DLOG(INFO) << "Optimization: " << icase << " is best";
best_cost = ts.getBestSolution().getCost();
best_sol = ts.getBestSolution();
}
assert(true==false);
}
#ifdef VRPMINTRACE
best_sol.dumpCostValues();
best_sol.tau();
#endif
best_sol.dumpSolutionForPg();
twc->cleanUp();
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
|
/*
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Native glue for Java class org.conscrypt.NativeCrypto
*/
#define TO_STRING1(x) #x
#define TO_STRING(x) TO_STRING1(x)
#ifndef JNI_JARJAR_PREFIX
#ifndef CONSCRYPT_NOT_UNBUNDLED
#define CONSCRYPT_UNBUNDLED
#endif
#define JNI_JARJAR_PREFIX
#endif
#define LOG_TAG "NativeCrypto"
#include <arpa/inet.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef CONSCRYPT_UNBUNDLED
#include <dlfcn.h>
#endif
#include <jni.h>
#include <openssl/asn1t.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#if !defined(OPENSSL_IS_BORINGSSL)
#include "crypto/ecdsa/ecs_locl.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
/* If we're compiled unbundled from Android system image, we use the
* CompatibilityCloseMonitor
*/
#include "AsynchronousCloseMonitor.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "cutils/log.h"
#else
#include <android/log.h>
#include "log_compat.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
#else
#define NATIVE_METHOD(className, functionName, signature) \
{ #functionName, signature, reinterpret_cast<void*>(className ## _ ## functionName) }
#define REGISTER_NATIVE_METHODS(jni_class_name) \
RegisterNativeMethods(env, jni_class_name, gMethods, arraysize(gMethods))
#endif
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#include "NetFd.h"
#undef WITH_JNI_TRACE
#undef WITH_JNI_TRACE_MD
#undef WITH_JNI_TRACE_DATA
/*
* How to use this for debugging with Wireshark:
*
* 1. Pull lines from logcat to a file that looks like (without quotes):
* "RSA Session-ID:... Master-Key:..." <CR>
* "RSA Session-ID:... Master-Key:..." <CR>
* <etc>
* 2. Start Wireshark
* 3. Go to Edit -> Preferences -> SSL -> (Pre-)Master-Key log and fill in
* the file you put the lines in above.
* 4. Follow the stream that corresponds to the desired "Session-ID" in
* the Server Hello.
*/
#undef WITH_JNI_TRACE_KEYS
#ifdef WITH_JNI_TRACE
#define JNI_TRACE(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__))
#else
#define JNI_TRACE(...) ((void)0)
#endif
#ifdef WITH_JNI_TRACE_MD
#define JNI_TRACE_MD(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__));
#else
#define JNI_TRACE_MD(...) ((void)0)
#endif
// don't overwhelm logcat
#define WITH_JNI_TRACE_DATA_CHUNK_SIZE 512
static JavaVM* gJavaVM;
static jclass cryptoUpcallsClass;
static jclass openSslInputStreamClass;
static jclass nativeRefClass;
static jclass byteArrayClass;
static jclass calendarClass;
static jclass objectClass;
static jclass objectArrayClass;
static jclass integerClass;
static jclass inputStreamClass;
static jclass outputStreamClass;
static jclass stringClass;
static jfieldID nativeRef_context;
static jmethodID calendar_setMethod;
static jmethodID inputStream_readMethod;
static jmethodID integer_valueOfMethod;
static jmethodID openSslInputStream_readLineMethod;
static jmethodID outputStream_writeMethod;
static jmethodID outputStream_flushMethod;
struct OPENSSL_Delete {
void operator()(void* p) const {
OPENSSL_free(p);
}
};
typedef UniquePtr<unsigned char, OPENSSL_Delete> Unique_OPENSSL_str;
struct BIO_Delete {
void operator()(BIO* p) const {
BIO_free_all(p);
}
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
struct BIGNUM_Delete {
void operator()(BIGNUM* p) const {
BN_free(p);
}
};
typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
struct ASN1_INTEGER_Delete {
void operator()(ASN1_INTEGER* p) const {
ASN1_INTEGER_free(p);
}
};
typedef UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> Unique_ASN1_INTEGER;
struct DH_Delete {
void operator()(DH* p) const {
DH_free(p);
}
};
typedef UniquePtr<DH, DH_Delete> Unique_DH;
struct DSA_Delete {
void operator()(DSA* p) const {
DSA_free(p);
}
};
typedef UniquePtr<DSA, DSA_Delete> Unique_DSA;
struct EC_GROUP_Delete {
void operator()(EC_GROUP* p) const {
EC_GROUP_free(p);
}
};
typedef UniquePtr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP;
struct EC_POINT_Delete {
void operator()(EC_POINT* p) const {
EC_POINT_clear_free(p);
}
};
typedef UniquePtr<EC_POINT, EC_POINT_Delete> Unique_EC_POINT;
struct EC_KEY_Delete {
void operator()(EC_KEY* p) const {
EC_KEY_free(p);
}
};
typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
struct EVP_MD_CTX_Delete {
void operator()(EVP_MD_CTX* p) const {
EVP_MD_CTX_destroy(p);
}
};
typedef UniquePtr<EVP_MD_CTX, EVP_MD_CTX_Delete> Unique_EVP_MD_CTX;
struct EVP_CIPHER_CTX_Delete {
void operator()(EVP_CIPHER_CTX* p) const {
EVP_CIPHER_CTX_free(p);
}
};
typedef UniquePtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_Delete> Unique_EVP_CIPHER_CTX;
struct EVP_PKEY_Delete {
void operator()(EVP_PKEY* p) const {
EVP_PKEY_free(p);
}
};
typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
struct PKCS8_PRIV_KEY_INFO_Delete {
void operator()(PKCS8_PRIV_KEY_INFO* p) const {
PKCS8_PRIV_KEY_INFO_free(p);
}
};
typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
struct RSA_Delete {
void operator()(RSA* p) const {
RSA_free(p);
}
};
typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
struct ASN1_BIT_STRING_Delete {
void operator()(ASN1_BIT_STRING* p) const {
ASN1_BIT_STRING_free(p);
}
};
typedef UniquePtr<ASN1_BIT_STRING, ASN1_BIT_STRING_Delete> Unique_ASN1_BIT_STRING;
struct ASN1_OBJECT_Delete {
void operator()(ASN1_OBJECT* p) const {
ASN1_OBJECT_free(p);
}
};
typedef UniquePtr<ASN1_OBJECT, ASN1_OBJECT_Delete> Unique_ASN1_OBJECT;
struct ASN1_GENERALIZEDTIME_Delete {
void operator()(ASN1_GENERALIZEDTIME* p) const {
ASN1_GENERALIZEDTIME_free(p);
}
};
typedef UniquePtr<ASN1_GENERALIZEDTIME, ASN1_GENERALIZEDTIME_Delete> Unique_ASN1_GENERALIZEDTIME;
struct SSL_Delete {
void operator()(SSL* p) const {
SSL_free(p);
}
};
typedef UniquePtr<SSL, SSL_Delete> Unique_SSL;
struct SSL_CTX_Delete {
void operator()(SSL_CTX* p) const {
SSL_CTX_free(p);
}
};
typedef UniquePtr<SSL_CTX, SSL_CTX_Delete> Unique_SSL_CTX;
struct X509_Delete {
void operator()(X509* p) const {
X509_free(p);
}
};
typedef UniquePtr<X509, X509_Delete> Unique_X509;
struct X509_NAME_Delete {
void operator()(X509_NAME* p) const {
X509_NAME_free(p);
}
};
typedef UniquePtr<X509_NAME, X509_NAME_Delete> Unique_X509_NAME;
#if !defined(OPENSSL_IS_BORINGSSL)
struct PKCS7_Delete {
void operator()(PKCS7* p) const {
PKCS7_free(p);
}
};
typedef UniquePtr<PKCS7, PKCS7_Delete> Unique_PKCS7;
#endif
struct sk_SSL_CIPHER_Delete {
void operator()(STACK_OF(SSL_CIPHER)* p) const {
// We don't own SSL_CIPHER references, so no need for pop_free
sk_SSL_CIPHER_free(p);
}
};
typedef UniquePtr<STACK_OF(SSL_CIPHER), sk_SSL_CIPHER_Delete> Unique_sk_SSL_CIPHER;
struct sk_X509_Delete {
void operator()(STACK_OF(X509)* p) const {
sk_X509_pop_free(p, X509_free);
}
};
typedef UniquePtr<STACK_OF(X509), sk_X509_Delete> Unique_sk_X509;
struct sk_X509_NAME_Delete {
void operator()(STACK_OF(X509_NAME)* p) const {
sk_X509_NAME_pop_free(p, X509_NAME_free);
}
};
typedef UniquePtr<STACK_OF(X509_NAME), sk_X509_NAME_Delete> Unique_sk_X509_NAME;
struct sk_ASN1_OBJECT_Delete {
void operator()(STACK_OF(ASN1_OBJECT)* p) const {
sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
}
};
typedef UniquePtr<STACK_OF(ASN1_OBJECT), sk_ASN1_OBJECT_Delete> Unique_sk_ASN1_OBJECT;
struct sk_GENERAL_NAME_Delete {
void operator()(STACK_OF(GENERAL_NAME)* p) const {
sk_GENERAL_NAME_pop_free(p, GENERAL_NAME_free);
}
};
typedef UniquePtr<STACK_OF(GENERAL_NAME), sk_GENERAL_NAME_Delete> Unique_sk_GENERAL_NAME;
/**
* Many OpenSSL APIs take ownership of an argument on success but don't free the argument
* on failure. This means we need to tell our scoped pointers when we've transferred ownership,
* without triggering a warning by not using the result of release().
*/
#define OWNERSHIP_TRANSFERRED(obj) \
do { typeof (obj.release()) _dummy __attribute__((unused)) = obj.release(); } while(0)
/**
* Frees the SSL error state.
*
* OpenSSL keeps an "error stack" per thread, and given that this code
* can be called from arbitrary threads that we don't keep track of,
* we err on the side of freeing the error state promptly (instead of,
* say, at thread death).
*/
static void freeOpenSslErrorState(void) {
ERR_clear_error();
ERR_remove_thread_state(NULL);
}
/**
* Manages the freeing of the OpenSSL error stack. This allows you to
* instantiate this object during an SSL call that may fail and not worry
* about manually calling freeOpenSslErrorState() later.
*
* As an optimization, you can also call .release() for passing as an
* argument to things that free the error stack state as a side-effect.
*/
class OpenSslError {
public:
OpenSslError() : sslError_(SSL_ERROR_NONE), released_(false) {
}
OpenSslError(SSL* ssl, int returnCode) : sslError_(SSL_ERROR_NONE), released_(false) {
reset(ssl, returnCode);
}
~OpenSslError() {
if (!released_ && sslError_ != SSL_ERROR_NONE) {
freeOpenSslErrorState();
}
}
int get() const {
return sslError_;
}
void reset(SSL* ssl, int returnCode) {
if (returnCode <= 0) {
sslError_ = SSL_get_error(ssl, returnCode);
} else {
sslError_ = SSL_ERROR_NONE;
}
}
int release() {
released_ = true;
return sslError_;
}
private:
int sslError_;
bool released_;
};
/**
* Throws a OutOfMemoryError with the given string as a message.
*/
static void jniThrowOutOfMemory(JNIEnv* env, const char* message) {
jniThrowException(env, "java/lang/OutOfMemoryError", message);
}
/**
* Throws a BadPaddingException with the given string as a message.
*/
static void throwBadPaddingException(JNIEnv* env, const char* message) {
JNI_TRACE("throwBadPaddingException %s", message);
jniThrowException(env, "javax/crypto/BadPaddingException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwSignatureException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSignatureException %s", message);
jniThrowException(env, "java/security/SignatureException", message);
}
/**
* Throws a InvalidKeyException with the given string as a message.
*/
static void throwInvalidKeyException(JNIEnv* env, const char* message) {
JNI_TRACE("throwInvalidKeyException %s", message);
jniThrowException(env, "java/security/InvalidKeyException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwIllegalBlockSizeException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalBlockSizeException %s", message);
jniThrowException(env, "javax/crypto/IllegalBlockSizeException", message);
}
/**
* Throws a NoSuchAlgorithmException with the given string as a message.
*/
static void throwNoSuchAlgorithmException(JNIEnv* env, const char* message) {
JNI_TRACE("throwUnknownAlgorithmException %s", message);
jniThrowException(env, "java/security/NoSuchAlgorithmException", message);
}
static void throwForAsn1Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case ASN1_R_UNABLE_TO_DECODE_RSA_KEY:
case ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY:
case ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE:
case ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE:
// These #if sections can be removed once BoringSSL is landed.
#if defined(ASN1_R_WRONG_PUBLIC_KEY_TYPE)
case ASN1_R_WRONG_PUBLIC_KEY_TYPE:
throwInvalidKeyException(env, message);
break;
#endif
#if defined(ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
#endif
default:
jniThrowRuntimeException(env, message);
break;
}
}
#if defined(OPENSSL_IS_BORINGSSL)
static void throwForCipherError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case CIPHER_R_BAD_DECRYPT:
throwBadPaddingException(env, message);
break;
case CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case CIPHER_R_WRONG_FINAL_BLOCK_LENGTH:
throwIllegalBlockSizeException(env, message);
break;
case CIPHER_R_AES_KEY_SETUP_FAILED:
case CIPHER_R_BAD_KEY_LENGTH:
case CIPHER_R_UNSUPPORTED_KEY_SIZE:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForEvpError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case EVP_R_MISSING_PARAMETERS:
throwInvalidKeyException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
case EVP_R_X931_UNSUPPORTED:
throwNoSuchAlgorithmException(env, message);
break;
// These #if sections can be make unconditional once BoringSSL is landed.
#if defined(EVP_R_WRONG_PUBLIC_KEY_TYPE)
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
throwInvalidKeyException(env, message);
break;
#endif
#if defined(EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
#endif
default:
jniThrowRuntimeException(env, message);
break;
}
}
#else
static void throwForEvpError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case EVP_R_BAD_DECRYPT:
throwBadPaddingException(env, message);
break;
case EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case EVP_R_WRONG_FINAL_BLOCK_LENGTH:
throwIllegalBlockSizeException(env, message);
break;
case EVP_R_BAD_KEY_LENGTH:
case EVP_R_BN_DECODE_ERROR:
case EVP_R_BN_PUBKEY_ERROR:
case EVP_R_INVALID_KEY_LENGTH:
case EVP_R_MISSING_PARAMETERS:
case EVP_R_UNSUPPORTED_KEY_SIZE:
case EVP_R_UNSUPPORTED_KEYLENGTH:
throwInvalidKeyException(env, message);
break;
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
throwSignatureException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
#endif
static void throwForRsaError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case RSA_R_BLOCK_TYPE_IS_NOT_01:
case RSA_R_BLOCK_TYPE_IS_NOT_02:
throwBadPaddingException(env, message);
break;
case RSA_R_BAD_SIGNATURE:
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
case RSA_R_INVALID_MESSAGE_LENGTH:
case RSA_R_WRONG_SIGNATURE_LENGTH:
#if !defined(OPENSSL_IS_BORINGSSL)
case RSA_R_ALGORITHM_MISMATCH:
case RSA_R_DATA_GREATER_THAN_MOD_LEN:
#endif
throwSignatureException(env, message);
break;
case RSA_R_UNKNOWN_ALGORITHM_TYPE:
throwNoSuchAlgorithmException(env, message);
break;
case RSA_R_MODULUS_TOO_LARGE:
case RSA_R_NO_PUBLIC_EXPONENT:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForX509Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case X509_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
/*
* Checks this thread's OpenSSL error queue and throws a RuntimeException if
* necessary.
*
* @return true if an exception was thrown, false if not.
*/
static bool throwExceptionIfNecessary(JNIEnv* env, const char* location __attribute__ ((unused))) {
const char* file;
int line;
const char* data;
int flags;
unsigned long error = ERR_get_error_line_data(&file, &line, &data, &flags);
int result = false;
if (error != 0) {
char message[256];
ERR_error_string_n(error, message, sizeof(message));
int library = ERR_GET_LIB(error);
int reason = ERR_GET_REASON(error);
JNI_TRACE("OpenSSL error in %s error=%lx library=%x reason=%x (%s:%d): %s %s",
location, error, library, reason, file, line, message,
(flags & ERR_TXT_STRING) ? data : "(no data)");
switch (library) {
case ERR_LIB_RSA:
throwForRsaError(env, reason, message);
break;
case ERR_LIB_ASN1:
throwForAsn1Error(env, reason, message);
break;
#if defined(OPENSSL_IS_BORINGSSL)
case ERR_LIB_CIPHER:
throwForCipherError(env, reason, message);
break;
#endif
case ERR_LIB_EVP:
throwForEvpError(env, reason, message);
break;
case ERR_LIB_X509:
throwForX509Error(env, reason, message);
break;
case ERR_LIB_DSA:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
result = true;
}
freeOpenSslErrorState();
return result;
}
/**
* Throws an SocketTimeoutException with the given string as a message.
*/
static void throwSocketTimeoutException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSocketTimeoutException %s", message);
jniThrowException(env, "java/net/SocketTimeoutException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLHandshakeExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLHandshakeException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLException", message);
}
/**
* Throws a javax.net.ssl.SSLProcotolException with the given string as a message.
*/
static void throwSSLProtocolExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLProtocolExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLProtocolException", message);
}
/**
* Throws an SSLException with a message constructed from the current
* SSL errors. This will also log the errors.
*
* @param env the JNI environment
* @param ssl the possibly NULL SSL
* @param sslErrorCode error code returned from SSL_get_error() or
* SSL_ERROR_NONE to probe with ERR_get_error
* @param message null-ok; general error message
*/
static void throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCode,
const char* message, void (*actualThrow)(JNIEnv*, const char*) = throwSSLExceptionStr) {
if (message == NULL) {
message = "SSL error";
}
// First consult the SSL error code for the general message.
const char* sslErrorStr = NULL;
switch (sslErrorCode) {
case SSL_ERROR_NONE:
if (ERR_peek_error() == 0) {
sslErrorStr = "OK";
} else {
sslErrorStr = "";
}
break;
case SSL_ERROR_SSL:
sslErrorStr = "Failure in SSL library, usually a protocol error";
break;
case SSL_ERROR_WANT_READ:
sslErrorStr = "SSL_ERROR_WANT_READ occurred. You should never see this.";
break;
case SSL_ERROR_WANT_WRITE:
sslErrorStr = "SSL_ERROR_WANT_WRITE occurred. You should never see this.";
break;
case SSL_ERROR_WANT_X509_LOOKUP:
sslErrorStr = "SSL_ERROR_WANT_X509_LOOKUP occurred. You should never see this.";
break;
case SSL_ERROR_SYSCALL:
sslErrorStr = "I/O error during system call";
break;
case SSL_ERROR_ZERO_RETURN:
sslErrorStr = "SSL_ERROR_ZERO_RETURN occurred. You should never see this.";
break;
case SSL_ERROR_WANT_CONNECT:
sslErrorStr = "SSL_ERROR_WANT_CONNECT occurred. You should never see this.";
break;
case SSL_ERROR_WANT_ACCEPT:
sslErrorStr = "SSL_ERROR_WANT_ACCEPT occurred. You should never see this.";
break;
default:
sslErrorStr = "Unknown SSL error";
}
// Prepend either our explicit message or a default one.
char* str;
if (asprintf(&str, "%s: ssl=%p: %s", message, ssl, sslErrorStr) <= 0) {
// problem with asprintf, just throw argument message, log everything
actualThrow(env, message);
ALOGV("%s: ssl=%p: %s", message, ssl, sslErrorStr);
freeOpenSslErrorState();
return;
}
char* allocStr = str;
// For protocol errors, SSL might have more information.
if (sslErrorCode == SSL_ERROR_NONE || sslErrorCode == SSL_ERROR_SSL) {
// Append each error as an additional line to the message.
for (;;) {
char errStr[256];
const char* file;
int line;
const char* data;
int flags;
unsigned long err = ERR_get_error_line_data(&file, &line, &data, &flags);
if (err == 0) {
break;
}
ERR_error_string_n(err, errStr, sizeof(errStr));
int ret = asprintf(&str, "%s\n%s (%s:%d %p:0x%08x)",
(allocStr == NULL) ? "" : allocStr,
errStr,
file,
line,
(flags & ERR_TXT_STRING) ? data : "(no data)",
flags);
if (ret < 0) {
break;
}
free(allocStr);
allocStr = str;
}
// For errors during system calls, errno might be our friend.
} else if (sslErrorCode == SSL_ERROR_SYSCALL) {
if (asprintf(&str, "%s, %s", allocStr, strerror(errno)) >= 0) {
free(allocStr);
allocStr = str;
}
// If the error code is invalid, print it.
} else if (sslErrorCode > SSL_ERROR_WANT_ACCEPT) {
if (asprintf(&str, ", error code is %d", sslErrorCode) >= 0) {
free(allocStr);
allocStr = str;
}
}
if (sslErrorCode == SSL_ERROR_SSL) {
throwSSLProtocolExceptionStr(env, allocStr);
} else {
actualThrow(env, allocStr);
}
ALOGV("%s", allocStr);
free(allocStr);
freeOpenSslErrorState();
}
/**
* Helper function that grabs the casts an ssl pointer and then checks for nullness.
* If this function returns NULL and <code>throwIfNull</code> is
* passed as <code>true</code>, then this function will call
* <code>throwSSLExceptionStr</code> before returning, so in this case of
* NULL, a caller of this function should simply return and allow JNI
* to do its thing.
*
* @param env the JNI environment
* @param ssl_address; the ssl_address pointer as an integer
* @param throwIfNull whether to throw if the SSL pointer is NULL
* @returns the pointer, which may be NULL
*/
static SSL_CTX* to_SSL_CTX(JNIEnv* env, jlong ssl_ctx_address, bool throwIfNull) {
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
if ((ssl_ctx == NULL) && throwIfNull) {
JNI_TRACE("ssl_ctx == null");
jniThrowNullPointerException(env, "ssl_ctx == null");
}
return ssl_ctx;
}
static SSL* to_SSL(JNIEnv* env, jlong ssl_address, bool throwIfNull) {
SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
if ((ssl == NULL) && throwIfNull) {
JNI_TRACE("ssl == null");
jniThrowNullPointerException(env, "ssl == null");
}
return ssl;
}
static SSL_SESSION* to_SSL_SESSION(JNIEnv* env, jlong ssl_session_address, bool throwIfNull) {
SSL_SESSION* ssl_session
= reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
if ((ssl_session == NULL) && throwIfNull) {
JNI_TRACE("ssl_session == null");
jniThrowNullPointerException(env, "ssl_session == null");
}
return ssl_session;
}
static SSL_CIPHER* to_SSL_CIPHER(JNIEnv* env, jlong ssl_cipher_address, bool throwIfNull) {
SSL_CIPHER* ssl_cipher
= reinterpret_cast<SSL_CIPHER*>(static_cast<uintptr_t>(ssl_cipher_address));
if ((ssl_cipher == NULL) && throwIfNull) {
JNI_TRACE("ssl_cipher == null");
jniThrowNullPointerException(env, "ssl_cipher == null");
}
return ssl_cipher;
}
template<typename T>
static T* fromContextObject(JNIEnv* env, jobject contextObject) {
T* ref = reinterpret_cast<T*>(env->GetLongField(contextObject, nativeRef_context));
if (ref == NULL) {
JNI_TRACE("ctx == null");
jniThrowNullPointerException(env, "ctx == null");
}
return ref;
}
/**
* Converts a Java byte[] two's complement to an OpenSSL BIGNUM. This will
* allocate the BIGNUM if *dest == NULL. Returns true on success. If the
* return value is false, there is a pending exception.
*/
static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
JNI_TRACE("arrayToBignum(%p, %p)", source, dest);
if (dest == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => dest is null!", source, dest);
jniThrowNullPointerException(env, "dest == null");
return false;
}
JNI_TRACE("arrayToBignum(%p, %p) *dest == %p", source, dest, *dest);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
/* if the array is empty, it is zero. */
if (tmpSize == 0) {
if (*dest == NULL) {
*dest = BN_new();
}
BN_zero(*dest);
return true;
}
UniquePtr<unsigned char[]> twosComplement;
bool negative = (tmp[0] & 0x80) != 0;
if (negative) {
// Need to convert to two's complement.
twosComplement.reset(new unsigned char[tmpSize]);
unsigned char* twosBytes = reinterpret_cast<unsigned char*>(twosComplement.get());
memcpy(twosBytes, tmp, tmpSize);
tmp = twosBytes;
bool carry = true;
for (ssize_t i = tmpSize - 1; i >= 0; i--) {
twosBytes[i] ^= 0xFF;
if (carry) {
carry = (++twosBytes[i]) == 0;
}
}
}
BIGNUM *ret = BN_bin2bn(tmp, tmpSize, *dest);
if (ret == NULL) {
jniThrowRuntimeException(env, "Conversion to BIGNUM failed");
JNI_TRACE("arrayToBignum(%p, %p) => threw exception", source, dest);
return false;
}
BN_set_negative(ret, negative ? 1 : 0);
*dest = ret;
JNI_TRACE("arrayToBignum(%p, %p) => *dest = %p", source, dest, ret);
return true;
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* arrayToBignumSize sets |*out_size| to the size of the big-endian number
* contained in |source|. It returns true on success and sets an exception and
* returns false otherwise.
*/
static bool arrayToBignumSize(JNIEnv* env, jbyteArray source, size_t* out_size) {
JNI_TRACE("arrayToBignumSize(%p, %p)", source, out_size);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const uint8_t* tmp = reinterpret_cast<const uint8_t*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
if (tmpSize == 0) {
*out_size = 0;
return true;
}
if ((tmp[0] & 0x80) != 0) {
// Negative numbers are invalid.
jniThrowRuntimeException(env, "Negative number");
return false;
}
while (tmpSize > 0 && tmp[0] == 0) {
tmp++;
tmpSize--;
}
*out_size = tmpSize;
return true;
}
#endif
/**
* Converts an OpenSSL BIGNUM to a Java byte[] array in two's complement.
*/
static jbyteArray bignumToArray(JNIEnv* env, const BIGNUM* source, const char* sourceName) {
JNI_TRACE("bignumToArray(%p, %s)", source, sourceName);
if (source == NULL) {
jniThrowNullPointerException(env, sourceName);
return NULL;
}
size_t numBytes = BN_num_bytes(source) + 1;
jbyteArray javaBytes = env->NewByteArray(numBytes);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bignumToArray(%p, %s) => NULL", source, sourceName);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
if (BN_num_bytes(source) > 0 && BN_bn2bin(source, tmp + 1) <= 0) {
throwExceptionIfNecessary(env, "bignumToArray");
return NULL;
}
// Set the sign and convert to two's complement if necessary for the Java code.
if (BN_is_negative(source)) {
bool carry = true;
for (ssize_t i = numBytes - 1; i >= 0; i--) {
tmp[i] ^= 0xFF;
if (carry) {
carry = (++tmp[i]) == 0;
}
}
*tmp |= 0x80;
} else {
*tmp = 0x00;
}
JNI_TRACE("bignumToArray(%p, %s) => %p", source, sourceName, javaBytes);
return javaBytes;
}
/**
* Converts various OpenSSL ASN.1 types to a jbyteArray with DER-encoded data
* inside. The "i2d_func" function pointer is a function of the "i2d_<TYPE>"
* from the OpenSSL ASN.1 API.
*/
template<typename T>
jbyteArray ASN1ToByteArray(JNIEnv* env, T* obj, int (*i2d_func)(T*, unsigned char**)) {
if (obj == NULL) {
jniThrowNullPointerException(env, "ASN1 input == null");
JNI_TRACE("ASN1ToByteArray(%p) => null input", obj);
return NULL;
}
int derLen = i2d_func(obj, NULL);
if (derLen < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => measurement failed", obj);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => creating byte array failed", obj);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => using byte array failed", obj);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
int ret = i2d_func(obj, &p);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => final conversion failed", obj);
return NULL;
}
JNI_TRACE("ASN1ToByteArray(%p) => success (%d bytes written)", obj, ret);
return byteArray.release();
}
template<typename T, T* (*d2i_func)(T**, const unsigned char**, long)>
T* ByteArrayToASN1(JNIEnv* env, jbyteArray byteArray) {
ScopedByteArrayRO bytes(env, byteArray);
if (bytes.get() == NULL) {
JNI_TRACE("ByteArrayToASN1(%p) => using byte array failed", byteArray);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
return d2i_func(NULL, &tmp, bytes.size());
}
/**
* Converts ASN.1 BIT STRING to a jbooleanArray.
*/
jbooleanArray ASN1BitStringToBooleanArray(JNIEnv* env, ASN1_BIT_STRING* bitStr) {
int size = bitStr->length * 8;
if (bitStr->flags & ASN1_STRING_FLAG_BITS_LEFT) {
size -= bitStr->flags & 0x07;
}
ScopedLocalRef<jbooleanArray> bitsRef(env, env->NewBooleanArray(size));
if (bitsRef.get() == NULL) {
return NULL;
}
ScopedBooleanArrayRW bitsArray(env, bitsRef.get());
for (int i = 0; i < static_cast<int>(bitsArray.size()); i++) {
bitsArray[i] = ASN1_BIT_STRING_get_bit(bitStr, i);
}
return bitsRef.release();
}
/**
* To avoid the round-trip to ASN.1 and back in X509_dup, we just up the reference count.
*/
static X509* X509_dup_nocopy(X509* x509) {
if (x509 == NULL) {
return NULL;
}
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509);
return x509;
}
/*
* Sets the read and write BIO for an SSL connection and removes it when it goes out of scope.
* We hang on to BIO with a JNI GlobalRef and we want to remove them as soon as possible.
*/
class ScopedSslBio {
public:
ScopedSslBio(SSL *ssl, BIO* rbio, BIO* wbio) : ssl_(ssl) {
SSL_set_bio(ssl_, rbio, wbio);
CRYPTO_add(&rbio->references,1,CRYPTO_LOCK_BIO);
CRYPTO_add(&wbio->references,1,CRYPTO_LOCK_BIO);
}
~ScopedSslBio() {
SSL_set_bio(ssl_, NULL, NULL);
}
private:
SSL* const ssl_;
};
/**
* Obtains the current thread's JNIEnv
*/
static JNIEnv* getJNIEnv() {
JNIEnv* env;
if (gJavaVM->AttachCurrentThread(&env, NULL) < 0) {
ALOGE("Could not attach JavaVM to find current JNIEnv");
return NULL;
}
return env;
}
/**
* BIO for InputStream
*/
class BIO_Stream {
public:
BIO_Stream(jobject stream) :
mEof(false) {
JNIEnv* env = getJNIEnv();
mStream = env->NewGlobalRef(stream);
}
~BIO_Stream() {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(mStream);
}
bool isEof() const {
JNI_TRACE("isEof? %s", mEof ? "yes" : "no");
return mEof;
}
int flush() {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_Stream::flush called with pending exception");
return -1;
}
env->CallVoidMethod(mStream, outputStream_flushMethod);
if (env->ExceptionCheck()) {
return -1;
}
return 1;
}
protected:
jobject getStream() {
return mStream;
}
void setEof(bool eof) {
mEof = eof;
}
private:
jobject mStream;
bool mEof;
};
class BIO_InputStream : public BIO_Stream {
public:
BIO_InputStream(jobject stream) :
BIO_Stream(stream) {
}
int read(char *buf, int len) {
return read_internal(buf, len, inputStream_readMethod);
}
int gets(char *buf, int len) {
if (len > PEM_LINE_LENGTH) {
len = PEM_LINE_LENGTH;
}
int read = read_internal(buf, len - 1, openSslInputStream_readLineMethod);
buf[read] = '\0';
JNI_TRACE("BIO::gets \"%s\"", buf);
return read;
}
private:
int read_internal(char *buf, int len, jmethodID method) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_InputStream::read could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_InputStream::read failed call to NewByteArray");
return -1;
}
jint read = env->CallIntMethod(getStream(), method, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read failed call to InputStream#read");
return -1;
}
/* Java uses -1 to indicate EOF condition. */
if (read == -1) {
setEof(true);
read = 0;
} else if (read > 0) {
env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast<jbyte*>(buf));
}
return read;
}
public:
/** Length of PEM-encoded line (64) plus CR plus NULL */
static const int PEM_LINE_LENGTH = 66;
};
class BIO_OutputStream : public BIO_Stream {
public:
BIO_OutputStream(jobject stream) :
BIO_Stream(stream) {
}
int write(const char *buf, int len) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_OutputStream::write => could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_OutputStream::write => failed call to NewByteArray");
return -1;
}
env->SetByteArrayRegion(javaBytes.get(), 0, len, reinterpret_cast<const jbyte*>(buf));
env->CallVoidMethod(getStream(), outputStream_writeMethod, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => failed call to OutputStream#write");
return -1;
}
return len;
}
};
static int bio_stream_create(BIO *b) {
b->init = 1;
b->num = 0;
b->ptr = NULL;
b->flags = 0;
return 1;
}
static int bio_stream_destroy(BIO *b) {
if (b == NULL) {
return 0;
}
if (b->ptr != NULL) {
delete static_cast<BIO_Stream*>(b->ptr);
b->ptr = NULL;
}
b->init = 0;
b->flags = 0;
return 1;
}
static int bio_stream_read(BIO *b, char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
int ret = stream->read(buf, len);
if (ret == 0) {
// EOF is indicated by -1 with a BIO flag.
BIO_set_retry_read(b);
return -1;
}
return ret;
}
static int bio_stream_write(BIO *b, const char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, len);
}
static int bio_stream_puts(BIO *b, const char *buf) {
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, strlen(buf));
}
static int bio_stream_gets(BIO *b, char *buf, int len) {
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
return stream->gets(buf, len);
}
static void bio_stream_assign(BIO *b, BIO_Stream* stream) {
b->ptr = static_cast<void*>(stream);
}
static long bio_stream_ctrl(BIO *b, int cmd, long, void *) {
BIO_Stream* stream = static_cast<BIO_Stream*>(b->ptr);
switch (cmd) {
case BIO_CTRL_EOF:
return stream->isEof() ? 1 : 0;
case BIO_CTRL_FLUSH:
return stream->flush();
default:
return 0;
}
}
static BIO_METHOD stream_bio_method = {
( 100 | 0x0400 ), /* source/sink BIO */
"InputStream/OutputStream BIO",
bio_stream_write, /* bio_write */
bio_stream_read, /* bio_read */
bio_stream_puts, /* bio_puts */
bio_stream_gets, /* bio_gets */
bio_stream_ctrl, /* bio_ctrl */
bio_stream_create, /* bio_create */
bio_stream_destroy, /* bio_free */
NULL, /* no bio_callback_ctrl */
};
static jbyteArray rawSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey,
const char* message, size_t message_len) {
ScopedLocalRef<jbyteArray> messageArray(env, env->NewByteArray(message_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW messageBytes(env, messageArray.get());
if (messageBytes.get() == NULL) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(messageBytes.get(), message, message_len);
}
jmethodID rawSignMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rawSignDigestWithPrivateKey", "(Ljava/security/PrivateKey;[B)[B");
if (rawSignMethod == NULL) {
ALOGE("Could not find rawSignDigestWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass, rawSignMethod, privateKey, messageArray.get()));
}
static jbyteArray rawCipherWithPrivateKey(JNIEnv* env, jobject privateKey, jboolean encrypt,
const char* ciphertext, size_t ciphertext_len) {
ScopedLocalRef<jbyteArray> ciphertextArray(env, env->NewByteArray(ciphertext_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rawCipherWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW ciphertextBytes(env, ciphertextArray.get());
if (ciphertextBytes.get() == NULL) {
JNI_TRACE("rawCipherWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(ciphertextBytes.get(), ciphertext, ciphertext_len);
}
jmethodID rawCipherMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rawCipherWithPrivateKey", "(Ljava/security/PrivateKey;Z[B)[B");
if (rawCipherMethod == NULL) {
ALOGE("Could not find rawCipherWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass, rawCipherMethod, privateKey, encrypt, ciphertextArray.get()));
}
// *********************************************
// From keystore_openssl.cpp in Chromium source.
// *********************************************
#if !defined(OPENSSL_IS_BORINGSSL)
// Custom RSA_METHOD that uses the platform APIs.
// Note that for now, only signing through RSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
// See <openssl/rsa.h> for exact declaration of RSA_METHOD.
int RsaMethodPubEnc(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
int RsaMethodPubDec(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
// See RSA_eay_private_encrypt in
// third_party/openssl/openssl/crypto/rsa/rsa_eay.c for the default
// implementation of this function.
int RsaMethodPrivEnc(int flen,
const unsigned char *from,
unsigned char *to,
RSA *rsa,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
return -1;
}
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// For RSA keys, this function behaves as RSA_private_encrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(from), flen));
if (signature.get() == NULL) {
ALOGE("Could not sign message in RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (signatureBytes.size() > expected_size) {
ALOGE("RSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer. rawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - signatureBytes.size();
memset(to, 0, zero_pad);
memcpy(to + zero_pad, signatureBytes.get(), signatureBytes.size());
return expected_size;
}
int RsaMethodPrivDec(int flen,
const unsigned char* from,
unsigned char* to,
RSA* rsa,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
return -1;
}
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// For RSA keys, this function behaves as RSA_private_decrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> cleartext(env, rawCipherWithPrivateKey(env, private_key, false,
reinterpret_cast<const char*>(from), flen));
if (cleartext.get() == NULL) {
ALOGE("Could not decrypt message in RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO cleartextBytes(env, cleartext.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (cleartextBytes.size() > expected_size) {
ALOGE("RSA ciphertext size mismatch, actual: %zd, expected <= %zd", cleartextBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer.
memcpy(to, cleartextBytes.get(), cleartextBytes.size());
return cleartextBytes.size();
}
int RsaMethodInit(RSA*) {
return 0;
}
int RsaMethodFinish(RSA* rsa) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
jobject key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (key != NULL) {
RSA_set_app_data(rsa, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(key);
}
// Actual return value is ignored by OpenSSL. There are no docs
// explaining what this is supposed to be.
return 0;
}
const RSA_METHOD android_rsa_method = {
/* .name = */ "Android signing-only RSA method",
/* .rsa_pub_enc = */ RsaMethodPubEnc,
/* .rsa_pub_dec = */ RsaMethodPubDec,
/* .rsa_priv_enc = */ RsaMethodPrivEnc,
/* .rsa_priv_dec = */ RsaMethodPrivDec,
/* .rsa_mod_exp = */ NULL,
/* .bn_mod_exp = */ NULL,
/* .init = */ RsaMethodInit,
/* .finish = */ RsaMethodFinish,
// This flag is necessary to tell OpenSSL to avoid checking the content
// (i.e. internal fields) of the private key. Otherwise, it will complain
// it's not valid for the certificate.
/* .flags = */ RSA_METHOD_FLAG_NO_CHECK,
/* .app_data = */ NULL,
/* .rsa_sign = */ NULL,
/* .rsa_verify = */ NULL,
/* .rsa_keygen = */ NULL,
};
// Used to ensure that the global JNI reference associated with a custom
// EC_KEY + ECDSA_METHOD wrapper is released when its EX_DATA is destroyed
// (this function is called when EVP_PKEY_free() is called on the wrapper).
void ExDataFree(void* /* parent */,
void* ptr,
CRYPTO_EX_DATA* ad,
int idx,
long /* argl */,
void* /* argp */) {
jobject private_key = reinterpret_cast<jobject>(ptr);
if (private_key == NULL) return;
CRYPTO_set_ex_data(ad, idx, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(private_key);
}
int ExDataDup(CRYPTO_EX_DATA* /* to */,
CRYPTO_EX_DATA* /* from */,
void* /* from_d */,
int /* idx */,
long /* argl */,
void* /* argp */) {
// This callback shall never be called with the current OpenSSL
// implementation (the library only ever duplicates EX_DATA items
// for SSL and BIO objects). But provide this to catch regressions
// in the future.
// Return value is currently ignored by OpenSSL.
return 0;
}
class EcdsaExDataIndex {
public:
int ex_data_index() { return ex_data_index_; }
static EcdsaExDataIndex& Instance() {
static EcdsaExDataIndex singleton;
return singleton;
}
private:
EcdsaExDataIndex() {
ex_data_index_ = ECDSA_get_ex_new_index(0, NULL, NULL, ExDataDup, ExDataFree);
}
EcdsaExDataIndex(EcdsaExDataIndex const&);
~EcdsaExDataIndex() {}
EcdsaExDataIndex& operator=(EcdsaExDataIndex const&);
int ex_data_index_;
};
// Returns the index of the custom EX_DATA used to store the JNI reference.
int EcdsaGetExDataIndex(void) {
EcdsaExDataIndex& exData = EcdsaExDataIndex::Instance();
return exData.ex_data_index();
}
ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst, int dgst_len, const BIGNUM* /* inv */,
const BIGNUM* /* rp */, EC_KEY* eckey) {
// Retrieve private key JNI reference.
jobject private_key =
reinterpret_cast<jobject>(ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex()));
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodDoSign!");
return NULL;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return NULL;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key, reinterpret_cast<const char*>(dgst),
dgst_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return NULL;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey));
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
max_expected_size);
return NULL;
}
// Convert signature to ECDSA_SIG object
const unsigned char* sigbuf = reinterpret_cast<const unsigned char*>(signatureBytes.get());
long siglen = static_cast<long>(signatureBytes.size());
return d2i_ECDSA_SIG(NULL, &sigbuf, siglen);
}
int EcdsaMethodSignSetup(EC_KEY* /* eckey */,
BN_CTX* /* ctx */,
BIGNUM** /* kinv */,
BIGNUM** /* r */,
const unsigned char*,
int) {
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB);
return -1;
}
int EcdsaMethodDoVerify(const unsigned char* /* dgst */,
int /* dgst_len */,
const ECDSA_SIG* /* sig */,
EC_KEY* /* eckey */) {
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB);
return -1;
}
const ECDSA_METHOD android_ecdsa_method = {
/* .name = */ "Android signing-only ECDSA method",
/* .ecdsa_do_sign = */ EcdsaMethodDoSign,
/* .ecdsa_sign_setup = */ EcdsaMethodSignSetup,
/* .ecdsa_do_verify = */ EcdsaMethodDoVerify,
/* .flags = */ 0,
/* .app_data = */ NULL,
};
#else /* OPENSSL_IS_BORINGSSL */
namespace {
ENGINE *g_engine;
int g_rsa_exdata_index;
int g_ecdsa_exdata_index;
pthread_once_t g_engine_once = PTHREAD_ONCE_INIT;
void init_engine_globals();
void ensure_engine_globals() {
pthread_once(&g_engine_once, init_engine_globals);
}
// KeyExData contains the data that is contained in the EX_DATA of the RSA
// and ECDSA objects that are created to wrap Android system keys.
struct KeyExData {
// private_key contains a reference to a Java, private-key object.
jobject private_key;
// cached_size contains the "size" of the key. This is the size of the
// modulus (in bytes) for RSA, or the group order size for ECDSA. This
// avoids calling into Java to calculate the size.
size_t cached_size;
};
// ExDataDup is called when one of the RSA or EC_KEY objects is duplicated. We
// don't support this and it should never happen.
int ExDataDup(CRYPTO_EX_DATA* to,
const CRYPTO_EX_DATA* from,
void** from_d,
int index,
long argl,
void* argp) {
return 0;
}
// ExDataFree is called when one of the RSA or EC_KEY objects is freed.
void ExDataFree(void* parent,
void* ptr,
CRYPTO_EX_DATA* ad,
int index,
long argl,
void* argp) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
KeyExData *ex_data = reinterpret_cast<KeyExData*>(ptr);
if (ex_data != NULL) {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(ex_data->private_key);
delete ex_data;
}
}
KeyExData* RsaGetExData(const RSA* rsa) {
return reinterpret_cast<KeyExData*>(RSA_get_ex_data(rsa, g_rsa_exdata_index));
}
size_t RsaMethodSize(const RSA *rsa) {
const KeyExData *ex_data = RsaGetExData(rsa);
return ex_data->cached_size;
}
int RsaMethodEncrypt(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
OPENSSL_PUT_ERROR(RSA, encrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
int RsaMethodSignRaw(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
OPENSSL_PUT_ERROR(RSA, sign_raw, RSA_R_UNKNOWN_PADDING_TYPE);
return 0;
}
// Retrieve private key JNI reference.
const KeyExData *ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
// For RSA keys, this function behaves as RSA_private_decrypt with
// PKCS#1 v1.5 padding.
ScopedLocalRef<jbyteArray> cleartext(
env, rawCipherWithPrivateKey(env, ex_data->private_key, false,
reinterpret_cast<const char*>(in), in_len));
if (cleartext.get() == NULL) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO result(env, cleartext.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (result.size() > expected_size) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
if (max_out < expected_size) {
OPENSSL_PUT_ERROR(RSA, sign_raw, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer. RawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - result.size();
memset(out, 0, zero_pad);
memcpy(out + zero_pad, &result[0], result.size());
*out_len = expected_size;
return 1;
}
int RsaMethodDecrypt(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
OPENSSL_PUT_ERROR(RSA, decrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
int RsaMethodVerifyRaw(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
OPENSSL_PUT_ERROR(RSA, verify_raw, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
const RSA_METHOD android_rsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
RsaMethodSize,
NULL /* sign */,
NULL /* verify */,
RsaMethodEncrypt,
RsaMethodSignRaw,
RsaMethodDecrypt,
RsaMethodVerifyRaw,
NULL /* mod_exp */,
NULL /* bn_mod_exp */,
NULL /* private_transform */,
RSA_FLAG_OPAQUE,
NULL /* keygen */,
};
// Custom ECDSA_METHOD that uses the platform APIs.
// Note that for now, only signing through ECDSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
jobject EcKeyGetKey(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->private_key;
}
size_t EcdsaMethodGroupOrderSize(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->cached_size;
}
int EcdsaMethodSign(const uint8_t* digest,
size_t digest_len,
uint8_t* sig,
unsigned int* sig_len,
EC_KEY* ec_key) {
// Retrieve private key JNI reference.
jobject private_key = EcKeyGetKey(ec_key);
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodSign!");
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return 0;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(digest),
digest_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return 0;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = ECDSA_size(ec_key);
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd",
signatureBytes.size(), max_expected_size);
return 0;
}
memcpy(sig, signatureBytes.get(), signatureBytes.size());
*sig_len = signatureBytes.size();
return 1;
}
int EcdsaMethodVerify(const uint8_t* digest,
size_t digest_len,
const uint8_t* sig,
size_t sig_len,
EC_KEY* ec_key) {
OPENSSL_PUT_ERROR(ECDSA, ECDSA_do_verify, ECDSA_R_NOT_IMPLEMENTED);
return 0;
}
const ECDSA_METHOD android_ecdsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
EcdsaMethodGroupOrderSize,
EcdsaMethodSign,
EcdsaMethodVerify,
ECDSA_FLAG_OPAQUE,
};
void init_engine_globals() {
g_rsa_exdata_index =
RSA_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
ExDataDup, ExDataFree);
g_ecdsa_exdata_index =
EC_KEY_get_ex_new_index(0 /* argl */, NULL /* argp */,
NULL /* new_func */, ExDataDup, ExDataFree);
g_engine = ENGINE_new();
ENGINE_set_RSA_method(g_engine, &android_rsa_method,
sizeof(android_rsa_method));
ENGINE_set_ECDSA_method(g_engine, &android_ecdsa_method,
sizeof(android_ecdsa_method));
}
} // anonymous namespace
#endif
#ifdef CONSCRYPT_UNBUNDLED
/*
* This is a big hack; don't learn from this. Basically what happened is we do
* not have an API way to insert ourselves into the AsynchronousCloseMonitor
* that's compiled into the native libraries for libcore when we're unbundled.
* So we try to look up the symbol from the main library to find it.
*/
typedef void (*acm_ctor_func)(void*, int);
typedef void (*acm_dtor_func)(void*);
static acm_ctor_func async_close_monitor_ctor = NULL;
static acm_dtor_func async_close_monitor_dtor = NULL;
class CompatibilityCloseMonitor {
public:
CompatibilityCloseMonitor(int fd) {
if (async_close_monitor_ctor != NULL) {
async_close_monitor_ctor(objBuffer, fd);
}
}
~CompatibilityCloseMonitor() {
if (async_close_monitor_dtor != NULL) {
async_close_monitor_dtor(objBuffer);
}
}
private:
char objBuffer[256];
#if 0
static_assert(sizeof(objBuffer) > 2*sizeof(AsynchronousCloseMonitor),
"CompatibilityCloseMonitor must be larger than the actual object");
#endif
};
static void findAsynchronousCloseMonitorFuncs() {
void *lib = dlopen("libjavacore.so", RTLD_NOW);
if (lib != NULL) {
async_close_monitor_ctor = (acm_ctor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorC1Ei");
async_close_monitor_dtor = (acm_dtor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorD1Ev");
}
}
#endif
/**
* Copied from libnativehelper NetworkUtilites.cpp
*/
static bool setBlocking(int fd, bool blocking) {
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
return false;
}
if (!blocking) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int rc = fcntl(fd, F_SETFL, flags);
return (rc != -1);
}
/**
* OpenSSL locking support. Taken from the O'Reilly book by Viega et al., but I
* suppose there are not many other ways to do this on a Linux system (modulo
* isomorphism).
*/
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#define THROW_SSLEXCEPTION (-2)
#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
#define THROWN_EXCEPTION (-4)
static MUTEX_TYPE* mutex_buf = NULL;
static void locking_function(int mode, int n, const char*, int) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(mutex_buf[n]);
} else {
MUTEX_UNLOCK(mutex_buf[n]);
}
}
static void threadid_callback(CRYPTO_THREADID *threadid) {
#if defined(__APPLE__)
uint64_t owner;
int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6
if (rc == 0) {
CRYPTO_THREADID_set_numeric(threadid, owner);
} else {
ALOGE("Error calling pthread_threadid_np");
}
#else
// bionic exposes gettid(), but glibc doesn't
CRYPTO_THREADID_set_numeric(threadid, syscall(__NR_gettid));
#endif
}
int THREAD_setup(void) {
mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
if (!mutex_buf) {
return 0;
}
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
MUTEX_SETUP(mutex_buf[i]);
}
CRYPTO_THREADID_set_callback(threadid_callback);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int THREAD_cleanup(void) {
if (!mutex_buf) {
return 0;
}
CRYPTO_THREADID_set_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks( ); i++) {
MUTEX_CLEANUP(mutex_buf[i]);
}
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
/**
* Initialization phase for every OpenSSL job: Loads the Error strings, the
* crypto algorithms and reset the OpenSSL library
*/
static void NativeCrypto_clinit(JNIEnv*, jclass)
{
SSL_load_error_strings();
ERR_load_crypto_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
THREAD_setup();
}
static void NativeCrypto_ENGINE_load_dynamic(JNIEnv*, jclass) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("ENGINE_load_dynamic()");
ENGINE_load_dynamic();
#endif
}
static jlong NativeCrypto_ENGINE_by_id(JNIEnv* env, jclass, jstring idJava) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("ENGINE_by_id(%p)", idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
JNI_TRACE("ENGINE_by_id(%p) => id == null", idJava);
return 0;
}
JNI_TRACE("ENGINE_by_id(\"%s\")", id.c_str());
ENGINE* e = ENGINE_by_id(id.c_str());
if (e == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("ENGINE_by_id(\"%s\") => %p", id.c_str(), e);
return reinterpret_cast<uintptr_t>(e);
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_add(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_add(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_add(e);
/*
* We tolerate errors, because the most likely error is that
* the ENGINE is already in the list.
*/
freeOpenSslErrorState();
JNI_TRACE("ENGINE_add(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_init(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_init(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_init(e);
JNI_TRACE("ENGINE_init(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_finish(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_finish(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_finish(e);
JNI_TRACE("ENGINE_finish(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_free(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_free(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_free(e);
JNI_TRACE("ENGINE_free(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
#if defined(OPENSSL_IS_BORINGSSL)
extern "C" {
/* EVP_PKEY_from_keystore is from system/security/keystore-engine. */
extern EVP_PKEY* EVP_PKEY_from_keystore(const char *key_id);
}
#endif
static jlong NativeCrypto_ENGINE_load_private_key(JNIEnv* env, jclass, jlong engineRef,
jstring idJava) {
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "id == NULL");
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_load_private_key(%p, %p)", e, idJava);
Unique_EVP_PKEY pkey(ENGINE_load_private_key(e, id.c_str(), NULL, NULL));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("ENGINE_load_private_key(%p, %p) => %p", e, idJava, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
#else
#if defined(NO_KEYSTORE_ENGINE)
jniThrowRuntimeException(env, "No keystore ENGINE support compiled in");
return 0;
#else
Unique_EVP_PKEY pkey(EVP_PKEY_from_keystore(id.c_str()));
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "Failed to find named key in keystore");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
#endif
#endif
}
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong engineRef)
{
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_get_id(%p)", e);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_get_id(%p) => engine == null", e);
return NULL;
}
const char *id = ENGINE_get_id(e);
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF(id));
JNI_TRACE("ENGINE_get_id(%p) => \"%s\"", e, id);
return idJava.release();
#else
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF("keystore"));
return idJava.release();
#endif
}
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv* env, jclass, jlong engineRef,
jstring cmdJava, jstring argJava, jint cmd_optional)
{
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d)", e, cmdJava, argJava, cmd_optional);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d) => engine == null", e, cmdJava, argJava,
cmd_optional);
return 0;
}
ScopedUtfChars cmdChars(env, cmdJava);
if (cmdChars.c_str() == NULL) {
return 0;
}
UniquePtr<ScopedUtfChars> arg;
const char* arg_c_str = NULL;
if (argJava != NULL) {
arg.reset(new ScopedUtfChars(env, argJava));
arg_c_str = arg->c_str();
if (arg_c_str == NULL) {
return 0;
}
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d)", e, cmdChars.c_str(), arg_c_str,
cmd_optional);
int ret = ENGINE_ctrl_cmd_string(e, cmdChars.c_str(), arg_c_str, cmd_optional);
if (ret != 1) {
throwExceptionIfNecessary(env, "ENGINE_ctrl_cmd_string");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => threw error", e,
cmdChars.c_str(), arg_c_str, cmd_optional);
return 0;
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => %d", e, cmdChars.c_str(),
arg_c_str, cmd_optional, ret);
return ret;
#else
return 0;
#endif
}
static jlong NativeCrypto_EVP_PKEY_new_DH(JNIEnv* env, jclass,
jbyteArray p, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p)",
p, g, pub_key, priv_key);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
jniThrowRuntimeException(env, "DH_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dh->p)) {
return 0;
}
if (!arrayToBignum(env, g, &dh->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dh->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dh->priv_key)) {
return 0;
}
if (dh->p == NULL || dh->g == NULL
|| (pub_key != NULL && dh->pub_key == NULL)
|| (priv_key != NULL && dh->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/* The public key can be recovered if the private key is available. */
if (dh->pub_key == NULL && dh->priv_key != NULL) {
if (!DH_generate_key(dh.get())) {
jniThrowRuntimeException(env, "EVP_PKEY_new_DH failed during pub_key generation");
return 0;
}
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DH failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
*/
static jlong NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass,
jbyteArray n, jbyteArray e, jbyteArray d,
jbyteArray p, jbyteArray q,
jbyteArray dmp1, jbyteArray dmq1,
jbyteArray iqmp) {
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p, dmp1=%p, dmq1=%p, iqmp=%p)",
n, e, d, p, q, dmp1, dmq1, iqmp);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_new failed");
return 0;
}
if (e == NULL && d == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "e == NULL && d == NULL");
JNI_TRACE("NativeCrypto_EVP_PKEY_new_RSA => e == NULL && d == NULL");
return 0;
}
if (!arrayToBignum(env, n, &rsa->n)) {
return 0;
}
if (e != NULL && !arrayToBignum(env, e, &rsa->e)) {
return 0;
}
if (d != NULL && !arrayToBignum(env, d, &rsa->d)) {
return 0;
}
if (p != NULL && !arrayToBignum(env, p, &rsa->p)) {
return 0;
}
if (q != NULL && !arrayToBignum(env, q, &rsa->q)) {
return 0;
}
if (dmp1 != NULL && !arrayToBignum(env, dmp1, &rsa->dmp1)) {
return 0;
}
if (dmq1 != NULL && !arrayToBignum(env, dmq1, &rsa->dmq1)) {
return 0;
}
if (iqmp != NULL && !arrayToBignum(env, iqmp, &rsa->iqmp)) {
return 0;
}
#ifdef WITH_JNI_TRACE
if (p != NULL && q != NULL) {
int check = RSA_check_key(rsa.get());
JNI_TRACE("EVP_PKEY_new_RSA(...) RSA_check_key returns %d", check);
}
#endif
if (rsa->n == NULL || (rsa->e == NULL && rsa->d == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
/*
* If the private exponent is available, there is the potential to do signing
* operations. If the public exponent is also available, OpenSSL will do RSA
* blinding. Enable it if possible.
*/
if (rsa->d != NULL) {
if (rsa->e != NULL) {
JNI_TRACE("EVP_PKEY_new_RSA(...) enabling RSA blinding => %p", rsa.get());
RSA_blinding_on(rsa.get(), NULL);
} else {
JNI_TRACE("EVP_PKEY_new_RSA(...) disabling RSA blinding => %p", rsa.get());
RSA_blinding_off(rsa.get());
}
}
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p dmp1=%p, dmq1=%p, iqmp=%p) => %p",
n, e, d, p, q, dmp1, dmq1, iqmp, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_EC_KEY(JNIEnv* env, jclass, jobject groupRef,
jobject pubkeyRef, jbyteArray keyJavaBytes) {
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
const EC_POINT* pubkey = fromContextObject<EC_POINT>(env, pubkeyRef);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p)", group, pubkey, keyJavaBytes);
Unique_BIGNUM key(NULL);
if (keyJavaBytes != NULL) {
BIGNUM* keyRef = NULL;
if (!arrayToBignum(env, keyJavaBytes, &keyRef)) {
return 0;
}
key.reset(keyRef);
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
jniThrowRuntimeException(env, "EC_KEY_new failed");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) > EC_KEY_set_group failed", group, pubkey,
keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (pubkey != NULL) {
if (EC_KEY_set_public_key(eckey.get(), pubkey) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_public_key");
return 0;
}
}
if (key.get() != NULL) {
if (EC_KEY_set_private_key(eckey.get(), key.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
if (pubkey == NULL) {
Unique_EC_POINT calcPubkey(EC_POINT_new(group));
if (!EC_POINT_mul(group, calcPubkey.get(), key.get(), NULL, NULL, NULL)) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => can't calulate public key", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
EC_KEY_set_public_key(eckey.get(), calcPubkey.get());
}
}
if (!EC_KEY_check_key(eckey.get())) {
JNI_TRACE("EVP_KEY_new_EC_KEY(%p, %p, %p) => invalid key created", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_check_key");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => %p", group, pubkey, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_mac_key(JNIEnv* env, jclass, jint pkeyType,
jbyteArray keyJavaBytes)
{
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p)", pkeyType, keyJavaBytes);
ScopedByteArrayRO key(env, keyJavaBytes);
if (key.get() == NULL) {
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(key.get());
Unique_EVP_PKEY pkey(EVP_PKEY_new_mac_key(pkeyType, (ENGINE *) NULL, tmp, key.size()));
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => threw error", pkeyType, keyJavaBytes);
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => %p", pkeyType, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static int NativeCrypto_EVP_PKEY_type(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_type(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_type(pkey->type);
JNI_TRACE("EVP_PKEY_type(%p) => %d", pkey, result);
return result;
}
/**
* private static native int EVP_PKEY_size(int pkey);
*/
static int NativeCrypto_EVP_PKEY_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_size(pkey);
JNI_TRACE("EVP_PKEY_size(%p) => %d", pkey, result);
return result;
}
static jstring NativeCrypto_EVP_PKEY_print_public(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_print_public(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_public(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_public");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_public(%p) => \"%s\"", pkey, tmp);
return description;
}
static jstring NativeCrypto_EVP_PKEY_print_private(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_print_private(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_private(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_private");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_private(%p) => \"%s\"", pkey, tmp);
return description;
}
static void NativeCrypto_EVP_PKEY_free(JNIEnv*, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_free(%p)", pkey);
if (pkey != NULL) {
EVP_PKEY_free(pkey);
}
}
static jint NativeCrypto_EVP_PKEY_cmp(JNIEnv* env, jclass, jobject pkey1Ref, jobject pkey2Ref) {
EVP_PKEY* pkey1 = fromContextObject<EVP_PKEY>(env, pkey1Ref);
EVP_PKEY* pkey2 = fromContextObject<EVP_PKEY>(env, pkey2Ref);
JNI_TRACE("EVP_PKEY_cmp(%p, %p)", pkey1, pkey2);
if (pkey1 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey1 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey1 == NULL");
return -1;
} else if (pkey2 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey2 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey2 == NULL");
return -1;
}
int result = EVP_PKEY_cmp(pkey1, pkey2);
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => %d", pkey1, pkey2, result);
return result;
}
/*
* static native byte[] i2d_PKCS8_PRIV_KEY_INFO(int, byte[])
*/
static jbyteArray NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PKCS8_PRIV_KEY_INFO(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return NULL;
}
Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("key=%p i2d_PKCS8_PRIV_KEY_INFO => error from key to PKCS8", pkey);
return NULL;
}
return ASN1ToByteArray<PKCS8_PRIV_KEY_INFO>(env, pkcs8.get(), i2d_PKCS8_PRIV_KEY_INFO);
}
/*
* static native int d2i_PKCS8_PRIV_KEY_INFO(byte[])
*/
static jlong NativeCrypto_d2i_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jbyteArray keyJavaBytes) {
JNI_TRACE("d2i_PKCS8_PRIV_KEY_INFO(%p)", keyJavaBytes);
ScopedByteArrayRO bytes(env, keyJavaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => threw exception", keyJavaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &tmp, bytes.size()));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from DER to PKCS8", keyJavaBytes);
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from PKCS8 to key", keyJavaBytes);
return 0;
}
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => %p", keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* static native byte[] i2d_PUBKEY(int)
*/
static jbyteArray NativeCrypto_i2d_PUBKEY(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PUBKEY(%p)", pkey);
return ASN1ToByteArray<EVP_PKEY>(env, pkey, reinterpret_cast<int (*) (EVP_PKEY*, uint8_t **)>(i2d_PUBKEY));
}
/*
* static native int d2i_PUBKEY(byte[])
*/
static jlong NativeCrypto_d2i_PUBKEY(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("d2i_PUBKEY(%p)", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("d2i_PUBKEY(%p) => threw error", javaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, bytes.size()));
if (pkey.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PUBKEY => threw exception", javaBytes);
throwExceptionIfNecessary(env, "d2i_PUBKEY");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getRSAPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jbyteArray modulusBytes) {
JNI_TRACE("getRSAPrivateKeyWrapper(%p, %p)", javaKey, modulusBytes);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
RSA_set_method(rsa.get(), &android_rsa_method);
if (!arrayToBignum(env, modulusBytes, &rsa->n)) {
return 0;
}
RSA_set_app_data(rsa.get(), env->NewGlobalRef(javaKey));
#else
size_t cached_size;
if (!arrayToBignumSize(env, modulusBytes, &cached_size)) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
return 0;
}
ensure_engine_globals();
Unique_RSA rsa(RSA_new_method(g_engine));
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
ex_data->cached_size = cached_size;
RSA_set_ex_data(rsa.get(), g_rsa_exdata_index, ex_data);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getRSAPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "getRSAPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getECPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jobject groupRef) {
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("getECPrivateKeyWrapper(%p, %p)", javaKey, group);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_EC_KEY ecKey(EC_KEY_new());
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
EC_KEY_set_group(ecKey.get(), group);
ECDSA_set_method(ecKey.get(), &android_ecdsa_method);
ECDSA_set_ex_data(ecKey.get(), EcdsaGetExDataIndex(), env->NewGlobalRef(javaKey));
#else
ensure_engine_globals();
Unique_EC_KEY ecKey(EC_KEY_new_method(g_engine));
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
BIGNUM order;
BN_init(&order);
if (!EC_GROUP_get_order(group, &order, NULL)) {
BN_free(&order);
jniThrowRuntimeException(env, "EC_GROUP_get_order failed");
return 0;
}
ex_data->cached_size = BN_num_bytes(&order);
BN_free(&order);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getECPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getECPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), ecKey.get()) != 1) {
jniThrowRuntimeException(env, "getECPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(ecKey);
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native int RSA_generate_key(int modulusBits, byte[] publicExponent);
*/
static jlong NativeCrypto_RSA_generate_key_ex(JNIEnv* env, jclass, jint modulusBits,
jbyteArray publicExponent) {
JNI_TRACE("RSA_generate_key_ex(%d, %p)", modulusBits, publicExponent);
BIGNUM* eRef = NULL;
if (!arrayToBignum(env, publicExponent, &eRef)) {
return 0;
}
Unique_BIGNUM e(eRef);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
if (RSA_generate_key_ex(rsa.get(), modulusBits, e.get(), NULL) < 0) {
throwExceptionIfNecessary(env, "RSA_generate_key_ex");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("RSA_generate_key_ex(n=%d, e=%p) => %p", modulusBits, publicExponent, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jint NativeCrypto_RSA_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("RSA_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_size failed");
return 0;
}
return static_cast<jint>(RSA_size(rsa.get()));
}
typedef int RSACryptOperation(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
int padding);
static jint RSA_crypt_operation(RSACryptOperation operation,
const char* caller __attribute__ ((unused)), JNIEnv* env, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("%s(%d, %p, %p, %p)", caller, flen, fromJavaBytes, toJavaBytes, pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return -1;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
return -1;
}
ScopedByteArrayRO from(env, fromJavaBytes);
if (from.get() == NULL) {
return -1;
}
ScopedByteArrayRW to(env, toJavaBytes);
if (to.get() == NULL) {
return -1;
}
int resultSize = operation(static_cast<int>(flen),
reinterpret_cast<const unsigned char*>(from.get()),
reinterpret_cast<unsigned char*>(to.get()), rsa.get(), padding);
if (resultSize == -1) {
JNI_TRACE("%s => failed", caller);
throwExceptionIfNecessary(env, "RSA_crypt_operation");
return -1;
}
JNI_TRACE("%s(%d, %p, %p, %p) => %d", caller, flen, fromJavaBytes, toJavaBytes, pkey,
resultSize);
return static_cast<jint>(resultSize);
}
static jint NativeCrypto_RSA_private_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_private_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
/*
* public static native byte[][] get_RSA_public_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_public_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
return joa;
}
/*
* public static native byte[][] get_RSA_private_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_private_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(8, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
if (rsa->e != NULL) {
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
}
if (rsa->d != NULL) {
jbyteArray d = bignumToArray(env, rsa->d, "d");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, d);
}
if (rsa->p != NULL) {
jbyteArray p = bignumToArray(env, rsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, p);
}
if (rsa->q != NULL) {
jbyteArray q = bignumToArray(env, rsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, q);
}
if (rsa->dmp1 != NULL) {
jbyteArray dmp1 = bignumToArray(env, rsa->dmp1, "dmp1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 5, dmp1);
}
if (rsa->dmq1 != NULL) {
jbyteArray dmq1 = bignumToArray(env, rsa->dmq1, "dmq1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 6, dmq1);
}
if (rsa->iqmp != NULL) {
jbyteArray iqmp = bignumToArray(env, rsa->iqmp, "iqmp");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 7, iqmp);
}
return joa;
}
static jlong NativeCrypto_DH_generate_parameters_ex(JNIEnv* env, jclass, jint primeBits, jlong generator) {
JNI_TRACE("DH_generate_parameters_ex(%d, %lld)", primeBits, (long long) generator);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowOutOfMemory(env, "Unable to allocate DH key");
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("DH_generate_parameters_ex generating parameters");
if (!DH_generate_parameters_ex(dh.get(), primeBits, generator, NULL)) {
JNI_TRACE("DH_generate_parameters_ex => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowRuntimeException(env, "NativeCrypto_DH_generate_parameters_ex failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
JNI_TRACE("DH_generate_parameters_ex failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("DH_generate_parameters_ex(n=%d, g=%lld) => %p", primeBits, (long long) generator,
pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static void NativeCrypto_DH_generate_key(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("DH_generate_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "Unable to get DH key");
freeOpenSslErrorState();
}
if (!DH_generate_key(dh.get())) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
}
}
static jobjectArray NativeCrypto_get_DH_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_DH_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
throwExceptionIfNecessary(env, "get_DH_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(4, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dh->p != NULL) {
jbyteArray p = bignumToArray(env, dh->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, p);
}
if (dh->g != NULL) {
jbyteArray g = bignumToArray(env, dh->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, g);
}
if (dh->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dh->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, pub_key);
}
if (dh->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dh->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, priv_key);
}
return joa;
}
#define EC_CURVE_GFP 1
#define EC_CURVE_GF2M 2
/**
* Return group type or 0 if unknown group.
* EC_GROUP_GFP or EC_GROUP_GF2M
*/
static int get_EC_GROUP_type(const EC_GROUP* group)
{
#if !defined(OPENSSL_IS_BORINGSSL)
const EC_METHOD* method = EC_GROUP_method_of(group);
if (method == EC_GFp_nist_method()
|| method == EC_GFp_mont_method()
|| method == EC_GFp_simple_method()) {
return EC_CURVE_GFP;
} else if (method == EC_GF2m_simple_method()) {
return EC_CURVE_GF2M;
}
return 0;
#else
return EC_CURVE_GFP;
#endif
}
static jlong NativeCrypto_EC_GROUP_new_by_curve_name(JNIEnv* env, jclass, jstring curveNameJava)
{
JNI_TRACE("EC_GROUP_new_by_curve_name(%p)", curveNameJava);
ScopedUtfChars curveName(env, curveNameJava);
if (curveName.c_str() == NULL) {
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s)", curveName.c_str());
int nid = OBJ_sn2nid(curveName.c_str());
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID name", curveName.c_str());
return 0;
}
EC_GROUP* group = EC_GROUP_new_by_curve_name(nid);
if (group == NULL) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID %d", curveName.c_str(), nid);
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => %p", curveName.c_str(), group);
return reinterpret_cast<uintptr_t>(group);
}
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv* env, jclass, jobject groupRef,
jint flag)
{
#if !defined(OPENSSL_IS_BORINGSSL)
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d)", group, flag);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_asn1_flag => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_asn1_flag(group, flag);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d) => success", group, flag);
#endif
}
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv* env, jclass,
jobject groupRef, jint form)
{
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d)", group, form);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_point_conversion_form => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_point_conversion_form(group, static_cast<point_conversion_form_t>(form));
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d) => success", group, form);
}
static jstring NativeCrypto_EC_GROUP_get_curve_name(JNIEnv* env, jclass, jobject groupRef) {
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
int nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_get_curve_name(%p) => unnamed curve", group);
return NULL;
}
const char* shortName = OBJ_nid2sn(nid);
JNI_TRACE("EC_GROUP_get_curve_name(%p) => \"%s\"", group, shortName);
return env->NewStringUTF(shortName);
}
static jobjectArray NativeCrypto_EC_GROUP_get_curve(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve(%p)", group);
Unique_BIGNUM p(BN_new());
Unique_BIGNUM a(BN_new());
Unique_BIGNUM b(BN_new());
if (get_EC_GROUP_type(group) != EC_CURVE_GFP) {
jniThrowRuntimeException(env, "invalid group");
return NULL;
}
int ret = EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), (BN_CTX*) NULL);
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_GROUP_get_curve");
return NULL;
}
jobjectArray joa = env->NewObjectArray(3, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray pArray = bignumToArray(env, p.get(), "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, pArray);
jbyteArray aArray = bignumToArray(env, a.get(), "a");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, aArray);
jbyteArray bArray = bignumToArray(env, b.get(), "b");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, bArray);
JNI_TRACE("EC_GROUP_get_curve(%p) => %p", group, joa);
return joa;
}
static jbyteArray NativeCrypto_EC_GROUP_get_order(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_order(%p)", group);
Unique_BIGNUM order(BN_new());
if (order.get() == NULL) {
JNI_TRACE("EC_GROUP_get_order(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_order(group, order.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_order(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_order");
return NULL;
}
jbyteArray orderArray = bignumToArray(env, order.get(), "order");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_order(%p) => %p", group, orderArray);
return orderArray;
}
static jint NativeCrypto_EC_GROUP_get_degree(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_degree(%p)", group);
jint degree = EC_GROUP_get_degree(group);
if (degree == 0) {
JNI_TRACE("EC_GROUP_get_degree(%p) => unsupported", group);
jniThrowRuntimeException(env, "not supported");
return 0;
}
JNI_TRACE("EC_GROUP_get_degree(%p) => %d", group, degree);
return degree;
}
static jbyteArray NativeCrypto_EC_GROUP_get_cofactor(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_cofactor(%p)", group);
Unique_BIGNUM cofactor(BN_new());
if (cofactor.get() == NULL) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_cofactor(group, cofactor.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_cofactor");
return NULL;
}
jbyteArray cofactorArray = bignumToArray(env, cofactor.get(), "cofactor");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_cofactor(%p) => %p", group, cofactorArray);
return cofactorArray;
}
static jint NativeCrypto_get_EC_GROUP_type(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("get_EC_GROUP_type(%p)", group);
int type = get_EC_GROUP_type(group);
if (type == 0) {
JNI_TRACE("get_EC_GROUP_type(%p) => curve type", group);
jniThrowRuntimeException(env, "unknown curve type");
} else {
JNI_TRACE("get_EC_GROUP_type(%p) => %d", group, type);
}
return type;
}
static void NativeCrypto_EC_GROUP_clear_free(JNIEnv* env, jclass, jlong groupRef)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_free(group);
JNI_TRACE("EC_GROUP_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_GROUP_cmp(JNIEnv* env, jclass, jobject group1Ref,
jobject group2Ref)
{
const EC_GROUP* group1 = fromContextObject<EC_GROUP>(env, group1Ref);
const EC_GROUP* group2 = fromContextObject<EC_GROUP>(env, group2Ref);
JNI_TRACE("EC_GROUP_cmp(%p, %p)", group1, group2);
if (group1 == NULL || group2 == NULL) {
JNI_TRACE("EC_GROUP_cmp(%p, %p) => group1 == null || group2 == null", group1, group2);
jniThrowNullPointerException(env, "group1 == null || group2 == null");
return false;
}
#if !defined(OPENSSL_IS_BORINGSSL)
int ret = EC_GROUP_cmp(group1, group2, NULL);
#else
int ret = EC_GROUP_cmp(group1, group2);
#endif
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", group1, group2, ret);
return ret == 0;
}
static jlong NativeCrypto_EC_GROUP_get_generator(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_generator(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_get_generator(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
const EC_POINT* generator = EC_GROUP_get0_generator(group);
Unique_EC_POINT dup(EC_POINT_dup(generator, group));
if (dup.get() == NULL) {
JNI_TRACE("EC_GROUP_get_generator(%p) => oom error", group);
jniThrowOutOfMemory(env, "unable to dupe generator");
return 0;
}
JNI_TRACE("EC_GROUP_get_generator(%p) => %p", group, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static jlong NativeCrypto_EC_POINT_new(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_POINT_new(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_new(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
EC_POINT* point = EC_POINT_new(group);
if (point == NULL) {
jniThrowOutOfMemory(env, "Unable create an EC_POINT");
return 0;
}
return reinterpret_cast<uintptr_t>(point);
}
static void NativeCrypto_EC_POINT_clear_free(JNIEnv* env, jclass, jlong groupRef) {
EC_POINT* group = reinterpret_cast<EC_POINT*>(groupRef);
JNI_TRACE("EC_POINT_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_POINT_free(group);
JNI_TRACE("EC_POINT_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_POINT_cmp(JNIEnv* env, jclass, jobject groupRef, jobject point1Ref,
jobject point2Ref)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
const EC_POINT* point1 = fromContextObject<EC_POINT>(env, point1Ref);
const EC_POINT* point2 = fromContextObject<EC_POINT>(env, point2Ref);
JNI_TRACE("EC_POINT_cmp(%p, %p, %p)", group, point1, point2);
if (group == NULL || point1 == NULL || point2 == NULL) {
JNI_TRACE("EC_POINT_cmp(%p, %p, %p) => group == null || point1 == null || point2 == null",
group, point1, point2);
jniThrowNullPointerException(env, "group == null || point1 == null || point2 == null");
return false;
}
int ret = EC_POINT_cmp(group, point1, point2, (BN_CTX*)NULL);
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", point1, point2, ret);
return ret == 0;
}
static void NativeCrypto_EC_POINT_set_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef, jbyteArray xjavaBytes, jbyteArray yjavaBytes)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p)", group, point, xjavaBytes,
yjavaBytes);
if (group == NULL || point == NULL) {
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => group == null || point == null",
group, point, xjavaBytes, yjavaBytes);
jniThrowNullPointerException(env, "group == null || point == null");
return;
}
BIGNUM* xRef = NULL;
if (!arrayToBignum(env, xjavaBytes, &xRef)) {
return;
}
Unique_BIGNUM x(xRef);
BIGNUM* yRef = NULL;
if (!arrayToBignum(env, yjavaBytes, &yRef)) {
return;
}
Unique_BIGNUM y(yRef);
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_set_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
#if !defined(OPENSSL_IS_BORINGSSL)
case EC_CURVE_GF2M:
ret = EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
#endif
default:
jniThrowRuntimeException(env, "invalid curve type");
return;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates");
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => %d", group, point,
xjavaBytes, yjavaBytes, ret);
}
static jobjectArray NativeCrypto_EC_POINT_get_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
const EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
Unique_BIGNUM x(BN_new());
Unique_BIGNUM y(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_get_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return NULL;
}
if (ret != 1) {
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
throwExceptionIfNecessary(env, "EC_POINT_get_affine_coordinates");
return NULL;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray xBytes = bignumToArray(env, x.get(), "x");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, xBytes);
jbyteArray yBytes = bignumToArray(env, y.get(), "y");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, yBytes);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) => %p", group, point, joa);
return joa;
}
static jlong NativeCrypto_EC_KEY_generate_key(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_KEY_generate_key(%p)", group);
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_new() oom", group);
jniThrowOutOfMemory(env, "Unable to create an EC_KEY");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_set_group error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (EC_KEY_generate_key(eckey.get()) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_generate_key error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_KEY_generate_key");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EC_KEY_generate_key(%p) => %p", group, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EC_KEY_get1_group(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get1_group(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("EC_KEY_get1_group(%p) => pkey == null", pkey);
return 0;
}
if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
jniThrowRuntimeException(env, "not EC key");
JNI_TRACE("EC_KEY_get1_group(%p) => not EC key (type == %d)", pkey,
EVP_PKEY_type(pkey->type));
return 0;
}
EC_GROUP* group = EC_GROUP_dup(EC_KEY_get0_group(pkey->pkey.ec));
JNI_TRACE("EC_KEY_get1_group(%p) => %p", pkey, group);
return reinterpret_cast<uintptr_t>(group);
}
static jbyteArray NativeCrypto_EC_KEY_get_private_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_private_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return NULL;
}
const BIGNUM *privkey = EC_KEY_get0_private_key(eckey.get());
jbyteArray privBytes = bignumToArray(env, privkey, "privkey");
if (env->ExceptionCheck()) {
JNI_TRACE("EC_KEY_get_private_key(%p) => threw error", pkey);
return NULL;
}
JNI_TRACE("EC_KEY_get_private_key(%p) => %p", pkey, privBytes);
return privBytes;
}
static jlong NativeCrypto_EC_KEY_get_public_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_public_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return 0;
}
Unique_EC_POINT dup(EC_POINT_dup(EC_KEY_get0_public_key(eckey.get()),
EC_KEY_get0_group(eckey.get())));
if (dup.get() == NULL) {
JNI_TRACE("EC_KEY_get_public_key(%p) => can't dup public key", pkey);
jniThrowRuntimeException(env, "EC_POINT_dup");
return 0;
}
JNI_TRACE("EC_KEY_get_public_key(%p) => %p", pkey, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv* env, jclass, jobject pkeyRef,
jboolean enabled)
{
#if !defined(OPENSSL_IS_BORINGSSL)
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_set_nonce_from_hash(%p, %d)", pkey, enabled ? 1 : 0);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return;
}
EC_KEY_set_nonce_from_hash(eckey.get(), enabled ? 1 : 0);
#endif
}
static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass,
jbyteArray outArray, jint outOffset, jobject pubkeyRef, jobject privkeyRef)
{
EVP_PKEY* pubPkey = fromContextObject<EVP_PKEY>(env, pubkeyRef);
EVP_PKEY* privPkey = fromContextObject<EVP_PKEY>(env, privkeyRef);
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p)", outArray, outOffset, pubPkey, privPkey);
ScopedByteArrayRW out(env, outArray);
if (out.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) can't get output buffer",
outArray, outOffset, pubPkey, privPkey);
return -1;
}
if ((outOffset < 0) || ((size_t) outOffset >= out.size())) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
if (pubPkey == NULL) {
jniThrowNullPointerException(env, "pubPkey == null");
return -1;
}
Unique_EC_KEY pubkey(EVP_PKEY_get1_EC_KEY(pubPkey));
if (pubkey.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
const EC_POINT* pubkeyPoint = EC_KEY_get0_public_key(pubkey.get());
if (pubkeyPoint == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key point", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
if (privPkey == NULL) {
jniThrowNullPointerException(env, "privPkey == null");
return -1;
}
Unique_EC_KEY privkey(EVP_PKEY_get1_EC_KEY(privPkey));
if (privkey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY private");
return -1;
}
int outputLength = ECDH_compute_key(
&out[outOffset],
out.size() - outOffset,
pubkeyPoint,
privkey.get(),
NULL // No KDF
);
if (outputLength == -1) {
throwExceptionIfNecessary(env, "ECDH_compute_key");
return -1;
}
return outputLength;
}
static jlong NativeCrypto_EVP_MD_CTX_create(JNIEnv* env, jclass) {
JNI_TRACE_MD("EVP_MD_CTX_create()");
Unique_EVP_MD_CTX ctx(EVP_MD_CTX_create());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable create a EVP_MD_CTX");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_create() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static void NativeCrypto_EVP_MD_CTX_init(JNIEnv* env, jclass, jobject ctxRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_init(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_init(ctx);
}
}
static void NativeCrypto_EVP_MD_CTX_destroy(JNIEnv*, jclass, jlong ctxRef) {
EVP_MD_CTX* ctx = reinterpret_cast<EVP_MD_CTX*>(ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_destroy(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_destroy(ctx);
}
}
static jint NativeCrypto_EVP_MD_CTX_copy(JNIEnv* env, jclass, jobject dstCtxRef, jobject srcCtxRef) {
EVP_MD_CTX* dst_ctx = fromContextObject<EVP_MD_CTX>(env, dstCtxRef);
const EVP_MD_CTX* src_ctx = fromContextObject<EVP_MD_CTX>(env, srcCtxRef);
JNI_TRACE_MD("EVP_MD_CTX_copy(%p. %p)", dst_ctx, src_ctx);
if (src_ctx == NULL) {
return 0;
} else if (dst_ctx == NULL) {
return 0;
}
int result = EVP_MD_CTX_copy_ex(dst_ctx, src_ctx);
if (result == 0) {
jniThrowRuntimeException(env, "Unable to copy EVP_MD_CTX");
freeOpenSslErrorState();
}
JNI_TRACE_MD("EVP_MD_CTX_copy(%p, %p) => %d", dst_ctx, src_ctx, result);
return result;
}
/*
* public static native int EVP_DigestFinal(long, byte[], int)
*/
static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray hash,
jint offset) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d)", ctx, hash, offset);
if (ctx == NULL) {
return -1;
} else if (hash == NULL) {
jniThrowNullPointerException(env, "ctx == null || hash == null");
return -1;
}
ScopedByteArrayRW hashBytes(env, hash);
if (hashBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_DigestFinal_ex(ctx,
reinterpret_cast<unsigned char*>(hashBytes.get() + offset),
&bytesWritten);
if (ok == 0) {
throwExceptionIfNecessary(env, "EVP_DigestFinal");
}
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d) => %d", ctx, hash, offset, bytesWritten);
return bytesWritten;
}
static jint evpInit(JNIEnv* env, jobject evpMdCtxRef, jlong evpMdRef, const char* jniName,
int (*init_func)(EVP_MD_CTX*, const EVP_MD*, ENGINE*)) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* evp_md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE_MD("%s(%p, %p)", jniName, ctx, evp_md);
if (ctx == NULL) {
return 0;
} else if (evp_md == NULL) {
jniThrowNullPointerException(env, "evp_md == null");
return 0;
}
int ok = init_func(ctx, evp_md, NULL);
if (ok == 0) {
bool exception = throwExceptionIfNecessary(env, jniName);
if (exception) {
JNI_TRACE("%s(%p) => threw exception", jniName, evp_md);
return 0;
}
}
JNI_TRACE_MD("%s(%p, %p) => %d", jniName, ctx, evp_md, ok);
return ok;
}
static jint NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_DigestInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_SignInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_SignInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_VerifyInit", EVP_DigestInit_ex);
}
/*
* public static native int EVP_get_digestbyname(java.lang.String)
*/
static jlong NativeCrypto_EVP_get_digestbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%p)", algorithm);
if (algorithm == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s)", algorithmChars.c_str());
#if !defined(OPENSSL_IS_BORINGSSL)
const EVP_MD* evp_md = EVP_get_digestbyname(algorithmChars.c_str());
if (evp_md == NULL) {
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => %p", algorithmChars.c_str(), evp_md);
return reinterpret_cast<uintptr_t>(evp_md);
#else
const char *alg = algorithmChars.c_str();
const EVP_MD *md;
if (strcasecmp(alg, "md4") == 0) {
md = EVP_md4();
} else if (strcasecmp(alg, "md5") == 0) {
md = EVP_md5();
} else if (strcasecmp(alg, "sha1") == 0) {
md = EVP_sha1();
} else if (strcasecmp(alg, "sha224") == 0) {
md = EVP_sha224();
} else if (strcasecmp(alg, "sha256") == 0) {
md = EVP_sha256();
} else if (strcasecmp(alg, "sha384") == 0) {
md = EVP_sha384();
} else if (strcasecmp(alg, "sha512") == 0) {
md = EVP_sha512();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
return reinterpret_cast<uintptr_t>(md);
#endif
}
/*
* public static native int EVP_MD_size(long)
*/
static jint NativeCrypto_EVP_MD_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p) => %d", evp_md, result);
return result;
}
/*
* public static int void EVP_MD_block_size(long)
*/
static jint NativeCrypto_EVP_MD_block_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_block_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p) => %d", evp_md, result);
return result;
}
static void NativeCrypto_EVP_DigestSignInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jobject pkeyRef) {
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p)", mdCtx, md, pkey);
if (mdCtx == NULL) {
return;
}
if (md == NULL) {
jniThrowNullPointerException(env, "md == null");
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
if (EVP_DigestSignInit(mdCtx, (EVP_PKEY_CTX **) NULL, md, (ENGINE *) NULL, pkey) <= 0) {
JNI_TRACE("ctx=%p EVP_DigestSignInit => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignInit");
return;
}
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p) => success", mdCtx, md, pkey);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jbyteArray inJavaBytes, jint inOffset,
jint inLength, const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *,
size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE_MD("%s(%p, %p, %d, %d)", jniName, mdCtx, inJavaBytes, inOffset, inLength);
if (mdCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inJavaBytes);
if (inBytes.get() == NULL) {
return;
}
if (inOffset < 0 || size_t(inOffset) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inOffset");
return;
}
const ssize_t inEnd = inOffset + inLength;
if (inLength < 0 || inEnd < 0 || size_t(inEnd) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inLength");
return;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char *>(inBytes.get());
if (!update_func(mdCtx, tmp + inOffset, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d, %d) => success", jniName, mdCtx, inJavaBytes, inOffset, inLength);
}
static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestSignUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_SignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_SignUpdate",
EVP_DigestUpdate);
}
static jbyteArray NativeCrypto_EVP_DigestSignFinal(JNIEnv* env, jclass, jobject evpMdCtxRef)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestSignFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return NULL;
}
size_t len;
if (EVP_DigestSignFinal(mdCtx, NULL, &len) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return 0;
}
ScopedLocalRef<jbyteArray> outJavaBytes(env, env->NewByteArray(len));
if (outJavaBytes.get() == NULL) {
return NULL;
}
ScopedByteArrayRW outBytes(env, outJavaBytes.get());
if (outBytes.get() == NULL) {
return NULL;
}
unsigned char *tmp = reinterpret_cast<unsigned char*>(outBytes.get());
if (EVP_DigestSignFinal(mdCtx, tmp, &len) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return 0;
}
JNI_TRACE("EVP_DigestSignFinal(%p) => %p", mdCtx, outJavaBytes.get());
return outJavaBytes.release();
}
/*
* public static native int EVP_SignFinal(long, byte[], int, long)
*/
static jint NativeCrypto_EVP_SignFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray signature,
jint offset, jobject pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p)", ctx, signature, offset, pkey);
if (ctx == NULL) {
return -1;
} else if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRW signatureBytes(env, signature);
if (signatureBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_SignFinal(ctx,
reinterpret_cast<unsigned char*>(signatureBytes.get() + offset),
&bytesWritten,
pkey);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_SignFinal");
}
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p) => %u",
ctx, signature, offset, pkey, bytesWritten);
return bytesWritten;
}
/*
* public static native void EVP_VerifyUpdate(long, byte[], int, int)
*/
static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray buffer, jint offset, jint length) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE("NativeCrypto_EVP_VerifyUpdate(%p, %p, %d, %d)", ctx, buffer, offset, length);
if (ctx == NULL) {
return;
} else if (buffer == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return;
}
if (bufferBytes.size() < static_cast<size_t>(offset + length)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
int ok = EVP_VerifyUpdate(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyUpdate");
}
}
/*
* public static native int EVP_VerifyFinal(long, byte[], int, int, long)
*/
static jint NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray buffer,
jint offset, jint length, jobject pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p)",
ctx, buffer, offset, length, pkey);
if (ctx == NULL) {
return -1;
} else if (buffer == NULL || pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return -1;
}
int ok = EVP_VerifyFinal(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length,
pkey);
if (ok < 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyFinal");
}
/*
* For DSA keys, OpenSSL appears to have a bug where it returns
* errors for any result != 1. See dsa_ossl.c in dsa_do_verify
*/
freeOpenSslErrorState();
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p) => %d",
ctx, buffer, offset, length, pkey, ok);
return ok;
}
static jlong NativeCrypto_EVP_get_cipherbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("EVP_get_cipherbyname(%p)", algorithm);
#if !defined(OPENSSL_IS_BORINGSSL)
if (algorithm == NULL) {
JNI_TRACE("EVP_get_cipherbyname(%p) => threw exception algorithm == null", algorithm);
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("EVP_get_cipherbyname(%p) => algorithm = %s", algorithm, algorithmChars.c_str());
const EVP_CIPHER* evp_cipher = EVP_get_cipherbyname(algorithmChars.c_str());
if (evp_cipher == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("EVP_get_cipherbyname(%s) => %p", algorithmChars.c_str(), evp_cipher);
return reinterpret_cast<uintptr_t>(evp_cipher);
#else
ScopedUtfChars scoped_alg(env, algorithm);
const char *alg = scoped_alg.c_str();
const EVP_CIPHER *cipher;
if (strcasecmp(alg, "rc4") == 0) {
cipher = EVP_rc4();
} else if (strcasecmp(alg, "des-cbc") == 0) {
cipher = EVP_des_cbc();
} else if (strcasecmp(alg, "des-ede3-cbc") == 0) {
cipher = EVP_des_ede3_cbc();
} else if (strcasecmp(alg, "aes-128-ecb") == 0) {
cipher = EVP_aes_128_ecb();
} else if (strcasecmp(alg, "aes-128-cbc") == 0) {
cipher = EVP_aes_128_cbc();
} else if (strcasecmp(alg, "aes-128-ctr") == 0) {
cipher = EVP_aes_128_ctr();
} else if (strcasecmp(alg, "aes-128-gcm") == 0) {
cipher = EVP_aes_128_gcm();
} else if (strcasecmp(alg, "aes-256-ecb") == 0) {
cipher = EVP_aes_256_ecb();
} else if (strcasecmp(alg, "aes-256-cbc") == 0) {
cipher = EVP_aes_256_cbc();
} else if (strcasecmp(alg, "aes-256-ctr") == 0) {
cipher = EVP_aes_256_ctr();
} else if (strcasecmp(alg, "aes-256-gcm") == 0) {
cipher = EVP_aes_256_gcm();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
return reinterpret_cast<uintptr_t>(cipher);
#endif
}
static void NativeCrypto_EVP_CipherInit_ex(JNIEnv* env, jclass, jobject ctxRef, jlong evpCipherRef,
jbyteArray keyArray, jbyteArray ivArray, jboolean encrypting) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d)", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("EVP_CipherUpdate => ctx == null");
return;
}
// The key can be null if we need to set extra parameters.
UniquePtr<unsigned char[]> keyPtr;
if (keyArray != NULL) {
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
keyPtr.reset(new unsigned char[keyBytes.size()]);
memcpy(keyPtr.get(), keyBytes.get(), keyBytes.size());
}
// The IV can be null if we're using ECB.
UniquePtr<unsigned char[]> ivPtr;
if (ivArray != NULL) {
ScopedByteArrayRO ivBytes(env, ivArray);
if (ivBytes.get() == NULL) {
return;
}
ivPtr.reset(new unsigned char[ivBytes.size()]);
memcpy(ivPtr.get(), ivBytes.get(), ivBytes.size());
}
if (!EVP_CipherInit_ex(ctx, evpCipher, NULL, keyPtr.get(), ivPtr.get(), encrypting ? 1 : 0)) {
throwExceptionIfNecessary(env, "EVP_CipherInit_ex");
JNI_TRACE("EVP_CipherInit_ex => error initializing cipher");
return;
}
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d) => success", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
}
/*
* public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
* int inOffset, int inLength);
*/
static jint NativeCrypto_EVP_CipherUpdate(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray inArray, jint inOffset, jint inLength) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d)", ctx, outArray, outOffset, inArray, inOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherUpdate => ctx == null", ctx);
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
const size_t inSize = inBytes.size();
if (size_t(inOffset + inLength) > inSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"in.length < (inSize + inOffset)");
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
const size_t outSize = outBytes.size();
if (size_t(outOffset + inLength) > outSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"out.length < inSize + outOffset + blockSize - 1");
return 0;
}
JNI_TRACE("ctx=%p EVP_CipherUpdate in=%p in.length=%zd inOffset=%zd inLength=%zd out=%p out.length=%zd outOffset=%zd",
ctx, inBytes.get(), inBytes.size(), inOffset, inLength, outBytes.get(), outBytes.size(), outOffset);
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
const unsigned char* in = reinterpret_cast<const unsigned char*>(inBytes.get());
int outl;
if (!EVP_CipherUpdate(ctx, out + outOffset, &outl, in + inOffset, inLength)) {
throwExceptionIfNecessary(env, "EVP_CipherUpdate");
JNI_TRACE("ctx=%p EVP_CipherUpdate => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d) => %d", ctx, outArray, outOffset, inArray,
inOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CipherFinal_ex(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray outArray, jint outOffset) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherFinal_ex(%p, %p, %d)", ctx, outArray, outOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => ctx == null", ctx);
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
int outl;
if (!EVP_CipherFinal_ex(ctx, out + outOffset, &outl)) {
throwExceptionIfNecessary(env, "EVP_CipherFinal_ex");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherFinal(%p, %p, %d) => %d", ctx, outArray, outOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CIPHER_iv_length(JNIEnv* env, jclass, jlong evpCipherRef) {
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CIPHER_iv_length(%p)", evpCipher);
if (evpCipher == NULL) {
jniThrowNullPointerException(env, "evpCipher == null");
JNI_TRACE("EVP_CIPHER_iv_length => evpCipher == null");
return 0;
}
const int ivLength = EVP_CIPHER_iv_length(evpCipher);
JNI_TRACE("EVP_CIPHER_iv_length(%p) => %d", evpCipher, ivLength);
return ivLength;
}
static jlong NativeCrypto_EVP_CIPHER_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("EVP_CIPHER_CTX_new()");
Unique_EVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate cipher context");
JNI_TRACE("EVP_CipherInit_ex => context allocation error");
return 0;
}
JNI_TRACE("EVP_CIPHER_CTX_new() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static jint NativeCrypto_EVP_CIPHER_CTX_block_size(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_block_size => ctx == null", ctx);
return 0;
}
int blockSize = EVP_CIPHER_CTX_block_size(ctx);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p) => %d", ctx, blockSize);
return blockSize;
}
static jint NativeCrypto_get_EVP_CIPHER_CTX_buf_len(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_buf_len => ctx == null", ctx);
return 0;
}
int buf_len = ctx->buf_len;
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p) => %d", ctx, buf_len);
return buf_len;
}
static void NativeCrypto_EVP_CIPHER_CTX_set_padding(JNIEnv* env, jclass, jobject ctxRef,
jboolean enablePaddingBool) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
jint enablePadding = enablePaddingBool ? 1 : 0;
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d)", ctx, enablePadding);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_padding => ctx == null", ctx);
return;
}
EVP_CIPHER_CTX_set_padding(ctx, enablePadding); // Not void, but always returns 1.
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d) => success", ctx, enablePadding);
}
static void NativeCrypto_EVP_CIPHER_CTX_set_key_length(JNIEnv* env, jclass, jobject ctxRef,
jint keySizeBits) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d)", ctx, keySizeBits);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_key_length => ctx == null", ctx);
return;
}
if (!EVP_CIPHER_CTX_set_key_length(ctx, keySizeBits)) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_CIPHER_CTX_set_key_length");
JNI_TRACE("NativeCrypto_EVP_CIPHER_CTX_set_key_length => threw error");
return;
}
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d) => success", ctx, keySizeBits);
}
static void NativeCrypto_EVP_CIPHER_CTX_cleanup(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p)", ctx);
if (ctx != NULL) {
if (!EVP_CIPHER_CTX_cleanup(ctx)) {
throwExceptionIfNecessary(env, "EVP_CIPHER_CTX_cleanup");
JNI_TRACE("EVP_CIPHER_CTX_cleanup => threw error");
return;
}
}
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p) => success", ctx);
}
/**
* public static native void RAND_seed(byte[]);
*/
static void NativeCrypto_RAND_seed(JNIEnv* env, jclass, jbyteArray seed) {
JNI_TRACE("NativeCrypto_RAND_seed seed=%p", seed);
#if !defined(OPENSSL_IS_BORINGSSL)
ScopedByteArrayRO randseed(env, seed);
if (randseed.get() == NULL) {
return;
}
RAND_seed(randseed.get(), randseed.size());
#else
return;
#endif
}
static jint NativeCrypto_RAND_load_file(JNIEnv* env, jclass, jstring filename, jlong max_bytes) {
JNI_TRACE("NativeCrypto_RAND_load_file filename=%p max_bytes=%lld", filename, (long long) max_bytes);
#if !defined(OPENSSL_IS_BORINGSSL)
ScopedUtfChars file(env, filename);
if (file.c_str() == NULL) {
return -1;
}
int result = RAND_load_file(file.c_str(), max_bytes);
JNI_TRACE("NativeCrypto_RAND_load_file file=%s => %d", file.c_str(), result);
return result;
#else
// OpenSSLRandom calls this and checks the return value.
return static_cast<jint>(max_bytes);
#endif
}
static void NativeCrypto_RAND_bytes(JNIEnv* env, jclass, jbyteArray output) {
JNI_TRACE("NativeCrypto_RAND_bytes(%p)", output);
ScopedByteArrayRW outputBytes(env, output);
if (outputBytes.get() == NULL) {
return;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(outputBytes.get());
if (RAND_bytes(tmp, outputBytes.size()) <= 0) {
throwExceptionIfNecessary(env, "NativeCrypto_RAND_bytes");
JNI_TRACE("tmp=%p NativeCrypto_RAND_bytes => threw error", tmp);
return;
}
JNI_TRACE("NativeCrypto_RAND_bytes(%p) => success", output);
}
static jint NativeCrypto_OBJ_txt2nid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return 0;
}
int nid = OBJ_txt2nid(oid.c_str());
JNI_TRACE("OBJ_txt2nid(%s) => %d", oid.c_str(), nid);
return nid;
}
static jstring NativeCrypto_OBJ_txt2nid_longName(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_longName(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_longName(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_longName(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const char* longName = OBJ_nid2ln(nid);
JNI_TRACE("OBJ_txt2nid_longName(%s) => %s", oid.c_str(), longName);
return env->NewStringUTF(longName);
}
static jstring ASN1_OBJECT_to_OID_string(JNIEnv* env, const ASN1_OBJECT* obj) {
/*
* The OBJ_obj2txt API doesn't "measure" if you pass in NULL as the buffer.
* Just make a buffer that's large enough here. The documentation recommends
* 80 characters.
*/
char output[128];
int ret = OBJ_obj2txt(output, sizeof(output), obj, 1);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1_OBJECT_to_OID_string");
return NULL;
} else if (size_t(ret) >= sizeof(output)) {
jniThrowRuntimeException(env, "ASN1_OBJECT_to_OID_string buffer too small");
return NULL;
}
JNI_TRACE("ASN1_OBJECT_to_OID_string(%p) => %s", obj, output);
return env->NewStringUTF(output);
}
static jlong NativeCrypto_create_BIO_InputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_InputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_InputStream(streamObj));
JNI_TRACE("create_BIO_InputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static jlong NativeCrypto_create_BIO_OutputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_OutputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_OutputStream(streamObj));
JNI_TRACE("create_BIO_OutputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static int NativeCrypto_BIO_read(JNIEnv* env, jclass, jlong bioRef, jbyteArray outputJavaBytes) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_read(%p, %p)", bio, outputJavaBytes);
if (outputJavaBytes == NULL) {
jniThrowNullPointerException(env, "output == null");
JNI_TRACE("BIO_read(%p, %p) => output == null", bio, outputJavaBytes);
return 0;
}
int outputSize = env->GetArrayLength(outputJavaBytes);
UniquePtr<unsigned char[]> buffer(new unsigned char[outputSize]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for read");
return 0;
}
int read = BIO_read(bio, buffer.get(), outputSize);
if (read <= 0) {
jniThrowException(env, "java/io/IOException", "BIO_read");
JNI_TRACE("BIO_read(%p, %p) => threw IO exception", bio, outputJavaBytes);
return 0;
}
env->SetByteArrayRegion(outputJavaBytes, 0, read, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("BIO_read(%p, %p) => %d", bio, outputJavaBytes, read);
return read;
}
static void NativeCrypto_BIO_write(JNIEnv* env, jclass, jlong bioRef, jbyteArray inputJavaBytes,
jint offset, jint length) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_write(%p, %p, %d, %d)", bio, inputJavaBytes, offset, length);
if (inputJavaBytes == NULL) {
jniThrowNullPointerException(env, "input == null");
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "offset < 0 || length < 0");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
int inputSize = env->GetArrayLength(inputJavaBytes);
if (inputSize < offset + length) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"input.length < offset + length");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[length]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for write");
return;
}
env->GetByteArrayRegion(inputJavaBytes, offset, length, reinterpret_cast<jbyte*>(buffer.get()));
if (BIO_write(bio, buffer.get(), length) != length) {
freeOpenSslErrorState();
jniThrowException(env, "java/io/IOException", "BIO_write");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IO error", bio, inputJavaBytes, offset, length);
return;
}
JNI_TRACE("BIO_write(%p, %p, %d, %d) => success", bio, inputJavaBytes, offset, length);
}
static void NativeCrypto_BIO_free_all(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_free_all(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return;
}
BIO_free_all(bio);
}
static jstring X509_NAME_to_jstring(JNIEnv* env, X509_NAME* name, unsigned long flags) {
JNI_TRACE("X509_NAME_to_jstring(%p)", name);
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
JNI_TRACE("X509_NAME_to_jstring(%p) => threw error", name);
return NULL;
}
/* Don't interpret the string. */
flags &= ~(ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_ESC_MSB);
/* Write in given format and null terminate. */
X509_NAME_print_ex(buffer.get(), name, 0, flags);
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
JNI_TRACE("X509_NAME_to_jstring(%p) => \"%s\"", name, tmp);
return env->NewStringUTF(tmp);
}
/**
* Converts GENERAL_NAME items to the output format expected in
* X509Certificate#getSubjectAlternativeNames and
* X509Certificate#getIssuerAlternativeNames return.
*/
static jobject GENERAL_NAME_to_jobject(JNIEnv* env, GENERAL_NAME* gen) {
switch (gen->type) {
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI: {
// This must not be a T61String and must not contain NULLs.
const char* data = reinterpret_cast<const char*>(ASN1_STRING_data(gen->d.ia5));
ssize_t len = ASN1_STRING_length(gen->d.ia5);
if ((len == static_cast<ssize_t>(strlen(data)))
&& (ASN1_PRINTABLE_type(ASN1_STRING_data(gen->d.ia5), len) != V_ASN1_T61STRING)) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI \"%s\"", gen, data);
return env->NewStringUTF(data);
} else {
jniThrowException(env, "java/security/cert/CertificateParsingException",
"Invalid dNSName encoding");
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI invalid", gen);
return NULL;
}
}
case GEN_DIRNAME:
/* Write in RFC 2253 format */
return X509_NAME_to_jstring(env, gen->d.directoryName, XN_FLAG_RFC2253);
case GEN_IPADD: {
const void *ip = reinterpret_cast<const void *>(gen->d.ip->data);
if (gen->d.ip->length == 4) {
// IPv4
UniquePtr<char[]> buffer(new char[INET_ADDRSTRLEN]);
if (inet_ntop(AF_INET, ip, buffer.get(), INET_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 failed %s", gen, strerror(errno));
}
} else if (gen->d.ip->length == 16) {
// IPv6
UniquePtr<char[]> buffer(new char[INET6_ADDRSTRLEN]);
if (inet_ntop(AF_INET6, ip, buffer.get(), INET6_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 failed %s", gen, strerror(errno));
}
}
/* Invalid IP encodings are pruned out without throwing an exception. */
return NULL;
}
case GEN_RID:
return ASN1_OBJECT_to_OID_string(env, gen->d.registeredID);
case GEN_OTHERNAME:
case GEN_X400:
default:
return ASN1ToByteArray<GENERAL_NAME>(env, gen, i2d_GENERAL_NAME);
}
return NULL;
}
#define GN_STACK_SUBJECT_ALT_NAME 1
#define GN_STACK_ISSUER_ALT_NAME 2
static jobjectArray NativeCrypto_get_X509_GENERAL_NAME_stack(JNIEnv* env, jclass, jlong x509Ref,
jint type) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d)", x509, type);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => x509 == null", x509, type);
return NULL;
}
X509_check_ca(x509);
STACK_OF(GENERAL_NAME)* gn_stack;
Unique_sk_GENERAL_NAME stackHolder;
if (type == GN_STACK_SUBJECT_ALT_NAME) {
gn_stack = x509->altname;
} else if (type == GN_STACK_ISSUER_ALT_NAME) {
stackHolder.reset(
static_cast<STACK_OF(GENERAL_NAME)*>(X509_get_ext_d2i(x509, NID_issuer_alt_name,
NULL, NULL)));
gn_stack = stackHolder.get();
} else {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => unknown type", x509, type);
return NULL;
}
int count = sk_GENERAL_NAME_num(gn_stack);
if (count <= 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no entries)", x509, type);
return NULL;
}
/*
* Keep track of how many originally so we can ignore any invalid
* values later.
*/
const int origCount = count;
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, objectArrayClass, NULL));
for (int i = 0, j = 0; i < origCount; i++, j++) {
GENERAL_NAME* gen = sk_GENERAL_NAME_value(gn_stack, i);
ScopedLocalRef<jobject> val(env, GENERAL_NAME_to_jobject(env, gen));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => threw exception parsing gen name",
x509, type);
return NULL;
}
/*
* If it's NULL, we'll have to skip this, reduce the number of total
* entries, and fix up the array later.
*/
if (val.get() == NULL) {
j--;
count--;
continue;
}
ScopedLocalRef<jobjectArray> item(env, env->NewObjectArray(2, objectClass, NULL));
ScopedLocalRef<jobject> type(env, env->CallStaticObjectMethod(integerClass,
integer_valueOfMethod, gen->type));
env->SetObjectArrayElement(item.get(), 0, type.get());
env->SetObjectArrayElement(item.get(), 1, val.get());
env->SetObjectArrayElement(joa.get(), j, item.get());
}
if (count == 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to 0; returning NULL",
x509, type, origCount);
joa.reset(NULL);
} else if (origCount != count) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to %d", x509, type,
origCount, count);
ScopedLocalRef<jobjectArray> joa_copy(env, env->NewObjectArray(count, objectArrayClass,
NULL));
for (int i = 0; i < count; i++) {
ScopedLocalRef<jobject> item(env, env->GetObjectArrayElement(joa.get(), i));
env->SetObjectArrayElement(joa_copy.get(), i, item.get());
}
joa.reset(joa_copy.release());
}
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => %d entries", x509, type, count);
return joa.release();
}
static jlong NativeCrypto_X509_get_notBefore(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notBefore(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notBefore(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notBefore = X509_get_notBefore(x509);
JNI_TRACE("X509_get_notBefore(%p) => %p", x509, notBefore);
return reinterpret_cast<uintptr_t>(notBefore);
}
static jlong NativeCrypto_X509_get_notAfter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notAfter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notAfter(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notAfter = X509_get_notAfter(x509);
JNI_TRACE("X509_get_notAfter(%p) => %p", x509, notAfter);
return reinterpret_cast<uintptr_t>(notAfter);
}
static long NativeCrypto_X509_get_version(JNIEnv*, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_version(%p)", x509);
long version = X509_get_version(x509);
JNI_TRACE("X509_get_version(%p) => %ld", x509, version);
return version;
}
template<typename T>
static jbyteArray get_X509Type_serialNumber(JNIEnv* env, T* x509Type, ASN1_INTEGER* (*get_serial_func)(T*)) {
JNI_TRACE("get_X509Type_serialNumber(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_serialNumber(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_INTEGER* serialNumber = get_serial_func(x509Type);
Unique_BIGNUM serialBn(ASN1_INTEGER_to_BN(serialNumber, NULL));
if (serialBn.get() == NULL) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
ScopedLocalRef<jbyteArray> serialArray(env, bignumToArray(env, serialBn.get(), "serialBn"));
if (env->ExceptionCheck()) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
JNI_TRACE("X509_get_serialNumber(%p) => %p", x509Type, serialArray.get());
return serialArray.release();
}
/* OpenSSL includes set_serialNumber but not get. */
#if !defined(X509_REVOKED_get_serialNumber)
static ASN1_INTEGER* X509_REVOKED_get_serialNumber(X509_REVOKED* x) {
return x->serialNumber;
}
#endif
static jbyteArray NativeCrypto_X509_get_serialNumber(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_serialNumber(%p)", x509);
return get_X509Type_serialNumber<X509>(env, x509, X509_get_serialNumber);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_serialNumber(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_serialNumber(%p)", revoked);
return get_X509Type_serialNumber<X509_REVOKED>(env, revoked, X509_REVOKED_get_serialNumber);
}
static void NativeCrypto_X509_verify(JNIEnv* env, jclass, jlong x509Ref, jobject pkeyRef) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_verify(%p, %p)", x509, pkey);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_verify(%p, %p) => x509 == null", x509, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_verify(%p, %p) => pkey == null", x509, pkey);
return;
}
if (X509_verify(x509, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_verify");
JNI_TRACE("X509_verify(%p, %p) => verify failure", x509, pkey);
} else {
JNI_TRACE("X509_verify(%p, %p) => verify success", x509, pkey);
}
}
static jbyteArray NativeCrypto_get_X509_cert_info_enc(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_cert_info_enc(%p)", x509);
return ASN1ToByteArray<X509_CINF>(env, x509->cert_info, i2d_X509_CINF);
}
static jint NativeCrypto_get_X509_ex_flags(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_flags(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_flags(%p) => x509 == null", x509);
return 0;
}
X509_check_ca(x509);
return x509->ex_flags;
}
static jboolean NativeCrypto_X509_check_issued(JNIEnv*, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_check_issued(%p, %p)", x509_1, x509_2);
int ret = X509_check_issued(x509_1, x509_2);
JNI_TRACE("X509_check_issued(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void get_X509_signature(X509 *x509, ASN1_BIT_STRING** signature) {
*signature = x509->signature;
}
static void get_X509_CRL_signature(X509_CRL *crl, ASN1_BIT_STRING** signature) {
*signature = crl->signature;
}
template<typename T>
static jbyteArray get_X509Type_signature(JNIEnv* env, T* x509Type, void (*get_signature_func)(T*, ASN1_BIT_STRING**)) {
JNI_TRACE("get_X509Type_signature(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_signature(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_BIT_STRING* signature;
get_signature_func(x509Type, &signature);
ScopedLocalRef<jbyteArray> signatureArray(env, env->NewByteArray(signature->length));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509Type_signature(%p) => threw exception", x509Type);
return NULL;
}
ScopedByteArrayRW signatureBytes(env, signatureArray.get());
if (signatureBytes.get() == NULL) {
JNI_TRACE("get_X509Type_signature(%p) => using byte array failed", x509Type);
return NULL;
}
memcpy(signatureBytes.get(), signature->data, signature->length);
JNI_TRACE("get_X509Type_signature(%p) => %p (%d bytes)", x509Type, signatureArray.get(),
signature->length);
return signatureArray.release();
}
static jbyteArray NativeCrypto_get_X509_signature(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_signature(%p)", x509);
return get_X509Type_signature<X509>(env, x509, get_X509_signature);
}
static jbyteArray NativeCrypto_get_X509_CRL_signature(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_signature(%p)", crl);
return get_X509Type_signature<X509_CRL>(env, crl, get_X509_CRL_signature);
}
static jlong NativeCrypto_X509_CRL_get0_by_cert(JNIEnv* env, jclass, jlong x509crlRef, jlong x509Ref) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p)", x509crl, x509);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509crl == null", x509crl, x509);
return 0;
} else if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509 == null", x509crl, x509);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_cert(x509crl, &revoked, x509);
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => none", x509crl, x509);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, x509, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
static jlong NativeCrypto_X509_CRL_get0_by_serial(JNIEnv* env, jclass, jlong x509crlRef, jbyteArray serialArray) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p)", x509crl, serialArray);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => crl == null", x509crl, serialArray);
return 0;
}
Unique_BIGNUM serialBn(BN_new());
if (serialBn.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN allocation failed", x509crl, serialArray);
return 0;
}
BIGNUM* serialBare = serialBn.get();
if (!arrayToBignum(env, serialArray, &serialBare)) {
if (!env->ExceptionCheck()) {
jniThrowNullPointerException(env, "serial == null");
}
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
Unique_ASN1_INTEGER serialInteger(BN_to_ASN1_INTEGER(serialBn.get(), NULL));
if (serialInteger.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_serial(x509crl, &revoked, serialInteger.get());
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => none", x509crl, serialArray);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, serialArray, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
/* This appears to be missing from OpenSSL. */
#if !defined(X509_REVOKED_dup)
X509_REVOKED* X509_REVOKED_dup(X509_REVOKED* x) {
return reinterpret_cast<X509_REVOKED*>(ASN1_item_dup(ASN1_ITEM_rptr(X509_REVOKED), x));
}
#endif
static jlongArray NativeCrypto_X509_CRL_get_REVOKED(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_REVOKED(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
return NULL;
}
STACK_OF(X509_REVOKED)* stack = X509_CRL_get_REVOKED(crl);
if (stack == NULL) {
JNI_TRACE("X509_CRL_get_REVOKED(%p) => stack is null", crl);
return NULL;
}
size_t size = sk_X509_REVOKED_num(stack);
ScopedLocalRef<jlongArray> revokedArray(env, env->NewLongArray(size));
ScopedLongArrayRW revoked(env, revokedArray.get());
for (size_t i = 0; i < size; i++) {
X509_REVOKED* item = reinterpret_cast<X509_REVOKED*>(sk_X509_REVOKED_value(stack, i));
revoked[i] = reinterpret_cast<uintptr_t>(X509_REVOKED_dup(item));
}
JNI_TRACE("X509_CRL_get_REVOKED(%p) => %p [size=%zd]", stack, revokedArray.get(), size);
return revokedArray.release();
}
static jbyteArray NativeCrypto_i2d_X509_CRL(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("i2d_X509_CRL(%p)", crl);
return ASN1ToByteArray<X509_CRL>(env, crl, i2d_X509_CRL);
}
static void NativeCrypto_X509_CRL_free(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_free(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_free(%p) => crl == null", crl);
return;
}
X509_CRL_free(crl);
}
static void NativeCrypto_X509_CRL_print(JNIEnv* env, jclass, jlong bioRef, jlong x509CrlRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_print(%p, %p)", bio, crl);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_CRL_print(%p, %p) => bio == null", bio, crl);
return;
}
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_print(%p, %p) => crl == null", bio, crl);
return;
}
if (!X509_CRL_print(bio, crl)) {
throwExceptionIfNecessary(env, "X509_CRL_print");
JNI_TRACE("X509_CRL_print(%p, %p) => threw error", bio, crl);
} else {
JNI_TRACE("X509_CRL_print(%p, %p) => success", bio, crl);
}
}
static jstring NativeCrypto_get_X509_CRL_sig_alg_oid(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p)", crl);
if (crl == NULL || crl->sig_alg == NULL) {
jniThrowNullPointerException(env, "crl == NULL || crl->sig_alg == NULL");
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p) => crl == NULL", crl);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, crl->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_CRL_sig_alg_parameter(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => crl == null", crl);
return NULL;
}
if (crl->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => null", crl);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, crl->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbyteArray NativeCrypto_X509_CRL_get_issuer_name(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_issuer_name(%p)", crl);
return ASN1ToByteArray<X509_NAME>(env, X509_CRL_get_issuer(crl), i2d_X509_NAME);
}
static long NativeCrypto_X509_CRL_get_version(JNIEnv*, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_version(%p)", crl);
long version = X509_CRL_get_version(crl);
JNI_TRACE("X509_CRL_get_version(%p) => %ld", crl, version);
return version;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static X509_EXTENSION *X509Type_get_ext(JNIEnv* env, T* x509Type, jstring oidString) {
JNI_TRACE("X509Type_get_ext(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509 == null");
return NULL;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
return NULL;
}
Unique_ASN1_OBJECT asn1(OBJ_txt2obj(oid.c_str(), 1));
if (asn1.get() == NULL) {
JNI_TRACE("X509Type_get_ext(%p, %s) => oid conversion failed", x509Type, oid.c_str());
freeOpenSslErrorState();
return NULL;
}
int extIndex = get_ext_by_OBJ_func(x509Type, (ASN1_OBJECT*) asn1.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509Type_get_ext(%p, %s) => ext not found", x509Type, oid.c_str());
return NULL;
}
X509_EXTENSION* ext = get_ext_func(x509Type, extIndex);
JNI_TRACE("X509Type_get_ext(%p, %s) => %p", x509Type, oid.c_str(), ext);
return ext;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static jbyteArray X509Type_get_ext_oid(JNIEnv* env, T* x509Type, jstring oidString) {
X509_EXTENSION* ext = X509Type_get_ext<T, get_ext_by_OBJ_func, get_ext_func>(env, x509Type,
oidString);
if (ext == NULL) {
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => fetching extension failed", x509Type, oidString);
return NULL;
}
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => %p", x509Type, oidString, ext->value);
return ASN1ToByteArray<ASN1_OCTET_STRING>(env, ext->value, i2d_ASN1_OCTET_STRING);
}
static jint NativeCrypto_X509_CRL_get_ext(JNIEnv* env, jclass, jlong x509CrlRef, jstring oid) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext(%p, %p)", crl, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(
env, crl, oid);
JNI_TRACE("X509_CRL_get_ext(%p, %p) => %p", crl, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jint NativeCrypto_X509_REVOKED_get_ext(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oid) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext(%p, %p)", revoked, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ,
X509_REVOKED_get_ext>(env, revoked, oid);
JNI_TRACE("X509_REVOKED_get_ext(%p, %p) => %p", revoked, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_dup(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_dup(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_dup(%p) => revoked == null", revoked);
return 0;
}
X509_REVOKED* dup = X509_REVOKED_dup(revoked);
JNI_TRACE("X509_REVOKED_dup(%p) => %p", revoked, dup);
return reinterpret_cast<uintptr_t>(dup);
}
static jlong NativeCrypto_get_X509_REVOKED_revocationDate(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("get_X509_REVOKED_revocationDate(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => revoked == null", revoked);
return 0;
}
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => %p", revoked, revoked->revocationDate);
return reinterpret_cast<uintptr_t>(revoked->revocationDate);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
static void NativeCrypto_X509_REVOKED_print(JNIEnv* env, jclass, jlong bioRef, jlong x509RevokedRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_print(%p, %p)", bio, revoked);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => bio == null", bio, revoked);
return;
}
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => revoked == null", bio, revoked);
return;
}
BIO_printf(bio, "Serial Number: ");
i2a_ASN1_INTEGER(bio, revoked->serialNumber);
BIO_printf(bio, "\nRevocation Date: ");
ASN1_TIME_print(bio, revoked->revocationDate);
BIO_printf(bio, "\n");
X509V3_extensions_print(bio, "CRL entry extensions", revoked->extensions, 0, 0);
}
#pragma GCC diagnostic pop
static jbyteArray NativeCrypto_get_X509_CRL_crl_enc(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_crl_enc(%p)", crl);
return ASN1ToByteArray<X509_CRL_INFO>(env, crl->crl, i2d_X509_CRL_INFO);
}
static void NativeCrypto_X509_CRL_verify(JNIEnv* env, jclass, jlong x509CrlRef, jobject pkeyRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_CRL_verify(%p, %p)", crl, pkey);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => crl == null", crl, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => pkey == null", crl, pkey);
return;
}
if (X509_CRL_verify(crl, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_CRL_verify");
JNI_TRACE("X509_CRL_verify(%p, %p) => verify failure", crl, pkey);
} else {
JNI_TRACE("X509_CRL_verify(%p, %p) => verify success", crl, pkey);
}
}
static jlong NativeCrypto_X509_CRL_get_lastUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_lastUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* lastUpdate = X509_CRL_get_lastUpdate(crl);
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => %p", crl, lastUpdate);
return reinterpret_cast<uintptr_t>(lastUpdate);
}
static jlong NativeCrypto_X509_CRL_get_nextUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_nextUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* nextUpdate = X509_CRL_get_nextUpdate(crl);
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => %p", crl, nextUpdate);
return reinterpret_cast<uintptr_t>(nextUpdate);
}
static jbyteArray NativeCrypto_i2d_X509_REVOKED(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* x509Revoked =
reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("i2d_X509_REVOKED(%p)", x509Revoked);
return ASN1ToByteArray<X509_REVOKED>(env, x509Revoked, i2d_X509_REVOKED);
}
static jint NativeCrypto_X509_supported_extension(JNIEnv* env, jclass, jlong x509ExtensionRef) {
X509_EXTENSION* ext = reinterpret_cast<X509_EXTENSION*>(static_cast<uintptr_t>(x509ExtensionRef));
if (ext == NULL) {
jniThrowNullPointerException(env, "ext == NULL");
return 0;
}
return X509_supported_extension(ext);
}
static inline void get_ASN1_TIME_data(char **data, int* output, size_t len) {
char c = **data;
**data = '\0';
*data -= len;
*output = atoi(*data);
*(*data + len) = c;
}
static void NativeCrypto_ASN1_TIME_to_Calendar(JNIEnv* env, jclass, jlong asn1TimeRef, jobject calendar) {
ASN1_TIME* asn1Time = reinterpret_cast<ASN1_TIME*>(static_cast<uintptr_t>(asn1TimeRef));
JNI_TRACE("ASN1_TIME_to_Calendar(%p, %p)", asn1Time, calendar);
if (asn1Time == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
Unique_ASN1_GENERALIZEDTIME gen(ASN1_TIME_to_generalizedtime(asn1Time, NULL));
if (gen.get() == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
if (gen->length < 14 || gen->data == NULL) {
jniThrowNullPointerException(env, "gen->length < 14 || gen->data == NULL");
return;
}
int sec, min, hour, mday, mon, year;
char *p = (char*) &gen->data[14];
get_ASN1_TIME_data(&p, &sec, 2);
get_ASN1_TIME_data(&p, &min, 2);
get_ASN1_TIME_data(&p, &hour, 2);
get_ASN1_TIME_data(&p, &mday, 2);
get_ASN1_TIME_data(&p, &mon, 2);
get_ASN1_TIME_data(&p, &year, 4);
env->CallVoidMethod(calendar, calendar_setMethod, year, mon - 1, mday, hour, min, sec);
}
static jstring NativeCrypto_OBJ_txt2nid_oid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_oid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_oid(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_oid(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const ASN1_OBJECT* obj = OBJ_nid2obj(nid);
if (obj == NULL) {
throwExceptionIfNecessary(env, "OBJ_nid2obj");
return NULL;
}
ScopedLocalRef<jstring> ouputStr(env, ASN1_OBJECT_to_OID_string(env, obj));
JNI_TRACE("OBJ_txt2nid_oid(%s) => %p", oid.c_str(), ouputStr.get());
return ouputStr.release();
}
static jstring NativeCrypto_X509_NAME_print_ex(JNIEnv* env, jclass, jlong x509NameRef, jlong jflags) {
X509_NAME* x509name = reinterpret_cast<X509_NAME*>(static_cast<uintptr_t>(x509NameRef));
unsigned long flags = static_cast<unsigned long>(jflags);
JNI_TRACE("X509_NAME_print_ex(%p, %ld)", x509name, flags);
if (x509name == NULL) {
jniThrowNullPointerException(env, "x509name == null");
JNI_TRACE("X509_NAME_print_ex(%p, %ld) => x509name == null", x509name, flags);
return NULL;
}
return X509_NAME_to_jstring(env, x509name, flags);
}
template <typename T, T* (*d2i_func)(BIO*, T**)>
static jlong d2i_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return 0;
}
T* x = d2i_func(bio, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "d2i_ASN1Object_to_jlong");
return 0;
}
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_d2i_X509_CRL_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509_CRL, d2i_X509_CRL_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509, d2i_X509_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509(JNIEnv* env, jclass, jbyteArray certBytes) {
X509* x = ByteArrayToASN1<X509, d2i_X509>(env, certBytes);
return reinterpret_cast<uintptr_t>(x);
}
static jbyteArray NativeCrypto_i2d_X509(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509(%p)", x509);
return ASN1ToByteArray<X509>(env, x509, i2d_X509);
}
static jbyteArray NativeCrypto_i2d_X509_PUBKEY(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509_PUBKEY(%p)", x509);
return ASN1ToByteArray<X509_PUBKEY>(env, X509_get_X509_PUBKEY(x509), i2d_X509_PUBKEY);
}
template<typename T, T* (*PEM_read_func)(BIO*, T**, pem_password_cb*, void*)>
static jlong PEM_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => bio == null", bio);
return 0;
}
T* x = PEM_read_func(bio, NULL, NULL, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "PEM_ASN1Object_to_jlong");
// Sometimes the PEM functions fail without pushing an error
if (!env->ExceptionCheck()) {
jniThrowRuntimeException(env, "Failure parsing PEM");
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => threw exception", bio);
return 0;
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => %p", bio, x);
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_PEM_read_bio_X509(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509(0x%llx)", (long long) bioRef);
return PEM_ASN1Object_to_jlong<X509, PEM_read_bio_X509>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_X509_CRL(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509_CRL(0x%llx)", (long long) bioRef);
return PEM_ASN1Object_to_jlong<X509_CRL, PEM_read_bio_X509_CRL>(env, bioRef);
}
template <typename T, typename T_stack>
static jlongArray PKCS7_to_ItemArray(JNIEnv* env, T_stack* stack, T* (*dup_func)(T*))
{
if (stack == NULL) {
return NULL;
}
ScopedLocalRef<jlongArray> ref_array(env, NULL);
size_t size = sk_num(reinterpret_cast<_STACK*>(stack));
ref_array.reset(env->NewLongArray(size));
ScopedLongArrayRW items(env, ref_array.get());
for (size_t i = 0; i < size; i++) {
T* item = reinterpret_cast<T*>(sk_value(reinterpret_cast<_STACK*>(stack), i));
items[i] = reinterpret_cast<uintptr_t>(dup_func(item));
}
JNI_TRACE("PKCS7_to_ItemArray(%p) => %p [size=%d]", stack, ref_array.get(), size);
return ref_array.release();
}
#define PKCS7_CERTS 1
#define PKCS7_CRLS 2
static jbyteArray NativeCrypto_i2d_PKCS7(JNIEnv* env, jclass, jlongArray certsArray) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("i2d_PKCS7(%p)", certsArray);
Unique_PKCS7 pkcs7(PKCS7_new());
if (pkcs7.get() == NULL) {
jniThrowNullPointerException(env, "pkcs7 == null");
JNI_TRACE("i2d_PKCS7(%p) => pkcs7 == null", certsArray);
return NULL;
}
if (PKCS7_set_type(pkcs7.get(), NID_pkcs7_signed) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type");
return NULL;
}
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (PKCS7_add_certificate(pkcs7.get(), item) != 1) {
throwExceptionIfNecessary(env, "i2d_PKCS7");
return NULL;
}
}
JNI_TRACE("i2d_PKCS7(%p) => %zd certs", certsArray, certs.size());
return ASN1ToByteArray<PKCS7>(env, pkcs7.get(), i2d_PKCS7);
#else // OPENSSL_IS_BORINGSSL
STACK_OF(X509) *stack = sk_X509_new_null();
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (sk_X509_push(stack, item) == 0) {
sk_X509_free(stack);
throwExceptionIfNecessary(env, "sk_X509_push");
return NULL;
}
}
CBB out;
CBB_init(&out, 1024 * certs.size());
if (!PKCS7_bundle_certificates(&out, stack)) {
CBB_cleanup(&out);
sk_X509_free(stack);
throwExceptionIfNecessary(env, "PKCS7_bundle_certificates");
return NULL;
}
sk_X509_free(stack);
uint8_t *derBytes;
size_t derLen;
if (!CBB_finish(&out, &derBytes, &derLen)) {
CBB_cleanup(&out);
throwExceptionIfNecessary(env, "CBB_finish");
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("creating byte array failed");
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("using byte array failed");
return NULL;
}
uint8_t* p = reinterpret_cast<unsigned char*>(bytes.get());
memcpy(p, derBytes, derLen);
return byteArray.release();
#endif // OPENSSL_IS_BORINGSSL
}
typedef STACK_OF(X509) PKIPATH;
ASN1_ITEM_TEMPLATE(PKIPATH) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PkiPath, X509)
ASN1_ITEM_TEMPLATE_END(PKIPATH)
static jlongArray NativeCrypto_ASN1_seq_unpack_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p)", bio);
Unique_sk_X509 path((PKIPATH*) ASN1_item_d2i_bio(ASN1_ITEM_rptr(PKIPATH), bio, NULL));
if (path.get() == NULL) {
throwExceptionIfNecessary(env, "ASN1_seq_unpack_X509_bio");
return NULL;
}
size_t size = sk_X509_num(path.get());
ScopedLocalRef<jlongArray> certArray(env, env->NewLongArray(size));
ScopedLongArrayRW certs(env, certArray.get());
for (size_t i = 0; i < size; i++) {
X509* item = reinterpret_cast<X509*>(sk_X509_shift(path.get()));
certs[i] = reinterpret_cast<uintptr_t>(item);
}
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => returns %zd items", bio, size);
return certArray.release();
}
static jbyteArray NativeCrypto_ASN1_seq_pack_X509(JNIEnv* env, jclass, jlongArray certs) {
JNI_TRACE("ASN1_seq_pack_X509(%p)", certs);
ScopedLongArrayRO certsArray(env, certs);
if (certsArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to get certs array", certs);
return NULL;
}
Unique_sk_X509 certStack(sk_X509_new_null());
if (certStack.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to make cert stack", certs);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
sk_X509_push(certStack.get(), X509_dup_nocopy(x509));
}
int len;
Unique_OPENSSL_str encoded(ASN1_seq_pack(
reinterpret_cast<STACK_OF(OPENSSL_BLOCK)*>(
reinterpret_cast<uintptr_t>(certStack.get())),
reinterpret_cast<int (*)(void*, unsigned char**)>(i2d_X509), NULL, &len));
if (encoded.get() == NULL || len < 0) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => trouble encoding", certs);
return NULL;
}
uint8_t *out = encoded.get();
size_t out_len = len;
#else
CBB result, seq_contents;
if (!CBB_init(&result, 2048 * certsArray.size())) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => CBB_init failed", certs);
return NULL;
}
if (!CBB_add_asn1(&result, &seq_contents, CBS_ASN1_SEQUENCE)) {
CBB_cleanup(&result);
return NULL;
}
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
uint8_t *buf;
int len = i2d_X509(x509, NULL);
if (len < 0 ||
!CBB_add_space(&seq_contents, &buf, len) ||
i2d_X509(x509, &buf) < 0) {
CBB_cleanup(&result);
return NULL;
}
}
uint8_t *out;
size_t out_len;
if (!CBB_finish(&result, &out, &out_len)) {
CBB_cleanup(&result);
return NULL;
}
UniquePtr<uint8_t> out_storage(out);
#endif
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(out_len));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => creating byte array failed", certs);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => using byte array failed", certs);
return NULL;
}
uint8_t *p = reinterpret_cast<uint8_t*>(bytes.get());
memcpy(p, out, out_len);
return byteArray.release();
}
static void NativeCrypto_X509_free(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_free(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_free(%p) => x509 == null", x509);
return;
}
X509_free(x509);
}
static jint NativeCrypto_X509_cmp(JNIEnv* env, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_cmp(%p, %p)", x509_1, x509_2);
if (x509_1 == NULL) {
jniThrowNullPointerException(env, "x509_1 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_1 == null", x509_1, x509_2);
return -1;
}
if (x509_2 == NULL) {
jniThrowNullPointerException(env, "x509_2 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_2 == null", x509_1, x509_2);
return -1;
}
int ret = X509_cmp(x509_1, x509_2);
JNI_TRACE("X509_cmp(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static jint NativeCrypto_get_X509_hashCode(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_hashCode(%p) => x509 == null", x509);
return 0;
}
// Force caching extensions.
X509_check_ca(x509);
jint hashCode = 0L;
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
hashCode = 31 * hashCode + x509->sha1_hash[i];
}
return hashCode;
}
static void NativeCrypto_X509_print_ex(JNIEnv* env, jclass, jlong bioRef, jlong x509Ref,
jlong nmflagJava, jlong certflagJava) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
long nmflag = static_cast<long>(nmflagJava);
long certflag = static_cast<long>(certflagJava);
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld)", bio, x509, nmflag, certflag);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => bio == null", bio, x509, nmflag, certflag);
return;
}
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => x509 == null", bio, x509, nmflag, certflag);
return;
}
if (!X509_print_ex(bio, x509, nmflag, certflag)) {
throwExceptionIfNecessary(env, "X509_print_ex");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => threw error", bio, x509, nmflag, certflag);
} else {
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => success", bio, x509, nmflag, certflag);
}
}
static jlong NativeCrypto_X509_get_pubkey(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_pubkey(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_pubkey(%p) => x509 == null", x509);
return 0;
}
Unique_EVP_PKEY pkey(X509_get_pubkey(x509));
if (pkey.get() == NULL) {
#if defined(OPENSSL_IS_BORINGSSL)
const uint32_t last_error = ERR_peek_last_error();
const uint32_t first_error = ERR_peek_error();
if ((ERR_GET_LIB(last_error) == ERR_LIB_EVP &&
ERR_GET_REASON(last_error) == EVP_R_UNKNOWN_PUBLIC_KEY_TYPE) ||
(ERR_GET_LIB(first_error) == ERR_LIB_EC &&
ERR_GET_REASON(first_error) == EC_R_UNKNOWN_GROUP)) {
freeOpenSslErrorState();
throwNoSuchAlgorithmException(env, "X509_get_pubkey");
return 0;
}
#endif
throwExceptionIfNecessary(env, "X509_get_pubkey");
return 0;
}
JNI_TRACE("X509_get_pubkey(%p) => %p", x509, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jbyteArray NativeCrypto_X509_get_issuer_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_issuer_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_issuer_name(x509), i2d_X509_NAME);
}
static jbyteArray NativeCrypto_X509_get_subject_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_subject_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_subject_name(x509), i2d_X509_NAME);
}
static jstring NativeCrypto_get_X509_pubkey_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_pubkey_oid(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_pubkey_oid(%p) => x509 == null", x509);
return NULL;
}
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
return ASN1_OBJECT_to_OID_string(env, pubkey->algor->algorithm);
}
static jstring NativeCrypto_get_X509_sig_alg_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_oid(%p)", x509);
if (x509 == NULL || x509->sig_alg == NULL) {
jniThrowNullPointerException(env, "x509 == NULL || x509->sig_alg == NULL");
JNI_TRACE("get_X509_sig_alg_oid(%p) => x509 == NULL", x509);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, x509->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_sig_alg_parameter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_parameter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_sig_alg_parameter(%p) => x509 == null", x509);
return NULL;
}
if (x509->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_sig_alg_parameter(%p) => null", x509);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, x509->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbooleanArray NativeCrypto_get_X509_issuerUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_issuerUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_issuerUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->issuerUID == NULL) {
JNI_TRACE("get_X509_issuerUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->issuerUID);
}
static jbooleanArray NativeCrypto_get_X509_subjectUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_subjectUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_subjectUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->subjectUID == NULL) {
JNI_TRACE("get_X509_subjectUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->subjectUID);
}
static jbooleanArray NativeCrypto_get_X509_ex_kusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_kusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_kusage(%p) => x509 == null", x509);
return NULL;
}
Unique_ASN1_BIT_STRING bitStr(static_cast<ASN1_BIT_STRING*>(
X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL)));
if (bitStr.get() == NULL) {
JNI_TRACE("get_X509_ex_kusage(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, bitStr.get());
}
static jobjectArray NativeCrypto_get_X509_ex_xkusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_xkusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_xkusage(%p) => x509 == null", x509);
return NULL;
}
Unique_sk_ASN1_OBJECT objArray(static_cast<STACK_OF(ASN1_OBJECT)*>(
X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL)));
if (objArray.get() == NULL) {
JNI_TRACE("get_X509_ex_xkusage(%p) => null", x509);
return NULL;
}
size_t size = sk_ASN1_OBJECT_num(objArray.get());
ScopedLocalRef<jobjectArray> exKeyUsage(env, env->NewObjectArray(size, stringClass, NULL));
if (exKeyUsage.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
ScopedLocalRef<jstring> oidStr(env, ASN1_OBJECT_to_OID_string(env,
sk_ASN1_OBJECT_value(objArray.get(), i)));
env->SetObjectArrayElement(exKeyUsage.get(), i, oidStr.get());
}
JNI_TRACE("get_X509_ex_xkusage(%p) => success (%zd entries)", x509, size);
return exKeyUsage.release();
}
static jint NativeCrypto_get_X509_ex_pathlen(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_pathlen(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_pathlen(%p) => x509 == null", x509);
return 0;
}
/* Just need to do this to cache the ex_* values. */
X509_check_ca(x509);
JNI_TRACE("get_X509_ex_pathlen(%p) => %ld", x509, x509->ex_pathlen);
return x509->ex_pathlen;
}
static jbyteArray NativeCrypto_X509_get_ext_oid(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_ext_oid(%p, %p)", x509, oidString);
return X509Type_get_ext_oid<X509, X509_get_ext_by_OBJ, X509_get_ext>(env, x509, oidString);
}
static jbyteArray NativeCrypto_X509_CRL_get_ext_oid(JNIEnv* env, jclass, jlong x509CrlRef,
jstring oidString) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext_oid(%p, %p)", crl, oidString);
return X509Type_get_ext_oid<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(env, crl,
oidString);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_ext_oid(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oidString) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext_oid(%p, %p)", revoked, oidString);
return X509Type_get_ext_oid<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ, X509_REVOKED_get_ext>(
env, revoked, oidString);
}
template<typename T, int (*get_ext_by_critical_func)(T*, int, int), X509_EXTENSION* (*get_ext_func)(T*, int)>
static jobjectArray get_X509Type_ext_oids(JNIEnv* env, jlong x509Ref, jint critical) {
T* x509 = reinterpret_cast<T*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509Type_ext_oids(%p, %d)", x509, critical);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => x509 == null", x509, critical);
return NULL;
}
int lastPos = -1;
int count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
count++;
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) has %d entries", x509, critical, count);
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, stringClass, NULL));
if (joa.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => fail to allocate result array", x509, critical);
return NULL;
}
lastPos = -1;
count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
X509_EXTENSION* ext = get_ext_func(x509, lastPos);
ScopedLocalRef<jstring> extOid(env, ASN1_OBJECT_to_OID_string(env, ext->object));
if (extOid.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p) => couldn't get OID", x509);
return NULL;
}
env->SetObjectArrayElement(joa.get(), count++, extOid.get());
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => success", x509, critical);
return joa.release();
}
static jobjectArray NativeCrypto_get_X509_ext_oids(JNIEnv* env, jclass, jlong x509Ref,
jint critical) {
JNI_TRACE("get_X509_ext_oids(0x%llx, %d)", (long long) x509Ref, critical);
return get_X509Type_ext_oids<X509, X509_get_ext_by_critical, X509_get_ext>(env, x509Ref,
critical);
}
static jobjectArray NativeCrypto_get_X509_CRL_ext_oids(JNIEnv* env, jclass, jlong x509CrlRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509CrlRef, critical);
return get_X509Type_ext_oids<X509_CRL, X509_CRL_get_ext_by_critical, X509_CRL_get_ext>(env,
x509CrlRef, critical);
}
static jobjectArray NativeCrypto_get_X509_REVOKED_ext_oids(JNIEnv* env, jclass, jlong x509RevokedRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509RevokedRef, critical);
return get_X509Type_ext_oids<X509_REVOKED, X509_REVOKED_get_ext_by_critical,
X509_REVOKED_get_ext>(env, x509RevokedRef, critical);
}
#ifdef WITH_JNI_TRACE
/**
* Based on example logging call back from SSL_CTX_set_info_callback man page
*/
static void info_callback_LOG(const SSL* s __attribute__ ((unused)), int where, int ret)
{
int w = where & ~SSL_ST_MASK;
const char* str;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
} else {
str = "undefined";
}
if (where & SSL_CB_LOOP) {
JNI_TRACE("ssl=%p %s:%s %s", s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
JNI_TRACE("ssl=%p SSL3 alert %s:%s:%s %s %s",
s,
str,
SSL_alert_type_string(ret),
SSL_alert_desc_string(ret),
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
JNI_TRACE("ssl=%p %s:failed exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret < 0) {
JNI_TRACE("ssl=%p %s:error exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret == 1) {
JNI_TRACE("ssl=%p %s:ok exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown exit %d in %s %s",
s, str, ret, SSL_state_string(s), SSL_state_string_long(s));
}
} else if (where & SSL_CB_HANDSHAKE_START) {
JNI_TRACE("ssl=%p handshake start in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_HANDSHAKE_DONE) {
JNI_TRACE("ssl=%p handshake done in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown where %d in %s %s",
s, str, where, SSL_state_string(s), SSL_state_string_long(s));
}
}
#endif
/**
* Returns an array containing all the X509 certificate references
*/
static jlongArray getCertificateRefs(JNIEnv* env, const STACK_OF(X509)* chain)
{
if (chain == NULL) {
// Chain can be NULL if the associated cipher doesn't do certs.
return NULL;
}
ssize_t count = sk_X509_num(chain);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jlongArray> refArray(env, env->NewLongArray(count));
ScopedLongArrayRW refs(env, refArray.get());
if (refs.get() == NULL) {
return NULL;
}
for (ssize_t i = 0; i < count; i++) {
refs[i] = reinterpret_cast<uintptr_t>(X509_dup_nocopy(sk_X509_value(chain, i)));
}
return refArray.release();
}
/**
* Returns an array containing all the X500 principal's bytes.
*/
static jobjectArray getPrincipalBytes(JNIEnv* env, const STACK_OF(X509_NAME)* names)
{
if (names == NULL) {
return NULL;
}
int count = sk_X509_NAME_num(names);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, byteArrayClass, NULL));
if (joa.get() == NULL) {
return NULL;
}
for (int i = 0; i < count; i++) {
X509_NAME* principal = sk_X509_NAME_value(names, i);
ScopedLocalRef<jbyteArray> byteArray(env, ASN1ToByteArray<X509_NAME>(env,
principal, i2d_X509_NAME));
if (byteArray.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(joa.get(), i, byteArray.get());
}
return joa.release();
}
/**
* Our additional application data needed for getting synchronization right.
* This maybe warrants a bit of lengthy prose:
*
* (1) We use a flag to reflect whether we consider the SSL connection alive.
* Any read or write attempt loops will be cancelled once this flag becomes 0.
*
* (2) We use an int to count the number of threads that are blocked by the
* underlying socket. This may be at most two (one reader and one writer), since
* the Java layer ensures that no more threads will enter the native code at the
* same time.
*
* (3) The pipe is used primarily as a means of cancelling a blocking select()
* when we want to close the connection (aka "emergency button"). It is also
* necessary for dealing with a possible race condition situation: There might
* be cases where both threads see an SSL_ERROR_WANT_READ or
* SSL_ERROR_WANT_WRITE. Both will enter a select() with the proper argument.
* If one leaves the select() successfully before the other enters it, the
* "success" event is already consumed and the second thread will be blocked,
* possibly forever (depending on network conditions).
*
* The idea for solving the problem looks like this: Whenever a thread is
* successful in moving around data on the network, and it knows there is
* another thread stuck in a select(), it will write a byte to the pipe, waking
* up the other thread. A thread that returned from select(), on the other hand,
* knows whether it's been woken up by the pipe. If so, it will consume the
* byte, and the original state of affairs has been restored.
*
* The pipe may seem like a bit of overhead, but it fits in nicely with the
* other file descriptors of the select(), so there's only one condition to wait
* for.
*
* (4) Finally, a mutex is needed to make sure that at most one thread is in
* either SSL_read() or SSL_write() at any given time. This is an OpenSSL
* requirement. We use the same mutex to guard the field for counting the
* waiting threads.
*
* Note: The current implementation assumes that we don't have to deal with
* problems induced by multiple cores or processors and their respective
* memory caches. One possible problem is that of inconsistent views on the
* "aliveAndKicking" field. This could be worked around by also enclosing all
* accesses to that field inside a lock/unlock sequence of our mutex, but
* currently this seems a bit like overkill. Marking volatile at the very least.
*
* During handshaking, additional fields are used to up-call into
* Java to perform certificate verification and handshake
* completion. These are also used in any renegotiation.
*
* (5) the JNIEnv so we can invoke the Java callback
*
* (6) a NativeCrypto.SSLHandshakeCallbacks instance for callbacks from native to Java
*
* (7) a java.io.FileDescriptor wrapper to check for socket close
*
* We store the NPN protocols list so we can either send it (from the server) or
* select a protocol (on the client). We eagerly acquire a pointer to the array
* data so the callback doesn't need to acquire resources that it cannot
* release.
*
* Because renegotiation can be requested by the peer at any time,
* care should be taken to maintain an appropriate JNIEnv on any
* downcall to openssl since it could result in an upcall to Java. The
* current code does try to cover these cases by conditionally setting
* the JNIEnv on calls that can read and write to the SSL such as
* SSL_do_handshake, SSL_read, SSL_write, and SSL_shutdown.
*
* Finally, we have two emphemeral keys setup by OpenSSL callbacks:
*
* (8) a set of ephemeral RSA keys that is lazily generated if a peer
* wants to use an exportable RSA cipher suite.
*
* (9) a set of ephemeral EC keys that is lazily generated if a peer
* wants to use an TLS_ECDHE_* cipher suite.
*
*/
class AppData {
public:
volatile int aliveAndKicking;
int waitingThreads;
int fdsEmergency[2];
MUTEX_TYPE mutex;
JNIEnv* env;
jobject sslHandshakeCallbacks;
jbyteArray npnProtocolsArray;
jbyte* npnProtocolsData;
size_t npnProtocolsLength;
jbyteArray alpnProtocolsArray;
jbyte* alpnProtocolsData;
size_t alpnProtocolsLength;
Unique_RSA ephemeralRsa;
Unique_EC_KEY ephemeralEc;
/**
* Creates the application data context for the SSL*.
*/
public:
static AppData* create() {
UniquePtr<AppData> appData(new AppData());
if (pipe(appData.get()->fdsEmergency) == -1) {
ALOGE("AppData::create pipe(2) failed: %s", strerror(errno));
return NULL;
}
if (!setBlocking(appData.get()->fdsEmergency[0], false)) {
ALOGE("AppData::create fcntl(2) failed: %s", strerror(errno));
return NULL;
}
if (MUTEX_SETUP(appData.get()->mutex) == -1) {
ALOGE("pthread_mutex_init(3) failed: %s", strerror(errno));
return NULL;
}
return appData.release();
}
~AppData() {
aliveAndKicking = 0;
if (fdsEmergency[0] != -1) {
close(fdsEmergency[0]);
}
if (fdsEmergency[1] != -1) {
close(fdsEmergency[1]);
}
clearCallbackState();
MUTEX_CLEANUP(mutex);
}
private:
AppData() :
aliveAndKicking(1),
waitingThreads(0),
env(NULL),
sslHandshakeCallbacks(NULL),
npnProtocolsArray(NULL),
npnProtocolsData(NULL),
npnProtocolsLength(-1),
alpnProtocolsArray(NULL),
alpnProtocolsData(NULL),
alpnProtocolsLength(-1),
ephemeralRsa(NULL),
ephemeralEc(NULL) {
fdsEmergency[0] = -1;
fdsEmergency[1] = -1;
}
public:
/**
* Used to set the SSL-to-Java callback state before each SSL_*
* call that may result in a callback. It should be cleared after
* the operation returns with clearCallbackState.
*
* @param env The JNIEnv
* @param shc The SSLHandshakeCallbacks
* @param fd The FileDescriptor
* @param npnProtocols NPN protocols so that they may be advertised (by the
* server) or selected (by the client). Has no effect
* unless NPN is enabled.
* @param alpnProtocols ALPN protocols so that they may be advertised (by the
* server) or selected (by the client). Passing non-NULL
* enables ALPN.
*/
bool setCallbackState(JNIEnv* e, jobject shc, jobject fd, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
UniquePtr<NetFd> netFd;
if (fd != NULL) {
netFd.reset(new NetFd(e, fd));
if (netFd->isClosed()) {
JNI_TRACE("appData=%p setCallbackState => netFd->isClosed() == true", this);
return false;
}
}
env = e;
sslHandshakeCallbacks = shc;
if (npnProtocols != NULL) {
npnProtocolsData = e->GetByteArrayElements(npnProtocols, NULL);
if (npnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => npnProtocolsData == NULL", this);
return false;
}
npnProtocolsArray = npnProtocols;
npnProtocolsLength = e->GetArrayLength(npnProtocols);
}
if (alpnProtocols != NULL) {
alpnProtocolsData = e->GetByteArrayElements(alpnProtocols, NULL);
if (alpnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => alpnProtocolsData == NULL", this);
return false;
}
alpnProtocolsArray = alpnProtocols;
alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
}
return true;
}
void clearCallbackState() {
sslHandshakeCallbacks = NULL;
if (npnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(npnProtocolsArray, npnProtocolsData, JNI_ABORT);
npnProtocolsArray = NULL;
npnProtocolsData = NULL;
npnProtocolsLength = -1;
}
if (alpnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(alpnProtocolsArray, alpnProtocolsData, JNI_ABORT);
alpnProtocolsArray = NULL;
alpnProtocolsData = NULL;
alpnProtocolsLength = -1;
}
env = NULL;
}
};
/**
* Dark magic helper function that checks, for a given SSL session, whether it
* can SSL_read() or SSL_write() without blocking. Takes into account any
* concurrent attempts to close the SSLSocket from the Java side. This is
* needed to get rid of the hangs that occur when thread #1 closes the SSLSocket
* while thread #2 is sitting in a blocking read or write. The type argument
* specifies whether we are waiting for readability or writability. It expects
* to be passed either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, since we
* only need to wait in case one of these problems occurs.
*
* @param env
* @param type Either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
* @param fdObject The FileDescriptor, since appData->fileDescriptor should be NULL
* @param appData The application data structure with mutex info etc.
* @param timeout_millis The timeout value for select call, with the special value
* 0 meaning no timeout at all (wait indefinitely). Note: This is
* the Java semantics of the timeout value, not the usual
* select() semantics.
* @return The result of the inner select() call,
* THROW_SOCKETEXCEPTION if a SocketException was thrown, -1 on
* additional errors
*/
static int sslSelect(JNIEnv* env, int type, jobject fdObject, AppData* appData, int timeout_millis) {
// This loop is an expanded version of the NET_FAILURE_RETRY
// macro. It cannot simply be used in this case because select
// cannot be restarted without recreating the fd_sets and timeout
// structure.
int result;
fd_set rfds;
fd_set wfds;
do {
NetFd fd(env, fdObject);
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
int intFd = fd.get();
JNI_TRACE("sslSelect type=%s fd=%d appData=%p timeout_millis=%d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE", intFd, appData, timeout_millis);
FD_ZERO(&rfds);
FD_ZERO(&wfds);
if (type == SSL_ERROR_WANT_READ) {
FD_SET(intFd, &rfds);
} else {
FD_SET(intFd, &wfds);
}
FD_SET(appData->fdsEmergency[0], &rfds);
int maxFd = (intFd > appData->fdsEmergency[0]) ? intFd : appData->fdsEmergency[0];
// Build a struct for the timeout data if we actually want a timeout.
timeval tv;
timeval* ptv;
if (timeout_millis > 0) {
tv.tv_sec = timeout_millis / 1000;
tv.tv_usec = (timeout_millis % 1000) * 1000;
ptv = &tv;
} else {
ptv = NULL;
}
#ifndef CONSCRYPT_UNBUNDLED
AsynchronousCloseMonitor monitor(intFd);
#else
CompatibilityCloseMonitor monitor(intFd);
#endif
result = select(maxFd + 1, &rfds, &wfds, NULL, ptv);
JNI_TRACE("sslSelect %s fd=%d appData=%p timeout_millis=%d => %d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE",
fd.get(), appData, timeout_millis, result);
if (result == -1) {
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
if (errno != EINTR) {
break;
}
}
} while (result == -1);
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (result > 0) {
// We have been woken up by a token in the emergency pipe. We
// can't be sure the token is still in the pipe at this point
// because it could have already been read by the thread that
// originally wrote it if it entered sslSelect and acquired
// the mutex before we did. Thus we cannot safely read from
// the pipe in a blocking way (so we make the pipe
// non-blocking at creation).
if (FD_ISSET(appData->fdsEmergency[0], &rfds)) {
char token;
do {
read(appData->fdsEmergency[0], &token, 1);
} while (errno == EINTR);
}
}
// Tell the world that there is now one thread less waiting for the
// underlying network.
appData->waitingThreads--;
MUTEX_UNLOCK(appData->mutex);
return result;
}
/**
* Helper function that wakes up a thread blocked in select(), in case there is
* one. Is being called by sslRead() and sslWrite() as well as by JNI glue
* before closing the connection.
*
* @param data The application data structure with mutex info etc.
*/
static void sslNotify(AppData* appData) {
// Write a byte to the emergency pipe, so a concurrent select() can return.
// Note we have to restore the errno of the original system call, since the
// caller relies on it for generating error messages.
int errnoBackup = errno;
char token = '*';
do {
errno = 0;
write(appData->fdsEmergency[1], &token, 1);
} while (errno == EINTR);
errno = errnoBackup;
}
static AppData* toAppData(const SSL* ssl) {
return reinterpret_cast<AppData*>(SSL_get_app_data(ssl));
}
/**
* Verify the X509 certificate via SSL_CTX_set_cert_verify_callback
*/
static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg __attribute__ ((unused)))
{
/* Get the correct index to the SSLobject stored into X509_STORE_CTX. */
SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_store_ctx,
SSL_get_ex_data_X509_STORE_CTX_idx()));
JNI_TRACE("ssl=%p cert_verify_callback x509_store_ctx=%p arg=%p", ssl, x509_store_ctx, arg);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in cert_verify_callback");
JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "verifyCertificateChain", "(J[JLjava/lang/String;)V");
jlongArray refArray = getCertificateRefs(env, x509_store_ctx->untrusted);
#if !defined(OPENSSL_IS_BORINGSSL)
const char* authMethod = SSL_authentication_method(ssl);
#else
const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
const char *authMethod = SSL_CIPHER_get_kx_name(cipher);
#endif
JNI_TRACE("ssl=%p cert_verify_callback calling verifyCertificateChain authMethod=%s",
ssl, authMethod);
jstring authMethodString = env->NewStringUTF(authMethod);
env->CallVoidMethod(sslHandshakeCallbacks, methodID,
static_cast<jlong>(reinterpret_cast<uintptr_t>(SSL_get1_session(ssl))), refArray,
authMethodString);
int result = (env->ExceptionCheck()) ? 0 : 1;
JNI_TRACE("ssl=%p cert_verify_callback => %d", ssl, result);
return result;
}
/**
* Call back to watch for handshake to be completed. This is necessary
* for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake
* returns before the handshake is completed in this case.
*/
static void info_callback(const SSL* ssl, int where, int ret) {
JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret);
#ifdef WITH_JNI_TRACE
info_callback_LOG(ssl, where, ret);
#endif
if (!(where & SSL_CB_HANDSHAKE_DONE) && !(where & SSL_CB_HANDSHAKE_START)) {
JNI_TRACE("ssl=%p info_callback ignored", ssl);
return;
}
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in info_callback");
JNI_TRACE("ssl=%p info_callback env error", ssl);
return;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback already pending exception", ssl);
return;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(cls, "onSSLStateChange", "(JII)V");
JNI_TRACE("ssl=%p info_callback calling onSSLStateChange", ssl);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, reinterpret_cast<jlong>(ssl), where, ret);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback exception", ssl);
}
JNI_TRACE("ssl=%p info_callback completed", ssl);
}
/**
* Call back to ask for a client certificate. There are three possible exit codes:
*
* 1 is success. x509Out and pkeyOut should point to the correct private key and certificate.
* 0 is unable to find key. x509Out and pkeyOut should be NULL.
* -1 is error and it doesn't matter what x509Out and pkeyOut are.
*/
static int client_cert_cb(SSL* ssl, X509** x509Out, EVP_PKEY** pkeyOut) {
JNI_TRACE("ssl=%p client_cert_cb x509Out=%p pkeyOut=%p", ssl, x509Out, pkeyOut);
/* Clear output of key and certificate in case of early exit due to error. */
*x509Out = NULL;
*pkeyOut = NULL;
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in client_cert_cb");
JNI_TRACE("ssl=%p client_cert_cb env error => 0", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb already pending exception => 0", ssl);
return -1;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "clientCertificateRequested", "([B[[B)V");
// Call Java callback which can use SSL_use_certificate and SSL_use_PrivateKey to set values
char ssl2_ctype = SSL3_CT_RSA_SIGN;
const char* ctype = NULL;
#if !defined(OPENSSL_IS_BORINGSSL)
int ctype_num = 0;
jobjectArray issuers = NULL;
switch (ssl->version) {
case SSL2_VERSION:
ctype = &ssl2_ctype;
ctype_num = 1;
break;
case SSL3_VERSION:
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
case DTLS1_VERSION:
ctype = ssl->s3->tmp.ctype;
ctype_num = ssl->s3->tmp.ctype_num;
issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
break;
}
#else
int ctype_num = SSL_get0_certificate_types(ssl, &ctype);
jobjectArray issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
#endif
#ifdef WITH_JNI_TRACE
for (int i = 0; i < ctype_num; i++) {
JNI_TRACE("ssl=%p clientCertificateRequested keyTypes[%d]=%d", ssl, i, ctype[i]);
}
#endif
jbyteArray keyTypes = env->NewByteArray(ctype_num);
if (keyTypes == NULL) {
JNI_TRACE("ssl=%p client_cert_cb bytes == null => 0", ssl);
return 0;
}
env->SetByteArrayRegion(keyTypes, 0, ctype_num, reinterpret_cast<const jbyte*>(ctype));
JNI_TRACE("ssl=%p clientCertificateRequested calling clientCertificateRequested "
"keyTypes=%p issuers=%p", ssl, keyTypes, issuers);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, keyTypes, issuers);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb exception => 0", ssl);
return -1;
}
// Check for values set from Java
X509* certificate = SSL_get_certificate(ssl);
EVP_PKEY* privatekey = SSL_get_privatekey(ssl);
int result = 0;
if (certificate != NULL && privatekey != NULL) {
*x509Out = certificate;
*pkeyOut = privatekey;
result = 1;
} else {
// Some error conditions return NULL, so make sure it doesn't linger.
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p client_cert_cb => *x509=%p *pkey=%p %d", ssl, *x509Out, *pkeyOut, result);
return result;
}
/**
* Pre-Shared Key (PSK) client callback.
*/
static unsigned int psk_client_callback(SSL* ssl, const char *hint,
char *identity, unsigned int max_identity_len,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_client_callback");
JNI_TRACE("ssl=%p psk_client_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID =
env->GetMethodID(cls, "clientPSKKeyRequested", "(Ljava/lang/String;[B[B)I");
JNI_TRACE("ssl=%p psk_client_callback calling clientPSKKeyRequested", ssl);
ScopedLocalRef<jstring> identityHintJava(
env,
(hint != NULL) ? env->NewStringUTF(hint) : NULL);
ScopedLocalRef<jbyteArray> identityJava(env, env->NewByteArray(max_identity_len));
if (identityJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate identity bufffer", ssl);
return 0;
}
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
ScopedByteArrayRO identityJavaRo(env, identityJava.get());
if (identityJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get identity bytes", ssl);
return 0;
}
memcpy(identity, identityJavaRo.get(), max_identity_len);
JNI_TRACE("ssl=%p psk_client_callback completed", ssl);
return keyLen;
}
/**
* Pre-Shared Key (PSK) server callback.
*/
static unsigned int psk_server_callback(SSL* ssl, const char *identity,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_server_callback");
JNI_TRACE("ssl=%p psk_server_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(
cls, "serverPSKKeyRequested", "(Ljava/lang/String;Ljava/lang/String;[B)I");
JNI_TRACE("ssl=%p psk_server_callback calling serverPSKKeyRequested", ssl);
const char* identityHint = SSL_get_psk_identity_hint(ssl);
// identityHint = NULL;
// identity = NULL;
ScopedLocalRef<jstring> identityHintJava(
env,
(identityHint != NULL) ? env->NewStringUTF(identityHint) : NULL);
ScopedLocalRef<jstring> identityJava(
env,
(identity != NULL) ? env->NewStringUTF(identity) : NULL);
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
JNI_TRACE("ssl=%p psk_server_callback completed", ssl);
return keyLen;
}
static RSA* rsaGenerateKey(int keylength) {
Unique_BIGNUM bn(BN_new());
if (bn.get() == NULL) {
return NULL;
}
int setWordResult = BN_set_word(bn.get(), RSA_F4);
if (setWordResult != 1) {
return NULL;
}
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
return NULL;
}
int generateResult = RSA_generate_key_ex(rsa.get(), keylength, bn.get(), NULL);
if (generateResult != 1) {
return NULL;
}
return rsa.release();
}
/**
* Call back to ask for an ephemeral RSA key for SSL_RSA_EXPORT_WITH_RC4_40_MD5 (aka EXP-RC4-MD5)
*/
static RSA* tmp_rsa_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_rsa_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralRsa.get() == NULL) {
JNI_TRACE("ssl=%p tmp_rsa_callback generating ephemeral RSA key", ssl);
appData->ephemeralRsa.reset(rsaGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_rsa_callback => %p", ssl, appData->ephemeralRsa.get());
return appData->ephemeralRsa.get();
}
static DH* dhGenerateParameters(int keylength) {
#if !defined(OPENSSL_IS_BORINGSSL)
/*
* The SSL_CTX_set_tmp_dh_callback(3SSL) man page discusses two
* different options for generating DH keys. One is generating the
* keys using a single set of DH parameters. However, generating
* DH parameters is slow enough (minutes) that they suggest doing
* it once at install time. The other is to generate DH keys from
* DSA parameters. Generating DSA parameters is faster than DH
* parameters, but to prevent small subgroup attacks, they needed
* to be regenerated for each set of DH keys. Setting the
* SSL_OP_SINGLE_DH_USE option make sure OpenSSL will call back
* for new DH parameters every type it needs to generate DH keys.
*/
// Fast path but must have SSL_OP_SINGLE_DH_USE set
Unique_DSA dsa(DSA_new());
if (!DSA_generate_parameters_ex(dsa.get(), keylength, NULL, 0, NULL, NULL, NULL)) {
return NULL;
}
DH* dh = DSA_dup_DH(dsa.get());
return dh;
#else
/* At the time of writing, OpenSSL and BoringSSL are hard coded to request
* a 1024-bit DH. */
if (keylength <= 1024) {
return DH_get_1024_160(NULL);
}
if (keylength <= 2048) {
return DH_get_2048_224(NULL);
}
/* In the case of a large request, return the strongest DH group that
* we have predefined. Generating a group takes far too long to be
* reasonable. */
return DH_get_2048_256(NULL);
#endif
}
/**
* Call back to ask for Diffie-Hellman parameters
*/
static DH* tmp_dh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_dh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
DH* tmp_dh = dhGenerateParameters(keylength);
JNI_TRACE("ssl=%p tmp_dh_callback => %p", ssl, tmp_dh);
return tmp_dh;
}
static EC_KEY* ecGenerateKey(int keylength __attribute__ ((unused))) {
// TODO selected curve based on keylength
Unique_EC_KEY ec(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (ec.get() == NULL) {
return NULL;
}
return ec.release();
}
/**
* Call back to ask for an ephemeral EC key for TLS_ECDHE_* cipher suites
*/
static EC_KEY* tmp_ecdh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_ecdh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralEc.get() == NULL) {
JNI_TRACE("ssl=%p tmp_ecdh_callback generating ephemeral EC key", ssl);
appData->ephemeralEc.reset(ecGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_ecdh_callback => %p", ssl, appData->ephemeralEc.get());
return appData->ephemeralEc.get();
}
/*
* public static native int SSL_CTX_new();
*/
static jlong NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass) {
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
if (sslCtx.get() == NULL) {
throwExceptionIfNecessary(env, "SSL_CTX_new");
return 0;
}
SSL_CTX_set_options(sslCtx.get(),
SSL_OP_ALL
// Note: We explicitly do not allow SSLv2 to be used.
| SSL_OP_NO_SSLv2
// We also disable session tickets for better compatibility b/2682876
| SSL_OP_NO_TICKET
// We also disable compression for better compatibility b/2710492 b/2710497
| SSL_OP_NO_COMPRESSION
// Because dhGenerateParameters uses DSA_generate_parameters_ex
| SSL_OP_SINGLE_DH_USE
// Because ecGenerateParameters uses a fixed named curve
| SSL_OP_SINGLE_ECDH_USE);
int mode = SSL_CTX_get_mode(sslCtx.get());
/*
* Turn on "partial write" mode. This means that SSL_write() will
* behave like Posix write() and possibly return after only
* writing a partial buffer. Note: The alternative, perhaps
* surprisingly, is not that SSL_write() always does full writes
* but that it will force you to retry write calls having
* preserved the full state of the original call. (This is icky
* and undesirable.)
*/
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
// Reuse empty buffers within the SSL_CTX to save memory
mode |= SSL_MODE_RELEASE_BUFFERS;
SSL_CTX_set_mode(sslCtx.get(), mode);
SSL_CTX_set_cert_verify_callback(sslCtx.get(), cert_verify_callback, NULL);
SSL_CTX_set_info_callback(sslCtx.get(), info_callback);
SSL_CTX_set_client_cert_cb(sslCtx.get(), client_cert_cb);
SSL_CTX_set_tmp_rsa_callback(sslCtx.get(), tmp_rsa_callback);
SSL_CTX_set_tmp_dh_callback(sslCtx.get(), tmp_dh_callback);
SSL_CTX_set_tmp_ecdh_callback(sslCtx.get(), tmp_ecdh_callback);
// When TLS Channel ID extension is used, use the new version of it.
sslCtx.get()->tlsext_channel_id_enabled_new = 1;
JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx.get());
return (jlong) sslCtx.release();
}
/**
* public static native void SSL_CTX_free(long ssl_ctx)
*/
static void NativeCrypto_SSL_CTX_free(JNIEnv* env,
jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_free(ssl_ctx);
}
static void NativeCrypto_SSL_CTX_set_session_id_context(JNIEnv* env, jclass,
jlong ssl_ctx_address, jbyteArray sid_ctx)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context sid_ctx=%p", ssl_ctx, sid_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO buf(env, sid_ctx);
if (buf.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => threw exception", ssl_ctx);
return;
}
unsigned int length = buf.size();
if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"length > SSL_MAX_SSL_SESSION_ID_LENGTH");
JNI_TRACE("NativeCrypto_SSL_CTX_set_session_id_context => length = %d", length);
return;
}
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buf.get());
int result = SSL_CTX_set_session_id_context(ssl_ctx, bytes, length);
if (result == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_SSL_CTX_set_session_id_context");
return;
}
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => ok", ssl_ctx);
}
/**
* public static native int SSL_new(long ssl_ctx) throws SSLException;
*/
static jlong NativeCrypto_SSL_new(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new", ssl_ctx);
if (ssl_ctx == NULL) {
return 0;
}
Unique_SSL ssl(SSL_new(ssl_ctx));
if (ssl.get() == NULL) {
throwSSLExceptionWithSslErrors(env, NULL, SSL_ERROR_NONE,
"Unable to create SSL structure");
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
return 0;
}
/*
* Create our special application data.
*/
AppData* appData = AppData::create();
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to create application data");
freeOpenSslErrorState();
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new appData => 0", ssl_ctx);
return 0;
}
SSL_set_app_data(ssl.get(), reinterpret_cast<char*>(appData));
/*
* Java code in class OpenSSLSocketImpl does the verification. Since
* the callbacks do all the verification of the chain, this flag
* simply controls whether to send protocol-level alerts or not.
* SSL_VERIFY_NONE means don't send alerts and anything else means send
* alerts.
*/
SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => ssl=%p appData=%p", ssl_ctx, ssl.get(), appData);
return (jlong) ssl.release();
}
static void NativeCrypto_SSL_enable_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_enable_tls_channel_id", ssl);
if (ssl == NULL) {
return;
}
long ret = SSL_enable_tls_channel_id(ssl);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error enabling Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_tls_channel_id => error", ssl);
return;
}
}
static jbyteArray NativeCrypto_SSL_get_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id", ssl);
if (ssl == NULL) {
return NULL;
}
// Channel ID is 64 bytes long. Unfortunately, OpenSSL doesn't declare this length
// as a constant anywhere.
jbyteArray javaBytes = env->NewByteArray(64);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => NULL", ssl);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
// Unfortunately, the SSL_get_tls_channel_id method below always returns 64 (upon success)
// regardless of the number of bytes copied into the output buffer "tmp". Thus, the correctness
// of this code currently relies on the "tmp" buffer being exactly 64 bytes long.
long ret = SSL_get_tls_channel_id(ssl, tmp, 64);
if (ret == 0) {
// Channel ID either not set or did not verify
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => not available", ssl);
return NULL;
} else if (ret != 64) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error getting Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_tls_channel_id => error, returned %ld", ssl, ret);
return NULL;
}
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id() => %p", ssl, javaBytes);
return javaBytes;
}
static void NativeCrypto_SSL_set1_tls_channel_id(JNIEnv* env, jclass,
jlong ssl_address, jobject pkeyRef)
{
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => pkey == null", ssl);
return;
}
// SSL_set1_tls_channel_id requires ssl->server to be set to 0.
// Unfortunately, the default value is 1 and it's only changed to 0 just
// before the handshake starts (see NativeCrypto_SSL_do_handshake).
ssl->server = 0;
long ret = SSL_set1_tls_channel_id(ssl, pkey);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(
env, ssl, SSL_ERROR_NONE, "Error setting private key for Channel ID");
SSL_clear(ssl);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => error", ssl);
return;
}
// SSL_set1_tls_channel_id expects to take ownership of the EVP_PKEY, but
// we have an external reference from the caller such as an OpenSSLKey,
// so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => ok", ssl);
}
static void NativeCrypto_SSL_use_PrivateKey(JNIEnv* env, jclass, jlong ssl_address,
jobject pkeyRef) {
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_use_PrivateKey privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_use_PrivateKey => pkey == null", ssl);
return;
}
int ret = SSL_use_PrivateKey(ssl, pkey);
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting private key");
SSL_clear(ssl);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => error", ssl);
return;
}
// SSL_use_PrivateKey expects to take ownership of the EVP_PKEY,
// but we have an external reference from the caller such as an
// OpenSSLKey, so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => ok", ssl);
}
static void NativeCrypto_SSL_use_certificate(JNIEnv* env, jclass,
jlong ssl_address, jlongArray certificatesJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate certificates=%p", ssl, certificatesJava);
if (ssl == NULL) {
return;
}
if (certificatesJava == NULL) {
jniThrowNullPointerException(env, "certificates == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
size_t length = env->GetArrayLength(certificatesJava);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "certificates.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates.length == 0", ssl);
return;
}
ScopedLongArrayRO certificates(env, certificatesJava);
if (certificates.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
Unique_X509 serverCert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[0]))));
if (serverCert.get() == NULL) {
// Note this shouldn't happen since we checked the number of certificates above.
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
int ret = SSL_use_certificate(ssl, serverCert.get());
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(serverCert);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !sk_X509_push(chain.get(), cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
int chainResult = SSL_use_certificate_chain(ssl, chain.get());
if (chainResult == 0) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate_chain error",
ssl);
return;
}
OWNERSHIP_TRANSFERRED(chain);
#else
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !SSL_add0_chain_cert(ssl, cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
#endif
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => ok", ssl);
}
static void NativeCrypto_SSL_check_private_key(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key", ssl);
if (ssl == NULL) {
return;
}
int ret = SSL_check_private_key(ssl);
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error checking private key");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => ok", ssl);
}
static void NativeCrypto_SSL_set_client_CA_list(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray principals)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list principals=%p", ssl, principals);
if (ssl == NULL) {
return;
}
if (principals == NULL) {
jniThrowNullPointerException(env, "principals == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals == null", ssl);
return;
}
int length = env->GetArrayLength(principals);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "principals.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals.length == 0", ssl);
return;
}
Unique_sk_X509_NAME principalsStack(sk_X509_NAME_new_null());
if (principalsStack.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate principal stack");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => stack allocation error", ssl);
return;
}
for (int i = 0; i < length; i++) {
ScopedLocalRef<jbyteArray> principal(env,
reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(principals, i)));
if (principal.get() == NULL) {
jniThrowNullPointerException(env, "principals element == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals element null", ssl);
return;
}
ScopedByteArrayRO buf(env, principal.get());
if (buf.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => threw exception", ssl);
return;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(buf.get());
Unique_X509_NAME principalX509Name(d2i_X509_NAME(NULL, &tmp, buf.size()));
if (principalX509Name.get() == NULL) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing principal");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals parsing error",
ssl);
return;
}
if (!sk_X509_NAME_push(principalsStack.get(), principalX509Name.release())) {
jniThrowOutOfMemory(env, "Unable to push principal");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principal push error", ssl);
return;
}
}
SSL_set_client_CA_list(ssl, principalsStack.release());
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => ok", ssl);
}
/**
* public static native long SSL_get_mode(long ssl);
*/
static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl);
if (ssl == NULL) {
return 0;
}
long mode = SSL_get_mode(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0x%lx", ssl, mode);
return mode;
}
/**
* public static native long SSL_set_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_get_options(long ssl);
*/
static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl);
if (ssl == NULL) {
return 0;
}
long options = SSL_get_options(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0x%lx", ssl, options);
return options;
}
/**
* public static native long SSL_set_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options => 0x%lx", ssl, result);
return result;
}
static void NativeCrypto_SSL_use_psk_identity_hint(JNIEnv* env, jclass,
jlong ssl_address, jstring identityHintJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_psk_identity_hint identityHint=%p",
ssl, identityHintJava);
if (ssl == NULL) {
return;
}
int ret;
if (identityHintJava == NULL) {
ret = SSL_use_psk_identity_hint(ssl, NULL);
} else {
ScopedUtfChars identityHint(env, identityHintJava);
if (identityHint.c_str() == NULL) {
throwSSLExceptionStr(env, "Failed to obtain identityHint bytes");
return;
}
ret = SSL_use_psk_identity_hint(ssl, identityHint.c_str());
}
if (ret != 1) {
int sslErrorCode = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Failed to set PSK identity hint");
SSL_clear(ssl);
}
}
static void NativeCrypto_set_SSL_psk_client_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_client_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_client_callback(ssl, (enabled) ? psk_client_callback : NULL);
}
static void NativeCrypto_set_SSL_psk_server_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_server_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_server_callback(ssl, (enabled) ? psk_server_callback : NULL);
}
static jlongArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl);
STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl);
int count = (cipherStack != NULL) ? sk_SSL_CIPHER_num(cipherStack) : 0;
ScopedLocalRef<jlongArray> ciphersArray(env, env->NewLongArray(count));
ScopedLongArrayRW ciphers(env, ciphersArray.get());
for (int i = 0; i < count; i++) {
ciphers[i] = reinterpret_cast<jlong>(sk_SSL_CIPHER_value(cipherStack, i));
}
JNI_TRACE("NativeCrypto_SSL_get_ciphers(%p) => %p [size=%d]", ssl, ciphersArray.get(), count);
return ciphersArray.release();
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_mkey(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_mkey => %ld", cipher, cipher->algorithm_mkey);
return cipher->algorithm_mkey;
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_auth(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_auth => %ld", cipher, cipher->algorithm_auth);
return cipher->algorithm_auth;
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_cipher_lists(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray cipherSuites)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%p", ssl, cipherSuites);
if (ssl == NULL) {
return;
}
if (cipherSuites == NULL) {
jniThrowNullPointerException(env, "cipherSuites == null");
return;
}
int length = env->GetArrayLength(cipherSuites);
static const char noSSLv2[] = "!SSLv2";
size_t cipherStringLen = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
if (c.c_str() == NULL) {
return;
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For the separating colon */
if (cipherStringLen + c.size() < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += c.size();
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For final NUL. */
UniquePtr<char[]> cipherString(new char[cipherStringLen]);
if (cipherString.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to alloc cipher string");
return;
}
memcpy(cipherString.get(), noSSLv2, strlen(noSSLv2));
size_t j = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
cipherString[j++] = ':';
memcpy(&cipherString[j], c.c_str(), c.size());
j += c.size();
}
cipherString[j++] = 0;
if (j != cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Internal error");
return;
}
if (!SSL_set_cipher_list(ssl, cipherString.get())) {
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Illegal cipher suite strings.");
return;
}
}
static void NativeCrypto_SSL_set_accept_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_accept_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_accept_state(ssl);
}
static void NativeCrypto_SSL_set_connect_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_connect_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_connect_state(ssl);
}
/**
* Sets certificate expectations, especially for server to request client auth
*/
static void NativeCrypto_SSL_set_verify(JNIEnv* env,
jclass, jlong ssl_address, jint mode)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify mode=%x", ssl, mode);
if (ssl == NULL) {
return;
}
SSL_set_verify(ssl, (int)mode, NULL);
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass,
jlong ssl_address, jlong ssl_session_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session);
if (ssl == NULL) {
return;
}
int ret = SSL_set_session(ssl, ssl_session);
if (ret != 1) {
/*
* Translate the error, and throw if it turns out to be a real
* problem.
*/
int sslErrorCode = SSL_get_error(ssl, ret);
if (sslErrorCode != SSL_ERROR_ZERO_RETURN) {
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "SSL session set");
SSL_clear(ssl);
}
}
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean creation_enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d",
ssl, creation_enabled);
if (ssl == NULL) {
return;
}
#if !defined(OPENSSL_IS_BORINGSSL)
SSL_set_session_creation_enabled(ssl, creation_enabled);
#else
if (creation_enabled) {
SSL_clear_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
} else {
SSL_set_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
}
#endif
}
static void NativeCrypto_SSL_set_tlsext_host_name(JNIEnv* env, jclass,
jlong ssl_address, jstring hostname)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostname=%p",
ssl, hostname);
if (ssl == NULL) {
return;
}
ScopedUtfChars hostnameChars(env, hostname);
if (hostnameChars.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostnameChars=%s",
ssl, hostnameChars.c_str());
int ret = SSL_set_tlsext_host_name(ssl, hostnameChars.c_str());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting host name");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => ok", ssl);
}
static jstring NativeCrypto_SSL_get_servername(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername", ssl);
if (ssl == NULL) {
return NULL;
}
const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername => %s", ssl, servername);
return env->NewStringUTF(servername);
}
/**
* A common selection path for both NPN and ALPN since they're essentially the
* same protocol. The list of protocols in "primary" is considered the order
* which should take precedence.
*/
static int proto_select(SSL* ssl __attribute__ ((unused)),
unsigned char **out, unsigned char *outLength,
const unsigned char *primary, const unsigned int primaryLength,
const unsigned char *secondary, const unsigned int secondaryLength) {
if (primary != NULL && secondary != NULL) {
JNI_TRACE("primary=%p, length=%d", primary, primaryLength);
int status = SSL_select_next_proto(out, outLength, primary, primaryLength, secondary,
secondaryLength);
switch (status) {
case OPENSSL_NPN_NEGOTIATED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN negotiated", ssl);
return SSL_TLSEXT_ERR_OK;
break;
case OPENSSL_NPN_UNSUPPORTED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN unsupported", ssl);
break;
case OPENSSL_NPN_NO_OVERLAP:
JNI_TRACE("ssl=%p proto_select NPN/ALPN no overlap", ssl);
break;
}
} else {
if (out != NULL && outLength != NULL) {
*out = NULL;
*outLength = 0;
}
JNI_TRACE("protocols=NULL");
}
return SSL_TLSEXT_ERR_NOACK;
}
/**
* Callback for the server to select an ALPN protocol.
*/
static int alpn_select_callback(SSL* ssl, const unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen, void *) {
JNI_TRACE("ssl=%p alpn_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
return proto_select(ssl, const_cast<unsigned char **>(out), outlen,
reinterpret_cast<unsigned char*>(appData->alpnProtocolsData),
appData->alpnProtocolsLength, in, inlen);
}
/**
* Callback for the client to select an NPN protocol.
*/
static int next_proto_select_callback(SSL* ssl, unsigned char** out, unsigned char* outlen,
const unsigned char* in, unsigned int inlen, void*)
{
JNI_TRACE("ssl=%p next_proto_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
// Enable False Start on the client if the server understands NPN
// http://www.imperialviolet.org/2012/04/11/falsestart.html
SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
return proto_select(ssl, out, outlen, in, inlen,
reinterpret_cast<unsigned char*>(appData->npnProtocolsData),
appData->npnProtocolsLength);
}
/**
* Callback for the server to advertise available protocols.
*/
static int next_protos_advertised_callback(SSL* ssl,
const unsigned char **out, unsigned int *outlen, void *)
{
JNI_TRACE("ssl=%p next_protos_advertised_callback", ssl);
AppData* appData = toAppData(ssl);
unsigned char* npnProtocols = reinterpret_cast<unsigned char*>(appData->npnProtocolsData);
if (npnProtocols != NULL) {
*out = npnProtocols;
*outlen = appData->npnProtocolsLength;
return SSL_TLSEXT_ERR_OK;
} else {
*out = NULL;
*outlen = 0;
return SSL_TLSEXT_ERR_NOACK;
}
}
static void NativeCrypto_SSL_CTX_enable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_callback, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_protos_advertised_callback, NULL); // server
}
static void NativeCrypto_SSL_CTX_disable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, NULL, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, NULL, NULL); // server
}
static jbyteArray NativeCrypto_SSL_get_npn_negotiated_protocol(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_npn_negotiated_protocol", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_next_proto_negotiated(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
static int NativeCrypto_SSL_set_alpn_protos(JNIEnv* env, jclass, jlong ssl_address,
jbyteArray protos) {
SSL* ssl = to_SSL(env, ssl_address, true);
if (ssl == NULL) {
return 0;
}
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p", ssl, protos);
if (protos == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=NULL", ssl);
return 1;
}
ScopedByteArrayRO protosBytes(env, protos);
if (protosBytes.get() == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => protosBytes == NULL", ssl,
protos);
return 0;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char*>(protosBytes.get());
int ret = SSL_set_alpn_protos(ssl, tmp, protosBytes.size());
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => ret=%d", ssl, protos, ret);
return ret;
}
static jbyteArray NativeCrypto_SSL_get0_alpn_selected(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p SSL_get0_alpn_selected", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_alpn_selected(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
#ifdef WITH_JNI_TRACE_KEYS
static inline char hex_char(unsigned char in)
{
if (in < 10) {
return '0' + in;
} else if (in <= 0xF0) {
return 'A' + in - 10;
} else {
return '?';
}
}
static void hex_string(char **dest, unsigned char* input, int len)
{
*dest = (char*) malloc(len * 2 + 1);
char *output = *dest;
for (int i = 0; i < len; i++) {
*output++ = hex_char(input[i] >> 4);
*output++ = hex_char(input[i] & 0xF);
}
*output = '\0';
}
static void debug_print_session_key(SSL_SESSION* session)
{
char *session_id_str;
char *master_key_str;
const char *key_type;
char *keyline;
hex_string(&session_id_str, session->session_id, session->session_id_length);
hex_string(&master_key_str, session->master_key, session->master_key_length);
X509* peer = SSL_SESSION_get0_peer(session);
EVP_PKEY* pkey = X509_PUBKEY_get(peer->cert_info->key);
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
key_type = "RSA";
break;
case EVP_PKEY_DSA:
key_type = "DSA";
break;
case EVP_PKEY_EC:
key_type = "EC";
break;
default:
key_type = "Unknown";
break;
}
asprintf(&keyline, "%s Session-ID:%s Master-Key:%s\n", key_type, session_id_str,
master_key_str);
JNI_TRACE("ssl_session=%p %s", session, keyline);
free(session_id_str);
free(master_key_str);
free(keyline);
}
#endif /* WITH_JNI_TRACE_KEYS */
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake_bio(JNIEnv* env, jclass, jlong ssl_address,
jlong rbioRef, jlong wbioRef, jobject shc, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
BIO* rbio = reinterpret_cast<BIO*>(rbioRef);
BIO* wbio = reinterpret_cast<BIO*>(wbioRef);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio rbio=%p wbio=%p shc=%p client_mode=%d npn=%p",
ssl, rbio, wbio, shc, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => rbio == null || wbio == NULL", ssl);
return 0;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (!client_mode && alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
int ret = 0;
errno = 0;
if (!appData->setCallbackState(env, shc, NULL, npnProtocols, alpnProtocols)) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio exception => 0", ssl);
return 0;
}
if (ret <= 0) { // error. See SSL_do_handshake(3SSL) man page.
// error case
OpenSslError sslError(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio ret=%d errno=%d sslError=%d",
ssl, ret, errno, sslError.get());
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we need to exit to allow
* the SSLEngine code to wrap or unwrap.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
SSL_clear(ssl);
} else if (sslError.get() != SSL_ERROR_WANT_READ &&
sslError.get() != SSL_ERROR_WANT_WRITE) {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio error => 0", ssl);
return 0;
}
// success. handshake completed
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return reinterpret_cast<uintptr_t>(ssl_session);
}
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jint timeout_millis, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd=%p shc=%p timeout_millis=%d client_mode=%d npn=%p",
ssl, fdObject, shc, timeout_millis, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd == null => 0", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
NetFd fd(env, fdObject);
if (fd.isClosed()) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd.isClosed() => 0", ssl);
return 0;
}
int ret = SSL_set_fd(ssl, fd.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd.get());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE,
"Error setting the file descriptor");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake SSL_set_fd => 0", ssl);
return 0;
}
/*
* Make socket non-blocking, so SSL_connect SSL_read() and SSL_write() don't hang
* forever and we can use select() to find out if the socket is ready.
*/
if (!setBlocking(fd.get(), false)) {
throwSSLExceptionStr(env, "Unable to make socket non blocking");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setBlocking => 0", ssl);
return 0;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (client_mode) {
SSL_set_connect_state(ssl);
} else {
SSL_set_accept_state(ssl);
if (alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
}
ret = 0;
OpenSslError sslError;
while (appData->aliveAndKicking) {
errno = 0;
if (!appData->setCallbackState(env, shc, fdObject, npnProtocols, alpnProtocols)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake exception => 0", ssl);
return 0;
}
// success case
if (ret == 1) {
break;
}
// retry case
if (errno == EINTR) {
continue;
}
// error case
sslError.reset(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake ret=%d errno=%d sslError=%d timeout_millis=%d",
ssl, ret, errno, sslError.get(), timeout_millis);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we use sslSelect to
* wait for it to become ready. If that doesn't happen
* before the specified timeout or an error occurs, we
* cancel the handshake. Otherwise we try the SSL_connect
* again.
*/
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslSelect => 0", ssl);
return 0;
}
if (selectResult == -1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_SYSCALL, "handshake error",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == -1 => 0", ssl);
return 0;
}
if (selectResult == 0) {
throwSocketTimeoutException(env, "SSL handshake timed out");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == 0 => 0", ssl);
return 0;
}
} else {
// ALOGE("Unknown error %d during handshake", error);
break;
}
}
// clean error. See SSL_do_handshake(3SSL) man page.
if (ret == 0) {
/*
* The other side closed the socket before the handshake could be
* completed, but everything is within the bounds of the TLS protocol.
* We still might want to find out the real reason of the failure.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
} else {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
}
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake clean error => 0", ssl);
return 0;
}
// unclean error. See SSL_do_handshake(3SSL) man page.
if (ret < 0) {
/*
* Translate the error and throw exception. We are sure it is an error
* at this point.
*/
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "SSL handshake aborted",
throwSSLHandshakeExceptionStr);
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake unclean error => 0", ssl);
return 0;
}
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return (jlong) ssl_session;
}
/**
* Perform SSL renegotiation
*/
static void NativeCrypto_SSL_renegotiate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate", ssl);
if (ssl == NULL) {
return;
}
int result = SSL_renegotiate(ssl);
if (result != 1) {
throwSSLExceptionStr(env, "Problem with SSL_renegotiate");
return;
}
// first call asks client to perform renegotiation
int ret = SSL_do_handshake(ssl);
if (ret != 1) {
OpenSslError sslError(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"Problem with SSL_do_handshake after SSL_renegotiate");
return;
}
// if client agrees, set ssl state and perform renegotiation
ssl->state = SSL_ST_ACCEPT;
SSL_do_handshake(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate =>", ssl);
}
/**
* public static native byte[][] SSL_get_certificate(long ssl);
*/
static jlongArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl);
if (ssl == NULL) {
return NULL;
}
X509* certificate = SSL_get_certificate(ssl);
if (certificate == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
// SSL_get_certificate can return NULL during an error as well.
freeOpenSslErrorState();
return NULL;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => threw exception", ssl);
return NULL;
}
if (!sk_X509_push(chain.get(), X509_dup_nocopy(certificate))) {
jniThrowOutOfMemory(env, "Unable to push local certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
STACK_OF(X509)* cert_chain = SSL_get_certificate_chain(ssl, certificate);
for (int i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#else
STACK_OF(X509) *cert_chain = NULL;
if (!SSL_get0_chain_certs(ssl, &cert_chain)) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_chain_certs => NULL", ssl);
freeOpenSslErrorState();
return NULL;
}
for (size_t i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#endif
jlongArray refArray = getCertificateRefs(env, chain.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => %p", ssl, refArray);
return refArray;
}
// Fills a long[] with the peer certificates in the chain.
static jlongArray NativeCrypto_SSL_get_peer_cert_chain(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain", ssl);
if (ssl == NULL) {
return NULL;
}
STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl);
Unique_sk_X509 chain_copy(NULL);
if (ssl->server) {
X509* x509 = SSL_get_peer_certificate(ssl);
if (x509 == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => NULL", ssl);
return NULL;
}
chain_copy.reset(sk_X509_new_null());
if (chain_copy.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate dup error", ssl);
return NULL;
}
size_t chain_size = sk_X509_num(chain);
for (size_t i = 0; i < chain_size; i++) {
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(sk_X509_value(chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate chain push error", ssl);
return NULL;
}
}
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(x509))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate push error", ssl);
return NULL;
}
chain = chain_copy.get();
}
jlongArray refArray = getCertificateRefs(env, chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => %p", ssl, refArray);
return refArray;
}
static int sslRead(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, char* buf, jint len,
OpenSslError& sslError, int read_timeout_millis) {
JNI_TRACE("ssl=%p sslRead buf=%p len=%d", ssl, buf, len);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslRead appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
while (appData->aliveAndKicking) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslRead => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
int result = SSL_read(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p sslRead => THROWN_EXCEPTION", ssl);
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslRead SSL_read result=%d sslError=%d", ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslRead data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE: {
return result;
}
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, read_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
return -1;
}
static jint NativeCrypto_SSL_read_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray destJava,
jint destOffset, jint destLength, jlong sourceBioRef, jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sourceBioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO dest=%p sourceBio=%p sinkBio=%p shc=%p",
ssl, destJava, rbio, wbio, shc);
if (ssl == NULL) {
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => rbio == null || wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
ScopedByteArrayRW dest(env, destJava);
if (dest.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return -1;
}
if (destOffset < 0 || destOffset > ssize_t(dest.size()) || destLength < 0
|| destLength > (ssize_t) dest.size() - destOffset) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => destOffset=%d, destLength=%d, size=%zd",
ssl, destOffset, destLength, dest.size());
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => appData == NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set callback state");
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => set callback state failed", ssl);
return -1;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
int result = SSL_read(ssl, dest.get() + destOffset, destLength);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return THROWN_EXCEPTION;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO SSL_read result=%d sslError=%d", ssl, result,
sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE:
break;
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
result = -1;
break;
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
result = 0;
break;
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
result = -1;
break;
} else if (errno == EINTR) {
// System call has been interrupted. Simply retry.
result = 0;
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
return -1;
}
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => %d", ssl, result);
return result;
}
/**
* OpenSSL read function (2): read into buffer at offset n chunks.
* Returns 1 (success) or value <= 0 (failure).
*/
static jint NativeCrypto_SSL_read(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len,
jint read_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read fd=%p shc=%p b=%p offset=%d len=%d read_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, read_timeout_millis);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => fd == null", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => sslHandshakeCallbacks == null", ssl);
return 0;
}
ScopedByteArrayRW bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => threw exception", ssl);
return 0;
}
OpenSslError sslError;
int ret = sslRead(env, ssl, fdObject, shc, reinterpret_cast<char*>(bytes.get() + offset), len,
sslError, read_timeout_millis);
int result;
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslRead() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
result = -1;
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Read timed out");
result = -1;
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
// or RuntimeException thrown by callback
result = -1;
break;
default:
result = ret;
break;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => %d", ssl, result);
return result;
}
static int sslWrite(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, const char* buf, jint len,
OpenSslError& sslError, int write_timeout_millis) {
JNI_TRACE("ssl=%p sslWrite buf=%p len=%d write_timeout_millis=%d",
ssl, buf, len, write_timeout_millis);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslWrite appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
int count = len;
while (appData->aliveAndKicking && ((len > 0) || (ssl->s3->wbuf.left > 0))) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslWrite => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
JNI_TRACE("ssl=%p sslWrite SSL_write len=%d left=%d", ssl, len, ssl->s3->wbuf.left);
int result = SSL_write(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p sslWrite exception => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslWrite SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError.get(), ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslWrite data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully wrote at least one byte.
case SSL_ERROR_NONE: {
buf += result;
len -= result;
break;
}
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
// The concept of a write timeout doesn't really make sense, and
// it's also not standard Java behavior, so we wait forever here.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData,
write_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
JNI_TRACE("ssl=%p sslWrite => count=%d", ssl, count);
return count;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static int NativeCrypto_SSL_write_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray sourceJava, jint len,
jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO source=%p len=%d wbio=%p shc=%p",
ssl, sourceJava, len, wbio, shc);
if (ssl == NULL) {
return -1;
}
if (wbio == NULL) {
jniThrowNullPointerException(env, "wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO appData => NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return 0;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set appdata callback");
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => appData can't set callback", ssl);
return -1;
}
ScopedByteArrayRO source(env, sourceJava);
if (source.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => threw exception", ssl);
return -1;
}
Unique_BIO emptyBio(BIO_new_mem_buf(NULL, 0));
ScopedSslBio sslBio(ssl, emptyBio.get(), wbio);
int result = SSL_write(ssl, reinterpret_cast<const char*>(source.get()), len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO exception => exception pending (reneg)", ssl);
return -1;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError.get(), ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
case SSL_ERROR_NONE:
return result;
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
return -1;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return 0;
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
return 0;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
}
}
return -1;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static void NativeCrypto_SSL_write(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len, jint write_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write fd=%p shc=%p b=%p offset=%d len=%d write_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, write_timeout_millis);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => sslHandshakeCallbacks == null", ssl);
return;
}
ScopedByteArrayRO bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => threw exception", ssl);
return;
}
OpenSslError sslError;
int ret = sslWrite(env, ssl, fdObject, shc, reinterpret_cast<const char*>(bytes.get() + offset),
len, sslError, write_timeout_millis);
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslWrite() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Write timed out");
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
break;
default:
break;
}
}
/**
* Interrupt any pending I/O before closing the socket.
*/
static void NativeCrypto_SSL_interrupt(
JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_interrupt", ssl);
if (ssl == NULL) {
return;
}
/*
* Mark the connection as quasi-dead, then send something to the emergency
* file descriptor, so any blocking select() calls are woken up.
*/
AppData* appData = toAppData(ssl);
if (appData != NULL) {
appData->aliveAndKicking = 0;
// At most two threads can be waiting.
sslNotify(appData);
sslNotify(appData);
}
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown(JNIEnv* env, jclass, jlong ssl_address,
jobject fdObject, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown fd=%p shc=%p", ssl, fdObject, shc);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
freeOpenSslErrorState();
return;
}
/*
* Try to make socket blocking again. OpenSSL literature recommends this.
*/
int fd = SSL_get_fd(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown s=%d", ssl, fd);
if (fd != -1) {
setBlocking(fd, true);
}
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
SSL_clear(ssl);
freeOpenSslErrorState();
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown_BIO(JNIEnv* env, jclass, jlong ssl_address, jlong rbioRef,
jlong wbioRef, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(rbioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(wbioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown rbio=%p wbio=%p shc=%p", ssl, rbio, wbio, shc);
if (ssl == NULL) {
return;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => rbio == null || wbio == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
SSL_clear(ssl);
freeOpenSslErrorState();
return;
}
ScopedSslBio scopedBio(ssl, rbio, wbio);
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
SSL_clear(ssl);
freeOpenSslErrorState();
}
static jint NativeCrypto_SSL_get_shutdown(JNIEnv* env, jclass, jlong ssl_address) {
const SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown", ssl);
if (ssl == NULL) {
jniThrowNullPointerException(env, "ssl == null");
return 0;
}
int status = SSL_get_shutdown(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown => %d", ssl, status);
return static_cast<jint>(status);
}
/**
* public static native void SSL_free(long ssl);
*/
static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl);
if (ssl == NULL) {
return;
}
AppData* appData = toAppData(ssl);
SSL_set_app_data(ssl, NULL);
delete appData;
SSL_free(ssl);
}
/**
* Gets and returns in a byte array the ID of the actual SSL session.
*/
static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass,
jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
jbyteArray result = env->NewByteArray(ssl_session->session_id_length);
if (result != NULL) {
jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id);
env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src);
}
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d",
ssl_session, result, ssl_session->session_id_length);
return result;
}
/**
* Gets and returns in a long integer the creation's time of the
* actual SSL session.
*/
static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session);
if (ssl_session == NULL) {
return 0;
}
// result must be jlong, not long or *1000 will overflow
jlong result = SSL_SESSION_get_time(ssl_session);
result *= 1000; // OpenSSL uses seconds, Java uses milliseconds.
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, (long long) result);
return result;
}
/**
* Gets and returns in a string the version of the SSL protocol. If it
* returns the string "unknown" it means that no connection is established.
*/
static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const char* protocol = SSL_SESSION_get_version(ssl_session);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol);
return env->NewStringUTF(protocol);
}
/**
* Gets and returns in a string the cipher negotiated for the SSL session.
*/
static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const SSL_CIPHER* cipher = ssl_session->cipher;
const char* name = SSL_CIPHER_get_name(cipher);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name);
return env->NewStringUTF(name);
}
/**
* Frees the SSL session.
*/
static void NativeCrypto_SSL_SESSION_free(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session);
if (ssl_session == NULL) {
return;
}
SSL_SESSION_free(ssl_session);
}
/**
* Serializes the native state of the session (ID, cipher, and keys but
* not certificates). Returns a byte[] containing the DER-encoded state.
* See apache mod_ssl.
*/
static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
return ASN1ToByteArray<SSL_SESSION>(env, ssl_session, i2d_SSL_SESSION);
}
/**
* Deserialize the session.
*/
static jlong NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => threw exception");
return 0;
}
const unsigned char* ucp = reinterpret_cast<const unsigned char*>(bytes.get());
SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, bytes.size());
#if !defined(OPENSSL_IS_BORINGSSL)
// Initialize SSL_SESSION cipher field based on cipher_id http://b/7091840
if (ssl_session != NULL) {
// based on ssl_get_prev_session
uint32_t cipher_id_network_order = htonl(ssl_session->cipher_id);
uint8_t* cipher_id_byte_pointer = reinterpret_cast<uint8_t*>(&cipher_id_network_order);
if (ssl_session->ssl_version >= SSL3_VERSION_MAJOR) {
cipher_id_byte_pointer += 2; // skip first two bytes for SSL3+
} else {
cipher_id_byte_pointer += 1; // skip first byte for SSL2
}
ssl_session->cipher = SSLv23_method()->get_cipher_by_char(cipher_id_byte_pointer);
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION cipher_id=%lx hton=%x 0=%x 1=%x cipher=%s",
ssl_session->cipher_id, cipher_id_network_order,
cipher_id_byte_pointer[0], cipher_id_byte_pointer[1],
SSL_CIPHER_get_name(ssl_session->cipher));
}
#endif
if (ssl_session == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session);
return reinterpret_cast<uintptr_t>(ssl_session);
}
static jlong NativeCrypto_ERR_peek_last_error(JNIEnv*, jclass) {
return ERR_peek_last_error();
}
#define FILE_DESCRIPTOR "Ljava/io/FileDescriptor;"
#define SSL_CALLBACKS "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto$SSLHandshakeCallbacks;"
#define REF_EC_GROUP "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_GROUP;"
#define REF_EC_POINT "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_POINT;"
#define REF_EVP_CIPHER_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_CIPHER_CTX;"
#define REF_EVP_PKEY "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_PKEY;"
static JNINativeMethod sNativeCryptoMethods[] = {
NATIVE_METHOD(NativeCrypto, clinit, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_dynamic, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_by_id, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_add, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_init, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_finish, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_free, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_private_key, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_get_id, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, ENGINE_ctrl_cmd_string, "(JLjava/lang/String;Ljava/lang/String;I)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DH, "([B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_RSA, "([B[B[B[B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_EC_KEY, "(" REF_EC_GROUP REF_EC_POINT "[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_mac_key, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_type, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_public, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_private, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_cmp, "(" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS8_PRIV_KEY_INFO, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS8_PRIV_KEY_INFO, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_PUBKEY, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PUBKEY, "([B)J"),
NATIVE_METHOD(NativeCrypto, getRSAPrivateKeyWrapper, "(Ljava/security/interfaces/RSAPrivateKey;[B)J"),
NATIVE_METHOD(NativeCrypto, getECPrivateKeyWrapper, "(Ljava/security/interfaces/ECPrivateKey;" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, RSA_generate_key_ex, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, RSA_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, RSA_private_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, get_RSA_private_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, get_RSA_public_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, DH_generate_parameters_ex, "(IJ)J"),
NATIVE_METHOD(NativeCrypto, DH_generate_key, "(" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_DH_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_by_curve_name, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_asn1_flag, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_point_conversion_form, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve_name, "(" REF_EC_GROUP ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve, "(" REF_EC_GROUP ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_order, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_degree, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_cofactor, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_cmp, "(" REF_EC_GROUP REF_EC_GROUP ")Z"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_generator, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, get_EC_GROUP_type, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_POINT_new, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_POINT_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_cmp, "(" REF_EC_GROUP REF_EC_POINT REF_EC_POINT ")Z"),
NATIVE_METHOD(NativeCrypto, EC_POINT_set_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT "[B[B)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_get_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_generate_key, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get1_group, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_private_key, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_public_key, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_set_nonce_from_hash, "(" REF_EVP_PKEY "Z)V"),
NATIVE_METHOD(NativeCrypto, ECDH_compute_key, "([BI" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_create, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_init, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_destroy, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_copy, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_get_digestbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_SignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BI" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[B)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)[B"),
NATIVE_METHOD(NativeCrypto, EVP_get_cipherbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_CipherInit_ex, "(" REF_EVP_CIPHER_CTX "J[B[BZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CipherUpdate, "(" REF_EVP_CIPHER_CTX "[BI[BII)I"),
NATIVE_METHOD(NativeCrypto, EVP_CipherFinal_ex, "(" REF_EVP_CIPHER_CTX "[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_iv_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_block_size, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_buf_len, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_padding, "(" REF_EVP_CIPHER_CTX "Z)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_key_length, "(" REF_EVP_CIPHER_CTX "I)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_cleanup, "(J)V"),
NATIVE_METHOD(NativeCrypto, RAND_seed, "([B)V"),
NATIVE_METHOD(NativeCrypto, RAND_load_file, "(Ljava/lang/String;J)I"),
NATIVE_METHOD(NativeCrypto, RAND_bytes, "([B)V"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid, "(Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_longName, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_oid, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, create_BIO_InputStream, ("(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream;)J")),
NATIVE_METHOD(NativeCrypto, create_BIO_OutputStream, "(Ljava/io/OutputStream;)J"),
NATIVE_METHOD(NativeCrypto, BIO_read, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, BIO_write, "(J[BII)V"),
NATIVE_METHOD(NativeCrypto, BIO_free_all, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_NAME_print_ex, "(JJ)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, d2i_X509_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, d2i_X509, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509, "(J)[B"),
NATIVE_METHOD(NativeCrypto, i2d_X509_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS7, "([J)[B"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_unpack_X509_bio, "(J)[J"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_pack_X509, "([J)[B"),
NATIVE_METHOD(NativeCrypto, X509_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, get_X509_hashCode, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_print_ex, "(JJJJ)V"),
NATIVE_METHOD(NativeCrypto, X509_get_pubkey, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_get_subject_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_pubkey_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_issuerUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_subjectUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_kusage, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_xkusage, "(J)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_pathlen, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_crl_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_lastUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_nextUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_revocationDate, "(J)J"),
NATIVE_METHOD(NativeCrypto, get_X509_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_GENERAL_NAME_stack, "(JI)[[Ljava/lang/Object;"),
NATIVE_METHOD(NativeCrypto, X509_get_notBefore, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_notAfter, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_X509_cert_info_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_flags, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_check_issued, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, d2i_X509_CRL_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509_CRL, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_cert, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_serial, "(J[B)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_REVOKED, "(J)[J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_CRL, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_REVOKED, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_supported_extension, "(J)I"),
NATIVE_METHOD(NativeCrypto, ASN1_TIME_to_Calendar, "(JLjava/util/Calendar;)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_session_id_context, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_tls_channel_id, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_tls_channel_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set1_tls_channel_id, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_PrivateKey, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_certificate, "(J[J)V"),
NATIVE_METHOD(NativeCrypto, SSL_check_private_key, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_client_CA_list, "(J[[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_mode, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_get_options, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_use_psk_identity_hint, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_client_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_server_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_cipher_lists, "(J[Ljava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ciphers, "(J)[J"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_auth, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_mkey, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_set_accept_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_connect_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_verify, "(JI)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session_creation_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_tlsext_host_name, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_servername, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "IZ[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake_bio, "(JJJ" SSL_CALLBACKS "Z[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_renegotiate, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_certificate, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_get_peer_cert_chain, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_read, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)I"),
NATIVE_METHOD(NativeCrypto, SSL_read_BIO, "(J[BIIJJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_write, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)V"),
NATIVE_METHOD(NativeCrypto, SSL_write_BIO, "(J[BIJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_interrupt, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown, "(J" FILE_DESCRIPTOR SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown_BIO, "(JJJ" SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_get_shutdown, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_session_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_time, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_version, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_cipher, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, i2d_SSL_SESSION, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_SSL_SESSION, "([B)J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_enable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_disable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_npn_negotiated_protocol, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set_alpn_protos, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, SSL_get0_alpn_selected, "(J)[B"),
NATIVE_METHOD(NativeCrypto, ERR_peek_last_error, "()J"),
};
static jclass getGlobalRefToClass(JNIEnv* env, const char* className) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(className));
jclass globalRef = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (globalRef == NULL) {
ALOGE("failed to find class %s", className);
abort();
}
return globalRef;
}
static jmethodID getMethodRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jmethodID localMethod = env->GetMethodID(clazz, name, sig);
if (localMethod == NULL) {
ALOGE("could not find method %s", name);
abort();
}
return localMethod;
}
static jfieldID getFieldRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jfieldID localField = env->GetFieldID(clazz, name, sig);
if (localField == NULL) {
ALOGE("could not find field %s", name);
abort();
}
return localField;
}
static void initialize_conscrypt(JNIEnv* env) {
jniRegisterNativeMethods(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto",
sNativeCryptoMethods, NELEM(sNativeCryptoMethods));
cryptoUpcallsClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/CryptoUpcalls");
nativeRefClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef");
openSslInputStreamClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream");
nativeRef_context = getFieldRef(env, nativeRefClass, "context", "J");
calendar_setMethod = getMethodRef(env, calendarClass, "set", "(IIIIII)V");
inputStream_readMethod = getMethodRef(env, inputStreamClass, "read", "([B)I");
integer_valueOfMethod = env->GetStaticMethodID(integerClass, "valueOf",
"(I)Ljava/lang/Integer;");
openSslInputStream_readLineMethod = getMethodRef(env, openSslInputStreamClass, "gets",
"([B)I");
outputStream_writeMethod = getMethodRef(env, outputStreamClass, "write", "([B)V");
outputStream_flushMethod = getMethodRef(env, outputStreamClass, "flush", "()V");
#ifdef CONSCRYPT_UNBUNDLED
findAsynchronousCloseMonitorFuncs();
#endif
}
static jclass findClass(JNIEnv* env, const char* name) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(name));
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (result == NULL) {
ALOGE("failed to find class '%s'", name);
abort();
}
return result;
}
#ifdef STATIC_LIB
// Give client libs everything they need to initialize our JNI
int libconscrypt_JNI_OnLoad(JavaVM *vm, void*) {
#else
// Use JNI_OnLoad for when we're standalone
int JNI_OnLoad(JavaVM *vm, void*) {
JNI_TRACE("JNI_OnLoad NativeCrypto");
#endif
gJavaVM = vm;
JNIEnv *env;
if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
ALOGE("Could not get JNIEnv");
return JNI_ERR;
}
byteArrayClass = findClass(env, "[B");
calendarClass = findClass(env, "java/util/Calendar");
inputStreamClass = findClass(env, "java/io/InputStream");
integerClass = findClass(env, "java/lang/Integer");
objectClass = findClass(env, "java/lang/Object");
objectArrayClass = findClass(env, "[Ljava/lang/Object;");
outputStreamClass = findClass(env, "java/io/OutputStream");
stringClass = findClass(env, "java/lang/String");
initialize_conscrypt(env);
return JNI_VERSION_1_6;
}
am 86dd832a: Clear SSL state safely
* commit '86dd832ac26112890b3e815a144ff062ae9b3559':
Clear SSL state safely
/*
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Native glue for Java class org.conscrypt.NativeCrypto
*/
#define TO_STRING1(x) #x
#define TO_STRING(x) TO_STRING1(x)
#ifndef JNI_JARJAR_PREFIX
#ifndef CONSCRYPT_NOT_UNBUNDLED
#define CONSCRYPT_UNBUNDLED
#endif
#define JNI_JARJAR_PREFIX
#endif
#define LOG_TAG "NativeCrypto"
#include <arpa/inet.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef CONSCRYPT_UNBUNDLED
#include <dlfcn.h>
#endif
#include <jni.h>
#include <openssl/asn1t.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#if !defined(OPENSSL_IS_BORINGSSL)
#include "crypto/ecdsa/ecs_locl.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
/* If we're compiled unbundled from Android system image, we use the
* CompatibilityCloseMonitor
*/
#include "AsynchronousCloseMonitor.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "cutils/log.h"
#else
#include <android/log.h>
#include "log_compat.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
#else
#define NATIVE_METHOD(className, functionName, signature) \
{ #functionName, signature, reinterpret_cast<void*>(className ## _ ## functionName) }
#define REGISTER_NATIVE_METHODS(jni_class_name) \
RegisterNativeMethods(env, jni_class_name, gMethods, arraysize(gMethods))
#endif
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#include "NetFd.h"
#undef WITH_JNI_TRACE
#undef WITH_JNI_TRACE_MD
#undef WITH_JNI_TRACE_DATA
/*
* How to use this for debugging with Wireshark:
*
* 1. Pull lines from logcat to a file that looks like (without quotes):
* "RSA Session-ID:... Master-Key:..." <CR>
* "RSA Session-ID:... Master-Key:..." <CR>
* <etc>
* 2. Start Wireshark
* 3. Go to Edit -> Preferences -> SSL -> (Pre-)Master-Key log and fill in
* the file you put the lines in above.
* 4. Follow the stream that corresponds to the desired "Session-ID" in
* the Server Hello.
*/
#undef WITH_JNI_TRACE_KEYS
#ifdef WITH_JNI_TRACE
#define JNI_TRACE(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__))
#else
#define JNI_TRACE(...) ((void)0)
#endif
#ifdef WITH_JNI_TRACE_MD
#define JNI_TRACE_MD(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__));
#else
#define JNI_TRACE_MD(...) ((void)0)
#endif
// don't overwhelm logcat
#define WITH_JNI_TRACE_DATA_CHUNK_SIZE 512
static JavaVM* gJavaVM;
static jclass cryptoUpcallsClass;
static jclass openSslInputStreamClass;
static jclass nativeRefClass;
static jclass byteArrayClass;
static jclass calendarClass;
static jclass objectClass;
static jclass objectArrayClass;
static jclass integerClass;
static jclass inputStreamClass;
static jclass outputStreamClass;
static jclass stringClass;
static jfieldID nativeRef_context;
static jmethodID calendar_setMethod;
static jmethodID inputStream_readMethod;
static jmethodID integer_valueOfMethod;
static jmethodID openSslInputStream_readLineMethod;
static jmethodID outputStream_writeMethod;
static jmethodID outputStream_flushMethod;
struct OPENSSL_Delete {
void operator()(void* p) const {
OPENSSL_free(p);
}
};
typedef UniquePtr<unsigned char, OPENSSL_Delete> Unique_OPENSSL_str;
struct BIO_Delete {
void operator()(BIO* p) const {
BIO_free_all(p);
}
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
struct BIGNUM_Delete {
void operator()(BIGNUM* p) const {
BN_free(p);
}
};
typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
struct ASN1_INTEGER_Delete {
void operator()(ASN1_INTEGER* p) const {
ASN1_INTEGER_free(p);
}
};
typedef UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> Unique_ASN1_INTEGER;
struct DH_Delete {
void operator()(DH* p) const {
DH_free(p);
}
};
typedef UniquePtr<DH, DH_Delete> Unique_DH;
struct DSA_Delete {
void operator()(DSA* p) const {
DSA_free(p);
}
};
typedef UniquePtr<DSA, DSA_Delete> Unique_DSA;
struct EC_GROUP_Delete {
void operator()(EC_GROUP* p) const {
EC_GROUP_free(p);
}
};
typedef UniquePtr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP;
struct EC_POINT_Delete {
void operator()(EC_POINT* p) const {
EC_POINT_clear_free(p);
}
};
typedef UniquePtr<EC_POINT, EC_POINT_Delete> Unique_EC_POINT;
struct EC_KEY_Delete {
void operator()(EC_KEY* p) const {
EC_KEY_free(p);
}
};
typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
struct EVP_MD_CTX_Delete {
void operator()(EVP_MD_CTX* p) const {
EVP_MD_CTX_destroy(p);
}
};
typedef UniquePtr<EVP_MD_CTX, EVP_MD_CTX_Delete> Unique_EVP_MD_CTX;
struct EVP_CIPHER_CTX_Delete {
void operator()(EVP_CIPHER_CTX* p) const {
EVP_CIPHER_CTX_free(p);
}
};
typedef UniquePtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_Delete> Unique_EVP_CIPHER_CTX;
struct EVP_PKEY_Delete {
void operator()(EVP_PKEY* p) const {
EVP_PKEY_free(p);
}
};
typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
struct PKCS8_PRIV_KEY_INFO_Delete {
void operator()(PKCS8_PRIV_KEY_INFO* p) const {
PKCS8_PRIV_KEY_INFO_free(p);
}
};
typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
struct RSA_Delete {
void operator()(RSA* p) const {
RSA_free(p);
}
};
typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
struct ASN1_BIT_STRING_Delete {
void operator()(ASN1_BIT_STRING* p) const {
ASN1_BIT_STRING_free(p);
}
};
typedef UniquePtr<ASN1_BIT_STRING, ASN1_BIT_STRING_Delete> Unique_ASN1_BIT_STRING;
struct ASN1_OBJECT_Delete {
void operator()(ASN1_OBJECT* p) const {
ASN1_OBJECT_free(p);
}
};
typedef UniquePtr<ASN1_OBJECT, ASN1_OBJECT_Delete> Unique_ASN1_OBJECT;
struct ASN1_GENERALIZEDTIME_Delete {
void operator()(ASN1_GENERALIZEDTIME* p) const {
ASN1_GENERALIZEDTIME_free(p);
}
};
typedef UniquePtr<ASN1_GENERALIZEDTIME, ASN1_GENERALIZEDTIME_Delete> Unique_ASN1_GENERALIZEDTIME;
struct SSL_Delete {
void operator()(SSL* p) const {
SSL_free(p);
}
};
typedef UniquePtr<SSL, SSL_Delete> Unique_SSL;
struct SSL_CTX_Delete {
void operator()(SSL_CTX* p) const {
SSL_CTX_free(p);
}
};
typedef UniquePtr<SSL_CTX, SSL_CTX_Delete> Unique_SSL_CTX;
struct X509_Delete {
void operator()(X509* p) const {
X509_free(p);
}
};
typedef UniquePtr<X509, X509_Delete> Unique_X509;
struct X509_NAME_Delete {
void operator()(X509_NAME* p) const {
X509_NAME_free(p);
}
};
typedef UniquePtr<X509_NAME, X509_NAME_Delete> Unique_X509_NAME;
#if !defined(OPENSSL_IS_BORINGSSL)
struct PKCS7_Delete {
void operator()(PKCS7* p) const {
PKCS7_free(p);
}
};
typedef UniquePtr<PKCS7, PKCS7_Delete> Unique_PKCS7;
#endif
struct sk_SSL_CIPHER_Delete {
void operator()(STACK_OF(SSL_CIPHER)* p) const {
// We don't own SSL_CIPHER references, so no need for pop_free
sk_SSL_CIPHER_free(p);
}
};
typedef UniquePtr<STACK_OF(SSL_CIPHER), sk_SSL_CIPHER_Delete> Unique_sk_SSL_CIPHER;
struct sk_X509_Delete {
void operator()(STACK_OF(X509)* p) const {
sk_X509_pop_free(p, X509_free);
}
};
typedef UniquePtr<STACK_OF(X509), sk_X509_Delete> Unique_sk_X509;
struct sk_X509_NAME_Delete {
void operator()(STACK_OF(X509_NAME)* p) const {
sk_X509_NAME_pop_free(p, X509_NAME_free);
}
};
typedef UniquePtr<STACK_OF(X509_NAME), sk_X509_NAME_Delete> Unique_sk_X509_NAME;
struct sk_ASN1_OBJECT_Delete {
void operator()(STACK_OF(ASN1_OBJECT)* p) const {
sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
}
};
typedef UniquePtr<STACK_OF(ASN1_OBJECT), sk_ASN1_OBJECT_Delete> Unique_sk_ASN1_OBJECT;
struct sk_GENERAL_NAME_Delete {
void operator()(STACK_OF(GENERAL_NAME)* p) const {
sk_GENERAL_NAME_pop_free(p, GENERAL_NAME_free);
}
};
typedef UniquePtr<STACK_OF(GENERAL_NAME), sk_GENERAL_NAME_Delete> Unique_sk_GENERAL_NAME;
/**
* Many OpenSSL APIs take ownership of an argument on success but don't free the argument
* on failure. This means we need to tell our scoped pointers when we've transferred ownership,
* without triggering a warning by not using the result of release().
*/
#define OWNERSHIP_TRANSFERRED(obj) \
do { typeof (obj.release()) _dummy __attribute__((unused)) = obj.release(); } while(0)
/**
* Frees the SSL error state.
*
* OpenSSL keeps an "error stack" per thread, and given that this code
* can be called from arbitrary threads that we don't keep track of,
* we err on the side of freeing the error state promptly (instead of,
* say, at thread death).
*/
static void freeOpenSslErrorState(void) {
ERR_clear_error();
ERR_remove_thread_state(NULL);
}
/**
* Manages the freeing of the OpenSSL error stack. This allows you to
* instantiate this object during an SSL call that may fail and not worry
* about manually calling freeOpenSslErrorState() later.
*
* As an optimization, you can also call .release() for passing as an
* argument to things that free the error stack state as a side-effect.
*/
class OpenSslError {
public:
OpenSslError() : sslError_(SSL_ERROR_NONE), released_(false) {
}
OpenSslError(SSL* ssl, int returnCode) : sslError_(SSL_ERROR_NONE), released_(false) {
reset(ssl, returnCode);
}
~OpenSslError() {
if (!released_ && sslError_ != SSL_ERROR_NONE) {
freeOpenSslErrorState();
}
}
int get() const {
return sslError_;
}
void reset(SSL* ssl, int returnCode) {
if (returnCode <= 0) {
sslError_ = SSL_get_error(ssl, returnCode);
} else {
sslError_ = SSL_ERROR_NONE;
}
}
int release() {
released_ = true;
return sslError_;
}
private:
int sslError_;
bool released_;
};
/**
* Throws a OutOfMemoryError with the given string as a message.
*/
static void jniThrowOutOfMemory(JNIEnv* env, const char* message) {
jniThrowException(env, "java/lang/OutOfMemoryError", message);
}
/**
* Throws a BadPaddingException with the given string as a message.
*/
static void throwBadPaddingException(JNIEnv* env, const char* message) {
JNI_TRACE("throwBadPaddingException %s", message);
jniThrowException(env, "javax/crypto/BadPaddingException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwSignatureException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSignatureException %s", message);
jniThrowException(env, "java/security/SignatureException", message);
}
/**
* Throws a InvalidKeyException with the given string as a message.
*/
static void throwInvalidKeyException(JNIEnv* env, const char* message) {
JNI_TRACE("throwInvalidKeyException %s", message);
jniThrowException(env, "java/security/InvalidKeyException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static void throwIllegalBlockSizeException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalBlockSizeException %s", message);
jniThrowException(env, "javax/crypto/IllegalBlockSizeException", message);
}
/**
* Throws a NoSuchAlgorithmException with the given string as a message.
*/
static void throwNoSuchAlgorithmException(JNIEnv* env, const char* message) {
JNI_TRACE("throwUnknownAlgorithmException %s", message);
jniThrowException(env, "java/security/NoSuchAlgorithmException", message);
}
static void throwForAsn1Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case ASN1_R_UNABLE_TO_DECODE_RSA_KEY:
case ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY:
case ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE:
case ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE:
// These #if sections can be removed once BoringSSL is landed.
#if defined(ASN1_R_WRONG_PUBLIC_KEY_TYPE)
case ASN1_R_WRONG_PUBLIC_KEY_TYPE:
throwInvalidKeyException(env, message);
break;
#endif
#if defined(ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
#endif
default:
jniThrowRuntimeException(env, message);
break;
}
}
#if defined(OPENSSL_IS_BORINGSSL)
static void throwForCipherError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case CIPHER_R_BAD_DECRYPT:
throwBadPaddingException(env, message);
break;
case CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case CIPHER_R_WRONG_FINAL_BLOCK_LENGTH:
throwIllegalBlockSizeException(env, message);
break;
case CIPHER_R_AES_KEY_SETUP_FAILED:
case CIPHER_R_BAD_KEY_LENGTH:
case CIPHER_R_UNSUPPORTED_KEY_SIZE:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForEvpError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case EVP_R_MISSING_PARAMETERS:
throwInvalidKeyException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
case EVP_R_X931_UNSUPPORTED:
throwNoSuchAlgorithmException(env, message);
break;
// These #if sections can be make unconditional once BoringSSL is landed.
#if defined(EVP_R_WRONG_PUBLIC_KEY_TYPE)
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
throwInvalidKeyException(env, message);
break;
#endif
#if defined(EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
#endif
default:
jniThrowRuntimeException(env, message);
break;
}
}
#else
static void throwForEvpError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case EVP_R_BAD_DECRYPT:
throwBadPaddingException(env, message);
break;
case EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case EVP_R_WRONG_FINAL_BLOCK_LENGTH:
throwIllegalBlockSizeException(env, message);
break;
case EVP_R_BAD_KEY_LENGTH:
case EVP_R_BN_DECODE_ERROR:
case EVP_R_BN_PUBKEY_ERROR:
case EVP_R_INVALID_KEY_LENGTH:
case EVP_R_MISSING_PARAMETERS:
case EVP_R_UNSUPPORTED_KEY_SIZE:
case EVP_R_UNSUPPORTED_KEYLENGTH:
throwInvalidKeyException(env, message);
break;
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
throwSignatureException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
#endif
static void throwForRsaError(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case RSA_R_BLOCK_TYPE_IS_NOT_01:
case RSA_R_BLOCK_TYPE_IS_NOT_02:
throwBadPaddingException(env, message);
break;
case RSA_R_BAD_SIGNATURE:
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
case RSA_R_INVALID_MESSAGE_LENGTH:
case RSA_R_WRONG_SIGNATURE_LENGTH:
#if !defined(OPENSSL_IS_BORINGSSL)
case RSA_R_ALGORITHM_MISMATCH:
case RSA_R_DATA_GREATER_THAN_MOD_LEN:
#endif
throwSignatureException(env, message);
break;
case RSA_R_UNKNOWN_ALGORITHM_TYPE:
throwNoSuchAlgorithmException(env, message);
break;
case RSA_R_MODULUS_TOO_LARGE:
case RSA_R_NO_PUBLIC_EXPONENT:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
static void throwForX509Error(JNIEnv* env, int reason, const char *message) {
switch (reason) {
case X509_R_UNSUPPORTED_ALGORITHM:
throwNoSuchAlgorithmException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
}
/*
* Checks this thread's OpenSSL error queue and throws a RuntimeException if
* necessary.
*
* @return true if an exception was thrown, false if not.
*/
static bool throwExceptionIfNecessary(JNIEnv* env, const char* location __attribute__ ((unused))) {
const char* file;
int line;
const char* data;
int flags;
unsigned long error = ERR_get_error_line_data(&file, &line, &data, &flags);
int result = false;
if (error != 0) {
char message[256];
ERR_error_string_n(error, message, sizeof(message));
int library = ERR_GET_LIB(error);
int reason = ERR_GET_REASON(error);
JNI_TRACE("OpenSSL error in %s error=%lx library=%x reason=%x (%s:%d): %s %s",
location, error, library, reason, file, line, message,
(flags & ERR_TXT_STRING) ? data : "(no data)");
switch (library) {
case ERR_LIB_RSA:
throwForRsaError(env, reason, message);
break;
case ERR_LIB_ASN1:
throwForAsn1Error(env, reason, message);
break;
#if defined(OPENSSL_IS_BORINGSSL)
case ERR_LIB_CIPHER:
throwForCipherError(env, reason, message);
break;
#endif
case ERR_LIB_EVP:
throwForEvpError(env, reason, message);
break;
case ERR_LIB_X509:
throwForX509Error(env, reason, message);
break;
case ERR_LIB_DSA:
throwInvalidKeyException(env, message);
break;
default:
jniThrowRuntimeException(env, message);
break;
}
result = true;
}
freeOpenSslErrorState();
return result;
}
/**
* Throws an SocketTimeoutException with the given string as a message.
*/
static void throwSocketTimeoutException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSocketTimeoutException %s", message);
jniThrowException(env, "java/net/SocketTimeoutException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLHandshakeExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLHandshakeException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static void throwSSLExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLException", message);
}
/**
* Throws a javax.net.ssl.SSLProcotolException with the given string as a message.
*/
static void throwSSLProtocolExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLProtocolExceptionStr %s", message);
jniThrowException(env, "javax/net/ssl/SSLProtocolException", message);
}
/**
* Throws an SSLException with a message constructed from the current
* SSL errors. This will also log the errors.
*
* @param env the JNI environment
* @param ssl the possibly NULL SSL
* @param sslErrorCode error code returned from SSL_get_error() or
* SSL_ERROR_NONE to probe with ERR_get_error
* @param message null-ok; general error message
*/
static void throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCode,
const char* message, void (*actualThrow)(JNIEnv*, const char*) = throwSSLExceptionStr) {
if (message == NULL) {
message = "SSL error";
}
// First consult the SSL error code for the general message.
const char* sslErrorStr = NULL;
switch (sslErrorCode) {
case SSL_ERROR_NONE:
if (ERR_peek_error() == 0) {
sslErrorStr = "OK";
} else {
sslErrorStr = "";
}
break;
case SSL_ERROR_SSL:
sslErrorStr = "Failure in SSL library, usually a protocol error";
break;
case SSL_ERROR_WANT_READ:
sslErrorStr = "SSL_ERROR_WANT_READ occurred. You should never see this.";
break;
case SSL_ERROR_WANT_WRITE:
sslErrorStr = "SSL_ERROR_WANT_WRITE occurred. You should never see this.";
break;
case SSL_ERROR_WANT_X509_LOOKUP:
sslErrorStr = "SSL_ERROR_WANT_X509_LOOKUP occurred. You should never see this.";
break;
case SSL_ERROR_SYSCALL:
sslErrorStr = "I/O error during system call";
break;
case SSL_ERROR_ZERO_RETURN:
sslErrorStr = "SSL_ERROR_ZERO_RETURN occurred. You should never see this.";
break;
case SSL_ERROR_WANT_CONNECT:
sslErrorStr = "SSL_ERROR_WANT_CONNECT occurred. You should never see this.";
break;
case SSL_ERROR_WANT_ACCEPT:
sslErrorStr = "SSL_ERROR_WANT_ACCEPT occurred. You should never see this.";
break;
default:
sslErrorStr = "Unknown SSL error";
}
// Prepend either our explicit message or a default one.
char* str;
if (asprintf(&str, "%s: ssl=%p: %s", message, ssl, sslErrorStr) <= 0) {
// problem with asprintf, just throw argument message, log everything
actualThrow(env, message);
ALOGV("%s: ssl=%p: %s", message, ssl, sslErrorStr);
freeOpenSslErrorState();
return;
}
char* allocStr = str;
// For protocol errors, SSL might have more information.
if (sslErrorCode == SSL_ERROR_NONE || sslErrorCode == SSL_ERROR_SSL) {
// Append each error as an additional line to the message.
for (;;) {
char errStr[256];
const char* file;
int line;
const char* data;
int flags;
unsigned long err = ERR_get_error_line_data(&file, &line, &data, &flags);
if (err == 0) {
break;
}
ERR_error_string_n(err, errStr, sizeof(errStr));
int ret = asprintf(&str, "%s\n%s (%s:%d %p:0x%08x)",
(allocStr == NULL) ? "" : allocStr,
errStr,
file,
line,
(flags & ERR_TXT_STRING) ? data : "(no data)",
flags);
if (ret < 0) {
break;
}
free(allocStr);
allocStr = str;
}
// For errors during system calls, errno might be our friend.
} else if (sslErrorCode == SSL_ERROR_SYSCALL) {
if (asprintf(&str, "%s, %s", allocStr, strerror(errno)) >= 0) {
free(allocStr);
allocStr = str;
}
// If the error code is invalid, print it.
} else if (sslErrorCode > SSL_ERROR_WANT_ACCEPT) {
if (asprintf(&str, ", error code is %d", sslErrorCode) >= 0) {
free(allocStr);
allocStr = str;
}
}
if (sslErrorCode == SSL_ERROR_SSL) {
throwSSLProtocolExceptionStr(env, allocStr);
} else {
actualThrow(env, allocStr);
}
ALOGV("%s", allocStr);
free(allocStr);
freeOpenSslErrorState();
}
/**
* Helper function that grabs the casts an ssl pointer and then checks for nullness.
* If this function returns NULL and <code>throwIfNull</code> is
* passed as <code>true</code>, then this function will call
* <code>throwSSLExceptionStr</code> before returning, so in this case of
* NULL, a caller of this function should simply return and allow JNI
* to do its thing.
*
* @param env the JNI environment
* @param ssl_address; the ssl_address pointer as an integer
* @param throwIfNull whether to throw if the SSL pointer is NULL
* @returns the pointer, which may be NULL
*/
static SSL_CTX* to_SSL_CTX(JNIEnv* env, jlong ssl_ctx_address, bool throwIfNull) {
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
if ((ssl_ctx == NULL) && throwIfNull) {
JNI_TRACE("ssl_ctx == null");
jniThrowNullPointerException(env, "ssl_ctx == null");
}
return ssl_ctx;
}
static SSL* to_SSL(JNIEnv* env, jlong ssl_address, bool throwIfNull) {
SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
if ((ssl == NULL) && throwIfNull) {
JNI_TRACE("ssl == null");
jniThrowNullPointerException(env, "ssl == null");
}
return ssl;
}
static SSL_SESSION* to_SSL_SESSION(JNIEnv* env, jlong ssl_session_address, bool throwIfNull) {
SSL_SESSION* ssl_session
= reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
if ((ssl_session == NULL) && throwIfNull) {
JNI_TRACE("ssl_session == null");
jniThrowNullPointerException(env, "ssl_session == null");
}
return ssl_session;
}
static SSL_CIPHER* to_SSL_CIPHER(JNIEnv* env, jlong ssl_cipher_address, bool throwIfNull) {
SSL_CIPHER* ssl_cipher
= reinterpret_cast<SSL_CIPHER*>(static_cast<uintptr_t>(ssl_cipher_address));
if ((ssl_cipher == NULL) && throwIfNull) {
JNI_TRACE("ssl_cipher == null");
jniThrowNullPointerException(env, "ssl_cipher == null");
}
return ssl_cipher;
}
template<typename T>
static T* fromContextObject(JNIEnv* env, jobject contextObject) {
T* ref = reinterpret_cast<T*>(env->GetLongField(contextObject, nativeRef_context));
if (ref == NULL) {
JNI_TRACE("ctx == null");
jniThrowNullPointerException(env, "ctx == null");
}
return ref;
}
/**
* Converts a Java byte[] two's complement to an OpenSSL BIGNUM. This will
* allocate the BIGNUM if *dest == NULL. Returns true on success. If the
* return value is false, there is a pending exception.
*/
static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
JNI_TRACE("arrayToBignum(%p, %p)", source, dest);
if (dest == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => dest is null!", source, dest);
jniThrowNullPointerException(env, "dest == null");
return false;
}
JNI_TRACE("arrayToBignum(%p, %p) *dest == %p", source, dest, *dest);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
/* if the array is empty, it is zero. */
if (tmpSize == 0) {
if (*dest == NULL) {
*dest = BN_new();
}
BN_zero(*dest);
return true;
}
UniquePtr<unsigned char[]> twosComplement;
bool negative = (tmp[0] & 0x80) != 0;
if (negative) {
// Need to convert to two's complement.
twosComplement.reset(new unsigned char[tmpSize]);
unsigned char* twosBytes = reinterpret_cast<unsigned char*>(twosComplement.get());
memcpy(twosBytes, tmp, tmpSize);
tmp = twosBytes;
bool carry = true;
for (ssize_t i = tmpSize - 1; i >= 0; i--) {
twosBytes[i] ^= 0xFF;
if (carry) {
carry = (++twosBytes[i]) == 0;
}
}
}
BIGNUM *ret = BN_bin2bn(tmp, tmpSize, *dest);
if (ret == NULL) {
jniThrowRuntimeException(env, "Conversion to BIGNUM failed");
JNI_TRACE("arrayToBignum(%p, %p) => threw exception", source, dest);
return false;
}
BN_set_negative(ret, negative ? 1 : 0);
*dest = ret;
JNI_TRACE("arrayToBignum(%p, %p) => *dest = %p", source, dest, ret);
return true;
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* arrayToBignumSize sets |*out_size| to the size of the big-endian number
* contained in |source|. It returns true on success and sets an exception and
* returns false otherwise.
*/
static bool arrayToBignumSize(JNIEnv* env, jbyteArray source, size_t* out_size) {
JNI_TRACE("arrayToBignumSize(%p, %p)", source, out_size);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const uint8_t* tmp = reinterpret_cast<const uint8_t*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
if (tmpSize == 0) {
*out_size = 0;
return true;
}
if ((tmp[0] & 0x80) != 0) {
// Negative numbers are invalid.
jniThrowRuntimeException(env, "Negative number");
return false;
}
while (tmpSize > 0 && tmp[0] == 0) {
tmp++;
tmpSize--;
}
*out_size = tmpSize;
return true;
}
#endif
/**
* Converts an OpenSSL BIGNUM to a Java byte[] array in two's complement.
*/
static jbyteArray bignumToArray(JNIEnv* env, const BIGNUM* source, const char* sourceName) {
JNI_TRACE("bignumToArray(%p, %s)", source, sourceName);
if (source == NULL) {
jniThrowNullPointerException(env, sourceName);
return NULL;
}
size_t numBytes = BN_num_bytes(source) + 1;
jbyteArray javaBytes = env->NewByteArray(numBytes);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bignumToArray(%p, %s) => NULL", source, sourceName);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
if (BN_num_bytes(source) > 0 && BN_bn2bin(source, tmp + 1) <= 0) {
throwExceptionIfNecessary(env, "bignumToArray");
return NULL;
}
// Set the sign and convert to two's complement if necessary for the Java code.
if (BN_is_negative(source)) {
bool carry = true;
for (ssize_t i = numBytes - 1; i >= 0; i--) {
tmp[i] ^= 0xFF;
if (carry) {
carry = (++tmp[i]) == 0;
}
}
*tmp |= 0x80;
} else {
*tmp = 0x00;
}
JNI_TRACE("bignumToArray(%p, %s) => %p", source, sourceName, javaBytes);
return javaBytes;
}
/**
* Converts various OpenSSL ASN.1 types to a jbyteArray with DER-encoded data
* inside. The "i2d_func" function pointer is a function of the "i2d_<TYPE>"
* from the OpenSSL ASN.1 API.
*/
template<typename T>
jbyteArray ASN1ToByteArray(JNIEnv* env, T* obj, int (*i2d_func)(T*, unsigned char**)) {
if (obj == NULL) {
jniThrowNullPointerException(env, "ASN1 input == null");
JNI_TRACE("ASN1ToByteArray(%p) => null input", obj);
return NULL;
}
int derLen = i2d_func(obj, NULL);
if (derLen < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => measurement failed", obj);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => creating byte array failed", obj);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => using byte array failed", obj);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
int ret = i2d_func(obj, &p);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => final conversion failed", obj);
return NULL;
}
JNI_TRACE("ASN1ToByteArray(%p) => success (%d bytes written)", obj, ret);
return byteArray.release();
}
template<typename T, T* (*d2i_func)(T**, const unsigned char**, long)>
T* ByteArrayToASN1(JNIEnv* env, jbyteArray byteArray) {
ScopedByteArrayRO bytes(env, byteArray);
if (bytes.get() == NULL) {
JNI_TRACE("ByteArrayToASN1(%p) => using byte array failed", byteArray);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
return d2i_func(NULL, &tmp, bytes.size());
}
/**
* Converts ASN.1 BIT STRING to a jbooleanArray.
*/
jbooleanArray ASN1BitStringToBooleanArray(JNIEnv* env, ASN1_BIT_STRING* bitStr) {
int size = bitStr->length * 8;
if (bitStr->flags & ASN1_STRING_FLAG_BITS_LEFT) {
size -= bitStr->flags & 0x07;
}
ScopedLocalRef<jbooleanArray> bitsRef(env, env->NewBooleanArray(size));
if (bitsRef.get() == NULL) {
return NULL;
}
ScopedBooleanArrayRW bitsArray(env, bitsRef.get());
for (int i = 0; i < static_cast<int>(bitsArray.size()); i++) {
bitsArray[i] = ASN1_BIT_STRING_get_bit(bitStr, i);
}
return bitsRef.release();
}
/**
* Safely clear SSL sessions and throw an error if there was something already
* in the error stack.
*/
static void safeSslClear(SSL* ssl) {
if (SSL_clear(ssl) != 1) {
freeOpenSslErrorState();
}
}
/**
* To avoid the round-trip to ASN.1 and back in X509_dup, we just up the reference count.
*/
static X509* X509_dup_nocopy(X509* x509) {
if (x509 == NULL) {
return NULL;
}
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509);
return x509;
}
/*
* Sets the read and write BIO for an SSL connection and removes it when it goes out of scope.
* We hang on to BIO with a JNI GlobalRef and we want to remove them as soon as possible.
*/
class ScopedSslBio {
public:
ScopedSslBio(SSL *ssl, BIO* rbio, BIO* wbio) : ssl_(ssl) {
SSL_set_bio(ssl_, rbio, wbio);
CRYPTO_add(&rbio->references,1,CRYPTO_LOCK_BIO);
CRYPTO_add(&wbio->references,1,CRYPTO_LOCK_BIO);
}
~ScopedSslBio() {
SSL_set_bio(ssl_, NULL, NULL);
}
private:
SSL* const ssl_;
};
/**
* Obtains the current thread's JNIEnv
*/
static JNIEnv* getJNIEnv() {
JNIEnv* env;
if (gJavaVM->AttachCurrentThread(&env, NULL) < 0) {
ALOGE("Could not attach JavaVM to find current JNIEnv");
return NULL;
}
return env;
}
/**
* BIO for InputStream
*/
class BIO_Stream {
public:
BIO_Stream(jobject stream) :
mEof(false) {
JNIEnv* env = getJNIEnv();
mStream = env->NewGlobalRef(stream);
}
~BIO_Stream() {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(mStream);
}
bool isEof() const {
JNI_TRACE("isEof? %s", mEof ? "yes" : "no");
return mEof;
}
int flush() {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_Stream::flush called with pending exception");
return -1;
}
env->CallVoidMethod(mStream, outputStream_flushMethod);
if (env->ExceptionCheck()) {
return -1;
}
return 1;
}
protected:
jobject getStream() {
return mStream;
}
void setEof(bool eof) {
mEof = eof;
}
private:
jobject mStream;
bool mEof;
};
class BIO_InputStream : public BIO_Stream {
public:
BIO_InputStream(jobject stream) :
BIO_Stream(stream) {
}
int read(char *buf, int len) {
return read_internal(buf, len, inputStream_readMethod);
}
int gets(char *buf, int len) {
if (len > PEM_LINE_LENGTH) {
len = PEM_LINE_LENGTH;
}
int read = read_internal(buf, len - 1, openSslInputStream_readLineMethod);
buf[read] = '\0';
JNI_TRACE("BIO::gets \"%s\"", buf);
return read;
}
private:
int read_internal(char *buf, int len, jmethodID method) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_InputStream::read could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_InputStream::read failed call to NewByteArray");
return -1;
}
jint read = env->CallIntMethod(getStream(), method, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read failed call to InputStream#read");
return -1;
}
/* Java uses -1 to indicate EOF condition. */
if (read == -1) {
setEof(true);
read = 0;
} else if (read > 0) {
env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast<jbyte*>(buf));
}
return read;
}
public:
/** Length of PEM-encoded line (64) plus CR plus NULL */
static const int PEM_LINE_LENGTH = 66;
};
class BIO_OutputStream : public BIO_Stream {
public:
BIO_OutputStream(jobject stream) :
BIO_Stream(stream) {
}
int write(const char *buf, int len) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_OutputStream::write => could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_OutputStream::write => failed call to NewByteArray");
return -1;
}
env->SetByteArrayRegion(javaBytes.get(), 0, len, reinterpret_cast<const jbyte*>(buf));
env->CallVoidMethod(getStream(), outputStream_writeMethod, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => failed call to OutputStream#write");
return -1;
}
return len;
}
};
static int bio_stream_create(BIO *b) {
b->init = 1;
b->num = 0;
b->ptr = NULL;
b->flags = 0;
return 1;
}
static int bio_stream_destroy(BIO *b) {
if (b == NULL) {
return 0;
}
if (b->ptr != NULL) {
delete static_cast<BIO_Stream*>(b->ptr);
b->ptr = NULL;
}
b->init = 0;
b->flags = 0;
return 1;
}
static int bio_stream_read(BIO *b, char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
int ret = stream->read(buf, len);
if (ret == 0) {
// EOF is indicated by -1 with a BIO flag.
BIO_set_retry_read(b);
return -1;
}
return ret;
}
static int bio_stream_write(BIO *b, const char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, len);
}
static int bio_stream_puts(BIO *b, const char *buf) {
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, strlen(buf));
}
static int bio_stream_gets(BIO *b, char *buf, int len) {
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
return stream->gets(buf, len);
}
static void bio_stream_assign(BIO *b, BIO_Stream* stream) {
b->ptr = static_cast<void*>(stream);
}
static long bio_stream_ctrl(BIO *b, int cmd, long, void *) {
BIO_Stream* stream = static_cast<BIO_Stream*>(b->ptr);
switch (cmd) {
case BIO_CTRL_EOF:
return stream->isEof() ? 1 : 0;
case BIO_CTRL_FLUSH:
return stream->flush();
default:
return 0;
}
}
static BIO_METHOD stream_bio_method = {
( 100 | 0x0400 ), /* source/sink BIO */
"InputStream/OutputStream BIO",
bio_stream_write, /* bio_write */
bio_stream_read, /* bio_read */
bio_stream_puts, /* bio_puts */
bio_stream_gets, /* bio_gets */
bio_stream_ctrl, /* bio_ctrl */
bio_stream_create, /* bio_create */
bio_stream_destroy, /* bio_free */
NULL, /* no bio_callback_ctrl */
};
static jbyteArray rawSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey,
const char* message, size_t message_len) {
ScopedLocalRef<jbyteArray> messageArray(env, env->NewByteArray(message_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW messageBytes(env, messageArray.get());
if (messageBytes.get() == NULL) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(messageBytes.get(), message, message_len);
}
jmethodID rawSignMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rawSignDigestWithPrivateKey", "(Ljava/security/PrivateKey;[B)[B");
if (rawSignMethod == NULL) {
ALOGE("Could not find rawSignDigestWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass, rawSignMethod, privateKey, messageArray.get()));
}
static jbyteArray rawCipherWithPrivateKey(JNIEnv* env, jobject privateKey, jboolean encrypt,
const char* ciphertext, size_t ciphertext_len) {
ScopedLocalRef<jbyteArray> ciphertextArray(env, env->NewByteArray(ciphertext_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rawCipherWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW ciphertextBytes(env, ciphertextArray.get());
if (ciphertextBytes.get() == NULL) {
JNI_TRACE("rawCipherWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(ciphertextBytes.get(), ciphertext, ciphertext_len);
}
jmethodID rawCipherMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rawCipherWithPrivateKey", "(Ljava/security/PrivateKey;Z[B)[B");
if (rawCipherMethod == NULL) {
ALOGE("Could not find rawCipherWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass, rawCipherMethod, privateKey, encrypt, ciphertextArray.get()));
}
// *********************************************
// From keystore_openssl.cpp in Chromium source.
// *********************************************
#if !defined(OPENSSL_IS_BORINGSSL)
// Custom RSA_METHOD that uses the platform APIs.
// Note that for now, only signing through RSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
// See <openssl/rsa.h> for exact declaration of RSA_METHOD.
int RsaMethodPubEnc(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
int RsaMethodPubDec(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
// See RSA_eay_private_encrypt in
// third_party/openssl/openssl/crypto/rsa/rsa_eay.c for the default
// implementation of this function.
int RsaMethodPrivEnc(int flen,
const unsigned char *from,
unsigned char *to,
RSA *rsa,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
return -1;
}
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// For RSA keys, this function behaves as RSA_private_encrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(from), flen));
if (signature.get() == NULL) {
ALOGE("Could not sign message in RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (signatureBytes.size() > expected_size) {
ALOGE("RSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer. rawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - signatureBytes.size();
memset(to, 0, zero_pad);
memcpy(to + zero_pad, signatureBytes.get(), signatureBytes.size());
return expected_size;
}
int RsaMethodPrivDec(int flen,
const unsigned char* from,
unsigned char* to,
RSA* rsa,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
return -1;
}
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// For RSA keys, this function behaves as RSA_private_decrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> cleartext(env, rawCipherWithPrivateKey(env, private_key, false,
reinterpret_cast<const char*>(from), flen));
if (cleartext.get() == NULL) {
ALOGE("Could not decrypt message in RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO cleartextBytes(env, cleartext.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (cleartextBytes.size() > expected_size) {
ALOGE("RSA ciphertext size mismatch, actual: %zd, expected <= %zd", cleartextBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer.
memcpy(to, cleartextBytes.get(), cleartextBytes.size());
return cleartextBytes.size();
}
int RsaMethodInit(RSA*) {
return 0;
}
int RsaMethodFinish(RSA* rsa) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
jobject key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (key != NULL) {
RSA_set_app_data(rsa, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(key);
}
// Actual return value is ignored by OpenSSL. There are no docs
// explaining what this is supposed to be.
return 0;
}
const RSA_METHOD android_rsa_method = {
/* .name = */ "Android signing-only RSA method",
/* .rsa_pub_enc = */ RsaMethodPubEnc,
/* .rsa_pub_dec = */ RsaMethodPubDec,
/* .rsa_priv_enc = */ RsaMethodPrivEnc,
/* .rsa_priv_dec = */ RsaMethodPrivDec,
/* .rsa_mod_exp = */ NULL,
/* .bn_mod_exp = */ NULL,
/* .init = */ RsaMethodInit,
/* .finish = */ RsaMethodFinish,
// This flag is necessary to tell OpenSSL to avoid checking the content
// (i.e. internal fields) of the private key. Otherwise, it will complain
// it's not valid for the certificate.
/* .flags = */ RSA_METHOD_FLAG_NO_CHECK,
/* .app_data = */ NULL,
/* .rsa_sign = */ NULL,
/* .rsa_verify = */ NULL,
/* .rsa_keygen = */ NULL,
};
// Used to ensure that the global JNI reference associated with a custom
// EC_KEY + ECDSA_METHOD wrapper is released when its EX_DATA is destroyed
// (this function is called when EVP_PKEY_free() is called on the wrapper).
void ExDataFree(void* /* parent */,
void* ptr,
CRYPTO_EX_DATA* ad,
int idx,
long /* argl */,
void* /* argp */) {
jobject private_key = reinterpret_cast<jobject>(ptr);
if (private_key == NULL) return;
CRYPTO_set_ex_data(ad, idx, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(private_key);
}
int ExDataDup(CRYPTO_EX_DATA* /* to */,
CRYPTO_EX_DATA* /* from */,
void* /* from_d */,
int /* idx */,
long /* argl */,
void* /* argp */) {
// This callback shall never be called with the current OpenSSL
// implementation (the library only ever duplicates EX_DATA items
// for SSL and BIO objects). But provide this to catch regressions
// in the future.
// Return value is currently ignored by OpenSSL.
return 0;
}
class EcdsaExDataIndex {
public:
int ex_data_index() { return ex_data_index_; }
static EcdsaExDataIndex& Instance() {
static EcdsaExDataIndex singleton;
return singleton;
}
private:
EcdsaExDataIndex() {
ex_data_index_ = ECDSA_get_ex_new_index(0, NULL, NULL, ExDataDup, ExDataFree);
}
EcdsaExDataIndex(EcdsaExDataIndex const&);
~EcdsaExDataIndex() {}
EcdsaExDataIndex& operator=(EcdsaExDataIndex const&);
int ex_data_index_;
};
// Returns the index of the custom EX_DATA used to store the JNI reference.
int EcdsaGetExDataIndex(void) {
EcdsaExDataIndex& exData = EcdsaExDataIndex::Instance();
return exData.ex_data_index();
}
ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst, int dgst_len, const BIGNUM* /* inv */,
const BIGNUM* /* rp */, EC_KEY* eckey) {
// Retrieve private key JNI reference.
jobject private_key =
reinterpret_cast<jobject>(ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex()));
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodDoSign!");
return NULL;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return NULL;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key, reinterpret_cast<const char*>(dgst),
dgst_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return NULL;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey));
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
max_expected_size);
return NULL;
}
// Convert signature to ECDSA_SIG object
const unsigned char* sigbuf = reinterpret_cast<const unsigned char*>(signatureBytes.get());
long siglen = static_cast<long>(signatureBytes.size());
return d2i_ECDSA_SIG(NULL, &sigbuf, siglen);
}
int EcdsaMethodSignSetup(EC_KEY* /* eckey */,
BN_CTX* /* ctx */,
BIGNUM** /* kinv */,
BIGNUM** /* r */,
const unsigned char*,
int) {
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB);
return -1;
}
int EcdsaMethodDoVerify(const unsigned char* /* dgst */,
int /* dgst_len */,
const ECDSA_SIG* /* sig */,
EC_KEY* /* eckey */) {
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB);
return -1;
}
const ECDSA_METHOD android_ecdsa_method = {
/* .name = */ "Android signing-only ECDSA method",
/* .ecdsa_do_sign = */ EcdsaMethodDoSign,
/* .ecdsa_sign_setup = */ EcdsaMethodSignSetup,
/* .ecdsa_do_verify = */ EcdsaMethodDoVerify,
/* .flags = */ 0,
/* .app_data = */ NULL,
};
#else /* OPENSSL_IS_BORINGSSL */
namespace {
ENGINE *g_engine;
int g_rsa_exdata_index;
int g_ecdsa_exdata_index;
pthread_once_t g_engine_once = PTHREAD_ONCE_INIT;
void init_engine_globals();
void ensure_engine_globals() {
pthread_once(&g_engine_once, init_engine_globals);
}
// KeyExData contains the data that is contained in the EX_DATA of the RSA
// and ECDSA objects that are created to wrap Android system keys.
struct KeyExData {
// private_key contains a reference to a Java, private-key object.
jobject private_key;
// cached_size contains the "size" of the key. This is the size of the
// modulus (in bytes) for RSA, or the group order size for ECDSA. This
// avoids calling into Java to calculate the size.
size_t cached_size;
};
// ExDataDup is called when one of the RSA or EC_KEY objects is duplicated. We
// don't support this and it should never happen.
int ExDataDup(CRYPTO_EX_DATA* to,
const CRYPTO_EX_DATA* from,
void** from_d,
int index,
long argl,
void* argp) {
return 0;
}
// ExDataFree is called when one of the RSA or EC_KEY objects is freed.
void ExDataFree(void* parent,
void* ptr,
CRYPTO_EX_DATA* ad,
int index,
long argl,
void* argp) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
KeyExData *ex_data = reinterpret_cast<KeyExData*>(ptr);
if (ex_data != NULL) {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(ex_data->private_key);
delete ex_data;
}
}
KeyExData* RsaGetExData(const RSA* rsa) {
return reinterpret_cast<KeyExData*>(RSA_get_ex_data(rsa, g_rsa_exdata_index));
}
size_t RsaMethodSize(const RSA *rsa) {
const KeyExData *ex_data = RsaGetExData(rsa);
return ex_data->cached_size;
}
int RsaMethodEncrypt(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
OPENSSL_PUT_ERROR(RSA, encrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
int RsaMethodSignRaw(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
OPENSSL_PUT_ERROR(RSA, sign_raw, RSA_R_UNKNOWN_PADDING_TYPE);
return 0;
}
// Retrieve private key JNI reference.
const KeyExData *ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
// For RSA keys, this function behaves as RSA_private_decrypt with
// PKCS#1 v1.5 padding.
ScopedLocalRef<jbyteArray> cleartext(
env, rawCipherWithPrivateKey(env, ex_data->private_key, false,
reinterpret_cast<const char*>(in), in_len));
if (cleartext.get() == NULL) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO result(env, cleartext.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (result.size() > expected_size) {
OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
return 0;
}
if (max_out < expected_size) {
OPENSSL_PUT_ERROR(RSA, sign_raw, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer. RawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - result.size();
memset(out, 0, zero_pad);
memcpy(out + zero_pad, &result[0], result.size());
*out_len = expected_size;
return 1;
}
int RsaMethodDecrypt(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
OPENSSL_PUT_ERROR(RSA, decrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
int RsaMethodVerifyRaw(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
OPENSSL_PUT_ERROR(RSA, verify_raw, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
const RSA_METHOD android_rsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
RsaMethodSize,
NULL /* sign */,
NULL /* verify */,
RsaMethodEncrypt,
RsaMethodSignRaw,
RsaMethodDecrypt,
RsaMethodVerifyRaw,
NULL /* mod_exp */,
NULL /* bn_mod_exp */,
NULL /* private_transform */,
RSA_FLAG_OPAQUE,
NULL /* keygen */,
};
// Custom ECDSA_METHOD that uses the platform APIs.
// Note that for now, only signing through ECDSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
jobject EcKeyGetKey(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->private_key;
}
size_t EcdsaMethodGroupOrderSize(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->cached_size;
}
int EcdsaMethodSign(const uint8_t* digest,
size_t digest_len,
uint8_t* sig,
unsigned int* sig_len,
EC_KEY* ec_key) {
// Retrieve private key JNI reference.
jobject private_key = EcKeyGetKey(ec_key);
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodSign!");
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return 0;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(digest),
digest_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return 0;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = ECDSA_size(ec_key);
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd",
signatureBytes.size(), max_expected_size);
return 0;
}
memcpy(sig, signatureBytes.get(), signatureBytes.size());
*sig_len = signatureBytes.size();
return 1;
}
int EcdsaMethodVerify(const uint8_t* digest,
size_t digest_len,
const uint8_t* sig,
size_t sig_len,
EC_KEY* ec_key) {
OPENSSL_PUT_ERROR(ECDSA, ECDSA_do_verify, ECDSA_R_NOT_IMPLEMENTED);
return 0;
}
const ECDSA_METHOD android_ecdsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
EcdsaMethodGroupOrderSize,
EcdsaMethodSign,
EcdsaMethodVerify,
ECDSA_FLAG_OPAQUE,
};
void init_engine_globals() {
g_rsa_exdata_index =
RSA_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
ExDataDup, ExDataFree);
g_ecdsa_exdata_index =
EC_KEY_get_ex_new_index(0 /* argl */, NULL /* argp */,
NULL /* new_func */, ExDataDup, ExDataFree);
g_engine = ENGINE_new();
ENGINE_set_RSA_method(g_engine, &android_rsa_method,
sizeof(android_rsa_method));
ENGINE_set_ECDSA_method(g_engine, &android_ecdsa_method,
sizeof(android_ecdsa_method));
}
} // anonymous namespace
#endif
#ifdef CONSCRYPT_UNBUNDLED
/*
* This is a big hack; don't learn from this. Basically what happened is we do
* not have an API way to insert ourselves into the AsynchronousCloseMonitor
* that's compiled into the native libraries for libcore when we're unbundled.
* So we try to look up the symbol from the main library to find it.
*/
typedef void (*acm_ctor_func)(void*, int);
typedef void (*acm_dtor_func)(void*);
static acm_ctor_func async_close_monitor_ctor = NULL;
static acm_dtor_func async_close_monitor_dtor = NULL;
class CompatibilityCloseMonitor {
public:
CompatibilityCloseMonitor(int fd) {
if (async_close_monitor_ctor != NULL) {
async_close_monitor_ctor(objBuffer, fd);
}
}
~CompatibilityCloseMonitor() {
if (async_close_monitor_dtor != NULL) {
async_close_monitor_dtor(objBuffer);
}
}
private:
char objBuffer[256];
#if 0
static_assert(sizeof(objBuffer) > 2*sizeof(AsynchronousCloseMonitor),
"CompatibilityCloseMonitor must be larger than the actual object");
#endif
};
static void findAsynchronousCloseMonitorFuncs() {
void *lib = dlopen("libjavacore.so", RTLD_NOW);
if (lib != NULL) {
async_close_monitor_ctor = (acm_ctor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorC1Ei");
async_close_monitor_dtor = (acm_dtor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorD1Ev");
}
}
#endif
/**
* Copied from libnativehelper NetworkUtilites.cpp
*/
static bool setBlocking(int fd, bool blocking) {
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
return false;
}
if (!blocking) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int rc = fcntl(fd, F_SETFL, flags);
return (rc != -1);
}
/**
* OpenSSL locking support. Taken from the O'Reilly book by Viega et al., but I
* suppose there are not many other ways to do this on a Linux system (modulo
* isomorphism).
*/
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#define THROW_SSLEXCEPTION (-2)
#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
#define THROWN_EXCEPTION (-4)
static MUTEX_TYPE* mutex_buf = NULL;
static void locking_function(int mode, int n, const char*, int) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(mutex_buf[n]);
} else {
MUTEX_UNLOCK(mutex_buf[n]);
}
}
static void threadid_callback(CRYPTO_THREADID *threadid) {
#if defined(__APPLE__)
uint64_t owner;
int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6
if (rc == 0) {
CRYPTO_THREADID_set_numeric(threadid, owner);
} else {
ALOGE("Error calling pthread_threadid_np");
}
#else
// bionic exposes gettid(), but glibc doesn't
CRYPTO_THREADID_set_numeric(threadid, syscall(__NR_gettid));
#endif
}
int THREAD_setup(void) {
mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
if (!mutex_buf) {
return 0;
}
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
MUTEX_SETUP(mutex_buf[i]);
}
CRYPTO_THREADID_set_callback(threadid_callback);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int THREAD_cleanup(void) {
if (!mutex_buf) {
return 0;
}
CRYPTO_THREADID_set_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks( ); i++) {
MUTEX_CLEANUP(mutex_buf[i]);
}
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
/**
* Initialization phase for every OpenSSL job: Loads the Error strings, the
* crypto algorithms and reset the OpenSSL library
*/
static void NativeCrypto_clinit(JNIEnv*, jclass)
{
SSL_load_error_strings();
ERR_load_crypto_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
THREAD_setup();
}
static void NativeCrypto_ENGINE_load_dynamic(JNIEnv*, jclass) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("ENGINE_load_dynamic()");
ENGINE_load_dynamic();
#endif
}
static jlong NativeCrypto_ENGINE_by_id(JNIEnv* env, jclass, jstring idJava) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("ENGINE_by_id(%p)", idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
JNI_TRACE("ENGINE_by_id(%p) => id == null", idJava);
return 0;
}
JNI_TRACE("ENGINE_by_id(\"%s\")", id.c_str());
ENGINE* e = ENGINE_by_id(id.c_str());
if (e == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("ENGINE_by_id(\"%s\") => %p", id.c_str(), e);
return reinterpret_cast<uintptr_t>(e);
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_add(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_add(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_add(e);
/*
* We tolerate errors, because the most likely error is that
* the ENGINE is already in the list.
*/
freeOpenSslErrorState();
JNI_TRACE("ENGINE_add(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_init(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_init(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_init(e);
JNI_TRACE("ENGINE_init(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_finish(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_finish(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_finish(e);
JNI_TRACE("ENGINE_finish(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
static jint NativeCrypto_ENGINE_free(JNIEnv* env, jclass, jlong engineRef) {
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_free(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_free(e);
JNI_TRACE("ENGINE_free(%p) => %d", e, ret);
return ret;
#else
return 0;
#endif
}
#if defined(OPENSSL_IS_BORINGSSL)
extern "C" {
/* EVP_PKEY_from_keystore is from system/security/keystore-engine. */
extern EVP_PKEY* EVP_PKEY_from_keystore(const char *key_id);
}
#endif
static jlong NativeCrypto_ENGINE_load_private_key(JNIEnv* env, jclass, jlong engineRef,
jstring idJava) {
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "id == NULL");
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_load_private_key(%p, %p)", e, idJava);
Unique_EVP_PKEY pkey(ENGINE_load_private_key(e, id.c_str(), NULL, NULL));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("ENGINE_load_private_key(%p, %p) => %p", e, idJava, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
#else
#if defined(NO_KEYSTORE_ENGINE)
jniThrowRuntimeException(env, "No keystore ENGINE support compiled in");
return 0;
#else
Unique_EVP_PKEY pkey(EVP_PKEY_from_keystore(id.c_str()));
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "Failed to find named key in keystore");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
#endif
#endif
}
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong engineRef)
{
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_get_id(%p)", e);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_get_id(%p) => engine == null", e);
return NULL;
}
const char *id = ENGINE_get_id(e);
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF(id));
JNI_TRACE("ENGINE_get_id(%p) => \"%s\"", e, id);
return idJava.release();
#else
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF("keystore"));
return idJava.release();
#endif
}
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv* env, jclass, jlong engineRef,
jstring cmdJava, jstring argJava, jint cmd_optional)
{
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d)", e, cmdJava, argJava, cmd_optional);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d) => engine == null", e, cmdJava, argJava,
cmd_optional);
return 0;
}
ScopedUtfChars cmdChars(env, cmdJava);
if (cmdChars.c_str() == NULL) {
return 0;
}
UniquePtr<ScopedUtfChars> arg;
const char* arg_c_str = NULL;
if (argJava != NULL) {
arg.reset(new ScopedUtfChars(env, argJava));
arg_c_str = arg->c_str();
if (arg_c_str == NULL) {
return 0;
}
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d)", e, cmdChars.c_str(), arg_c_str,
cmd_optional);
int ret = ENGINE_ctrl_cmd_string(e, cmdChars.c_str(), arg_c_str, cmd_optional);
if (ret != 1) {
throwExceptionIfNecessary(env, "ENGINE_ctrl_cmd_string");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => threw error", e,
cmdChars.c_str(), arg_c_str, cmd_optional);
return 0;
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => %d", e, cmdChars.c_str(),
arg_c_str, cmd_optional, ret);
return ret;
#else
return 0;
#endif
}
static jlong NativeCrypto_EVP_PKEY_new_DH(JNIEnv* env, jclass,
jbyteArray p, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p)",
p, g, pub_key, priv_key);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
jniThrowRuntimeException(env, "DH_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dh->p)) {
return 0;
}
if (!arrayToBignum(env, g, &dh->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dh->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dh->priv_key)) {
return 0;
}
if (dh->p == NULL || dh->g == NULL
|| (pub_key != NULL && dh->pub_key == NULL)
|| (priv_key != NULL && dh->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/* The public key can be recovered if the private key is available. */
if (dh->pub_key == NULL && dh->priv_key != NULL) {
if (!DH_generate_key(dh.get())) {
jniThrowRuntimeException(env, "EVP_PKEY_new_DH failed during pub_key generation");
return 0;
}
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DH failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
*/
static jlong NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass,
jbyteArray n, jbyteArray e, jbyteArray d,
jbyteArray p, jbyteArray q,
jbyteArray dmp1, jbyteArray dmq1,
jbyteArray iqmp) {
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p, dmp1=%p, dmq1=%p, iqmp=%p)",
n, e, d, p, q, dmp1, dmq1, iqmp);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_new failed");
return 0;
}
if (e == NULL && d == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "e == NULL && d == NULL");
JNI_TRACE("NativeCrypto_EVP_PKEY_new_RSA => e == NULL && d == NULL");
return 0;
}
if (!arrayToBignum(env, n, &rsa->n)) {
return 0;
}
if (e != NULL && !arrayToBignum(env, e, &rsa->e)) {
return 0;
}
if (d != NULL && !arrayToBignum(env, d, &rsa->d)) {
return 0;
}
if (p != NULL && !arrayToBignum(env, p, &rsa->p)) {
return 0;
}
if (q != NULL && !arrayToBignum(env, q, &rsa->q)) {
return 0;
}
if (dmp1 != NULL && !arrayToBignum(env, dmp1, &rsa->dmp1)) {
return 0;
}
if (dmq1 != NULL && !arrayToBignum(env, dmq1, &rsa->dmq1)) {
return 0;
}
if (iqmp != NULL && !arrayToBignum(env, iqmp, &rsa->iqmp)) {
return 0;
}
#ifdef WITH_JNI_TRACE
if (p != NULL && q != NULL) {
int check = RSA_check_key(rsa.get());
JNI_TRACE("EVP_PKEY_new_RSA(...) RSA_check_key returns %d", check);
}
#endif
if (rsa->n == NULL || (rsa->e == NULL && rsa->d == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
/*
* If the private exponent is available, there is the potential to do signing
* operations. If the public exponent is also available, OpenSSL will do RSA
* blinding. Enable it if possible.
*/
if (rsa->d != NULL) {
if (rsa->e != NULL) {
JNI_TRACE("EVP_PKEY_new_RSA(...) enabling RSA blinding => %p", rsa.get());
RSA_blinding_on(rsa.get(), NULL);
} else {
JNI_TRACE("EVP_PKEY_new_RSA(...) disabling RSA blinding => %p", rsa.get());
RSA_blinding_off(rsa.get());
}
}
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p dmp1=%p, dmq1=%p, iqmp=%p) => %p",
n, e, d, p, q, dmp1, dmq1, iqmp, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_EC_KEY(JNIEnv* env, jclass, jobject groupRef,
jobject pubkeyRef, jbyteArray keyJavaBytes) {
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
const EC_POINT* pubkey = fromContextObject<EC_POINT>(env, pubkeyRef);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p)", group, pubkey, keyJavaBytes);
Unique_BIGNUM key(NULL);
if (keyJavaBytes != NULL) {
BIGNUM* keyRef = NULL;
if (!arrayToBignum(env, keyJavaBytes, &keyRef)) {
return 0;
}
key.reset(keyRef);
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
jniThrowRuntimeException(env, "EC_KEY_new failed");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) > EC_KEY_set_group failed", group, pubkey,
keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (pubkey != NULL) {
if (EC_KEY_set_public_key(eckey.get(), pubkey) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_public_key");
return 0;
}
}
if (key.get() != NULL) {
if (EC_KEY_set_private_key(eckey.get(), key.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
if (pubkey == NULL) {
Unique_EC_POINT calcPubkey(EC_POINT_new(group));
if (!EC_POINT_mul(group, calcPubkey.get(), key.get(), NULL, NULL, NULL)) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => can't calulate public key", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
EC_KEY_set_public_key(eckey.get(), calcPubkey.get());
}
}
if (!EC_KEY_check_key(eckey.get())) {
JNI_TRACE("EVP_KEY_new_EC_KEY(%p, %p, %p) => invalid key created", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_check_key");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => %p", group, pubkey, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_mac_key(JNIEnv* env, jclass, jint pkeyType,
jbyteArray keyJavaBytes)
{
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p)", pkeyType, keyJavaBytes);
ScopedByteArrayRO key(env, keyJavaBytes);
if (key.get() == NULL) {
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(key.get());
Unique_EVP_PKEY pkey(EVP_PKEY_new_mac_key(pkeyType, (ENGINE *) NULL, tmp, key.size()));
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => threw error", pkeyType, keyJavaBytes);
throwExceptionIfNecessary(env, "ENGINE_load_private_key");
return 0;
}
JNI_TRACE("EVP_PKEY_new_mac_key(%d, %p) => %p", pkeyType, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static int NativeCrypto_EVP_PKEY_type(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_type(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_type(pkey->type);
JNI_TRACE("EVP_PKEY_type(%p) => %d", pkey, result);
return result;
}
/**
* private static native int EVP_PKEY_size(int pkey);
*/
static int NativeCrypto_EVP_PKEY_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_PKEY_size(pkey);
JNI_TRACE("EVP_PKEY_size(%p) => %d", pkey, result);
return result;
}
static jstring NativeCrypto_EVP_PKEY_print_public(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_print_public(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_public(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_public");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_public(%p) => \"%s\"", pkey, tmp);
return description;
}
static jstring NativeCrypto_EVP_PKEY_print_private(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_print_private(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (EVP_PKEY_print_private(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, "EVP_PKEY_print_private");
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("EVP_PKEY_print_private(%p) => \"%s\"", pkey, tmp);
return description;
}
static void NativeCrypto_EVP_PKEY_free(JNIEnv*, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_free(%p)", pkey);
if (pkey != NULL) {
EVP_PKEY_free(pkey);
}
}
static jint NativeCrypto_EVP_PKEY_cmp(JNIEnv* env, jclass, jobject pkey1Ref, jobject pkey2Ref) {
EVP_PKEY* pkey1 = fromContextObject<EVP_PKEY>(env, pkey1Ref);
EVP_PKEY* pkey2 = fromContextObject<EVP_PKEY>(env, pkey2Ref);
JNI_TRACE("EVP_PKEY_cmp(%p, %p)", pkey1, pkey2);
if (pkey1 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey1 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey1 == NULL");
return -1;
} else if (pkey2 == NULL) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => failed pkey2 == NULL", pkey1, pkey2);
jniThrowNullPointerException(env, "pkey2 == NULL");
return -1;
}
int result = EVP_PKEY_cmp(pkey1, pkey2);
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => %d", pkey1, pkey2, result);
return result;
}
/*
* static native byte[] i2d_PKCS8_PRIV_KEY_INFO(int, byte[])
*/
static jbyteArray NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PKCS8_PRIV_KEY_INFO(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return NULL;
}
Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("key=%p i2d_PKCS8_PRIV_KEY_INFO => error from key to PKCS8", pkey);
return NULL;
}
return ASN1ToByteArray<PKCS8_PRIV_KEY_INFO>(env, pkcs8.get(), i2d_PKCS8_PRIV_KEY_INFO);
}
/*
* static native int d2i_PKCS8_PRIV_KEY_INFO(byte[])
*/
static jlong NativeCrypto_d2i_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jbyteArray keyJavaBytes) {
JNI_TRACE("d2i_PKCS8_PRIV_KEY_INFO(%p)", keyJavaBytes);
ScopedByteArrayRO bytes(env, keyJavaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => threw exception", keyJavaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &tmp, bytes.size()));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from DER to PKCS8", keyJavaBytes);
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from PKCS8 to key", keyJavaBytes);
return 0;
}
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => %p", keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* static native byte[] i2d_PUBKEY(int)
*/
static jbyteArray NativeCrypto_i2d_PUBKEY(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PUBKEY(%p)", pkey);
return ASN1ToByteArray<EVP_PKEY>(env, pkey, reinterpret_cast<int (*) (EVP_PKEY*, uint8_t **)>(i2d_PUBKEY));
}
/*
* static native int d2i_PUBKEY(byte[])
*/
static jlong NativeCrypto_d2i_PUBKEY(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("d2i_PUBKEY(%p)", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("d2i_PUBKEY(%p) => threw error", javaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, bytes.size()));
if (pkey.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PUBKEY => threw exception", javaBytes);
throwExceptionIfNecessary(env, "d2i_PUBKEY");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getRSAPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jbyteArray modulusBytes) {
JNI_TRACE("getRSAPrivateKeyWrapper(%p, %p)", javaKey, modulusBytes);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
RSA_set_method(rsa.get(), &android_rsa_method);
if (!arrayToBignum(env, modulusBytes, &rsa->n)) {
return 0;
}
RSA_set_app_data(rsa.get(), env->NewGlobalRef(javaKey));
#else
size_t cached_size;
if (!arrayToBignumSize(env, modulusBytes, &cached_size)) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
return 0;
}
ensure_engine_globals();
Unique_RSA rsa(RSA_new_method(g_engine));
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
ex_data->cached_size = cached_size;
RSA_set_ex_data(rsa.get(), g_rsa_exdata_index, ex_data);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getRSAPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "getRSAPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getECPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jobject groupRef) {
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("getECPrivateKeyWrapper(%p, %p)", javaKey, group);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_EC_KEY ecKey(EC_KEY_new());
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
EC_KEY_set_group(ecKey.get(), group);
ECDSA_set_method(ecKey.get(), &android_ecdsa_method);
ECDSA_set_ex_data(ecKey.get(), EcdsaGetExDataIndex(), env->NewGlobalRef(javaKey));
#else
ensure_engine_globals();
Unique_EC_KEY ecKey(EC_KEY_new_method(g_engine));
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
BIGNUM order;
BN_init(&order);
if (!EC_GROUP_get_order(group, &order, NULL)) {
BN_free(&order);
jniThrowRuntimeException(env, "EC_GROUP_get_order failed");
return 0;
}
ex_data->cached_size = BN_num_bytes(&order);
BN_free(&order);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getECPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getECPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), ecKey.get()) != 1) {
jniThrowRuntimeException(env, "getECPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(ecKey);
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native int RSA_generate_key(int modulusBits, byte[] publicExponent);
*/
static jlong NativeCrypto_RSA_generate_key_ex(JNIEnv* env, jclass, jint modulusBits,
jbyteArray publicExponent) {
JNI_TRACE("RSA_generate_key_ex(%d, %p)", modulusBits, publicExponent);
BIGNUM* eRef = NULL;
if (!arrayToBignum(env, publicExponent, &eRef)) {
return 0;
}
Unique_BIGNUM e(eRef);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
if (RSA_generate_key_ex(rsa.get(), modulusBits, e.get(), NULL) < 0) {
throwExceptionIfNecessary(env, "RSA_generate_key_ex");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("RSA_generate_key_ex(n=%d, e=%p) => %p", modulusBits, publicExponent, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jint NativeCrypto_RSA_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("RSA_size(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_size failed");
return 0;
}
return static_cast<jint>(RSA_size(rsa.get()));
}
typedef int RSACryptOperation(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
int padding);
static jint RSA_crypt_operation(RSACryptOperation operation,
const char* caller __attribute__ ((unused)), JNIEnv* env, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("%s(%d, %p, %p, %p)", caller, flen, fromJavaBytes, toJavaBytes, pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return -1;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
return -1;
}
ScopedByteArrayRO from(env, fromJavaBytes);
if (from.get() == NULL) {
return -1;
}
ScopedByteArrayRW to(env, toJavaBytes);
if (to.get() == NULL) {
return -1;
}
int resultSize = operation(static_cast<int>(flen),
reinterpret_cast<const unsigned char*>(from.get()),
reinterpret_cast<unsigned char*>(to.get()), rsa.get(), padding);
if (resultSize == -1) {
JNI_TRACE("%s => failed", caller);
throwExceptionIfNecessary(env, "RSA_crypt_operation");
return -1;
}
JNI_TRACE("%s(%d, %p, %p, %p) => %d", caller, flen, fromJavaBytes, toJavaBytes, pkey,
resultSize);
return static_cast<jint>(resultSize);
}
static jint NativeCrypto_RSA_private_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_private_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
/*
* public static native byte[][] get_RSA_public_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_public_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
return joa;
}
/*
* public static native byte[][] get_RSA_private_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_private_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(8, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
if (rsa->e != NULL) {
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
}
if (rsa->d != NULL) {
jbyteArray d = bignumToArray(env, rsa->d, "d");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, d);
}
if (rsa->p != NULL) {
jbyteArray p = bignumToArray(env, rsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, p);
}
if (rsa->q != NULL) {
jbyteArray q = bignumToArray(env, rsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, q);
}
if (rsa->dmp1 != NULL) {
jbyteArray dmp1 = bignumToArray(env, rsa->dmp1, "dmp1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 5, dmp1);
}
if (rsa->dmq1 != NULL) {
jbyteArray dmq1 = bignumToArray(env, rsa->dmq1, "dmq1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 6, dmq1);
}
if (rsa->iqmp != NULL) {
jbyteArray iqmp = bignumToArray(env, rsa->iqmp, "iqmp");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 7, iqmp);
}
return joa;
}
static jlong NativeCrypto_DH_generate_parameters_ex(JNIEnv* env, jclass, jint primeBits, jlong generator) {
JNI_TRACE("DH_generate_parameters_ex(%d, %lld)", primeBits, (long long) generator);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowOutOfMemory(env, "Unable to allocate DH key");
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("DH_generate_parameters_ex generating parameters");
if (!DH_generate_parameters_ex(dh.get(), primeBits, generator, NULL)) {
JNI_TRACE("DH_generate_parameters_ex => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowRuntimeException(env, "NativeCrypto_DH_generate_parameters_ex failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
JNI_TRACE("DH_generate_parameters_ex failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("DH_generate_parameters_ex(n=%d, g=%lld) => %p", primeBits, (long long) generator,
pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static void NativeCrypto_DH_generate_key(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("DH_generate_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "Unable to get DH key");
freeOpenSslErrorState();
}
if (!DH_generate_key(dh.get())) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
}
}
static jobjectArray NativeCrypto_get_DH_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_DH_params(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
throwExceptionIfNecessary(env, "get_DH_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(4, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dh->p != NULL) {
jbyteArray p = bignumToArray(env, dh->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, p);
}
if (dh->g != NULL) {
jbyteArray g = bignumToArray(env, dh->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, g);
}
if (dh->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dh->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, pub_key);
}
if (dh->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dh->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, priv_key);
}
return joa;
}
#define EC_CURVE_GFP 1
#define EC_CURVE_GF2M 2
/**
* Return group type or 0 if unknown group.
* EC_GROUP_GFP or EC_GROUP_GF2M
*/
static int get_EC_GROUP_type(const EC_GROUP* group)
{
#if !defined(OPENSSL_IS_BORINGSSL)
const EC_METHOD* method = EC_GROUP_method_of(group);
if (method == EC_GFp_nist_method()
|| method == EC_GFp_mont_method()
|| method == EC_GFp_simple_method()) {
return EC_CURVE_GFP;
} else if (method == EC_GF2m_simple_method()) {
return EC_CURVE_GF2M;
}
return 0;
#else
return EC_CURVE_GFP;
#endif
}
static jlong NativeCrypto_EC_GROUP_new_by_curve_name(JNIEnv* env, jclass, jstring curveNameJava)
{
JNI_TRACE("EC_GROUP_new_by_curve_name(%p)", curveNameJava);
ScopedUtfChars curveName(env, curveNameJava);
if (curveName.c_str() == NULL) {
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s)", curveName.c_str());
int nid = OBJ_sn2nid(curveName.c_str());
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID name", curveName.c_str());
return 0;
}
EC_GROUP* group = EC_GROUP_new_by_curve_name(nid);
if (group == NULL) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID %d", curveName.c_str(), nid);
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => %p", curveName.c_str(), group);
return reinterpret_cast<uintptr_t>(group);
}
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv* env, jclass, jobject groupRef,
jint flag)
{
#if !defined(OPENSSL_IS_BORINGSSL)
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d)", group, flag);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_asn1_flag => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_asn1_flag(group, flag);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d) => success", group, flag);
#endif
}
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv* env, jclass,
jobject groupRef, jint form)
{
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d)", group, form);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_point_conversion_form => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_set_point_conversion_form(group, static_cast<point_conversion_form_t>(form));
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d) => success", group, form);
}
static jstring NativeCrypto_EC_GROUP_get_curve_name(JNIEnv* env, jclass, jobject groupRef) {
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
int nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_get_curve_name(%p) => unnamed curve", group);
return NULL;
}
const char* shortName = OBJ_nid2sn(nid);
JNI_TRACE("EC_GROUP_get_curve_name(%p) => \"%s\"", group, shortName);
return env->NewStringUTF(shortName);
}
static jobjectArray NativeCrypto_EC_GROUP_get_curve(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve(%p)", group);
Unique_BIGNUM p(BN_new());
Unique_BIGNUM a(BN_new());
Unique_BIGNUM b(BN_new());
if (get_EC_GROUP_type(group) != EC_CURVE_GFP) {
jniThrowRuntimeException(env, "invalid group");
return NULL;
}
int ret = EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), (BN_CTX*) NULL);
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_GROUP_get_curve");
return NULL;
}
jobjectArray joa = env->NewObjectArray(3, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray pArray = bignumToArray(env, p.get(), "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, pArray);
jbyteArray aArray = bignumToArray(env, a.get(), "a");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, aArray);
jbyteArray bArray = bignumToArray(env, b.get(), "b");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, bArray);
JNI_TRACE("EC_GROUP_get_curve(%p) => %p", group, joa);
return joa;
}
static jbyteArray NativeCrypto_EC_GROUP_get_order(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_order(%p)", group);
Unique_BIGNUM order(BN_new());
if (order.get() == NULL) {
JNI_TRACE("EC_GROUP_get_order(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_order(group, order.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_order(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_order");
return NULL;
}
jbyteArray orderArray = bignumToArray(env, order.get(), "order");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_order(%p) => %p", group, orderArray);
return orderArray;
}
static jint NativeCrypto_EC_GROUP_get_degree(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_degree(%p)", group);
jint degree = EC_GROUP_get_degree(group);
if (degree == 0) {
JNI_TRACE("EC_GROUP_get_degree(%p) => unsupported", group);
jniThrowRuntimeException(env, "not supported");
return 0;
}
JNI_TRACE("EC_GROUP_get_degree(%p) => %d", group, degree);
return degree;
}
static jbyteArray NativeCrypto_EC_GROUP_get_cofactor(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_cofactor(%p)", group);
Unique_BIGNUM cofactor(BN_new());
if (cofactor.get() == NULL) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_cofactor(group, cofactor.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_cofactor");
return NULL;
}
jbyteArray cofactorArray = bignumToArray(env, cofactor.get(), "cofactor");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_cofactor(%p) => %p", group, cofactorArray);
return cofactorArray;
}
static jint NativeCrypto_get_EC_GROUP_type(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("get_EC_GROUP_type(%p)", group);
int type = get_EC_GROUP_type(group);
if (type == 0) {
JNI_TRACE("get_EC_GROUP_type(%p) => curve type", group);
jniThrowRuntimeException(env, "unknown curve type");
} else {
JNI_TRACE("get_EC_GROUP_type(%p) => %d", group, type);
}
return type;
}
static void NativeCrypto_EC_GROUP_clear_free(JNIEnv* env, jclass, jlong groupRef)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_free(group);
JNI_TRACE("EC_GROUP_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_GROUP_cmp(JNIEnv* env, jclass, jobject group1Ref,
jobject group2Ref)
{
const EC_GROUP* group1 = fromContextObject<EC_GROUP>(env, group1Ref);
const EC_GROUP* group2 = fromContextObject<EC_GROUP>(env, group2Ref);
JNI_TRACE("EC_GROUP_cmp(%p, %p)", group1, group2);
if (group1 == NULL || group2 == NULL) {
JNI_TRACE("EC_GROUP_cmp(%p, %p) => group1 == null || group2 == null", group1, group2);
jniThrowNullPointerException(env, "group1 == null || group2 == null");
return false;
}
#if !defined(OPENSSL_IS_BORINGSSL)
int ret = EC_GROUP_cmp(group1, group2, NULL);
#else
int ret = EC_GROUP_cmp(group1, group2);
#endif
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", group1, group2, ret);
return ret == 0;
}
static jlong NativeCrypto_EC_GROUP_get_generator(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_generator(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_get_generator(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
const EC_POINT* generator = EC_GROUP_get0_generator(group);
Unique_EC_POINT dup(EC_POINT_dup(generator, group));
if (dup.get() == NULL) {
JNI_TRACE("EC_GROUP_get_generator(%p) => oom error", group);
jniThrowOutOfMemory(env, "unable to dupe generator");
return 0;
}
JNI_TRACE("EC_GROUP_get_generator(%p) => %p", group, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static jlong NativeCrypto_EC_POINT_new(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_POINT_new(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_new(%p) => group == null", group);
jniThrowNullPointerException(env, "group == null");
return 0;
}
EC_POINT* point = EC_POINT_new(group);
if (point == NULL) {
jniThrowOutOfMemory(env, "Unable create an EC_POINT");
return 0;
}
return reinterpret_cast<uintptr_t>(point);
}
static void NativeCrypto_EC_POINT_clear_free(JNIEnv* env, jclass, jlong groupRef) {
EC_POINT* group = reinterpret_cast<EC_POINT*>(groupRef);
JNI_TRACE("EC_POINT_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_POINT_free(group);
JNI_TRACE("EC_POINT_clear_free(%p) => success", group);
}
static jboolean NativeCrypto_EC_POINT_cmp(JNIEnv* env, jclass, jobject groupRef, jobject point1Ref,
jobject point2Ref)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
const EC_POINT* point1 = fromContextObject<EC_POINT>(env, point1Ref);
const EC_POINT* point2 = fromContextObject<EC_POINT>(env, point2Ref);
JNI_TRACE("EC_POINT_cmp(%p, %p, %p)", group, point1, point2);
if (group == NULL || point1 == NULL || point2 == NULL) {
JNI_TRACE("EC_POINT_cmp(%p, %p, %p) => group == null || point1 == null || point2 == null",
group, point1, point2);
jniThrowNullPointerException(env, "group == null || point1 == null || point2 == null");
return false;
}
int ret = EC_POINT_cmp(group, point1, point2, (BN_CTX*)NULL);
JNI_TRACE("ECP_GROUP_cmp(%p, %p) => %d", point1, point2, ret);
return ret == 0;
}
static void NativeCrypto_EC_POINT_set_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef, jbyteArray xjavaBytes, jbyteArray yjavaBytes)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p)", group, point, xjavaBytes,
yjavaBytes);
if (group == NULL || point == NULL) {
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => group == null || point == null",
group, point, xjavaBytes, yjavaBytes);
jniThrowNullPointerException(env, "group == null || point == null");
return;
}
BIGNUM* xRef = NULL;
if (!arrayToBignum(env, xjavaBytes, &xRef)) {
return;
}
Unique_BIGNUM x(xRef);
BIGNUM* yRef = NULL;
if (!arrayToBignum(env, yjavaBytes, &yRef)) {
return;
}
Unique_BIGNUM y(yRef);
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_set_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
#if !defined(OPENSSL_IS_BORINGSSL)
case EC_CURVE_GF2M:
ret = EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
#endif
default:
jniThrowRuntimeException(env, "invalid curve type");
return;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates");
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => %d", group, point,
xjavaBytes, yjavaBytes, ret);
}
static jobjectArray NativeCrypto_EC_POINT_get_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
const EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
Unique_BIGNUM x(BN_new());
Unique_BIGNUM y(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_get_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return NULL;
}
if (ret != 1) {
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
throwExceptionIfNecessary(env, "EC_POINT_get_affine_coordinates");
return NULL;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray xBytes = bignumToArray(env, x.get(), "x");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, xBytes);
jbyteArray yBytes = bignumToArray(env, y.get(), "y");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, yBytes);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) => %p", group, point, joa);
return joa;
}
static jlong NativeCrypto_EC_KEY_generate_key(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_KEY_generate_key(%p)", group);
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_new() oom", group);
jniThrowOutOfMemory(env, "Unable to create an EC_KEY");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_set_group error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (EC_KEY_generate_key(eckey.get()) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_generate_key error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_KEY_generate_key");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EC_KEY_generate_key(%p) => %p", group, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EC_KEY_get1_group(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get1_group(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("EC_KEY_get1_group(%p) => pkey == null", pkey);
return 0;
}
if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
jniThrowRuntimeException(env, "not EC key");
JNI_TRACE("EC_KEY_get1_group(%p) => not EC key (type == %d)", pkey,
EVP_PKEY_type(pkey->type));
return 0;
}
EC_GROUP* group = EC_GROUP_dup(EC_KEY_get0_group(pkey->pkey.ec));
JNI_TRACE("EC_KEY_get1_group(%p) => %p", pkey, group);
return reinterpret_cast<uintptr_t>(group);
}
static jbyteArray NativeCrypto_EC_KEY_get_private_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_private_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return NULL;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return NULL;
}
const BIGNUM *privkey = EC_KEY_get0_private_key(eckey.get());
jbyteArray privBytes = bignumToArray(env, privkey, "privkey");
if (env->ExceptionCheck()) {
JNI_TRACE("EC_KEY_get_private_key(%p) => threw error", pkey);
return NULL;
}
JNI_TRACE("EC_KEY_get_private_key(%p) => %p", pkey, privBytes);
return privBytes;
}
static jlong NativeCrypto_EC_KEY_get_public_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_public_key(%p)", pkey);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return 0;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return 0;
}
Unique_EC_POINT dup(EC_POINT_dup(EC_KEY_get0_public_key(eckey.get()),
EC_KEY_get0_group(eckey.get())));
if (dup.get() == NULL) {
JNI_TRACE("EC_KEY_get_public_key(%p) => can't dup public key", pkey);
jniThrowRuntimeException(env, "EC_POINT_dup");
return 0;
}
JNI_TRACE("EC_KEY_get_public_key(%p) => %p", pkey, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv* env, jclass, jobject pkeyRef,
jboolean enabled)
{
#if !defined(OPENSSL_IS_BORINGSSL)
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_set_nonce_from_hash(%p, %d)", pkey, enabled ? 1 : 0);
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return;
}
EC_KEY_set_nonce_from_hash(eckey.get(), enabled ? 1 : 0);
#endif
}
static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass,
jbyteArray outArray, jint outOffset, jobject pubkeyRef, jobject privkeyRef)
{
EVP_PKEY* pubPkey = fromContextObject<EVP_PKEY>(env, pubkeyRef);
EVP_PKEY* privPkey = fromContextObject<EVP_PKEY>(env, privkeyRef);
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p)", outArray, outOffset, pubPkey, privPkey);
ScopedByteArrayRW out(env, outArray);
if (out.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) can't get output buffer",
outArray, outOffset, pubPkey, privPkey);
return -1;
}
if ((outOffset < 0) || ((size_t) outOffset >= out.size())) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
if (pubPkey == NULL) {
jniThrowNullPointerException(env, "pubPkey == null");
return -1;
}
Unique_EC_KEY pubkey(EVP_PKEY_get1_EC_KEY(pubPkey));
if (pubkey.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
const EC_POINT* pubkeyPoint = EC_KEY_get0_public_key(pubkey.get());
if (pubkeyPoint == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key point", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public");
return -1;
}
if (privPkey == NULL) {
jniThrowNullPointerException(env, "privPkey == null");
return -1;
}
Unique_EC_KEY privkey(EVP_PKEY_get1_EC_KEY(privPkey));
if (privkey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY private");
return -1;
}
int outputLength = ECDH_compute_key(
&out[outOffset],
out.size() - outOffset,
pubkeyPoint,
privkey.get(),
NULL // No KDF
);
if (outputLength == -1) {
throwExceptionIfNecessary(env, "ECDH_compute_key");
return -1;
}
return outputLength;
}
static jlong NativeCrypto_EVP_MD_CTX_create(JNIEnv* env, jclass) {
JNI_TRACE_MD("EVP_MD_CTX_create()");
Unique_EVP_MD_CTX ctx(EVP_MD_CTX_create());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable create a EVP_MD_CTX");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_create() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static void NativeCrypto_EVP_MD_CTX_init(JNIEnv* env, jclass, jobject ctxRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_init(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_init(ctx);
}
}
static void NativeCrypto_EVP_MD_CTX_destroy(JNIEnv*, jclass, jlong ctxRef) {
EVP_MD_CTX* ctx = reinterpret_cast<EVP_MD_CTX*>(ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_destroy(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_destroy(ctx);
}
}
static jint NativeCrypto_EVP_MD_CTX_copy(JNIEnv* env, jclass, jobject dstCtxRef, jobject srcCtxRef) {
EVP_MD_CTX* dst_ctx = fromContextObject<EVP_MD_CTX>(env, dstCtxRef);
const EVP_MD_CTX* src_ctx = fromContextObject<EVP_MD_CTX>(env, srcCtxRef);
JNI_TRACE_MD("EVP_MD_CTX_copy(%p. %p)", dst_ctx, src_ctx);
if (src_ctx == NULL) {
return 0;
} else if (dst_ctx == NULL) {
return 0;
}
int result = EVP_MD_CTX_copy_ex(dst_ctx, src_ctx);
if (result == 0) {
jniThrowRuntimeException(env, "Unable to copy EVP_MD_CTX");
freeOpenSslErrorState();
}
JNI_TRACE_MD("EVP_MD_CTX_copy(%p, %p) => %d", dst_ctx, src_ctx, result);
return result;
}
/*
* public static native int EVP_DigestFinal(long, byte[], int)
*/
static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray hash,
jint offset) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d)", ctx, hash, offset);
if (ctx == NULL) {
return -1;
} else if (hash == NULL) {
jniThrowNullPointerException(env, "ctx == null || hash == null");
return -1;
}
ScopedByteArrayRW hashBytes(env, hash);
if (hashBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_DigestFinal_ex(ctx,
reinterpret_cast<unsigned char*>(hashBytes.get() + offset),
&bytesWritten);
if (ok == 0) {
throwExceptionIfNecessary(env, "EVP_DigestFinal");
}
JNI_TRACE_MD("EVP_DigestFinal(%p, %p, %d) => %d", ctx, hash, offset, bytesWritten);
return bytesWritten;
}
static jint evpInit(JNIEnv* env, jobject evpMdCtxRef, jlong evpMdRef, const char* jniName,
int (*init_func)(EVP_MD_CTX*, const EVP_MD*, ENGINE*)) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* evp_md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE_MD("%s(%p, %p)", jniName, ctx, evp_md);
if (ctx == NULL) {
return 0;
} else if (evp_md == NULL) {
jniThrowNullPointerException(env, "evp_md == null");
return 0;
}
int ok = init_func(ctx, evp_md, NULL);
if (ok == 0) {
bool exception = throwExceptionIfNecessary(env, jniName);
if (exception) {
JNI_TRACE("%s(%p) => threw exception", jniName, evp_md);
return 0;
}
}
JNI_TRACE_MD("%s(%p, %p) => %d", jniName, ctx, evp_md, ok);
return ok;
}
static jint NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_DigestInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_SignInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_SignInit", EVP_DigestInit_ex);
}
static jint NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) {
return evpInit(env, evpMdCtxRef, evpMdRef, "EVP_VerifyInit", EVP_DigestInit_ex);
}
/*
* public static native int EVP_get_digestbyname(java.lang.String)
*/
static jlong NativeCrypto_EVP_get_digestbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%p)", algorithm);
if (algorithm == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s)", algorithmChars.c_str());
#if !defined(OPENSSL_IS_BORINGSSL)
const EVP_MD* evp_md = EVP_get_digestbyname(algorithmChars.c_str());
if (evp_md == NULL) {
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => %p", algorithmChars.c_str(), evp_md);
return reinterpret_cast<uintptr_t>(evp_md);
#else
const char *alg = algorithmChars.c_str();
const EVP_MD *md;
if (strcasecmp(alg, "md4") == 0) {
md = EVP_md4();
} else if (strcasecmp(alg, "md5") == 0) {
md = EVP_md5();
} else if (strcasecmp(alg, "sha1") == 0) {
md = EVP_sha1();
} else if (strcasecmp(alg, "sha224") == 0) {
md = EVP_sha224();
} else if (strcasecmp(alg, "sha256") == 0) {
md = EVP_sha256();
} else if (strcasecmp(alg, "sha384") == 0) {
md = EVP_sha384();
} else if (strcasecmp(alg, "sha512") == 0) {
md = EVP_sha512();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
return reinterpret_cast<uintptr_t>(md);
#endif
}
/*
* public static native int EVP_MD_size(long)
*/
static jint NativeCrypto_EVP_MD_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p) => %d", evp_md, result);
return result;
}
/*
* public static int void EVP_MD_block_size(long)
*/
static jint NativeCrypto_EVP_MD_block_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_block_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p) => %d", evp_md, result);
return result;
}
static void NativeCrypto_EVP_DigestSignInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jobject pkeyRef) {
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p)", mdCtx, md, pkey);
if (mdCtx == NULL) {
return;
}
if (md == NULL) {
jniThrowNullPointerException(env, "md == null");
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
return;
}
if (EVP_DigestSignInit(mdCtx, (EVP_PKEY_CTX **) NULL, md, (ENGINE *) NULL, pkey) <= 0) {
JNI_TRACE("ctx=%p EVP_DigestSignInit => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignInit");
return;
}
JNI_TRACE("EVP_DigestSignInit(%p, %p, %p) => success", mdCtx, md, pkey);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jbyteArray inJavaBytes, jint inOffset,
jint inLength, const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *,
size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE_MD("%s(%p, %p, %d, %d)", jniName, mdCtx, inJavaBytes, inOffset, inLength);
if (mdCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inJavaBytes);
if (inBytes.get() == NULL) {
return;
}
if (inOffset < 0 || size_t(inOffset) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inOffset");
return;
}
const ssize_t inEnd = inOffset + inLength;
if (inLength < 0 || inEnd < 0 || size_t(inEnd) > inBytes.size()) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inLength");
return;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char *>(inBytes.get());
if (!update_func(mdCtx, tmp + inOffset, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d, %d) => success", jniName, mdCtx, inJavaBytes, inOffset, inLength);
}
static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestSignUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_SignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_SignUpdate",
EVP_DigestUpdate);
}
static jbyteArray NativeCrypto_EVP_DigestSignFinal(JNIEnv* env, jclass, jobject evpMdCtxRef)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestSignFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return NULL;
}
size_t len;
if (EVP_DigestSignFinal(mdCtx, NULL, &len) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return 0;
}
ScopedLocalRef<jbyteArray> outJavaBytes(env, env->NewByteArray(len));
if (outJavaBytes.get() == NULL) {
return NULL;
}
ScopedByteArrayRW outBytes(env, outJavaBytes.get());
if (outBytes.get() == NULL) {
return NULL;
}
unsigned char *tmp = reinterpret_cast<unsigned char*>(outBytes.get());
if (EVP_DigestSignFinal(mdCtx, tmp, &len) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return 0;
}
JNI_TRACE("EVP_DigestSignFinal(%p) => %p", mdCtx, outJavaBytes.get());
return outJavaBytes.release();
}
/*
* public static native int EVP_SignFinal(long, byte[], int, long)
*/
static jint NativeCrypto_EVP_SignFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray signature,
jint offset, jobject pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p)", ctx, signature, offset, pkey);
if (ctx == NULL) {
return -1;
} else if (pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRW signatureBytes(env, signature);
if (signatureBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_SignFinal(ctx,
reinterpret_cast<unsigned char*>(signatureBytes.get() + offset),
&bytesWritten,
pkey);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_SignFinal");
}
JNI_TRACE("NativeCrypto_EVP_SignFinal(%p, %p, %d, %p) => %u",
ctx, signature, offset, pkey, bytesWritten);
return bytesWritten;
}
/*
* public static native void EVP_VerifyUpdate(long, byte[], int, int)
*/
static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray buffer, jint offset, jint length) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE("NativeCrypto_EVP_VerifyUpdate(%p, %p, %d, %d)", ctx, buffer, offset, length);
if (ctx == NULL) {
return;
} else if (buffer == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return;
}
if (bufferBytes.size() < static_cast<size_t>(offset + length)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return;
}
int ok = EVP_VerifyUpdate(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length);
if (ok == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyUpdate");
}
}
/*
* public static native int EVP_VerifyFinal(long, byte[], int, int, long)
*/
static jint NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray buffer,
jint offset, jint length, jobject pkeyRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p)",
ctx, buffer, offset, length, pkey);
if (ctx == NULL) {
return -1;
} else if (buffer == NULL || pkey == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedByteArrayRO bufferBytes(env, buffer);
if (bufferBytes.get() == NULL) {
return -1;
}
int ok = EVP_VerifyFinal(ctx,
reinterpret_cast<const unsigned char*>(bufferBytes.get() + offset),
length,
pkey);
if (ok < 0) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyFinal");
}
/*
* For DSA keys, OpenSSL appears to have a bug where it returns
* errors for any result != 1. See dsa_ossl.c in dsa_do_verify
*/
freeOpenSslErrorState();
JNI_TRACE("NativeCrypto_EVP_VerifyFinal(%p, %p, %d, %d, %p) => %d",
ctx, buffer, offset, length, pkey, ok);
return ok;
}
static jlong NativeCrypto_EVP_get_cipherbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("EVP_get_cipherbyname(%p)", algorithm);
#if !defined(OPENSSL_IS_BORINGSSL)
if (algorithm == NULL) {
JNI_TRACE("EVP_get_cipherbyname(%p) => threw exception algorithm == null", algorithm);
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("EVP_get_cipherbyname(%p) => algorithm = %s", algorithm, algorithmChars.c_str());
const EVP_CIPHER* evp_cipher = EVP_get_cipherbyname(algorithmChars.c_str());
if (evp_cipher == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("EVP_get_cipherbyname(%s) => %p", algorithmChars.c_str(), evp_cipher);
return reinterpret_cast<uintptr_t>(evp_cipher);
#else
ScopedUtfChars scoped_alg(env, algorithm);
const char *alg = scoped_alg.c_str();
const EVP_CIPHER *cipher;
if (strcasecmp(alg, "rc4") == 0) {
cipher = EVP_rc4();
} else if (strcasecmp(alg, "des-cbc") == 0) {
cipher = EVP_des_cbc();
} else if (strcasecmp(alg, "des-ede3-cbc") == 0) {
cipher = EVP_des_ede3_cbc();
} else if (strcasecmp(alg, "aes-128-ecb") == 0) {
cipher = EVP_aes_128_ecb();
} else if (strcasecmp(alg, "aes-128-cbc") == 0) {
cipher = EVP_aes_128_cbc();
} else if (strcasecmp(alg, "aes-128-ctr") == 0) {
cipher = EVP_aes_128_ctr();
} else if (strcasecmp(alg, "aes-128-gcm") == 0) {
cipher = EVP_aes_128_gcm();
} else if (strcasecmp(alg, "aes-256-ecb") == 0) {
cipher = EVP_aes_256_ecb();
} else if (strcasecmp(alg, "aes-256-cbc") == 0) {
cipher = EVP_aes_256_cbc();
} else if (strcasecmp(alg, "aes-256-ctr") == 0) {
cipher = EVP_aes_256_ctr();
} else if (strcasecmp(alg, "aes-256-gcm") == 0) {
cipher = EVP_aes_256_gcm();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
return reinterpret_cast<uintptr_t>(cipher);
#endif
}
static void NativeCrypto_EVP_CipherInit_ex(JNIEnv* env, jclass, jobject ctxRef, jlong evpCipherRef,
jbyteArray keyArray, jbyteArray ivArray, jboolean encrypting) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d)", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("EVP_CipherUpdate => ctx == null");
return;
}
// The key can be null if we need to set extra parameters.
UniquePtr<unsigned char[]> keyPtr;
if (keyArray != NULL) {
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
keyPtr.reset(new unsigned char[keyBytes.size()]);
memcpy(keyPtr.get(), keyBytes.get(), keyBytes.size());
}
// The IV can be null if we're using ECB.
UniquePtr<unsigned char[]> ivPtr;
if (ivArray != NULL) {
ScopedByteArrayRO ivBytes(env, ivArray);
if (ivBytes.get() == NULL) {
return;
}
ivPtr.reset(new unsigned char[ivBytes.size()]);
memcpy(ivPtr.get(), ivBytes.get(), ivBytes.size());
}
if (!EVP_CipherInit_ex(ctx, evpCipher, NULL, keyPtr.get(), ivPtr.get(), encrypting ? 1 : 0)) {
throwExceptionIfNecessary(env, "EVP_CipherInit_ex");
JNI_TRACE("EVP_CipherInit_ex => error initializing cipher");
return;
}
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d) => success", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
}
/*
* public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
* int inOffset, int inLength);
*/
static jint NativeCrypto_EVP_CipherUpdate(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray inArray, jint inOffset, jint inLength) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d)", ctx, outArray, outOffset, inArray, inOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherUpdate => ctx == null", ctx);
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
const size_t inSize = inBytes.size();
if (size_t(inOffset + inLength) > inSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"in.length < (inSize + inOffset)");
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
const size_t outSize = outBytes.size();
if (size_t(outOffset + inLength) > outSize) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"out.length < inSize + outOffset + blockSize - 1");
return 0;
}
JNI_TRACE("ctx=%p EVP_CipherUpdate in=%p in.length=%zd inOffset=%zd inLength=%zd out=%p out.length=%zd outOffset=%zd",
ctx, inBytes.get(), inBytes.size(), inOffset, inLength, outBytes.get(), outBytes.size(), outOffset);
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
const unsigned char* in = reinterpret_cast<const unsigned char*>(inBytes.get());
int outl;
if (!EVP_CipherUpdate(ctx, out + outOffset, &outl, in + inOffset, inLength)) {
throwExceptionIfNecessary(env, "EVP_CipherUpdate");
JNI_TRACE("ctx=%p EVP_CipherUpdate => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d) => %d", ctx, outArray, outOffset, inArray,
inOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CipherFinal_ex(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray outArray, jint outOffset) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherFinal_ex(%p, %p, %d)", ctx, outArray, outOffset);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => ctx == null", ctx);
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
int outl;
if (!EVP_CipherFinal_ex(ctx, out + outOffset, &outl)) {
throwExceptionIfNecessary(env, "EVP_CipherFinal_ex");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherFinal(%p, %p, %d) => %d", ctx, outArray, outOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CIPHER_iv_length(JNIEnv* env, jclass, jlong evpCipherRef) {
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CIPHER_iv_length(%p)", evpCipher);
if (evpCipher == NULL) {
jniThrowNullPointerException(env, "evpCipher == null");
JNI_TRACE("EVP_CIPHER_iv_length => evpCipher == null");
return 0;
}
const int ivLength = EVP_CIPHER_iv_length(evpCipher);
JNI_TRACE("EVP_CIPHER_iv_length(%p) => %d", evpCipher, ivLength);
return ivLength;
}
static jlong NativeCrypto_EVP_CIPHER_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("EVP_CIPHER_CTX_new()");
Unique_EVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate cipher context");
JNI_TRACE("EVP_CipherInit_ex => context allocation error");
return 0;
}
JNI_TRACE("EVP_CIPHER_CTX_new() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static jint NativeCrypto_EVP_CIPHER_CTX_block_size(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_block_size => ctx == null", ctx);
return 0;
}
int blockSize = EVP_CIPHER_CTX_block_size(ctx);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p) => %d", ctx, blockSize);
return blockSize;
}
static jint NativeCrypto_get_EVP_CIPHER_CTX_buf_len(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p)", ctx);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_buf_len => ctx == null", ctx);
return 0;
}
int buf_len = ctx->buf_len;
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p) => %d", ctx, buf_len);
return buf_len;
}
static void NativeCrypto_EVP_CIPHER_CTX_set_padding(JNIEnv* env, jclass, jobject ctxRef,
jboolean enablePaddingBool) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
jint enablePadding = enablePaddingBool ? 1 : 0;
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d)", ctx, enablePadding);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_padding => ctx == null", ctx);
return;
}
EVP_CIPHER_CTX_set_padding(ctx, enablePadding); // Not void, but always returns 1.
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d) => success", ctx, enablePadding);
}
static void NativeCrypto_EVP_CIPHER_CTX_set_key_length(JNIEnv* env, jclass, jobject ctxRef,
jint keySizeBits) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d)", ctx, keySizeBits);
if (ctx == NULL) {
jniThrowNullPointerException(env, "ctx == null");
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_key_length => ctx == null", ctx);
return;
}
if (!EVP_CIPHER_CTX_set_key_length(ctx, keySizeBits)) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_CIPHER_CTX_set_key_length");
JNI_TRACE("NativeCrypto_EVP_CIPHER_CTX_set_key_length => threw error");
return;
}
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d) => success", ctx, keySizeBits);
}
static void NativeCrypto_EVP_CIPHER_CTX_cleanup(JNIEnv* env, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p)", ctx);
if (ctx != NULL) {
if (!EVP_CIPHER_CTX_cleanup(ctx)) {
throwExceptionIfNecessary(env, "EVP_CIPHER_CTX_cleanup");
JNI_TRACE("EVP_CIPHER_CTX_cleanup => threw error");
return;
}
}
JNI_TRACE("EVP_CIPHER_CTX_cleanup(%p) => success", ctx);
}
/**
* public static native void RAND_seed(byte[]);
*/
static void NativeCrypto_RAND_seed(JNIEnv* env, jclass, jbyteArray seed) {
JNI_TRACE("NativeCrypto_RAND_seed seed=%p", seed);
#if !defined(OPENSSL_IS_BORINGSSL)
ScopedByteArrayRO randseed(env, seed);
if (randseed.get() == NULL) {
return;
}
RAND_seed(randseed.get(), randseed.size());
#else
return;
#endif
}
static jint NativeCrypto_RAND_load_file(JNIEnv* env, jclass, jstring filename, jlong max_bytes) {
JNI_TRACE("NativeCrypto_RAND_load_file filename=%p max_bytes=%lld", filename, (long long) max_bytes);
#if !defined(OPENSSL_IS_BORINGSSL)
ScopedUtfChars file(env, filename);
if (file.c_str() == NULL) {
return -1;
}
int result = RAND_load_file(file.c_str(), max_bytes);
JNI_TRACE("NativeCrypto_RAND_load_file file=%s => %d", file.c_str(), result);
return result;
#else
// OpenSSLRandom calls this and checks the return value.
return static_cast<jint>(max_bytes);
#endif
}
static void NativeCrypto_RAND_bytes(JNIEnv* env, jclass, jbyteArray output) {
JNI_TRACE("NativeCrypto_RAND_bytes(%p)", output);
ScopedByteArrayRW outputBytes(env, output);
if (outputBytes.get() == NULL) {
return;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(outputBytes.get());
if (RAND_bytes(tmp, outputBytes.size()) <= 0) {
throwExceptionIfNecessary(env, "NativeCrypto_RAND_bytes");
JNI_TRACE("tmp=%p NativeCrypto_RAND_bytes => threw error", tmp);
return;
}
JNI_TRACE("NativeCrypto_RAND_bytes(%p) => success", output);
}
static jint NativeCrypto_OBJ_txt2nid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return 0;
}
int nid = OBJ_txt2nid(oid.c_str());
JNI_TRACE("OBJ_txt2nid(%s) => %d", oid.c_str(), nid);
return nid;
}
static jstring NativeCrypto_OBJ_txt2nid_longName(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_longName(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_longName(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_longName(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const char* longName = OBJ_nid2ln(nid);
JNI_TRACE("OBJ_txt2nid_longName(%s) => %s", oid.c_str(), longName);
return env->NewStringUTF(longName);
}
static jstring ASN1_OBJECT_to_OID_string(JNIEnv* env, const ASN1_OBJECT* obj) {
/*
* The OBJ_obj2txt API doesn't "measure" if you pass in NULL as the buffer.
* Just make a buffer that's large enough here. The documentation recommends
* 80 characters.
*/
char output[128];
int ret = OBJ_obj2txt(output, sizeof(output), obj, 1);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1_OBJECT_to_OID_string");
return NULL;
} else if (size_t(ret) >= sizeof(output)) {
jniThrowRuntimeException(env, "ASN1_OBJECT_to_OID_string buffer too small");
return NULL;
}
JNI_TRACE("ASN1_OBJECT_to_OID_string(%p) => %s", obj, output);
return env->NewStringUTF(output);
}
static jlong NativeCrypto_create_BIO_InputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_InputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_InputStream(streamObj));
JNI_TRACE("create_BIO_InputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static jlong NativeCrypto_create_BIO_OutputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_OutputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_OutputStream(streamObj));
JNI_TRACE("create_BIO_OutputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static int NativeCrypto_BIO_read(JNIEnv* env, jclass, jlong bioRef, jbyteArray outputJavaBytes) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_read(%p, %p)", bio, outputJavaBytes);
if (outputJavaBytes == NULL) {
jniThrowNullPointerException(env, "output == null");
JNI_TRACE("BIO_read(%p, %p) => output == null", bio, outputJavaBytes);
return 0;
}
int outputSize = env->GetArrayLength(outputJavaBytes);
UniquePtr<unsigned char[]> buffer(new unsigned char[outputSize]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for read");
return 0;
}
int read = BIO_read(bio, buffer.get(), outputSize);
if (read <= 0) {
jniThrowException(env, "java/io/IOException", "BIO_read");
JNI_TRACE("BIO_read(%p, %p) => threw IO exception", bio, outputJavaBytes);
return 0;
}
env->SetByteArrayRegion(outputJavaBytes, 0, read, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("BIO_read(%p, %p) => %d", bio, outputJavaBytes, read);
return read;
}
static void NativeCrypto_BIO_write(JNIEnv* env, jclass, jlong bioRef, jbyteArray inputJavaBytes,
jint offset, jint length) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_write(%p, %p, %d, %d)", bio, inputJavaBytes, offset, length);
if (inputJavaBytes == NULL) {
jniThrowNullPointerException(env, "input == null");
return;
}
if (offset < 0 || length < 0) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "offset < 0 || length < 0");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
int inputSize = env->GetArrayLength(inputJavaBytes);
if (inputSize < offset + length) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException",
"input.length < offset + length");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[length]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for write");
return;
}
env->GetByteArrayRegion(inputJavaBytes, offset, length, reinterpret_cast<jbyte*>(buffer.get()));
if (BIO_write(bio, buffer.get(), length) != length) {
freeOpenSslErrorState();
jniThrowException(env, "java/io/IOException", "BIO_write");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IO error", bio, inputJavaBytes, offset, length);
return;
}
JNI_TRACE("BIO_write(%p, %p, %d, %d) => success", bio, inputJavaBytes, offset, length);
}
static void NativeCrypto_BIO_free_all(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_free_all(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return;
}
BIO_free_all(bio);
}
static jstring X509_NAME_to_jstring(JNIEnv* env, X509_NAME* name, unsigned long flags) {
JNI_TRACE("X509_NAME_to_jstring(%p)", name);
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
JNI_TRACE("X509_NAME_to_jstring(%p) => threw error", name);
return NULL;
}
/* Don't interpret the string. */
flags &= ~(ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_ESC_MSB);
/* Write in given format and null terminate. */
X509_NAME_print_ex(buffer.get(), name, 0, flags);
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
JNI_TRACE("X509_NAME_to_jstring(%p) => \"%s\"", name, tmp);
return env->NewStringUTF(tmp);
}
/**
* Converts GENERAL_NAME items to the output format expected in
* X509Certificate#getSubjectAlternativeNames and
* X509Certificate#getIssuerAlternativeNames return.
*/
static jobject GENERAL_NAME_to_jobject(JNIEnv* env, GENERAL_NAME* gen) {
switch (gen->type) {
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI: {
// This must not be a T61String and must not contain NULLs.
const char* data = reinterpret_cast<const char*>(ASN1_STRING_data(gen->d.ia5));
ssize_t len = ASN1_STRING_length(gen->d.ia5);
if ((len == static_cast<ssize_t>(strlen(data)))
&& (ASN1_PRINTABLE_type(ASN1_STRING_data(gen->d.ia5), len) != V_ASN1_T61STRING)) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI \"%s\"", gen, data);
return env->NewStringUTF(data);
} else {
jniThrowException(env, "java/security/cert/CertificateParsingException",
"Invalid dNSName encoding");
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI invalid", gen);
return NULL;
}
}
case GEN_DIRNAME:
/* Write in RFC 2253 format */
return X509_NAME_to_jstring(env, gen->d.directoryName, XN_FLAG_RFC2253);
case GEN_IPADD: {
const void *ip = reinterpret_cast<const void *>(gen->d.ip->data);
if (gen->d.ip->length == 4) {
// IPv4
UniquePtr<char[]> buffer(new char[INET_ADDRSTRLEN]);
if (inet_ntop(AF_INET, ip, buffer.get(), INET_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 failed %s", gen, strerror(errno));
}
} else if (gen->d.ip->length == 16) {
// IPv6
UniquePtr<char[]> buffer(new char[INET6_ADDRSTRLEN]);
if (inet_ntop(AF_INET6, ip, buffer.get(), INET6_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 failed %s", gen, strerror(errno));
}
}
/* Invalid IP encodings are pruned out without throwing an exception. */
return NULL;
}
case GEN_RID:
return ASN1_OBJECT_to_OID_string(env, gen->d.registeredID);
case GEN_OTHERNAME:
case GEN_X400:
default:
return ASN1ToByteArray<GENERAL_NAME>(env, gen, i2d_GENERAL_NAME);
}
return NULL;
}
#define GN_STACK_SUBJECT_ALT_NAME 1
#define GN_STACK_ISSUER_ALT_NAME 2
static jobjectArray NativeCrypto_get_X509_GENERAL_NAME_stack(JNIEnv* env, jclass, jlong x509Ref,
jint type) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d)", x509, type);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => x509 == null", x509, type);
return NULL;
}
X509_check_ca(x509);
STACK_OF(GENERAL_NAME)* gn_stack;
Unique_sk_GENERAL_NAME stackHolder;
if (type == GN_STACK_SUBJECT_ALT_NAME) {
gn_stack = x509->altname;
} else if (type == GN_STACK_ISSUER_ALT_NAME) {
stackHolder.reset(
static_cast<STACK_OF(GENERAL_NAME)*>(X509_get_ext_d2i(x509, NID_issuer_alt_name,
NULL, NULL)));
gn_stack = stackHolder.get();
} else {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => unknown type", x509, type);
return NULL;
}
int count = sk_GENERAL_NAME_num(gn_stack);
if (count <= 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no entries)", x509, type);
return NULL;
}
/*
* Keep track of how many originally so we can ignore any invalid
* values later.
*/
const int origCount = count;
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, objectArrayClass, NULL));
for (int i = 0, j = 0; i < origCount; i++, j++) {
GENERAL_NAME* gen = sk_GENERAL_NAME_value(gn_stack, i);
ScopedLocalRef<jobject> val(env, GENERAL_NAME_to_jobject(env, gen));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => threw exception parsing gen name",
x509, type);
return NULL;
}
/*
* If it's NULL, we'll have to skip this, reduce the number of total
* entries, and fix up the array later.
*/
if (val.get() == NULL) {
j--;
count--;
continue;
}
ScopedLocalRef<jobjectArray> item(env, env->NewObjectArray(2, objectClass, NULL));
ScopedLocalRef<jobject> type(env, env->CallStaticObjectMethod(integerClass,
integer_valueOfMethod, gen->type));
env->SetObjectArrayElement(item.get(), 0, type.get());
env->SetObjectArrayElement(item.get(), 1, val.get());
env->SetObjectArrayElement(joa.get(), j, item.get());
}
if (count == 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to 0; returning NULL",
x509, type, origCount);
joa.reset(NULL);
} else if (origCount != count) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to %d", x509, type,
origCount, count);
ScopedLocalRef<jobjectArray> joa_copy(env, env->NewObjectArray(count, objectArrayClass,
NULL));
for (int i = 0; i < count; i++) {
ScopedLocalRef<jobject> item(env, env->GetObjectArrayElement(joa.get(), i));
env->SetObjectArrayElement(joa_copy.get(), i, item.get());
}
joa.reset(joa_copy.release());
}
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => %d entries", x509, type, count);
return joa.release();
}
static jlong NativeCrypto_X509_get_notBefore(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notBefore(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notBefore(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notBefore = X509_get_notBefore(x509);
JNI_TRACE("X509_get_notBefore(%p) => %p", x509, notBefore);
return reinterpret_cast<uintptr_t>(notBefore);
}
static jlong NativeCrypto_X509_get_notAfter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notAfter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notAfter(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notAfter = X509_get_notAfter(x509);
JNI_TRACE("X509_get_notAfter(%p) => %p", x509, notAfter);
return reinterpret_cast<uintptr_t>(notAfter);
}
static long NativeCrypto_X509_get_version(JNIEnv*, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_version(%p)", x509);
long version = X509_get_version(x509);
JNI_TRACE("X509_get_version(%p) => %ld", x509, version);
return version;
}
template<typename T>
static jbyteArray get_X509Type_serialNumber(JNIEnv* env, T* x509Type, ASN1_INTEGER* (*get_serial_func)(T*)) {
JNI_TRACE("get_X509Type_serialNumber(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_serialNumber(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_INTEGER* serialNumber = get_serial_func(x509Type);
Unique_BIGNUM serialBn(ASN1_INTEGER_to_BN(serialNumber, NULL));
if (serialBn.get() == NULL) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
ScopedLocalRef<jbyteArray> serialArray(env, bignumToArray(env, serialBn.get(), "serialBn"));
if (env->ExceptionCheck()) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
JNI_TRACE("X509_get_serialNumber(%p) => %p", x509Type, serialArray.get());
return serialArray.release();
}
/* OpenSSL includes set_serialNumber but not get. */
#if !defined(X509_REVOKED_get_serialNumber)
static ASN1_INTEGER* X509_REVOKED_get_serialNumber(X509_REVOKED* x) {
return x->serialNumber;
}
#endif
static jbyteArray NativeCrypto_X509_get_serialNumber(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_serialNumber(%p)", x509);
return get_X509Type_serialNumber<X509>(env, x509, X509_get_serialNumber);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_serialNumber(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_serialNumber(%p)", revoked);
return get_X509Type_serialNumber<X509_REVOKED>(env, revoked, X509_REVOKED_get_serialNumber);
}
static void NativeCrypto_X509_verify(JNIEnv* env, jclass, jlong x509Ref, jobject pkeyRef) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_verify(%p, %p)", x509, pkey);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_verify(%p, %p) => x509 == null", x509, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_verify(%p, %p) => pkey == null", x509, pkey);
return;
}
if (X509_verify(x509, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_verify");
JNI_TRACE("X509_verify(%p, %p) => verify failure", x509, pkey);
} else {
JNI_TRACE("X509_verify(%p, %p) => verify success", x509, pkey);
}
}
static jbyteArray NativeCrypto_get_X509_cert_info_enc(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_cert_info_enc(%p)", x509);
return ASN1ToByteArray<X509_CINF>(env, x509->cert_info, i2d_X509_CINF);
}
static jint NativeCrypto_get_X509_ex_flags(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_flags(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_flags(%p) => x509 == null", x509);
return 0;
}
X509_check_ca(x509);
return x509->ex_flags;
}
static jboolean NativeCrypto_X509_check_issued(JNIEnv*, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_check_issued(%p, %p)", x509_1, x509_2);
int ret = X509_check_issued(x509_1, x509_2);
JNI_TRACE("X509_check_issued(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void get_X509_signature(X509 *x509, ASN1_BIT_STRING** signature) {
*signature = x509->signature;
}
static void get_X509_CRL_signature(X509_CRL *crl, ASN1_BIT_STRING** signature) {
*signature = crl->signature;
}
template<typename T>
static jbyteArray get_X509Type_signature(JNIEnv* env, T* x509Type, void (*get_signature_func)(T*, ASN1_BIT_STRING**)) {
JNI_TRACE("get_X509Type_signature(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_signature(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_BIT_STRING* signature;
get_signature_func(x509Type, &signature);
ScopedLocalRef<jbyteArray> signatureArray(env, env->NewByteArray(signature->length));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509Type_signature(%p) => threw exception", x509Type);
return NULL;
}
ScopedByteArrayRW signatureBytes(env, signatureArray.get());
if (signatureBytes.get() == NULL) {
JNI_TRACE("get_X509Type_signature(%p) => using byte array failed", x509Type);
return NULL;
}
memcpy(signatureBytes.get(), signature->data, signature->length);
JNI_TRACE("get_X509Type_signature(%p) => %p (%d bytes)", x509Type, signatureArray.get(),
signature->length);
return signatureArray.release();
}
static jbyteArray NativeCrypto_get_X509_signature(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_signature(%p)", x509);
return get_X509Type_signature<X509>(env, x509, get_X509_signature);
}
static jbyteArray NativeCrypto_get_X509_CRL_signature(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_signature(%p)", crl);
return get_X509Type_signature<X509_CRL>(env, crl, get_X509_CRL_signature);
}
static jlong NativeCrypto_X509_CRL_get0_by_cert(JNIEnv* env, jclass, jlong x509crlRef, jlong x509Ref) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p)", x509crl, x509);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509crl == null", x509crl, x509);
return 0;
} else if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509 == null", x509crl, x509);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_cert(x509crl, &revoked, x509);
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => none", x509crl, x509);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, x509, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
static jlong NativeCrypto_X509_CRL_get0_by_serial(JNIEnv* env, jclass, jlong x509crlRef, jbyteArray serialArray) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p)", x509crl, serialArray);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => crl == null", x509crl, serialArray);
return 0;
}
Unique_BIGNUM serialBn(BN_new());
if (serialBn.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN allocation failed", x509crl, serialArray);
return 0;
}
BIGNUM* serialBare = serialBn.get();
if (!arrayToBignum(env, serialArray, &serialBare)) {
if (!env->ExceptionCheck()) {
jniThrowNullPointerException(env, "serial == null");
}
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
Unique_ASN1_INTEGER serialInteger(BN_to_ASN1_INTEGER(serialBn.get(), NULL));
if (serialInteger.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_serial(x509crl, &revoked, serialInteger.get());
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => none", x509crl, serialArray);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, serialArray, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
/* This appears to be missing from OpenSSL. */
#if !defined(X509_REVOKED_dup)
X509_REVOKED* X509_REVOKED_dup(X509_REVOKED* x) {
return reinterpret_cast<X509_REVOKED*>(ASN1_item_dup(ASN1_ITEM_rptr(X509_REVOKED), x));
}
#endif
static jlongArray NativeCrypto_X509_CRL_get_REVOKED(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_REVOKED(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
return NULL;
}
STACK_OF(X509_REVOKED)* stack = X509_CRL_get_REVOKED(crl);
if (stack == NULL) {
JNI_TRACE("X509_CRL_get_REVOKED(%p) => stack is null", crl);
return NULL;
}
size_t size = sk_X509_REVOKED_num(stack);
ScopedLocalRef<jlongArray> revokedArray(env, env->NewLongArray(size));
ScopedLongArrayRW revoked(env, revokedArray.get());
for (size_t i = 0; i < size; i++) {
X509_REVOKED* item = reinterpret_cast<X509_REVOKED*>(sk_X509_REVOKED_value(stack, i));
revoked[i] = reinterpret_cast<uintptr_t>(X509_REVOKED_dup(item));
}
JNI_TRACE("X509_CRL_get_REVOKED(%p) => %p [size=%zd]", stack, revokedArray.get(), size);
return revokedArray.release();
}
static jbyteArray NativeCrypto_i2d_X509_CRL(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("i2d_X509_CRL(%p)", crl);
return ASN1ToByteArray<X509_CRL>(env, crl, i2d_X509_CRL);
}
static void NativeCrypto_X509_CRL_free(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_free(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_free(%p) => crl == null", crl);
return;
}
X509_CRL_free(crl);
}
static void NativeCrypto_X509_CRL_print(JNIEnv* env, jclass, jlong bioRef, jlong x509CrlRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_print(%p, %p)", bio, crl);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_CRL_print(%p, %p) => bio == null", bio, crl);
return;
}
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_print(%p, %p) => crl == null", bio, crl);
return;
}
if (!X509_CRL_print(bio, crl)) {
throwExceptionIfNecessary(env, "X509_CRL_print");
JNI_TRACE("X509_CRL_print(%p, %p) => threw error", bio, crl);
} else {
JNI_TRACE("X509_CRL_print(%p, %p) => success", bio, crl);
}
}
static jstring NativeCrypto_get_X509_CRL_sig_alg_oid(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p)", crl);
if (crl == NULL || crl->sig_alg == NULL) {
jniThrowNullPointerException(env, "crl == NULL || crl->sig_alg == NULL");
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p) => crl == NULL", crl);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, crl->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_CRL_sig_alg_parameter(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => crl == null", crl);
return NULL;
}
if (crl->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => null", crl);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, crl->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbyteArray NativeCrypto_X509_CRL_get_issuer_name(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_issuer_name(%p)", crl);
return ASN1ToByteArray<X509_NAME>(env, X509_CRL_get_issuer(crl), i2d_X509_NAME);
}
static long NativeCrypto_X509_CRL_get_version(JNIEnv*, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_version(%p)", crl);
long version = X509_CRL_get_version(crl);
JNI_TRACE("X509_CRL_get_version(%p) => %ld", crl, version);
return version;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static X509_EXTENSION *X509Type_get_ext(JNIEnv* env, T* x509Type, jstring oidString) {
JNI_TRACE("X509Type_get_ext(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509 == null");
return NULL;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
return NULL;
}
Unique_ASN1_OBJECT asn1(OBJ_txt2obj(oid.c_str(), 1));
if (asn1.get() == NULL) {
JNI_TRACE("X509Type_get_ext(%p, %s) => oid conversion failed", x509Type, oid.c_str());
freeOpenSslErrorState();
return NULL;
}
int extIndex = get_ext_by_OBJ_func(x509Type, (ASN1_OBJECT*) asn1.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509Type_get_ext(%p, %s) => ext not found", x509Type, oid.c_str());
return NULL;
}
X509_EXTENSION* ext = get_ext_func(x509Type, extIndex);
JNI_TRACE("X509Type_get_ext(%p, %s) => %p", x509Type, oid.c_str(), ext);
return ext;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static jbyteArray X509Type_get_ext_oid(JNIEnv* env, T* x509Type, jstring oidString) {
X509_EXTENSION* ext = X509Type_get_ext<T, get_ext_by_OBJ_func, get_ext_func>(env, x509Type,
oidString);
if (ext == NULL) {
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => fetching extension failed", x509Type, oidString);
return NULL;
}
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => %p", x509Type, oidString, ext->value);
return ASN1ToByteArray<ASN1_OCTET_STRING>(env, ext->value, i2d_ASN1_OCTET_STRING);
}
static jint NativeCrypto_X509_CRL_get_ext(JNIEnv* env, jclass, jlong x509CrlRef, jstring oid) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext(%p, %p)", crl, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(
env, crl, oid);
JNI_TRACE("X509_CRL_get_ext(%p, %p) => %p", crl, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jint NativeCrypto_X509_REVOKED_get_ext(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oid) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext(%p, %p)", revoked, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ,
X509_REVOKED_get_ext>(env, revoked, oid);
JNI_TRACE("X509_REVOKED_get_ext(%p, %p) => %p", revoked, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_dup(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_dup(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_dup(%p) => revoked == null", revoked);
return 0;
}
X509_REVOKED* dup = X509_REVOKED_dup(revoked);
JNI_TRACE("X509_REVOKED_dup(%p) => %p", revoked, dup);
return reinterpret_cast<uintptr_t>(dup);
}
static jlong NativeCrypto_get_X509_REVOKED_revocationDate(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("get_X509_REVOKED_revocationDate(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => revoked == null", revoked);
return 0;
}
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => %p", revoked, revoked->revocationDate);
return reinterpret_cast<uintptr_t>(revoked->revocationDate);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
static void NativeCrypto_X509_REVOKED_print(JNIEnv* env, jclass, jlong bioRef, jlong x509RevokedRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_print(%p, %p)", bio, revoked);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => bio == null", bio, revoked);
return;
}
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => revoked == null", bio, revoked);
return;
}
BIO_printf(bio, "Serial Number: ");
i2a_ASN1_INTEGER(bio, revoked->serialNumber);
BIO_printf(bio, "\nRevocation Date: ");
ASN1_TIME_print(bio, revoked->revocationDate);
BIO_printf(bio, "\n");
X509V3_extensions_print(bio, "CRL entry extensions", revoked->extensions, 0, 0);
}
#pragma GCC diagnostic pop
static jbyteArray NativeCrypto_get_X509_CRL_crl_enc(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_crl_enc(%p)", crl);
return ASN1ToByteArray<X509_CRL_INFO>(env, crl->crl, i2d_X509_CRL_INFO);
}
static void NativeCrypto_X509_CRL_verify(JNIEnv* env, jclass, jlong x509CrlRef, jobject pkeyRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_CRL_verify(%p, %p)", crl, pkey);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => crl == null", crl, pkey);
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => pkey == null", crl, pkey);
return;
}
if (X509_CRL_verify(crl, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_CRL_verify");
JNI_TRACE("X509_CRL_verify(%p, %p) => verify failure", crl, pkey);
} else {
JNI_TRACE("X509_CRL_verify(%p, %p) => verify success", crl, pkey);
}
}
static jlong NativeCrypto_X509_CRL_get_lastUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_lastUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* lastUpdate = X509_CRL_get_lastUpdate(crl);
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => %p", crl, lastUpdate);
return reinterpret_cast<uintptr_t>(lastUpdate);
}
static jlong NativeCrypto_X509_CRL_get_nextUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_nextUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* nextUpdate = X509_CRL_get_nextUpdate(crl);
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => %p", crl, nextUpdate);
return reinterpret_cast<uintptr_t>(nextUpdate);
}
static jbyteArray NativeCrypto_i2d_X509_REVOKED(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* x509Revoked =
reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("i2d_X509_REVOKED(%p)", x509Revoked);
return ASN1ToByteArray<X509_REVOKED>(env, x509Revoked, i2d_X509_REVOKED);
}
static jint NativeCrypto_X509_supported_extension(JNIEnv* env, jclass, jlong x509ExtensionRef) {
X509_EXTENSION* ext = reinterpret_cast<X509_EXTENSION*>(static_cast<uintptr_t>(x509ExtensionRef));
if (ext == NULL) {
jniThrowNullPointerException(env, "ext == NULL");
return 0;
}
return X509_supported_extension(ext);
}
static inline void get_ASN1_TIME_data(char **data, int* output, size_t len) {
char c = **data;
**data = '\0';
*data -= len;
*output = atoi(*data);
*(*data + len) = c;
}
static void NativeCrypto_ASN1_TIME_to_Calendar(JNIEnv* env, jclass, jlong asn1TimeRef, jobject calendar) {
ASN1_TIME* asn1Time = reinterpret_cast<ASN1_TIME*>(static_cast<uintptr_t>(asn1TimeRef));
JNI_TRACE("ASN1_TIME_to_Calendar(%p, %p)", asn1Time, calendar);
if (asn1Time == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
Unique_ASN1_GENERALIZEDTIME gen(ASN1_TIME_to_generalizedtime(asn1Time, NULL));
if (gen.get() == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
if (gen->length < 14 || gen->data == NULL) {
jniThrowNullPointerException(env, "gen->length < 14 || gen->data == NULL");
return;
}
int sec, min, hour, mday, mon, year;
char *p = (char*) &gen->data[14];
get_ASN1_TIME_data(&p, &sec, 2);
get_ASN1_TIME_data(&p, &min, 2);
get_ASN1_TIME_data(&p, &hour, 2);
get_ASN1_TIME_data(&p, &mday, 2);
get_ASN1_TIME_data(&p, &mon, 2);
get_ASN1_TIME_data(&p, &year, 4);
env->CallVoidMethod(calendar, calendar_setMethod, year, mon - 1, mday, hour, min, sec);
}
static jstring NativeCrypto_OBJ_txt2nid_oid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_oid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_oid(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_oid(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const ASN1_OBJECT* obj = OBJ_nid2obj(nid);
if (obj == NULL) {
throwExceptionIfNecessary(env, "OBJ_nid2obj");
return NULL;
}
ScopedLocalRef<jstring> ouputStr(env, ASN1_OBJECT_to_OID_string(env, obj));
JNI_TRACE("OBJ_txt2nid_oid(%s) => %p", oid.c_str(), ouputStr.get());
return ouputStr.release();
}
static jstring NativeCrypto_X509_NAME_print_ex(JNIEnv* env, jclass, jlong x509NameRef, jlong jflags) {
X509_NAME* x509name = reinterpret_cast<X509_NAME*>(static_cast<uintptr_t>(x509NameRef));
unsigned long flags = static_cast<unsigned long>(jflags);
JNI_TRACE("X509_NAME_print_ex(%p, %ld)", x509name, flags);
if (x509name == NULL) {
jniThrowNullPointerException(env, "x509name == null");
JNI_TRACE("X509_NAME_print_ex(%p, %ld) => x509name == null", x509name, flags);
return NULL;
}
return X509_NAME_to_jstring(env, x509name, flags);
}
template <typename T, T* (*d2i_func)(BIO*, T**)>
static jlong d2i_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return 0;
}
T* x = d2i_func(bio, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "d2i_ASN1Object_to_jlong");
return 0;
}
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_d2i_X509_CRL_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509_CRL, d2i_X509_CRL_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509, d2i_X509_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509(JNIEnv* env, jclass, jbyteArray certBytes) {
X509* x = ByteArrayToASN1<X509, d2i_X509>(env, certBytes);
return reinterpret_cast<uintptr_t>(x);
}
static jbyteArray NativeCrypto_i2d_X509(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509(%p)", x509);
return ASN1ToByteArray<X509>(env, x509, i2d_X509);
}
static jbyteArray NativeCrypto_i2d_X509_PUBKEY(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509_PUBKEY(%p)", x509);
return ASN1ToByteArray<X509_PUBKEY>(env, X509_get_X509_PUBKEY(x509), i2d_X509_PUBKEY);
}
template<typename T, T* (*PEM_read_func)(BIO*, T**, pem_password_cb*, void*)>
static jlong PEM_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => bio == null", bio);
return 0;
}
T* x = PEM_read_func(bio, NULL, NULL, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "PEM_ASN1Object_to_jlong");
// Sometimes the PEM functions fail without pushing an error
if (!env->ExceptionCheck()) {
jniThrowRuntimeException(env, "Failure parsing PEM");
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => threw exception", bio);
return 0;
}
JNI_TRACE("PEM_ASN1Object_to_jlong(%p) => %p", bio, x);
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_PEM_read_bio_X509(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509(0x%llx)", (long long) bioRef);
return PEM_ASN1Object_to_jlong<X509, PEM_read_bio_X509>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_X509_CRL(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509_CRL(0x%llx)", (long long) bioRef);
return PEM_ASN1Object_to_jlong<X509_CRL, PEM_read_bio_X509_CRL>(env, bioRef);
}
template <typename T, typename T_stack>
static jlongArray PKCS7_to_ItemArray(JNIEnv* env, T_stack* stack, T* (*dup_func)(T*))
{
if (stack == NULL) {
return NULL;
}
ScopedLocalRef<jlongArray> ref_array(env, NULL);
size_t size = sk_num(reinterpret_cast<_STACK*>(stack));
ref_array.reset(env->NewLongArray(size));
ScopedLongArrayRW items(env, ref_array.get());
for (size_t i = 0; i < size; i++) {
T* item = reinterpret_cast<T*>(sk_value(reinterpret_cast<_STACK*>(stack), i));
items[i] = reinterpret_cast<uintptr_t>(dup_func(item));
}
JNI_TRACE("PKCS7_to_ItemArray(%p) => %p [size=%d]", stack, ref_array.get(), size);
return ref_array.release();
}
#define PKCS7_CERTS 1
#define PKCS7_CRLS 2
static jbyteArray NativeCrypto_i2d_PKCS7(JNIEnv* env, jclass, jlongArray certsArray) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("i2d_PKCS7(%p)", certsArray);
Unique_PKCS7 pkcs7(PKCS7_new());
if (pkcs7.get() == NULL) {
jniThrowNullPointerException(env, "pkcs7 == null");
JNI_TRACE("i2d_PKCS7(%p) => pkcs7 == null", certsArray);
return NULL;
}
if (PKCS7_set_type(pkcs7.get(), NID_pkcs7_signed) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type");
return NULL;
}
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (PKCS7_add_certificate(pkcs7.get(), item) != 1) {
throwExceptionIfNecessary(env, "i2d_PKCS7");
return NULL;
}
}
JNI_TRACE("i2d_PKCS7(%p) => %zd certs", certsArray, certs.size());
return ASN1ToByteArray<PKCS7>(env, pkcs7.get(), i2d_PKCS7);
#else // OPENSSL_IS_BORINGSSL
STACK_OF(X509) *stack = sk_X509_new_null();
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (sk_X509_push(stack, item) == 0) {
sk_X509_free(stack);
throwExceptionIfNecessary(env, "sk_X509_push");
return NULL;
}
}
CBB out;
CBB_init(&out, 1024 * certs.size());
if (!PKCS7_bundle_certificates(&out, stack)) {
CBB_cleanup(&out);
sk_X509_free(stack);
throwExceptionIfNecessary(env, "PKCS7_bundle_certificates");
return NULL;
}
sk_X509_free(stack);
uint8_t *derBytes;
size_t derLen;
if (!CBB_finish(&out, &derBytes, &derLen)) {
CBB_cleanup(&out);
throwExceptionIfNecessary(env, "CBB_finish");
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("creating byte array failed");
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("using byte array failed");
return NULL;
}
uint8_t* p = reinterpret_cast<unsigned char*>(bytes.get());
memcpy(p, derBytes, derLen);
return byteArray.release();
#endif // OPENSSL_IS_BORINGSSL
}
typedef STACK_OF(X509) PKIPATH;
ASN1_ITEM_TEMPLATE(PKIPATH) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PkiPath, X509)
ASN1_ITEM_TEMPLATE_END(PKIPATH)
static jlongArray NativeCrypto_ASN1_seq_unpack_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p)", bio);
Unique_sk_X509 path((PKIPATH*) ASN1_item_d2i_bio(ASN1_ITEM_rptr(PKIPATH), bio, NULL));
if (path.get() == NULL) {
throwExceptionIfNecessary(env, "ASN1_seq_unpack_X509_bio");
return NULL;
}
size_t size = sk_X509_num(path.get());
ScopedLocalRef<jlongArray> certArray(env, env->NewLongArray(size));
ScopedLongArrayRW certs(env, certArray.get());
for (size_t i = 0; i < size; i++) {
X509* item = reinterpret_cast<X509*>(sk_X509_shift(path.get()));
certs[i] = reinterpret_cast<uintptr_t>(item);
}
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => returns %zd items", bio, size);
return certArray.release();
}
static jbyteArray NativeCrypto_ASN1_seq_pack_X509(JNIEnv* env, jclass, jlongArray certs) {
JNI_TRACE("ASN1_seq_pack_X509(%p)", certs);
ScopedLongArrayRO certsArray(env, certs);
if (certsArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to get certs array", certs);
return NULL;
}
Unique_sk_X509 certStack(sk_X509_new_null());
if (certStack.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to make cert stack", certs);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
sk_X509_push(certStack.get(), X509_dup_nocopy(x509));
}
int len;
Unique_OPENSSL_str encoded(ASN1_seq_pack(
reinterpret_cast<STACK_OF(OPENSSL_BLOCK)*>(
reinterpret_cast<uintptr_t>(certStack.get())),
reinterpret_cast<int (*)(void*, unsigned char**)>(i2d_X509), NULL, &len));
if (encoded.get() == NULL || len < 0) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => trouble encoding", certs);
return NULL;
}
uint8_t *out = encoded.get();
size_t out_len = len;
#else
CBB result, seq_contents;
if (!CBB_init(&result, 2048 * certsArray.size())) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => CBB_init failed", certs);
return NULL;
}
if (!CBB_add_asn1(&result, &seq_contents, CBS_ASN1_SEQUENCE)) {
CBB_cleanup(&result);
return NULL;
}
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
uint8_t *buf;
int len = i2d_X509(x509, NULL);
if (len < 0 ||
!CBB_add_space(&seq_contents, &buf, len) ||
i2d_X509(x509, &buf) < 0) {
CBB_cleanup(&result);
return NULL;
}
}
uint8_t *out;
size_t out_len;
if (!CBB_finish(&result, &out, &out_len)) {
CBB_cleanup(&result);
return NULL;
}
UniquePtr<uint8_t> out_storage(out);
#endif
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(out_len));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => creating byte array failed", certs);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => using byte array failed", certs);
return NULL;
}
uint8_t *p = reinterpret_cast<uint8_t*>(bytes.get());
memcpy(p, out, out_len);
return byteArray.release();
}
static void NativeCrypto_X509_free(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_free(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_free(%p) => x509 == null", x509);
return;
}
X509_free(x509);
}
static jint NativeCrypto_X509_cmp(JNIEnv* env, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_cmp(%p, %p)", x509_1, x509_2);
if (x509_1 == NULL) {
jniThrowNullPointerException(env, "x509_1 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_1 == null", x509_1, x509_2);
return -1;
}
if (x509_2 == NULL) {
jniThrowNullPointerException(env, "x509_2 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_2 == null", x509_1, x509_2);
return -1;
}
int ret = X509_cmp(x509_1, x509_2);
JNI_TRACE("X509_cmp(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static jint NativeCrypto_get_X509_hashCode(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_hashCode(%p) => x509 == null", x509);
return 0;
}
// Force caching extensions.
X509_check_ca(x509);
jint hashCode = 0L;
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
hashCode = 31 * hashCode + x509->sha1_hash[i];
}
return hashCode;
}
static void NativeCrypto_X509_print_ex(JNIEnv* env, jclass, jlong bioRef, jlong x509Ref,
jlong nmflagJava, jlong certflagJava) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
long nmflag = static_cast<long>(nmflagJava);
long certflag = static_cast<long>(certflagJava);
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld)", bio, x509, nmflag, certflag);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => bio == null", bio, x509, nmflag, certflag);
return;
}
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => x509 == null", bio, x509, nmflag, certflag);
return;
}
if (!X509_print_ex(bio, x509, nmflag, certflag)) {
throwExceptionIfNecessary(env, "X509_print_ex");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => threw error", bio, x509, nmflag, certflag);
} else {
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => success", bio, x509, nmflag, certflag);
}
}
static jlong NativeCrypto_X509_get_pubkey(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_pubkey(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_pubkey(%p) => x509 == null", x509);
return 0;
}
Unique_EVP_PKEY pkey(X509_get_pubkey(x509));
if (pkey.get() == NULL) {
#if defined(OPENSSL_IS_BORINGSSL)
const uint32_t last_error = ERR_peek_last_error();
const uint32_t first_error = ERR_peek_error();
if ((ERR_GET_LIB(last_error) == ERR_LIB_EVP &&
ERR_GET_REASON(last_error) == EVP_R_UNKNOWN_PUBLIC_KEY_TYPE) ||
(ERR_GET_LIB(first_error) == ERR_LIB_EC &&
ERR_GET_REASON(first_error) == EC_R_UNKNOWN_GROUP)) {
freeOpenSslErrorState();
throwNoSuchAlgorithmException(env, "X509_get_pubkey");
return 0;
}
#endif
throwExceptionIfNecessary(env, "X509_get_pubkey");
return 0;
}
JNI_TRACE("X509_get_pubkey(%p) => %p", x509, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jbyteArray NativeCrypto_X509_get_issuer_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_issuer_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_issuer_name(x509), i2d_X509_NAME);
}
static jbyteArray NativeCrypto_X509_get_subject_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_subject_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_subject_name(x509), i2d_X509_NAME);
}
static jstring NativeCrypto_get_X509_pubkey_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_pubkey_oid(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_pubkey_oid(%p) => x509 == null", x509);
return NULL;
}
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
return ASN1_OBJECT_to_OID_string(env, pubkey->algor->algorithm);
}
static jstring NativeCrypto_get_X509_sig_alg_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_oid(%p)", x509);
if (x509 == NULL || x509->sig_alg == NULL) {
jniThrowNullPointerException(env, "x509 == NULL || x509->sig_alg == NULL");
JNI_TRACE("get_X509_sig_alg_oid(%p) => x509 == NULL", x509);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, x509->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_sig_alg_parameter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_parameter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_sig_alg_parameter(%p) => x509 == null", x509);
return NULL;
}
if (x509->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_sig_alg_parameter(%p) => null", x509);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, x509->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbooleanArray NativeCrypto_get_X509_issuerUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_issuerUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_issuerUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->issuerUID == NULL) {
JNI_TRACE("get_X509_issuerUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->issuerUID);
}
static jbooleanArray NativeCrypto_get_X509_subjectUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_subjectUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_subjectUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->subjectUID == NULL) {
JNI_TRACE("get_X509_subjectUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->subjectUID);
}
static jbooleanArray NativeCrypto_get_X509_ex_kusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_kusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_kusage(%p) => x509 == null", x509);
return NULL;
}
Unique_ASN1_BIT_STRING bitStr(static_cast<ASN1_BIT_STRING*>(
X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL)));
if (bitStr.get() == NULL) {
JNI_TRACE("get_X509_ex_kusage(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, bitStr.get());
}
static jobjectArray NativeCrypto_get_X509_ex_xkusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_xkusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_xkusage(%p) => x509 == null", x509);
return NULL;
}
Unique_sk_ASN1_OBJECT objArray(static_cast<STACK_OF(ASN1_OBJECT)*>(
X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL)));
if (objArray.get() == NULL) {
JNI_TRACE("get_X509_ex_xkusage(%p) => null", x509);
return NULL;
}
size_t size = sk_ASN1_OBJECT_num(objArray.get());
ScopedLocalRef<jobjectArray> exKeyUsage(env, env->NewObjectArray(size, stringClass, NULL));
if (exKeyUsage.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
ScopedLocalRef<jstring> oidStr(env, ASN1_OBJECT_to_OID_string(env,
sk_ASN1_OBJECT_value(objArray.get(), i)));
env->SetObjectArrayElement(exKeyUsage.get(), i, oidStr.get());
}
JNI_TRACE("get_X509_ex_xkusage(%p) => success (%zd entries)", x509, size);
return exKeyUsage.release();
}
static jint NativeCrypto_get_X509_ex_pathlen(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_pathlen(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_pathlen(%p) => x509 == null", x509);
return 0;
}
/* Just need to do this to cache the ex_* values. */
X509_check_ca(x509);
JNI_TRACE("get_X509_ex_pathlen(%p) => %ld", x509, x509->ex_pathlen);
return x509->ex_pathlen;
}
static jbyteArray NativeCrypto_X509_get_ext_oid(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_ext_oid(%p, %p)", x509, oidString);
return X509Type_get_ext_oid<X509, X509_get_ext_by_OBJ, X509_get_ext>(env, x509, oidString);
}
static jbyteArray NativeCrypto_X509_CRL_get_ext_oid(JNIEnv* env, jclass, jlong x509CrlRef,
jstring oidString) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext_oid(%p, %p)", crl, oidString);
return X509Type_get_ext_oid<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(env, crl,
oidString);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_ext_oid(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oidString) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext_oid(%p, %p)", revoked, oidString);
return X509Type_get_ext_oid<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ, X509_REVOKED_get_ext>(
env, revoked, oidString);
}
template<typename T, int (*get_ext_by_critical_func)(T*, int, int), X509_EXTENSION* (*get_ext_func)(T*, int)>
static jobjectArray get_X509Type_ext_oids(JNIEnv* env, jlong x509Ref, jint critical) {
T* x509 = reinterpret_cast<T*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509Type_ext_oids(%p, %d)", x509, critical);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => x509 == null", x509, critical);
return NULL;
}
int lastPos = -1;
int count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
count++;
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) has %d entries", x509, critical, count);
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, stringClass, NULL));
if (joa.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => fail to allocate result array", x509, critical);
return NULL;
}
lastPos = -1;
count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
X509_EXTENSION* ext = get_ext_func(x509, lastPos);
ScopedLocalRef<jstring> extOid(env, ASN1_OBJECT_to_OID_string(env, ext->object));
if (extOid.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p) => couldn't get OID", x509);
return NULL;
}
env->SetObjectArrayElement(joa.get(), count++, extOid.get());
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => success", x509, critical);
return joa.release();
}
static jobjectArray NativeCrypto_get_X509_ext_oids(JNIEnv* env, jclass, jlong x509Ref,
jint critical) {
JNI_TRACE("get_X509_ext_oids(0x%llx, %d)", (long long) x509Ref, critical);
return get_X509Type_ext_oids<X509, X509_get_ext_by_critical, X509_get_ext>(env, x509Ref,
critical);
}
static jobjectArray NativeCrypto_get_X509_CRL_ext_oids(JNIEnv* env, jclass, jlong x509CrlRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509CrlRef, critical);
return get_X509Type_ext_oids<X509_CRL, X509_CRL_get_ext_by_critical, X509_CRL_get_ext>(env,
x509CrlRef, critical);
}
static jobjectArray NativeCrypto_get_X509_REVOKED_ext_oids(JNIEnv* env, jclass, jlong x509RevokedRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509RevokedRef, critical);
return get_X509Type_ext_oids<X509_REVOKED, X509_REVOKED_get_ext_by_critical,
X509_REVOKED_get_ext>(env, x509RevokedRef, critical);
}
#ifdef WITH_JNI_TRACE
/**
* Based on example logging call back from SSL_CTX_set_info_callback man page
*/
static void info_callback_LOG(const SSL* s __attribute__ ((unused)), int where, int ret)
{
int w = where & ~SSL_ST_MASK;
const char* str;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
} else {
str = "undefined";
}
if (where & SSL_CB_LOOP) {
JNI_TRACE("ssl=%p %s:%s %s", s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
JNI_TRACE("ssl=%p SSL3 alert %s:%s:%s %s %s",
s,
str,
SSL_alert_type_string(ret),
SSL_alert_desc_string(ret),
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
JNI_TRACE("ssl=%p %s:failed exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret < 0) {
JNI_TRACE("ssl=%p %s:error exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret == 1) {
JNI_TRACE("ssl=%p %s:ok exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown exit %d in %s %s",
s, str, ret, SSL_state_string(s), SSL_state_string_long(s));
}
} else if (where & SSL_CB_HANDSHAKE_START) {
JNI_TRACE("ssl=%p handshake start in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_HANDSHAKE_DONE) {
JNI_TRACE("ssl=%p handshake done in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown where %d in %s %s",
s, str, where, SSL_state_string(s), SSL_state_string_long(s));
}
}
#endif
/**
* Returns an array containing all the X509 certificate references
*/
static jlongArray getCertificateRefs(JNIEnv* env, const STACK_OF(X509)* chain)
{
if (chain == NULL) {
// Chain can be NULL if the associated cipher doesn't do certs.
return NULL;
}
ssize_t count = sk_X509_num(chain);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jlongArray> refArray(env, env->NewLongArray(count));
ScopedLongArrayRW refs(env, refArray.get());
if (refs.get() == NULL) {
return NULL;
}
for (ssize_t i = 0; i < count; i++) {
refs[i] = reinterpret_cast<uintptr_t>(X509_dup_nocopy(sk_X509_value(chain, i)));
}
return refArray.release();
}
/**
* Returns an array containing all the X500 principal's bytes.
*/
static jobjectArray getPrincipalBytes(JNIEnv* env, const STACK_OF(X509_NAME)* names)
{
if (names == NULL) {
return NULL;
}
int count = sk_X509_NAME_num(names);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, byteArrayClass, NULL));
if (joa.get() == NULL) {
return NULL;
}
for (int i = 0; i < count; i++) {
X509_NAME* principal = sk_X509_NAME_value(names, i);
ScopedLocalRef<jbyteArray> byteArray(env, ASN1ToByteArray<X509_NAME>(env,
principal, i2d_X509_NAME));
if (byteArray.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(joa.get(), i, byteArray.get());
}
return joa.release();
}
/**
* Our additional application data needed for getting synchronization right.
* This maybe warrants a bit of lengthy prose:
*
* (1) We use a flag to reflect whether we consider the SSL connection alive.
* Any read or write attempt loops will be cancelled once this flag becomes 0.
*
* (2) We use an int to count the number of threads that are blocked by the
* underlying socket. This may be at most two (one reader and one writer), since
* the Java layer ensures that no more threads will enter the native code at the
* same time.
*
* (3) The pipe is used primarily as a means of cancelling a blocking select()
* when we want to close the connection (aka "emergency button"). It is also
* necessary for dealing with a possible race condition situation: There might
* be cases where both threads see an SSL_ERROR_WANT_READ or
* SSL_ERROR_WANT_WRITE. Both will enter a select() with the proper argument.
* If one leaves the select() successfully before the other enters it, the
* "success" event is already consumed and the second thread will be blocked,
* possibly forever (depending on network conditions).
*
* The idea for solving the problem looks like this: Whenever a thread is
* successful in moving around data on the network, and it knows there is
* another thread stuck in a select(), it will write a byte to the pipe, waking
* up the other thread. A thread that returned from select(), on the other hand,
* knows whether it's been woken up by the pipe. If so, it will consume the
* byte, and the original state of affairs has been restored.
*
* The pipe may seem like a bit of overhead, but it fits in nicely with the
* other file descriptors of the select(), so there's only one condition to wait
* for.
*
* (4) Finally, a mutex is needed to make sure that at most one thread is in
* either SSL_read() or SSL_write() at any given time. This is an OpenSSL
* requirement. We use the same mutex to guard the field for counting the
* waiting threads.
*
* Note: The current implementation assumes that we don't have to deal with
* problems induced by multiple cores or processors and their respective
* memory caches. One possible problem is that of inconsistent views on the
* "aliveAndKicking" field. This could be worked around by also enclosing all
* accesses to that field inside a lock/unlock sequence of our mutex, but
* currently this seems a bit like overkill. Marking volatile at the very least.
*
* During handshaking, additional fields are used to up-call into
* Java to perform certificate verification and handshake
* completion. These are also used in any renegotiation.
*
* (5) the JNIEnv so we can invoke the Java callback
*
* (6) a NativeCrypto.SSLHandshakeCallbacks instance for callbacks from native to Java
*
* (7) a java.io.FileDescriptor wrapper to check for socket close
*
* We store the NPN protocols list so we can either send it (from the server) or
* select a protocol (on the client). We eagerly acquire a pointer to the array
* data so the callback doesn't need to acquire resources that it cannot
* release.
*
* Because renegotiation can be requested by the peer at any time,
* care should be taken to maintain an appropriate JNIEnv on any
* downcall to openssl since it could result in an upcall to Java. The
* current code does try to cover these cases by conditionally setting
* the JNIEnv on calls that can read and write to the SSL such as
* SSL_do_handshake, SSL_read, SSL_write, and SSL_shutdown.
*
* Finally, we have two emphemeral keys setup by OpenSSL callbacks:
*
* (8) a set of ephemeral RSA keys that is lazily generated if a peer
* wants to use an exportable RSA cipher suite.
*
* (9) a set of ephemeral EC keys that is lazily generated if a peer
* wants to use an TLS_ECDHE_* cipher suite.
*
*/
class AppData {
public:
volatile int aliveAndKicking;
int waitingThreads;
int fdsEmergency[2];
MUTEX_TYPE mutex;
JNIEnv* env;
jobject sslHandshakeCallbacks;
jbyteArray npnProtocolsArray;
jbyte* npnProtocolsData;
size_t npnProtocolsLength;
jbyteArray alpnProtocolsArray;
jbyte* alpnProtocolsData;
size_t alpnProtocolsLength;
Unique_RSA ephemeralRsa;
Unique_EC_KEY ephemeralEc;
/**
* Creates the application data context for the SSL*.
*/
public:
static AppData* create() {
UniquePtr<AppData> appData(new AppData());
if (pipe(appData.get()->fdsEmergency) == -1) {
ALOGE("AppData::create pipe(2) failed: %s", strerror(errno));
return NULL;
}
if (!setBlocking(appData.get()->fdsEmergency[0], false)) {
ALOGE("AppData::create fcntl(2) failed: %s", strerror(errno));
return NULL;
}
if (MUTEX_SETUP(appData.get()->mutex) == -1) {
ALOGE("pthread_mutex_init(3) failed: %s", strerror(errno));
return NULL;
}
return appData.release();
}
~AppData() {
aliveAndKicking = 0;
if (fdsEmergency[0] != -1) {
close(fdsEmergency[0]);
}
if (fdsEmergency[1] != -1) {
close(fdsEmergency[1]);
}
clearCallbackState();
MUTEX_CLEANUP(mutex);
}
private:
AppData() :
aliveAndKicking(1),
waitingThreads(0),
env(NULL),
sslHandshakeCallbacks(NULL),
npnProtocolsArray(NULL),
npnProtocolsData(NULL),
npnProtocolsLength(-1),
alpnProtocolsArray(NULL),
alpnProtocolsData(NULL),
alpnProtocolsLength(-1),
ephemeralRsa(NULL),
ephemeralEc(NULL) {
fdsEmergency[0] = -1;
fdsEmergency[1] = -1;
}
public:
/**
* Used to set the SSL-to-Java callback state before each SSL_*
* call that may result in a callback. It should be cleared after
* the operation returns with clearCallbackState.
*
* @param env The JNIEnv
* @param shc The SSLHandshakeCallbacks
* @param fd The FileDescriptor
* @param npnProtocols NPN protocols so that they may be advertised (by the
* server) or selected (by the client). Has no effect
* unless NPN is enabled.
* @param alpnProtocols ALPN protocols so that they may be advertised (by the
* server) or selected (by the client). Passing non-NULL
* enables ALPN.
*/
bool setCallbackState(JNIEnv* e, jobject shc, jobject fd, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
UniquePtr<NetFd> netFd;
if (fd != NULL) {
netFd.reset(new NetFd(e, fd));
if (netFd->isClosed()) {
JNI_TRACE("appData=%p setCallbackState => netFd->isClosed() == true", this);
return false;
}
}
env = e;
sslHandshakeCallbacks = shc;
if (npnProtocols != NULL) {
npnProtocolsData = e->GetByteArrayElements(npnProtocols, NULL);
if (npnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => npnProtocolsData == NULL", this);
return false;
}
npnProtocolsArray = npnProtocols;
npnProtocolsLength = e->GetArrayLength(npnProtocols);
}
if (alpnProtocols != NULL) {
alpnProtocolsData = e->GetByteArrayElements(alpnProtocols, NULL);
if (alpnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => alpnProtocolsData == NULL", this);
return false;
}
alpnProtocolsArray = alpnProtocols;
alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
}
return true;
}
void clearCallbackState() {
sslHandshakeCallbacks = NULL;
if (npnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(npnProtocolsArray, npnProtocolsData, JNI_ABORT);
npnProtocolsArray = NULL;
npnProtocolsData = NULL;
npnProtocolsLength = -1;
}
if (alpnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(alpnProtocolsArray, alpnProtocolsData, JNI_ABORT);
alpnProtocolsArray = NULL;
alpnProtocolsData = NULL;
alpnProtocolsLength = -1;
}
env = NULL;
}
};
/**
* Dark magic helper function that checks, for a given SSL session, whether it
* can SSL_read() or SSL_write() without blocking. Takes into account any
* concurrent attempts to close the SSLSocket from the Java side. This is
* needed to get rid of the hangs that occur when thread #1 closes the SSLSocket
* while thread #2 is sitting in a blocking read or write. The type argument
* specifies whether we are waiting for readability or writability. It expects
* to be passed either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, since we
* only need to wait in case one of these problems occurs.
*
* @param env
* @param type Either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
* @param fdObject The FileDescriptor, since appData->fileDescriptor should be NULL
* @param appData The application data structure with mutex info etc.
* @param timeout_millis The timeout value for select call, with the special value
* 0 meaning no timeout at all (wait indefinitely). Note: This is
* the Java semantics of the timeout value, not the usual
* select() semantics.
* @return The result of the inner select() call,
* THROW_SOCKETEXCEPTION if a SocketException was thrown, -1 on
* additional errors
*/
static int sslSelect(JNIEnv* env, int type, jobject fdObject, AppData* appData, int timeout_millis) {
// This loop is an expanded version of the NET_FAILURE_RETRY
// macro. It cannot simply be used in this case because select
// cannot be restarted without recreating the fd_sets and timeout
// structure.
int result;
fd_set rfds;
fd_set wfds;
do {
NetFd fd(env, fdObject);
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
int intFd = fd.get();
JNI_TRACE("sslSelect type=%s fd=%d appData=%p timeout_millis=%d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE", intFd, appData, timeout_millis);
FD_ZERO(&rfds);
FD_ZERO(&wfds);
if (type == SSL_ERROR_WANT_READ) {
FD_SET(intFd, &rfds);
} else {
FD_SET(intFd, &wfds);
}
FD_SET(appData->fdsEmergency[0], &rfds);
int maxFd = (intFd > appData->fdsEmergency[0]) ? intFd : appData->fdsEmergency[0];
// Build a struct for the timeout data if we actually want a timeout.
timeval tv;
timeval* ptv;
if (timeout_millis > 0) {
tv.tv_sec = timeout_millis / 1000;
tv.tv_usec = (timeout_millis % 1000) * 1000;
ptv = &tv;
} else {
ptv = NULL;
}
#ifndef CONSCRYPT_UNBUNDLED
AsynchronousCloseMonitor monitor(intFd);
#else
CompatibilityCloseMonitor monitor(intFd);
#endif
result = select(maxFd + 1, &rfds, &wfds, NULL, ptv);
JNI_TRACE("sslSelect %s fd=%d appData=%p timeout_millis=%d => %d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE",
fd.get(), appData, timeout_millis, result);
if (result == -1) {
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
if (errno != EINTR) {
break;
}
}
} while (result == -1);
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (result > 0) {
// We have been woken up by a token in the emergency pipe. We
// can't be sure the token is still in the pipe at this point
// because it could have already been read by the thread that
// originally wrote it if it entered sslSelect and acquired
// the mutex before we did. Thus we cannot safely read from
// the pipe in a blocking way (so we make the pipe
// non-blocking at creation).
if (FD_ISSET(appData->fdsEmergency[0], &rfds)) {
char token;
do {
read(appData->fdsEmergency[0], &token, 1);
} while (errno == EINTR);
}
}
// Tell the world that there is now one thread less waiting for the
// underlying network.
appData->waitingThreads--;
MUTEX_UNLOCK(appData->mutex);
return result;
}
/**
* Helper function that wakes up a thread blocked in select(), in case there is
* one. Is being called by sslRead() and sslWrite() as well as by JNI glue
* before closing the connection.
*
* @param data The application data structure with mutex info etc.
*/
static void sslNotify(AppData* appData) {
// Write a byte to the emergency pipe, so a concurrent select() can return.
// Note we have to restore the errno of the original system call, since the
// caller relies on it for generating error messages.
int errnoBackup = errno;
char token = '*';
do {
errno = 0;
write(appData->fdsEmergency[1], &token, 1);
} while (errno == EINTR);
errno = errnoBackup;
}
static AppData* toAppData(const SSL* ssl) {
return reinterpret_cast<AppData*>(SSL_get_app_data(ssl));
}
/**
* Verify the X509 certificate via SSL_CTX_set_cert_verify_callback
*/
static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg __attribute__ ((unused)))
{
/* Get the correct index to the SSLobject stored into X509_STORE_CTX. */
SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_store_ctx,
SSL_get_ex_data_X509_STORE_CTX_idx()));
JNI_TRACE("ssl=%p cert_verify_callback x509_store_ctx=%p arg=%p", ssl, x509_store_ctx, arg);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in cert_verify_callback");
JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "verifyCertificateChain", "(J[JLjava/lang/String;)V");
jlongArray refArray = getCertificateRefs(env, x509_store_ctx->untrusted);
#if !defined(OPENSSL_IS_BORINGSSL)
const char* authMethod = SSL_authentication_method(ssl);
#else
const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
const char *authMethod = SSL_CIPHER_get_kx_name(cipher);
#endif
JNI_TRACE("ssl=%p cert_verify_callback calling verifyCertificateChain authMethod=%s",
ssl, authMethod);
jstring authMethodString = env->NewStringUTF(authMethod);
env->CallVoidMethod(sslHandshakeCallbacks, methodID,
static_cast<jlong>(reinterpret_cast<uintptr_t>(SSL_get1_session(ssl))), refArray,
authMethodString);
int result = (env->ExceptionCheck()) ? 0 : 1;
JNI_TRACE("ssl=%p cert_verify_callback => %d", ssl, result);
return result;
}
/**
* Call back to watch for handshake to be completed. This is necessary
* for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake
* returns before the handshake is completed in this case.
*/
static void info_callback(const SSL* ssl, int where, int ret) {
JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret);
#ifdef WITH_JNI_TRACE
info_callback_LOG(ssl, where, ret);
#endif
if (!(where & SSL_CB_HANDSHAKE_DONE) && !(where & SSL_CB_HANDSHAKE_START)) {
JNI_TRACE("ssl=%p info_callback ignored", ssl);
return;
}
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in info_callback");
JNI_TRACE("ssl=%p info_callback env error", ssl);
return;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback already pending exception", ssl);
return;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(cls, "onSSLStateChange", "(JII)V");
JNI_TRACE("ssl=%p info_callback calling onSSLStateChange", ssl);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, reinterpret_cast<jlong>(ssl), where, ret);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback exception", ssl);
}
JNI_TRACE("ssl=%p info_callback completed", ssl);
}
/**
* Call back to ask for a client certificate. There are three possible exit codes:
*
* 1 is success. x509Out and pkeyOut should point to the correct private key and certificate.
* 0 is unable to find key. x509Out and pkeyOut should be NULL.
* -1 is error and it doesn't matter what x509Out and pkeyOut are.
*/
static int client_cert_cb(SSL* ssl, X509** x509Out, EVP_PKEY** pkeyOut) {
JNI_TRACE("ssl=%p client_cert_cb x509Out=%p pkeyOut=%p", ssl, x509Out, pkeyOut);
/* Clear output of key and certificate in case of early exit due to error. */
*x509Out = NULL;
*pkeyOut = NULL;
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in client_cert_cb");
JNI_TRACE("ssl=%p client_cert_cb env error => 0", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb already pending exception => 0", ssl);
return -1;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "clientCertificateRequested", "([B[[B)V");
// Call Java callback which can use SSL_use_certificate and SSL_use_PrivateKey to set values
char ssl2_ctype = SSL3_CT_RSA_SIGN;
const char* ctype = NULL;
#if !defined(OPENSSL_IS_BORINGSSL)
int ctype_num = 0;
jobjectArray issuers = NULL;
switch (ssl->version) {
case SSL2_VERSION:
ctype = &ssl2_ctype;
ctype_num = 1;
break;
case SSL3_VERSION:
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
case DTLS1_VERSION:
ctype = ssl->s3->tmp.ctype;
ctype_num = ssl->s3->tmp.ctype_num;
issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
break;
}
#else
int ctype_num = SSL_get0_certificate_types(ssl, &ctype);
jobjectArray issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
#endif
#ifdef WITH_JNI_TRACE
for (int i = 0; i < ctype_num; i++) {
JNI_TRACE("ssl=%p clientCertificateRequested keyTypes[%d]=%d", ssl, i, ctype[i]);
}
#endif
jbyteArray keyTypes = env->NewByteArray(ctype_num);
if (keyTypes == NULL) {
JNI_TRACE("ssl=%p client_cert_cb bytes == null => 0", ssl);
return 0;
}
env->SetByteArrayRegion(keyTypes, 0, ctype_num, reinterpret_cast<const jbyte*>(ctype));
JNI_TRACE("ssl=%p clientCertificateRequested calling clientCertificateRequested "
"keyTypes=%p issuers=%p", ssl, keyTypes, issuers);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, keyTypes, issuers);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb exception => 0", ssl);
return -1;
}
// Check for values set from Java
X509* certificate = SSL_get_certificate(ssl);
EVP_PKEY* privatekey = SSL_get_privatekey(ssl);
int result = 0;
if (certificate != NULL && privatekey != NULL) {
*x509Out = certificate;
*pkeyOut = privatekey;
result = 1;
} else {
// Some error conditions return NULL, so make sure it doesn't linger.
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p client_cert_cb => *x509=%p *pkey=%p %d", ssl, *x509Out, *pkeyOut, result);
return result;
}
/**
* Pre-Shared Key (PSK) client callback.
*/
static unsigned int psk_client_callback(SSL* ssl, const char *hint,
char *identity, unsigned int max_identity_len,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_client_callback");
JNI_TRACE("ssl=%p psk_client_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID =
env->GetMethodID(cls, "clientPSKKeyRequested", "(Ljava/lang/String;[B[B)I");
JNI_TRACE("ssl=%p psk_client_callback calling clientPSKKeyRequested", ssl);
ScopedLocalRef<jstring> identityHintJava(
env,
(hint != NULL) ? env->NewStringUTF(hint) : NULL);
ScopedLocalRef<jbyteArray> identityJava(env, env->NewByteArray(max_identity_len));
if (identityJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate identity bufffer", ssl);
return 0;
}
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
ScopedByteArrayRO identityJavaRo(env, identityJava.get());
if (identityJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get identity bytes", ssl);
return 0;
}
memcpy(identity, identityJavaRo.get(), max_identity_len);
JNI_TRACE("ssl=%p psk_client_callback completed", ssl);
return keyLen;
}
/**
* Pre-Shared Key (PSK) server callback.
*/
static unsigned int psk_server_callback(SSL* ssl, const char *identity,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_server_callback");
JNI_TRACE("ssl=%p psk_server_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(
cls, "serverPSKKeyRequested", "(Ljava/lang/String;Ljava/lang/String;[B)I");
JNI_TRACE("ssl=%p psk_server_callback calling serverPSKKeyRequested", ssl);
const char* identityHint = SSL_get_psk_identity_hint(ssl);
// identityHint = NULL;
// identity = NULL;
ScopedLocalRef<jstring> identityHintJava(
env,
(identityHint != NULL) ? env->NewStringUTF(identityHint) : NULL);
ScopedLocalRef<jstring> identityJava(
env,
(identity != NULL) ? env->NewStringUTF(identity) : NULL);
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
JNI_TRACE("ssl=%p psk_server_callback completed", ssl);
return keyLen;
}
static RSA* rsaGenerateKey(int keylength) {
Unique_BIGNUM bn(BN_new());
if (bn.get() == NULL) {
return NULL;
}
int setWordResult = BN_set_word(bn.get(), RSA_F4);
if (setWordResult != 1) {
return NULL;
}
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
return NULL;
}
int generateResult = RSA_generate_key_ex(rsa.get(), keylength, bn.get(), NULL);
if (generateResult != 1) {
return NULL;
}
return rsa.release();
}
/**
* Call back to ask for an ephemeral RSA key for SSL_RSA_EXPORT_WITH_RC4_40_MD5 (aka EXP-RC4-MD5)
*/
static RSA* tmp_rsa_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_rsa_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralRsa.get() == NULL) {
JNI_TRACE("ssl=%p tmp_rsa_callback generating ephemeral RSA key", ssl);
appData->ephemeralRsa.reset(rsaGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_rsa_callback => %p", ssl, appData->ephemeralRsa.get());
return appData->ephemeralRsa.get();
}
static DH* dhGenerateParameters(int keylength) {
#if !defined(OPENSSL_IS_BORINGSSL)
/*
* The SSL_CTX_set_tmp_dh_callback(3SSL) man page discusses two
* different options for generating DH keys. One is generating the
* keys using a single set of DH parameters. However, generating
* DH parameters is slow enough (minutes) that they suggest doing
* it once at install time. The other is to generate DH keys from
* DSA parameters. Generating DSA parameters is faster than DH
* parameters, but to prevent small subgroup attacks, they needed
* to be regenerated for each set of DH keys. Setting the
* SSL_OP_SINGLE_DH_USE option make sure OpenSSL will call back
* for new DH parameters every type it needs to generate DH keys.
*/
// Fast path but must have SSL_OP_SINGLE_DH_USE set
Unique_DSA dsa(DSA_new());
if (!DSA_generate_parameters_ex(dsa.get(), keylength, NULL, 0, NULL, NULL, NULL)) {
return NULL;
}
DH* dh = DSA_dup_DH(dsa.get());
return dh;
#else
/* At the time of writing, OpenSSL and BoringSSL are hard coded to request
* a 1024-bit DH. */
if (keylength <= 1024) {
return DH_get_1024_160(NULL);
}
if (keylength <= 2048) {
return DH_get_2048_224(NULL);
}
/* In the case of a large request, return the strongest DH group that
* we have predefined. Generating a group takes far too long to be
* reasonable. */
return DH_get_2048_256(NULL);
#endif
}
/**
* Call back to ask for Diffie-Hellman parameters
*/
static DH* tmp_dh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_dh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
DH* tmp_dh = dhGenerateParameters(keylength);
JNI_TRACE("ssl=%p tmp_dh_callback => %p", ssl, tmp_dh);
return tmp_dh;
}
static EC_KEY* ecGenerateKey(int keylength __attribute__ ((unused))) {
// TODO selected curve based on keylength
Unique_EC_KEY ec(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (ec.get() == NULL) {
return NULL;
}
return ec.release();
}
/**
* Call back to ask for an ephemeral EC key for TLS_ECDHE_* cipher suites
*/
static EC_KEY* tmp_ecdh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_ecdh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralEc.get() == NULL) {
JNI_TRACE("ssl=%p tmp_ecdh_callback generating ephemeral EC key", ssl);
appData->ephemeralEc.reset(ecGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_ecdh_callback => %p", ssl, appData->ephemeralEc.get());
return appData->ephemeralEc.get();
}
/*
* public static native int SSL_CTX_new();
*/
static jlong NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass) {
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
if (sslCtx.get() == NULL) {
throwExceptionIfNecessary(env, "SSL_CTX_new");
return 0;
}
SSL_CTX_set_options(sslCtx.get(),
SSL_OP_ALL
// Note: We explicitly do not allow SSLv2 to be used.
| SSL_OP_NO_SSLv2
// We also disable session tickets for better compatibility b/2682876
| SSL_OP_NO_TICKET
// We also disable compression for better compatibility b/2710492 b/2710497
| SSL_OP_NO_COMPRESSION
// Because dhGenerateParameters uses DSA_generate_parameters_ex
| SSL_OP_SINGLE_DH_USE
// Because ecGenerateParameters uses a fixed named curve
| SSL_OP_SINGLE_ECDH_USE);
int mode = SSL_CTX_get_mode(sslCtx.get());
/*
* Turn on "partial write" mode. This means that SSL_write() will
* behave like Posix write() and possibly return after only
* writing a partial buffer. Note: The alternative, perhaps
* surprisingly, is not that SSL_write() always does full writes
* but that it will force you to retry write calls having
* preserved the full state of the original call. (This is icky
* and undesirable.)
*/
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
// Reuse empty buffers within the SSL_CTX to save memory
mode |= SSL_MODE_RELEASE_BUFFERS;
SSL_CTX_set_mode(sslCtx.get(), mode);
SSL_CTX_set_cert_verify_callback(sslCtx.get(), cert_verify_callback, NULL);
SSL_CTX_set_info_callback(sslCtx.get(), info_callback);
SSL_CTX_set_client_cert_cb(sslCtx.get(), client_cert_cb);
SSL_CTX_set_tmp_rsa_callback(sslCtx.get(), tmp_rsa_callback);
SSL_CTX_set_tmp_dh_callback(sslCtx.get(), tmp_dh_callback);
SSL_CTX_set_tmp_ecdh_callback(sslCtx.get(), tmp_ecdh_callback);
// When TLS Channel ID extension is used, use the new version of it.
sslCtx.get()->tlsext_channel_id_enabled_new = 1;
JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx.get());
return (jlong) sslCtx.release();
}
/**
* public static native void SSL_CTX_free(long ssl_ctx)
*/
static void NativeCrypto_SSL_CTX_free(JNIEnv* env,
jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_free(ssl_ctx);
}
static void NativeCrypto_SSL_CTX_set_session_id_context(JNIEnv* env, jclass,
jlong ssl_ctx_address, jbyteArray sid_ctx)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context sid_ctx=%p", ssl_ctx, sid_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO buf(env, sid_ctx);
if (buf.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => threw exception", ssl_ctx);
return;
}
unsigned int length = buf.size();
if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"length > SSL_MAX_SSL_SESSION_ID_LENGTH");
JNI_TRACE("NativeCrypto_SSL_CTX_set_session_id_context => length = %d", length);
return;
}
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buf.get());
int result = SSL_CTX_set_session_id_context(ssl_ctx, bytes, length);
if (result == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_SSL_CTX_set_session_id_context");
return;
}
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => ok", ssl_ctx);
}
/**
* public static native int SSL_new(long ssl_ctx) throws SSLException;
*/
static jlong NativeCrypto_SSL_new(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new", ssl_ctx);
if (ssl_ctx == NULL) {
return 0;
}
Unique_SSL ssl(SSL_new(ssl_ctx));
if (ssl.get() == NULL) {
throwSSLExceptionWithSslErrors(env, NULL, SSL_ERROR_NONE,
"Unable to create SSL structure");
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
return 0;
}
/*
* Create our special application data.
*/
AppData* appData = AppData::create();
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to create application data");
freeOpenSslErrorState();
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new appData => 0", ssl_ctx);
return 0;
}
SSL_set_app_data(ssl.get(), reinterpret_cast<char*>(appData));
/*
* Java code in class OpenSSLSocketImpl does the verification. Since
* the callbacks do all the verification of the chain, this flag
* simply controls whether to send protocol-level alerts or not.
* SSL_VERIFY_NONE means don't send alerts and anything else means send
* alerts.
*/
SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => ssl=%p appData=%p", ssl_ctx, ssl.get(), appData);
return (jlong) ssl.release();
}
static void NativeCrypto_SSL_enable_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_enable_tls_channel_id", ssl);
if (ssl == NULL) {
return;
}
long ret = SSL_enable_tls_channel_id(ssl);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error enabling Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_tls_channel_id => error", ssl);
return;
}
}
static jbyteArray NativeCrypto_SSL_get_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id", ssl);
if (ssl == NULL) {
return NULL;
}
// Channel ID is 64 bytes long. Unfortunately, OpenSSL doesn't declare this length
// as a constant anywhere.
jbyteArray javaBytes = env->NewByteArray(64);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => NULL", ssl);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
// Unfortunately, the SSL_get_tls_channel_id method below always returns 64 (upon success)
// regardless of the number of bytes copied into the output buffer "tmp". Thus, the correctness
// of this code currently relies on the "tmp" buffer being exactly 64 bytes long.
long ret = SSL_get_tls_channel_id(ssl, tmp, 64);
if (ret == 0) {
// Channel ID either not set or did not verify
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => not available", ssl);
return NULL;
} else if (ret != 64) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error getting Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_tls_channel_id => error, returned %ld", ssl, ret);
return NULL;
}
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id() => %p", ssl, javaBytes);
return javaBytes;
}
static void NativeCrypto_SSL_set1_tls_channel_id(JNIEnv* env, jclass,
jlong ssl_address, jobject pkeyRef)
{
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => pkey == null", ssl);
return;
}
// SSL_set1_tls_channel_id requires ssl->server to be set to 0.
// Unfortunately, the default value is 1 and it's only changed to 0 just
// before the handshake starts (see NativeCrypto_SSL_do_handshake).
ssl->server = 0;
long ret = SSL_set1_tls_channel_id(ssl, pkey);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(
env, ssl, SSL_ERROR_NONE, "Error setting private key for Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => error", ssl);
return;
}
// SSL_set1_tls_channel_id expects to take ownership of the EVP_PKEY, but
// we have an external reference from the caller such as an OpenSSLKey,
// so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => ok", ssl);
}
static void NativeCrypto_SSL_use_PrivateKey(JNIEnv* env, jclass, jlong ssl_address,
jobject pkeyRef) {
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_use_PrivateKey privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
jniThrowNullPointerException(env, "pkey == null");
JNI_TRACE("ssl=%p SSL_use_PrivateKey => pkey == null", ssl);
return;
}
int ret = SSL_use_PrivateKey(ssl, pkey);
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting private key");
safeSslClear(ssl);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => error", ssl);
return;
}
// SSL_use_PrivateKey expects to take ownership of the EVP_PKEY,
// but we have an external reference from the caller such as an
// OpenSSLKey, so we manually increment the reference count here.
CRYPTO_add(&pkey->references,+1,CRYPTO_LOCK_EVP_PKEY);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => ok", ssl);
}
static void NativeCrypto_SSL_use_certificate(JNIEnv* env, jclass,
jlong ssl_address, jlongArray certificatesJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate certificates=%p", ssl, certificatesJava);
if (ssl == NULL) {
return;
}
if (certificatesJava == NULL) {
jniThrowNullPointerException(env, "certificates == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
size_t length = env->GetArrayLength(certificatesJava);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "certificates.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates.length == 0", ssl);
return;
}
ScopedLongArrayRO certificates(env, certificatesJava);
if (certificates.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
Unique_X509 serverCert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[0]))));
if (serverCert.get() == NULL) {
// Note this shouldn't happen since we checked the number of certificates above.
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
int ret = SSL_use_certificate(ssl, serverCert.get());
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(serverCert);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !sk_X509_push(chain.get(), cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
int chainResult = SSL_use_certificate_chain(ssl, chain.get());
if (chainResult == 0) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate_chain error",
ssl);
return;
}
OWNERSHIP_TRANSFERRED(chain);
#else
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !SSL_add0_chain_cert(ssl, cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
#endif
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => ok", ssl);
}
static void NativeCrypto_SSL_check_private_key(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key", ssl);
if (ssl == NULL) {
return;
}
int ret = SSL_check_private_key(ssl);
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error checking private key");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => ok", ssl);
}
static void NativeCrypto_SSL_set_client_CA_list(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray principals)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list principals=%p", ssl, principals);
if (ssl == NULL) {
return;
}
if (principals == NULL) {
jniThrowNullPointerException(env, "principals == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals == null", ssl);
return;
}
int length = env->GetArrayLength(principals);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "principals.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals.length == 0", ssl);
return;
}
Unique_sk_X509_NAME principalsStack(sk_X509_NAME_new_null());
if (principalsStack.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate principal stack");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => stack allocation error", ssl);
return;
}
for (int i = 0; i < length; i++) {
ScopedLocalRef<jbyteArray> principal(env,
reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(principals, i)));
if (principal.get() == NULL) {
jniThrowNullPointerException(env, "principals element == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals element null", ssl);
return;
}
ScopedByteArrayRO buf(env, principal.get());
if (buf.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => threw exception", ssl);
return;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(buf.get());
Unique_X509_NAME principalX509Name(d2i_X509_NAME(NULL, &tmp, buf.size()));
if (principalX509Name.get() == NULL) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing principal");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals parsing error",
ssl);
return;
}
if (!sk_X509_NAME_push(principalsStack.get(), principalX509Name.release())) {
jniThrowOutOfMemory(env, "Unable to push principal");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principal push error", ssl);
return;
}
}
SSL_set_client_CA_list(ssl, principalsStack.release());
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => ok", ssl);
}
/**
* public static native long SSL_get_mode(long ssl);
*/
static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl);
if (ssl == NULL) {
return 0;
}
long mode = SSL_get_mode(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0x%lx", ssl, mode);
return mode;
}
/**
* public static native long SSL_set_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_get_options(long ssl);
*/
static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl);
if (ssl == NULL) {
return 0;
}
long options = SSL_get_options(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0x%lx", ssl, options);
return options;
}
/**
* public static native long SSL_set_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options => 0x%lx", ssl, result);
return result;
}
static void NativeCrypto_SSL_use_psk_identity_hint(JNIEnv* env, jclass,
jlong ssl_address, jstring identityHintJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_psk_identity_hint identityHint=%p",
ssl, identityHintJava);
if (ssl == NULL) {
return;
}
int ret;
if (identityHintJava == NULL) {
ret = SSL_use_psk_identity_hint(ssl, NULL);
} else {
ScopedUtfChars identityHint(env, identityHintJava);
if (identityHint.c_str() == NULL) {
throwSSLExceptionStr(env, "Failed to obtain identityHint bytes");
return;
}
ret = SSL_use_psk_identity_hint(ssl, identityHint.c_str());
}
if (ret != 1) {
int sslErrorCode = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Failed to set PSK identity hint");
safeSslClear(ssl);
}
}
static void NativeCrypto_set_SSL_psk_client_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_client_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_client_callback(ssl, (enabled) ? psk_client_callback : NULL);
}
static void NativeCrypto_set_SSL_psk_server_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_server_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_server_callback(ssl, (enabled) ? psk_server_callback : NULL);
}
static jlongArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl);
STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl);
int count = (cipherStack != NULL) ? sk_SSL_CIPHER_num(cipherStack) : 0;
ScopedLocalRef<jlongArray> ciphersArray(env, env->NewLongArray(count));
ScopedLongArrayRW ciphers(env, ciphersArray.get());
for (int i = 0; i < count; i++) {
ciphers[i] = reinterpret_cast<jlong>(sk_SSL_CIPHER_value(cipherStack, i));
}
JNI_TRACE("NativeCrypto_SSL_get_ciphers(%p) => %p [size=%d]", ssl, ciphersArray.get(), count);
return ciphersArray.release();
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_mkey(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_mkey => %ld", cipher, cipher->algorithm_mkey);
return cipher->algorithm_mkey;
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_auth(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_auth => %ld", cipher, cipher->algorithm_auth);
return cipher->algorithm_auth;
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_cipher_lists(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray cipherSuites)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%p", ssl, cipherSuites);
if (ssl == NULL) {
return;
}
if (cipherSuites == NULL) {
jniThrowNullPointerException(env, "cipherSuites == null");
return;
}
int length = env->GetArrayLength(cipherSuites);
static const char noSSLv2[] = "!SSLv2";
size_t cipherStringLen = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
if (c.c_str() == NULL) {
return;
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For the separating colon */
if (cipherStringLen + c.size() < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += c.size();
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For final NUL. */
UniquePtr<char[]> cipherString(new char[cipherStringLen]);
if (cipherString.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to alloc cipher string");
return;
}
memcpy(cipherString.get(), noSSLv2, strlen(noSSLv2));
size_t j = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
cipherString[j++] = ':';
memcpy(&cipherString[j], c.c_str(), c.size());
j += c.size();
}
cipherString[j++] = 0;
if (j != cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Internal error");
return;
}
if (!SSL_set_cipher_list(ssl, cipherString.get())) {
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Illegal cipher suite strings.");
return;
}
}
static void NativeCrypto_SSL_set_accept_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_accept_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_accept_state(ssl);
}
static void NativeCrypto_SSL_set_connect_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_connect_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_connect_state(ssl);
}
/**
* Sets certificate expectations, especially for server to request client auth
*/
static void NativeCrypto_SSL_set_verify(JNIEnv* env,
jclass, jlong ssl_address, jint mode)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify mode=%x", ssl, mode);
if (ssl == NULL) {
return;
}
SSL_set_verify(ssl, (int)mode, NULL);
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass,
jlong ssl_address, jlong ssl_session_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session);
if (ssl == NULL) {
return;
}
int ret = SSL_set_session(ssl, ssl_session);
if (ret != 1) {
/*
* Translate the error, and throw if it turns out to be a real
* problem.
*/
int sslErrorCode = SSL_get_error(ssl, ret);
if (sslErrorCode != SSL_ERROR_ZERO_RETURN) {
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "SSL session set");
safeSslClear(ssl);
}
}
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean creation_enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d",
ssl, creation_enabled);
if (ssl == NULL) {
return;
}
#if !defined(OPENSSL_IS_BORINGSSL)
SSL_set_session_creation_enabled(ssl, creation_enabled);
#else
if (creation_enabled) {
SSL_clear_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
} else {
SSL_set_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
}
#endif
}
static void NativeCrypto_SSL_set_tlsext_host_name(JNIEnv* env, jclass,
jlong ssl_address, jstring hostname)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostname=%p",
ssl, hostname);
if (ssl == NULL) {
return;
}
ScopedUtfChars hostnameChars(env, hostname);
if (hostnameChars.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostnameChars=%s",
ssl, hostnameChars.c_str());
int ret = SSL_set_tlsext_host_name(ssl, hostnameChars.c_str());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting host name");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => ok", ssl);
}
static jstring NativeCrypto_SSL_get_servername(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername", ssl);
if (ssl == NULL) {
return NULL;
}
const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername => %s", ssl, servername);
return env->NewStringUTF(servername);
}
/**
* A common selection path for both NPN and ALPN since they're essentially the
* same protocol. The list of protocols in "primary" is considered the order
* which should take precedence.
*/
static int proto_select(SSL* ssl __attribute__ ((unused)),
unsigned char **out, unsigned char *outLength,
const unsigned char *primary, const unsigned int primaryLength,
const unsigned char *secondary, const unsigned int secondaryLength) {
if (primary != NULL && secondary != NULL) {
JNI_TRACE("primary=%p, length=%d", primary, primaryLength);
int status = SSL_select_next_proto(out, outLength, primary, primaryLength, secondary,
secondaryLength);
switch (status) {
case OPENSSL_NPN_NEGOTIATED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN negotiated", ssl);
return SSL_TLSEXT_ERR_OK;
break;
case OPENSSL_NPN_UNSUPPORTED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN unsupported", ssl);
break;
case OPENSSL_NPN_NO_OVERLAP:
JNI_TRACE("ssl=%p proto_select NPN/ALPN no overlap", ssl);
break;
}
} else {
if (out != NULL && outLength != NULL) {
*out = NULL;
*outLength = 0;
}
JNI_TRACE("protocols=NULL");
}
return SSL_TLSEXT_ERR_NOACK;
}
/**
* Callback for the server to select an ALPN protocol.
*/
static int alpn_select_callback(SSL* ssl, const unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen, void *) {
JNI_TRACE("ssl=%p alpn_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
return proto_select(ssl, const_cast<unsigned char **>(out), outlen,
reinterpret_cast<unsigned char*>(appData->alpnProtocolsData),
appData->alpnProtocolsLength, in, inlen);
}
/**
* Callback for the client to select an NPN protocol.
*/
static int next_proto_select_callback(SSL* ssl, unsigned char** out, unsigned char* outlen,
const unsigned char* in, unsigned int inlen, void*)
{
JNI_TRACE("ssl=%p next_proto_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
// Enable False Start on the client if the server understands NPN
// http://www.imperialviolet.org/2012/04/11/falsestart.html
SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
return proto_select(ssl, out, outlen, in, inlen,
reinterpret_cast<unsigned char*>(appData->npnProtocolsData),
appData->npnProtocolsLength);
}
/**
* Callback for the server to advertise available protocols.
*/
static int next_protos_advertised_callback(SSL* ssl,
const unsigned char **out, unsigned int *outlen, void *)
{
JNI_TRACE("ssl=%p next_protos_advertised_callback", ssl);
AppData* appData = toAppData(ssl);
unsigned char* npnProtocols = reinterpret_cast<unsigned char*>(appData->npnProtocolsData);
if (npnProtocols != NULL) {
*out = npnProtocols;
*outlen = appData->npnProtocolsLength;
return SSL_TLSEXT_ERR_OK;
} else {
*out = NULL;
*outlen = 0;
return SSL_TLSEXT_ERR_NOACK;
}
}
static void NativeCrypto_SSL_CTX_enable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_callback, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_protos_advertised_callback, NULL); // server
}
static void NativeCrypto_SSL_CTX_disable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, NULL, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, NULL, NULL); // server
}
static jbyteArray NativeCrypto_SSL_get_npn_negotiated_protocol(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_npn_negotiated_protocol", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_next_proto_negotiated(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
static int NativeCrypto_SSL_set_alpn_protos(JNIEnv* env, jclass, jlong ssl_address,
jbyteArray protos) {
SSL* ssl = to_SSL(env, ssl_address, true);
if (ssl == NULL) {
return 0;
}
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p", ssl, protos);
if (protos == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=NULL", ssl);
return 1;
}
ScopedByteArrayRO protosBytes(env, protos);
if (protosBytes.get() == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => protosBytes == NULL", ssl,
protos);
return 0;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char*>(protosBytes.get());
int ret = SSL_set_alpn_protos(ssl, tmp, protosBytes.size());
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => ret=%d", ssl, protos, ret);
return ret;
}
static jbyteArray NativeCrypto_SSL_get0_alpn_selected(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p SSL_get0_alpn_selected", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_alpn_selected(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
#ifdef WITH_JNI_TRACE_KEYS
static inline char hex_char(unsigned char in)
{
if (in < 10) {
return '0' + in;
} else if (in <= 0xF0) {
return 'A' + in - 10;
} else {
return '?';
}
}
static void hex_string(char **dest, unsigned char* input, int len)
{
*dest = (char*) malloc(len * 2 + 1);
char *output = *dest;
for (int i = 0; i < len; i++) {
*output++ = hex_char(input[i] >> 4);
*output++ = hex_char(input[i] & 0xF);
}
*output = '\0';
}
static void debug_print_session_key(SSL_SESSION* session)
{
char *session_id_str;
char *master_key_str;
const char *key_type;
char *keyline;
hex_string(&session_id_str, session->session_id, session->session_id_length);
hex_string(&master_key_str, session->master_key, session->master_key_length);
X509* peer = SSL_SESSION_get0_peer(session);
EVP_PKEY* pkey = X509_PUBKEY_get(peer->cert_info->key);
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
key_type = "RSA";
break;
case EVP_PKEY_DSA:
key_type = "DSA";
break;
case EVP_PKEY_EC:
key_type = "EC";
break;
default:
key_type = "Unknown";
break;
}
asprintf(&keyline, "%s Session-ID:%s Master-Key:%s\n", key_type, session_id_str,
master_key_str);
JNI_TRACE("ssl_session=%p %s", session, keyline);
free(session_id_str);
free(master_key_str);
free(keyline);
}
#endif /* WITH_JNI_TRACE_KEYS */
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake_bio(JNIEnv* env, jclass, jlong ssl_address,
jlong rbioRef, jlong wbioRef, jobject shc, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
BIO* rbio = reinterpret_cast<BIO*>(rbioRef);
BIO* wbio = reinterpret_cast<BIO*>(wbioRef);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio rbio=%p wbio=%p shc=%p client_mode=%d npn=%p",
ssl, rbio, wbio, shc, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => rbio == null || wbio == NULL", ssl);
return 0;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (!client_mode && alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
int ret = 0;
errno = 0;
if (!appData->setCallbackState(env, shc, NULL, npnProtocols, alpnProtocols)) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio exception => 0", ssl);
return 0;
}
if (ret <= 0) { // error. See SSL_do_handshake(3SSL) man page.
// error case
OpenSslError sslError(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio ret=%d errno=%d sslError=%d",
ssl, ret, errno, sslError.get());
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we need to exit to allow
* the SSLEngine code to wrap or unwrap.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
safeSslClear(ssl);
} else if (sslError.get() != SSL_ERROR_WANT_READ &&
sslError.get() != SSL_ERROR_WANT_WRITE) {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio error => 0", ssl);
return 0;
}
// success. handshake completed
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return reinterpret_cast<uintptr_t>(ssl_session);
}
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jint timeout_millis, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd=%p shc=%p timeout_millis=%d client_mode=%d npn=%p",
ssl, fdObject, shc, timeout_millis, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd == null => 0", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
NetFd fd(env, fdObject);
if (fd.isClosed()) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd.isClosed() => 0", ssl);
return 0;
}
int ret = SSL_set_fd(ssl, fd.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd.get());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE,
"Error setting the file descriptor");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake SSL_set_fd => 0", ssl);
return 0;
}
/*
* Make socket non-blocking, so SSL_connect SSL_read() and SSL_write() don't hang
* forever and we can use select() to find out if the socket is ready.
*/
if (!setBlocking(fd.get(), false)) {
throwSSLExceptionStr(env, "Unable to make socket non blocking");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setBlocking => 0", ssl);
return 0;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (client_mode) {
SSL_set_connect_state(ssl);
} else {
SSL_set_accept_state(ssl);
if (alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
}
ret = 0;
OpenSslError sslError;
while (appData->aliveAndKicking) {
errno = 0;
if (!appData->setCallbackState(env, shc, fdObject, npnProtocols, alpnProtocols)) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
SSL_clear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake exception => 0", ssl);
return 0;
}
// success case
if (ret == 1) {
break;
}
// retry case
if (errno == EINTR) {
continue;
}
// error case
sslError.reset(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake ret=%d errno=%d sslError=%d timeout_millis=%d",
ssl, ret, errno, sslError.get(), timeout_millis);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we use sslSelect to
* wait for it to become ready. If that doesn't happen
* before the specified timeout or an error occurs, we
* cancel the handshake. Otherwise we try the SSL_connect
* again.
*/
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslSelect => 0", ssl);
return 0;
}
if (selectResult == -1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_SYSCALL, "handshake error",
throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == -1 => 0", ssl);
return 0;
}
if (selectResult == 0) {
throwSocketTimeoutException(env, "SSL handshake timed out");
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == 0 => 0", ssl);
return 0;
}
} else {
// ALOGE("Unknown error %d during handshake", error);
break;
}
}
// clean error. See SSL_do_handshake(3SSL) man page.
if (ret == 0) {
/*
* The other side closed the socket before the handshake could be
* completed, but everything is within the bounds of the TLS protocol.
* We still might want to find out the real reason of the failure.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
} else {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
}
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake clean error => 0", ssl);
return 0;
}
// unclean error. See SSL_do_handshake(3SSL) man page.
if (ret < 0) {
/*
* Translate the error and throw exception. We are sure it is an error
* at this point.
*/
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "SSL handshake aborted",
throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake unclean error => 0", ssl);
return 0;
}
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return (jlong) ssl_session;
}
/**
* Perform SSL renegotiation
*/
static void NativeCrypto_SSL_renegotiate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate", ssl);
if (ssl == NULL) {
return;
}
int result = SSL_renegotiate(ssl);
if (result != 1) {
throwSSLExceptionStr(env, "Problem with SSL_renegotiate");
return;
}
// first call asks client to perform renegotiation
int ret = SSL_do_handshake(ssl);
if (ret != 1) {
OpenSslError sslError(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"Problem with SSL_do_handshake after SSL_renegotiate");
return;
}
// if client agrees, set ssl state and perform renegotiation
ssl->state = SSL_ST_ACCEPT;
SSL_do_handshake(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate =>", ssl);
}
/**
* public static native byte[][] SSL_get_certificate(long ssl);
*/
static jlongArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl);
if (ssl == NULL) {
return NULL;
}
X509* certificate = SSL_get_certificate(ssl);
if (certificate == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
// SSL_get_certificate can return NULL during an error as well.
freeOpenSslErrorState();
return NULL;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => threw exception", ssl);
return NULL;
}
if (!sk_X509_push(chain.get(), X509_dup_nocopy(certificate))) {
jniThrowOutOfMemory(env, "Unable to push local certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
STACK_OF(X509)* cert_chain = SSL_get_certificate_chain(ssl, certificate);
for (int i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#else
STACK_OF(X509) *cert_chain = NULL;
if (!SSL_get0_chain_certs(ssl, &cert_chain)) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_chain_certs => NULL", ssl);
freeOpenSslErrorState();
return NULL;
}
for (size_t i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#endif
jlongArray refArray = getCertificateRefs(env, chain.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => %p", ssl, refArray);
return refArray;
}
// Fills a long[] with the peer certificates in the chain.
static jlongArray NativeCrypto_SSL_get_peer_cert_chain(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain", ssl);
if (ssl == NULL) {
return NULL;
}
STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl);
Unique_sk_X509 chain_copy(NULL);
if (ssl->server) {
X509* x509 = SSL_get_peer_certificate(ssl);
if (x509 == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => NULL", ssl);
return NULL;
}
chain_copy.reset(sk_X509_new_null());
if (chain_copy.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate dup error", ssl);
return NULL;
}
size_t chain_size = sk_X509_num(chain);
for (size_t i = 0; i < chain_size; i++) {
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(sk_X509_value(chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate chain push error", ssl);
return NULL;
}
}
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(x509))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate push error", ssl);
return NULL;
}
chain = chain_copy.get();
}
jlongArray refArray = getCertificateRefs(env, chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => %p", ssl, refArray);
return refArray;
}
static int sslRead(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, char* buf, jint len,
OpenSslError& sslError, int read_timeout_millis) {
JNI_TRACE("ssl=%p sslRead buf=%p len=%d", ssl, buf, len);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslRead appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
while (appData->aliveAndKicking) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslRead => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
int result = SSL_read(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p sslRead => THROWN_EXCEPTION", ssl);
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslRead SSL_read result=%d sslError=%d", ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslRead data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE: {
return result;
}
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, read_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
return -1;
}
static jint NativeCrypto_SSL_read_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray destJava,
jint destOffset, jint destLength, jlong sourceBioRef, jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sourceBioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO dest=%p sourceBio=%p sinkBio=%p shc=%p",
ssl, destJava, rbio, wbio, shc);
if (ssl == NULL) {
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => rbio == null || wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
ScopedByteArrayRW dest(env, destJava);
if (dest.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return -1;
}
if (destOffset < 0 || destOffset > ssize_t(dest.size()) || destLength < 0
|| destLength > (ssize_t) dest.size() - destOffset) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => destOffset=%d, destLength=%d, size=%zd",
ssl, destOffset, destLength, dest.size());
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => appData == NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set callback state");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => set callback state failed", ssl);
return -1;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
int result = SSL_read(ssl, dest.get() + destOffset, destLength);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return THROWN_EXCEPTION;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO SSL_read result=%d sslError=%d", ssl, result,
sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE:
break;
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
result = -1;
break;
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
result = 0;
break;
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
result = -1;
break;
} else if (errno == EINTR) {
// System call has been interrupted. Simply retry.
result = 0;
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
return -1;
}
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => %d", ssl, result);
return result;
}
/**
* OpenSSL read function (2): read into buffer at offset n chunks.
* Returns 1 (success) or value <= 0 (failure).
*/
static jint NativeCrypto_SSL_read(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len,
jint read_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read fd=%p shc=%p b=%p offset=%d len=%d read_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, read_timeout_millis);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => fd == null", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => sslHandshakeCallbacks == null", ssl);
return 0;
}
ScopedByteArrayRW bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => threw exception", ssl);
return 0;
}
OpenSslError sslError;
int ret = sslRead(env, ssl, fdObject, shc, reinterpret_cast<char*>(bytes.get() + offset), len,
sslError, read_timeout_millis);
int result;
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslRead() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
result = -1;
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Read timed out");
result = -1;
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
// or RuntimeException thrown by callback
result = -1;
break;
default:
result = ret;
break;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => %d", ssl, result);
return result;
}
static int sslWrite(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, const char* buf, jint len,
OpenSslError& sslError, int write_timeout_millis) {
JNI_TRACE("ssl=%p sslWrite buf=%p len=%d write_timeout_millis=%d",
ssl, buf, len, write_timeout_millis);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslWrite appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
int count = len;
while (appData->aliveAndKicking && ((len > 0) || (ssl->s3->wbuf.left > 0))) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslWrite => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
JNI_TRACE("ssl=%p sslWrite SSL_write len=%d left=%d", ssl, len, ssl->s3->wbuf.left);
int result = SSL_write(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p sslWrite exception => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslWrite SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError.get(), ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslWrite data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully wrote at least one byte.
case SSL_ERROR_NONE: {
buf += result;
len -= result;
break;
}
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
// The concept of a write timeout doesn't really make sense, and
// it's also not standard Java behavior, so we wait forever here.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData,
write_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
JNI_TRACE("ssl=%p sslWrite => count=%d", ssl, count);
return count;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static int NativeCrypto_SSL_write_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray sourceJava, jint len,
jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO source=%p len=%d wbio=%p shc=%p",
ssl, sourceJava, len, wbio, shc);
if (ssl == NULL) {
return -1;
}
if (wbio == NULL) {
jniThrowNullPointerException(env, "wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO appData => NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return 0;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set appdata callback");
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => appData can't set callback", ssl);
return -1;
}
ScopedByteArrayRO source(env, sourceJava);
if (source.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => threw exception", ssl);
return -1;
}
Unique_BIO emptyBio(BIO_new_mem_buf(NULL, 0));
ScopedSslBio sslBio(ssl, emptyBio.get(), wbio);
int result = SSL_write(ssl, reinterpret_cast<const char*>(source.get()), len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO exception => exception pending (reneg)", ssl);
return -1;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO SSL_write result=%d sslError=%d left=%d",
ssl, result, sslError.get(), ssl->s3->wbuf.left);
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
case SSL_ERROR_NONE:
return result;
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
return -1;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return 0;
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
return 0;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
}
}
return -1;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static void NativeCrypto_SSL_write(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len, jint write_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write fd=%p shc=%p b=%p offset=%d len=%d write_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, write_timeout_millis);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => sslHandshakeCallbacks == null", ssl);
return;
}
ScopedByteArrayRO bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => threw exception", ssl);
return;
}
OpenSslError sslError;
int ret = sslWrite(env, ssl, fdObject, shc, reinterpret_cast<const char*>(bytes.get() + offset),
len, sslError, write_timeout_millis);
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslWrite() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Write timed out");
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
break;
default:
break;
}
}
/**
* Interrupt any pending I/O before closing the socket.
*/
static void NativeCrypto_SSL_interrupt(
JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_interrupt", ssl);
if (ssl == NULL) {
return;
}
/*
* Mark the connection as quasi-dead, then send something to the emergency
* file descriptor, so any blocking select() calls are woken up.
*/
AppData* appData = toAppData(ssl);
if (appData != NULL) {
appData->aliveAndKicking = 0;
// At most two threads can be waiting.
sslNotify(appData);
sslNotify(appData);
}
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown(JNIEnv* env, jclass, jlong ssl_address,
jobject fdObject, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown fd=%p shc=%p", ssl, fdObject, shc);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
freeOpenSslErrorState();
safeSslClear(ssl);
return;
}
/*
* Try to make socket blocking again. OpenSSL literature recommends this.
*/
int fd = SSL_get_fd(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown s=%d", ssl, fd);
if (fd != -1) {
setBlocking(fd, true);
}
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
freeOpenSslErrorState();
safeSslClear(ssl);
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown_BIO(JNIEnv* env, jclass, jlong ssl_address, jlong rbioRef,
jlong wbioRef, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(rbioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(wbioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown rbio=%p wbio=%p shc=%p", ssl, rbio, wbio, shc);
if (ssl == NULL) {
return;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => rbio == null || wbio == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
freeOpenSslErrorState();
safeSslClear(ssl);
return;
}
ScopedSslBio scopedBio(ssl, rbio, wbio);
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
freeOpenSslErrorState();
safeSslClear(ssl);
}
static jint NativeCrypto_SSL_get_shutdown(JNIEnv* env, jclass, jlong ssl_address) {
const SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown", ssl);
if (ssl == NULL) {
jniThrowNullPointerException(env, "ssl == null");
return 0;
}
int status = SSL_get_shutdown(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown => %d", ssl, status);
return static_cast<jint>(status);
}
/**
* public static native void SSL_free(long ssl);
*/
static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl);
if (ssl == NULL) {
return;
}
AppData* appData = toAppData(ssl);
SSL_set_app_data(ssl, NULL);
delete appData;
SSL_free(ssl);
}
/**
* Gets and returns in a byte array the ID of the actual SSL session.
*/
static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass,
jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
jbyteArray result = env->NewByteArray(ssl_session->session_id_length);
if (result != NULL) {
jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id);
env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src);
}
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d",
ssl_session, result, ssl_session->session_id_length);
return result;
}
/**
* Gets and returns in a long integer the creation's time of the
* actual SSL session.
*/
static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session);
if (ssl_session == NULL) {
return 0;
}
// result must be jlong, not long or *1000 will overflow
jlong result = SSL_SESSION_get_time(ssl_session);
result *= 1000; // OpenSSL uses seconds, Java uses milliseconds.
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, (long long) result);
return result;
}
/**
* Gets and returns in a string the version of the SSL protocol. If it
* returns the string "unknown" it means that no connection is established.
*/
static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const char* protocol = SSL_SESSION_get_version(ssl_session);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol);
return env->NewStringUTF(protocol);
}
/**
* Gets and returns in a string the cipher negotiated for the SSL session.
*/
static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const SSL_CIPHER* cipher = ssl_session->cipher;
const char* name = SSL_CIPHER_get_name(cipher);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name);
return env->NewStringUTF(name);
}
/**
* Frees the SSL session.
*/
static void NativeCrypto_SSL_SESSION_free(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session);
if (ssl_session == NULL) {
return;
}
SSL_SESSION_free(ssl_session);
}
/**
* Serializes the native state of the session (ID, cipher, and keys but
* not certificates). Returns a byte[] containing the DER-encoded state.
* See apache mod_ssl.
*/
static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
return ASN1ToByteArray<SSL_SESSION>(env, ssl_session, i2d_SSL_SESSION);
}
/**
* Deserialize the session.
*/
static jlong NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => threw exception");
return 0;
}
const unsigned char* ucp = reinterpret_cast<const unsigned char*>(bytes.get());
SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, bytes.size());
#if !defined(OPENSSL_IS_BORINGSSL)
// Initialize SSL_SESSION cipher field based on cipher_id http://b/7091840
if (ssl_session != NULL) {
// based on ssl_get_prev_session
uint32_t cipher_id_network_order = htonl(ssl_session->cipher_id);
uint8_t* cipher_id_byte_pointer = reinterpret_cast<uint8_t*>(&cipher_id_network_order);
if (ssl_session->ssl_version >= SSL3_VERSION_MAJOR) {
cipher_id_byte_pointer += 2; // skip first two bytes for SSL3+
} else {
cipher_id_byte_pointer += 1; // skip first byte for SSL2
}
ssl_session->cipher = SSLv23_method()->get_cipher_by_char(cipher_id_byte_pointer);
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION cipher_id=%lx hton=%x 0=%x 1=%x cipher=%s",
ssl_session->cipher_id, cipher_id_network_order,
cipher_id_byte_pointer[0], cipher_id_byte_pointer[1],
SSL_CIPHER_get_name(ssl_session->cipher));
}
#endif
if (ssl_session == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session);
return reinterpret_cast<uintptr_t>(ssl_session);
}
static jlong NativeCrypto_ERR_peek_last_error(JNIEnv*, jclass) {
return ERR_peek_last_error();
}
#define FILE_DESCRIPTOR "Ljava/io/FileDescriptor;"
#define SSL_CALLBACKS "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto$SSLHandshakeCallbacks;"
#define REF_EC_GROUP "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_GROUP;"
#define REF_EC_POINT "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_POINT;"
#define REF_EVP_CIPHER_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_CIPHER_CTX;"
#define REF_EVP_PKEY "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_PKEY;"
static JNINativeMethod sNativeCryptoMethods[] = {
NATIVE_METHOD(NativeCrypto, clinit, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_dynamic, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_by_id, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_add, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_init, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_finish, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_free, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_private_key, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_get_id, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, ENGINE_ctrl_cmd_string, "(JLjava/lang/String;Ljava/lang/String;I)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DH, "([B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_RSA, "([B[B[B[B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_EC_KEY, "(" REF_EC_GROUP REF_EC_POINT "[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_mac_key, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_type, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_public, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_private, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_cmp, "(" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS8_PRIV_KEY_INFO, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS8_PRIV_KEY_INFO, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_PUBKEY, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PUBKEY, "([B)J"),
NATIVE_METHOD(NativeCrypto, getRSAPrivateKeyWrapper, "(Ljava/security/interfaces/RSAPrivateKey;[B)J"),
NATIVE_METHOD(NativeCrypto, getECPrivateKeyWrapper, "(Ljava/security/interfaces/ECPrivateKey;" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, RSA_generate_key_ex, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, RSA_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, RSA_private_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, get_RSA_private_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, get_RSA_public_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, DH_generate_parameters_ex, "(IJ)J"),
NATIVE_METHOD(NativeCrypto, DH_generate_key, "(" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_DH_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_by_curve_name, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_asn1_flag, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_point_conversion_form, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve_name, "(" REF_EC_GROUP ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve, "(" REF_EC_GROUP ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_order, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_degree, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_cofactor, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_cmp, "(" REF_EC_GROUP REF_EC_GROUP ")Z"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_generator, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, get_EC_GROUP_type, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_POINT_new, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_POINT_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_cmp, "(" REF_EC_GROUP REF_EC_POINT REF_EC_POINT ")Z"),
NATIVE_METHOD(NativeCrypto, EC_POINT_set_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT "[B[B)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_get_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_generate_key, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get1_group, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_private_key, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_public_key, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_set_nonce_from_hash, "(" REF_EVP_PKEY "Z)V"),
NATIVE_METHOD(NativeCrypto, ECDH_compute_key, "([BI" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_create, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_init, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_destroy, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_copy, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_get_digestbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_SignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_SignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BI" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_VerifyFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[B)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)[B"),
NATIVE_METHOD(NativeCrypto, EVP_get_cipherbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_CipherInit_ex, "(" REF_EVP_CIPHER_CTX "J[B[BZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CipherUpdate, "(" REF_EVP_CIPHER_CTX "[BI[BII)I"),
NATIVE_METHOD(NativeCrypto, EVP_CipherFinal_ex, "(" REF_EVP_CIPHER_CTX "[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_iv_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_block_size, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_buf_len, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_padding, "(" REF_EVP_CIPHER_CTX "Z)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_key_length, "(" REF_EVP_CIPHER_CTX "I)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_cleanup, "(J)V"),
NATIVE_METHOD(NativeCrypto, RAND_seed, "([B)V"),
NATIVE_METHOD(NativeCrypto, RAND_load_file, "(Ljava/lang/String;J)I"),
NATIVE_METHOD(NativeCrypto, RAND_bytes, "([B)V"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid, "(Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_longName, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_oid, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, create_BIO_InputStream, ("(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream;)J")),
NATIVE_METHOD(NativeCrypto, create_BIO_OutputStream, "(Ljava/io/OutputStream;)J"),
NATIVE_METHOD(NativeCrypto, BIO_read, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, BIO_write, "(J[BII)V"),
NATIVE_METHOD(NativeCrypto, BIO_free_all, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_NAME_print_ex, "(JJ)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, d2i_X509_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, d2i_X509, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509, "(J)[B"),
NATIVE_METHOD(NativeCrypto, i2d_X509_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS7, "([J)[B"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_unpack_X509_bio, "(J)[J"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_pack_X509, "([J)[B"),
NATIVE_METHOD(NativeCrypto, X509_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, get_X509_hashCode, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_print_ex, "(JJJJ)V"),
NATIVE_METHOD(NativeCrypto, X509_get_pubkey, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_get_subject_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_pubkey_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_issuerUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_subjectUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_kusage, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_xkusage, "(J)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_pathlen, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_crl_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_lastUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_nextUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_revocationDate, "(J)J"),
NATIVE_METHOD(NativeCrypto, get_X509_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_GENERAL_NAME_stack, "(JI)[[Ljava/lang/Object;"),
NATIVE_METHOD(NativeCrypto, X509_get_notBefore, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_notAfter, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_X509_cert_info_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_flags, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_check_issued, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, d2i_X509_CRL_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509_CRL, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_cert, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_serial, "(J[B)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_REVOKED, "(J)[J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_CRL, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_REVOKED, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_supported_extension, "(J)I"),
NATIVE_METHOD(NativeCrypto, ASN1_TIME_to_Calendar, "(JLjava/util/Calendar;)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_session_id_context, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_tls_channel_id, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_tls_channel_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set1_tls_channel_id, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_PrivateKey, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_certificate, "(J[J)V"),
NATIVE_METHOD(NativeCrypto, SSL_check_private_key, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_client_CA_list, "(J[[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_mode, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_get_options, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_use_psk_identity_hint, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_client_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_server_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_cipher_lists, "(J[Ljava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ciphers, "(J)[J"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_auth, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_mkey, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_set_accept_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_connect_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_verify, "(JI)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session_creation_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_tlsext_host_name, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_servername, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "IZ[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake_bio, "(JJJ" SSL_CALLBACKS "Z[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_renegotiate, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_certificate, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_get_peer_cert_chain, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_read, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)I"),
NATIVE_METHOD(NativeCrypto, SSL_read_BIO, "(J[BIIJJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_write, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)V"),
NATIVE_METHOD(NativeCrypto, SSL_write_BIO, "(J[BIJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_interrupt, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown, "(J" FILE_DESCRIPTOR SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown_BIO, "(JJJ" SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_get_shutdown, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_session_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_time, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_version, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_cipher, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, i2d_SSL_SESSION, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_SSL_SESSION, "([B)J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_enable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_disable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_npn_negotiated_protocol, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set_alpn_protos, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, SSL_get0_alpn_selected, "(J)[B"),
NATIVE_METHOD(NativeCrypto, ERR_peek_last_error, "()J"),
};
static jclass getGlobalRefToClass(JNIEnv* env, const char* className) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(className));
jclass globalRef = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (globalRef == NULL) {
ALOGE("failed to find class %s", className);
abort();
}
return globalRef;
}
static jmethodID getMethodRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jmethodID localMethod = env->GetMethodID(clazz, name, sig);
if (localMethod == NULL) {
ALOGE("could not find method %s", name);
abort();
}
return localMethod;
}
static jfieldID getFieldRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jfieldID localField = env->GetFieldID(clazz, name, sig);
if (localField == NULL) {
ALOGE("could not find field %s", name);
abort();
}
return localField;
}
static void initialize_conscrypt(JNIEnv* env) {
jniRegisterNativeMethods(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto",
sNativeCryptoMethods, NELEM(sNativeCryptoMethods));
cryptoUpcallsClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/CryptoUpcalls");
nativeRefClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef");
openSslInputStreamClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream");
nativeRef_context = getFieldRef(env, nativeRefClass, "context", "J");
calendar_setMethod = getMethodRef(env, calendarClass, "set", "(IIIIII)V");
inputStream_readMethod = getMethodRef(env, inputStreamClass, "read", "([B)I");
integer_valueOfMethod = env->GetStaticMethodID(integerClass, "valueOf",
"(I)Ljava/lang/Integer;");
openSslInputStream_readLineMethod = getMethodRef(env, openSslInputStreamClass, "gets",
"([B)I");
outputStream_writeMethod = getMethodRef(env, outputStreamClass, "write", "([B)V");
outputStream_flushMethod = getMethodRef(env, outputStreamClass, "flush", "()V");
#ifdef CONSCRYPT_UNBUNDLED
findAsynchronousCloseMonitorFuncs();
#endif
}
static jclass findClass(JNIEnv* env, const char* name) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(name));
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (result == NULL) {
ALOGE("failed to find class '%s'", name);
abort();
}
return result;
}
#ifdef STATIC_LIB
// Give client libs everything they need to initialize our JNI
int libconscrypt_JNI_OnLoad(JavaVM *vm, void*) {
#else
// Use JNI_OnLoad for when we're standalone
int JNI_OnLoad(JavaVM *vm, void*) {
JNI_TRACE("JNI_OnLoad NativeCrypto");
#endif
gJavaVM = vm;
JNIEnv *env;
if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
ALOGE("Could not get JNIEnv");
return JNI_ERR;
}
byteArrayClass = findClass(env, "[B");
calendarClass = findClass(env, "java/util/Calendar");
inputStreamClass = findClass(env, "java/io/InputStream");
integerClass = findClass(env, "java/lang/Integer");
objectClass = findClass(env, "java/lang/Object");
objectArrayClass = findClass(env, "[Ljava/lang/Object;");
outputStreamClass = findClass(env, "java/io/OutputStream");
stringClass = findClass(env, "java/lang/String");
initialize_conscrypt(env);
return JNI_VERSION_1_6;
}
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen, Daniel Melanz
// =============================================================================
//
// Main driver function for the HMMWV full model with solid axle suspension,
// using rigid tire-terrain contact.
//
// If using the Irrlicht interface, river inputs are obtained from the keyboard.
//
// The global reference frame has Z up, X towards the back of the vehicle, and
// Y pointing to the right.
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "models/hmmwv/HMMWV.h"
#include "models/hmmwv/vehicle/HMMWV_VehicleSolidAxle.h"
#include "models/hmmwv/tire/HMMWV_RigidTire.h"
#include "models/hmmwv/HMMWV_FuncDriver.h"
#include "models/hmmwv/HMMWV_RigidTerrain.h"
// If Irrlicht support is available...
#if IRRLICHT_ENABLED
// ...include additional headers
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiDriver.h"
// ...and specify whether the demo should actually use Irrlicht
# define USE_IRRLICHT
#endif
// DEBUGGING: Uncomment the following line to print shock data
//#define DEBUG_LOG
using namespace chrono;
using namespace hmmwv;
// =============================================================================
// Initial vehicle position
ChVector<> initLoc(0, 0, 1.7); // sprung mass height at design = 49.68 in
ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction
// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0; // size in X direction
double terrainWidth = 100.0; // size in Y directoin
// Simulation step size
double step_size = 0.001;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
// Time interval between two output frames
double output_step_size = 1.0 / 1; // once a second
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// --------------------------
// Create the various modules
// --------------------------
// Create the HMMWV vehicle
HMMWV_VehicleSolidAxle vehicle(false,
hmmwv::PRIMITIVES,
hmmwv::NONE);
vehicle.Initialize(ChCoordsys<>(initLoc, initRot));
// Create the ground
HMMWV_RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);
//terrain.AddMovingObstacles(10);
terrain.AddFixedObstacles();
// Create the tires
HMMWV_RigidTire tire_front_right(terrain, 0.7f);
HMMWV_RigidTire tire_front_left(terrain, 0.7f);
HMMWV_RigidTire tire_rear_right(terrain, 0.7f);
HMMWV_RigidTire tire_rear_left(terrain, 0.7f);
tire_front_right.Initialize(vehicle.GetWheelBody(FRONT_RIGHT));
tire_front_left.Initialize(vehicle.GetWheelBody(FRONT_LEFT));
tire_rear_right.Initialize(vehicle.GetWheelBody(REAR_RIGHT));
tire_rear_left.Initialize(vehicle.GetWheelBody(REAR_LEFT));
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&vehicle,
L"HMMWV demo",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
bool do_shadows = true; // shadow map is experimental
irr::scene::ILightSceneNode* mlight = 0;
if (!do_shadows)
{
application.AddTypicalLights(
irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
}
else
{
mlight = application.AddLightWithShadow(
irr::core::vector3df(10.f, 30.f, 60.f),
irr::core::vector3df(0.f, 0.f, 0.f),
150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);
}
application.SetTimestep(step_size);
ChIrrGuiDriver driver(application, vehicle, trackPoint, 6.0, 0.5);
// Set the time response for steering and throttle keyboard inputs.
// NOTE: this is not exact, since we do not render quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double throttle_time = 1.0; // time to go from 0 to +1
double braking_time = 0.3; // time to go from 0 to +1
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetThrottleDelta(render_step_size / throttle_time);
driver.SetBrakingDelta(render_step_size / braking_time);
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
if (do_shadows)
{
application.AddShadowAll();
}
#else
HMMWV_FuncDriver driver;
#endif
// ---------------
// Simulation loop
// ---------------
#ifdef DEBUG_LOG
GetLog() << "\n\n============ System Configuration ============\n";
vehicle.LogHardpointLocations();
#endif
ChTireForces tire_forces(4);
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Number of simulation steps between two output frames
int output_steps = (int)std::ceil(output_step_size / step_size);
// Initialize simulation frame counter and simulation time
int step_number = 0;
double time = 0;
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
while (application.GetDevice()->run())
{
// update the position of the shadow mapping so that it follows the car
if (do_shadows)
{
ChVector<> lightaim = vehicle.GetChassisPos();
ChVector<> lightpos = vehicle.GetChassisPos() + ChVector<>(10, 30, 60);
irr::core::vector3df mlightpos((irr::f32)lightpos.x, (irr::f32)lightpos.y, (irr::f32)lightpos.z);
irr::core::vector3df mlightaim((irr::f32)lightaim.x, (irr::f32)lightaim.y, (irr::f32)lightaim.z);
application.GetEffects()->getShadowLight(0).setPosition(mlightpos);
application.GetEffects()->getShadowLight(0).setTarget(mlightaim);
mlight->setPosition(mlightpos);
}
// Render scene
if (step_number % render_steps == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
#ifdef DEBUG_LOG
if (step_number % output_steps == 0) {
GetLog() << "\n\n============ System Information ============\n";
GetLog() << "Time = " << time << "\n\n";
vehicle.DebugLog(DBG_SPRINGS | DBG_SHOCKS | DBG_CONSTRAINTS);
}
#endif
// Update modules (inter-module communication)
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right.Update(time, vehicle.GetWheelState(FRONT_RIGHT));
tire_front_left.Update(time, vehicle.GetWheelState(FRONT_LEFT));
tire_rear_right.Update(time, vehicle.GetWheelState(REAR_RIGHT));
tire_rear_left.Update(time, vehicle.GetWheelState(REAR_LEFT));
tire_forces[FRONT_LEFT] = tire_front_left.GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right.GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left.GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right.GetTireForce();
vehicle.Update(time, driver.getThrottle(), driver.getSteering(), driver.getBraking(), tire_forces);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
terrain.Advance(step);
tire_front_right.Advance(step);
tire_front_left.Advance(step);
tire_rear_right.Advance(step);
tire_rear_left.Advance(step);
vehicle.Advance(step);
// Increment frame number
step_number++;
}
application.GetDevice()->drop();
#else
int render_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
HMMWV_Vehicle::ExportMeshPovray(out_dir);
HMMWV_WheelLeft::ExportMeshPovray(out_dir);
HMMWV_WheelRight::ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (step_number % render_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&vehicle, filename);
std::cout << "Output frame: " << render_frame << std::endl;
std::cout << "Sim frame: " << step_number << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.getThrottle() << " steering: " << driver.getSteering() << std::endl;
std::cout << std::endl;
render_frame++;
}
// Update modules
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right.Update(time, vehicle.GetWheelState(FRONT_RIGHT));
tire_front_left.Update(time, vehicle.GetWheelState(FRONT_LEFT));
tire_rear_right.Update(time, vehicle.GetWheelState(REAR_RIGHT));
tire_rear_left.Update(time, vehicle.GetWheelState(REAR_LEFT));
tire_forces[FRONT_LEFT] = tire_front_left.GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right.GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left.GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right.GetTireForce();
vehicle.Update(time, driver.getThrottle(), driver.getSteering(), driver.getBraking(), tire_forces);
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
terrain.Advance(step_size);
tire_front_right.Advance(step_size);
tire_front_left.Advance(step_size);
tire_rear_right.Advance(step_size);
tire_rear_left.Advance(step_size);
vehicle.Advance(step_size);
// Increment frame number
step_number++;
}
#endif
return 0;
}
Update main driver function for the solid axle HMMWV demo.
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen, Daniel Melanz
// =============================================================================
//
// Main driver function for the HMMWV full model with solid axle suspension,
// using rigid tire-terrain contact.
//
// If using the Irrlicht interface, river inputs are obtained from the keyboard.
//
// The global reference frame has Z up, X towards the back of the vehicle, and
// Y pointing to the right.
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "models/hmmwv/HMMWV.h"
#include "models/hmmwv/vehicle/HMMWV_VehicleSolidAxle.h"
#include "models/hmmwv/tire/HMMWV_RigidTire.h"
#include "models/hmmwv/tire/HMMWV_LugreTire.h"
#include "models/hmmwv/HMMWV_FuncDriver.h"
#include "models/hmmwv/HMMWV_RigidTerrain.h"
// If Irrlicht support is available...
#if IRRLICHT_ENABLED
// ...include additional headers
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiDriver.h"
// ...and specify whether the demo should actually use Irrlicht
# define USE_IRRLICHT
#endif
// DEBUGGING: Uncomment the following line to print shock data
//#define DEBUG_LOG
using namespace chrono;
using namespace hmmwv;
// =============================================================================
// Initial vehicle position
ChVector<> initLoc(0, 0, 1.7); // sprung mass height at design = 49.68 in
ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction
// Type of tire model (RIGID, PACEJKA, or LUGRE)
TireModelType tire_model = RIGID;
// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0; // size in X direction
double terrainWidth = 100.0; // size in Y directoin
// Simulation step size
double step_size = 0.001;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
// Time interval between two output frames
double output_step_size = 1.0 / 1; // once a second
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV_SOLIDAXLE";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// --------------------------
// Create the various modules
// --------------------------
// Create the HMMWV vehicle
HMMWV_VehicleSolidAxle vehicle(false,
hmmwv::PRIMITIVES,
hmmwv::NONE);
vehicle.Initialize(ChCoordsys<>(initLoc, initRot));
// Create the ground
HMMWV_RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);
//terrain.AddMovingObstacles(10);
terrain.AddFixedObstacles();
// Create the tires
ChSharedPtr<ChTire> tire_front_right;
ChSharedPtr<ChTire> tire_front_left;
ChSharedPtr<ChTire> tire_rear_right;
ChSharedPtr<ChTire> tire_rear_left;
switch (tire_model) {
case RIGID:
{
ChSharedPtr<HMMWV_RigidTire> tire_FR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_FL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_RR = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
ChSharedPtr<HMMWV_RigidTire> tire_RL = ChSharedPtr<HMMWV_RigidTire>(new HMMWV_RigidTire(terrain, 0.7f));
tire_FR->Initialize(vehicle.GetWheelBody(FRONT_RIGHT));
tire_FL->Initialize(vehicle.GetWheelBody(FRONT_LEFT));
tire_RR->Initialize(vehicle.GetWheelBody(REAR_RIGHT));
tire_RL->Initialize(vehicle.GetWheelBody(REAR_LEFT));
tire_front_right = tire_FR;
tire_front_left = tire_FL;
tire_rear_right = tire_RR;
tire_rear_left = tire_RL;
break;
}
case LUGRE:
{
ChSharedPtr<HMMWV_LugreTire> tire_FR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_FL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_RR = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
ChSharedPtr<HMMWV_LugreTire> tire_RL = ChSharedPtr<HMMWV_LugreTire>(new HMMWV_LugreTire(terrain));
tire_FR->Initialize();
tire_FL->Initialize();
tire_RR->Initialize();
tire_RL->Initialize();
tire_front_right = tire_FR;
tire_front_left = tire_FL;
tire_rear_right = tire_RR;
tire_rear_left = tire_RL;
break;
}
}
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&vehicle,
L"HMMWV Solid-Axle demo",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
bool do_shadows = true; // shadow map is experimental
irr::scene::ILightSceneNode* mlight = 0;
if (!do_shadows)
{
application.AddTypicalLights(
irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
}
else
{
mlight = application.AddLightWithShadow(
irr::core::vector3df(10.f, 30.f, 60.f),
irr::core::vector3df(0.f, 0.f, 0.f),
150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);
}
application.SetTimestep(step_size);
ChIrrGuiDriver driver(application, vehicle, trackPoint, 6.0, 0.5, true);
// Set the time response for steering and throttle keyboard inputs.
// NOTE: this is not exact, since we do not render quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double throttle_time = 1.0; // time to go from 0 to +1
double braking_time = 0.3; // time to go from 0 to +1
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetThrottleDelta(render_step_size / throttle_time);
driver.SetBrakingDelta(render_step_size / braking_time);
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
if (do_shadows)
{
application.AddShadowAll();
}
#else
HMMWV_FuncDriver driver;
#endif
// ---------------
// Simulation loop
// ---------------
#ifdef DEBUG_LOG
GetLog() << "\n\n============ System Configuration ============\n";
vehicle.LogHardpointLocations();
#endif
// Inter-module communication data
ChTireForces tire_forces(4);
ChBodyState wheel_states[4];
double throttle_input;
double steering_input;
double braking_input;
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Number of simulation steps between two output frames
int output_steps = (int)std::ceil(output_step_size / step_size);
// Initialize simulation frame counter and simulation time
int step_number = 0;
double time = 0;
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
while (application.GetDevice()->run())
{
// update the position of the shadow mapping so that it follows the car
if (do_shadows)
{
ChVector<> lightaim = vehicle.GetChassisPos();
ChVector<> lightpos = vehicle.GetChassisPos() + ChVector<>(10, 30, 60);
irr::core::vector3df mlightpos((irr::f32)lightpos.x, (irr::f32)lightpos.y, (irr::f32)lightpos.z);
irr::core::vector3df mlightaim((irr::f32)lightaim.x, (irr::f32)lightaim.y, (irr::f32)lightaim.z);
application.GetEffects()->getShadowLight(0).setPosition(mlightpos);
application.GetEffects()->getShadowLight(0).setTarget(mlightaim);
mlight->setPosition(mlightpos);
}
// Render scene
if (step_number % render_steps == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
#ifdef DEBUG_LOG
if (step_number % output_steps == 0) {
GetLog() << "\n\n============ System Information ============\n";
GetLog() << "Time = " << time << "\n\n";
vehicle.DebugLog(DBG_SPRINGS | DBG_SHOCKS | DBG_CONSTRAINTS);
}
#endif
// Collect output data from modules (for inter-module communication)
throttle_input = driver.getThrottle();
steering_input = driver.getSteering();
braking_input = driver.getBraking();
tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce();
wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT);
wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT);
wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right->Update(time, wheel_states[FRONT_LEFT]);
tire_front_left->Update(time, wheel_states[FRONT_RIGHT]);
tire_rear_right->Update(time, wheel_states[REAR_LEFT]);
tire_rear_left->Update(time, wheel_states[REAR_RIGHT]);
vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
terrain.Advance(step);
tire_front_right->Advance(step);
tire_front_left->Advance(step);
tire_rear_right->Advance(step);
tire_rear_left->Advance(step);
vehicle.Advance(step);
// Increment frame number
step_number++;
}
application.GetDevice()->drop();
#else
int render_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
HMMWV_VehicleSolidAxle::ExportMeshPovray(out_dir);
HMMWV_WheelLeft::ExportMeshPovray(out_dir);
HMMWV_WheelRight::ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (step_number % render_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&vehicle, filename);
std::cout << "Output frame: " << render_frame << std::endl;
std::cout << "Sim frame: " << step_number << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.getThrottle() << " steering: " << driver.getSteering() << std::endl;
std::cout << std::endl;
render_frame++;
}
// Collect output data from modules (for inter-module communication)
throttle_input = driver.getThrottle();
steering_input = driver.getSteering();
braking_input = driver.getBraking();
tire_forces[FRONT_LEFT] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT] = tire_front_right->GetTireForce();
tire_forces[REAR_LEFT] = tire_rear_left->GetTireForce();
tire_forces[REAR_RIGHT] = tire_rear_right->GetTireForce();
wheel_states[FRONT_LEFT] = vehicle.GetWheelState(FRONT_RIGHT);
wheel_states[FRONT_RIGHT] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[REAR_LEFT] = vehicle.GetWheelState(REAR_RIGHT);
wheel_states[REAR_RIGHT] = vehicle.GetWheelState(REAR_LEFT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
terrain.Update(time);
tire_front_right->Update(time, wheel_states[FRONT_LEFT]);
tire_front_left->Update(time, wheel_states[FRONT_RIGHT]);
tire_rear_right->Update(time, wheel_states[REAR_LEFT]);
tire_rear_left->Update(time, wheel_states[REAR_RIGHT]);
vehicle.Update(time, throttle_input, steering_input, braking_input, tire_forces);
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
terrain.Advance(step_size);
tire_front_right->Advance(step_size);
tire_front_left->Advance(step_size);
tire_rear_right->Advance(step_size);
tire_rear_left->Advance(step_size);
vehicle.Advance(step_size);
// Increment frame number
step_number++;
}
#endif
return 0;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The BlocknetDX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "primitives/transaction.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/sign.h"
#include "script/standard.h"
#include "uint256.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <stdint.h>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include <boost/assign/list_of.hpp>
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH (const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
} else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"blocknetdxaddress\" (string) blocknetdx address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1"));
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
#ifdef ENABLE_WALLET
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of blocknetdx addresses to filter\n"
" [\n"
" \"address\" (string) blocknetdx address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the blocknetdx address\n"
" \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in btc\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\""));
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2) {
Array inputs = params[2].get_array();
BOOST_FOREACH (Value& input, inputs) {
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BlocknetDX address: ") + input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH (const COutput& out, vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount", ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations", out.nDepth));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
#endif
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n"
"\nCreate a transaction spending the given inputs and sending to the given addresses.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"address\": x.xxx (numeric, required) The key is the blocknetdx address, the value is the btc amount\n"
" ,...\n"
" }\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n" +
HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\""));
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CMutableTransaction rawTx;
BOOST_FOREACH (const Value& input, inputs) {
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH (const Pair& s, sendTo)
{
if (s.name_ == string("data"))
{
std::vector<unsigned char> data = ParseHex(s.value_.get_str());
if(data.size()>512*1024)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Message length greater than 1*1024*1024");
CTxOut out(0,CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
}
else
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BlocknetDX address: ") + s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + s.name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
return EncodeHexTx(rawTx);
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) blocknetdx address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\""));
RPCTypeCheck(params, list_of(str_type));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value decodescript(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) blocknetdx address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\""));
RPCTypeCheck(params, list_of(str_type));
Object r;
CScript script;
if (params[0].get_str().size() > 0) {
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
return r;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n"
" \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\""));
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
} catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache& viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH (const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type) {
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH (Value k, keys) {
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type) {
Array prevTxs = params[1].get_array();
BOOST_FOREACH (Value& p, prevTxs) {
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" +
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut + 1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript", str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null)) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of(string("ALL"), int(SIGHASH_ALL))(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))(string("NONE"), int(SIGHASH_NONE))(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE | SIGHASH_ANYONECANPAY))(string("SINGLE"), int(SIGHASH_SINGLE))(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY));
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH (const CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i)))
fComplete = false;
}
Object result;
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n" +
HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\""));
RPCTypeCheck(params, list_of(str_type)(bool_type));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
CCoinsViewCache& view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) {
if (state.IsInvalid())
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
else
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
comment for createrawtransaction
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The BlocknetDX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "primitives/transaction.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/sign.h"
#include "script/standard.h"
#include "uint256.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <stdint.h>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include <boost/assign/list_of.hpp>
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH (const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
} else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"blocknetdxaddress\" (string) blocknetdx address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1"));
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
#ifdef ENABLE_WALLET
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of blocknetdx addresses to filter\n"
" [\n"
" \"address\" (string) blocknetdx address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the blocknetdx address\n"
" \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in btc\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\""));
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2) {
Array inputs = params[2].get_array();
BOOST_FOREACH (Value& input, inputs) {
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BlocknetDX address: ") + input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH (const COutput& out, vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount", ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations", out.nDepth));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
#endif
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"data\":\"<Message>\",\"address\":amount,...}\n"
"\nCreate a transaction spending the given inputs\n"
"(array of objects containing transaction id and output number),\n"
"Message is Hex encoded for use with OP_RETURN Limit of 25300bytes\n"
"and sending to the given addresses.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"data\":\"<Message>\", (string, optional) hex encoded data\n"
" \"address\": x.xxx (numeric, required) The key is the blocknetdx address, the value is the btc amount\n"
" ,...\n"
" }\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n" +
HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\""));
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CMutableTransaction rawTx;
BOOST_FOREACH (const Value& input, inputs) {
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH (const Pair& s, sendTo)
{
if (s.name_ == string("data"))
{
std::vector<unsigned char> data = ParseHex(s.value_.get_str());
if(data.size()>512*1024)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Message length greater than 1*1024*1024");
CTxOut out(0,CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
}
else
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BlocknetDX address: ") + s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + s.name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
return EncodeHexTx(rawTx);
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) blocknetdx address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\""));
RPCTypeCheck(params, list_of(str_type));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value decodescript(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) blocknetdx address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\""));
RPCTypeCheck(params, list_of(str_type));
Object r;
CScript script;
if (params[0].get_str().size() > 0) {
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
return r;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n"
" \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\""));
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
} catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache& viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH (const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type) {
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH (Value k, keys) {
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type) {
Array prevTxs = params[1].get_array();
BOOST_FOREACH (Value& p, prevTxs) {
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" +
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut + 1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript", str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null)) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of(string("ALL"), int(SIGHASH_ALL))(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))(string("NONE"), int(SIGHASH_NONE))(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE | SIGHASH_ANYONECANPAY))(string("SINGLE"), int(SIGHASH_SINGLE))(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY));
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH (const CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i)))
fComplete = false;
}
Object result;
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n" +
HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\""));
RPCTypeCheck(params, list_of(str_type)(bool_type));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
CCoinsViewCache& view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) {
if (state.IsInvalid())
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
else
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
|
/*
* OCPlanner.cc
*
* Copyright (C) 2012 by OpenCog Foundation
* Written by Shujing KE
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <set>
#include <boost/variant.hpp>
#include <opencog/util/oc_assert.h>
#include <opencog/util/StringManipulator.h>
#include <opencog/spacetime/SpaceTime.h>
#include <opencog/spacetime/SpaceServer.h>
#include <opencog/spatial/3DSpaceMap/Entity3D.h>
#include <opencog/spatial/3DSpaceMap/Octree3DMapManager.h>
#include <opencog/spatial/3DSpaceMap/Block3DMapUtil.h>
#include <opencog/spatial/3DSpaceMap/Pathfinder3D.h>
#include <opencog/embodiment/Control/PerceptionActionInterface/ActionParamType.h>
#include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h>
#include <opencog/server/BaseServer.h>
#include <opencog/query/PatternMatch.h>
#include <opencog/query/PatternMatchEngine.h>
#include <opencog/util/StringManipulator.h>
#include <opencog/atomspace/atom_types.h>
#include <opencog/embodiment/AtomSpaceExtensions/atom_types.h>
#include <opencog/nlp/types/atom_types.h>
#include <opencog/spacetime/atom_types.h>
#include <opencog/embodiment/Control/PerceptionActionInterface/PAI.h>
#include "Inquery.h"
#include "OCPlanner.h"
using namespace opencog::oac;
using namespace opencog::pai;
AtomSpace* Inquery::atomSpace= 0;
SpaceServer::SpaceMap* Inquery::spaceMap = 0;
void Inquery::init(AtomSpace* _atomSpace)
{
atomSpace = _atomSpace;
spaceMap = &(spaceServer().getLatestMap());
}
void Inquery::setSpaceMap(SpaceServer::SpaceMap *_spaceMap)
{
spaceMap = _spaceMap;
}
void Inquery::reSetSpaceMap()
{
spaceMap = &(spaceServer().getLatestMap());
}
ParamValue Inquery::getParamValueFromAtomspace( State& state)
{
vector<ParamValue> stateOwnerList = state.stateOwnerList;
Entity entity1, entity2, entity3;
Handle a, b, c = Handle::UNDEFINED;
entity1 = boost::get<Entity>(stateOwnerList[0]);
a = AtomSpaceUtil::getEntityHandle(*atomSpace,entity1.id);
if(stateOwnerList.size() > 1)
{
entity2 = boost::get<Entity>(stateOwnerList[1]);
b = AtomSpaceUtil::getEntityHandle(*atomSpace,entity2.id);
}
if(stateOwnerList.size() > 2)
{
entity3 = boost::get<Entity>(stateOwnerList[2]);
c = AtomSpaceUtil::getEntityHandle(*atomSpace,entity3.id);
}
Handle evalLink = AtomSpaceUtil::getLatestEvaluationLink(*atomSpace, state.name(), a , b, c);
if (evalLink == Handle::UNDEFINED)
{
logger().error("Inquery::getParamValueFromAtomspace : There is no evaluation link for predicate: "
+ state.name() );
return UNDEFINED_VALUE;
}
Handle listLink = atomSpace->getOutgoing(evalLink, 1);
if (listLink== Handle::UNDEFINED)
{
logger().error("Inquery::getParamValueFromAtomspace : There is no list link for the Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
// So the value node is always after the owners.
// We need to know how many owners this state has
// the size of the state owners
int ownerSize = stateOwnerList.size();
HandleSeq listLinkOutgoings = atomSpace->getOutgoing(listLink);
if ( listLinkOutgoings.size() == ownerSize )
{ // some evalLink without a value node, e.g.:
/* It means these two objects are far away from each other, we'll get its value from its truthvalue
(EvaluationLink (stv 1 0.0012484394) (av -14 1 0)
(PredicateNode "far" (av -21 1 0))
(ListLink (av -12 0 0)
(ObjectNode "id_-1522462" (av -12 1 0))
(ObjectNode "id_5640" (av -20 0 0))
)
)
*/
// then the state value type should be boolean
if (state.getActionParamType().getCode() != BOOLEAN_CODE)
{
logger().error("Inquery::getParamValueFromAtomspace : There is no value node for this Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
if (atomSpace->getMean(evalLink) > 0.5)
return "true";
else
return "false";
}
else if ( listLinkOutgoings.size() - ownerSize == 1)
{
// some state only has one value node, which is the most common state,e.g.:
// (EvaluationLink (stv 1 0.0012484394) (av -23 1 0)
// (PredicateNode "material" (av -23 1 0))
// (ListLink (av -23 0 0)
// (StructureNode "id_CHUNK_2_2_0_BLOCK_15_6_104" (av -23 0 0))
// (ConceptNode "Stone" (av -23 0 0))
// )
// )
Handle valueHandle = atomSpace->getOutgoing(listLink, ownerSize);// the ownerSize is just the index of the value node
if ( valueHandle == Handle::UNDEFINED )
{
logger().error("Inquery::getParamValueFromAtomspace : There is no list link for the Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
// this kind of state value can only be bool,int,float,string or entity
switch (state.getActionParamType().getCode())
{
case BOOLEAN_CODE:
case INT_CODE:
case FLOAT_CODE:
case STRING_CODE:
return (atomSpace->getName(valueHandle));
case ENTITY_CODE:
return Entity(atomSpace->getName(valueHandle) ,PAI::getObjectTypeFromHandle(*atomSpace, valueHandle));
default:
logger().error("Inquery::getParamValueFromAtomspace : There is more than one value node for the Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
}
else if (listLinkOutgoings.size() - ownerSize == 2)
{
// when this state value is fuzzy number interval, there will be 2 number nodes for the value
Handle valueHandle1 = atomSpace->getOutgoing(listLink, ownerSize);// the ownerSize is just the index of the value node
Handle valueHandle2 = atomSpace->getOutgoing(listLink, ownerSize + 1);
if ( (valueHandle1 == Handle::UNDEFINED) || (valueHandle2 == Handle::UNDEFINED) )
{
logger().error("Inquery::getParamValueFromAtomspace :Type error: The value type is fuzzy interval, but there are not 2 number nodes in its listlink , for the Evaluation Link: "
+ state.name() );
return UNDEFINED_VALUE;
}
switch (state.getActionParamType().getCode())
{
case FUZZY_INTERVAL_INT_CODE:
{
int lowInt = atoi(atomSpace->getName(valueHandle1).c_str());
int highInt = atoi(atomSpace->getName(valueHandle2).c_str());
return FuzzyIntervalInt(lowInt,highInt);
}
case FUZZY_INTERVAL_FLOAT_CODE:
{
float lowf = atof(atomSpace->getName(valueHandle1).c_str());
float highf = atof(atomSpace->getName(valueHandle2).c_str());
return FuzzyIntervalFloat(lowf,highf);
}
default:
logger().error("Inquery::getParamValueFromAtomspace : Type error: There is 2 number nodes for the Evaluation Link: "
+ state.name() + ". But it is neighter a fuzzyIntervalInt nor a fuzzyIntervalFLoat");
return UNDEFINED_VALUE;
}
}
else if(listLinkOutgoings.size() - ownerSize == 3)
{// when it is a vector, it will have 3 number nodes, e.g.:
// the link and nodes are like this:
// (EvaluationLink (av -23 0 0) // this the "valueH"
// (PredicateNode "AGISIM_position" (av -23 1 0))
// (ListLink (av -23 0 0)
// (StructureNode "id_CHUNK_2_2_0_BLOCK_6_6_104" (av -23 0 0))
// (NumberNode "54.5" (av -23 0 0))
// (NumberNode "54.5" (av -23 0 0))
// (NumberNode "104.5" (av -23 0 0))
// )
// )
Handle valueHandle1 = atomSpace->getOutgoing(listLink, ownerSize);// the ownerSize is just the index of the value node
Handle valueHandle2 = atomSpace->getOutgoing(listLink, ownerSize + 1);
Handle valueHandle3 = atomSpace->getOutgoing(listLink, ownerSize + 2);
if ( (valueHandle1 == Handle::UNDEFINED) || (valueHandle2 == Handle::UNDEFINED) || (valueHandle3 == Handle::UNDEFINED) )
{
logger().error("Inquery::getParamValueFromAtomspace :Type error: The value type is vector or rotation,but there are not 3 number nodes in its listlink , for the Evaluation Link: "
+ state.name() );
return UNDEFINED_VALUE;
}
double x = atof(atomSpace->getName(valueHandle1).c_str());
double y = atof(atomSpace->getName(valueHandle2).c_str());
double z = atof(atomSpace->getName(valueHandle3).c_str());
switch (state.getActionParamType().getCode())
{
case VECTOR_CODE:
return Vector(x,y,z);
case ROTATION_CODE:
return Rotation(x,y,z);
default:
logger().error("Inquery::getParamValueFromAtomspace : Type error: There is 3 number nodes for the Evaluation Link: "
+ state.name() + ". But it is neighter a Vector nor a Rotation");
return UNDEFINED_VALUE;
}
}
else
{
logger().error("Inquery::getParamValueFromAtomspace :the number of value nodes is invalid for the Evaluation Link: "
+ state.name() );
return UNDEFINED_VALUE;
}
}
ParamValue Inquery::getParamValueFromHandle(string var, Handle& valueH)
{
switch (opencog::oac::GetVariableType(var))
{
case ENTITY_CODE:
{
return Entity(atomSpace->getName(valueH) ,PAI::getObjectTypeFromHandle(*atomSpace, valueH));
}
case BOOLEAN_CODE:
{
string strVar = atomSpace->getName(valueH);
if ((strVar == "true")||(strVar == "True"))
return opencog::oac::SV_TRUE;
else
return opencog::oac::SV_FALSE;
}
case INT_CODE:
case FLOAT_CODE:
case STRING_CODE:
{
return (atomSpace->getName(valueH));
}
case VECTOR_CODE:
{
Handle valueHandle1 = atomSpace->getOutgoing(valueH, 0);// the ownerSize is just the index of the value node
Handle valueHandle2 = atomSpace->getOutgoing(valueH, 1);
Handle valueHandle3 = atomSpace->getOutgoing(valueH, 2);
if ( (valueHandle1 == Handle::UNDEFINED) || (valueHandle2 == Handle::UNDEFINED) || (valueHandle3 == Handle::UNDEFINED) )
{
logger().error("Inquery::getParamValueFromHandle :Type error: The value type is vector or rotation,but there are not 3 number nodes in its listlink ");
return UNDEFINED_VALUE;
}
double x = atof(atomSpace->getName(valueHandle1).c_str());
double y = atof(atomSpace->getName(valueHandle2).c_str());
double z = atof(atomSpace->getName(valueHandle3).c_str());
return Vector(x,y,z);
}
default:
{
return UNDEFINED_VALUE;
}
}
}
ParamValue Inquery::inqueryDistance(const vector<ParamValue>& stateOwnerList)
{
double d = DOUBLE_MAX;
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
Entity* entity1 = boost::get<Entity>(&var1);
Entity* entity2 = boost::get<Entity>(&var2);
Vector* vector2 = boost::get<Vector>(&var2);
if (entity1 && entity2)
{
d = spaceMap->distanceBetween(entity1->id, entity2->id);
}
else if (entity1 && vector2)
{
d = spaceMap->distanceBetween(entity1->id, SpaceServer::SpaceMapPoint(vector2->x,vector2->y,vector2->z));
}
return (opencog::toString(d));
}
ParamValue Inquery::inqueryExist(const vector<ParamValue>& stateOwnerList)
{
Entity entity = boost::get<Entity>(stateOwnerList.front());
// if (! entity)
// return "false";
bool is_exist = spaceMap->containsObject(entity.id);
return (opencog::toString(is_exist));
}
ParamValue Inquery::inqueryAtLocation(const vector<ParamValue>& stateOwnerList)
{
ParamValue obj = stateOwnerList.front();
Entity* entity = boost::get<Entity>(&obj);
Handle h = AtomSpaceUtil::getObjectHandle(*atomSpace, entity->id);
SpaceServer::SpaceMapPoint pos;
if (h == Handle::UNDEFINED) // not an object, let try if it's an agent
h = AtomSpaceUtil::getAgentHandle(*atomSpace, entity->id);
if(h == Handle::UNDEFINED)
return Vector(DOUBLE_MAX,DOUBLE_MAX,DOUBLE_MAX);
else
pos = spaceMap->getObjectLocation(h);
if (pos == SpaceServer::SpaceMapPoint::ZERO)
return Vector(DOUBLE_MAX,DOUBLE_MAX,DOUBLE_MAX);
else
return Vector(pos.x,pos.y,pos.z);
}
ParamValue Inquery::inqueryIsSolid(const vector<ParamValue>& stateOwnerList)
{
ParamValue var = stateOwnerList.back();
Vector* pos = boost::get<Vector>(&var);
if (! pos)
return "false";
if (spaceMap->checkIsSolid((int)pos->x,(int)pos->y,(int)pos->z))
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsStandable(const vector<ParamValue>& stateOwnerList)
{
ParamValue var = stateOwnerList.back();
Vector* pos = boost::get<Vector>(&var);
if (! pos)
return "false";
if (spaceMap->checkStandable((int)pos->x,(int)pos->y,(int)pos->z))
return "true";
else
return "false";
}
ParamValue Inquery::inqueryExistPath(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
spatial::BlockVector pos1,pos2;
Entity* entity1 = boost::get<Entity>(&var1);
if (entity1)
pos1 = spaceMap->getObjectLocation(entity1->id);
else
{
Vector* v1 = boost::get<Vector>(&var1);
pos1 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
}
Entity* entity2 = boost::get<Entity>(&var2);
if (entity2)
pos2 = spaceMap->getObjectLocation(entity2->id);
else
{
Vector* v2 = boost::get<Vector>(&var2);
pos2 = SpaceServer::SpaceMapPoint(v2->x,v2->y,v2->z);
}
if (SpaceServer::SpaceMap::isTwoPositionsAdjacent(pos1, pos2))
{
if (spatial::Pathfinder3D::checkNeighbourAccessable(spaceMap, pos1, pos2.x - pos1.x, pos2.y - pos1.y, pos2.z - pos1.z))
return "true";
else
return "false";
}
vector<spatial::BlockVector> path;
spatial::BlockVector nearestPos;
if (spatial::Pathfinder3D::AStar3DPathFinder(spaceMap, pos1, pos2, path, nearestPos))
return "true";
else
return "false";
}
vector<ParamValue> Inquery::inqueryNearestAccessiblePosition(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
spatial::BlockVector pos1,pos2;
vector<ParamValue> values;
Entity* entity1 = boost::get<Entity>(&var1);
if (entity1)
pos1 = spaceMap->getObjectLocation(entity1->id);
else
{
Vector* v1 = boost::get<Vector>(&var1);
pos1 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
}
Entity* entity2 = boost::get<Entity>(&var2);
if (entity2)
pos2 = spaceMap->getObjectLocation(entity2->id);
else
{
Vector* v2 = boost::get<Vector>(&var2);
pos2 = SpaceServer::SpaceMapPoint(v2->x,v2->y,v2->z);
}
spatial::BlockVector nearestPos;
vector<spatial::BlockVector> path;
spatial::Pathfinder3D::AStar3DPathFinder(spaceMap, pos1, pos2, path, nearestPos);
if (nearestPos != pos1)
{
values.push_back(Vector(nearestPos.x,nearestPos.y,nearestPos.z));
}
return values;
}
vector<ParamValue> Inquery::inqueryAdjacentPosition(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
spatial::BlockVector pos1;
vector<ParamValue> values;
Entity* entity1 = boost::get<Entity>(&var1);
if (entity1)
pos1 = spaceMap->getObjectLocation(entity1->id);
else
{
Vector* v1 = boost::get<Vector>(&var1);
pos1 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
}
// return 24 adjacent neighbour locations (26 neighbours except the pos above and below)
int x,y,z;
for (x = -1; x <= 1; x ++)
for (y = -1; x <= 1; x ++)
for (z = -1; z <= 1; z ++)
{
if ( (x == 0) && (y == 0))
continue;
values.push_back(Vector(pos1.x + x,pos1.y + y,pos1.z + z));
}
return values;
}
vector<ParamValue> Inquery::inqueryStandableNearbyAccessablePosition(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList[1];
spatial::BlockVector pos1, pos2;
vector<ParamValue> values;
Entity* entity1 = boost::get<Entity>(&var1);
pos1 = spaceMap->getObjectLocation(entity1->id);
Vector* v1 = boost::get<Vector>(&var2);
pos2 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
// return 24 adjacent neighbour locations (26 neighbours except the pos above and below)
int x,y,z;
for (x = -1; x <= 1; x ++)
for (y = -1; x <= 1; x ++)
for (z = -1; z <= 1; z ++)
{
if ( (x == 0) && (y == 0))
{
continue;
SpaceServer::SpaceMapPoint curPos(pos2.x + x,pos2.y + y,pos2.z + z);
// check if it's standable
if (! spaceMap->checkStandable(curPos))
continue;
// check if there is a path from the avatar to this position
if (SpaceServer::SpaceMap::isTwoPositionsAdjacent(pos1, pos2))
{
if (spatial::Pathfinder3D::checkNeighbourAccessable(spaceMap, pos1, pos2.x - pos1.x, pos2.y - pos1.y, pos2.z - pos1.z))
{
values.push_back(Vector(curPos.x,curPos.y,curPos.z));
}
continue;
}
vector<spatial::BlockVector> path;
spatial::BlockVector nearestPos;
if (spatial::Pathfinder3D::AStar3DPathFinder(spaceMap, pos1, pos2, path, nearestPos))
values.push_back(Vector(curPos.x,curPos.y,curPos.z));
}
}
return values;
}
ParamValue Inquery::inqueryIsAdjacent(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
Vector* v1 = boost::get<Vector>(&var1);
Vector* v2 = boost::get<Vector>(&var2);
if ((!v1)||(!v2))
return "false";
SpaceServer::SpaceMapPoint pos1(v1->x,v1->y,v1->z);
SpaceServer::SpaceMapPoint pos2(v2->x,v2->y,v2->z);
if (SpaceServer::SpaceMap::isTwoPositionsAdjacent(pos1, pos2))
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsAbove(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::ABOVE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsBeside(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::BESIDE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsNear(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::NEAR) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsFar(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::FAR_) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsTouching(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::TOUCHING) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsInside(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::INSIDE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsOutside(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::OUTSIDE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsBelow(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::BELOW) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsLeftOf(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::LEFT_OF) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsRightOf(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::RIGHT_OF) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsBehind(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::BEHIND) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsInFrontOf(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::IN_FRONT_OF) != relations.end())
return "true";
else
return "false";
}
set<spatial::SPATIAL_RELATION> Inquery::getSpatialRelations(const vector<ParamValue>& stateOwnerList)
{
// set<spatial::SPATIAL_RELATION> empty;
Entity entity1 = boost::get<Entity>( stateOwnerList.front());
Entity entity2 = boost::get<Entity>( stateOwnerList[1]);
Entity entity3 = boost::get<Entity>( stateOwnerList[2]);
/*
if ((entity1 == 0)||(entity2 == 0))
return empty;
*/
string entity3ID = "";
if (stateOwnerList.size() == 3)
{
Entity entity3 = boost::get<Entity>( stateOwnerList.back());
entity3ID = entity3.id;
}
return spaceMap->computeSpatialRelations(entity1.id, entity2.id, entity3.id);
}
// find atoms by given condition, by patern mactcher.
HandleSeq Inquery::findAllObjectsByGivenCondition(State* state)
{
HandleSeq results;
Handle inhSecondOutgoing;
HandleSeq evalNonFirstOutgoings;
switch (state->getActionParamType().getCode())
{
case ENTITY_CODE:
{
const Entity& entity = state->stateVariable->getEntityValue();
inhSecondOutgoing = AtomSpaceUtil::getEntityHandle(*atomSpace,entity.id);
if (inhSecondOutgoing == Handle::UNDEFINED)
{
logger().warn("Inquery::findAllObjectsByGivenCondition : There is no Entity Node for this state value: "
+ state->name());
return results; // return empty result
}
evalNonFirstOutgoings.push_back(inhSecondOutgoing);
break;
}
case INT_CODE:
case FLOAT_CODE:
{
const string& value = state->stateVariable->getStringValue();
inhSecondOutgoing = AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,value.c_str());
evalNonFirstOutgoings.push_back(inhSecondOutgoing);
break;
}
case STRING_CODE:
{
const string& value = state->stateVariable->getStringValue();
inhSecondOutgoing = AtomSpaceUtil::addNode(*atomSpace,CONCEPT_NODE,value.c_str());
evalNonFirstOutgoings.push_back(inhSecondOutgoing);
break;
}
case VECTOR_CODE:
{
const Vector& vector = state->stateVariable->getVectorValue();
// for vector and rotation, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,opencog::toString(vector.x).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,opencog::toString(vector.y).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,opencog::toString(vector.z).c_str()));
break;
}
case ROTATION_CODE:
{
const Rotation & value= state->stateVariable->getRotationValue();
// for vector, rotation and fuzzy values, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.pitch).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.roll).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.yaw).c_str()));
break;
}
case FUZZY_INTERVAL_INT_CODE:
{
const FuzzyIntervalInt& value = state->stateVariable->getFuzzyIntervalIntValue();
// for vector, rotation and fuzzy values, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_low).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_high).c_str()));
break;
}
case FUZZY_INTERVAL_FLOAT_CODE:
{
const FuzzyIntervalFloat& value = state->stateVariable->getFuzzyIntervalFloatValue();
// for vector, rotation and fuzzy values, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_low).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_high).c_str()));
break;
}
}
// first search from EvaluationLinks
if (evalNonFirstOutgoings.size() > 0)
results = AtomSpaceUtil::getNodesByEvaluationLink(*atomSpace,state->name(),evalNonFirstOutgoings);
// if cannot find any result, search from InheritanceLink
if ((results.size() == 0) && (inhSecondOutgoing != Handle::UNDEFINED))
results = AtomSpaceUtil::getNodesByInheritanceLink(*atomSpace, inhSecondOutgoing);
return results;
}
HandleSeq Inquery::generatePMNodeFromeAParamValue(ParamValue& paramValue, RuleNode* ruleNode)
{
HandleSeq results;
ParamValue* realValue;
if (! Rule::isParamValueUnGrounded(paramValue))
{
// this stateOwner is const, just add it
realValue = ¶mValue;
}
else
{
// this stateOwner is a variable
// look for the value of this variable in the current grounding parameter map
ParamGroundedMapInARule::iterator paramMapIt = ruleNode->currentBindingsFromForwardState.find(ActionParameter::ParamValueToString(paramValue));
if (paramMapIt != ruleNode->currentBindingsFromForwardState.end())
{
// found it in the current groundings, so just add it as a const
realValue = &(paramMapIt->second);
}
else
{
// it has not been grounded, so add it as a variable node
results.push_back(AtomSpaceUtil::addNode(*atomSpace,VARIABLE_NODE, (ActionParameter::ParamValueToString(paramValue)).c_str()));
}
}
string* str = boost::get<string>(realValue);
Entity* entity ;
Vector* vector;
Rotation* rot;
FuzzyIntervalInt* fuzzyInt;
FuzzyIntervalFloat* fuzzyFloat;
if( str)
{
if (StringManipulator::isNumber(*str))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, str->c_str()));
}
else
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,CONCEPT_NODE, str->c_str()));
}
}
else if ( entity = boost::get<Entity>(realValue))
{
Handle entityHandle = AtomSpaceUtil::getEntityHandle(*atomSpace,entity->id);
OC_ASSERT((entityHandle != Handle::UNDEFINED),
"OCPlanner::generatePMNodeFromeAParamValue: cannot find the handle for this entity : %s is invalid.\n",
ActionParameter::ParamValueToString(*realValue).c_str());
results.push_back(entityHandle);
}
else if (vector = boost::get<Vector>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(vector->x).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(vector->y).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(vector->z).c_str()));
}
else if (rot = boost::get<Rotation>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(rot->pitch).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(rot->roll).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(rot->yaw).c_str()));
}
else if (fuzzyInt = boost::get<FuzzyIntervalInt>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyInt->bound_low).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyInt->bound_high).c_str()));
}
else if (fuzzyFloat = boost::get<FuzzyIntervalFloat>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyFloat->bound_low).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyFloat->bound_high).c_str()));
}
return results;
}
// return an EvaluationLink with variableNodes for using Pattern Matching
Handle Inquery::generatePMLinkFromAState(State* state, RuleNode* ruleNode)
{
// Create evaluationlink used by pattern matcher
Handle predicateNode = AtomSpaceUtil::addNode(*atomSpace,PREDICATE_NODE, state->name().c_str());
HandleSeq predicateListLinkOutgoings;
// add all the stateOwners
for (vector<ParamValue>::iterator ownerIt = state->stateOwnerList.begin(); ownerIt != state->stateOwnerList.end(); ++ ownerIt)
{
HandleSeq handles = generatePMNodeFromeAParamValue(*ownerIt,ruleNode);
OC_ASSERT((handles.size() != 0),
"OCPlanner::generatePMLinkFromAState: cannot generate handle for this state owner value for state: %s is invalid.\n",
state->name().c_str());
predicateListLinkOutgoings.insert(predicateListLinkOutgoings.end(), handles.begin(),handles.end());
}
// add the state value
HandleSeq handles = generatePMNodeFromeAParamValue(state->stateVariable->getValue(),ruleNode);
predicateListLinkOutgoings.insert(predicateListLinkOutgoings.end(), handles.begin(),handles.end());
Handle predicateListLink = AtomSpaceUtil::addLink(*atomSpace,LIST_LINK, predicateListLinkOutgoings);
HandleSeq evalLinkOutgoings;
evalLinkOutgoings.push_back(predicateNode);
evalLinkOutgoings.push_back(predicateListLink);
Handle hEvalLink = AtomSpaceUtil::addLink(*atomSpace,EVALUATION_LINK, evalLinkOutgoings);
return hEvalLink;
}
HandleSeq Inquery::findCandidatesByPatternMatching(RuleNode *ruleNode, vector<int> &stateIndexes, vector<string>& varNames)
{
HandleSeq variableNodes,andLinkOutgoings, implicationLinkOutgoings, bindLinkOutgoings;
set<string> allVariables;
for(int i = 0; i < stateIndexes.size() ; ++ i)
{
int index = stateIndexes[i];
list<UngroundedVariablesInAState>::iterator it = ruleNode->curUngroundedVariables.begin();
for(int x = 0; x <= index; ++x)
++ it;
UngroundedVariablesInAState& record = (UngroundedVariablesInAState&)(*it);
vector<string> tempVariables;
set_union(allVariables.begin(),allVariables.end(),record.vars.begin(),record.vars.end(),tempVariables.begin());
allVariables = set<string>(tempVariables.begin(),tempVariables.end());
andLinkOutgoings.push_back(record.PMLink);
}
set<string>::iterator itor = allVariables.begin();
for(;itor != allVariables.end(); ++ itor)
{
variableNodes.push_back(AtomSpaceUtil::addNode(*atomSpace,VARIABLE_NODE,(*itor).c_str()));
varNames.push_back((*itor).c_str());
}
Handle hVariablesListLink = AtomSpaceUtil::addLink(*atomSpace,LIST_LINK,variableNodes);
Handle hAndLink = AtomSpaceUtil::addLink(*atomSpace,AND_LINK,andLinkOutgoings);
implicationLinkOutgoings.push_back(hAndLink);
implicationLinkOutgoings.push_back(hVariablesListLink);
Handle hImplicationLink = AtomSpaceUtil::addLink(*atomSpace,IMPLICATION_LINK, implicationLinkOutgoings);
bindLinkOutgoings.push_back(hVariablesListLink);
bindLinkOutgoings.push_back(hImplicationLink);
Handle hBindLink = AtomSpaceUtil::addLink(*atomSpace,BIND_LINK, bindLinkOutgoings);
// Run pattern matcher
PatternMatch pm;
pm.set_atomspace(atomSpace);
Handle hResultListLink = pm.bindlink(hBindLink);
// Get result
// Note: Don't forget remove the hResultListLink
HandleSeq resultSet = atomSpace->getOutgoing(hResultListLink);
atomSpace->removeAtom(hResultListLink);
return resultSet;
}
Fixed bug for generate a node for one matching condition for using Pattern Matching, from a state in the precondition list of a RuleNode
/*
* OCPlanner.cc
*
* Copyright (C) 2012 by OpenCog Foundation
* Written by Shujing KE
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <set>
#include <boost/variant.hpp>
#include <opencog/util/oc_assert.h>
#include <opencog/util/StringManipulator.h>
#include <opencog/spacetime/SpaceTime.h>
#include <opencog/spacetime/SpaceServer.h>
#include <opencog/spatial/3DSpaceMap/Entity3D.h>
#include <opencog/spatial/3DSpaceMap/Octree3DMapManager.h>
#include <opencog/spatial/3DSpaceMap/Block3DMapUtil.h>
#include <opencog/spatial/3DSpaceMap/Pathfinder3D.h>
#include <opencog/embodiment/Control/PerceptionActionInterface/ActionParamType.h>
#include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h>
#include <opencog/server/BaseServer.h>
#include <opencog/query/PatternMatch.h>
#include <opencog/query/PatternMatchEngine.h>
#include <opencog/util/StringManipulator.h>
#include <opencog/atomspace/atom_types.h>
#include <opencog/embodiment/AtomSpaceExtensions/atom_types.h>
#include <opencog/nlp/types/atom_types.h>
#include <opencog/spacetime/atom_types.h>
#include <opencog/embodiment/Control/PerceptionActionInterface/PAI.h>
#include "Inquery.h"
#include "OCPlanner.h"
using namespace opencog::oac;
using namespace opencog::pai;
AtomSpace* Inquery::atomSpace= 0;
SpaceServer::SpaceMap* Inquery::spaceMap = 0;
void Inquery::init(AtomSpace* _atomSpace)
{
atomSpace = _atomSpace;
spaceMap = &(spaceServer().getLatestMap());
}
void Inquery::setSpaceMap(SpaceServer::SpaceMap *_spaceMap)
{
spaceMap = _spaceMap;
}
void Inquery::reSetSpaceMap()
{
spaceMap = &(spaceServer().getLatestMap());
}
ParamValue Inquery::getParamValueFromAtomspace( State& state)
{
vector<ParamValue> stateOwnerList = state.stateOwnerList;
Entity entity1, entity2, entity3;
Handle a, b, c = Handle::UNDEFINED;
entity1 = boost::get<Entity>(stateOwnerList[0]);
a = AtomSpaceUtil::getEntityHandle(*atomSpace,entity1.id);
if(stateOwnerList.size() > 1)
{
entity2 = boost::get<Entity>(stateOwnerList[1]);
b = AtomSpaceUtil::getEntityHandle(*atomSpace,entity2.id);
}
if(stateOwnerList.size() > 2)
{
entity3 = boost::get<Entity>(stateOwnerList[2]);
c = AtomSpaceUtil::getEntityHandle(*atomSpace,entity3.id);
}
Handle evalLink = AtomSpaceUtil::getLatestEvaluationLink(*atomSpace, state.name(), a , b, c);
if (evalLink == Handle::UNDEFINED)
{
logger().error("Inquery::getParamValueFromAtomspace : There is no evaluation link for predicate: "
+ state.name() );
return UNDEFINED_VALUE;
}
Handle listLink = atomSpace->getOutgoing(evalLink, 1);
if (listLink== Handle::UNDEFINED)
{
logger().error("Inquery::getParamValueFromAtomspace : There is no list link for the Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
// So the value node is always after the owners.
// We need to know how many owners this state has
// the size of the state owners
int ownerSize = stateOwnerList.size();
HandleSeq listLinkOutgoings = atomSpace->getOutgoing(listLink);
if ( listLinkOutgoings.size() == ownerSize )
{ // some evalLink without a value node, e.g.:
/* It means these two objects are far away from each other, we'll get its value from its truthvalue
(EvaluationLink (stv 1 0.0012484394) (av -14 1 0)
(PredicateNode "far" (av -21 1 0))
(ListLink (av -12 0 0)
(ObjectNode "id_-1522462" (av -12 1 0))
(ObjectNode "id_5640" (av -20 0 0))
)
)
*/
// then the state value type should be boolean
if (state.getActionParamType().getCode() != BOOLEAN_CODE)
{
logger().error("Inquery::getParamValueFromAtomspace : There is no value node for this Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
if (atomSpace->getMean(evalLink) > 0.5)
return "true";
else
return "false";
}
else if ( listLinkOutgoings.size() - ownerSize == 1)
{
// some state only has one value node, which is the most common state,e.g.:
// (EvaluationLink (stv 1 0.0012484394) (av -23 1 0)
// (PredicateNode "material" (av -23 1 0))
// (ListLink (av -23 0 0)
// (StructureNode "id_CHUNK_2_2_0_BLOCK_15_6_104" (av -23 0 0))
// (ConceptNode "Stone" (av -23 0 0))
// )
// )
Handle valueHandle = atomSpace->getOutgoing(listLink, ownerSize);// the ownerSize is just the index of the value node
if ( valueHandle == Handle::UNDEFINED )
{
logger().error("Inquery::getParamValueFromAtomspace : There is no list link for the Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
// this kind of state value can only be bool,int,float,string or entity
switch (state.getActionParamType().getCode())
{
case BOOLEAN_CODE:
case INT_CODE:
case FLOAT_CODE:
case STRING_CODE:
return (atomSpace->getName(valueHandle));
case ENTITY_CODE:
return Entity(atomSpace->getName(valueHandle) ,PAI::getObjectTypeFromHandle(*atomSpace, valueHandle));
default:
logger().error("Inquery::getParamValueFromAtomspace : There is more than one value node for the Evaluation Link: "
+ state.name());
return UNDEFINED_VALUE;
}
}
else if (listLinkOutgoings.size() - ownerSize == 2)
{
// when this state value is fuzzy number interval, there will be 2 number nodes for the value
Handle valueHandle1 = atomSpace->getOutgoing(listLink, ownerSize);// the ownerSize is just the index of the value node
Handle valueHandle2 = atomSpace->getOutgoing(listLink, ownerSize + 1);
if ( (valueHandle1 == Handle::UNDEFINED) || (valueHandle2 == Handle::UNDEFINED) )
{
logger().error("Inquery::getParamValueFromAtomspace :Type error: The value type is fuzzy interval, but there are not 2 number nodes in its listlink , for the Evaluation Link: "
+ state.name() );
return UNDEFINED_VALUE;
}
switch (state.getActionParamType().getCode())
{
case FUZZY_INTERVAL_INT_CODE:
{
int lowInt = atoi(atomSpace->getName(valueHandle1).c_str());
int highInt = atoi(atomSpace->getName(valueHandle2).c_str());
return FuzzyIntervalInt(lowInt,highInt);
}
case FUZZY_INTERVAL_FLOAT_CODE:
{
float lowf = atof(atomSpace->getName(valueHandle1).c_str());
float highf = atof(atomSpace->getName(valueHandle2).c_str());
return FuzzyIntervalFloat(lowf,highf);
}
default:
logger().error("Inquery::getParamValueFromAtomspace : Type error: There is 2 number nodes for the Evaluation Link: "
+ state.name() + ". But it is neighter a fuzzyIntervalInt nor a fuzzyIntervalFLoat");
return UNDEFINED_VALUE;
}
}
else if(listLinkOutgoings.size() - ownerSize == 3)
{// when it is a vector, it will have 3 number nodes, e.g.:
// the link and nodes are like this:
// (EvaluationLink (av -23 0 0) // this the "valueH"
// (PredicateNode "AGISIM_position" (av -23 1 0))
// (ListLink (av -23 0 0)
// (StructureNode "id_CHUNK_2_2_0_BLOCK_6_6_104" (av -23 0 0))
// (NumberNode "54.5" (av -23 0 0))
// (NumberNode "54.5" (av -23 0 0))
// (NumberNode "104.5" (av -23 0 0))
// )
// )
Handle valueHandle1 = atomSpace->getOutgoing(listLink, ownerSize);// the ownerSize is just the index of the value node
Handle valueHandle2 = atomSpace->getOutgoing(listLink, ownerSize + 1);
Handle valueHandle3 = atomSpace->getOutgoing(listLink, ownerSize + 2);
if ( (valueHandle1 == Handle::UNDEFINED) || (valueHandle2 == Handle::UNDEFINED) || (valueHandle3 == Handle::UNDEFINED) )
{
logger().error("Inquery::getParamValueFromAtomspace :Type error: The value type is vector or rotation,but there are not 3 number nodes in its listlink , for the Evaluation Link: "
+ state.name() );
return UNDEFINED_VALUE;
}
double x = atof(atomSpace->getName(valueHandle1).c_str());
double y = atof(atomSpace->getName(valueHandle2).c_str());
double z = atof(atomSpace->getName(valueHandle3).c_str());
switch (state.getActionParamType().getCode())
{
case VECTOR_CODE:
return Vector(x,y,z);
case ROTATION_CODE:
return Rotation(x,y,z);
default:
logger().error("Inquery::getParamValueFromAtomspace : Type error: There is 3 number nodes for the Evaluation Link: "
+ state.name() + ". But it is neighter a Vector nor a Rotation");
return UNDEFINED_VALUE;
}
}
else
{
logger().error("Inquery::getParamValueFromAtomspace :the number of value nodes is invalid for the Evaluation Link: "
+ state.name() );
return UNDEFINED_VALUE;
}
}
ParamValue Inquery::getParamValueFromHandle(string var, Handle& valueH)
{
switch (opencog::oac::GetVariableType(var))
{
case ENTITY_CODE:
{
return Entity(atomSpace->getName(valueH) ,PAI::getObjectTypeFromHandle(*atomSpace, valueH));
}
case BOOLEAN_CODE:
{
string strVar = atomSpace->getName(valueH);
if ((strVar == "true")||(strVar == "True"))
return opencog::oac::SV_TRUE;
else
return opencog::oac::SV_FALSE;
}
case INT_CODE:
case FLOAT_CODE:
case STRING_CODE:
{
return (atomSpace->getName(valueH));
}
case VECTOR_CODE:
{
Handle valueHandle1 = atomSpace->getOutgoing(valueH, 0);// the ownerSize is just the index of the value node
Handle valueHandle2 = atomSpace->getOutgoing(valueH, 1);
Handle valueHandle3 = atomSpace->getOutgoing(valueH, 2);
if ( (valueHandle1 == Handle::UNDEFINED) || (valueHandle2 == Handle::UNDEFINED) || (valueHandle3 == Handle::UNDEFINED) )
{
logger().error("Inquery::getParamValueFromHandle :Type error: The value type is vector or rotation,but there are not 3 number nodes in its listlink ");
return UNDEFINED_VALUE;
}
double x = atof(atomSpace->getName(valueHandle1).c_str());
double y = atof(atomSpace->getName(valueHandle2).c_str());
double z = atof(atomSpace->getName(valueHandle3).c_str());
return Vector(x,y,z);
}
default:
{
return UNDEFINED_VALUE;
}
}
}
ParamValue Inquery::inqueryDistance(const vector<ParamValue>& stateOwnerList)
{
double d = DOUBLE_MAX;
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
Entity* entity1 = boost::get<Entity>(&var1);
Entity* entity2 = boost::get<Entity>(&var2);
Vector* vector2 = boost::get<Vector>(&var2);
if (entity1 && entity2)
{
d = spaceMap->distanceBetween(entity1->id, entity2->id);
}
else if (entity1 && vector2)
{
d = spaceMap->distanceBetween(entity1->id, SpaceServer::SpaceMapPoint(vector2->x,vector2->y,vector2->z));
}
return (opencog::toString(d));
}
ParamValue Inquery::inqueryExist(const vector<ParamValue>& stateOwnerList)
{
Entity entity = boost::get<Entity>(stateOwnerList.front());
// if (! entity)
// return "false";
bool is_exist = spaceMap->containsObject(entity.id);
return (opencog::toString(is_exist));
}
ParamValue Inquery::inqueryAtLocation(const vector<ParamValue>& stateOwnerList)
{
ParamValue obj = stateOwnerList.front();
Entity* entity = boost::get<Entity>(&obj);
Handle h = AtomSpaceUtil::getObjectHandle(*atomSpace, entity->id);
SpaceServer::SpaceMapPoint pos;
if (h == Handle::UNDEFINED) // not an object, let try if it's an agent
h = AtomSpaceUtil::getAgentHandle(*atomSpace, entity->id);
if(h == Handle::UNDEFINED)
return Vector(DOUBLE_MAX,DOUBLE_MAX,DOUBLE_MAX);
else
pos = spaceMap->getObjectLocation(h);
if (pos == SpaceServer::SpaceMapPoint::ZERO)
return Vector(DOUBLE_MAX,DOUBLE_MAX,DOUBLE_MAX);
else
return Vector(pos.x,pos.y,pos.z);
}
ParamValue Inquery::inqueryIsSolid(const vector<ParamValue>& stateOwnerList)
{
ParamValue var = stateOwnerList.back();
Vector* pos = boost::get<Vector>(&var);
if (! pos)
return "false";
if (spaceMap->checkIsSolid((int)pos->x,(int)pos->y,(int)pos->z))
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsStandable(const vector<ParamValue>& stateOwnerList)
{
ParamValue var = stateOwnerList.back();
Vector* pos = boost::get<Vector>(&var);
if (! pos)
return "false";
if (spaceMap->checkStandable((int)pos->x,(int)pos->y,(int)pos->z))
return "true";
else
return "false";
}
ParamValue Inquery::inqueryExistPath(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
spatial::BlockVector pos1,pos2;
Entity* entity1 = boost::get<Entity>(&var1);
if (entity1)
pos1 = spaceMap->getObjectLocation(entity1->id);
else
{
Vector* v1 = boost::get<Vector>(&var1);
pos1 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
}
Entity* entity2 = boost::get<Entity>(&var2);
if (entity2)
pos2 = spaceMap->getObjectLocation(entity2->id);
else
{
Vector* v2 = boost::get<Vector>(&var2);
pos2 = SpaceServer::SpaceMapPoint(v2->x,v2->y,v2->z);
}
if (SpaceServer::SpaceMap::isTwoPositionsAdjacent(pos1, pos2))
{
if (spatial::Pathfinder3D::checkNeighbourAccessable(spaceMap, pos1, pos2.x - pos1.x, pos2.y - pos1.y, pos2.z - pos1.z))
return "true";
else
return "false";
}
vector<spatial::BlockVector> path;
spatial::BlockVector nearestPos;
if (spatial::Pathfinder3D::AStar3DPathFinder(spaceMap, pos1, pos2, path, nearestPos))
return "true";
else
return "false";
}
vector<ParamValue> Inquery::inqueryNearestAccessiblePosition(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
spatial::BlockVector pos1,pos2;
vector<ParamValue> values;
Entity* entity1 = boost::get<Entity>(&var1);
if (entity1)
pos1 = spaceMap->getObjectLocation(entity1->id);
else
{
Vector* v1 = boost::get<Vector>(&var1);
pos1 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
}
Entity* entity2 = boost::get<Entity>(&var2);
if (entity2)
pos2 = spaceMap->getObjectLocation(entity2->id);
else
{
Vector* v2 = boost::get<Vector>(&var2);
pos2 = SpaceServer::SpaceMapPoint(v2->x,v2->y,v2->z);
}
spatial::BlockVector nearestPos;
vector<spatial::BlockVector> path;
spatial::Pathfinder3D::AStar3DPathFinder(spaceMap, pos1, pos2, path, nearestPos);
if (nearestPos != pos1)
{
values.push_back(Vector(nearestPos.x,nearestPos.y,nearestPos.z));
}
return values;
}
vector<ParamValue> Inquery::inqueryAdjacentPosition(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
spatial::BlockVector pos1;
vector<ParamValue> values;
Entity* entity1 = boost::get<Entity>(&var1);
if (entity1)
pos1 = spaceMap->getObjectLocation(entity1->id);
else
{
Vector* v1 = boost::get<Vector>(&var1);
pos1 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
}
// return 24 adjacent neighbour locations (26 neighbours except the pos above and below)
int x,y,z;
for (x = -1; x <= 1; x ++)
for (y = -1; x <= 1; x ++)
for (z = -1; z <= 1; z ++)
{
if ( (x == 0) && (y == 0))
continue;
values.push_back(Vector(pos1.x + x,pos1.y + y,pos1.z + z));
}
return values;
}
vector<ParamValue> Inquery::inqueryStandableNearbyAccessablePosition(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList[1];
spatial::BlockVector pos1, pos2;
vector<ParamValue> values;
Entity* entity1 = boost::get<Entity>(&var1);
pos1 = spaceMap->getObjectLocation(entity1->id);
Vector* v1 = boost::get<Vector>(&var2);
pos2 = SpaceServer::SpaceMapPoint(v1->x,v1->y,v1->z);
// return 24 adjacent neighbour locations (26 neighbours except the pos above and below)
int x,y,z;
for (x = -1; x <= 1; x ++)
for (y = -1; x <= 1; x ++)
for (z = -1; z <= 1; z ++)
{
if ( (x == 0) && (y == 0))
{
continue;
SpaceServer::SpaceMapPoint curPos(pos2.x + x,pos2.y + y,pos2.z + z);
// check if it's standable
if (! spaceMap->checkStandable(curPos))
continue;
// check if there is a path from the avatar to this position
if (SpaceServer::SpaceMap::isTwoPositionsAdjacent(pos1, pos2))
{
if (spatial::Pathfinder3D::checkNeighbourAccessable(spaceMap, pos1, pos2.x - pos1.x, pos2.y - pos1.y, pos2.z - pos1.z))
{
values.push_back(Vector(curPos.x,curPos.y,curPos.z));
}
continue;
}
vector<spatial::BlockVector> path;
spatial::BlockVector nearestPos;
if (spatial::Pathfinder3D::AStar3DPathFinder(spaceMap, pos1, pos2, path, nearestPos))
values.push_back(Vector(curPos.x,curPos.y,curPos.z));
}
}
return values;
}
ParamValue Inquery::inqueryIsAdjacent(const vector<ParamValue>& stateOwnerList)
{
ParamValue var1 = stateOwnerList.front();
ParamValue var2 = stateOwnerList.back();
Vector* v1 = boost::get<Vector>(&var1);
Vector* v2 = boost::get<Vector>(&var2);
if ((!v1)||(!v2))
return "false";
SpaceServer::SpaceMapPoint pos1(v1->x,v1->y,v1->z);
SpaceServer::SpaceMapPoint pos2(v2->x,v2->y,v2->z);
if (SpaceServer::SpaceMap::isTwoPositionsAdjacent(pos1, pos2))
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsAbove(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::ABOVE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsBeside(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::BESIDE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsNear(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::NEAR) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsFar(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::FAR_) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsTouching(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::TOUCHING) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsInside(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::INSIDE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsOutside(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::OUTSIDE) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsBelow(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::BELOW) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsLeftOf(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::LEFT_OF) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsRightOf(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::RIGHT_OF) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsBehind(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::BEHIND) != relations.end())
return "true";
else
return "false";
}
ParamValue Inquery::inqueryIsInFrontOf(const vector<ParamValue>& stateOwnerList)
{
set<spatial::SPATIAL_RELATION> relations = getSpatialRelations(stateOwnerList);
if (relations.find(spatial::IN_FRONT_OF) != relations.end())
return "true";
else
return "false";
}
set<spatial::SPATIAL_RELATION> Inquery::getSpatialRelations(const vector<ParamValue>& stateOwnerList)
{
// set<spatial::SPATIAL_RELATION> empty;
Entity entity1 = boost::get<Entity>( stateOwnerList.front());
Entity entity2 = boost::get<Entity>( stateOwnerList[1]);
Entity entity3 = boost::get<Entity>( stateOwnerList[2]);
/*
if ((entity1 == 0)||(entity2 == 0))
return empty;
*/
string entity3ID = "";
if (stateOwnerList.size() == 3)
{
Entity entity3 = boost::get<Entity>( stateOwnerList.back());
entity3ID = entity3.id;
}
return spaceMap->computeSpatialRelations(entity1.id, entity2.id, entity3.id);
}
// find atoms by given condition, by patern mactcher.
HandleSeq Inquery::findAllObjectsByGivenCondition(State* state)
{
HandleSeq results;
Handle inhSecondOutgoing;
HandleSeq evalNonFirstOutgoings;
switch (state->getActionParamType().getCode())
{
case ENTITY_CODE:
{
const Entity& entity = state->stateVariable->getEntityValue();
inhSecondOutgoing = AtomSpaceUtil::getEntityHandle(*atomSpace,entity.id);
if (inhSecondOutgoing == Handle::UNDEFINED)
{
logger().warn("Inquery::findAllObjectsByGivenCondition : There is no Entity Node for this state value: "
+ state->name());
return results; // return empty result
}
evalNonFirstOutgoings.push_back(inhSecondOutgoing);
break;
}
case INT_CODE:
case FLOAT_CODE:
{
const string& value = state->stateVariable->getStringValue();
inhSecondOutgoing = AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,value.c_str());
evalNonFirstOutgoings.push_back(inhSecondOutgoing);
break;
}
case STRING_CODE:
{
const string& value = state->stateVariable->getStringValue();
inhSecondOutgoing = AtomSpaceUtil::addNode(*atomSpace,CONCEPT_NODE,value.c_str());
evalNonFirstOutgoings.push_back(inhSecondOutgoing);
break;
}
case VECTOR_CODE:
{
const Vector& vector = state->stateVariable->getVectorValue();
// for vector and rotation, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,opencog::toString(vector.x).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,opencog::toString(vector.y).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE,opencog::toString(vector.z).c_str()));
break;
}
case ROTATION_CODE:
{
const Rotation & value= state->stateVariable->getRotationValue();
// for vector, rotation and fuzzy values, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.pitch).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.roll).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.yaw).c_str()));
break;
}
case FUZZY_INTERVAL_INT_CODE:
{
const FuzzyIntervalInt& value = state->stateVariable->getFuzzyIntervalIntValue();
// for vector, rotation and fuzzy values, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_low).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_high).c_str()));
break;
}
case FUZZY_INTERVAL_FLOAT_CODE:
{
const FuzzyIntervalFloat& value = state->stateVariable->getFuzzyIntervalFloatValue();
// for vector, rotation and fuzzy values, the inheritancelink do not apply
// so only for evaluationlink
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_low).c_str()));
evalNonFirstOutgoings.push_back(AtomSpaceUtil::addNode(*atomSpace, NUMBER_NODE, opencog::toString(value.bound_high).c_str()));
break;
}
}
// first search from EvaluationLinks
if (evalNonFirstOutgoings.size() > 0)
results = AtomSpaceUtil::getNodesByEvaluationLink(*atomSpace,state->name(),evalNonFirstOutgoings);
// if cannot find any result, search from InheritanceLink
if ((results.size() == 0) && (inhSecondOutgoing != Handle::UNDEFINED))
results = AtomSpaceUtil::getNodesByInheritanceLink(*atomSpace, inhSecondOutgoing);
return results;
}
HandleSeq Inquery::generatePMNodeFromeAParamValue(ParamValue& paramValue, RuleNode* ruleNode)
{
HandleSeq results;
ParamValue* realValue;
if (! Rule::isParamValueUnGrounded(paramValue))
{
// this stateOwner is const, just add it
realValue = ¶mValue;
}
else
{
// this stateOwner is a variable
// look for the value of this variable in the current grounding parameter map
ParamGroundedMapInARule::iterator paramMapIt = ruleNode->currentBindingsFromForwardState.find(ActionParameter::ParamValueToString(paramValue));
if (paramMapIt != ruleNode->currentBindingsFromForwardState.end())
{
// found it in the current groundings, so just add it as a const
realValue = &(paramMapIt->second);
}
else
{
// it has not been grounded, so add it as a variable node
results.push_back(AtomSpaceUtil::addNode(*atomSpace,VARIABLE_NODE, (ActionParameter::ParamValueToString(paramValue)).c_str()));
return results;
}
}
string* str = boost::get<string>(realValue);
Entity* entity ;
Vector* vector;
Rotation* rot;
FuzzyIntervalInt* fuzzyInt;
FuzzyIntervalFloat* fuzzyFloat;
if( str)
{
if (StringManipulator::isNumber(*str))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, str->c_str()));
}
else
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,CONCEPT_NODE, str->c_str()));
}
}
else if ( entity = boost::get<Entity>(realValue))
{
Handle entityHandle = AtomSpaceUtil::getEntityHandle(*atomSpace,entity->id);
OC_ASSERT((entityHandle != Handle::UNDEFINED),
"OCPlanner::generatePMNodeFromeAParamValue: cannot find the handle for this entity : %s is invalid.\n",
ActionParameter::ParamValueToString(*realValue).c_str());
results.push_back(entityHandle);
}
else if (vector = boost::get<Vector>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(vector->x).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(vector->y).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(vector->z).c_str()));
}
else if (rot = boost::get<Rotation>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(rot->pitch).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(rot->roll).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(rot->yaw).c_str()));
}
else if (fuzzyInt = boost::get<FuzzyIntervalInt>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyInt->bound_low).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyInt->bound_high).c_str()));
}
else if (fuzzyFloat = boost::get<FuzzyIntervalFloat>(realValue))
{
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyFloat->bound_low).c_str()));
results.push_back(AtomSpaceUtil::addNode(*atomSpace,NUMBER_NODE, opencog::toString(fuzzyFloat->bound_high).c_str()));
}
return results;
}
// return an EvaluationLink with variableNodes for using Pattern Matching
Handle Inquery::generatePMLinkFromAState(State* state, RuleNode* ruleNode)
{
// Create evaluationlink used by pattern matcher
Handle predicateNode = AtomSpaceUtil::addNode(*atomSpace,PREDICATE_NODE, state->name().c_str());
HandleSeq predicateListLinkOutgoings;
// add all the stateOwners
for (vector<ParamValue>::iterator ownerIt = state->stateOwnerList.begin(); ownerIt != state->stateOwnerList.end(); ++ ownerIt)
{
HandleSeq handles = generatePMNodeFromeAParamValue(*ownerIt,ruleNode);
OC_ASSERT((handles.size() != 0),
"OCPlanner::generatePMLinkFromAState: cannot generate handle for this state owner value for state: %s is invalid.\n",
state->name().c_str());
predicateListLinkOutgoings.insert(predicateListLinkOutgoings.end(), handles.begin(),handles.end());
}
// add the state value
HandleSeq handles = generatePMNodeFromeAParamValue(state->stateVariable->getValue(),ruleNode);
predicateListLinkOutgoings.insert(predicateListLinkOutgoings.end(), handles.begin(),handles.end());
Handle predicateListLink = AtomSpaceUtil::addLink(*atomSpace,LIST_LINK, predicateListLinkOutgoings);
HandleSeq evalLinkOutgoings;
evalLinkOutgoings.push_back(predicateNode);
evalLinkOutgoings.push_back(predicateListLink);
Handle hEvalLink = AtomSpaceUtil::addLink(*atomSpace,EVALUATION_LINK, evalLinkOutgoings);
return hEvalLink;
}
HandleSeq Inquery::findCandidatesByPatternMatching(RuleNode *ruleNode, vector<int> &stateIndexes, vector<string>& varNames)
{
HandleSeq variableNodes,andLinkOutgoings, implicationLinkOutgoings, bindLinkOutgoings;
set<string> allVariables;
for(int i = 0; i < stateIndexes.size() ; ++ i)
{
int index = stateIndexes[i];
list<UngroundedVariablesInAState>::iterator it = ruleNode->curUngroundedVariables.begin();
for(int x = 0; x <= index; ++x)
++ it;
UngroundedVariablesInAState& record = (UngroundedVariablesInAState&)(*it);
vector<string> tempVariables;
set_union(allVariables.begin(),allVariables.end(),record.vars.begin(),record.vars.end(),tempVariables.begin());
allVariables = set<string>(tempVariables.begin(),tempVariables.end());
andLinkOutgoings.push_back(record.PMLink);
}
set<string>::iterator itor = allVariables.begin();
for(;itor != allVariables.end(); ++ itor)
{
variableNodes.push_back(AtomSpaceUtil::addNode(*atomSpace,VARIABLE_NODE,(*itor).c_str()));
varNames.push_back((*itor).c_str());
}
Handle hVariablesListLink = AtomSpaceUtil::addLink(*atomSpace,LIST_LINK,variableNodes);
Handle hAndLink = AtomSpaceUtil::addLink(*atomSpace,AND_LINK,andLinkOutgoings);
implicationLinkOutgoings.push_back(hAndLink);
implicationLinkOutgoings.push_back(hVariablesListLink);
Handle hImplicationLink = AtomSpaceUtil::addLink(*atomSpace,IMPLICATION_LINK, implicationLinkOutgoings);
bindLinkOutgoings.push_back(hVariablesListLink);
bindLinkOutgoings.push_back(hImplicationLink);
Handle hBindLink = AtomSpaceUtil::addLink(*atomSpace,BIND_LINK, bindLinkOutgoings);
// Run pattern matcher
PatternMatch pm;
pm.set_atomspace(atomSpace);
Handle hResultListLink = pm.bindlink(hBindLink);
// Get result
// Note: Don't forget remove the hResultListLink
HandleSeq resultSet = atomSpace->getOutgoing(hResultListLink);
atomSpace->removeAtom(hResultListLink);
return resultSet;
}
|
#pragma once
#include "base/macros.hpp"
#include OPTIONAL_HEADER
#include <deque>
#include <map>
#include <memory>
#include "base/not_null.hpp"
#include "geometry/named_quantities.hpp"
#include "serialization/physics.pb.h"
namespace principia {
using geometry::Instant;
namespace physics {
// This traits class must export declarations similar to the following:
//
// using TimelineConstIterator = ...;
// static Instant const& time(TimelineConstIterator const it);
//
// TimelineConstIterator must be an STL-like iterator in the timeline of
// Tr4jectory. |time()| must return the corresponding time.
template<typename Tr4jectory>
struct ForkableTraits;
// This template represents a trajectory which is forkable and iterable. It
// uses CRTP to achieve static polymorphism on the return type of the member
// functions: we want them to return Tr4jectory, not Forkable, so that the
// clients don't have to down_cast.
template<typename Tr4jectory>
class Forkable {
public:
// An iterator into the timeline of the trajectory. Must be STL-like.
// Beware, if these iterators are invalidated all the guarantees of Forkable
// are void.
using TimelineConstIterator =
typename ForkableTraits<Tr4jectory>::TimelineConstIterator;
Forkable() = default;
virtual ~Forkable() = default;
// Deletes the child trajectory denoted by |*trajectory|, which must be a
// pointer previously returned by NewFork for this object. Nulls
// |*trajectory|.
void DeleteFork(not_null<Tr4jectory**> const trajectory);
// Returns true if this is a root trajectory.
bool is_root() const;
// Returns the root trajectory.
not_null<Tr4jectory const*> root() const;
not_null<Tr4jectory*> root();
// Returns the fork time for a nonroot trajectory and null for a root
// trajectory.
std::experimental::optional<Instant> ForkTime() const;
// A base class for iterating over the timeline of a trajectory, taking forks
// into account.
class Iterator {
public:
bool operator==(Iterator const& right) const;
bool operator!=(Iterator const& right) const;
Iterator& operator++();
Iterator& operator--();
// Returns the point in the timeline that is denoted by this iterator.
TimelineConstIterator current() const;
// Returns the (most forked) trajectory to which this iterator applies.
not_null<Tr4jectory const*> trajectory() const;
private:
Iterator() = default;
// We want a single representation for an end iterator. In various places
// we may end up with |current_| at the end of its timeline, but that
// timeline is not the "most forked" one. This function normalizes this
// object so that there is only one entry in the |ancestry_| (the "most
// forked" one) and |current_| is at its end.
void NormalizeIfEnd();
// Checks that this object verifies the invariants enforced by
// NormalizeIfEnd and dies if it doesn't.
void CheckNormalizedIfEnd();
// |ancestry_| is never empty. |current_| is an iterator in the timeline
// for |ancestry_.front()|. |current_| may be at end.
TimelineConstIterator current_;
std::deque<not_null<Tr4jectory const*>> ancestry_; // Pointers not owned.
template<typename Tr4jectory>
friend class Forkable;
};
Iterator Begin() const;
Iterator End() const;
Iterator Find(Instant const& time) const;
Iterator LowerBound(Instant const& time) const;
// Constructs an Iterator by wrapping the timeline iterator
// |position_in_ancestor_timeline| which must be an iterator in the timeline
// of |ancestor|. |ancestor| must be an ancestor of this trajectory
// (it may be this object). |position_in_ancestor_timeline| may only be at
// end if it is an iterator in this object (and ancestor is this object).
// TODO(phl): This is only used for |Begin|. Unclear if it needs to be a
// separate method.
Iterator Wrap(
not_null<const Tr4jectory*> const ancestor,
TimelineConstIterator const position_in_ancestor_timeline) const;
void WritePointerToMessage(
not_null<serialization::Trajectory::Pointer*> const message) const;
// |trajectory| must be a root.
static not_null<Tr4jectory*> ReadPointerFromMessage(
serialization::Trajectory::Pointer const& message,
not_null<Tr4jectory*> const trajectory);
protected:
// The API that must be implemented by subclasses.
// TODO(phl): Try to reduce this API. Forkable should probably not modify the
// timeline.
// Must return |this| of the proper type
virtual not_null<Tr4jectory*> that() = 0;
virtual not_null<Tr4jectory const*> that() const = 0;
// STL-like operations.
virtual TimelineConstIterator timeline_begin() const = 0;
virtual TimelineConstIterator timeline_end() const = 0;
virtual TimelineConstIterator timeline_find(Instant const& time) const = 0;
virtual TimelineConstIterator timeline_lower_bound(
Instant const& time) const = 0;
virtual bool timeline_empty() const = 0;
protected:
// The API that subclasses may use to implement their public operations.
// Creates a new child trajectory forked at time |time|, and returns it. The
// child trajectory shares its data with the current trajectory for times less
// than or equal to |time|. It may be changed independently from the parent
// trajectory for any time (strictly) greater than |time|. The child
// trajectory is owned by its parent trajectory. Deleting the parent
// trajectory deletes all child trajectories. |time| must be one of the times
// of this trajectory, and must be at or after the fork time, if any.
not_null<Tr4jectory*> NewFork(Instant const& time);
// Deletes all forks for times (strictly) greater than |time|. |time| must be
// at or after the fork time of this trajectory, if any.
void DeleteAllForksAfter(Instant const& time);
// Deletes all forks for times less than or equal to |time|. This trajectory
// must be a root.
void DeleteAllForksBefore(Instant const& time);
// This trajectory need not be a root.
void WriteSubTreeToMessage(
not_null<serialization::Trajectory*> const message) const;
void FillSubTreeFromMessage(serialization::Trajectory const& message);
private:
// There may be several forks starting from the same time, hence the multimap.
using Children = std::multimap<Instant, Tr4jectory>;
// Null for a root.
Tr4jectory* parent_ = nullptr;
// This iterator is never at |end()|.
std::experimental::optional<typename Children::const_iterator>
position_in_parent_children_;
// This iterator is at |end()| if the fork time is not in the parent timeline,
// i.e. is the parent timeline's own fork time.
std::experimental::optional<TimelineConstIterator>
position_in_parent_timeline_;
Children children_;
};
} // namespace physics
} // namespace principia
#include "physics/forkable_body.hpp"
Rename shadowed typename.
#pragma once
#include "base/macros.hpp"
#include OPTIONAL_HEADER
#include <deque>
#include <map>
#include <memory>
#include "base/not_null.hpp"
#include "geometry/named_quantities.hpp"
#include "serialization/physics.pb.h"
namespace principia {
using geometry::Instant;
namespace physics {
// This traits class must export declarations similar to the following:
//
// using TimelineConstIterator = ...;
// static Instant const& time(TimelineConstIterator const it);
//
// TimelineConstIterator must be an STL-like iterator in the timeline of
// Tr4jectory. |time()| must return the corresponding time.
template<typename Tr4jectory>
struct ForkableTraits;
// This template represents a trajectory which is forkable and iterable. It
// uses CRTP to achieve static polymorphism on the return type of the member
// functions: we want them to return Tr4jectory, not Forkable, so that the
// clients don't have to down_cast.
template<typename Tr4jectory>
class Forkable {
public:
// An iterator into the timeline of the trajectory. Must be STL-like.
// Beware, if these iterators are invalidated all the guarantees of Forkable
// are void.
using TimelineConstIterator =
typename ForkableTraits<Tr4jectory>::TimelineConstIterator;
Forkable() = default;
virtual ~Forkable() = default;
// Deletes the child trajectory denoted by |*trajectory|, which must be a
// pointer previously returned by NewFork for this object. Nulls
// |*trajectory|.
void DeleteFork(not_null<Tr4jectory**> const trajectory);
// Returns true if this is a root trajectory.
bool is_root() const;
// Returns the root trajectory.
not_null<Tr4jectory const*> root() const;
not_null<Tr4jectory*> root();
// Returns the fork time for a nonroot trajectory and null for a root
// trajectory.
std::experimental::optional<Instant> ForkTime() const;
// A base class for iterating over the timeline of a trajectory, taking forks
// into account.
class Iterator {
public:
bool operator==(Iterator const& right) const;
bool operator!=(Iterator const& right) const;
Iterator& operator++();
Iterator& operator--();
// Returns the point in the timeline that is denoted by this iterator.
TimelineConstIterator current() const;
// Returns the (most forked) trajectory to which this iterator applies.
not_null<Tr4jectory const*> trajectory() const;
private:
Iterator() = default;
// We want a single representation for an end iterator. In various places
// we may end up with |current_| at the end of its timeline, but that
// timeline is not the "most forked" one. This function normalizes this
// object so that there is only one entry in the |ancestry_| (the "most
// forked" one) and |current_| is at its end.
void NormalizeIfEnd();
// Checks that this object verifies the invariants enforced by
// NormalizeIfEnd and dies if it doesn't.
void CheckNormalizedIfEnd();
// |ancestry_| is never empty. |current_| is an iterator in the timeline
// for |ancestry_.front()|. |current_| may be at end.
TimelineConstIterator current_;
std::deque<not_null<Tr4jectory const*>> ancestry_; // Pointers not owned.
template<typename Trajectory>
friend class Forkable;
};
Iterator Begin() const;
Iterator End() const;
Iterator Find(Instant const& time) const;
Iterator LowerBound(Instant const& time) const;
// Constructs an Iterator by wrapping the timeline iterator
// |position_in_ancestor_timeline| which must be an iterator in the timeline
// of |ancestor|. |ancestor| must be an ancestor of this trajectory
// (it may be this object). |position_in_ancestor_timeline| may only be at
// end if it is an iterator in this object (and ancestor is this object).
// TODO(phl): This is only used for |Begin|. Unclear if it needs to be a
// separate method.
Iterator Wrap(
not_null<const Tr4jectory*> const ancestor,
TimelineConstIterator const position_in_ancestor_timeline) const;
void WritePointerToMessage(
not_null<serialization::Trajectory::Pointer*> const message) const;
// |trajectory| must be a root.
static not_null<Tr4jectory*> ReadPointerFromMessage(
serialization::Trajectory::Pointer const& message,
not_null<Tr4jectory*> const trajectory);
protected:
// The API that must be implemented by subclasses.
// TODO(phl): Try to reduce this API. Forkable should probably not modify the
// timeline.
// Must return |this| of the proper type
virtual not_null<Tr4jectory*> that() = 0;
virtual not_null<Tr4jectory const*> that() const = 0;
// STL-like operations.
virtual TimelineConstIterator timeline_begin() const = 0;
virtual TimelineConstIterator timeline_end() const = 0;
virtual TimelineConstIterator timeline_find(Instant const& time) const = 0;
virtual TimelineConstIterator timeline_lower_bound(
Instant const& time) const = 0;
virtual bool timeline_empty() const = 0;
protected:
// The API that subclasses may use to implement their public operations.
// Creates a new child trajectory forked at time |time|, and returns it. The
// child trajectory shares its data with the current trajectory for times less
// than or equal to |time|. It may be changed independently from the parent
// trajectory for any time (strictly) greater than |time|. The child
// trajectory is owned by its parent trajectory. Deleting the parent
// trajectory deletes all child trajectories. |time| must be one of the times
// of this trajectory, and must be at or after the fork time, if any.
not_null<Tr4jectory*> NewFork(Instant const& time);
// Deletes all forks for times (strictly) greater than |time|. |time| must be
// at or after the fork time of this trajectory, if any.
void DeleteAllForksAfter(Instant const& time);
// Deletes all forks for times less than or equal to |time|. This trajectory
// must be a root.
void DeleteAllForksBefore(Instant const& time);
// This trajectory need not be a root.
void WriteSubTreeToMessage(
not_null<serialization::Trajectory*> const message) const;
void FillSubTreeFromMessage(serialization::Trajectory const& message);
private:
// There may be several forks starting from the same time, hence the multimap.
using Children = std::multimap<Instant, Tr4jectory>;
// Null for a root.
Tr4jectory* parent_ = nullptr;
// This iterator is never at |end()|.
std::experimental::optional<typename Children::const_iterator>
position_in_parent_children_;
// This iterator is at |end()| if the fork time is not in the parent timeline,
// i.e. is the parent timeline's own fork time.
std::experimental::optional<TimelineConstIterator>
position_in_parent_timeline_;
Children children_;
};
} // namespace physics
} // namespace principia
#include "physics/forkable_body.hpp"
|
/***************************************************************************
* pythonscript.cpp
* This file is part of the KDE project
* copyright (C)2004-2005 by Sebastian Sauer (mail@dipe.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
* This program 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
* Library General Public License for more details.
* You should have received a copy of the GNU Library General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
***************************************************************************/
#include "pythonscript.h"
#include "pythonmodule.h"
#include "pythoninterpreter.h"
//#include "../api/object.h"
//#include "../api/list.h"
//#include "../main/manager.h"
#include "../main/scriptcontainer.h"
//#include "../api/qtobject.h"
//#include "../api/interpreter.h"
#include <kdebug.h>
using namespace Kross::Python;
namespace Kross { namespace Python {
//! @internal
class PythonScriptPrivate
{
public:
Py::Module* m_module;
Py::Object* m_code;
QStringList m_functions;
QStringList m_classes;
//QMap<QString, Kross::Api::Object::Ptr> m_functions;
//QMap<QString, Kross::Api::Object::Ptr> m_classes;
//QValueList<Kross::Api::Object::Ptr> m_classinstances;
};
}}
PythonScript::PythonScript(Kross::Api::Interpreter* interpreter, Kross::Api::ScriptContainer* scriptcontainer)
: Kross::Api::Script(interpreter, scriptcontainer)
, d(new PythonScriptPrivate())
{
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
kdDebug() << "PythonScript::PythonScript() Constructor." << endl;
#endif
d->m_module = 0;
d->m_code = 0;
}
PythonScript::~PythonScript()
{
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
kdDebug() << "PythonScript::~PythonScript() Destructor." << endl;
#endif
finalize();
delete d;
}
void PythonScript::initialize()
{
finalize();
try {
PyObject* pymod = PyModule_New((char*)m_scriptcontainer->getName().latin1());
d->m_module = new Py::Module(pymod, true);
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
if(d->m_module)
kdDebug() << QString("PythonScript::initialize() module='%1' refcount='%2'").arg(d->m_module->as_string().c_str()).arg(d->m_module->reference_count()) << endl;
#endif
// Compile the python script code. It will be later on request
// executed. That way we cache the compiled code.
PyObject* code = 0;
bool restricted = ((PythonInterpreter*)m_interpreter)->getOption("restricted", QVariant((bool)true)).toBool();
if(restricted) {
// Use the RestrictedPython module wrapped by the PythonSecurity class.
/*TODO
code = m_interpreter->m_security->compile_restricted(
m_scriptcontainer->getCode(),
m_scriptcontainer->getName(),
"exec"
);
*/
}
else {
// Just compile the code without any restrictions.
code = Py_CompileString(
(char*)m_scriptcontainer->getCode().latin1(),
(char*)m_scriptcontainer->getName().latin1(),
Py_file_input
);
}
if(! code)
throw Py::Exception();
d->m_code = new Py::Object(code, true);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(Py::Exception());
throw Kross::Api::RuntimeException(i18n("Failed to compile python code: %1").arg(errobj.as_string().c_str()));
}
}
void PythonScript::finalize()
{
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
if(d->m_module)
kdDebug() << QString("PythonScript::finalize() module='%1' refcount='%2'").arg(d->m_module->as_string().c_str()).arg(d->m_module->reference_count()) << endl;
#endif
delete d->m_module; d->m_module = 0;
delete d->m_code; d->m_code = 0;
d->m_functions.clear();
d->m_classes.clear();
}
const QStringList& PythonScript::getFunctionNames()
{
if(! d->m_module) initialize();
return d->m_functions;
/*
QStringList list;
Py::List l = d->m_module->getDict().keys();
int length = l.length();
for(Py::List::size_type i = 0; i < length; ++i)
list.append( l[i].str().as_string().c_str() );
return list;
*/
}
Kross::Api::Object::Ptr PythonScript::execute()
{
if(! d->m_module)
initialize();
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
kdDebug() << QString("PythonScript::execute()") << endl;
#endif
try {
Py::Dict mainmoduledict = ((PythonInterpreter*)m_interpreter)->m_module->getDict();
PyObject* pyresult = PyEval_EvalCode(
(PyCodeObject*)d->m_code->ptr(),
mainmoduledict.ptr(),
d->m_module->getDict().ptr()
);
if(! pyresult)
throw Py::Exception();
Py::Object result(pyresult, true);
kdDebug()<<"PythonScript::execute() result="<<result.as_string().c_str()<<endl;
Py::Dict moduledict( d->m_module->getDict().ptr() );
for(Py::Dict::iterator it = moduledict.begin(); it != moduledict.end(); ++it) {
Py::Dict::value_type vt(*it);
if(PyClass_Check( vt.second.ptr() )) {
kdDebug() << QString("PythonScript::execute() class '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_classes.append( vt.first.as_string().c_str() );
}
else if(vt.second.isCallable()) {
kdDebug() << QString("PythonScript::execute() function '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_functions.append( vt.first.as_string().c_str() );
}
}
Kross::Api::Object::Ptr r = PythonExtension::toObject(result);
return r;
}
catch(Py::Exception& e) {
throw Kross::Api::RuntimeException(i18n("Failed to execute python code: %1").arg(Py::value(e).as_string().c_str()));
}
/*
if(! d->m_module) initialize();
try {
Py::Dict mainmoduledict = ((PythonInterpreter*)m_interpreter)->m_module->getDict();
PyObject* pyrun = PyRun_String(
(char*)m_scriptcontainer->getCode().latin1(),
Py_file_input,
mainmoduledict.ptr(),
d->m_module->getDict().ptr()
);
if(! pyrun) {
Py::Object errobj = Py::value(Py::Exception()); // get last error
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
Py::Object run(pyrun, true); // the run-object takes care of freeing our pyrun pyobject.
//kdDebug() << QString("PythonScript::execute --------------------------- 1") << endl;
Py::Dict moduledict( d->m_module->getDict().ptr() );
for(Py::Dict::iterator it = moduledict.begin(); it != moduledict.end(); ++it) {
Py::Dict::value_type vt(*it);
if(PyClass_Check( vt.second.ptr() )) {
kdDebug() << QString("PythonScript::execute() class '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_classes.append( vt.first.as_string().c_str() );
}
else if(vt.second.isCallable()) {
kdDebug() << QString("PythonScript::execute() function '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_functions.append( vt.first.as_string().c_str() );
}
*/
/*
QString s;
if(vt.second.isCallable()) s += "isCallable ";
if(vt.second.isDict()) s += "isDict ";
if(vt.second.isList()) s += "isList ";
if(vt.second.isMapping()) s += "isMapping ";
if(vt.second.isNumeric()) s += "isNumeric ";
if(vt.second.isSequence()) s += "isSequence ";
if(vt.second.isTrue()) s += "isTrue ";
if(vt.second.isInstance()) s += "isInstance ";
if(PyClass_Check( vt.second.ptr() )) s += "vt.second.isClass ";
Py::String rf = vt.first.repr();
Py::String rs = vt.second.repr();
kdDebug() << QString("PythonScript::execute d->m_module->getDict() rs='%1' vt.first='%2' rf='%3' test='%4' s='%5'")
.arg(rs.as_string().c_str())
.arg(vt.first.as_string().c_str())
.arg(rf.as_string().c_str())
.arg("")
.arg(s) << endl;
//m_objects.replace(vt.first.repr().as_string().c_str(), vt.second);
if(PyClass_Check( vt.second.ptr() )) {
//PyObject *aclarg = Py_BuildValue("(s)", rs.as_string().c_str());
PyObject *pyinst = PyInstance_New(vt.second.ptr(), 0, 0);//aclarg, 0);
//Py_DECREF(aclarg);
if (pyinst == 0)
kdDebug() << QString("PythonScript::execute PyInstance_New() returned NULL !!!") << endl;
else {
Py::Object inst(pyinst, true);
kdDebug() << QString("====> PythonScript::execute inst='%1'").arg(inst.as_string().c_str()) << endl;
}
}
*/
/*
}
//kdDebug() << QString("PythonScript::execute --------------------------- 2") << endl;
//kdDebug() << QString("PythonScript::execute() PyRun_String='%1'").arg(run.str().as_string().c_str()) << endl;
return PythonExtension::toObject(run);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(e);
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
*/
}
Kross::Api::Object::Ptr PythonScript::callFunction(const QString& name, Kross::Api::List::Ptr args)
{
if(! d->m_module)
throw Kross::Api::RuntimeException(i18n("Script not initialized."));
try {
kdDebug() << QString("PythonScript::callFunction(%1, %2)")
.arg(name)
.arg(args ? QString::number(args->count()) : QString("NULL"))
<< endl;
Py::Dict moduledict = d->m_module->getDict();
// Try to determinate the function we like to execute.
PyObject* func = PyDict_GetItemString(moduledict.ptr(), name.latin1());
if( (! d->m_functions.contains(name)) || (! func) )
throw Kross::Api::AttributeException(i18n("No such function '%1'.").arg(name));
Py::Callable funcobject(func, true); // the funcobject takes care of freeing our func pyobject.
// Check if the object is really a function and therefore callable.
if(! funcobject.isCallable())
throw Kross::Api::AttributeException(i18n("Function is not callable."));
// Call the function.
Py::Object result = funcobject.apply(PythonExtension::toPyTuple(args));
/* TESTCASE
//PyObject* pDict = PyObject_GetAttrString(func,"__dict__");
//kdDebug()<<"INT => "<< PyObject_IsInstance(func,d->m_module->ptr()) <<endl;
//( PyCallable_Check(func)){//PyModule_CheckExact(func)){//PyModule_Check(func)){//PyMethod_Check(func)){//PyMethod_Function(func)){//PyInstance_Check(func) )
kdDebug() << QString("PythonScript::callFunction result='%1' type='%2'").arg(result.as_string().c_str()).arg(result.type().as_string().c_str()) << endl;
if(result.isInstance()) {
kdDebug() << ">>> IS_INSTANCE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl;
}
if(result.isCallable()) {
kdDebug() << ">>> IS_CALLABLE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl;
}
*/
return PythonExtension::toObject(result);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(e);
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
}
const QStringList& PythonScript::getClassNames()
{
if(! d->m_module) initialize();
return d->m_classes;
}
Kross::Api::Object::Ptr PythonScript::classInstance(const QString& name)
{
if(! d->m_module)
throw Kross::Api::RuntimeException(i18n("Script not initialized."));
try {
Py::Dict moduledict = d->m_module->getDict();
// Try to determinate the class.
PyObject* pyclass = PyDict_GetItemString(moduledict.ptr(), name.latin1());
if( (! d->m_classes.contains(name)) || (! pyclass) )
throw Kross::Api::AttributeException(i18n("No such class '%1'.").arg(name));
//PyClass_Check( vt.second.ptr() ))
//PyObject *aclarg = Py_BuildValue("(s)", rs.as_string().c_str());
PyObject *pyobj = PyInstance_New(pyclass, 0, 0);//aclarg, 0);
if(! pyobj)
throw Kross::Api::AttributeException(i18n("Failed to create instance of class '%1'.").arg(name));
Py::Object classobject(pyobj, true);
kdDebug() << QString("====> PythonScript::classInstance() inst='%1'").arg(classobject.as_string().c_str()) << endl;
return PythonExtension::toObject(classobject);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(e);
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
}
/// @internal
svn path=/trunk/koffice/kexi/scripting/python/; revision=436956
/***************************************************************************
* pythonscript.cpp
* This file is part of the KDE project
* copyright (C)2004-2005 by Sebastian Sauer (mail@dipe.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
* This program 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
* Library General Public License for more details.
* You should have received a copy of the GNU Library General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
***************************************************************************/
#include "pythonscript.h"
#include "pythonmodule.h"
#include "pythoninterpreter.h"
//#include "../api/object.h"
//#include "../api/list.h"
//#include "../main/manager.h"
#include "../main/scriptcontainer.h"
//#include "../api/qtobject.h"
//#include "../api/interpreter.h"
#include <kdebug.h>
using namespace Kross::Python;
namespace Kross { namespace Python {
/// @internal
class PythonScriptPrivate
{
public:
Py::Module* m_module;
Py::Object* m_code;
QStringList m_functions;
QStringList m_classes;
//QMap<QString, Kross::Api::Object::Ptr> m_functions;
//QMap<QString, Kross::Api::Object::Ptr> m_classes;
//QValueList<Kross::Api::Object::Ptr> m_classinstances;
};
}}
PythonScript::PythonScript(Kross::Api::Interpreter* interpreter, Kross::Api::ScriptContainer* scriptcontainer)
: Kross::Api::Script(interpreter, scriptcontainer)
, d(new PythonScriptPrivate())
{
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
kdDebug() << "PythonScript::PythonScript() Constructor." << endl;
#endif
d->m_module = 0;
d->m_code = 0;
}
PythonScript::~PythonScript()
{
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
kdDebug() << "PythonScript::~PythonScript() Destructor." << endl;
#endif
finalize();
delete d;
}
void PythonScript::initialize()
{
finalize();
try {
PyObject* pymod = PyModule_New((char*)m_scriptcontainer->getName().latin1());
d->m_module = new Py::Module(pymod, true);
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
if(d->m_module)
kdDebug() << QString("PythonScript::initialize() module='%1' refcount='%2'").arg(d->m_module->as_string().c_str()).arg(d->m_module->reference_count()) << endl;
#endif
// Compile the python script code. It will be later on request
// executed. That way we cache the compiled code.
PyObject* code = 0;
bool restricted = ((PythonInterpreter*)m_interpreter)->getOption("restricted", QVariant((bool)true)).toBool();
if(restricted) {
// Use the RestrictedPython module wrapped by the PythonSecurity class.
/*TODO
code = m_interpreter->m_security->compile_restricted(
m_scriptcontainer->getCode(),
m_scriptcontainer->getName(),
"exec"
);
*/
}
else {
// Just compile the code without any restrictions.
code = Py_CompileString(
(char*)m_scriptcontainer->getCode().latin1(),
(char*)m_scriptcontainer->getName().latin1(),
Py_file_input
);
}
if(! code)
throw Py::Exception();
d->m_code = new Py::Object(code, true);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(Py::Exception());
throw Kross::Api::RuntimeException(i18n("Failed to compile python code: %1").arg(errobj.as_string().c_str()));
}
}
void PythonScript::finalize()
{
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
if(d->m_module)
kdDebug() << QString("PythonScript::finalize() module='%1' refcount='%2'").arg(d->m_module->as_string().c_str()).arg(d->m_module->reference_count()) << endl;
#endif
delete d->m_module; d->m_module = 0;
delete d->m_code; d->m_code = 0;
d->m_functions.clear();
d->m_classes.clear();
}
const QStringList& PythonScript::getFunctionNames()
{
if(! d->m_module) initialize();
return d->m_functions;
/*
QStringList list;
Py::List l = d->m_module->getDict().keys();
int length = l.length();
for(Py::List::size_type i = 0; i < length; ++i)
list.append( l[i].str().as_string().c_str() );
return list;
*/
}
Kross::Api::Object::Ptr PythonScript::execute()
{
if(! d->m_module)
initialize();
#ifdef KROSS_PYTHON_SCRIPT_DEBUG
kdDebug() << QString("PythonScript::execute()") << endl;
#endif
try {
Py::Dict mainmoduledict = ((PythonInterpreter*)m_interpreter)->m_module->getDict();
PyObject* pyresult = PyEval_EvalCode(
(PyCodeObject*)d->m_code->ptr(),
mainmoduledict.ptr(),
d->m_module->getDict().ptr()
);
if(! pyresult)
throw Py::Exception();
Py::Object result(pyresult, true);
kdDebug()<<"PythonScript::execute() result="<<result.as_string().c_str()<<endl;
Py::Dict moduledict( d->m_module->getDict().ptr() );
for(Py::Dict::iterator it = moduledict.begin(); it != moduledict.end(); ++it) {
Py::Dict::value_type vt(*it);
if(PyClass_Check( vt.second.ptr() )) {
kdDebug() << QString("PythonScript::execute() class '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_classes.append( vt.first.as_string().c_str() );
}
else if(vt.second.isCallable()) {
kdDebug() << QString("PythonScript::execute() function '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_functions.append( vt.first.as_string().c_str() );
}
}
Kross::Api::Object::Ptr r = PythonExtension::toObject(result);
return r;
}
catch(Py::Exception& e) {
throw Kross::Api::RuntimeException(i18n("Failed to execute python code: %1").arg(Py::value(e).as_string().c_str()));
}
/*
if(! d->m_module) initialize();
try {
Py::Dict mainmoduledict = ((PythonInterpreter*)m_interpreter)->m_module->getDict();
PyObject* pyrun = PyRun_String(
(char*)m_scriptcontainer->getCode().latin1(),
Py_file_input,
mainmoduledict.ptr(),
d->m_module->getDict().ptr()
);
if(! pyrun) {
Py::Object errobj = Py::value(Py::Exception()); // get last error
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
Py::Object run(pyrun, true); // the run-object takes care of freeing our pyrun pyobject.
//kdDebug() << QString("PythonScript::execute --------------------------- 1") << endl;
Py::Dict moduledict( d->m_module->getDict().ptr() );
for(Py::Dict::iterator it = moduledict.begin(); it != moduledict.end(); ++it) {
Py::Dict::value_type vt(*it);
if(PyClass_Check( vt.second.ptr() )) {
kdDebug() << QString("PythonScript::execute() class '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_classes.append( vt.first.as_string().c_str() );
}
else if(vt.second.isCallable()) {
kdDebug() << QString("PythonScript::execute() function '%1' added.").arg(vt.first.as_string().c_str()) << endl;
d->m_functions.append( vt.first.as_string().c_str() );
}
*/
/*
QString s;
if(vt.second.isCallable()) s += "isCallable ";
if(vt.second.isDict()) s += "isDict ";
if(vt.second.isList()) s += "isList ";
if(vt.second.isMapping()) s += "isMapping ";
if(vt.second.isNumeric()) s += "isNumeric ";
if(vt.second.isSequence()) s += "isSequence ";
if(vt.second.isTrue()) s += "isTrue ";
if(vt.second.isInstance()) s += "isInstance ";
if(PyClass_Check( vt.second.ptr() )) s += "vt.second.isClass ";
Py::String rf = vt.first.repr();
Py::String rs = vt.second.repr();
kdDebug() << QString("PythonScript::execute d->m_module->getDict() rs='%1' vt.first='%2' rf='%3' test='%4' s='%5'")
.arg(rs.as_string().c_str())
.arg(vt.first.as_string().c_str())
.arg(rf.as_string().c_str())
.arg("")
.arg(s) << endl;
//m_objects.replace(vt.first.repr().as_string().c_str(), vt.second);
if(PyClass_Check( vt.second.ptr() )) {
//PyObject *aclarg = Py_BuildValue("(s)", rs.as_string().c_str());
PyObject *pyinst = PyInstance_New(vt.second.ptr(), 0, 0);//aclarg, 0);
//Py_DECREF(aclarg);
if (pyinst == 0)
kdDebug() << QString("PythonScript::execute PyInstance_New() returned NULL !!!") << endl;
else {
Py::Object inst(pyinst, true);
kdDebug() << QString("====> PythonScript::execute inst='%1'").arg(inst.as_string().c_str()) << endl;
}
}
*/
/*
}
//kdDebug() << QString("PythonScript::execute --------------------------- 2") << endl;
//kdDebug() << QString("PythonScript::execute() PyRun_String='%1'").arg(run.str().as_string().c_str()) << endl;
return PythonExtension::toObject(run);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(e);
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
*/
}
Kross::Api::Object::Ptr PythonScript::callFunction(const QString& name, Kross::Api::List::Ptr args)
{
if(! d->m_module)
throw Kross::Api::RuntimeException(i18n("Script not initialized."));
try {
kdDebug() << QString("PythonScript::callFunction(%1, %2)")
.arg(name)
.arg(args ? QString::number(args->count()) : QString("NULL"))
<< endl;
Py::Dict moduledict = d->m_module->getDict();
// Try to determinate the function we like to execute.
PyObject* func = PyDict_GetItemString(moduledict.ptr(), name.latin1());
if( (! d->m_functions.contains(name)) || (! func) )
throw Kross::Api::AttributeException(i18n("No such function '%1'.").arg(name));
Py::Callable funcobject(func, true); // the funcobject takes care of freeing our func pyobject.
// Check if the object is really a function and therefore callable.
if(! funcobject.isCallable())
throw Kross::Api::AttributeException(i18n("Function is not callable."));
// Call the function.
Py::Object result = funcobject.apply(PythonExtension::toPyTuple(args));
/* TESTCASE
//PyObject* pDict = PyObject_GetAttrString(func,"__dict__");
//kdDebug()<<"INT => "<< PyObject_IsInstance(func,d->m_module->ptr()) <<endl;
//( PyCallable_Check(func)){//PyModule_CheckExact(func)){//PyModule_Check(func)){//PyMethod_Check(func)){//PyMethod_Function(func)){//PyInstance_Check(func) )
kdDebug() << QString("PythonScript::callFunction result='%1' type='%2'").arg(result.as_string().c_str()).arg(result.type().as_string().c_str()) << endl;
if(result.isInstance()) {
kdDebug() << ">>> IS_INSTANCE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl;
}
if(result.isCallable()) {
kdDebug() << ">>> IS_CALLABLE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl;
}
*/
return PythonExtension::toObject(result);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(e);
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
}
const QStringList& PythonScript::getClassNames()
{
if(! d->m_module) initialize();
return d->m_classes;
}
Kross::Api::Object::Ptr PythonScript::classInstance(const QString& name)
{
if(! d->m_module)
throw Kross::Api::RuntimeException(i18n("Script not initialized."));
try {
Py::Dict moduledict = d->m_module->getDict();
// Try to determinate the class.
PyObject* pyclass = PyDict_GetItemString(moduledict.ptr(), name.latin1());
if( (! d->m_classes.contains(name)) || (! pyclass) )
throw Kross::Api::AttributeException(i18n("No such class '%1'.").arg(name));
//PyClass_Check( vt.second.ptr() ))
//PyObject *aclarg = Py_BuildValue("(s)", rs.as_string().c_str());
PyObject *pyobj = PyInstance_New(pyclass, 0, 0);//aclarg, 0);
if(! pyobj)
throw Kross::Api::AttributeException(i18n("Failed to create instance of class '%1'.").arg(name));
Py::Object classobject(pyobj, true);
kdDebug() << QString("====> PythonScript::classInstance() inst='%1'").arg(classobject.as_string().c_str()) << endl;
return PythonExtension::toObject(classobject);
}
catch(Py::Exception& e) {
Py::Object errobj = Py::value(e);
throw Kross::Api::RuntimeException(i18n("Python Exception: %1").arg(errobj.as_string().c_str()));
}
}
|
/*
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Native glue for Java class org.conscrypt.NativeCrypto
*/
#define TO_STRING1(x) #x
#define TO_STRING(x) TO_STRING1(x)
#ifndef JNI_JARJAR_PREFIX
#ifndef CONSCRYPT_NOT_UNBUNDLED
#define CONSCRYPT_UNBUNDLED
#endif
#define JNI_JARJAR_PREFIX
#endif
#define LOG_TAG "NativeCrypto"
#include <arpa/inet.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef CONSCRYPT_UNBUNDLED
#include <dlfcn.h>
#endif
#include <jni.h>
#include <openssl/asn1t.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#if defined(OPENSSL_IS_BORINGSSL)
#include <openssl/aead.h>
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
#if defined(GOOGLE_INTERNAL)
#include "third_party/openssl/openssl/src/crypto/ecdsa/ecs_locl.h"
#else
#include "crypto/ecdsa/ecs_locl.h"
#endif
#endif
#ifndef CONSCRYPT_UNBUNDLED
/* If we're compiled unbundled from Android system image, we use the
* CompatibilityCloseMonitor
*/
#include "AsynchronousCloseMonitor.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "cutils/log.h"
#else
#include "log_compat.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
#else
#define NATIVE_METHOD(className, functionName, signature) \
{ (char*) #functionName, (char*) signature, reinterpret_cast<void*>(className ## _ ## functionName) }
#define REGISTER_NATIVE_METHODS(jni_class_name) \
RegisterNativeMethods(env, jni_class_name, gMethods, arraysize(gMethods))
#endif
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#include "NetFd.h"
#include "macros.h"
#undef WITH_JNI_TRACE
#undef WITH_JNI_TRACE_MD
#undef WITH_JNI_TRACE_DATA
/*
* How to use this for debugging with Wireshark:
*
* 1. Pull lines from logcat to a file that looks like (without quotes):
* "RSA Session-ID:... Master-Key:..." <CR>
* "RSA Session-ID:... Master-Key:..." <CR>
* <etc>
* 2. Start Wireshark
* 3. Go to Edit -> Preferences -> SSL -> (Pre-)Master-Key log and fill in
* the file you put the lines in above.
* 4. Follow the stream that corresponds to the desired "Session-ID" in
* the Server Hello.
*/
#undef WITH_JNI_TRACE_KEYS
#ifdef WITH_JNI_TRACE
#define JNI_TRACE(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__))
#else
#define JNI_TRACE(...) ((void)0)
#endif
#ifdef WITH_JNI_TRACE_MD
#define JNI_TRACE_MD(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__));
#else
#define JNI_TRACE_MD(...) ((void)0)
#endif
// don't overwhelm logcat
#define WITH_JNI_TRACE_DATA_CHUNK_SIZE 512
static JavaVM* gJavaVM;
static jclass cryptoUpcallsClass;
static jclass openSslInputStreamClass;
static jclass nativeRefClass;
static jclass byteArrayClass;
static jclass calendarClass;
static jclass objectClass;
static jclass objectArrayClass;
static jclass integerClass;
static jclass inputStreamClass;
static jclass outputStreamClass;
static jclass stringClass;
static jfieldID nativeRef_context;
static jmethodID calendar_setMethod;
static jmethodID inputStream_readMethod;
static jmethodID integer_valueOfMethod;
static jmethodID openSslInputStream_readLineMethod;
static jmethodID outputStream_writeMethod;
static jmethodID outputStream_flushMethod;
struct OPENSSL_Delete {
void operator()(void* p) const {
OPENSSL_free(p);
}
};
typedef UniquePtr<unsigned char, OPENSSL_Delete> Unique_OPENSSL_str;
struct BIO_Delete {
void operator()(BIO* p) const {
BIO_free_all(p);
}
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
struct BIGNUM_Delete {
void operator()(BIGNUM* p) const {
BN_free(p);
}
};
typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
struct BN_CTX_Delete {
void operator()(BN_CTX* ctx) const {
BN_CTX_free(ctx);
}
};
typedef UniquePtr<BN_CTX, BN_CTX_Delete> Unique_BN_CTX;
struct ASN1_INTEGER_Delete {
void operator()(ASN1_INTEGER* p) const {
ASN1_INTEGER_free(p);
}
};
typedef UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> Unique_ASN1_INTEGER;
struct DH_Delete {
void operator()(DH* p) const {
DH_free(p);
}
};
typedef UniquePtr<DH, DH_Delete> Unique_DH;
struct DSA_Delete {
void operator()(DSA* p) const {
DSA_free(p);
}
};
typedef UniquePtr<DSA, DSA_Delete> Unique_DSA;
struct EC_GROUP_Delete {
void operator()(EC_GROUP* p) const {
EC_GROUP_free(p);
}
};
typedef UniquePtr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP;
struct EC_POINT_Delete {
void operator()(EC_POINT* p) const {
EC_POINT_clear_free(p);
}
};
typedef UniquePtr<EC_POINT, EC_POINT_Delete> Unique_EC_POINT;
struct EC_KEY_Delete {
void operator()(EC_KEY* p) const {
EC_KEY_free(p);
}
};
typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
struct EVP_MD_CTX_Delete {
void operator()(EVP_MD_CTX* p) const {
EVP_MD_CTX_destroy(p);
}
};
typedef UniquePtr<EVP_MD_CTX, EVP_MD_CTX_Delete> Unique_EVP_MD_CTX;
#if defined(OPENSSL_IS_BORINGSSL)
struct EVP_AEAD_CTX_Delete {
void operator()(EVP_AEAD_CTX* p) const {
EVP_AEAD_CTX_cleanup(p);
delete p;
}
};
typedef UniquePtr<EVP_AEAD_CTX, EVP_AEAD_CTX_Delete> Unique_EVP_AEAD_CTX;
#endif
struct EVP_CIPHER_CTX_Delete {
void operator()(EVP_CIPHER_CTX* p) const {
EVP_CIPHER_CTX_free(p);
}
};
typedef UniquePtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_Delete> Unique_EVP_CIPHER_CTX;
struct EVP_PKEY_Delete {
void operator()(EVP_PKEY* p) const {
EVP_PKEY_free(p);
}
};
typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
struct PKCS8_PRIV_KEY_INFO_Delete {
void operator()(PKCS8_PRIV_KEY_INFO* p) const {
PKCS8_PRIV_KEY_INFO_free(p);
}
};
typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
struct RSA_Delete {
void operator()(RSA* p) const {
RSA_free(p);
}
};
typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
struct ASN1_BIT_STRING_Delete {
void operator()(ASN1_BIT_STRING* p) const {
ASN1_BIT_STRING_free(p);
}
};
typedef UniquePtr<ASN1_BIT_STRING, ASN1_BIT_STRING_Delete> Unique_ASN1_BIT_STRING;
struct ASN1_OBJECT_Delete {
void operator()(ASN1_OBJECT* p) const {
ASN1_OBJECT_free(p);
}
};
typedef UniquePtr<ASN1_OBJECT, ASN1_OBJECT_Delete> Unique_ASN1_OBJECT;
struct ASN1_GENERALIZEDTIME_Delete {
void operator()(ASN1_GENERALIZEDTIME* p) const {
ASN1_GENERALIZEDTIME_free(p);
}
};
typedef UniquePtr<ASN1_GENERALIZEDTIME, ASN1_GENERALIZEDTIME_Delete> Unique_ASN1_GENERALIZEDTIME;
struct SSL_Delete {
void operator()(SSL* p) const {
SSL_free(p);
}
};
typedef UniquePtr<SSL, SSL_Delete> Unique_SSL;
struct SSL_CTX_Delete {
void operator()(SSL_CTX* p) const {
SSL_CTX_free(p);
}
};
typedef UniquePtr<SSL_CTX, SSL_CTX_Delete> Unique_SSL_CTX;
struct X509_Delete {
void operator()(X509* p) const {
X509_free(p);
}
};
typedef UniquePtr<X509, X509_Delete> Unique_X509;
struct X509_NAME_Delete {
void operator()(X509_NAME* p) const {
X509_NAME_free(p);
}
};
typedef UniquePtr<X509_NAME, X509_NAME_Delete> Unique_X509_NAME;
struct X509_EXTENSIONS_Delete {
void operator()(X509_EXTENSIONS* p) const {
sk_X509_EXTENSION_pop_free(p, X509_EXTENSION_free);
}
};
typedef UniquePtr<X509_EXTENSIONS, X509_EXTENSIONS_Delete> Unique_X509_EXTENSIONS;
#if !defined(OPENSSL_IS_BORINGSSL)
struct PKCS7_Delete {
void operator()(PKCS7* p) const {
PKCS7_free(p);
}
};
typedef UniquePtr<PKCS7, PKCS7_Delete> Unique_PKCS7;
#endif
struct sk_SSL_CIPHER_Delete {
void operator()(STACK_OF(SSL_CIPHER)* p) const {
// We don't own SSL_CIPHER references, so no need for pop_free
sk_SSL_CIPHER_free(p);
}
};
typedef UniquePtr<STACK_OF(SSL_CIPHER), sk_SSL_CIPHER_Delete> Unique_sk_SSL_CIPHER;
struct sk_X509_Delete {
void operator()(STACK_OF(X509)* p) const {
sk_X509_pop_free(p, X509_free);
}
};
typedef UniquePtr<STACK_OF(X509), sk_X509_Delete> Unique_sk_X509;
#if defined(OPENSSL_IS_BORINGSSL)
struct sk_X509_CRL_Delete {
void operator()(STACK_OF(X509_CRL)* p) const {
sk_X509_CRL_pop_free(p, X509_CRL_free);
}
};
typedef UniquePtr<STACK_OF(X509_CRL), sk_X509_CRL_Delete> Unique_sk_X509_CRL;
#endif
struct sk_X509_NAME_Delete {
void operator()(STACK_OF(X509_NAME)* p) const {
sk_X509_NAME_pop_free(p, X509_NAME_free);
}
};
typedef UniquePtr<STACK_OF(X509_NAME), sk_X509_NAME_Delete> Unique_sk_X509_NAME;
struct sk_ASN1_OBJECT_Delete {
void operator()(STACK_OF(ASN1_OBJECT)* p) const {
sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
}
};
typedef UniquePtr<STACK_OF(ASN1_OBJECT), sk_ASN1_OBJECT_Delete> Unique_sk_ASN1_OBJECT;
struct sk_GENERAL_NAME_Delete {
void operator()(STACK_OF(GENERAL_NAME)* p) const {
sk_GENERAL_NAME_pop_free(p, GENERAL_NAME_free);
}
};
typedef UniquePtr<STACK_OF(GENERAL_NAME), sk_GENERAL_NAME_Delete> Unique_sk_GENERAL_NAME;
/**
* Many OpenSSL APIs take ownership of an argument on success but don't free the argument
* on failure. This means we need to tell our scoped pointers when we've transferred ownership,
* without triggering a warning by not using the result of release().
*/
#define OWNERSHIP_TRANSFERRED(obj) \
do { typeof (obj.release()) _dummy __attribute__((unused)) = obj.release(); } while(0)
/**
* UNUSED_ARGUMENT can be used to mark an, otherwise unused, argument as "used"
* for the purposes of -Werror=unused-parameter. This can be needed when an
* argument's use is based on an #ifdef.
*/
#define UNUSED_ARGUMENT(x) ((void)(x));
/**
* Check array bounds for arguments when an array and offset are given.
*/
#define ARRAY_OFFSET_INVALID(array, offset) (offset < 0 || \
offset > static_cast<ssize_t>(array.size()))
/**
* Check array bounds for arguments when an array, offset, and length are given.
*/
#define ARRAY_OFFSET_LENGTH_INVALID(array, offset, len) (offset < 0 || \
offset > static_cast<ssize_t>(array.size()) || len < 0 || \
len > static_cast<ssize_t>(array.size()) - offset)
/**
* Frees the SSL error state.
*
* OpenSSL keeps an "error stack" per thread, and given that this code
* can be called from arbitrary threads that we don't keep track of,
* we err on the side of freeing the error state promptly (instead of,
* say, at thread death).
*/
static void freeOpenSslErrorState(void) {
ERR_clear_error();
ERR_remove_thread_state(NULL);
}
/**
* Manages the freeing of the OpenSSL error stack. This allows you to
* instantiate this object during an SSL call that may fail and not worry
* about manually calling freeOpenSslErrorState() later.
*
* As an optimization, you can also call .release() for passing as an
* argument to things that free the error stack state as a side-effect.
*/
class OpenSslError {
public:
OpenSslError() : sslError_(SSL_ERROR_NONE), released_(false) {
}
OpenSslError(SSL* ssl, int returnCode) : sslError_(SSL_ERROR_NONE), released_(false) {
reset(ssl, returnCode);
}
~OpenSslError() {
if (!released_ && sslError_ != SSL_ERROR_NONE) {
freeOpenSslErrorState();
}
}
int get() const {
return sslError_;
}
void reset(SSL* ssl, int returnCode) {
if (returnCode <= 0) {
sslError_ = SSL_get_error(ssl, returnCode);
} else {
sslError_ = SSL_ERROR_NONE;
}
}
int release() {
released_ = true;
return sslError_;
}
private:
int sslError_;
bool released_;
};
/**
* Throws a OutOfMemoryError with the given string as a message.
*/
static int jniThrowOutOfMemory(JNIEnv* env, const char* message) {
return jniThrowException(env, "java/lang/OutOfMemoryError", message);
}
/**
* Throws a BadPaddingException with the given string as a message.
*/
static int throwBadPaddingException(JNIEnv* env, const char* message) {
JNI_TRACE("throwBadPaddingException %s", message);
return jniThrowException(env, "javax/crypto/BadPaddingException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static int throwSignatureException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSignatureException %s", message);
return jniThrowException(env, "java/security/SignatureException", message);
}
/**
* Throws a InvalidKeyException with the given string as a message.
*/
static int throwInvalidKeyException(JNIEnv* env, const char* message) {
JNI_TRACE("throwInvalidKeyException %s", message);
return jniThrowException(env, "java/security/InvalidKeyException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static int throwIllegalBlockSizeException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalBlockSizeException %s", message);
return jniThrowException(env, "javax/crypto/IllegalBlockSizeException", message);
}
/**
* Throws a NoSuchAlgorithmException with the given string as a message.
*/
static int throwNoSuchAlgorithmException(JNIEnv* env, const char* message) {
JNI_TRACE("throwUnknownAlgorithmException %s", message);
return jniThrowException(env, "java/security/NoSuchAlgorithmException", message);
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* Throws a ParsingException with the given string as a message.
*/
static int throwParsingException(JNIEnv* env, const char* message) {
return jniThrowException(
env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLX509CertificateFactory$ParsingException",
message);
}
#endif
static int throwForAsn1Error(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE:
#if defined(ASN1_R_UNABLE_TO_DECODE_RSA_KEY)
case ASN1_R_UNABLE_TO_DECODE_RSA_KEY:
#endif
#if defined(ASN1_R_WRONG_PUBLIC_KEY_TYPE)
case ASN1_R_WRONG_PUBLIC_KEY_TYPE:
#endif
#if defined(ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY)
case ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY:
#endif
#if defined(ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE)
case ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE:
#endif
return throwInvalidKeyException(env, message);
break;
#if defined(ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
#endif
}
return defaultThrow(env, message);
}
#if defined(OPENSSL_IS_BORINGSSL)
static int throwForCipherError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case CIPHER_R_BAD_DECRYPT:
return throwBadPaddingException(env, message);
break;
case CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case CIPHER_R_WRONG_FINAL_BLOCK_LENGTH:
return throwIllegalBlockSizeException(env, message);
break;
case CIPHER_R_AES_KEY_SETUP_FAILED:
case CIPHER_R_BAD_KEY_LENGTH:
case CIPHER_R_UNSUPPORTED_KEY_SIZE:
return throwInvalidKeyException(env, message);
break;
}
return defaultThrow(env, message);
}
static int throwForEvpError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case EVP_R_MISSING_PARAMETERS:
return throwInvalidKeyException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
#if defined(EVP_R_X931_UNSUPPORTED)
case EVP_R_X931_UNSUPPORTED:
#endif
return throwNoSuchAlgorithmException(env, message);
break;
#if defined(EVP_R_WRONG_PUBLIC_KEY_TYPE)
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
return throwInvalidKeyException(env, message);
break;
#endif
#if defined(EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
#endif
default:
return defaultThrow(env, message);
break;
}
}
#else
static int throwForEvpError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case EVP_R_BAD_DECRYPT:
return throwBadPaddingException(env, message);
break;
case EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case EVP_R_WRONG_FINAL_BLOCK_LENGTH:
return throwIllegalBlockSizeException(env, message);
break;
case EVP_R_BAD_KEY_LENGTH:
case EVP_R_BN_DECODE_ERROR:
case EVP_R_BN_PUBKEY_ERROR:
case EVP_R_INVALID_KEY_LENGTH:
case EVP_R_MISSING_PARAMETERS:
case EVP_R_UNSUPPORTED_KEY_SIZE:
case EVP_R_UNSUPPORTED_KEYLENGTH:
return throwInvalidKeyException(env, message);
break;
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
return throwSignatureException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
default:
return defaultThrow(env, message);
break;
}
}
#endif
static int throwForRsaError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case RSA_R_BLOCK_TYPE_IS_NOT_01:
case RSA_R_PKCS_DECODING_ERROR:
#if defined(RSA_R_BLOCK_TYPE_IS_NOT_02)
case RSA_R_BLOCK_TYPE_IS_NOT_02:
#endif
return throwBadPaddingException(env, message);
break;
case RSA_R_BAD_SIGNATURE:
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
case RSA_R_INVALID_MESSAGE_LENGTH:
case RSA_R_WRONG_SIGNATURE_LENGTH:
#if !defined(OPENSSL_IS_BORINGSSL)
case RSA_R_ALGORITHM_MISMATCH:
case RSA_R_DATA_GREATER_THAN_MOD_LEN:
#endif
return throwSignatureException(env, message);
break;
case RSA_R_UNKNOWN_ALGORITHM_TYPE:
return throwNoSuchAlgorithmException(env, message);
break;
case RSA_R_MODULUS_TOO_LARGE:
case RSA_R_NO_PUBLIC_EXPONENT:
return throwInvalidKeyException(env, message);
break;
}
return defaultThrow(env, message);
}
static int throwForX509Error(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case X509_R_UNSUPPORTED_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
default:
return defaultThrow(env, message);
break;
}
}
/*
* Checks this thread's OpenSSL error queue and throws a RuntimeException if
* necessary.
*
* @return true if an exception was thrown, false if not.
*/
static bool throwExceptionIfNecessary(JNIEnv* env, const char* location __attribute__ ((unused)),
int (*defaultThrow)(JNIEnv*, const char*) = jniThrowRuntimeException) {
const char* file;
int line;
const char* data;
int flags;
unsigned long error = ERR_get_error_line_data(&file, &line, &data, &flags);
int result = false;
if (error != 0) {
char message[256];
ERR_error_string_n(error, message, sizeof(message));
int library = ERR_GET_LIB(error);
int reason = ERR_GET_REASON(error);
JNI_TRACE("OpenSSL error in %s error=%lx library=%x reason=%x (%s:%d): %s %s",
location, error, library, reason, file, line, message,
(flags & ERR_TXT_STRING) ? data : "(no data)");
switch (library) {
case ERR_LIB_RSA:
throwForRsaError(env, reason, message, defaultThrow);
break;
case ERR_LIB_ASN1:
throwForAsn1Error(env, reason, message, defaultThrow);
break;
#if defined(OPENSSL_IS_BORINGSSL)
case ERR_LIB_CIPHER:
throwForCipherError(env, reason, message, defaultThrow);
break;
#endif
case ERR_LIB_EVP:
throwForEvpError(env, reason, message, defaultThrow);
break;
case ERR_LIB_X509:
throwForX509Error(env, reason, message, defaultThrow);
break;
case ERR_LIB_DSA:
throwInvalidKeyException(env, message);
break;
default:
defaultThrow(env, message);
break;
}
result = true;
}
freeOpenSslErrorState();
return result;
}
/**
* Throws an SocketTimeoutException with the given string as a message.
*/
static int throwSocketTimeoutException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSocketTimeoutException %s", message);
return jniThrowException(env, "java/net/SocketTimeoutException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static int throwSSLHandshakeExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
return jniThrowException(env, "javax/net/ssl/SSLHandshakeException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static int throwSSLExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
return jniThrowException(env, "javax/net/ssl/SSLException", message);
}
/**
* Throws a javax.net.ssl.SSLProcotolException with the given string as a message.
*/
static int throwSSLProtocolExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLProtocolExceptionStr %s", message);
return jniThrowException(env, "javax/net/ssl/SSLProtocolException", message);
}
/**
* Throws an SSLException with a message constructed from the current
* SSL errors. This will also log the errors.
*
* @param env the JNI environment
* @param ssl the possibly NULL SSL
* @param sslErrorCode error code returned from SSL_get_error() or
* SSL_ERROR_NONE to probe with ERR_get_error
* @param message null-ok; general error message
*/
static int throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCode,
const char* message, int (*actualThrow)(JNIEnv*, const char*) = throwSSLExceptionStr) {
if (message == NULL) {
message = "SSL error";
}
// First consult the SSL error code for the general message.
const char* sslErrorStr = NULL;
switch (sslErrorCode) {
case SSL_ERROR_NONE:
if (ERR_peek_error() == 0) {
sslErrorStr = "OK";
} else {
sslErrorStr = "";
}
break;
case SSL_ERROR_SSL:
sslErrorStr = "Failure in SSL library, usually a protocol error";
break;
case SSL_ERROR_WANT_READ:
sslErrorStr = "SSL_ERROR_WANT_READ occurred. You should never see this.";
break;
case SSL_ERROR_WANT_WRITE:
sslErrorStr = "SSL_ERROR_WANT_WRITE occurred. You should never see this.";
break;
case SSL_ERROR_WANT_X509_LOOKUP:
sslErrorStr = "SSL_ERROR_WANT_X509_LOOKUP occurred. You should never see this.";
break;
case SSL_ERROR_SYSCALL:
sslErrorStr = "I/O error during system call";
break;
case SSL_ERROR_ZERO_RETURN:
sslErrorStr = "SSL_ERROR_ZERO_RETURN occurred. You should never see this.";
break;
case SSL_ERROR_WANT_CONNECT:
sslErrorStr = "SSL_ERROR_WANT_CONNECT occurred. You should never see this.";
break;
case SSL_ERROR_WANT_ACCEPT:
sslErrorStr = "SSL_ERROR_WANT_ACCEPT occurred. You should never see this.";
break;
default:
sslErrorStr = "Unknown SSL error";
}
// Prepend either our explicit message or a default one.
char* str;
if (asprintf(&str, "%s: ssl=%p: %s", message, ssl, sslErrorStr) <= 0) {
// problem with asprintf, just throw argument message, log everything
int ret = actualThrow(env, message);
ALOGV("%s: ssl=%p: %s", message, ssl, sslErrorStr);
freeOpenSslErrorState();
return ret;
}
char* allocStr = str;
// For protocol errors, SSL might have more information.
if (sslErrorCode == SSL_ERROR_NONE || sslErrorCode == SSL_ERROR_SSL) {
// Append each error as an additional line to the message.
for (;;) {
char errStr[256];
const char* file;
int line;
const char* data;
int flags;
unsigned long err = ERR_get_error_line_data(&file, &line, &data, &flags);
if (err == 0) {
break;
}
ERR_error_string_n(err, errStr, sizeof(errStr));
int ret = asprintf(&str, "%s\n%s (%s:%d %p:0x%08x)",
(allocStr == NULL) ? "" : allocStr,
errStr,
file,
line,
(flags & ERR_TXT_STRING) ? data : "(no data)",
flags);
if (ret < 0) {
break;
}
free(allocStr);
allocStr = str;
}
// For errors during system calls, errno might be our friend.
} else if (sslErrorCode == SSL_ERROR_SYSCALL) {
if (asprintf(&str, "%s, %s", allocStr, strerror(errno)) >= 0) {
free(allocStr);
allocStr = str;
}
// If the error code is invalid, print it.
} else if (sslErrorCode > SSL_ERROR_WANT_ACCEPT) {
if (asprintf(&str, ", error code is %d", sslErrorCode) >= 0) {
free(allocStr);
allocStr = str;
}
}
int ret;
if (sslErrorCode == SSL_ERROR_SSL) {
ret = throwSSLProtocolExceptionStr(env, allocStr);
} else {
ret = actualThrow(env, allocStr);
}
ALOGV("%s", allocStr);
free(allocStr);
freeOpenSslErrorState();
return ret;
}
/**
* Helper function that grabs the casts an ssl pointer and then checks for nullness.
* If this function returns NULL and <code>throwIfNull</code> is
* passed as <code>true</code>, then this function will call
* <code>throwSSLExceptionStr</code> before returning, so in this case of
* NULL, a caller of this function should simply return and allow JNI
* to do its thing.
*
* @param env the JNI environment
* @param ssl_address; the ssl_address pointer as an integer
* @param throwIfNull whether to throw if the SSL pointer is NULL
* @returns the pointer, which may be NULL
*/
static SSL_CTX* to_SSL_CTX(JNIEnv* env, jlong ssl_ctx_address, bool throwIfNull) {
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
if ((ssl_ctx == NULL) && throwIfNull) {
JNI_TRACE("ssl_ctx == null");
jniThrowNullPointerException(env, "ssl_ctx == null");
}
return ssl_ctx;
}
static SSL* to_SSL(JNIEnv* env, jlong ssl_address, bool throwIfNull) {
SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
if ((ssl == NULL) && throwIfNull) {
JNI_TRACE("ssl == null");
jniThrowNullPointerException(env, "ssl == null");
}
return ssl;
}
static SSL_SESSION* to_SSL_SESSION(JNIEnv* env, jlong ssl_session_address, bool throwIfNull) {
SSL_SESSION* ssl_session
= reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
if ((ssl_session == NULL) && throwIfNull) {
JNI_TRACE("ssl_session == null");
jniThrowNullPointerException(env, "ssl_session == null");
}
return ssl_session;
}
static SSL_CIPHER* to_SSL_CIPHER(JNIEnv* env, jlong ssl_cipher_address, bool throwIfNull) {
SSL_CIPHER* ssl_cipher
= reinterpret_cast<SSL_CIPHER*>(static_cast<uintptr_t>(ssl_cipher_address));
if ((ssl_cipher == NULL) && throwIfNull) {
JNI_TRACE("ssl_cipher == null");
jniThrowNullPointerException(env, "ssl_cipher == null");
}
return ssl_cipher;
}
template<typename T>
static T* fromContextObject(JNIEnv* env, jobject contextObject) {
if (contextObject == NULL) {
JNI_TRACE("contextObject == null");
jniThrowNullPointerException(env, "contextObject == null");
return NULL;
}
T* ref = reinterpret_cast<T*>(env->GetLongField(contextObject, nativeRef_context));
if (ref == NULL) {
JNI_TRACE("ref == null");
jniThrowNullPointerException(env, "ref == null");
return NULL;
}
return ref;
}
/**
* Converts a Java byte[] two's complement to an OpenSSL BIGNUM. This will
* allocate the BIGNUM if *dest == NULL. Returns true on success. If the
* return value is false, there is a pending exception.
*/
static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
JNI_TRACE("arrayToBignum(%p, %p)", source, dest);
if (dest == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => dest is null!", source, dest);
jniThrowNullPointerException(env, "dest == null");
return false;
}
JNI_TRACE("arrayToBignum(%p, %p) *dest == %p", source, dest, *dest);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
/* if the array is empty, it is zero. */
if (tmpSize == 0) {
if (*dest == NULL) {
*dest = BN_new();
}
BN_zero(*dest);
return true;
}
UniquePtr<unsigned char[]> twosComplement;
bool negative = (tmp[0] & 0x80) != 0;
if (negative) {
// Need to convert to two's complement.
twosComplement.reset(new unsigned char[tmpSize]);
unsigned char* twosBytes = reinterpret_cast<unsigned char*>(twosComplement.get());
memcpy(twosBytes, tmp, tmpSize);
tmp = twosBytes;
bool carry = true;
for (ssize_t i = tmpSize - 1; i >= 0; i--) {
twosBytes[i] ^= 0xFF;
if (carry) {
carry = (++twosBytes[i]) == 0;
}
}
}
BIGNUM *ret = BN_bin2bn(tmp, tmpSize, *dest);
if (ret == NULL) {
jniThrowRuntimeException(env, "Conversion to BIGNUM failed");
JNI_TRACE("arrayToBignum(%p, %p) => threw exception", source, dest);
return false;
}
BN_set_negative(ret, negative ? 1 : 0);
*dest = ret;
JNI_TRACE("arrayToBignum(%p, %p) => *dest = %p", source, dest, ret);
return true;
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* arrayToBignumSize sets |*out_size| to the size of the big-endian number
* contained in |source|. It returns true on success and sets an exception and
* returns false otherwise.
*/
static bool arrayToBignumSize(JNIEnv* env, jbyteArray source, size_t* out_size) {
JNI_TRACE("arrayToBignumSize(%p, %p)", source, out_size);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, out_size);
return false;
}
const uint8_t* tmp = reinterpret_cast<const uint8_t*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
if (tmpSize == 0) {
*out_size = 0;
return true;
}
if ((tmp[0] & 0x80) != 0) {
// Negative numbers are invalid.
jniThrowRuntimeException(env, "Negative number");
return false;
}
while (tmpSize > 0 && tmp[0] == 0) {
tmp++;
tmpSize--;
}
*out_size = tmpSize;
return true;
}
#endif
/**
* Converts an OpenSSL BIGNUM to a Java byte[] array in two's complement.
*/
static jbyteArray bignumToArray(JNIEnv* env, const BIGNUM* source, const char* sourceName) {
JNI_TRACE("bignumToArray(%p, %s)", source, sourceName);
if (source == NULL) {
jniThrowNullPointerException(env, sourceName);
return NULL;
}
size_t numBytes = BN_num_bytes(source) + 1;
jbyteArray javaBytes = env->NewByteArray(numBytes);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bignumToArray(%p, %s) => NULL", source, sourceName);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
if (BN_num_bytes(source) > 0 && BN_bn2bin(source, tmp + 1) <= 0) {
throwExceptionIfNecessary(env, "bignumToArray");
return NULL;
}
// Set the sign and convert to two's complement if necessary for the Java code.
if (BN_is_negative(source)) {
bool carry = true;
for (ssize_t i = numBytes - 1; i >= 0; i--) {
tmp[i] ^= 0xFF;
if (carry) {
carry = (++tmp[i]) == 0;
}
}
*tmp |= 0x80;
} else {
*tmp = 0x00;
}
JNI_TRACE("bignumToArray(%p, %s) => %p", source, sourceName, javaBytes);
return javaBytes;
}
/**
* Converts various OpenSSL ASN.1 types to a jbyteArray with DER-encoded data
* inside. The "i2d_func" function pointer is a function of the "i2d_<TYPE>"
* from the OpenSSL ASN.1 API.
*/
template<typename T>
jbyteArray ASN1ToByteArray(JNIEnv* env, T* obj, int (*i2d_func)(T*, unsigned char**)) {
if (obj == NULL) {
jniThrowNullPointerException(env, "ASN1 input == null");
JNI_TRACE("ASN1ToByteArray(%p) => null input", obj);
return NULL;
}
int derLen = i2d_func(obj, NULL);
if (derLen < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => measurement failed", obj);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => creating byte array failed", obj);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => using byte array failed", obj);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
int ret = i2d_func(obj, &p);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => final conversion failed", obj);
return NULL;
}
JNI_TRACE("ASN1ToByteArray(%p) => success (%d bytes written)", obj, ret);
return byteArray.release();
}
template<typename T, T* (*d2i_func)(T**, const unsigned char**, long)>
T* ByteArrayToASN1(JNIEnv* env, jbyteArray byteArray) {
ScopedByteArrayRO bytes(env, byteArray);
if (bytes.get() == NULL) {
JNI_TRACE("ByteArrayToASN1(%p) => using byte array failed", byteArray);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
return d2i_func(NULL, &tmp, bytes.size());
}
/**
* Converts ASN.1 BIT STRING to a jbooleanArray.
*/
jbooleanArray ASN1BitStringToBooleanArray(JNIEnv* env, ASN1_BIT_STRING* bitStr) {
int size = bitStr->length * 8;
if (bitStr->flags & ASN1_STRING_FLAG_BITS_LEFT) {
size -= bitStr->flags & 0x07;
}
ScopedLocalRef<jbooleanArray> bitsRef(env, env->NewBooleanArray(size));
if (bitsRef.get() == NULL) {
return NULL;
}
ScopedBooleanArrayRW bitsArray(env, bitsRef.get());
for (int i = 0; i < static_cast<int>(bitsArray.size()); i++) {
bitsArray[i] = ASN1_BIT_STRING_get_bit(bitStr, i);
}
return bitsRef.release();
}
/**
* Safely clear SSL sessions and throw an error if there was something already
* in the error stack.
*/
static void safeSslClear(SSL* ssl) {
if (SSL_clear(ssl) != 1) {
freeOpenSslErrorState();
}
}
/**
* To avoid the round-trip to ASN.1 and back in X509_dup, we just up the reference count.
*/
static X509* X509_dup_nocopy(X509* x509) {
if (x509 == NULL) {
return NULL;
}
#if defined(OPENSSL_IS_BORINGSSL)
return X509_up_ref(x509);
#else
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509);
return x509;
#endif
}
/*
* Sets the read and write BIO for an SSL connection and removes it when it goes out of scope.
* We hang on to BIO with a JNI GlobalRef and we want to remove them as soon as possible.
*/
class ScopedSslBio {
public:
ScopedSslBio(SSL *ssl, BIO* rbio, BIO* wbio) : ssl_(ssl) {
SSL_set_bio(ssl_, rbio, wbio);
BIO_up_ref(rbio);
BIO_up_ref(wbio);
}
~ScopedSslBio() {
SSL_set_bio(ssl_, NULL, NULL);
}
private:
SSL* const ssl_;
};
/**
* Obtains the current thread's JNIEnv
*/
static JNIEnv* getJNIEnv() {
JNIEnv* env;
#ifdef ANDROID
if (gJavaVM->AttachCurrentThread(&env, NULL) < 0) {
#else
if (gJavaVM->AttachCurrentThread(reinterpret_cast<void**>(&env), NULL) < 0) {
#endif
ALOGE("Could not attach JavaVM to find current JNIEnv");
return NULL;
}
return env;
}
/**
* BIO for InputStream
*/
class BIO_Stream {
public:
BIO_Stream(jobject stream) :
mEof(false) {
JNIEnv* env = getJNIEnv();
mStream = env->NewGlobalRef(stream);
}
~BIO_Stream() {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(mStream);
}
bool isEof() const {
JNI_TRACE("isEof? %s", mEof ? "yes" : "no");
return mEof;
}
int flush() {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_Stream::flush called with pending exception");
return -1;
}
env->CallVoidMethod(mStream, outputStream_flushMethod);
if (env->ExceptionCheck()) {
return -1;
}
return 1;
}
protected:
jobject getStream() {
return mStream;
}
void setEof(bool eof) {
mEof = eof;
}
private:
jobject mStream;
bool mEof;
};
class BIO_InputStream : public BIO_Stream {
public:
BIO_InputStream(jobject stream, bool isFinite) :
BIO_Stream(stream),
isFinite_(isFinite) {
}
int read(char *buf, int len) {
return read_internal(buf, len, inputStream_readMethod);
}
int gets(char *buf, int len) {
if (len > PEM_LINE_LENGTH) {
len = PEM_LINE_LENGTH;
}
int read = read_internal(buf, len - 1, openSslInputStream_readLineMethod);
buf[read] = '\0';
JNI_TRACE("BIO::gets \"%s\"", buf);
return read;
}
bool isFinite() const {
return isFinite_;
}
private:
const bool isFinite_;
int read_internal(char *buf, int len, jmethodID method) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_InputStream::read could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_InputStream::read failed call to NewByteArray");
return -1;
}
jint read = env->CallIntMethod(getStream(), method, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read failed call to InputStream#read");
return -1;
}
/* Java uses -1 to indicate EOF condition. */
if (read == -1) {
setEof(true);
read = 0;
} else if (read > 0) {
env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast<jbyte*>(buf));
}
return read;
}
public:
/** Length of PEM-encoded line (64) plus CR plus NULL */
static const int PEM_LINE_LENGTH = 66;
};
class BIO_OutputStream : public BIO_Stream {
public:
BIO_OutputStream(jobject stream) :
BIO_Stream(stream) {
}
int write(const char *buf, int len) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_OutputStream::write => could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_OutputStream::write => failed call to NewByteArray");
return -1;
}
env->SetByteArrayRegion(javaBytes.get(), 0, len, reinterpret_cast<const jbyte*>(buf));
env->CallVoidMethod(getStream(), outputStream_writeMethod, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => failed call to OutputStream#write");
return -1;
}
return len;
}
};
static int bio_stream_create(BIO *b) {
b->init = 1;
b->num = 0;
b->ptr = NULL;
b->flags = 0;
return 1;
}
static int bio_stream_destroy(BIO *b) {
if (b == NULL) {
return 0;
}
if (b->ptr != NULL) {
delete static_cast<BIO_Stream*>(b->ptr);
b->ptr = NULL;
}
b->init = 0;
b->flags = 0;
return 1;
}
static int bio_stream_read(BIO *b, char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
int ret = stream->read(buf, len);
if (ret == 0) {
if (stream->isFinite()) {
return 0;
}
// If the BIO_InputStream is not finite then EOF doesn't mean that
// there's nothing more coming.
BIO_set_retry_read(b);
return -1;
}
return ret;
}
static int bio_stream_write(BIO *b, const char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, len);
}
static int bio_stream_puts(BIO *b, const char *buf) {
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, strlen(buf));
}
static int bio_stream_gets(BIO *b, char *buf, int len) {
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
return stream->gets(buf, len);
}
static void bio_stream_assign(BIO *b, BIO_Stream* stream) {
b->ptr = static_cast<void*>(stream);
}
static long bio_stream_ctrl(BIO *b, int cmd, long, void *) {
BIO_Stream* stream = static_cast<BIO_Stream*>(b->ptr);
switch (cmd) {
case BIO_CTRL_EOF:
return stream->isEof() ? 1 : 0;
case BIO_CTRL_FLUSH:
return stream->flush();
default:
return 0;
}
}
static BIO_METHOD stream_bio_method = {
( 100 | 0x0400 ), /* source/sink BIO */
"InputStream/OutputStream BIO",
bio_stream_write, /* bio_write */
bio_stream_read, /* bio_read */
bio_stream_puts, /* bio_puts */
bio_stream_gets, /* bio_gets */
bio_stream_ctrl, /* bio_ctrl */
bio_stream_create, /* bio_create */
bio_stream_destroy, /* bio_free */
NULL, /* no bio_callback_ctrl */
};
static jbyteArray rawSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey,
const char* message, size_t message_len) {
ScopedLocalRef<jbyteArray> messageArray(env, env->NewByteArray(message_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW messageBytes(env, messageArray.get());
if (messageBytes.get() == NULL) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(messageBytes.get(), message, message_len);
}
jmethodID rawSignMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rawSignDigestWithPrivateKey", "(Ljava/security/PrivateKey;[B)[B");
if (rawSignMethod == NULL) {
ALOGE("Could not find rawSignDigestWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass, rawSignMethod, privateKey, messageArray.get()));
}
// rsaDecryptWithPrivateKey uses privateKey to decrypt |ciphertext_len| bytes
// from |ciphertext|. The ciphertext is expected to be padded using the scheme
// given in |padding|, which must be one of |RSA_*_PADDING| constants from
// OpenSSL.
static jbyteArray rsaDecryptWithPrivateKey(JNIEnv* env, jobject privateKey, jint padding,
const char* ciphertext, size_t ciphertext_len) {
ScopedLocalRef<jbyteArray> ciphertextArray(env, env->NewByteArray(ciphertext_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rsaDecryptWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW ciphertextBytes(env, ciphertextArray.get());
if (ciphertextBytes.get() == NULL) {
JNI_TRACE("rsaDecryptWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(ciphertextBytes.get(), ciphertext, ciphertext_len);
}
jmethodID rsaDecryptMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rsaDecryptWithPrivateKey", "(Ljava/security/PrivateKey;I[B)[B");
if (rsaDecryptMethod == NULL) {
ALOGE("Could not find rsaDecryptWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass,
rsaDecryptMethod,
privateKey,
padding,
ciphertextArray.get()));
}
// *********************************************
// From keystore_openssl.cpp in Chromium source.
// *********************************************
#if !defined(OPENSSL_IS_BORINGSSL)
// Custom RSA_METHOD that uses the platform APIs.
// Note that for now, only signing through RSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
// See <openssl/rsa.h> for exact declaration of RSA_METHOD.
int RsaMethodPubEnc(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
int RsaMethodPubDec(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
// See RSA_eay_private_encrypt in
// third_party/openssl/openssl/crypto/rsa/rsa_eay.c for the default
// implementation of this function.
int RsaMethodPrivEnc(int flen,
const unsigned char *from,
unsigned char *to,
RSA *rsa,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
return -1;
}
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// For RSA keys, this function behaves as RSA_private_encrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(from), flen));
if (signature.get() == NULL) {
ALOGE("Could not sign message in RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (signatureBytes.size() > expected_size) {
ALOGE("RSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer. rawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - signatureBytes.size();
memset(to, 0, zero_pad);
memcpy(to + zero_pad, signatureBytes.get(), signatureBytes.size());
return expected_size;
}
int RsaMethodPrivDec(int flen,
const unsigned char* from,
unsigned char* to,
RSA* rsa,
int padding) {
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// This function behaves as RSA_private_decrypt.
ScopedLocalRef<jbyteArray> cleartext(env, rsaDecryptWithPrivateKey(env, private_key,
padding, reinterpret_cast<const char*>(from), flen));
if (cleartext.get() == NULL) {
ALOGE("Could not decrypt message in RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO cleartextBytes(env, cleartext.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (cleartextBytes.size() > expected_size) {
ALOGE("RSA ciphertext size mismatch, actual: %zd, expected <= %zd", cleartextBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer.
memcpy(to, cleartextBytes.get(), cleartextBytes.size());
return cleartextBytes.size();
}
int RsaMethodInit(RSA*) {
return 0;
}
int RsaMethodFinish(RSA* rsa) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
jobject key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (key != NULL) {
RSA_set_app_data(rsa, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(key);
}
// Actual return value is ignored by OpenSSL. There are no docs
// explaining what this is supposed to be.
return 0;
}
const RSA_METHOD android_rsa_method = {
/* .name = */ "Android signing-only RSA method",
/* .rsa_pub_enc = */ RsaMethodPubEnc,
/* .rsa_pub_dec = */ RsaMethodPubDec,
/* .rsa_priv_enc = */ RsaMethodPrivEnc,
/* .rsa_priv_dec = */ RsaMethodPrivDec,
/* .rsa_mod_exp = */ NULL,
/* .bn_mod_exp = */ NULL,
/* .init = */ RsaMethodInit,
/* .finish = */ RsaMethodFinish,
// This flag is necessary to tell OpenSSL to avoid checking the content
// (i.e. internal fields) of the private key. Otherwise, it will complain
// it's not valid for the certificate.
/* .flags = */ RSA_METHOD_FLAG_NO_CHECK,
/* .app_data = */ NULL,
/* .rsa_sign = */ NULL,
/* .rsa_verify = */ NULL,
/* .rsa_keygen = */ NULL,
};
// Used to ensure that the global JNI reference associated with a custom
// EC_KEY + ECDSA_METHOD wrapper is released when its EX_DATA is destroyed
// (this function is called when EVP_PKEY_free() is called on the wrapper).
void ExDataFree(void* /* parent */,
void* ptr,
CRYPTO_EX_DATA* ad,
int idx,
long /* argl */,
#if defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL)
const void* /* argp */) {
#else /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
void* /* argp */) {
#endif /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
jobject private_key = reinterpret_cast<jobject>(ptr);
if (private_key == NULL) return;
CRYPTO_set_ex_data(ad, idx, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(private_key);
}
int ExDataDup(CRYPTO_EX_DATA* /* to */,
CRYPTO_EX_DATA* /* from */,
void* /* from_d */,
int /* idx */,
long /* argl */,
#if defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL)
const void* /* argp */) {
#else /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
void* /* argp */) {
#endif /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
// This callback shall never be called with the current OpenSSL
// implementation (the library only ever duplicates EX_DATA items
// for SSL and BIO objects). But provide this to catch regressions
// in the future.
// Return value is currently ignored by OpenSSL.
return 0;
}
class EcdsaExDataIndex {
public:
int ex_data_index() { return ex_data_index_; }
static EcdsaExDataIndex& Instance() {
static EcdsaExDataIndex singleton;
return singleton;
}
private:
EcdsaExDataIndex() {
ex_data_index_ = ECDSA_get_ex_new_index(0, NULL, NULL, ExDataDup, ExDataFree);
}
EcdsaExDataIndex(EcdsaExDataIndex const&);
~EcdsaExDataIndex() {}
EcdsaExDataIndex& operator=(EcdsaExDataIndex const&);
int ex_data_index_;
};
// Returns the index of the custom EX_DATA used to store the JNI reference.
int EcdsaGetExDataIndex(void) {
EcdsaExDataIndex& exData = EcdsaExDataIndex::Instance();
return exData.ex_data_index();
}
ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst, int dgst_len, const BIGNUM* /* inv */,
const BIGNUM* /* rp */, EC_KEY* eckey) {
// Retrieve private key JNI reference.
jobject private_key =
reinterpret_cast<jobject>(ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex()));
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodDoSign!");
return NULL;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return NULL;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key, reinterpret_cast<const char*>(dgst),
dgst_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return NULL;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey));
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
max_expected_size);
return NULL;
}
// Convert signature to ECDSA_SIG object
const unsigned char* sigbuf = reinterpret_cast<const unsigned char*>(signatureBytes.get());
long siglen = static_cast<long>(signatureBytes.size());
return d2i_ECDSA_SIG(NULL, &sigbuf, siglen);
}
int EcdsaMethodSignSetup(EC_KEY* /* eckey */,
BN_CTX* /* ctx */,
BIGNUM** /* kinv */,
BIGNUM** /* r */,
const unsigned char*,
int) {
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB);
return -1;
}
int EcdsaMethodDoVerify(const unsigned char* /* dgst */,
int /* dgst_len */,
const ECDSA_SIG* /* sig */,
EC_KEY* /* eckey */) {
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB);
return -1;
}
const ECDSA_METHOD android_ecdsa_method = {
/* .name = */ "Android signing-only ECDSA method",
/* .ecdsa_do_sign = */ EcdsaMethodDoSign,
/* .ecdsa_sign_setup = */ EcdsaMethodSignSetup,
/* .ecdsa_do_verify = */ EcdsaMethodDoVerify,
/* .flags = */ 0,
/* .app_data = */ NULL,
};
#else /* OPENSSL_IS_BORINGSSL */
namespace {
ENGINE *g_engine;
int g_rsa_exdata_index;
int g_ecdsa_exdata_index;
pthread_once_t g_engine_once = PTHREAD_ONCE_INIT;
void init_engine_globals();
void ensure_engine_globals() {
pthread_once(&g_engine_once, init_engine_globals);
}
// KeyExData contains the data that is contained in the EX_DATA of the RSA
// and ECDSA objects that are created to wrap Android system keys.
struct KeyExData {
// private_key contains a reference to a Java, private-key object.
jobject private_key;
// cached_size contains the "size" of the key. This is the size of the
// modulus (in bytes) for RSA, or the group order size for ECDSA. This
// avoids calling into Java to calculate the size.
size_t cached_size;
};
// ExDataDup is called when one of the RSA or EC_KEY objects is duplicated. We
// don't support this and it should never happen.
int ExDataDup(CRYPTO_EX_DATA* /* to */,
const CRYPTO_EX_DATA* /* from */,
void** /* from_d */,
int /* index */,
long /* argl */,
void* /* argp */) {
return 0;
}
// ExDataFree is called when one of the RSA or EC_KEY objects is freed.
void ExDataFree(void* /* parent */,
void* ptr,
CRYPTO_EX_DATA* /* ad */,
int /* index */,
long /* argl */,
void* /* argp */) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
KeyExData *ex_data = reinterpret_cast<KeyExData*>(ptr);
if (ex_data != NULL) {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(ex_data->private_key);
delete ex_data;
}
}
KeyExData* RsaGetExData(const RSA* rsa) {
return reinterpret_cast<KeyExData*>(RSA_get_ex_data(rsa, g_rsa_exdata_index));
}
size_t RsaMethodSize(const RSA *rsa) {
const KeyExData *ex_data = RsaGetExData(rsa);
return ex_data->cached_size;
}
int RsaMethodEncrypt(RSA* /* rsa */,
size_t* /* out_len */,
uint8_t* /* out */,
size_t /* max_out */,
const uint8_t* /* in */,
size_t /* in_len */,
int /* padding */) {
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
int RsaMethodSignRaw(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
return 0;
}
// Retrieve private key JNI reference.
const KeyExData *ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
// For RSA keys, this function behaves as RSA_private_encrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(
env, ex_data->private_key,
reinterpret_cast<const char*>(in), in_len));
if (signature.get() == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO result(env, signature.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (result.size() > expected_size) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
if (max_out < expected_size) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer. RawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - result.size();
memset(out, 0, zero_pad);
memcpy(out + zero_pad, &result[0], result.size());
*out_len = expected_size;
return 1;
}
int RsaMethodDecrypt(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
// Retrieve private key JNI reference.
const KeyExData *ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
// This function behaves as RSA_private_decrypt.
ScopedLocalRef<jbyteArray> cleartext(
env, rsaDecryptWithPrivateKey(
env, ex_data->private_key, padding,
reinterpret_cast<const char*>(in), in_len));
if (cleartext.get() == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO cleartextBytes(env, cleartext.get());
if (max_out < cleartextBytes.size()) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer.
memcpy(out, cleartextBytes.get(), cleartextBytes.size());
*out_len = cleartextBytes.size();
return 1;
}
int RsaMethodVerifyRaw(RSA* /* rsa */,
size_t* /* out_len */,
uint8_t* /* out */,
size_t /* max_out */,
const uint8_t* /* in */,
size_t /* in_len */,
int /* padding */) {
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
const RSA_METHOD android_rsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
RsaMethodSize,
NULL /* sign */,
NULL /* verify */,
RsaMethodEncrypt,
RsaMethodSignRaw,
RsaMethodDecrypt,
RsaMethodVerifyRaw,
NULL /* mod_exp */,
NULL /* bn_mod_exp */,
NULL /* private_transform */,
RSA_FLAG_OPAQUE,
NULL /* keygen */,
NULL /* multi_prime_keygen */,
NULL /* supports_digest */,
};
// Custom ECDSA_METHOD that uses the platform APIs.
// Note that for now, only signing through ECDSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
jobject EcKeyGetKey(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->private_key;
}
size_t EcdsaMethodGroupOrderSize(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->cached_size;
}
int EcdsaMethodSign(const uint8_t* digest,
size_t digest_len,
uint8_t* sig,
unsigned int* sig_len,
EC_KEY* ec_key) {
// Retrieve private key JNI reference.
jobject private_key = EcKeyGetKey(ec_key);
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodSign!");
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return 0;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(digest),
digest_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return 0;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = ECDSA_size(ec_key);
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd",
signatureBytes.size(), max_expected_size);
return 0;
}
memcpy(sig, signatureBytes.get(), signatureBytes.size());
*sig_len = signatureBytes.size();
return 1;
}
int EcdsaMethodVerify(const uint8_t* /* digest */,
size_t /* digest_len */,
const uint8_t* /* sig */,
size_t /* sig_len */,
EC_KEY* /* ec_key */) {
OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NOT_IMPLEMENTED);
return 0;
}
const ECDSA_METHOD android_ecdsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
EcdsaMethodGroupOrderSize,
EcdsaMethodSign,
EcdsaMethodVerify,
ECDSA_FLAG_OPAQUE,
};
void init_engine_globals() {
g_rsa_exdata_index =
RSA_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
ExDataDup, ExDataFree);
g_ecdsa_exdata_index =
EC_KEY_get_ex_new_index(0 /* argl */, NULL /* argp */,
NULL /* new_func */, ExDataDup, ExDataFree);
g_engine = ENGINE_new();
ENGINE_set_RSA_method(g_engine, &android_rsa_method,
sizeof(android_rsa_method));
ENGINE_set_ECDSA_method(g_engine, &android_ecdsa_method,
sizeof(android_ecdsa_method));
}
} // anonymous namespace
#endif
#ifdef CONSCRYPT_UNBUNDLED
/*
* This is a big hack; don't learn from this. Basically what happened is we do
* not have an API way to insert ourselves into the AsynchronousCloseMonitor
* that's compiled into the native libraries for libcore when we're unbundled.
* So we try to look up the symbol from the main library to find it.
*/
typedef void (*acm_ctor_func)(void*, int);
typedef void (*acm_dtor_func)(void*);
static acm_ctor_func async_close_monitor_ctor = NULL;
static acm_dtor_func async_close_monitor_dtor = NULL;
class CompatibilityCloseMonitor {
public:
CompatibilityCloseMonitor(int fd) {
if (async_close_monitor_ctor != NULL) {
async_close_monitor_ctor(objBuffer, fd);
}
}
~CompatibilityCloseMonitor() {
if (async_close_monitor_dtor != NULL) {
async_close_monitor_dtor(objBuffer);
}
}
private:
char objBuffer[256];
#if 0
static_assert(sizeof(objBuffer) > 2*sizeof(AsynchronousCloseMonitor),
"CompatibilityCloseMonitor must be larger than the actual object");
#endif
};
static void findAsynchronousCloseMonitorFuncs() {
void *lib = dlopen("libjavacore.so", RTLD_NOW);
if (lib != NULL) {
async_close_monitor_ctor = (acm_ctor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorC1Ei");
async_close_monitor_dtor = (acm_dtor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorD1Ev");
}
}
#endif
/**
* Copied from libnativehelper NetworkUtilites.cpp
*/
static bool setBlocking(int fd, bool blocking) {
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
return false;
}
if (!blocking) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int rc = fcntl(fd, F_SETFL, flags);
return (rc != -1);
}
/**
* OpenSSL locking support. Taken from the O'Reilly book by Viega et al., but I
* suppose there are not many other ways to do this on a Linux system (modulo
* isomorphism).
*/
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#define THROW_SSLEXCEPTION (-2)
#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
#define THROWN_EXCEPTION (-4)
static MUTEX_TYPE* mutex_buf = NULL;
static void locking_function(int mode, int n, const char*, int) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(mutex_buf[n]);
} else {
MUTEX_UNLOCK(mutex_buf[n]);
}
}
static void threadid_callback(CRYPTO_THREADID *threadid) {
#if defined(__APPLE__)
uint64_t owner;
int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6
if (rc == 0) {
CRYPTO_THREADID_set_numeric(threadid, owner);
} else {
ALOGE("Error calling pthread_threadid_np");
}
#else
// bionic exposes gettid(), but glibc doesn't
CRYPTO_THREADID_set_numeric(threadid, syscall(__NR_gettid));
#endif
}
int THREAD_setup(void) {
mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
if (!mutex_buf) {
return 0;
}
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
MUTEX_SETUP(mutex_buf[i]);
}
CRYPTO_THREADID_set_callback(threadid_callback);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int THREAD_cleanup(void) {
if (!mutex_buf) {
return 0;
}
CRYPTO_THREADID_set_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks( ); i++) {
MUTEX_CLEANUP(mutex_buf[i]);
}
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
/**
* Initialization phase for every OpenSSL job: Loads the Error strings, the
* crypto algorithms and reset the OpenSSL library
*/
static jboolean NativeCrypto_clinit(JNIEnv*, jclass)
{
SSL_load_error_strings();
ERR_load_crypto_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
THREAD_setup();
#if !defined(OPENSSL_IS_BORINGSSL)
return JNI_FALSE;
#else
return JNI_TRUE;
#endif
}
static void NativeCrypto_ENGINE_load_dynamic(JNIEnv*, jclass) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("ENGINE_load_dynamic()");
ENGINE_load_dynamic();
#endif
}
#if !defined(OPENSSL_IS_BORINGSSL)
static jlong NativeCrypto_ENGINE_by_id(JNIEnv* env, jclass, jstring idJava) {
JNI_TRACE("ENGINE_by_id(%p)", idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
JNI_TRACE("ENGINE_by_id(%p) => id == null", idJava);
return 0;
}
JNI_TRACE("ENGINE_by_id(\"%s\")", id.c_str());
ENGINE* e = ENGINE_by_id(id.c_str());
if (e == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("ENGINE_by_id(\"%s\") => %p", id.c_str(), e);
return reinterpret_cast<uintptr_t>(e);
}
#else
static jlong NativeCrypto_ENGINE_by_id(JNIEnv*, jclass, jstring) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_add(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_add(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_add(e);
/*
* We tolerate errors, because the most likely error is that
* the ENGINE is already in the list.
*/
freeOpenSslErrorState();
JNI_TRACE("ENGINE_add(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_add(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_init(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_init(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_init(e);
JNI_TRACE("ENGINE_init(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_init(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_finish(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_finish(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_finish(e);
JNI_TRACE("ENGINE_finish(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_finish(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_free(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_free(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_free(e);
JNI_TRACE("ENGINE_free(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_free(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if defined(OPENSSL_IS_BORINGSSL)
extern "C" {
/* EVP_PKEY_from_keystore is from system/security/keystore-engine. */
extern EVP_PKEY* EVP_PKEY_from_keystore(const char *key_id);
}
#endif
static jlong NativeCrypto_ENGINE_load_private_key(JNIEnv* env, jclass, jlong engineRef,
jstring idJava) {
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "id == NULL");
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_load_private_key(%p, %p)", e, idJava);
Unique_EVP_PKEY pkey(ENGINE_load_private_key(e, id.c_str(), NULL, NULL));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key", throwInvalidKeyException);
return 0;
}
JNI_TRACE("ENGINE_load_private_key(%p, %p) => %p", e, idJava, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
#else
UNUSED_ARGUMENT(engineRef);
#if defined(NO_KEYSTORE_ENGINE)
jniThrowRuntimeException(env, "No keystore ENGINE support compiled in");
return 0;
#else
Unique_EVP_PKEY pkey(EVP_PKEY_from_keystore(id.c_str()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key", throwInvalidKeyException);
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
#endif
#endif
}
#if !defined(OPENSSL_IS_BORINGSSL)
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong engineRef)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_get_id(%p)", e);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_get_id(%p) => engine == null", e);
return NULL;
}
const char *id = ENGINE_get_id(e);
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF(id));
JNI_TRACE("ENGINE_get_id(%p) => \"%s\"", e, id);
return idJava.release();
}
#else
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong)
{
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF("keystore"));
return idJava.release();
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv* env, jclass, jlong engineRef,
jstring cmdJava, jstring argJava, jint cmd_optional)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d)", e, cmdJava, argJava, cmd_optional);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d) => engine == null", e, cmdJava, argJava,
cmd_optional);
return 0;
}
ScopedUtfChars cmdChars(env, cmdJava);
if (cmdChars.c_str() == NULL) {
return 0;
}
UniquePtr<ScopedUtfChars> arg;
const char* arg_c_str = NULL;
if (argJava != NULL) {
arg.reset(new ScopedUtfChars(env, argJava));
arg_c_str = arg->c_str();
if (arg_c_str == NULL) {
return 0;
}
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d)", e, cmdChars.c_str(), arg_c_str,
cmd_optional);
int ret = ENGINE_ctrl_cmd_string(e, cmdChars.c_str(), arg_c_str, cmd_optional);
if (ret != 1) {
throwExceptionIfNecessary(env, "ENGINE_ctrl_cmd_string");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => threw error", e,
cmdChars.c_str(), arg_c_str, cmd_optional);
return 0;
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => %d", e, cmdChars.c_str(),
arg_c_str, cmd_optional, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv*, jclass, jlong, jstring, jstring, jint)
{
return 0;
}
#endif
static jlong NativeCrypto_EVP_PKEY_new_DH(JNIEnv* env, jclass,
jbyteArray p, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p)",
p, g, pub_key, priv_key);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
jniThrowRuntimeException(env, "DH_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dh->p)) {
return 0;
}
if (!arrayToBignum(env, g, &dh->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dh->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dh->priv_key)) {
return 0;
}
if (dh->p == NULL || dh->g == NULL
|| (pub_key != NULL && dh->pub_key == NULL)
|| (priv_key != NULL && dh->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/* The public key can be recovered if the private key is available. */
if (dh->pub_key == NULL && dh->priv_key != NULL) {
if (!DH_generate_key(dh.get())) {
jniThrowRuntimeException(env, "EVP_PKEY_new_DH failed during pub_key generation");
return 0;
}
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DH failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
*/
static jlong NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass,
jbyteArray n, jbyteArray e, jbyteArray d,
jbyteArray p, jbyteArray q,
jbyteArray dmp1, jbyteArray dmq1,
jbyteArray iqmp) {
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p, dmp1=%p, dmq1=%p, iqmp=%p)",
n, e, d, p, q, dmp1, dmq1, iqmp);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_new failed");
return 0;
}
if (e == NULL && d == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "e == NULL && d == NULL");
JNI_TRACE("NativeCrypto_EVP_PKEY_new_RSA => e == NULL && d == NULL");
return 0;
}
if (!arrayToBignum(env, n, &rsa->n)) {
return 0;
}
if (e != NULL && !arrayToBignum(env, e, &rsa->e)) {
return 0;
}
if (d != NULL && !arrayToBignum(env, d, &rsa->d)) {
return 0;
}
if (p != NULL && !arrayToBignum(env, p, &rsa->p)) {
return 0;
}
if (q != NULL && !arrayToBignum(env, q, &rsa->q)) {
return 0;
}
if (dmp1 != NULL && !arrayToBignum(env, dmp1, &rsa->dmp1)) {
return 0;
}
if (dmq1 != NULL && !arrayToBignum(env, dmq1, &rsa->dmq1)) {
return 0;
}
if (iqmp != NULL && !arrayToBignum(env, iqmp, &rsa->iqmp)) {
return 0;
}
#ifdef WITH_JNI_TRACE
if (p != NULL && q != NULL) {
int check = RSA_check_key(rsa.get());
JNI_TRACE("EVP_PKEY_new_RSA(...) RSA_check_key returns %d", check);
}
#endif
if (rsa->n == NULL || (rsa->e == NULL && rsa->d == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/*
* If the private exponent is available, there is the potential to do signing
* operations. However, we can only do blinding if the public exponent is also
* available. Disable blinding if the public exponent isn't available.
*
* TODO[kroot]: We should try to recover the public exponent by trying
* some common ones such 3, 17, or 65537.
*/
if (rsa->d != NULL && rsa->e == NULL) {
JNI_TRACE("EVP_PKEY_new_RSA(...) disabling RSA blinding => %p", rsa.get());
rsa->flags |= RSA_FLAG_NO_BLINDING;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p dmp1=%p, dmq1=%p, iqmp=%p) => %p",
n, e, d, p, q, dmp1, dmq1, iqmp, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_EC_KEY(JNIEnv* env, jclass, jobject groupRef,
jobject pubkeyRef, jbyteArray keyJavaBytes) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p)", groupRef, pubkeyRef, keyJavaBytes);
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
if (group == NULL) {
return 0;
}
const EC_POINT* pubkey = pubkeyRef == NULL ? NULL :
fromContextObject<EC_POINT>(env, pubkeyRef);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) <- ptr", group, pubkey, keyJavaBytes);
Unique_BIGNUM key(NULL);
if (keyJavaBytes != NULL) {
BIGNUM* keyRef = NULL;
if (!arrayToBignum(env, keyJavaBytes, &keyRef)) {
return 0;
}
key.reset(keyRef);
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
jniThrowRuntimeException(env, "EC_KEY_new failed");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) > EC_KEY_set_group failed", group, pubkey,
keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (pubkey != NULL) {
if (EC_KEY_set_public_key(eckey.get(), pubkey) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_public_key");
return 0;
}
}
if (key.get() != NULL) {
if (EC_KEY_set_private_key(eckey.get(), key.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
if (pubkey == NULL) {
Unique_EC_POINT calcPubkey(EC_POINT_new(group));
if (!EC_POINT_mul(group, calcPubkey.get(), key.get(), NULL, NULL, NULL)) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => can't calulate public key", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
EC_KEY_set_public_key(eckey.get(), calcPubkey.get());
}
}
if (!EC_KEY_check_key(eckey.get())) {
JNI_TRACE("EVP_KEY_new_EC_KEY(%p, %p, %p) => invalid key created", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_check_key");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => %p", group, pubkey, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static int NativeCrypto_EVP_PKEY_type(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_type(%p)", pkey);
if (pkey == NULL) {
return -1;
}
int result = EVP_PKEY_type(pkey->type);
JNI_TRACE("EVP_PKEY_type(%p) => %d", pkey, result);
return result;
}
/**
* private static native int EVP_PKEY_size(int pkey);
*/
static int NativeCrypto_EVP_PKEY_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_size(%p)", pkey);
if (pkey == NULL) {
return -1;
}
int result = EVP_PKEY_size(pkey);
JNI_TRACE("EVP_PKEY_size(%p) => %d", pkey, result);
return result;
}
typedef int print_func(BIO*, const EVP_PKEY*, int, ASN1_PCTX*);
static jstring evp_print_func(JNIEnv* env, jobject pkeyRef, print_func* func,
const char* debug_name) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("%s(%p)", debug_name, pkey);
if (pkey == NULL) {
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (func(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, debug_name);
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("%s(%p) => \"%s\"", debug_name, pkey, tmp);
return description;
}
static jstring NativeCrypto_EVP_PKEY_print_public(JNIEnv* env, jclass, jobject pkeyRef) {
return evp_print_func(env, pkeyRef, EVP_PKEY_print_public, "EVP_PKEY_print_public");
}
static jstring NativeCrypto_EVP_PKEY_print_params(JNIEnv* env, jclass, jobject pkeyRef) {
return evp_print_func(env, pkeyRef, EVP_PKEY_print_params, "EVP_PKEY_print_params");
}
static void NativeCrypto_EVP_PKEY_free(JNIEnv*, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_free(%p)", pkey);
if (pkey != NULL) {
EVP_PKEY_free(pkey);
}
}
static jint NativeCrypto_EVP_PKEY_cmp(JNIEnv* env, jclass, jobject pkey1Ref, jobject pkey2Ref) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p)", pkey1Ref, pkey2Ref);
EVP_PKEY* pkey1 = fromContextObject<EVP_PKEY>(env, pkey1Ref);
if (pkey1 == NULL) {
JNI_TRACE("EVP_PKEY_cmp => pkey1 == NULL");
return 0;
}
EVP_PKEY* pkey2 = fromContextObject<EVP_PKEY>(env, pkey2Ref);
if (pkey2 == NULL) {
JNI_TRACE("EVP_PKEY_cmp => pkey2 == NULL");
return 0;
}
JNI_TRACE("EVP_PKEY_cmp(%p, %p) <- ptr", pkey1, pkey2);
int result = EVP_PKEY_cmp(pkey1, pkey2);
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => %d", pkey1, pkey2, result);
return result;
}
/*
* static native byte[] i2d_PKCS8_PRIV_KEY_INFO(int, byte[])
*/
static jbyteArray NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PKCS8_PRIV_KEY_INFO(%p)", pkey);
if (pkey == NULL) {
return NULL;
}
Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("key=%p i2d_PKCS8_PRIV_KEY_INFO => error from key to PKCS8", pkey);
return NULL;
}
return ASN1ToByteArray<PKCS8_PRIV_KEY_INFO>(env, pkcs8.get(), i2d_PKCS8_PRIV_KEY_INFO);
}
/*
* static native int d2i_PKCS8_PRIV_KEY_INFO(byte[])
*/
static jlong NativeCrypto_d2i_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jbyteArray keyJavaBytes) {
JNI_TRACE("d2i_PKCS8_PRIV_KEY_INFO(%p)", keyJavaBytes);
ScopedByteArrayRO bytes(env, keyJavaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => threw exception", keyJavaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &tmp, bytes.size()));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from DER to PKCS8", keyJavaBytes);
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from PKCS8 to key", keyJavaBytes);
return 0;
}
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => %p", keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* static native byte[] i2d_PUBKEY(int)
*/
static jbyteArray NativeCrypto_i2d_PUBKEY(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PUBKEY(%p)", pkey);
if (pkey == NULL) {
return NULL;
}
return ASN1ToByteArray<EVP_PKEY>(env, pkey, reinterpret_cast<int (*) (EVP_PKEY*, uint8_t **)>(i2d_PUBKEY));
}
/*
* static native int d2i_PUBKEY(byte[])
*/
static jlong NativeCrypto_d2i_PUBKEY(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("d2i_PUBKEY(%p)", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("d2i_PUBKEY(%p) => threw error", javaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, bytes.size()));
if (pkey.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PUBKEY => threw exception", javaBytes);
throwExceptionIfNecessary(env, "d2i_PUBKEY");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getRSAPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jbyteArray modulusBytes) {
JNI_TRACE("getRSAPrivateKeyWrapper(%p, %p)", javaKey, modulusBytes);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
RSA_set_method(rsa.get(), &android_rsa_method);
if (!arrayToBignum(env, modulusBytes, &rsa->n)) {
return 0;
}
RSA_set_app_data(rsa.get(), env->NewGlobalRef(javaKey));
#else
size_t cached_size;
if (!arrayToBignumSize(env, modulusBytes, &cached_size)) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
return 0;
}
ensure_engine_globals();
Unique_RSA rsa(RSA_new_method(g_engine));
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
ex_data->cached_size = cached_size;
RSA_set_ex_data(rsa.get(), g_rsa_exdata_index, ex_data);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getRSAPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "getRSAPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getECPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jobject groupRef) {
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("getECPrivateKeyWrapper(%p, %p)", javaKey, group);
if (group == NULL) {
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_EC_KEY ecKey(EC_KEY_new());
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
EC_KEY_set_group(ecKey.get(), group);
ECDSA_set_method(ecKey.get(), &android_ecdsa_method);
ECDSA_set_ex_data(ecKey.get(), EcdsaGetExDataIndex(), env->NewGlobalRef(javaKey));
#else
ensure_engine_globals();
Unique_EC_KEY ecKey(EC_KEY_new_method(g_engine));
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
if (!EC_KEY_set_ex_data(ecKey.get(), g_ecdsa_exdata_index, ex_data)) {
env->DeleteGlobalRef(ex_data->private_key);
delete ex_data;
jniThrowRuntimeException(env, "EC_KEY_set_ex_data");
return 0;
}
BIGNUM order;
BN_init(&order);
if (!EC_GROUP_get_order(group, &order, NULL)) {
BN_free(&order);
jniThrowRuntimeException(env, "EC_GROUP_get_order failed");
return 0;
}
ex_data->cached_size = BN_num_bytes(&order);
BN_free(&order);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getECPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getECPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), ecKey.get()) != 1) {
jniThrowRuntimeException(env, "getECPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(ecKey);
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native int RSA_generate_key(int modulusBits, byte[] publicExponent);
*/
static jlong NativeCrypto_RSA_generate_key_ex(JNIEnv* env, jclass, jint modulusBits,
jbyteArray publicExponent) {
JNI_TRACE("RSA_generate_key_ex(%d, %p)", modulusBits, publicExponent);
BIGNUM* eRef = NULL;
if (!arrayToBignum(env, publicExponent, &eRef)) {
return 0;
}
Unique_BIGNUM e(eRef);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
if (RSA_generate_key_ex(rsa.get(), modulusBits, e.get(), NULL) < 0) {
throwExceptionIfNecessary(env, "RSA_generate_key_ex");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("RSA_generate_key_ex(n=%d, e=%p) => %p", modulusBits, publicExponent, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jint NativeCrypto_RSA_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("RSA_size(%p)", pkey);
if (pkey == NULL) {
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_size failed");
return 0;
}
return static_cast<jint>(RSA_size(rsa.get()));
}
typedef int RSACryptOperation(size_t flen, const unsigned char* from, unsigned char* to, RSA* rsa,
int padding);
static jint RSA_crypt_operation(RSACryptOperation operation, const char* caller, JNIEnv* env,
jint flen, jbyteArray fromJavaBytes, jbyteArray toJavaBytes,
jobject pkeyRef, jint padding) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("%s(%d, %p, %p, %p)", caller, flen, fromJavaBytes, toJavaBytes, pkey);
if (pkey == NULL) {
return -1;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
return -1;
}
ScopedByteArrayRO from(env, fromJavaBytes);
if (from.get() == NULL) {
return -1;
}
ScopedByteArrayRW to(env, toJavaBytes);
if (to.get() == NULL) {
return -1;
}
int resultSize = operation(
static_cast<size_t>(flen),
reinterpret_cast<const unsigned char*>(from.get()),
reinterpret_cast<unsigned char*>(to.get()), rsa.get(), padding);
if (resultSize == -1) {
if (throwExceptionIfNecessary(env, caller)) {
JNI_TRACE("%s => threw error", caller);
} else {
throwBadPaddingException(env, caller);
JNI_TRACE("%s => threw padding exception", caller);
}
return -1;
}
JNI_TRACE("%s(%d, %p, %p, %p) => %d", caller, flen, fromJavaBytes, toJavaBytes, pkey,
resultSize);
return static_cast<jint>(resultSize);
}
static jint NativeCrypto_RSA_private_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_private_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
/*
* public static native byte[][] get_RSA_public_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_public_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
return joa;
}
/*
* public static native byte[][] get_RSA_private_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_private_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(8, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
if (rsa->e != NULL) {
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
}
if (rsa->d != NULL) {
jbyteArray d = bignumToArray(env, rsa->d, "d");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, d);
}
if (rsa->p != NULL) {
jbyteArray p = bignumToArray(env, rsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, p);
}
if (rsa->q != NULL) {
jbyteArray q = bignumToArray(env, rsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, q);
}
if (rsa->dmp1 != NULL) {
jbyteArray dmp1 = bignumToArray(env, rsa->dmp1, "dmp1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 5, dmp1);
}
if (rsa->dmq1 != NULL) {
jbyteArray dmq1 = bignumToArray(env, rsa->dmq1, "dmq1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 6, dmq1);
}
if (rsa->iqmp != NULL) {
jbyteArray iqmp = bignumToArray(env, rsa->iqmp, "iqmp");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 7, iqmp);
}
return joa;
}
static jlong NativeCrypto_DH_generate_parameters_ex(JNIEnv* env, jclass, jint primeBits, jlong generator) {
JNI_TRACE("DH_generate_parameters_ex(%d, %lld)", primeBits, (long long) generator);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowOutOfMemory(env, "Unable to allocate DH key");
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("DH_generate_parameters_ex generating parameters");
if (!DH_generate_parameters_ex(dh.get(), primeBits, generator, NULL)) {
JNI_TRACE("DH_generate_parameters_ex => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowRuntimeException(env, "NativeCrypto_DH_generate_parameters_ex failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
JNI_TRACE("DH_generate_parameters_ex failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("DH_generate_parameters_ex(n=%d, g=%lld) => %p", primeBits, (long long) generator,
pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static void NativeCrypto_DH_generate_key(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("DH_generate_key(%p)", pkey);
if (pkey == NULL) {
return;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "Unable to get DH key");
freeOpenSslErrorState();
}
if (!DH_generate_key(dh.get())) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
}
}
static jobjectArray NativeCrypto_get_DH_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_DH_params(%p)", pkey);
if (pkey == NULL) {
return NULL;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
throwExceptionIfNecessary(env, "get_DH_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(4, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dh->p != NULL) {
jbyteArray p = bignumToArray(env, dh->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, p);
}
if (dh->g != NULL) {
jbyteArray g = bignumToArray(env, dh->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, g);
}
if (dh->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dh->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, pub_key);
}
if (dh->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dh->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, priv_key);
}
return joa;
}
#define EC_CURVE_GFP 1
#define EC_CURVE_GF2M 2
/**
* Return group type or 0 if unknown group.
* EC_GROUP_GFP or EC_GROUP_GF2M
*/
#if !defined(OPENSSL_IS_BORINGSSL)
static int get_EC_GROUP_type(const EC_GROUP* group)
{
const int curve_nid = EC_METHOD_get_field_type(EC_GROUP_method_of(group));
if (curve_nid == NID_X9_62_prime_field) {
return EC_CURVE_GFP;
} else if (curve_nid == NID_X9_62_characteristic_two_field) {
return EC_CURVE_GF2M;
}
return 0;
}
#else
static int get_EC_GROUP_type(const EC_GROUP*)
{
return EC_CURVE_GFP;
}
#endif
static jlong NativeCrypto_EC_GROUP_new_by_curve_name(JNIEnv* env, jclass, jstring curveNameJava)
{
JNI_TRACE("EC_GROUP_new_by_curve_name(%p)", curveNameJava);
ScopedUtfChars curveName(env, curveNameJava);
if (curveName.c_str() == NULL) {
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s)", curveName.c_str());
int nid = OBJ_sn2nid(curveName.c_str());
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID name", curveName.c_str());
return 0;
}
EC_GROUP* group = EC_GROUP_new_by_curve_name(nid);
if (group == NULL) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID %d", curveName.c_str(), nid);
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => %p", curveName.c_str(), group);
return reinterpret_cast<uintptr_t>(group);
}
static jlong NativeCrypto_EC_GROUP_new_arbitrary(
JNIEnv* env, jclass, jbyteArray pBytes, jbyteArray aBytes,
jbyteArray bBytes, jbyteArray xBytes, jbyteArray yBytes,
jbyteArray orderBytes, jint cofactorInt)
{
BIGNUM *p = NULL, *a = NULL, *b = NULL, *x = NULL, *y = NULL;
BIGNUM *order = NULL, *cofactor = NULL;
JNI_TRACE("EC_GROUP_new_arbitrary");
if (cofactorInt < 1) {
jniThrowException(env, "java/lang/IllegalArgumentException", "cofactor < 1");
return 0;
}
cofactor = BN_new();
if (cofactor == NULL) {
return 0;
}
int ok = 1;
if (!arrayToBignum(env, pBytes, &p) ||
!arrayToBignum(env, aBytes, &a) ||
!arrayToBignum(env, bBytes, &b) ||
!arrayToBignum(env, xBytes, &x) ||
!arrayToBignum(env, yBytes, &y) ||
!arrayToBignum(env, orderBytes, &order) ||
!BN_set_word(cofactor, cofactorInt)) {
ok = 0;
}
Unique_BIGNUM pStorage(p);
Unique_BIGNUM aStorage(a);
Unique_BIGNUM bStorage(b);
Unique_BIGNUM xStorage(x);
Unique_BIGNUM yStorage(y);
Unique_BIGNUM orderStorage(order);
Unique_BIGNUM cofactorStorage(cofactor);
if (!ok) {
return 0;
}
Unique_BN_CTX ctx(BN_CTX_new());
Unique_EC_GROUP group(EC_GROUP_new_curve_GFp(p, a, b, ctx.get()));
if (group.get() == NULL) {
JNI_TRACE("EC_GROUP_new_curve_GFp => NULL");
throwExceptionIfNecessary(env, "EC_GROUP_new_curve_GFp");
return 0;
}
Unique_EC_POINT generator(EC_POINT_new(group.get()));
if (generator.get() == NULL) {
JNI_TRACE("EC_POINT_new => NULL");
freeOpenSslErrorState();
return 0;
}
if (!EC_POINT_set_affine_coordinates_GFp(group.get(), generator.get(), x, y, ctx.get())) {
JNI_TRACE("EC_POINT_set_affine_coordinates_GFp => error");
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates_GFp");
return 0;
}
if (!EC_GROUP_set_generator(group.get(), generator.get(), order, cofactor)) {
JNI_TRACE("EC_GROUP_set_generator => error");
throwExceptionIfNecessary(env, "EC_GROUP_set_generator");
return 0;
}
JNI_TRACE("EC_GROUP_new_arbitrary => %p", group.get());
return reinterpret_cast<uintptr_t>(group.release());
}
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv* env, jclass, jobject groupRef,
jint flag)
{
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d)", group, flag);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_asn1_flag => group == NULL");
return;
}
EC_GROUP_set_asn1_flag(group, flag);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d) => success", group, flag);
}
#else
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv*, jclass, jobject, jint)
{
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv* env, jclass,
jobject groupRef, jint form)
{
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d)", group, form);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_point_conversion_form => group == NULL");
return;
}
EC_GROUP_set_point_conversion_form(group, static_cast<point_conversion_form_t>(form));
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d) => success", group, form);
}
#else
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv*, jclass, jobject, jint)
{
}
#endif
static jstring NativeCrypto_EC_GROUP_get_curve_name(JNIEnv* env, jclass, jobject groupRef) {
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
return 0;
}
int nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_get_curve_name(%p) => unnamed curve", group);
return NULL;
}
const char* shortName = OBJ_nid2sn(nid);
JNI_TRACE("EC_GROUP_get_curve_name(%p) => \"%s\"", group, shortName);
return env->NewStringUTF(shortName);
}
static jobjectArray NativeCrypto_EC_GROUP_get_curve(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve => group == NULL");
return NULL;
}
Unique_BIGNUM p(BN_new());
Unique_BIGNUM a(BN_new());
Unique_BIGNUM b(BN_new());
if (get_EC_GROUP_type(group) != EC_CURVE_GFP) {
jniThrowRuntimeException(env, "invalid group");
return NULL;
}
int ret = EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), (BN_CTX*) NULL);
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_GROUP_get_curve");
return NULL;
}
jobjectArray joa = env->NewObjectArray(3, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray pArray = bignumToArray(env, p.get(), "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, pArray);
jbyteArray aArray = bignumToArray(env, a.get(), "a");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, aArray);
jbyteArray bArray = bignumToArray(env, b.get(), "b");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, bArray);
JNI_TRACE("EC_GROUP_get_curve(%p) => %p", group, joa);
return joa;
}
static jbyteArray NativeCrypto_EC_GROUP_get_order(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_order(%p)", group);
if (group == NULL) {
return NULL;
}
Unique_BIGNUM order(BN_new());
if (order.get() == NULL) {
JNI_TRACE("EC_GROUP_get_order(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_order(group, order.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_order(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_order");
return NULL;
}
jbyteArray orderArray = bignumToArray(env, order.get(), "order");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_order(%p) => %p", group, orderArray);
return orderArray;
}
static jint NativeCrypto_EC_GROUP_get_degree(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_degree(%p)", group);
if (group == NULL) {
return 0;
}
jint degree = EC_GROUP_get_degree(group);
if (degree == 0) {
JNI_TRACE("EC_GROUP_get_degree(%p) => unsupported", group);
jniThrowRuntimeException(env, "not supported");
return 0;
}
JNI_TRACE("EC_GROUP_get_degree(%p) => %d", group, degree);
return degree;
}
static jbyteArray NativeCrypto_EC_GROUP_get_cofactor(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_cofactor(%p)", group);
if (group == NULL) {
return NULL;
}
Unique_BIGNUM cofactor(BN_new());
if (cofactor.get() == NULL) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_cofactor(group, cofactor.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_cofactor");
return NULL;
}
jbyteArray cofactorArray = bignumToArray(env, cofactor.get(), "cofactor");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_cofactor(%p) => %p", group, cofactorArray);
return cofactorArray;
}
static jint NativeCrypto_get_EC_GROUP_type(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("get_EC_GROUP_type(%p)", group);
if (group == NULL) {
return 0;
}
int type = get_EC_GROUP_type(group);
if (type == 0) {
JNI_TRACE("get_EC_GROUP_type(%p) => curve type", group);
jniThrowRuntimeException(env, "unknown curve type");
} else {
JNI_TRACE("get_EC_GROUP_type(%p) => %d", group, type);
}
return type;
}
static void NativeCrypto_EC_GROUP_clear_free(JNIEnv* env, jclass, jlong groupRef)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_free(group);
JNI_TRACE("EC_GROUP_clear_free(%p) => success", group);
}
static jlong NativeCrypto_EC_GROUP_get_generator(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_generator(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_get_generator(%p) => group == null", group);
return 0;
}
const EC_POINT* generator = EC_GROUP_get0_generator(group);
Unique_EC_POINT dup(EC_POINT_dup(generator, group));
if (dup.get() == NULL) {
JNI_TRACE("EC_GROUP_get_generator(%p) => oom error", group);
jniThrowOutOfMemory(env, "unable to dupe generator");
return 0;
}
JNI_TRACE("EC_GROUP_get_generator(%p) => %p", group, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static jlong NativeCrypto_EC_POINT_new(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_POINT_new(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_new(%p) => group == null", group);
return 0;
}
EC_POINT* point = EC_POINT_new(group);
if (point == NULL) {
jniThrowOutOfMemory(env, "Unable create an EC_POINT");
return 0;
}
return reinterpret_cast<uintptr_t>(point);
}
static void NativeCrypto_EC_POINT_clear_free(JNIEnv* env, jclass, jlong groupRef) {
EC_POINT* group = reinterpret_cast<EC_POINT*>(groupRef);
JNI_TRACE("EC_POINT_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_POINT_free(group);
JNI_TRACE("EC_POINT_clear_free(%p) => success", group);
}
static void NativeCrypto_EC_POINT_set_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef, jbyteArray xjavaBytes, jbyteArray yjavaBytes)
{
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p)", groupRef, pointRef, xjavaBytes,
yjavaBytes);
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
if (group == NULL) {
return;
}
EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
if (point == NULL) {
return;
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) <- ptr", group, point, xjavaBytes,
yjavaBytes);
BIGNUM* xRef = NULL;
if (!arrayToBignum(env, xjavaBytes, &xRef)) {
return;
}
Unique_BIGNUM x(xRef);
BIGNUM* yRef = NULL;
if (!arrayToBignum(env, yjavaBytes, &yRef)) {
return;
}
Unique_BIGNUM y(yRef);
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_set_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
#if !defined(OPENSSL_NO_EC2M)
case EC_CURVE_GF2M:
ret = EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
#endif
default:
jniThrowRuntimeException(env, "invalid curve type");
return;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates");
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => %d", group, point,
xjavaBytes, yjavaBytes, ret);
}
static jobjectArray NativeCrypto_EC_POINT_get_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef)
{
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", groupRef, pointRef);
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
if (group == NULL) {
return NULL;
}
const EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
if (point == NULL) {
return NULL;
}
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) <- ptr", group, point);
Unique_BIGNUM x(BN_new());
Unique_BIGNUM y(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_get_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return NULL;
}
if (ret != 1) {
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
throwExceptionIfNecessary(env, "EC_POINT_get_affine_coordinates");
return NULL;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray xBytes = bignumToArray(env, x.get(), "x");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, xBytes);
jbyteArray yBytes = bignumToArray(env, y.get(), "y");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, yBytes);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) => %p", group, point, joa);
return joa;
}
static jlong NativeCrypto_EC_KEY_generate_key(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_KEY_generate_key(%p)", group);
if (group == NULL) {
return 0;
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_new() oom", group);
jniThrowOutOfMemory(env, "Unable to create an EC_KEY");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_set_group error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (EC_KEY_generate_key(eckey.get()) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_generate_key error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_KEY_generate_key");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EC_KEY_generate_key(%p) => %p", group, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EC_KEY_get1_group(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get1_group(%p)", pkey);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_get1_group(%p) => pkey == null", pkey);
return 0;
}
if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
jniThrowRuntimeException(env, "not EC key");
JNI_TRACE("EC_KEY_get1_group(%p) => not EC key (type == %d)", pkey,
EVP_PKEY_type(pkey->type));
return 0;
}
EC_GROUP* group = EC_GROUP_dup(EC_KEY_get0_group(pkey->pkey.ec));
JNI_TRACE("EC_KEY_get1_group(%p) => %p", pkey, group);
return reinterpret_cast<uintptr_t>(group);
}
static jbyteArray NativeCrypto_EC_KEY_get_private_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_private_key(%p)", pkey);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_get_private_key => pkey == NULL");
return NULL;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return NULL;
}
const BIGNUM *privkey = EC_KEY_get0_private_key(eckey.get());
jbyteArray privBytes = bignumToArray(env, privkey, "privkey");
if (env->ExceptionCheck()) {
JNI_TRACE("EC_KEY_get_private_key(%p) => threw error", pkey);
return NULL;
}
JNI_TRACE("EC_KEY_get_private_key(%p) => %p", pkey, privBytes);
return privBytes;
}
static jlong NativeCrypto_EC_KEY_get_public_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_public_key(%p)", pkey);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_get_public_key => pkey == NULL");
return 0;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return 0;
}
Unique_EC_POINT dup(EC_POINT_dup(EC_KEY_get0_public_key(eckey.get()),
EC_KEY_get0_group(eckey.get())));
if (dup.get() == NULL) {
JNI_TRACE("EC_KEY_get_public_key(%p) => can't dup public key", pkey);
jniThrowRuntimeException(env, "EC_POINT_dup");
return 0;
}
JNI_TRACE("EC_KEY_get_public_key(%p) => %p", pkey, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv* env, jclass, jobject pkeyRef,
jboolean enabled)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_set_nonce_from_hash(%p, %d)", pkey, enabled ? 1 : 0);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_set_nonce_from_hash => pkey == NULL");
return;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return;
}
EC_KEY_set_nonce_from_hash(eckey.get(), enabled ? 1 : 0);
}
#else
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv*, jclass, jobject, jboolean)
{
}
#endif
static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass,
jbyteArray outArray, jint outOffset, jobject pubkeyRef, jobject privkeyRef)
{
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p)", outArray, outOffset, pubkeyRef, privkeyRef);
EVP_PKEY* pubPkey = fromContextObject<EVP_PKEY>(env, pubkeyRef);
if (pubPkey == NULL) {
JNI_TRACE("ECDH_compute_key => pubPkey == NULL");
return -1;
}
EVP_PKEY* privPkey = fromContextObject<EVP_PKEY>(env, privkeyRef);
if (privPkey == NULL) {
JNI_TRACE("ECDH_compute_key => privPkey == NULL");
return -1;
}
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) <- ptr", outArray, outOffset, pubPkey, privPkey);
ScopedByteArrayRW out(env, outArray);
if (out.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) can't get output buffer",
outArray, outOffset, pubPkey, privPkey);
return -1;
}
if (ARRAY_OFFSET_INVALID(out, outOffset)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
if (pubPkey == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => pubPkey == null", pubPkey);
jniThrowNullPointerException(env, "pubPkey == null");
return -1;
}
Unique_EC_KEY pubkey(EVP_PKEY_get1_EC_KEY(pubPkey));
if (pubkey.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public", throwInvalidKeyException);
return -1;
}
const EC_POINT* pubkeyPoint = EC_KEY_get0_public_key(pubkey.get());
if (pubkeyPoint == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key point", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public", throwInvalidKeyException);
return -1;
}
if (privPkey == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => privKey == null", pubPkey);
jniThrowNullPointerException(env, "privPkey == null");
return -1;
}
Unique_EC_KEY privkey(EVP_PKEY_get1_EC_KEY(privPkey));
if (privkey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY private", throwInvalidKeyException);
return -1;
}
int outputLength = ECDH_compute_key(
&out[outOffset],
out.size() - outOffset,
pubkeyPoint,
privkey.get(),
NULL // No KDF
);
if (outputLength == -1) {
JNI_TRACE("ECDH_compute_key(%p) => outputLength = -1", pubPkey);
throwExceptionIfNecessary(env, "ECDH_compute_key", throwInvalidKeyException);
return -1;
}
JNI_TRACE("ECDH_compute_key(%p) => outputLength=%d", pubPkey, outputLength);
return outputLength;
}
static jlong NativeCrypto_EVP_MD_CTX_create(JNIEnv* env, jclass) {
JNI_TRACE_MD("EVP_MD_CTX_create()");
Unique_EVP_MD_CTX ctx(EVP_MD_CTX_create());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable create a EVP_MD_CTX");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_create() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static void NativeCrypto_EVP_MD_CTX_cleanup(JNIEnv* env, jclass, jobject ctxRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_cleanup(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_cleanup(ctx);
}
}
static void NativeCrypto_EVP_MD_CTX_destroy(JNIEnv*, jclass, jlong ctxRef) {
EVP_MD_CTX* ctx = reinterpret_cast<EVP_MD_CTX*>(ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_destroy(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_destroy(ctx);
}
}
static jint NativeCrypto_EVP_MD_CTX_copy_ex(JNIEnv* env, jclass, jobject dstCtxRef,
jobject srcCtxRef) {
JNI_TRACE_MD("EVP_MD_CTX_copy_ex(%p. %p)", dstCtxRef, srcCtxRef);
EVP_MD_CTX* dst_ctx = fromContextObject<EVP_MD_CTX>(env, dstCtxRef);
if (dst_ctx == NULL) {
JNI_TRACE_MD("EVP_MD_CTX_copy_ex => dst_ctx == NULL");
return 0;
}
const EVP_MD_CTX* src_ctx = fromContextObject<EVP_MD_CTX>(env, srcCtxRef);
if (src_ctx == NULL) {
JNI_TRACE_MD("EVP_MD_CTX_copy_ex => src_ctx == NULL");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_copy_ex(%p. %p) <- ptr", dst_ctx, src_ctx);
int result = EVP_MD_CTX_copy_ex(dst_ctx, src_ctx);
if (result == 0) {
jniThrowRuntimeException(env, "Unable to copy EVP_MD_CTX");
freeOpenSslErrorState();
}
JNI_TRACE_MD("EVP_MD_CTX_copy_ex(%p, %p) => %d", dst_ctx, src_ctx, result);
return result;
}
/*
* public static native int EVP_DigestFinal_ex(long, byte[], int)
*/
static jint NativeCrypto_EVP_DigestFinal_ex(JNIEnv* env, jclass, jobject ctxRef, jbyteArray hash,
jint offset) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_DigestFinal_ex(%p, %p, %d)", ctx, hash, offset);
if (ctx == NULL) {
JNI_TRACE("EVP_DigestFinal_ex => ctx == NULL");
return -1;
} else if (hash == NULL) {
jniThrowNullPointerException(env, "hash == null");
return -1;
}
ScopedByteArrayRW hashBytes(env, hash);
if (hashBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_DigestFinal_ex(ctx,
reinterpret_cast<unsigned char*>(hashBytes.get() + offset),
&bytesWritten);
if (ok == 0) {
throwExceptionIfNecessary(env, "EVP_DigestFinal_ex");
}
JNI_TRACE_MD("EVP_DigestFinal_ex(%p, %p, %d) => %d (%d)", ctx, hash, offset, bytesWritten, ok);
return bytesWritten;
}
static jint NativeCrypto_EVP_DigestInit_ex(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong evpMdRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* evp_md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE_MD("EVP_DigestInit_ex(%p, %p)", ctx, evp_md);
if (ctx == NULL) {
JNI_TRACE("EVP_DigestInit_ex(%p) => ctx == NULL", evp_md);
return 0;
} else if (evp_md == NULL) {
jniThrowNullPointerException(env, "evp_md == null");
return 0;
}
int ok = EVP_DigestInit_ex(ctx, evp_md, NULL);
if (ok == 0) {
bool exception = throwExceptionIfNecessary(env, "EVP_DigestInit_ex");
if (exception) {
JNI_TRACE("EVP_DigestInit_ex(%p) => threw exception", evp_md);
return 0;
}
}
JNI_TRACE_MD("EVP_DigestInit_ex(%p, %p) => %d", ctx, evp_md, ok);
return ok;
}
/*
* public static native int EVP_get_digestbyname(java.lang.String)
*/
static jlong NativeCrypto_EVP_get_digestbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%p)", algorithm);
if (algorithm == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s)", algorithmChars.c_str());
#if !defined(OPENSSL_IS_BORINGSSL)
const EVP_MD* evp_md = EVP_get_digestbyname(algorithmChars.c_str());
if (evp_md == NULL) {
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => %p", algorithmChars.c_str(), evp_md);
return reinterpret_cast<uintptr_t>(evp_md);
#else
const char *alg = algorithmChars.c_str();
const EVP_MD *md;
if (strcasecmp(alg, "md4") == 0) {
md = EVP_md4();
} else if (strcasecmp(alg, "md5") == 0) {
md = EVP_md5();
} else if (strcasecmp(alg, "sha1") == 0) {
md = EVP_sha1();
} else if (strcasecmp(alg, "sha224") == 0) {
md = EVP_sha224();
} else if (strcasecmp(alg, "sha256") == 0) {
md = EVP_sha256();
} else if (strcasecmp(alg, "sha384") == 0) {
md = EVP_sha384();
} else if (strcasecmp(alg, "sha512") == 0) {
md = EVP_sha512();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
return reinterpret_cast<uintptr_t>(md);
#endif
}
/*
* public static native int EVP_MD_size(long)
*/
static jint NativeCrypto_EVP_MD_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p) => %d", evp_md, result);
return result;
}
/*
* public static int void EVP_MD_block_size(long)
*/
static jint NativeCrypto_EVP_MD_block_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_block_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p) => %d", evp_md, result);
return result;
}
static jlong evpDigestSignVerifyInit(
JNIEnv* env,
int (*init_func)(EVP_MD_CTX*, EVP_PKEY_CTX**, const EVP_MD*, ENGINE*, EVP_PKEY*),
const char* jniName,
jobject evpMdCtxRef, jlong evpMdRef, jobject pkeyRef) {
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
if (mdCtx == NULL) {
JNI_TRACE("%s => mdCtx == NULL", jniName);
return 0;
}
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
if (pkey == NULL) {
JNI_TRACE("ctx=%p $s => pkey == NULL", mdCtx, jniName);
return 0;
}
JNI_TRACE("%s(%p, %p, %p) <- ptr", jniName, mdCtx, md, pkey);
if (md == NULL) {
JNI_TRACE("ctx=%p %s => md == NULL", mdCtx, jniName);
jniThrowNullPointerException(env, "md == null");
return 0;
}
EVP_PKEY_CTX* pctx = NULL;
if (init_func(mdCtx, &pctx, md, (ENGINE *) NULL, pkey) <= 0) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
return 0;
}
JNI_TRACE("%s(%p, %p, %p) => success", jniName, mdCtx, md, pkey);
return reinterpret_cast<jlong>(pctx);
}
static jlong NativeCrypto_EVP_DigestSignInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jobject pkeyRef) {
return evpDigestSignVerifyInit(
env, EVP_DigestSignInit, "EVP_DigestSignInit", evpMdCtxRef, evpMdRef, pkeyRef);
}
static jlong NativeCrypto_EVP_DigestVerifyInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jobject pkeyRef) {
return evpDigestSignVerifyInit(
env, EVP_DigestVerifyInit, "EVP_DigestVerifyInit", evpMdCtxRef, evpMdRef, pkeyRef);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jlong inPtr, jint inLength,
const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *, size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const void *p = reinterpret_cast<const void *>(inPtr);
JNI_TRACE_MD("%s(%p, %p, %d)", jniName, mdCtx, p, inLength);
if (mdCtx == NULL) {
return;
}
if (p == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (!update_func(mdCtx, p, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d) => success", jniName, mdCtx, p, inLength);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jbyteArray inJavaBytes, jint inOffset,
jint inLength, const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *,
size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE_MD("%s(%p, %p, %d, %d)", jniName, mdCtx, inJavaBytes, inOffset, inLength);
if (mdCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inJavaBytes);
if (inBytes.get() == NULL) {
return;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inBytes");
return;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char *>(inBytes.get());
if (!update_func(mdCtx, tmp + inOffset, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d, %d) => success", jniName, mdCtx, inJavaBytes, inOffset, inLength);
}
static void NativeCrypto_EVP_DigestUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong inPtr, jint inLength) {
evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestUpdateDirect", EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestSignUpdate",
EVP_DigestSignUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong inPtr, jint inLength) {
evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestSignUpdateDirect",
EVP_DigestSignUpdate);
}
static void NativeCrypto_EVP_DigestVerifyUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestVerifyUpdate",
EVP_DigestVerifyUpdate);
}
static void NativeCrypto_EVP_DigestVerifyUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong inPtr, jint inLength) {
evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestVerifyUpdateDirect",
EVP_DigestVerifyUpdate);
}
static jbyteArray NativeCrypto_EVP_DigestSignFinal(JNIEnv* env, jclass, jobject evpMdCtxRef)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestSignFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return NULL;
}
size_t maxLen;
if (EVP_DigestSignFinal(mdCtx, NULL, &maxLen) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return NULL;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[maxLen]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate signature buffer");
return 0;
}
size_t actualLen;
if (EVP_DigestSignFinal(mdCtx, buffer.get(), &actualLen) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return NULL;
}
if (actualLen > maxLen) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => signature too long: %d vs %d",
actualLen, maxLen);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal signature too long");
return NULL;
}
ScopedLocalRef<jbyteArray> sigJavaBytes(env, env->NewByteArray(actualLen));
if (sigJavaBytes.get() == NULL) {
jniThrowOutOfMemory(env, "Failed to allocate signature byte[]");
return NULL;
}
env->SetByteArrayRegion(
sigJavaBytes.get(), 0, actualLen, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("EVP_DigestSignFinal(%p) => %p", mdCtx, sigJavaBytes.get());
return sigJavaBytes.release();
}
static jboolean NativeCrypto_EVP_DigestVerifyFinal(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray signature, jint offset, jint len)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestVerifyFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return 0;
}
ScopedByteArrayRO sigBytes(env, signature);
if (sigBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(sigBytes, offset, len)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "signature");
return 0;
}
const unsigned char *sigBuf = reinterpret_cast<const unsigned char *>(sigBytes.get());
int err = EVP_DigestVerifyFinal(mdCtx, sigBuf + offset, len);
jboolean result;
if (err == 1) {
// Signature verified
result = 1;
} else if (err == 0) {
// Signature did not verify
result = 0;
} else {
// Error while verifying signature
JNI_TRACE("ctx=%p EVP_DigestVerifyFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestVerifyFinal");
return 0;
}
// If the signature did not verify, BoringSSL error queue contains an error (BAD_SIGNATURE).
// Clear the error queue to prevent its state from affecting future operations.
freeOpenSslErrorState();
JNI_TRACE("EVP_DigestVerifyFinal(%p) => %d", mdCtx, result);
return result;
}
static jlong NativeCrypto_EVP_get_cipherbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("EVP_get_cipherbyname(%p)", algorithm);
#if !defined(OPENSSL_IS_BORINGSSL)
if (algorithm == NULL) {
JNI_TRACE("EVP_get_cipherbyname(%p) => threw exception algorithm == null", algorithm);
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("EVP_get_cipherbyname(%p) => algorithm = %s", algorithm, algorithmChars.c_str());
const EVP_CIPHER* evp_cipher = EVP_get_cipherbyname(algorithmChars.c_str());
if (evp_cipher == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("EVP_get_cipherbyname(%s) => %p", algorithmChars.c_str(), evp_cipher);
return reinterpret_cast<uintptr_t>(evp_cipher);
#else
ScopedUtfChars scoped_alg(env, algorithm);
const char *alg = scoped_alg.c_str();
const EVP_CIPHER *cipher;
if (strcasecmp(alg, "rc4") == 0) {
cipher = EVP_rc4();
} else if (strcasecmp(alg, "des-cbc") == 0) {
cipher = EVP_des_cbc();
} else if (strcasecmp(alg, "des-ede-cbc") == 0) {
cipher = EVP_des_cbc();
} else if (strcasecmp(alg, "des-ede3-cbc") == 0) {
cipher = EVP_des_ede3_cbc();
} else if (strcasecmp(alg, "aes-128-ecb") == 0) {
cipher = EVP_aes_128_ecb();
} else if (strcasecmp(alg, "aes-128-cbc") == 0) {
cipher = EVP_aes_128_cbc();
} else if (strcasecmp(alg, "aes-128-ctr") == 0) {
cipher = EVP_aes_128_ctr();
} else if (strcasecmp(alg, "aes-128-gcm") == 0) {
cipher = EVP_aes_128_gcm();
} else if (strcasecmp(alg, "aes-192-ecb") == 0) {
cipher = EVP_aes_192_ecb();
} else if (strcasecmp(alg, "aes-192-cbc") == 0) {
cipher = EVP_aes_192_cbc();
} else if (strcasecmp(alg, "aes-192-ctr") == 0) {
cipher = EVP_aes_192_ctr();
} else if (strcasecmp(alg, "aes-192-gcm") == 0) {
cipher = EVP_aes_192_gcm();
} else if (strcasecmp(alg, "aes-256-ecb") == 0) {
cipher = EVP_aes_256_ecb();
} else if (strcasecmp(alg, "aes-256-cbc") == 0) {
cipher = EVP_aes_256_cbc();
} else if (strcasecmp(alg, "aes-256-ctr") == 0) {
cipher = EVP_aes_256_ctr();
} else if (strcasecmp(alg, "aes-256-gcm") == 0) {
cipher = EVP_aes_256_gcm();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
return 0;
}
return reinterpret_cast<uintptr_t>(cipher);
#endif
}
static void NativeCrypto_EVP_CipherInit_ex(JNIEnv* env, jclass, jobject ctxRef, jlong evpCipherRef,
jbyteArray keyArray, jbyteArray ivArray, jboolean encrypting) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d)", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
if (ctx == NULL) {
JNI_TRACE("EVP_CipherUpdate => ctx == null");
return;
}
// The key can be null if we need to set extra parameters.
UniquePtr<unsigned char[]> keyPtr;
if (keyArray != NULL) {
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
keyPtr.reset(new unsigned char[keyBytes.size()]);
memcpy(keyPtr.get(), keyBytes.get(), keyBytes.size());
}
// The IV can be null if we're using ECB.
UniquePtr<unsigned char[]> ivPtr;
if (ivArray != NULL) {
ScopedByteArrayRO ivBytes(env, ivArray);
if (ivBytes.get() == NULL) {
return;
}
ivPtr.reset(new unsigned char[ivBytes.size()]);
memcpy(ivPtr.get(), ivBytes.get(), ivBytes.size());
}
if (!EVP_CipherInit_ex(ctx, evpCipher, NULL, keyPtr.get(), ivPtr.get(), encrypting ? 1 : 0)) {
throwExceptionIfNecessary(env, "EVP_CipherInit_ex");
JNI_TRACE("EVP_CipherInit_ex => error initializing cipher");
return;
}
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d) => success", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
}
/*
* public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
* int inOffset, int inLength);
*/
static jint NativeCrypto_EVP_CipherUpdate(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray inArray, jint inOffset, jint inLength) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d)", ctx, outArray, outOffset, inArray, inOffset);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CipherUpdate => ctx == null", ctx);
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inBytes");
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(outBytes, outOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "outBytes");
return 0;
}
JNI_TRACE("ctx=%p EVP_CipherUpdate in=%p in.length=%zd inOffset=%zd inLength=%zd out=%p out.length=%zd outOffset=%zd",
ctx, inBytes.get(), inBytes.size(), inOffset, inLength, outBytes.get(), outBytes.size(), outOffset);
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
const unsigned char* in = reinterpret_cast<const unsigned char*>(inBytes.get());
int outl;
if (!EVP_CipherUpdate(ctx, out + outOffset, &outl, in + inOffset, inLength)) {
throwExceptionIfNecessary(env, "EVP_CipherUpdate");
JNI_TRACE("ctx=%p EVP_CipherUpdate => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d) => %d", ctx, outArray, outOffset, inArray,
inOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CipherFinal_ex(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray outArray, jint outOffset) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherFinal_ex(%p, %p, %d)", ctx, outArray, outOffset);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => ctx == null", ctx);
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
int outl;
if (!EVP_CipherFinal_ex(ctx, out + outOffset, &outl)) {
if (throwExceptionIfNecessary(env, "EVP_CipherFinal_ex")) {
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw error", ctx);
} else {
throwBadPaddingException(env, "EVP_CipherFinal_ex");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw padding exception", ctx);
}
return 0;
}
JNI_TRACE("EVP_CipherFinal(%p, %p, %d) => %d", ctx, outArray, outOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CIPHER_iv_length(JNIEnv* env, jclass, jlong evpCipherRef) {
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CIPHER_iv_length(%p)", evpCipher);
if (evpCipher == NULL) {
jniThrowNullPointerException(env, "evpCipher == null");
JNI_TRACE("EVP_CIPHER_iv_length => evpCipher == null");
return 0;
}
const int ivLength = EVP_CIPHER_iv_length(evpCipher);
JNI_TRACE("EVP_CIPHER_iv_length(%p) => %d", evpCipher, ivLength);
return ivLength;
}
static jlong NativeCrypto_EVP_CIPHER_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("EVP_CIPHER_CTX_new()");
Unique_EVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate cipher context");
JNI_TRACE("EVP_CipherInit_ex => context allocation error");
return 0;
}
JNI_TRACE("EVP_CIPHER_CTX_new() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static jint NativeCrypto_EVP_CIPHER_CTX_block_size(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p)", ctx);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_block_size => ctx == null", ctx);
return 0;
}
int blockSize = EVP_CIPHER_CTX_block_size(ctx);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p) => %d", ctx, blockSize);
return blockSize;
}
static jint NativeCrypto_get_EVP_CIPHER_CTX_buf_len(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p)", ctx);
if (ctx == NULL) {
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_buf_len => ctx == null", ctx);
return 0;
}
int buf_len = ctx->buf_len;
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p) => %d", ctx, buf_len);
return buf_len;
}
static jboolean NativeCrypto_get_EVP_CIPHER_CTX_final_used(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_final_used(%p)", ctx);
if (ctx == NULL) {
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_final_used => ctx == null", ctx);
return 0;
}
bool final_used = ctx->final_used != 0;
JNI_TRACE("get_EVP_CIPHER_CTX_final_used(%p) => %d", ctx, final_used);
return final_used;
}
static void NativeCrypto_EVP_CIPHER_CTX_set_padding(JNIEnv* env, jclass, jobject ctxRef,
jboolean enablePaddingBool) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
jint enablePadding = enablePaddingBool ? 1 : 0;
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d)", ctx, enablePadding);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_padding => ctx == null", ctx);
return;
}
EVP_CIPHER_CTX_set_padding(ctx, enablePadding); // Not void, but always returns 1.
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d) => success", ctx, enablePadding);
}
static void NativeCrypto_EVP_CIPHER_CTX_set_key_length(JNIEnv* env, jclass, jobject ctxRef,
jint keySizeBits) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d)", ctx, keySizeBits);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_key_length => ctx == null", ctx);
return;
}
if (!EVP_CIPHER_CTX_set_key_length(ctx, keySizeBits)) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_CIPHER_CTX_set_key_length");
JNI_TRACE("NativeCrypto_EVP_CIPHER_CTX_set_key_length => threw error");
return;
}
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d) => success", ctx, keySizeBits);
}
static void NativeCrypto_EVP_CIPHER_CTX_free(JNIEnv*, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_free(%p)", ctx);
EVP_CIPHER_CTX_free(ctx);
}
static jlong NativeCrypto_EVP_aead_aes_128_gcm(JNIEnv* env, jclass) {
#if defined(OPENSSL_IS_BORINGSSL)
UNUSED_ARGUMENT(env);
const EVP_AEAD* ctx = EVP_aead_aes_128_gcm();
JNI_TRACE("EVP_aead_aes_128_gcm => ctx=%p", ctx);
return reinterpret_cast<jlong>(ctx);
#else
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jlong NativeCrypto_EVP_aead_aes_256_gcm(JNIEnv* env, jclass) {
#if defined(OPENSSL_IS_BORINGSSL)
UNUSED_ARGUMENT(env);
const EVP_AEAD* ctx = EVP_aead_aes_256_gcm();
JNI_TRACE("EVP_aead_aes_256_gcm => ctx=%p", ctx);
return reinterpret_cast<jlong>(ctx);
#else
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jlong NativeCrypto_EVP_AEAD_CTX_init(JNIEnv* env, jclass, jlong evpAeadRef,
jbyteArray keyArray, jint tagLen) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_CTX_init(%p, %p, %d)", evpAead, keyArray, tagLen);
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return 0;
}
Unique_EVP_AEAD_CTX aeadCtx(reinterpret_cast<EVP_AEAD_CTX*>(
OPENSSL_malloc(sizeof(EVP_AEAD_CTX))));
memset(aeadCtx.get(), 0, sizeof(EVP_AEAD_CTX));
const uint8_t* tmp = reinterpret_cast<const uint8_t*>(keyBytes.get());
int ret = EVP_AEAD_CTX_init(aeadCtx.get(), evpAead, tmp, keyBytes.size(), tagLen, NULL);
if (ret != 1) {
throwExceptionIfNecessary(env, "EVP_AEAD_CTX_init");
JNI_TRACE("EVP_AEAD_CTX_init(%p, %p, %d) => fail EVP_AEAD_CTX_init", evpAead,
keyArray, tagLen);
return 0;
}
JNI_TRACE("EVP_AEAD_CTX_init(%p, %p, %d) => %p", evpAead, keyArray, tagLen, aeadCtx.get());
return reinterpret_cast<jlong>(aeadCtx.release());
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
UNUSED_ARGUMENT(keyArray);
UNUSED_ARGUMENT(tagLen);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static void NativeCrypto_EVP_AEAD_CTX_cleanup(JNIEnv* env, jclass, jlong evpAeadCtxRef) {
#if defined(OPENSSL_IS_BORINGSSL)
EVP_AEAD_CTX* evpAeadCtx = reinterpret_cast<EVP_AEAD_CTX*>(evpAeadCtxRef);
JNI_TRACE("EVP_AEAD_CTX_cleanup(%p)", evpAeadCtx);
if (evpAeadCtx == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return;
}
EVP_AEAD_CTX_cleanup(evpAeadCtx);
OPENSSL_free(evpAeadCtx);
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadCtxRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
#endif
}
static jint NativeCrypto_EVP_AEAD_max_overhead(JNIEnv* env, jclass, jlong evpAeadRef) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_max_overhead(%p)", evpAead);
if (evpAead == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return 0;
}
int maxOverhead = EVP_AEAD_max_overhead(evpAead);
JNI_TRACE("EVP_AEAD_max_overhead(%p) => %d", evpAead, maxOverhead);
return maxOverhead;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jint NativeCrypto_EVP_AEAD_nonce_length(JNIEnv* env, jclass, jlong evpAeadRef) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_nonce_length(%p)", evpAead);
if (evpAead == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return 0;
}
int nonceLength = EVP_AEAD_nonce_length(evpAead);
JNI_TRACE("EVP_AEAD_nonce_length(%p) => %d", evpAead, nonceLength);
return nonceLength;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jint NativeCrypto_EVP_AEAD_max_tag_len(JNIEnv* env, jclass, jlong evpAeadRef) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_max_tag_len(%p)", evpAead);
if (evpAead == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return 0;
}
int maxTagLen = EVP_AEAD_max_tag_len(evpAead);
JNI_TRACE("EVP_AEAD_max_tag_len(%p) => %d", evpAead, maxTagLen);
return maxTagLen;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
#if defined(OPENSSL_IS_BORINGSSL)
typedef int (*evp_aead_ctx_op_func)(const EVP_AEAD_CTX *ctx, uint8_t *out,
size_t *out_len, size_t max_out_len,
const uint8_t *nonce, size_t nonce_len,
const uint8_t *in, size_t in_len,
const uint8_t *ad, size_t ad_len);
static jint evp_aead_ctx_op(JNIEnv* env, jobject ctxRef, jbyteArray outArray, jint outOffset,
jbyteArray nonceArray, jbyteArray inArray, jint inOffset, jint inLength,
jbyteArray aadArray, evp_aead_ctx_op_func realFunc) {
EVP_AEAD_CTX* ctx = fromContextObject<EVP_AEAD_CTX>(env, ctxRef);
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p)", ctx, outArray, outOffset,
nonceArray, inArray, inOffset, inLength, aadArray);
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_INVALID(outBytes, outOffset)) {
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p)", ctx, outArray, outOffset,
nonceArray, inArray, inOffset, inLength, aadArray);
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "out");
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p)", ctx, outArray, outOffset,
nonceArray, inArray, inOffset, inLength, aadArray);
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "in");
return 0;
}
UniquePtr<ScopedByteArrayRO> aad;
const uint8_t* aad_chars = NULL;
size_t aad_chars_size = 0;
if (aadArray != NULL) {
aad.reset(new ScopedByteArrayRO(env, aadArray));
aad_chars = reinterpret_cast<const uint8_t*>(aad->get());
if (aad_chars == NULL) {
return 0;
}
aad_chars_size = aad->size();
}
ScopedByteArrayRO nonceBytes(env, nonceArray);
if (nonceBytes.get() == NULL) {
return 0;
}
uint8_t* outTmp = reinterpret_cast<uint8_t*>(outBytes.get());
const uint8_t* inTmp = reinterpret_cast<const uint8_t*>(inBytes.get());
const uint8_t* nonceTmp = reinterpret_cast<const uint8_t*>(nonceBytes.get());
size_t actualOutLength;
int ret = realFunc(ctx, outTmp + outOffset, &actualOutLength, outBytes.size() - outOffset,
nonceTmp, nonceBytes.size(), inTmp + inOffset, inLength, aad_chars, aad_chars_size);
if (ret != 1) {
throwExceptionIfNecessary(env, "evp_aead_ctx_op");
}
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p) => ret=%d, outLength=%zd",
ctx, outArray, outOffset, nonceArray, inArray, inOffset, inLength, aadArray, ret,
actualOutLength);
return static_cast<jlong>(actualOutLength);
}
#endif
static jint NativeCrypto_EVP_AEAD_CTX_seal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray nonceArray, jbyteArray inArray, jint inOffset, jint inLength,
jbyteArray aadArray) {
#if defined(OPENSSL_IS_BORINGSSL)
return evp_aead_ctx_op(env, ctxRef, outArray, outOffset, nonceArray, inArray, inOffset,
inLength, aadArray, EVP_AEAD_CTX_seal);
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(ctxRef);
UNUSED_ARGUMENT(outArray);
UNUSED_ARGUMENT(outOffset);
UNUSED_ARGUMENT(nonceArray);
UNUSED_ARGUMENT(inArray);
UNUSED_ARGUMENT(inOffset);
UNUSED_ARGUMENT(inLength);
UNUSED_ARGUMENT(aadArray);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jint NativeCrypto_EVP_AEAD_CTX_open(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray nonceArray, jbyteArray inArray, jint inOffset, jint inLength,
jbyteArray aadArray) {
#if defined(OPENSSL_IS_BORINGSSL)
return evp_aead_ctx_op(env, ctxRef, outArray, outOffset, nonceArray, inArray, inOffset,
inLength, aadArray, EVP_AEAD_CTX_open);
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(ctxRef);
UNUSED_ARGUMENT(outArray);
UNUSED_ARGUMENT(outOffset);
UNUSED_ARGUMENT(nonceArray);
UNUSED_ARGUMENT(inArray);
UNUSED_ARGUMENT(inOffset);
UNUSED_ARGUMENT(inLength);
UNUSED_ARGUMENT(aadArray);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jlong NativeCrypto_HMAC_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("HMAC_CTX_new");
HMAC_CTX* hmacCtx = reinterpret_cast<HMAC_CTX*>(OPENSSL_malloc(sizeof(HMAC_CTX)));
if (hmacCtx == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate HMAC_CTX");
return 0;
}
HMAC_CTX_init(hmacCtx);
return reinterpret_cast<jlong>(hmacCtx);
}
static void NativeCrypto_HMAC_CTX_free(JNIEnv*, jclass, jlong hmacCtxRef) {
HMAC_CTX* hmacCtx = reinterpret_cast<HMAC_CTX*>(hmacCtxRef);
JNI_TRACE("HMAC_CTX_free(%p)", hmacCtx);
if (hmacCtx == NULL) {
return;
}
HMAC_CTX_cleanup(hmacCtx);
OPENSSL_free(hmacCtx);
}
static void NativeCrypto_HMAC_Init_ex(JNIEnv* env, jclass, jobject hmacCtxRef, jbyteArray keyArray,
jobject evpMdRef) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE("HMAC_Init_ex(%p, %p, %p)", hmacCtx, keyArray, md);
if (hmacCtx == NULL) {
jniThrowNullPointerException(env, "hmacCtx == null");
return;
}
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
const uint8_t* keyPtr = reinterpret_cast<const uint8_t*>(keyBytes.get());
if (!HMAC_Init_ex(hmacCtx, keyPtr, keyBytes.size(), md, NULL)) {
throwExceptionIfNecessary(env, "HMAC_Init_ex");
JNI_TRACE("HMAC_Init_ex(%p, %p, %p) => fail HMAC_Init_ex", hmacCtx, keyArray, md);
return;
}
}
static void NativeCrypto_HMAC_UpdateDirect(JNIEnv* env, jclass, jobject hmacCtxRef, jlong inPtr,
int inLength) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
const uint8_t* p = reinterpret_cast<const uint8_t*>(inPtr);
JNI_TRACE("HMAC_UpdateDirect(%p, %p, %d)", hmacCtx, p, inLength);
if (hmacCtx == NULL) {
return;
}
if (p == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (!HMAC_Update(hmacCtx, p, inLength)) {
JNI_TRACE("HMAC_UpdateDirect(%p, %p, %d) => threw exception", hmacCtx, p, inLength);
throwExceptionIfNecessary(env, "HMAC_UpdateDirect");
return;
}
}
static void NativeCrypto_HMAC_Update(JNIEnv* env, jclass, jobject hmacCtxRef, jbyteArray inArray,
jint inOffset, int inLength) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
JNI_TRACE("HMAC_Update(%p, %p, %d, %d)", hmacCtx, inArray, inOffset, inLength);
if (hmacCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inBytes");
return;
}
const uint8_t* inPtr = reinterpret_cast<const uint8_t*>(inBytes.get());
if (!HMAC_Update(hmacCtx, inPtr + inOffset, inLength)) {
JNI_TRACE("HMAC_Update(%p, %p, %d, %d) => threw exception", hmacCtx, inArray, inOffset,
inLength);
throwExceptionIfNecessary(env, "HMAC_Update");
return;
}
}
static jbyteArray NativeCrypto_HMAC_Final(JNIEnv* env, jclass, jobject hmacCtxRef) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
JNI_TRACE("HMAC_Final(%p)", hmacCtx);
if (hmacCtx == NULL) {
return NULL;
}
uint8_t result[EVP_MAX_MD_SIZE];
unsigned len;
if (!HMAC_Final(hmacCtx, result, &len)) {
JNI_TRACE("HMAC_Final(%p) => threw exception", hmacCtx);
throwExceptionIfNecessary(env, "HMAC_Final");
return NULL;
}
ScopedLocalRef<jbyteArray> resultArray(env, env->NewByteArray(len));
if (resultArray.get() == NULL) {
return NULL;
}
ScopedByteArrayRW resultBytes(env, resultArray.get());
if (resultBytes.get() == NULL) {
return NULL;
}
memcpy(resultBytes.get(), result, len);
return resultArray.release();
}
/**
* public static native void RAND_seed(byte[]);
*/
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_RAND_seed(JNIEnv* env, jclass, jbyteArray seed) {
JNI_TRACE("NativeCrypto_RAND_seed seed=%p", seed);
ScopedByteArrayRO randseed(env, seed);
if (randseed.get() == NULL) {
return;
}
RAND_seed(randseed.get(), randseed.size());
}
#else
static void NativeCrypto_RAND_seed(JNIEnv*, jclass, jbyteArray) {
}
#endif
static jint NativeCrypto_RAND_load_file(JNIEnv* env, jclass, jstring filename, jlong max_bytes) {
JNI_TRACE("NativeCrypto_RAND_load_file filename=%p max_bytes=%lld", filename, (long long) max_bytes);
#if !defined(OPENSSL_IS_BORINGSSL)
ScopedUtfChars file(env, filename);
if (file.c_str() == NULL) {
return -1;
}
int result = RAND_load_file(file.c_str(), max_bytes);
JNI_TRACE("NativeCrypto_RAND_load_file file=%s => %d", file.c_str(), result);
return result;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(filename);
// OpenSSLRandom calls this and checks the return value.
return static_cast<jint>(max_bytes);
#endif
}
static void NativeCrypto_RAND_bytes(JNIEnv* env, jclass, jbyteArray output) {
JNI_TRACE("NativeCrypto_RAND_bytes(%p)", output);
ScopedByteArrayRW outputBytes(env, output);
if (outputBytes.get() == NULL) {
return;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(outputBytes.get());
if (RAND_bytes(tmp, outputBytes.size()) <= 0) {
throwExceptionIfNecessary(env, "NativeCrypto_RAND_bytes");
JNI_TRACE("tmp=%p NativeCrypto_RAND_bytes => threw error", tmp);
return;
}
JNI_TRACE("NativeCrypto_RAND_bytes(%p) => success", output);
}
static jint NativeCrypto_OBJ_txt2nid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return 0;
}
int nid = OBJ_txt2nid(oid.c_str());
JNI_TRACE("OBJ_txt2nid(%s) => %d", oid.c_str(), nid);
return nid;
}
static jstring NativeCrypto_OBJ_txt2nid_longName(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_longName(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_longName(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_longName(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const char* longName = OBJ_nid2ln(nid);
JNI_TRACE("OBJ_txt2nid_longName(%s) => %s", oid.c_str(), longName);
return env->NewStringUTF(longName);
}
static jstring ASN1_OBJECT_to_OID_string(JNIEnv* env, const ASN1_OBJECT* obj) {
/*
* The OBJ_obj2txt API doesn't "measure" if you pass in NULL as the buffer.
* Just make a buffer that's large enough here. The documentation recommends
* 80 characters.
*/
char output[128];
int ret = OBJ_obj2txt(output, sizeof(output), obj, 1);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1_OBJECT_to_OID_string");
return NULL;
} else if (size_t(ret) >= sizeof(output)) {
jniThrowRuntimeException(env, "ASN1_OBJECT_to_OID_string buffer too small");
return NULL;
}
JNI_TRACE("ASN1_OBJECT_to_OID_string(%p) => %s", obj, output);
return env->NewStringUTF(output);
}
static jlong NativeCrypto_create_BIO_InputStream(JNIEnv* env, jclass,
jobject streamObj,
jboolean isFinite) {
JNI_TRACE("create_BIO_InputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_InputStream(streamObj, isFinite));
JNI_TRACE("create_BIO_InputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static jlong NativeCrypto_create_BIO_OutputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_OutputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_OutputStream(streamObj));
JNI_TRACE("create_BIO_OutputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static int NativeCrypto_BIO_read(JNIEnv* env, jclass, jlong bioRef, jbyteArray outputJavaBytes) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_read(%p, %p)", bio, outputJavaBytes);
if (outputJavaBytes == NULL) {
jniThrowNullPointerException(env, "output == null");
JNI_TRACE("BIO_read(%p, %p) => output == null", bio, outputJavaBytes);
return 0;
}
int outputSize = env->GetArrayLength(outputJavaBytes);
UniquePtr<unsigned char[]> buffer(new unsigned char[outputSize]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for read");
return 0;
}
int read = BIO_read(bio, buffer.get(), outputSize);
if (read <= 0) {
jniThrowException(env, "java/io/IOException", "BIO_read");
JNI_TRACE("BIO_read(%p, %p) => threw IO exception", bio, outputJavaBytes);
return 0;
}
env->SetByteArrayRegion(outputJavaBytes, 0, read, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("BIO_read(%p, %p) => %d", bio, outputJavaBytes, read);
return read;
}
static void NativeCrypto_BIO_write(JNIEnv* env, jclass, jlong bioRef, jbyteArray inputJavaBytes,
jint offset, jint length) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_write(%p, %p, %d, %d)", bio, inputJavaBytes, offset, length);
if (inputJavaBytes == NULL) {
jniThrowNullPointerException(env, "input == null");
return;
}
int inputSize = env->GetArrayLength(inputJavaBytes);
if (offset < 0 || offset > inputSize || length < 0 || length > inputSize - offset) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inputJavaBytes");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[length]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for write");
return;
}
env->GetByteArrayRegion(inputJavaBytes, offset, length, reinterpret_cast<jbyte*>(buffer.get()));
if (BIO_write(bio, buffer.get(), length) != length) {
freeOpenSslErrorState();
jniThrowException(env, "java/io/IOException", "BIO_write");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IO error", bio, inputJavaBytes, offset, length);
return;
}
JNI_TRACE("BIO_write(%p, %p, %d, %d) => success", bio, inputJavaBytes, offset, length);
}
static void NativeCrypto_BIO_free_all(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_free_all(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return;
}
BIO_free_all(bio);
}
static jstring X509_NAME_to_jstring(JNIEnv* env, X509_NAME* name, unsigned long flags) {
JNI_TRACE("X509_NAME_to_jstring(%p)", name);
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
JNI_TRACE("X509_NAME_to_jstring(%p) => threw error", name);
return NULL;
}
/* Don't interpret the string. */
flags &= ~(ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_ESC_MSB);
/* Write in given format and null terminate. */
X509_NAME_print_ex(buffer.get(), name, 0, flags);
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
JNI_TRACE("X509_NAME_to_jstring(%p) => \"%s\"", name, tmp);
return env->NewStringUTF(tmp);
}
/**
* Converts GENERAL_NAME items to the output format expected in
* X509Certificate#getSubjectAlternativeNames and
* X509Certificate#getIssuerAlternativeNames return.
*/
static jobject GENERAL_NAME_to_jobject(JNIEnv* env, GENERAL_NAME* gen) {
switch (gen->type) {
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI: {
// This must not be a T61String and must not contain NULLs.
const char* data = reinterpret_cast<const char*>(ASN1_STRING_data(gen->d.ia5));
ssize_t len = ASN1_STRING_length(gen->d.ia5);
if ((len == static_cast<ssize_t>(strlen(data)))
&& (ASN1_PRINTABLE_type(ASN1_STRING_data(gen->d.ia5), len) != V_ASN1_T61STRING)) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI \"%s\"", gen, data);
return env->NewStringUTF(data);
} else {
jniThrowException(env, "java/security/cert/CertificateParsingException",
"Invalid dNSName encoding");
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI invalid", gen);
return NULL;
}
}
case GEN_DIRNAME:
/* Write in RFC 2253 format */
return X509_NAME_to_jstring(env, gen->d.directoryName, XN_FLAG_RFC2253);
case GEN_IPADD: {
const void *ip = reinterpret_cast<const void *>(gen->d.ip->data);
if (gen->d.ip->length == 4) {
// IPv4
UniquePtr<char[]> buffer(new char[INET_ADDRSTRLEN]);
if (inet_ntop(AF_INET, ip, buffer.get(), INET_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 failed %s", gen, strerror(errno));
}
} else if (gen->d.ip->length == 16) {
// IPv6
UniquePtr<char[]> buffer(new char[INET6_ADDRSTRLEN]);
if (inet_ntop(AF_INET6, ip, buffer.get(), INET6_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 failed %s", gen, strerror(errno));
}
}
/* Invalid IP encodings are pruned out without throwing an exception. */
return NULL;
}
case GEN_RID:
return ASN1_OBJECT_to_OID_string(env, gen->d.registeredID);
case GEN_OTHERNAME:
case GEN_X400:
default:
return ASN1ToByteArray<GENERAL_NAME>(env, gen, i2d_GENERAL_NAME);
}
return NULL;
}
#define GN_STACK_SUBJECT_ALT_NAME 1
#define GN_STACK_ISSUER_ALT_NAME 2
static jobjectArray NativeCrypto_get_X509_GENERAL_NAME_stack(JNIEnv* env, jclass, jlong x509Ref,
jint type) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d)", x509, type);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => x509 == null", x509, type);
return NULL;
}
X509_check_ca(x509);
STACK_OF(GENERAL_NAME)* gn_stack;
Unique_sk_GENERAL_NAME stackHolder;
if (type == GN_STACK_SUBJECT_ALT_NAME) {
gn_stack = x509->altname;
} else if (type == GN_STACK_ISSUER_ALT_NAME) {
stackHolder.reset(
static_cast<STACK_OF(GENERAL_NAME)*>(X509_get_ext_d2i(x509, NID_issuer_alt_name,
NULL, NULL)));
gn_stack = stackHolder.get();
} else {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => unknown type", x509, type);
return NULL;
}
int count = sk_GENERAL_NAME_num(gn_stack);
if (count <= 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no entries)", x509, type);
return NULL;
}
/*
* Keep track of how many originally so we can ignore any invalid
* values later.
*/
const int origCount = count;
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, objectArrayClass, NULL));
for (int i = 0, j = 0; i < origCount; i++, j++) {
GENERAL_NAME* gen = sk_GENERAL_NAME_value(gn_stack, i);
ScopedLocalRef<jobject> val(env, GENERAL_NAME_to_jobject(env, gen));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => threw exception parsing gen name",
x509, type);
return NULL;
}
/*
* If it's NULL, we'll have to skip this, reduce the number of total
* entries, and fix up the array later.
*/
if (val.get() == NULL) {
j--;
count--;
continue;
}
ScopedLocalRef<jobjectArray> item(env, env->NewObjectArray(2, objectClass, NULL));
ScopedLocalRef<jobject> type(env, env->CallStaticObjectMethod(integerClass,
integer_valueOfMethod, gen->type));
env->SetObjectArrayElement(item.get(), 0, type.get());
env->SetObjectArrayElement(item.get(), 1, val.get());
env->SetObjectArrayElement(joa.get(), j, item.get());
}
if (count == 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to 0; returning NULL",
x509, type, origCount);
joa.reset(NULL);
} else if (origCount != count) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to %d", x509, type,
origCount, count);
ScopedLocalRef<jobjectArray> joa_copy(env, env->NewObjectArray(count, objectArrayClass,
NULL));
for (int i = 0; i < count; i++) {
ScopedLocalRef<jobject> item(env, env->GetObjectArrayElement(joa.get(), i));
env->SetObjectArrayElement(joa_copy.get(), i, item.get());
}
joa.reset(joa_copy.release());
}
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => %d entries", x509, type, count);
return joa.release();
}
static jlong NativeCrypto_X509_get_notBefore(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notBefore(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notBefore(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notBefore = X509_get_notBefore(x509);
JNI_TRACE("X509_get_notBefore(%p) => %p", x509, notBefore);
return reinterpret_cast<uintptr_t>(notBefore);
}
static jlong NativeCrypto_X509_get_notAfter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notAfter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notAfter(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notAfter = X509_get_notAfter(x509);
JNI_TRACE("X509_get_notAfter(%p) => %p", x509, notAfter);
return reinterpret_cast<uintptr_t>(notAfter);
}
static long NativeCrypto_X509_get_version(JNIEnv*, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_version(%p)", x509);
long version = X509_get_version(x509);
JNI_TRACE("X509_get_version(%p) => %ld", x509, version);
return version;
}
template<typename T>
static jbyteArray get_X509Type_serialNumber(JNIEnv* env, T* x509Type, ASN1_INTEGER* (*get_serial_func)(T*)) {
JNI_TRACE("get_X509Type_serialNumber(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_serialNumber(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_INTEGER* serialNumber = get_serial_func(x509Type);
Unique_BIGNUM serialBn(ASN1_INTEGER_to_BN(serialNumber, NULL));
if (serialBn.get() == NULL) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
ScopedLocalRef<jbyteArray> serialArray(env, bignumToArray(env, serialBn.get(), "serialBn"));
if (env->ExceptionCheck()) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
JNI_TRACE("X509_get_serialNumber(%p) => %p", x509Type, serialArray.get());
return serialArray.release();
}
/* OpenSSL includes set_serialNumber but not get. */
#if !defined(X509_REVOKED_get_serialNumber)
static ASN1_INTEGER* X509_REVOKED_get_serialNumber(X509_REVOKED* x) {
return x->serialNumber;
}
#endif
static jbyteArray NativeCrypto_X509_get_serialNumber(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_serialNumber(%p)", x509);
return get_X509Type_serialNumber<X509>(env, x509, X509_get_serialNumber);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_serialNumber(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_serialNumber(%p)", revoked);
return get_X509Type_serialNumber<X509_REVOKED>(env, revoked, X509_REVOKED_get_serialNumber);
}
static void NativeCrypto_X509_verify(JNIEnv* env, jclass, jlong x509Ref, jobject pkeyRef) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_verify(%p, %p)", x509, pkey);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_verify(%p, %p) => x509 == null", x509, pkey);
return;
}
if (pkey == NULL) {
JNI_TRACE("X509_verify(%p, %p) => pkey == null", x509, pkey);
return;
}
if (X509_verify(x509, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_verify");
JNI_TRACE("X509_verify(%p, %p) => verify failure", x509, pkey);
} else {
JNI_TRACE("X509_verify(%p, %p) => verify success", x509, pkey);
}
}
static jbyteArray NativeCrypto_get_X509_cert_info_enc(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_cert_info_enc(%p)", x509);
return ASN1ToByteArray<X509_CINF>(env, x509->cert_info, i2d_X509_CINF);
}
static jint NativeCrypto_get_X509_ex_flags(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_flags(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_flags(%p) => x509 == null", x509);
return 0;
}
X509_check_ca(x509);
return x509->ex_flags;
}
static jboolean NativeCrypto_X509_check_issued(JNIEnv*, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_check_issued(%p, %p)", x509_1, x509_2);
int ret = X509_check_issued(x509_1, x509_2);
JNI_TRACE("X509_check_issued(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void get_X509_signature(X509 *x509, ASN1_BIT_STRING** signature) {
*signature = x509->signature;
}
static void get_X509_CRL_signature(X509_CRL *crl, ASN1_BIT_STRING** signature) {
*signature = crl->signature;
}
template<typename T>
static jbyteArray get_X509Type_signature(JNIEnv* env, T* x509Type, void (*get_signature_func)(T*, ASN1_BIT_STRING**)) {
JNI_TRACE("get_X509Type_signature(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_signature(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_BIT_STRING* signature;
get_signature_func(x509Type, &signature);
ScopedLocalRef<jbyteArray> signatureArray(env, env->NewByteArray(signature->length));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509Type_signature(%p) => threw exception", x509Type);
return NULL;
}
ScopedByteArrayRW signatureBytes(env, signatureArray.get());
if (signatureBytes.get() == NULL) {
JNI_TRACE("get_X509Type_signature(%p) => using byte array failed", x509Type);
return NULL;
}
memcpy(signatureBytes.get(), signature->data, signature->length);
JNI_TRACE("get_X509Type_signature(%p) => %p (%d bytes)", x509Type, signatureArray.get(),
signature->length);
return signatureArray.release();
}
static jbyteArray NativeCrypto_get_X509_signature(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_signature(%p)", x509);
return get_X509Type_signature<X509>(env, x509, get_X509_signature);
}
static jbyteArray NativeCrypto_get_X509_CRL_signature(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_signature(%p)", crl);
return get_X509Type_signature<X509_CRL>(env, crl, get_X509_CRL_signature);
}
static jlong NativeCrypto_X509_CRL_get0_by_cert(JNIEnv* env, jclass, jlong x509crlRef, jlong x509Ref) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p)", x509crl, x509);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509crl == null", x509crl, x509);
return 0;
} else if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509 == null", x509crl, x509);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_cert(x509crl, &revoked, x509);
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => none", x509crl, x509);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, x509, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
static jlong NativeCrypto_X509_CRL_get0_by_serial(JNIEnv* env, jclass, jlong x509crlRef, jbyteArray serialArray) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p)", x509crl, serialArray);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => crl == null", x509crl, serialArray);
return 0;
}
Unique_BIGNUM serialBn(BN_new());
if (serialBn.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN allocation failed", x509crl, serialArray);
return 0;
}
BIGNUM* serialBare = serialBn.get();
if (!arrayToBignum(env, serialArray, &serialBare)) {
if (!env->ExceptionCheck()) {
jniThrowNullPointerException(env, "serial == null");
}
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
Unique_ASN1_INTEGER serialInteger(BN_to_ASN1_INTEGER(serialBn.get(), NULL));
if (serialInteger.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_serial(x509crl, &revoked, serialInteger.get());
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => none", x509crl, serialArray);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, serialArray, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
/* This appears to be missing from OpenSSL. */
#if !defined(X509_REVOKED_dup) && !defined(OPENSSL_IS_BORINGSSL)
X509_REVOKED* X509_REVOKED_dup(X509_REVOKED* x) {
return reinterpret_cast<X509_REVOKED*>(ASN1_item_dup(ASN1_ITEM_rptr(X509_REVOKED), x));
}
#endif
static jlongArray NativeCrypto_X509_CRL_get_REVOKED(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_REVOKED(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
return NULL;
}
STACK_OF(X509_REVOKED)* stack = X509_CRL_get_REVOKED(crl);
if (stack == NULL) {
JNI_TRACE("X509_CRL_get_REVOKED(%p) => stack is null", crl);
return NULL;
}
size_t size = sk_X509_REVOKED_num(stack);
ScopedLocalRef<jlongArray> revokedArray(env, env->NewLongArray(size));
ScopedLongArrayRW revoked(env, revokedArray.get());
for (size_t i = 0; i < size; i++) {
X509_REVOKED* item = reinterpret_cast<X509_REVOKED*>(sk_X509_REVOKED_value(stack, i));
revoked[i] = reinterpret_cast<uintptr_t>(X509_REVOKED_dup(item));
}
JNI_TRACE("X509_CRL_get_REVOKED(%p) => %p [size=%zd]", stack, revokedArray.get(), size);
return revokedArray.release();
}
static jbyteArray NativeCrypto_i2d_X509_CRL(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("i2d_X509_CRL(%p)", crl);
return ASN1ToByteArray<X509_CRL>(env, crl, i2d_X509_CRL);
}
static void NativeCrypto_X509_CRL_free(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_free(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_free(%p) => crl == null", crl);
return;
}
X509_CRL_free(crl);
}
static void NativeCrypto_X509_CRL_print(JNIEnv* env, jclass, jlong bioRef, jlong x509CrlRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_print(%p, %p)", bio, crl);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_CRL_print(%p, %p) => bio == null", bio, crl);
return;
}
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_print(%p, %p) => crl == null", bio, crl);
return;
}
if (!X509_CRL_print(bio, crl)) {
throwExceptionIfNecessary(env, "X509_CRL_print");
JNI_TRACE("X509_CRL_print(%p, %p) => threw error", bio, crl);
} else {
JNI_TRACE("X509_CRL_print(%p, %p) => success", bio, crl);
}
}
static jstring NativeCrypto_get_X509_CRL_sig_alg_oid(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p)", crl);
if (crl == NULL || crl->sig_alg == NULL) {
jniThrowNullPointerException(env, "crl == NULL || crl->sig_alg == NULL");
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p) => crl == NULL", crl);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, crl->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_CRL_sig_alg_parameter(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => crl == null", crl);
return NULL;
}
if (crl->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => null", crl);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, crl->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbyteArray NativeCrypto_X509_CRL_get_issuer_name(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_issuer_name(%p)", crl);
return ASN1ToByteArray<X509_NAME>(env, X509_CRL_get_issuer(crl), i2d_X509_NAME);
}
static long NativeCrypto_X509_CRL_get_version(JNIEnv*, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_version(%p)", crl);
long version = X509_CRL_get_version(crl);
JNI_TRACE("X509_CRL_get_version(%p) => %ld", crl, version);
return version;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static X509_EXTENSION *X509Type_get_ext(JNIEnv* env, T* x509Type, jstring oidString) {
JNI_TRACE("X509Type_get_ext(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509 == null");
return NULL;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
return NULL;
}
Unique_ASN1_OBJECT asn1(OBJ_txt2obj(oid.c_str(), 1));
if (asn1.get() == NULL) {
JNI_TRACE("X509Type_get_ext(%p, %s) => oid conversion failed", x509Type, oid.c_str());
freeOpenSslErrorState();
return NULL;
}
int extIndex = get_ext_by_OBJ_func(x509Type, (ASN1_OBJECT*) asn1.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509Type_get_ext(%p, %s) => ext not found", x509Type, oid.c_str());
return NULL;
}
X509_EXTENSION* ext = get_ext_func(x509Type, extIndex);
JNI_TRACE("X509Type_get_ext(%p, %s) => %p", x509Type, oid.c_str(), ext);
return ext;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static jbyteArray X509Type_get_ext_oid(JNIEnv* env, T* x509Type, jstring oidString) {
X509_EXTENSION* ext = X509Type_get_ext<T, get_ext_by_OBJ_func, get_ext_func>(env, x509Type,
oidString);
if (ext == NULL) {
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => fetching extension failed", x509Type, oidString);
return NULL;
}
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => %p", x509Type, oidString, ext->value);
return ASN1ToByteArray<ASN1_OCTET_STRING>(env, ext->value, i2d_ASN1_OCTET_STRING);
}
static jlong NativeCrypto_X509_CRL_get_ext(JNIEnv* env, jclass, jlong x509CrlRef, jstring oid) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext(%p, %p)", crl, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(
env, crl, oid);
JNI_TRACE("X509_CRL_get_ext(%p, %p) => %p", crl, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_get_ext(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oid) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext(%p, %p)", revoked, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ,
X509_REVOKED_get_ext>(env, revoked, oid);
JNI_TRACE("X509_REVOKED_get_ext(%p, %p) => %p", revoked, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_dup(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_dup(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_dup(%p) => revoked == null", revoked);
return 0;
}
X509_REVOKED* dup = X509_REVOKED_dup(revoked);
JNI_TRACE("X509_REVOKED_dup(%p) => %p", revoked, dup);
return reinterpret_cast<uintptr_t>(dup);
}
static jlong NativeCrypto_get_X509_REVOKED_revocationDate(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("get_X509_REVOKED_revocationDate(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => revoked == null", revoked);
return 0;
}
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => %p", revoked, revoked->revocationDate);
return reinterpret_cast<uintptr_t>(revoked->revocationDate);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
static void NativeCrypto_X509_REVOKED_print(JNIEnv* env, jclass, jlong bioRef, jlong x509RevokedRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_print(%p, %p)", bio, revoked);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => bio == null", bio, revoked);
return;
}
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => revoked == null", bio, revoked);
return;
}
BIO_printf(bio, "Serial Number: ");
i2a_ASN1_INTEGER(bio, revoked->serialNumber);
BIO_printf(bio, "\nRevocation Date: ");
ASN1_TIME_print(bio, revoked->revocationDate);
BIO_printf(bio, "\n");
X509V3_extensions_print(bio, "CRL entry extensions", revoked->extensions, 0, 0);
}
#pragma GCC diagnostic pop
static jbyteArray NativeCrypto_get_X509_CRL_crl_enc(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_crl_enc(%p)", crl);
return ASN1ToByteArray<X509_CRL_INFO>(env, crl->crl, i2d_X509_CRL_INFO);
}
static void NativeCrypto_X509_CRL_verify(JNIEnv* env, jclass, jlong x509CrlRef, jobject pkeyRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_CRL_verify(%p, %p)", crl, pkey);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => crl == null", crl, pkey);
return;
}
if (pkey == NULL) {
JNI_TRACE("X509_CRL_verify(%p, %p) => pkey == null", crl, pkey);
return;
}
if (X509_CRL_verify(crl, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_CRL_verify");
JNI_TRACE("X509_CRL_verify(%p, %p) => verify failure", crl, pkey);
} else {
JNI_TRACE("X509_CRL_verify(%p, %p) => verify success", crl, pkey);
}
}
static jlong NativeCrypto_X509_CRL_get_lastUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_lastUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* lastUpdate = X509_CRL_get_lastUpdate(crl);
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => %p", crl, lastUpdate);
return reinterpret_cast<uintptr_t>(lastUpdate);
}
static jlong NativeCrypto_X509_CRL_get_nextUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_nextUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* nextUpdate = X509_CRL_get_nextUpdate(crl);
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => %p", crl, nextUpdate);
return reinterpret_cast<uintptr_t>(nextUpdate);
}
static jbyteArray NativeCrypto_i2d_X509_REVOKED(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* x509Revoked =
reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("i2d_X509_REVOKED(%p)", x509Revoked);
return ASN1ToByteArray<X509_REVOKED>(env, x509Revoked, i2d_X509_REVOKED);
}
static jint NativeCrypto_X509_supported_extension(JNIEnv* env, jclass, jlong x509ExtensionRef) {
X509_EXTENSION* ext = reinterpret_cast<X509_EXTENSION*>(static_cast<uintptr_t>(x509ExtensionRef));
if (ext == NULL) {
jniThrowNullPointerException(env, "ext == NULL");
return 0;
}
return X509_supported_extension(ext);
}
static inline void get_ASN1_TIME_data(char **data, int* output, size_t len) {
char c = **data;
**data = '\0';
*data -= len;
*output = atoi(*data);
*(*data + len) = c;
}
static void NativeCrypto_ASN1_TIME_to_Calendar(JNIEnv* env, jclass, jlong asn1TimeRef, jobject calendar) {
ASN1_TIME* asn1Time = reinterpret_cast<ASN1_TIME*>(static_cast<uintptr_t>(asn1TimeRef));
JNI_TRACE("ASN1_TIME_to_Calendar(%p, %p)", asn1Time, calendar);
if (asn1Time == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
Unique_ASN1_GENERALIZEDTIME gen(ASN1_TIME_to_generalizedtime(asn1Time, NULL));
if (gen.get() == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
if (gen->length < 14 || gen->data == NULL) {
jniThrowNullPointerException(env, "gen->length < 14 || gen->data == NULL");
return;
}
int sec, min, hour, mday, mon, year;
char *p = (char*) &gen->data[14];
get_ASN1_TIME_data(&p, &sec, 2);
get_ASN1_TIME_data(&p, &min, 2);
get_ASN1_TIME_data(&p, &hour, 2);
get_ASN1_TIME_data(&p, &mday, 2);
get_ASN1_TIME_data(&p, &mon, 2);
get_ASN1_TIME_data(&p, &year, 4);
env->CallVoidMethod(calendar, calendar_setMethod, year, mon - 1, mday, hour, min, sec);
}
static jstring NativeCrypto_OBJ_txt2nid_oid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_oid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_oid(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_oid(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const ASN1_OBJECT* obj = OBJ_nid2obj(nid);
if (obj == NULL) {
throwExceptionIfNecessary(env, "OBJ_nid2obj");
return NULL;
}
ScopedLocalRef<jstring> ouputStr(env, ASN1_OBJECT_to_OID_string(env, obj));
JNI_TRACE("OBJ_txt2nid_oid(%s) => %p", oid.c_str(), ouputStr.get());
return ouputStr.release();
}
static jstring NativeCrypto_X509_NAME_print_ex(JNIEnv* env, jclass, jlong x509NameRef, jlong jflags) {
X509_NAME* x509name = reinterpret_cast<X509_NAME*>(static_cast<uintptr_t>(x509NameRef));
unsigned long flags = static_cast<unsigned long>(jflags);
JNI_TRACE("X509_NAME_print_ex(%p, %ld)", x509name, flags);
if (x509name == NULL) {
jniThrowNullPointerException(env, "x509name == null");
JNI_TRACE("X509_NAME_print_ex(%p, %ld) => x509name == null", x509name, flags);
return NULL;
}
return X509_NAME_to_jstring(env, x509name, flags);
}
template <typename T, T* (*d2i_func)(BIO*, T**)>
static jlong d2i_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return 0;
}
T* x = d2i_func(bio, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "d2i_ASN1Object_to_jlong");
return 0;
}
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_d2i_X509_CRL_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509_CRL, d2i_X509_CRL_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509, d2i_X509_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509(JNIEnv* env, jclass, jbyteArray certBytes) {
X509* x = ByteArrayToASN1<X509, d2i_X509>(env, certBytes);
return reinterpret_cast<uintptr_t>(x);
}
static jbyteArray NativeCrypto_i2d_X509(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509(%p)", x509);
return ASN1ToByteArray<X509>(env, x509, i2d_X509);
}
static jbyteArray NativeCrypto_i2d_X509_PUBKEY(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509_PUBKEY(%p)", x509);
return ASN1ToByteArray<X509_PUBKEY>(env, X509_get_X509_PUBKEY(x509), i2d_X509_PUBKEY);
}
template<typename T, T* (*PEM_read_func)(BIO*, T**, pem_password_cb*, void*)>
static jlong PEM_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_to_jlong(%p) => bio == null", bio);
return 0;
}
T* x = PEM_read_func(bio, NULL, NULL, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "PEM_to_jlong");
// Sometimes the PEM functions fail without pushing an error
if (!env->ExceptionCheck()) {
jniThrowRuntimeException(env, "Failure parsing PEM");
}
JNI_TRACE("PEM_to_jlong(%p) => threw exception", bio);
return 0;
}
JNI_TRACE("PEM_to_jlong(%p) => %p", bio, x);
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_PEM_read_bio_X509(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509(0x%llx)", (long long) bioRef);
return PEM_to_jlong<X509, PEM_read_bio_X509>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_X509_CRL(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509_CRL(0x%llx)", (long long) bioRef);
return PEM_to_jlong<X509_CRL, PEM_read_bio_X509_CRL>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_PUBKEY(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_PUBKEY(0x%llx)", (long long) bioRef);
return PEM_to_jlong<EVP_PKEY, PEM_read_bio_PUBKEY>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_PrivateKey(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_PrivateKey(0x%llx)", (long long) bioRef);
return PEM_to_jlong<EVP_PKEY, PEM_read_bio_PrivateKey>(env, bioRef);
}
template <typename T, typename T_stack>
static jlongArray PKCS7_to_ItemArray(JNIEnv* env, T_stack* stack, T* (*dup_func)(T*))
{
if (stack == NULL) {
return NULL;
}
ScopedLocalRef<jlongArray> ref_array(env, NULL);
size_t size = sk_num(reinterpret_cast<_STACK*>(stack));
ref_array.reset(env->NewLongArray(size));
ScopedLongArrayRW items(env, ref_array.get());
for (size_t i = 0; i < size; i++) {
T* item = reinterpret_cast<T*>(sk_value(reinterpret_cast<_STACK*>(stack), i));
items[i] = reinterpret_cast<uintptr_t>(dup_func(item));
}
JNI_TRACE("PKCS7_to_ItemArray(%p) => %p [size=%zd]", stack, ref_array.get(), size);
return ref_array.release();
}
#define PKCS7_CERTS 1
#define PKCS7_CRLS 2
static jbyteArray NativeCrypto_i2d_PKCS7(JNIEnv* env, jclass, jlongArray certsArray) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("i2d_PKCS7(%p)", certsArray);
Unique_PKCS7 pkcs7(PKCS7_new());
if (pkcs7.get() == NULL) {
jniThrowNullPointerException(env, "pkcs7 == null");
JNI_TRACE("i2d_PKCS7(%p) => pkcs7 == null", certsArray);
return NULL;
}
if (PKCS7_set_type(pkcs7.get(), NID_pkcs7_signed) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type");
return NULL;
}
// The EncapsulatedContentInfo must be present in the output, but OpenSSL
// will fill in a zero-length OID if you don't call PKCS7_set_content on the
// outer PKCS7 container. So we construct an empty PKCS7 data container and
// set it as the content.
Unique_PKCS7 pkcs7Data(PKCS7_new());
if (PKCS7_set_type(pkcs7Data.get(), NID_pkcs7_data) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type data");
return NULL;
}
if (PKCS7_set_content(pkcs7.get(), pkcs7Data.get()) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_content");
return NULL;
}
OWNERSHIP_TRANSFERRED(pkcs7Data);
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (PKCS7_add_certificate(pkcs7.get(), item) != 1) {
throwExceptionIfNecessary(env, "i2d_PKCS7");
return NULL;
}
}
JNI_TRACE("i2d_PKCS7(%p) => %zd certs", certsArray, certs.size());
return ASN1ToByteArray<PKCS7>(env, pkcs7.get(), i2d_PKCS7);
#else // OPENSSL_IS_BORINGSSL
STACK_OF(X509) *stack = sk_X509_new_null();
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (sk_X509_push(stack, item) == 0) {
sk_X509_free(stack);
throwExceptionIfNecessary(env, "sk_X509_push");
return NULL;
}
}
CBB out;
CBB_init(&out, 1024 * certs.size());
if (!PKCS7_bundle_certificates(&out, stack)) {
CBB_cleanup(&out);
sk_X509_free(stack);
throwExceptionIfNecessary(env, "PKCS7_bundle_certificates");
return NULL;
}
sk_X509_free(stack);
uint8_t *derBytes;
size_t derLen;
if (!CBB_finish(&out, &derBytes, &derLen)) {
CBB_cleanup(&out);
throwExceptionIfNecessary(env, "CBB_finish");
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("creating byte array failed");
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("using byte array failed");
return NULL;
}
uint8_t* p = reinterpret_cast<unsigned char*>(bytes.get());
memcpy(p, derBytes, derLen);
return byteArray.release();
#endif // OPENSSL_IS_BORINGSSL
}
#if !defined(OPENSSL_IS_BORINGSSL)
static STACK_OF(X509)* PKCS7_get_certs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->cert;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->cert;
} else {
JNI_TRACE("PKCS7_get_certs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
static STACK_OF(X509_CRL)* PKCS7_get_CRLs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->crl;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->crl;
} else {
JNI_TRACE("PKCS7_get_CRLs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
#endif
static jlongArray NativeCrypto_PEM_read_bio_PKCS7(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => bio == null", bio);
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_PKCS7 pkcs7(PEM_read_bio_PKCS7(bio, NULL, NULL, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "PEM_read_bio_PKCS7_CRLs");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => threw exception", bio);
return 0;
}
switch (which) {
case PKCS7_CERTS:
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
#else
if (which == PKCS7_CERTS) {
Unique_sk_X509 outCerts(sk_X509_new_null());
if (!PKCS7_get_PEM_certificates(outCerts.get(), bio)) {
throwExceptionIfNecessary(env, "PKCS7_get_PEM_certificates");
return 0;
}
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, outCerts.get(), X509_dup);
} else if (which == PKCS7_CRLS) {
Unique_sk_X509_CRL outCRLs(sk_X509_CRL_new_null());
if (!PKCS7_get_PEM_CRLs(outCRLs.get(), bio)) {
throwExceptionIfNecessary(env, "PKCS7_get_PEM_CRLs");
return 0;
}
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(
env, outCRLs.get(), X509_CRL_dup);
} else {
jniThrowRuntimeException(env, "unknown PKCS7 field");
return 0;
}
#endif
}
static jlongArray NativeCrypto_d2i_PKCS7_bio(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_PKCS7_bio(%p, %d)", bio, which);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => bio == null", bio, which);
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_PKCS7 pkcs7(d2i_PKCS7_bio(bio, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS7_bio");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => threw exception", bio, which);
return 0;
}
switch (which) {
case PKCS7_CERTS:
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => returned", bio, which);
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => returned", bio, which);
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
#else
uint8_t *data;
size_t len;
if (!BIO_read_asn1(bio, &data, &len, 256 * 1024 * 1024 /* max length, 256MB for sanity */)) {
if (!throwExceptionIfNecessary(env, "Error reading PKCS#7 data")) {
throwParsingException(env, "Error reading PKCS#7 data");
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading BIO", bio, which);
return 0;
}
Unique_OPENSSL_str data_storage(data);
CBS cbs;
CBS_init(&cbs, data, len);
if (which == PKCS7_CERTS) {
Unique_sk_X509 outCerts(sk_X509_new_null());
if (!PKCS7_get_certificates(outCerts.get(), &cbs)) {
if (!throwExceptionIfNecessary(env, "PKCS7_get_certificates")) {
throwParsingException(env, "Error parsing PKCS#7 certificate data");
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading certs", bio, which);
return 0;
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => success certs", bio, which);
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, outCerts.get(), X509_dup);
} else if (which == PKCS7_CRLS) {
Unique_sk_X509_CRL outCRLs(sk_X509_CRL_new_null());
if (!PKCS7_get_CRLs(outCRLs.get(), &cbs)) {
if (!throwExceptionIfNecessary(env, "PKCS7_get_CRLs")) {
throwParsingException(env, "Error parsing PKCS#7 CRL data");
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading CRLs", bio, which);
return 0;
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => success CRLs", bio, which);
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(
env, outCRLs.get(), X509_CRL_dup);
} else {
jniThrowRuntimeException(env, "unknown PKCS7 field");
return 0;
}
#endif
}
typedef STACK_OF(X509) PKIPATH;
ASN1_ITEM_TEMPLATE(PKIPATH) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PkiPath, X509)
ASN1_ITEM_TEMPLATE_END(PKIPATH)
static jlongArray NativeCrypto_ASN1_seq_unpack_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p)", bio);
Unique_sk_X509 path((PKIPATH*) ASN1_item_d2i_bio(ASN1_ITEM_rptr(PKIPATH), bio, NULL));
if (path.get() == NULL) {
throwExceptionIfNecessary(env, "ASN1_seq_unpack_X509_bio");
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => threw error", bio);
return NULL;
}
size_t size = sk_X509_num(path.get());
ScopedLocalRef<jlongArray> certArray(env, env->NewLongArray(size));
ScopedLongArrayRW certs(env, certArray.get());
for (size_t i = 0; i < size; i++) {
X509* item = reinterpret_cast<X509*>(sk_X509_shift(path.get()));
certs[i] = reinterpret_cast<uintptr_t>(item);
}
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => returns %zd items", bio, size);
return certArray.release();
}
static jbyteArray NativeCrypto_ASN1_seq_pack_X509(JNIEnv* env, jclass, jlongArray certs) {
JNI_TRACE("ASN1_seq_pack_X509(%p)", certs);
ScopedLongArrayRO certsArray(env, certs);
if (certsArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to get certs array", certs);
return NULL;
}
Unique_sk_X509 certStack(sk_X509_new_null());
if (certStack.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to make cert stack", certs);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
sk_X509_push(certStack.get(), X509_dup_nocopy(x509));
}
int len;
Unique_OPENSSL_str encoded(ASN1_seq_pack(
reinterpret_cast<STACK_OF(OPENSSL_BLOCK)*>(
reinterpret_cast<uintptr_t>(certStack.get())),
reinterpret_cast<int (*)(void*, unsigned char**)>(i2d_X509), NULL, &len));
if (encoded.get() == NULL || len < 0) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => trouble encoding", certs);
return NULL;
}
uint8_t *out = encoded.get();
size_t out_len = len;
#else
CBB result, seq_contents;
if (!CBB_init(&result, 2048 * certsArray.size())) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => CBB_init failed", certs);
return NULL;
}
if (!CBB_add_asn1(&result, &seq_contents, CBS_ASN1_SEQUENCE)) {
CBB_cleanup(&result);
return NULL;
}
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
uint8_t *buf;
int len = i2d_X509(x509, NULL);
if (len < 0 ||
!CBB_add_space(&seq_contents, &buf, len) ||
i2d_X509(x509, &buf) < 0) {
CBB_cleanup(&result);
return NULL;
}
}
uint8_t *out;
size_t out_len;
if (!CBB_finish(&result, &out, &out_len)) {
CBB_cleanup(&result);
return NULL;
}
UniquePtr<uint8_t> out_storage(out);
#endif
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(out_len));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => creating byte array failed", certs);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => using byte array failed", certs);
return NULL;
}
uint8_t *p = reinterpret_cast<uint8_t*>(bytes.get());
memcpy(p, out, out_len);
return byteArray.release();
}
static void NativeCrypto_X509_free(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_free(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_free(%p) => x509 == null", x509);
return;
}
X509_free(x509);
}
static jlong NativeCrypto_X509_dup(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_dup(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_dup(%p) => x509 == null", x509);
return 0;
}
return reinterpret_cast<uintptr_t>(X509_dup(x509));
}
static jint NativeCrypto_X509_cmp(JNIEnv* env, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_cmp(%p, %p)", x509_1, x509_2);
if (x509_1 == NULL) {
jniThrowNullPointerException(env, "x509_1 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_1 == null", x509_1, x509_2);
return -1;
}
if (x509_2 == NULL) {
jniThrowNullPointerException(env, "x509_2 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_2 == null", x509_1, x509_2);
return -1;
}
int ret = X509_cmp(x509_1, x509_2);
JNI_TRACE("X509_cmp(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void NativeCrypto_X509_delete_ext(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_delete_ext(%p, %p)", x509, oidString);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_delete_ext(%p, %p) => x509 == null", x509, oidString);
return;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
JNI_TRACE("X509_delete_ext(%p, %p) => oidString == null", x509, oidString);
return;
}
Unique_ASN1_OBJECT obj(OBJ_txt2obj(oid.c_str(), 1 /* allow numerical form only */));
if (obj.get() == NULL) {
JNI_TRACE("X509_delete_ext(%p, %s) => oid conversion failed", x509, oid.c_str());
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Invalid OID.");
return;
}
int extIndex = X509_get_ext_by_OBJ(x509, obj.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509_delete_ext(%p, %s) => ext not found", x509, oid.c_str());
return;
}
X509_EXTENSION* ext = X509_delete_ext(x509, extIndex);
if (ext != NULL) {
X509_EXTENSION_free(ext);
// Invalidate the cached encoding
#if defined(OPENSSL_IS_BORINGSSL)
X509_CINF_set_modified(X509_get_cert_info(x509));
#else
x509->cert_info->enc.modified = 1;
#endif
}
}
static jint NativeCrypto_get_X509_hashCode(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_hashCode(%p) => x509 == null", x509);
return 0;
}
// Force caching extensions.
X509_check_ca(x509);
jint hashCode = 0L;
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
hashCode = 31 * hashCode + x509->sha1_hash[i];
}
return hashCode;
}
static void NativeCrypto_X509_print_ex(JNIEnv* env, jclass, jlong bioRef, jlong x509Ref,
jlong nmflagJava, jlong certflagJava) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
long nmflag = static_cast<long>(nmflagJava);
long certflag = static_cast<long>(certflagJava);
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld)", bio, x509, nmflag, certflag);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => bio == null", bio, x509, nmflag, certflag);
return;
}
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => x509 == null", bio, x509, nmflag, certflag);
return;
}
if (!X509_print_ex(bio, x509, nmflag, certflag)) {
throwExceptionIfNecessary(env, "X509_print_ex");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => threw error", bio, x509, nmflag, certflag);
} else {
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => success", bio, x509, nmflag, certflag);
}
}
static jlong NativeCrypto_X509_get_pubkey(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_pubkey(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_pubkey(%p) => x509 == null", x509);
return 0;
}
Unique_EVP_PKEY pkey(X509_get_pubkey(x509));
if (pkey.get() == NULL) {
#if defined(OPENSSL_IS_BORINGSSL)
const uint32_t last_error = ERR_peek_last_error();
const uint32_t first_error = ERR_peek_error();
if ((ERR_GET_LIB(last_error) == ERR_LIB_EVP &&
ERR_GET_REASON(last_error) == EVP_R_UNKNOWN_PUBLIC_KEY_TYPE) ||
(ERR_GET_LIB(first_error) == ERR_LIB_EC &&
ERR_GET_REASON(first_error) == EC_R_UNKNOWN_GROUP)) {
freeOpenSslErrorState();
throwNoSuchAlgorithmException(env, "X509_get_pubkey");
return 0;
}
#endif
throwExceptionIfNecessary(env, "X509_get_pubkey");
return 0;
}
JNI_TRACE("X509_get_pubkey(%p) => %p", x509, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jbyteArray NativeCrypto_X509_get_issuer_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_issuer_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_issuer_name(x509), i2d_X509_NAME);
}
static jbyteArray NativeCrypto_X509_get_subject_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_subject_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_subject_name(x509), i2d_X509_NAME);
}
static jstring NativeCrypto_get_X509_pubkey_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_pubkey_oid(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_pubkey_oid(%p) => x509 == null", x509);
return NULL;
}
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
return ASN1_OBJECT_to_OID_string(env, pubkey->algor->algorithm);
}
static jstring NativeCrypto_get_X509_sig_alg_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_oid(%p)", x509);
if (x509 == NULL || x509->sig_alg == NULL) {
jniThrowNullPointerException(env, "x509 == NULL || x509->sig_alg == NULL");
JNI_TRACE("get_X509_sig_alg_oid(%p) => x509 == NULL", x509);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, x509->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_sig_alg_parameter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_parameter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_sig_alg_parameter(%p) => x509 == null", x509);
return NULL;
}
if (x509->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_sig_alg_parameter(%p) => null", x509);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, x509->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbooleanArray NativeCrypto_get_X509_issuerUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_issuerUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_issuerUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->issuerUID == NULL) {
JNI_TRACE("get_X509_issuerUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->issuerUID);
}
static jbooleanArray NativeCrypto_get_X509_subjectUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_subjectUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_subjectUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->subjectUID == NULL) {
JNI_TRACE("get_X509_subjectUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->subjectUID);
}
static jbooleanArray NativeCrypto_get_X509_ex_kusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_kusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_kusage(%p) => x509 == null", x509);
return NULL;
}
Unique_ASN1_BIT_STRING bitStr(static_cast<ASN1_BIT_STRING*>(
X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL)));
if (bitStr.get() == NULL) {
JNI_TRACE("get_X509_ex_kusage(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, bitStr.get());
}
static jobjectArray NativeCrypto_get_X509_ex_xkusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_xkusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_xkusage(%p) => x509 == null", x509);
return NULL;
}
Unique_sk_ASN1_OBJECT objArray(static_cast<STACK_OF(ASN1_OBJECT)*>(
X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL)));
if (objArray.get() == NULL) {
JNI_TRACE("get_X509_ex_xkusage(%p) => null", x509);
return NULL;
}
size_t size = sk_ASN1_OBJECT_num(objArray.get());
ScopedLocalRef<jobjectArray> exKeyUsage(env, env->NewObjectArray(size, stringClass, NULL));
if (exKeyUsage.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
ScopedLocalRef<jstring> oidStr(env, ASN1_OBJECT_to_OID_string(env,
sk_ASN1_OBJECT_value(objArray.get(), i)));
env->SetObjectArrayElement(exKeyUsage.get(), i, oidStr.get());
}
JNI_TRACE("get_X509_ex_xkusage(%p) => success (%zd entries)", x509, size);
return exKeyUsage.release();
}
static jint NativeCrypto_get_X509_ex_pathlen(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_pathlen(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_pathlen(%p) => x509 == null", x509);
return 0;
}
/* Just need to do this to cache the ex_* values. */
X509_check_ca(x509);
JNI_TRACE("get_X509_ex_pathlen(%p) => %ld", x509, x509->ex_pathlen);
return x509->ex_pathlen;
}
static jbyteArray NativeCrypto_X509_get_ext_oid(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_ext_oid(%p, %p)", x509, oidString);
return X509Type_get_ext_oid<X509, X509_get_ext_by_OBJ, X509_get_ext>(env, x509, oidString);
}
static jbyteArray NativeCrypto_X509_CRL_get_ext_oid(JNIEnv* env, jclass, jlong x509CrlRef,
jstring oidString) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext_oid(%p, %p)", crl, oidString);
return X509Type_get_ext_oid<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(env, crl,
oidString);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_ext_oid(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oidString) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext_oid(%p, %p)", revoked, oidString);
return X509Type_get_ext_oid<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ, X509_REVOKED_get_ext>(
env, revoked, oidString);
}
template<typename T, int (*get_ext_by_critical_func)(T*, int, int), X509_EXTENSION* (*get_ext_func)(T*, int)>
static jobjectArray get_X509Type_ext_oids(JNIEnv* env, jlong x509Ref, jint critical) {
T* x509 = reinterpret_cast<T*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509Type_ext_oids(%p, %d)", x509, critical);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => x509 == null", x509, critical);
return NULL;
}
int lastPos = -1;
int count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
count++;
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) has %d entries", x509, critical, count);
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, stringClass, NULL));
if (joa.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => fail to allocate result array", x509, critical);
return NULL;
}
lastPos = -1;
count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
X509_EXTENSION* ext = get_ext_func(x509, lastPos);
ScopedLocalRef<jstring> extOid(env, ASN1_OBJECT_to_OID_string(env, ext->object));
if (extOid.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p) => couldn't get OID", x509);
return NULL;
}
env->SetObjectArrayElement(joa.get(), count++, extOid.get());
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => success", x509, critical);
return joa.release();
}
static jobjectArray NativeCrypto_get_X509_ext_oids(JNIEnv* env, jclass, jlong x509Ref,
jint critical) {
JNI_TRACE("get_X509_ext_oids(0x%llx, %d)", (long long) x509Ref, critical);
return get_X509Type_ext_oids<X509, X509_get_ext_by_critical, X509_get_ext>(env, x509Ref,
critical);
}
static jobjectArray NativeCrypto_get_X509_CRL_ext_oids(JNIEnv* env, jclass, jlong x509CrlRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509CrlRef, critical);
return get_X509Type_ext_oids<X509_CRL, X509_CRL_get_ext_by_critical, X509_CRL_get_ext>(env,
x509CrlRef, critical);
}
static jobjectArray NativeCrypto_get_X509_REVOKED_ext_oids(JNIEnv* env, jclass, jlong x509RevokedRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509RevokedRef, critical);
return get_X509Type_ext_oids<X509_REVOKED, X509_REVOKED_get_ext_by_critical,
X509_REVOKED_get_ext>(env, x509RevokedRef, critical);
}
#ifdef WITH_JNI_TRACE
/**
* Based on example logging call back from SSL_CTX_set_info_callback man page
*/
static void info_callback_LOG(const SSL* s __attribute__ ((unused)), int where, int ret)
{
int w = where & ~SSL_ST_MASK;
const char* str;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
} else {
str = "undefined";
}
if (where & SSL_CB_LOOP) {
JNI_TRACE("ssl=%p %s:%s %s", s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
JNI_TRACE("ssl=%p SSL3 alert %s:%s:%s %s %s",
s,
str,
SSL_alert_type_string(ret),
SSL_alert_desc_string(ret),
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
JNI_TRACE("ssl=%p %s:failed exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret < 0) {
JNI_TRACE("ssl=%p %s:error exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret == 1) {
JNI_TRACE("ssl=%p %s:ok exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown exit %d in %s %s",
s, str, ret, SSL_state_string(s), SSL_state_string_long(s));
}
} else if (where & SSL_CB_HANDSHAKE_START) {
JNI_TRACE("ssl=%p handshake start in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_HANDSHAKE_DONE) {
JNI_TRACE("ssl=%p handshake done in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown where %d in %s %s",
s, str, where, SSL_state_string(s), SSL_state_string_long(s));
}
}
#endif
/**
* Returns an array containing all the X509 certificate references
*/
static jlongArray getCertificateRefs(JNIEnv* env, const STACK_OF(X509)* chain)
{
if (chain == NULL) {
// Chain can be NULL if the associated cipher doesn't do certs.
return NULL;
}
ssize_t count = sk_X509_num(chain);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jlongArray> refArray(env, env->NewLongArray(count));
ScopedLongArrayRW refs(env, refArray.get());
if (refs.get() == NULL) {
return NULL;
}
for (ssize_t i = 0; i < count; i++) {
refs[i] = reinterpret_cast<uintptr_t>(X509_dup_nocopy(sk_X509_value(chain, i)));
}
return refArray.release();
}
/**
* Returns an array containing all the X500 principal's bytes.
*/
static jobjectArray getPrincipalBytes(JNIEnv* env, const STACK_OF(X509_NAME)* names)
{
if (names == NULL) {
return NULL;
}
int count = sk_X509_NAME_num(names);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, byteArrayClass, NULL));
if (joa.get() == NULL) {
return NULL;
}
for (int i = 0; i < count; i++) {
X509_NAME* principal = sk_X509_NAME_value(names, i);
ScopedLocalRef<jbyteArray> byteArray(env, ASN1ToByteArray<X509_NAME>(env,
principal, i2d_X509_NAME));
if (byteArray.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(joa.get(), i, byteArray.get());
}
return joa.release();
}
/**
* Our additional application data needed for getting synchronization right.
* This maybe warrants a bit of lengthy prose:
*
* (1) We use a flag to reflect whether we consider the SSL connection alive.
* Any read or write attempt loops will be cancelled once this flag becomes 0.
*
* (2) We use an int to count the number of threads that are blocked by the
* underlying socket. This may be at most two (one reader and one writer), since
* the Java layer ensures that no more threads will enter the native code at the
* same time.
*
* (3) The pipe is used primarily as a means of cancelling a blocking select()
* when we want to close the connection (aka "emergency button"). It is also
* necessary for dealing with a possible race condition situation: There might
* be cases where both threads see an SSL_ERROR_WANT_READ or
* SSL_ERROR_WANT_WRITE. Both will enter a select() with the proper argument.
* If one leaves the select() successfully before the other enters it, the
* "success" event is already consumed and the second thread will be blocked,
* possibly forever (depending on network conditions).
*
* The idea for solving the problem looks like this: Whenever a thread is
* successful in moving around data on the network, and it knows there is
* another thread stuck in a select(), it will write a byte to the pipe, waking
* up the other thread. A thread that returned from select(), on the other hand,
* knows whether it's been woken up by the pipe. If so, it will consume the
* byte, and the original state of affairs has been restored.
*
* The pipe may seem like a bit of overhead, but it fits in nicely with the
* other file descriptors of the select(), so there's only one condition to wait
* for.
*
* (4) Finally, a mutex is needed to make sure that at most one thread is in
* either SSL_read() or SSL_write() at any given time. This is an OpenSSL
* requirement. We use the same mutex to guard the field for counting the
* waiting threads.
*
* Note: The current implementation assumes that we don't have to deal with
* problems induced by multiple cores or processors and their respective
* memory caches. One possible problem is that of inconsistent views on the
* "aliveAndKicking" field. This could be worked around by also enclosing all
* accesses to that field inside a lock/unlock sequence of our mutex, but
* currently this seems a bit like overkill. Marking volatile at the very least.
*
* During handshaking, additional fields are used to up-call into
* Java to perform certificate verification and handshake
* completion. These are also used in any renegotiation.
*
* (5) the JNIEnv so we can invoke the Java callback
*
* (6) a NativeCrypto.SSLHandshakeCallbacks instance for callbacks from native to Java
*
* (7) a java.io.FileDescriptor wrapper to check for socket close
*
* We store the NPN protocols list so we can either send it (from the server) or
* select a protocol (on the client). We eagerly acquire a pointer to the array
* data so the callback doesn't need to acquire resources that it cannot
* release.
*
* Because renegotiation can be requested by the peer at any time,
* care should be taken to maintain an appropriate JNIEnv on any
* downcall to openssl since it could result in an upcall to Java. The
* current code does try to cover these cases by conditionally setting
* the JNIEnv on calls that can read and write to the SSL such as
* SSL_do_handshake, SSL_read, SSL_write, and SSL_shutdown.
*
* Finally, we have two emphemeral keys setup by OpenSSL callbacks:
*
* (8) a set of ephemeral RSA keys that is lazily generated if a peer
* wants to use an exportable RSA cipher suite.
*
* (9) a set of ephemeral EC keys that is lazily generated if a peer
* wants to use an TLS_ECDHE_* cipher suite.
*
*/
class AppData {
public:
volatile int aliveAndKicking;
int waitingThreads;
int fdsEmergency[2];
MUTEX_TYPE mutex;
JNIEnv* env;
jobject sslHandshakeCallbacks;
jbyteArray npnProtocolsArray;
jbyte* npnProtocolsData;
size_t npnProtocolsLength;
jbyteArray alpnProtocolsArray;
jbyte* alpnProtocolsData;
size_t alpnProtocolsLength;
Unique_RSA ephemeralRsa;
/**
* Creates the application data context for the SSL*.
*/
public:
static AppData* create() {
UniquePtr<AppData> appData(new AppData());
if (pipe(appData.get()->fdsEmergency) == -1) {
ALOGE("AppData::create pipe(2) failed: %s", strerror(errno));
return NULL;
}
if (!setBlocking(appData.get()->fdsEmergency[0], false)) {
ALOGE("AppData::create fcntl(2) failed: %s", strerror(errno));
return NULL;
}
if (MUTEX_SETUP(appData.get()->mutex) == -1) {
ALOGE("pthread_mutex_init(3) failed: %s", strerror(errno));
return NULL;
}
return appData.release();
}
~AppData() {
aliveAndKicking = 0;
if (fdsEmergency[0] != -1) {
close(fdsEmergency[0]);
}
if (fdsEmergency[1] != -1) {
close(fdsEmergency[1]);
}
clearCallbackState();
MUTEX_CLEANUP(mutex);
}
private:
AppData() :
aliveAndKicking(1),
waitingThreads(0),
env(NULL),
sslHandshakeCallbacks(NULL),
npnProtocolsArray(NULL),
npnProtocolsData(NULL),
npnProtocolsLength(-1),
alpnProtocolsArray(NULL),
alpnProtocolsData(NULL),
alpnProtocolsLength(-1),
ephemeralRsa(NULL) {
fdsEmergency[0] = -1;
fdsEmergency[1] = -1;
}
public:
/**
* Used to set the SSL-to-Java callback state before each SSL_*
* call that may result in a callback. It should be cleared after
* the operation returns with clearCallbackState.
*
* @param env The JNIEnv
* @param shc The SSLHandshakeCallbacks
* @param fd The FileDescriptor
* @param npnProtocols NPN protocols so that they may be advertised (by the
* server) or selected (by the client). Has no effect
* unless NPN is enabled.
* @param alpnProtocols ALPN protocols so that they may be advertised (by the
* server) or selected (by the client). Passing non-NULL
* enables ALPN.
*/
bool setCallbackState(JNIEnv* e, jobject shc, jobject fd, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
UniquePtr<NetFd> netFd;
if (fd != NULL) {
netFd.reset(new NetFd(e, fd));
if (netFd->isClosed()) {
JNI_TRACE("appData=%p setCallbackState => netFd->isClosed() == true", this);
return false;
}
}
env = e;
sslHandshakeCallbacks = shc;
if (npnProtocols != NULL) {
npnProtocolsData = e->GetByteArrayElements(npnProtocols, NULL);
if (npnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => npnProtocolsData == NULL", this);
return false;
}
npnProtocolsArray = npnProtocols;
npnProtocolsLength = e->GetArrayLength(npnProtocols);
}
if (alpnProtocols != NULL) {
alpnProtocolsData = e->GetByteArrayElements(alpnProtocols, NULL);
if (alpnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => alpnProtocolsData == NULL", this);
return false;
}
alpnProtocolsArray = alpnProtocols;
alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
}
return true;
}
void clearCallbackState() {
sslHandshakeCallbacks = NULL;
if (npnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(npnProtocolsArray, npnProtocolsData, JNI_ABORT);
npnProtocolsArray = NULL;
npnProtocolsData = NULL;
npnProtocolsLength = -1;
}
if (alpnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(alpnProtocolsArray, alpnProtocolsData, JNI_ABORT);
alpnProtocolsArray = NULL;
alpnProtocolsData = NULL;
alpnProtocolsLength = -1;
}
env = NULL;
}
};
/**
* Dark magic helper function that checks, for a given SSL session, whether it
* can SSL_read() or SSL_write() without blocking. Takes into account any
* concurrent attempts to close the SSLSocket from the Java side. This is
* needed to get rid of the hangs that occur when thread #1 closes the SSLSocket
* while thread #2 is sitting in a blocking read or write. The type argument
* specifies whether we are waiting for readability or writability. It expects
* to be passed either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, since we
* only need to wait in case one of these problems occurs.
*
* @param env
* @param type Either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
* @param fdObject The FileDescriptor, since appData->fileDescriptor should be NULL
* @param appData The application data structure with mutex info etc.
* @param timeout_millis The timeout value for poll call, with the special value
* 0 meaning no timeout at all (wait indefinitely). Note: This is
* the Java semantics of the timeout value, not the usual
* poll() semantics.
* @return The result of the inner poll() call,
* THROW_SOCKETEXCEPTION if a SocketException was thrown, -1 on
* additional errors
*/
static int sslSelect(JNIEnv* env, int type, jobject fdObject, AppData* appData, int timeout_millis) {
// This loop is an expanded version of the NET_FAILURE_RETRY
// macro. It cannot simply be used in this case because poll
// cannot be restarted without recreating the pollfd structure.
int result;
struct pollfd fds[2];
do {
NetFd fd(env, fdObject);
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
int intFd = fd.get();
JNI_TRACE("sslSelect type=%s fd=%d appData=%p timeout_millis=%d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE", intFd, appData, timeout_millis);
memset(&fds, 0, sizeof(fds));
fds[0].fd = intFd;
if (type == SSL_ERROR_WANT_READ) {
fds[0].events = POLLIN | POLLPRI;
} else {
fds[0].events = POLLOUT | POLLPRI;
}
fds[1].fd = appData->fdsEmergency[0];
fds[1].events = POLLIN | POLLPRI;
// Converting from Java semantics to Posix semantics.
if (timeout_millis <= 0) {
timeout_millis = -1;
}
#ifndef CONSCRYPT_UNBUNDLED
AsynchronousCloseMonitor monitor(intFd);
#else
CompatibilityCloseMonitor monitor(intFd);
#endif
result = poll(fds, sizeof(fds)/sizeof(fds[0]), timeout_millis);
JNI_TRACE("sslSelect %s fd=%d appData=%p timeout_millis=%d => %d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE",
fd.get(), appData, timeout_millis, result);
if (result == -1) {
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
if (errno != EINTR) {
break;
}
}
} while (result == -1);
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (result > 0) {
// We have been woken up by a token in the emergency pipe. We
// can't be sure the token is still in the pipe at this point
// because it could have already been read by the thread that
// originally wrote it if it entered sslSelect and acquired
// the mutex before we did. Thus we cannot safely read from
// the pipe in a blocking way (so we make the pipe
// non-blocking at creation).
if (fds[1].revents & POLLIN) {
char token;
do {
(void) read(appData->fdsEmergency[0], &token, 1);
} while (errno == EINTR);
}
}
// Tell the world that there is now one thread less waiting for the
// underlying network.
appData->waitingThreads--;
MUTEX_UNLOCK(appData->mutex);
return result;
}
/**
* Helper function that wakes up a thread blocked in select(), in case there is
* one. Is being called by sslRead() and sslWrite() as well as by JNI glue
* before closing the connection.
*
* @param data The application data structure with mutex info etc.
*/
static void sslNotify(AppData* appData) {
// Write a byte to the emergency pipe, so a concurrent select() can return.
// Note we have to restore the errno of the original system call, since the
// caller relies on it for generating error messages.
int errnoBackup = errno;
char token = '*';
do {
errno = 0;
(void) write(appData->fdsEmergency[1], &token, 1);
} while (errno == EINTR);
errno = errnoBackup;
}
static AppData* toAppData(const SSL* ssl) {
return reinterpret_cast<AppData*>(SSL_get_app_data(ssl));
}
/**
* Verify the X509 certificate via SSL_CTX_set_cert_verify_callback
*/
static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg __attribute__ ((unused)))
{
/* Get the correct index to the SSLobject stored into X509_STORE_CTX. */
SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_store_ctx,
SSL_get_ex_data_X509_STORE_CTX_idx()));
JNI_TRACE("ssl=%p cert_verify_callback x509_store_ctx=%p arg=%p", ssl, x509_store_ctx, arg);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in cert_verify_callback");
JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "verifyCertificateChain", "(J[JLjava/lang/String;)V");
jlongArray refArray = getCertificateRefs(env, x509_store_ctx->untrusted);
#if !defined(OPENSSL_IS_BORINGSSL)
const char* authMethod = SSL_authentication_method(ssl);
#else
const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
const char *authMethod = SSL_CIPHER_get_kx_name(cipher);
#endif
JNI_TRACE("ssl=%p cert_verify_callback calling verifyCertificateChain authMethod=%s",
ssl, authMethod);
jstring authMethodString = env->NewStringUTF(authMethod);
env->CallVoidMethod(sslHandshakeCallbacks, methodID,
static_cast<jlong>(reinterpret_cast<uintptr_t>(SSL_get1_session(ssl))), refArray,
authMethodString);
int result = (env->ExceptionCheck()) ? 0 : 1;
JNI_TRACE("ssl=%p cert_verify_callback => %d", ssl, result);
return result;
}
/**
* Call back to watch for handshake to be completed. This is necessary
* for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake
* returns before the handshake is completed in this case.
*/
static void info_callback(const SSL* ssl, int where, int ret) {
JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret);
#ifdef WITH_JNI_TRACE
info_callback_LOG(ssl, where, ret);
#endif
if (!(where & SSL_CB_HANDSHAKE_DONE) && !(where & SSL_CB_HANDSHAKE_START)) {
JNI_TRACE("ssl=%p info_callback ignored", ssl);
return;
}
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in info_callback");
JNI_TRACE("ssl=%p info_callback env error", ssl);
return;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback already pending exception", ssl);
return;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(cls, "onSSLStateChange", "(JII)V");
JNI_TRACE("ssl=%p info_callback calling onSSLStateChange", ssl);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, reinterpret_cast<jlong>(ssl), where, ret);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback exception", ssl);
}
JNI_TRACE("ssl=%p info_callback completed", ssl);
}
/**
* Call back to ask for a client certificate. There are three possible exit codes:
*
* 1 is success. x509Out and pkeyOut should point to the correct private key and certificate.
* 0 is unable to find key. x509Out and pkeyOut should be NULL.
* -1 is error and it doesn't matter what x509Out and pkeyOut are.
*/
static int client_cert_cb(SSL* ssl, X509** x509Out, EVP_PKEY** pkeyOut) {
JNI_TRACE("ssl=%p client_cert_cb x509Out=%p pkeyOut=%p", ssl, x509Out, pkeyOut);
/* Clear output of key and certificate in case of early exit due to error. */
*x509Out = NULL;
*pkeyOut = NULL;
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in client_cert_cb");
JNI_TRACE("ssl=%p client_cert_cb env error => 0", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb already pending exception => 0", ssl);
return -1;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "clientCertificateRequested", "([B[[B)V");
// Call Java callback which can use SSL_use_certificate and SSL_use_PrivateKey to set values
#if !defined(OPENSSL_IS_BORINGSSL)
const char* ctype = NULL;
char ssl2_ctype = SSL3_CT_RSA_SIGN;
int ctype_num = 0;
jobjectArray issuers = NULL;
switch (ssl->version) {
case SSL2_VERSION:
ctype = &ssl2_ctype;
ctype_num = 1;
break;
case SSL3_VERSION:
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
case DTLS1_VERSION:
ctype = ssl->s3->tmp.ctype;
ctype_num = ssl->s3->tmp.ctype_num;
issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
break;
}
#else
const uint8_t* ctype = NULL;
int ctype_num = SSL_get0_certificate_types(ssl, &ctype);
jobjectArray issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
#endif
#ifdef WITH_JNI_TRACE
for (int i = 0; i < ctype_num; i++) {
JNI_TRACE("ssl=%p clientCertificateRequested keyTypes[%d]=%d", ssl, i, ctype[i]);
}
#endif
jbyteArray keyTypes = env->NewByteArray(ctype_num);
if (keyTypes == NULL) {
JNI_TRACE("ssl=%p client_cert_cb bytes == null => 0", ssl);
return 0;
}
env->SetByteArrayRegion(keyTypes, 0, ctype_num, reinterpret_cast<const jbyte*>(ctype));
JNI_TRACE("ssl=%p clientCertificateRequested calling clientCertificateRequested "
"keyTypes=%p issuers=%p", ssl, keyTypes, issuers);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, keyTypes, issuers);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb exception => 0", ssl);
return -1;
}
// Check for values set from Java
X509* certificate = SSL_get_certificate(ssl);
EVP_PKEY* privatekey = SSL_get_privatekey(ssl);
int result = 0;
if (certificate != NULL && privatekey != NULL) {
*x509Out = certificate;
*pkeyOut = privatekey;
result = 1;
} else {
// Some error conditions return NULL, so make sure it doesn't linger.
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p client_cert_cb => *x509=%p *pkey=%p %d", ssl, *x509Out, *pkeyOut, result);
return result;
}
/**
* Pre-Shared Key (PSK) client callback.
*/
static unsigned int psk_client_callback(SSL* ssl, const char *hint,
char *identity, unsigned int max_identity_len,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_client_callback");
JNI_TRACE("ssl=%p psk_client_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID =
env->GetMethodID(cls, "clientPSKKeyRequested", "(Ljava/lang/String;[B[B)I");
JNI_TRACE("ssl=%p psk_client_callback calling clientPSKKeyRequested", ssl);
ScopedLocalRef<jstring> identityHintJava(
env,
(hint != NULL) ? env->NewStringUTF(hint) : NULL);
ScopedLocalRef<jbyteArray> identityJava(env, env->NewByteArray(max_identity_len));
if (identityJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate identity bufffer", ssl);
return 0;
}
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
ScopedByteArrayRO identityJavaRo(env, identityJava.get());
if (identityJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get identity bytes", ssl);
return 0;
}
memcpy(identity, identityJavaRo.get(), max_identity_len);
JNI_TRACE("ssl=%p psk_client_callback completed", ssl);
return keyLen;
}
/**
* Pre-Shared Key (PSK) server callback.
*/
static unsigned int psk_server_callback(SSL* ssl, const char *identity,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_server_callback");
JNI_TRACE("ssl=%p psk_server_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(
cls, "serverPSKKeyRequested", "(Ljava/lang/String;Ljava/lang/String;[B)I");
JNI_TRACE("ssl=%p psk_server_callback calling serverPSKKeyRequested", ssl);
const char* identityHint = SSL_get_psk_identity_hint(ssl);
// identityHint = NULL;
// identity = NULL;
ScopedLocalRef<jstring> identityHintJava(
env,
(identityHint != NULL) ? env->NewStringUTF(identityHint) : NULL);
ScopedLocalRef<jstring> identityJava(
env,
(identity != NULL) ? env->NewStringUTF(identity) : NULL);
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
JNI_TRACE("ssl=%p psk_server_callback completed", ssl);
return keyLen;
}
static RSA* rsaGenerateKey(int keylength) {
Unique_BIGNUM bn(BN_new());
if (bn.get() == NULL) {
return NULL;
}
int setWordResult = BN_set_word(bn.get(), RSA_F4);
if (setWordResult != 1) {
return NULL;
}
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
return NULL;
}
int generateResult = RSA_generate_key_ex(rsa.get(), keylength, bn.get(), NULL);
if (generateResult != 1) {
return NULL;
}
return rsa.release();
}
/**
* Call back to ask for an ephemeral RSA key for SSL_RSA_EXPORT_WITH_RC4_40_MD5 (aka EXP-RC4-MD5)
*/
static RSA* tmp_rsa_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_rsa_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralRsa.get() == NULL) {
JNI_TRACE("ssl=%p tmp_rsa_callback generating ephemeral RSA key", ssl);
appData->ephemeralRsa.reset(rsaGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_rsa_callback => %p", ssl, appData->ephemeralRsa.get());
return appData->ephemeralRsa.get();
}
static DH* dhGenerateParameters(int keylength) {
#if !defined(OPENSSL_IS_BORINGSSL)
/*
* The SSL_CTX_set_tmp_dh_callback(3SSL) man page discusses two
* different options for generating DH keys. One is generating the
* keys using a single set of DH parameters. However, generating
* DH parameters is slow enough (minutes) that they suggest doing
* it once at install time. The other is to generate DH keys from
* DSA parameters. Generating DSA parameters is faster than DH
* parameters, but to prevent small subgroup attacks, they needed
* to be regenerated for each set of DH keys. Setting the
* SSL_OP_SINGLE_DH_USE option make sure OpenSSL will call back
* for new DH parameters every type it needs to generate DH keys.
*/
// Fast path but must have SSL_OP_SINGLE_DH_USE set
Unique_DSA dsa(DSA_new());
if (!DSA_generate_parameters_ex(dsa.get(), keylength, NULL, 0, NULL, NULL, NULL)) {
return NULL;
}
DH* dh = DSA_dup_DH(dsa.get());
return dh;
#else
/* At the time of writing, OpenSSL and BoringSSL are hard coded to request
* a 1024-bit DH. */
if (keylength <= 1024) {
return DH_get_1024_160(NULL);
}
if (keylength <= 2048) {
return DH_get_2048_224(NULL);
}
/* In the case of a large request, return the strongest DH group that
* we have predefined. Generating a group takes far too long to be
* reasonable. */
return DH_get_2048_256(NULL);
#endif
}
/**
* Call back to ask for Diffie-Hellman parameters
*/
static DH* tmp_dh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_dh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
DH* tmp_dh = dhGenerateParameters(keylength);
JNI_TRACE("ssl=%p tmp_dh_callback => %p", ssl, tmp_dh);
return tmp_dh;
}
/*
* public static native int SSL_CTX_new();
*/
static jlong NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass) {
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
if (sslCtx.get() == NULL) {
throwExceptionIfNecessary(env, "SSL_CTX_new");
return 0;
}
SSL_CTX_set_options(sslCtx.get(),
SSL_OP_ALL
// Note: We explicitly do not allow SSLv2 to be used.
| SSL_OP_NO_SSLv2
// We also disable session tickets for better compatibility b/2682876
| SSL_OP_NO_TICKET
// We also disable compression for better compatibility b/2710492 b/2710497
| SSL_OP_NO_COMPRESSION
// Because dhGenerateParameters uses DSA_generate_parameters_ex
| SSL_OP_SINGLE_DH_USE
// Generate a fresh ECDH keypair for each key exchange.
| SSL_OP_SINGLE_ECDH_USE);
int mode = SSL_CTX_get_mode(sslCtx.get());
/*
* Turn on "partial write" mode. This means that SSL_write() will
* behave like Posix write() and possibly return after only
* writing a partial buffer. Note: The alternative, perhaps
* surprisingly, is not that SSL_write() always does full writes
* but that it will force you to retry write calls having
* preserved the full state of the original call. (This is icky
* and undesirable.)
*/
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
// Reuse empty buffers within the SSL_CTX to save memory
mode |= SSL_MODE_RELEASE_BUFFERS;
SSL_CTX_set_mode(sslCtx.get(), mode);
SSL_CTX_set_cert_verify_callback(sslCtx.get(), cert_verify_callback, NULL);
SSL_CTX_set_info_callback(sslCtx.get(), info_callback);
SSL_CTX_set_client_cert_cb(sslCtx.get(), client_cert_cb);
SSL_CTX_set_tmp_rsa_callback(sslCtx.get(), tmp_rsa_callback);
SSL_CTX_set_tmp_dh_callback(sslCtx.get(), tmp_dh_callback);
// If negotiating ECDH, use P-256.
Unique_EC_KEY ec(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (ec.get() == NULL) {
throwExceptionIfNecessary(env, "EC_KEY_new_by_curve_name");
return 0;
}
SSL_CTX_set_tmp_ecdh(sslCtx.get(), ec.get());
JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx.get());
return (jlong) sslCtx.release();
}
/**
* public static native void SSL_CTX_free(long ssl_ctx)
*/
static void NativeCrypto_SSL_CTX_free(JNIEnv* env,
jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_free(ssl_ctx);
}
static void NativeCrypto_SSL_CTX_set_session_id_context(JNIEnv* env, jclass,
jlong ssl_ctx_address, jbyteArray sid_ctx)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context sid_ctx=%p", ssl_ctx, sid_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO buf(env, sid_ctx);
if (buf.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => threw exception", ssl_ctx);
return;
}
unsigned int length = buf.size();
if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"length > SSL_MAX_SSL_SESSION_ID_LENGTH");
JNI_TRACE("NativeCrypto_SSL_CTX_set_session_id_context => length = %d", length);
return;
}
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buf.get());
int result = SSL_CTX_set_session_id_context(ssl_ctx, bytes, length);
if (result == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_SSL_CTX_set_session_id_context");
return;
}
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => ok", ssl_ctx);
}
/**
* public static native int SSL_new(long ssl_ctx) throws SSLException;
*/
static jlong NativeCrypto_SSL_new(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new", ssl_ctx);
if (ssl_ctx == NULL) {
return 0;
}
Unique_SSL ssl(SSL_new(ssl_ctx));
if (ssl.get() == NULL) {
throwSSLExceptionWithSslErrors(env, NULL, SSL_ERROR_NONE,
"Unable to create SSL structure");
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
return 0;
}
/*
* Create our special application data.
*/
AppData* appData = AppData::create();
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to create application data");
freeOpenSslErrorState();
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new appData => 0", ssl_ctx);
return 0;
}
SSL_set_app_data(ssl.get(), reinterpret_cast<char*>(appData));
/*
* Java code in class OpenSSLSocketImpl does the verification. Since
* the callbacks do all the verification of the chain, this flag
* simply controls whether to send protocol-level alerts or not.
* SSL_VERIFY_NONE means don't send alerts and anything else means send
* alerts.
*/
SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => ssl=%p appData=%p", ssl_ctx, ssl.get(), appData);
return (jlong) ssl.release();
}
static void NativeCrypto_SSL_enable_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_enable_tls_channel_id", ssl);
if (ssl == NULL) {
return;
}
long ret = SSL_enable_tls_channel_id(ssl);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error enabling Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_tls_channel_id => error", ssl);
return;
}
}
static jbyteArray NativeCrypto_SSL_get_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id", ssl);
if (ssl == NULL) {
return NULL;
}
// Channel ID is 64 bytes long. Unfortunately, OpenSSL doesn't declare this length
// as a constant anywhere.
jbyteArray javaBytes = env->NewByteArray(64);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => NULL", ssl);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
// Unfortunately, the SSL_get_tls_channel_id method below always returns 64 (upon success)
// regardless of the number of bytes copied into the output buffer "tmp". Thus, the correctness
// of this code currently relies on the "tmp" buffer being exactly 64 bytes long.
long ret = SSL_get_tls_channel_id(ssl, tmp, 64);
if (ret == 0) {
// Channel ID either not set or did not verify
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => not available", ssl);
return NULL;
} else if (ret != 64) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error getting Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_tls_channel_id => error, returned %ld", ssl, ret);
return NULL;
}
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id() => %p", ssl, javaBytes);
return javaBytes;
}
static void NativeCrypto_SSL_set1_tls_channel_id(JNIEnv* env, jclass,
jlong ssl_address, jobject pkeyRef)
{
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => pkey == null", ssl);
return;
}
// SSL_set1_tls_channel_id requires ssl->server to be set to 0.
// Unfortunately, the default value is 1 and it's only changed to 0 just
// before the handshake starts (see NativeCrypto_SSL_do_handshake).
ssl->server = 0;
long ret = SSL_set1_tls_channel_id(ssl, pkey);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(
env, ssl, SSL_ERROR_NONE, "Error setting private key for Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => error", ssl);
return;
}
// SSL_set1_tls_channel_id expects to take ownership of the EVP_PKEY, but
// we have an external reference from the caller such as an OpenSSLKey,
// so we manually increment the reference count here.
EVP_PKEY_up_ref(pkey);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => ok", ssl);
}
static void NativeCrypto_SSL_use_PrivateKey(JNIEnv* env, jclass, jlong ssl_address,
jobject pkeyRef) {
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_use_PrivateKey privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
JNI_TRACE("ssl=%p SSL_use_PrivateKey => pkey == null", ssl);
return;
}
int ret = SSL_use_PrivateKey(ssl, pkey);
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting private key");
safeSslClear(ssl);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => error", ssl);
return;
}
// SSL_use_PrivateKey expects to take ownership of the EVP_PKEY,
// but we have an external reference from the caller such as an
// OpenSSLKey, so we manually increment the reference count here.
EVP_PKEY_up_ref(pkey);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => ok", ssl);
}
static void NativeCrypto_SSL_use_certificate(JNIEnv* env, jclass,
jlong ssl_address, jlongArray certificatesJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate certificates=%p", ssl, certificatesJava);
if (ssl == NULL) {
return;
}
if (certificatesJava == NULL) {
jniThrowNullPointerException(env, "certificates == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
size_t length = env->GetArrayLength(certificatesJava);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "certificates.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates.length == 0", ssl);
return;
}
ScopedLongArrayRO certificates(env, certificatesJava);
if (certificates.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
Unique_X509 serverCert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[0]))));
if (serverCert.get() == NULL) {
// Note this shouldn't happen since we checked the number of certificates above.
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
int ret = SSL_use_certificate(ssl, serverCert.get());
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(serverCert);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !sk_X509_push(chain.get(), cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
int chainResult = SSL_use_certificate_chain(ssl, chain.get());
if (chainResult == 0) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate_chain error",
ssl);
return;
}
OWNERSHIP_TRANSFERRED(chain);
#else
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !SSL_add0_chain_cert(ssl, cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
#endif
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => ok", ssl);
}
static void NativeCrypto_SSL_check_private_key(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key", ssl);
if (ssl == NULL) {
return;
}
int ret = SSL_check_private_key(ssl);
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error checking private key");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => ok", ssl);
}
static void NativeCrypto_SSL_set_client_CA_list(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray principals)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list principals=%p", ssl, principals);
if (ssl == NULL) {
return;
}
if (principals == NULL) {
jniThrowNullPointerException(env, "principals == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals == null", ssl);
return;
}
int length = env->GetArrayLength(principals);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "principals.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals.length == 0", ssl);
return;
}
Unique_sk_X509_NAME principalsStack(sk_X509_NAME_new_null());
if (principalsStack.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate principal stack");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => stack allocation error", ssl);
return;
}
for (int i = 0; i < length; i++) {
ScopedLocalRef<jbyteArray> principal(env,
reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(principals, i)));
if (principal.get() == NULL) {
jniThrowNullPointerException(env, "principals element == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals element null", ssl);
return;
}
ScopedByteArrayRO buf(env, principal.get());
if (buf.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => threw exception", ssl);
return;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(buf.get());
Unique_X509_NAME principalX509Name(d2i_X509_NAME(NULL, &tmp, buf.size()));
if (principalX509Name.get() == NULL) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing principal");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals parsing error",
ssl);
return;
}
if (!sk_X509_NAME_push(principalsStack.get(), principalX509Name.release())) {
jniThrowOutOfMemory(env, "Unable to push principal");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principal push error", ssl);
return;
}
}
SSL_set_client_CA_list(ssl, principalsStack.release());
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => ok", ssl);
}
/**
* public static native long SSL_get_mode(long ssl);
*/
static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl);
if (ssl == NULL) {
return 0;
}
long mode = SSL_get_mode(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0x%lx", ssl, mode);
return mode;
}
/**
* public static native long SSL_set_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_get_options(long ssl);
*/
static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl);
if (ssl == NULL) {
return 0;
}
long options = SSL_get_options(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0x%lx", ssl, options);
return options;
}
/**
* public static native long SSL_set_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native void SSL_enable_signed_cert_timestamps(long ssl);
*/
static void NativeCrypto_SSL_enable_signed_cert_timestamps(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_signed_cert_timestamps", ssl);
if (ssl == NULL) {
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
SSL_enable_signed_cert_timestamps(ssl);
#endif
}
/**
* public static native byte[] SSL_get_signed_cert_timestamp_list(long ssl);
*/
static jbyteArray NativeCrypto_SSL_get_signed_cert_timestamp_list(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_signed_cert_timestamp_list", ssl);
if (ssl == NULL) {
return NULL;
}
#if defined(OPENSSL_IS_BORINGSSL)
const uint8_t *data;
size_t data_len;
SSL_get0_signed_cert_timestamp_list(ssl, &data, &data_len);
if (data_len == 0) {
JNI_TRACE("NativeCrypto_SSL_get_signed_cert_timestamp_list(%p) => NULL",
ssl);
return NULL;
}
jbyteArray result = env->NewByteArray(data_len);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, data_len, (const jbyte*)data);
}
return result;
#else
return NULL;
#endif
}
/*
* public static native void SSL_CTX_set_signed_cert_timestamp_list(long ssl, byte[] response);
*/
static void NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list(JNIEnv *env, jclass,
jlong ssl_ctx_address, jbyteArray list) {
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO listBytes(env, list);
if (listBytes.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list =>"
" list == NULL", ssl_ctx);
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
if (!SSL_CTX_set_signed_cert_timestamp_list(ssl_ctx,
reinterpret_cast<const uint8_t *>(listBytes.get()),
listBytes.size())) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list => fail", ssl_ctx);
} else {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list => ok", ssl_ctx);
}
#endif
}
/*
* public static native void SSL_enable_ocsp_stapling(long ssl);
*/
static void NativeCrypto_SSL_enable_ocsp_stapling(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_ocsp_stapling", ssl);
if (ssl == NULL) {
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
SSL_enable_ocsp_stapling(ssl);
#endif
}
/*
* public static native byte[] SSL_get_ocsp_response(long ssl);
*/
static jbyteArray NativeCrypto_SSL_get_ocsp_response(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ocsp_response", ssl);
if (ssl == NULL) {
return NULL;
}
#if defined(OPENSSL_IS_BORINGSSL)
const uint8_t *data;
size_t data_len;
SSL_get0_ocsp_response(ssl, &data, &data_len);
if (data_len == 0) {
JNI_TRACE("NativeCrypto_SSL_get_ocsp_response(%p) => NULL", ssl);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(data_len));
if (byteArray.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_ocsp_response(%p) => creating byte array failed", ssl);
return NULL;
}
env->SetByteArrayRegion(byteArray.get(), 0, data_len, (const jbyte*)data);
JNI_TRACE("NativeCrypto_SSL_get_ocsp_response(%p) => %p [size=%zd]",
ssl, byteArray.get(), data_len);
return byteArray.release();
#else
return NULL;
#endif
}
/*
* public static native void SSL_CTX_set_ocsp_response(long ssl, byte[] response);
*/
static void NativeCrypto_SSL_CTX_set_ocsp_response(JNIEnv *env, jclass,
jlong ssl_ctx_address, jbyteArray response) {
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO responseBytes(env, response);
if (responseBytes.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response => response == NULL", ssl_ctx);
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
if (!SSL_CTX_set_ocsp_response(ssl_ctx,
reinterpret_cast<const uint8_t *>(responseBytes.get()),
responseBytes.size())) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response => fail", ssl_ctx);
} else {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response => ok", ssl_ctx);
}
#endif
}
static void NativeCrypto_SSL_use_psk_identity_hint(JNIEnv* env, jclass,
jlong ssl_address, jstring identityHintJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_psk_identity_hint identityHint=%p",
ssl, identityHintJava);
if (ssl == NULL) {
return;
}
int ret;
if (identityHintJava == NULL) {
ret = SSL_use_psk_identity_hint(ssl, NULL);
} else {
ScopedUtfChars identityHint(env, identityHintJava);
if (identityHint.c_str() == NULL) {
throwSSLExceptionStr(env, "Failed to obtain identityHint bytes");
return;
}
ret = SSL_use_psk_identity_hint(ssl, identityHint.c_str());
}
if (ret != 1) {
int sslErrorCode = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Failed to set PSK identity hint");
safeSslClear(ssl);
}
}
static void NativeCrypto_set_SSL_psk_client_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_client_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_client_callback(ssl, (enabled) ? psk_client_callback : NULL);
}
static void NativeCrypto_set_SSL_psk_server_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_server_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_server_callback(ssl, (enabled) ? psk_server_callback : NULL);
}
static jlongArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl);
STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl);
int count = (cipherStack != NULL) ? sk_SSL_CIPHER_num(cipherStack) : 0;
ScopedLocalRef<jlongArray> ciphersArray(env, env->NewLongArray(count));
ScopedLongArrayRW ciphers(env, ciphersArray.get());
for (int i = 0; i < count; i++) {
ciphers[i] = reinterpret_cast<jlong>(sk_SSL_CIPHER_value(cipherStack, i));
}
JNI_TRACE("NativeCrypto_SSL_get_ciphers(%p) => %p [size=%d]", ssl, ciphersArray.get(), count);
return ciphersArray.release();
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_mkey(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_mkey => %ld", cipher, (long) cipher->algorithm_mkey);
return cipher->algorithm_mkey;
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_auth(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_auth => %ld", cipher, (long) cipher->algorithm_auth);
return cipher->algorithm_auth;
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_cipher_lists(JNIEnv* env, jclass, jlong ssl_address,
jobjectArray cipherSuites) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%p", ssl, cipherSuites);
if (ssl == NULL) {
return;
}
if (cipherSuites == NULL) {
jniThrowNullPointerException(env, "cipherSuites == null");
return;
}
int length = env->GetArrayLength(cipherSuites);
/*
* Special case for empty cipher list. This is considered an error by the
* SSL_set_cipher_list API, but Java allows this silly configuration.
* However, the SSL cipher list is still set even when SSL_set_cipher_list
* returns 0 in this case. Just to make sure, we check the resulting cipher
* list to make sure it's zero length.
*/
if (length == 0) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=empty", ssl);
SSL_set_cipher_list(ssl, "");
freeOpenSslErrorState();
if (sk_SSL_CIPHER_num(SSL_get_ciphers(ssl)) != 0) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=empty => error", ssl);
jniThrowRuntimeException(env, "SSL_set_cipher_list did not update ciphers!");
}
return;
}
static const char noSSLv2[] = "!SSLv2";
size_t cipherStringLen = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
if (c.c_str() == NULL) {
return;
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For the separating colon */
if (cipherStringLen + c.size() < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += c.size();
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For final NUL. */
UniquePtr<char[]> cipherString(new char[cipherStringLen]);
if (cipherString.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to alloc cipher string");
return;
}
memcpy(cipherString.get(), noSSLv2, strlen(noSSLv2));
size_t j = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
cipherString[j++] = ':';
memcpy(&cipherString[j], c.c_str(), c.size());
j += c.size();
}
cipherString[j++] = 0;
if (j != cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Internal error");
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%s", ssl, cipherString.get());
if (!SSL_set_cipher_list(ssl, cipherString.get())) {
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Illegal cipher suite strings.");
return;
}
}
static void NativeCrypto_SSL_set_accept_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_accept_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_accept_state(ssl);
}
static void NativeCrypto_SSL_set_connect_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_connect_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_connect_state(ssl);
}
/**
* Sets certificate expectations, especially for server to request client auth
*/
static void NativeCrypto_SSL_set_verify(JNIEnv* env,
jclass, jlong ssl_address, jint mode)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify mode=%x", ssl, mode);
if (ssl == NULL) {
return;
}
SSL_set_verify(ssl, (int)mode, NULL);
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass,
jlong ssl_address, jlong ssl_session_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session);
if (ssl == NULL) {
return;
}
int ret = SSL_set_session(ssl, ssl_session);
if (ret != 1) {
/*
* Translate the error, and throw if it turns out to be a real
* problem.
*/
int sslErrorCode = SSL_get_error(ssl, ret);
if (sslErrorCode != SSL_ERROR_ZERO_RETURN) {
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "SSL session set");
safeSslClear(ssl);
}
}
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean creation_enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d",
ssl, creation_enabled);
if (ssl == NULL) {
return;
}
#if !defined(OPENSSL_IS_BORINGSSL)
SSL_set_session_creation_enabled(ssl, creation_enabled);
#else
if (creation_enabled) {
SSL_clear_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
} else {
SSL_set_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
}
#endif
}
static void NativeCrypto_SSL_set_reject_peer_renegotiations(JNIEnv* env, jclass,
jlong ssl_address, jboolean reject_renegotiations)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_reject_peer_renegotiations reject_renegotiations=%d",
ssl, reject_renegotiations);
if (ssl == NULL) {
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
SSL_set_reject_peer_renegotiations(ssl, reject_renegotiations);
#else
(void) reject_renegotiations;
/* OpenSSL doesn't support this call and accepts renegotiation requests by
* default. */
#endif
}
static void NativeCrypto_SSL_set_tlsext_host_name(JNIEnv* env, jclass,
jlong ssl_address, jstring hostname)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostname=%p",
ssl, hostname);
if (ssl == NULL) {
return;
}
ScopedUtfChars hostnameChars(env, hostname);
if (hostnameChars.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostnameChars=%s",
ssl, hostnameChars.c_str());
int ret = SSL_set_tlsext_host_name(ssl, hostnameChars.c_str());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting host name");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => ok", ssl);
}
static jstring NativeCrypto_SSL_get_servername(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername", ssl);
if (ssl == NULL) {
return NULL;
}
const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername => %s", ssl, servername);
return env->NewStringUTF(servername);
}
/**
* A common selection path for both NPN and ALPN since they're essentially the
* same protocol. The list of protocols in "primary" is considered the order
* which should take precedence.
*/
static int proto_select(SSL* ssl __attribute__ ((unused)),
unsigned char **out, unsigned char *outLength,
const unsigned char *primary, const unsigned int primaryLength,
const unsigned char *secondary, const unsigned int secondaryLength) {
if (primary != NULL && secondary != NULL) {
JNI_TRACE("primary=%p, length=%d", primary, primaryLength);
int status = SSL_select_next_proto(out, outLength, primary, primaryLength, secondary,
secondaryLength);
switch (status) {
case OPENSSL_NPN_NEGOTIATED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN negotiated", ssl);
return SSL_TLSEXT_ERR_OK;
break;
case OPENSSL_NPN_UNSUPPORTED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN unsupported", ssl);
break;
case OPENSSL_NPN_NO_OVERLAP:
JNI_TRACE("ssl=%p proto_select NPN/ALPN no overlap", ssl);
break;
}
} else {
if (out != NULL && outLength != NULL) {
*out = NULL;
*outLength = 0;
}
JNI_TRACE("protocols=NULL");
}
return SSL_TLSEXT_ERR_NOACK;
}
/**
* Callback for the server to select an ALPN protocol.
*/
static int alpn_select_callback(SSL* ssl, const unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen, void *) {
JNI_TRACE("ssl=%p alpn_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
return proto_select(ssl, const_cast<unsigned char **>(out), outlen,
reinterpret_cast<unsigned char*>(appData->alpnProtocolsData),
appData->alpnProtocolsLength, in, inlen);
}
/**
* Callback for the client to select an NPN protocol.
*/
static int next_proto_select_callback(SSL* ssl, unsigned char** out, unsigned char* outlen,
const unsigned char* in, unsigned int inlen, void*)
{
JNI_TRACE("ssl=%p next_proto_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
// Enable False Start on the client if the server understands NPN
// http://www.imperialviolet.org/2012/04/11/falsestart.html
SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
return proto_select(ssl, out, outlen, in, inlen,
reinterpret_cast<unsigned char*>(appData->npnProtocolsData),
appData->npnProtocolsLength);
}
/**
* Callback for the server to advertise available protocols.
*/
static int next_protos_advertised_callback(SSL* ssl,
const unsigned char **out, unsigned int *outlen, void *)
{
JNI_TRACE("ssl=%p next_protos_advertised_callback", ssl);
AppData* appData = toAppData(ssl);
unsigned char* npnProtocols = reinterpret_cast<unsigned char*>(appData->npnProtocolsData);
if (npnProtocols != NULL) {
*out = npnProtocols;
*outlen = appData->npnProtocolsLength;
return SSL_TLSEXT_ERR_OK;
} else {
*out = NULL;
*outlen = 0;
return SSL_TLSEXT_ERR_NOACK;
}
}
static void NativeCrypto_SSL_CTX_enable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_callback, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_protos_advertised_callback, NULL); // server
}
static void NativeCrypto_SSL_CTX_disable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, NULL, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, NULL, NULL); // server
}
static jbyteArray NativeCrypto_SSL_get_npn_negotiated_protocol(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_npn_negotiated_protocol", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_next_proto_negotiated(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
static int NativeCrypto_SSL_set_alpn_protos(JNIEnv* env, jclass, jlong ssl_address,
jbyteArray protos) {
SSL* ssl = to_SSL(env, ssl_address, true);
if (ssl == NULL) {
return 0;
}
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p", ssl, protos);
if (protos == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=NULL", ssl);
return 1;
}
ScopedByteArrayRO protosBytes(env, protos);
if (protosBytes.get() == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => protosBytes == NULL", ssl,
protos);
return 0;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char*>(protosBytes.get());
int ret = SSL_set_alpn_protos(ssl, tmp, protosBytes.size());
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => ret=%d", ssl, protos, ret);
return ret;
}
static jbyteArray NativeCrypto_SSL_get0_alpn_selected(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p SSL_get0_alpn_selected", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_alpn_selected(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
#ifdef WITH_JNI_TRACE_KEYS
static inline char hex_char(unsigned char in)
{
if (in < 10) {
return '0' + in;
} else if (in <= 0xF0) {
return 'A' + in - 10;
} else {
return '?';
}
}
static void hex_string(char **dest, unsigned char* input, int len)
{
*dest = (char*) malloc(len * 2 + 1);
char *output = *dest;
for (int i = 0; i < len; i++) {
*output++ = hex_char(input[i] >> 4);
*output++ = hex_char(input[i] & 0xF);
}
*output = '\0';
}
static void debug_print_session_key(SSL_SESSION* session)
{
char *session_id_str;
char *master_key_str;
const char *key_type;
char *keyline;
hex_string(&session_id_str, session->session_id, session->session_id_length);
hex_string(&master_key_str, session->master_key, session->master_key_length);
X509* peer = SSL_SESSION_get0_peer(session);
EVP_PKEY* pkey = X509_PUBKEY_get(peer->cert_info->key);
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
key_type = "RSA";
break;
case EVP_PKEY_DSA:
key_type = "DSA";
break;
case EVP_PKEY_EC:
key_type = "EC";
break;
default:
key_type = "Unknown";
break;
}
asprintf(&keyline, "%s Session-ID:%s Master-Key:%s\n", key_type, session_id_str,
master_key_str);
JNI_TRACE("ssl_session=%p %s", session, keyline);
free(session_id_str);
free(master_key_str);
free(keyline);
}
#endif /* WITH_JNI_TRACE_KEYS */
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake_bio(JNIEnv* env, jclass, jlong ssl_address,
jlong rbioRef, jlong wbioRef, jobject shc, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
BIO* rbio = reinterpret_cast<BIO*>(rbioRef);
BIO* wbio = reinterpret_cast<BIO*>(wbioRef);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio rbio=%p wbio=%p shc=%p client_mode=%d npn=%p",
ssl, rbio, wbio, shc, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => rbio == null || wbio == NULL", ssl);
return 0;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (!client_mode && alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
int ret = 0;
errno = 0;
if (!appData->setCallbackState(env, shc, NULL, npnProtocols, alpnProtocols)) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio exception => 0", ssl);
return 0;
}
if (ret <= 0) { // error. See SSL_do_handshake(3SSL) man page.
// error case
OpenSslError sslError(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio ret=%d errno=%d sslError=%d",
ssl, ret, errno, sslError.get());
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we need to exit to allow
* the SSLEngine code to wrap or unwrap.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0) ||
(sslError.get() == SSL_ERROR_ZERO_RETURN)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
safeSslClear(ssl);
} else if (sslError.get() != SSL_ERROR_WANT_READ &&
sslError.get() != SSL_ERROR_WANT_WRITE) {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio error => 0", ssl);
return 0;
}
// success. handshake completed
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return reinterpret_cast<uintptr_t>(ssl_session);
}
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jint timeout_millis, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd=%p shc=%p timeout_millis=%d client_mode=%d npn=%p",
ssl, fdObject, shc, timeout_millis, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd == null => 0", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
NetFd fd(env, fdObject);
if (fd.isClosed()) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd.isClosed() => 0", ssl);
return 0;
}
int ret = SSL_set_fd(ssl, fd.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd.get());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE,
"Error setting the file descriptor");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake SSL_set_fd => 0", ssl);
return 0;
}
/*
* Make socket non-blocking, so SSL_connect SSL_read() and SSL_write() don't hang
* forever and we can use select() to find out if the socket is ready.
*/
if (!setBlocking(fd.get(), false)) {
throwSSLExceptionStr(env, "Unable to make socket non blocking");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setBlocking => 0", ssl);
return 0;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (client_mode) {
SSL_set_connect_state(ssl);
} else {
SSL_set_accept_state(ssl);
if (alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
}
ret = 0;
OpenSslError sslError;
while (appData->aliveAndKicking) {
errno = 0;
if (!appData->setCallbackState(env, shc, fdObject, npnProtocols, alpnProtocols)) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake exception => 0", ssl);
return 0;
}
// success case
if (ret == 1) {
break;
}
// retry case
if (errno == EINTR) {
continue;
}
// error case
sslError.reset(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake ret=%d errno=%d sslError=%d timeout_millis=%d",
ssl, ret, errno, sslError.get(), timeout_millis);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we use sslSelect to
* wait for it to become ready. If that doesn't happen
* before the specified timeout or an error occurs, we
* cancel the handshake. Otherwise we try the SSL_connect
* again.
*/
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslSelect => 0", ssl);
return 0;
}
if (selectResult == -1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_SYSCALL, "handshake error",
throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == -1 => 0", ssl);
return 0;
}
if (selectResult == 0) {
throwSocketTimeoutException(env, "SSL handshake timed out");
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == 0 => 0", ssl);
return 0;
}
} else {
// ALOGE("Unknown error %d during handshake", error);
break;
}
}
// clean error. See SSL_do_handshake(3SSL) man page.
if (ret == 0) {
/*
* The other side closed the socket before the handshake could be
* completed, but everything is within the bounds of the TLS protocol.
* We still might want to find out the real reason of the failure.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0) ||
(sslError.get() == SSL_ERROR_ZERO_RETURN)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
} else {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
}
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake clean error => 0", ssl);
return 0;
}
// unclean error. See SSL_do_handshake(3SSL) man page.
if (ret < 0) {
/*
* Translate the error and throw exception. We are sure it is an error
* at this point.
*/
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "SSL handshake aborted",
throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake unclean error => 0", ssl);
return 0;
}
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return (jlong) ssl_session;
}
/**
* Perform SSL renegotiation
*/
static void NativeCrypto_SSL_renegotiate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate", ssl);
if (ssl == NULL) {
return;
}
int result = SSL_renegotiate(ssl);
if (result != 1) {
throwSSLExceptionStr(env, "Problem with SSL_renegotiate");
return;
}
// first call asks client to perform renegotiation
int ret = SSL_do_handshake(ssl);
if (ret != 1) {
OpenSslError sslError(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"Problem with SSL_do_handshake after SSL_renegotiate");
return;
}
// if client agrees, set ssl state and perform renegotiation
ssl->state = SSL_ST_ACCEPT;
SSL_do_handshake(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate =>", ssl);
}
/**
* public static native byte[][] SSL_get_certificate(long ssl);
*/
static jlongArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl);
if (ssl == NULL) {
return NULL;
}
X509* certificate = SSL_get_certificate(ssl);
if (certificate == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
// SSL_get_certificate can return NULL during an error as well.
freeOpenSslErrorState();
return NULL;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => threw exception", ssl);
return NULL;
}
if (!sk_X509_push(chain.get(), X509_dup_nocopy(certificate))) {
jniThrowOutOfMemory(env, "Unable to push local certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
STACK_OF(X509)* cert_chain = SSL_get_certificate_chain(ssl, certificate);
for (int i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#else
STACK_OF(X509) *cert_chain = NULL;
if (!SSL_get0_chain_certs(ssl, &cert_chain)) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_chain_certs => NULL", ssl);
freeOpenSslErrorState();
return NULL;
}
for (size_t i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#endif
jlongArray refArray = getCertificateRefs(env, chain.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => %p", ssl, refArray);
return refArray;
}
// Fills a long[] with the peer certificates in the chain.
static jlongArray NativeCrypto_SSL_get_peer_cert_chain(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain", ssl);
if (ssl == NULL) {
return NULL;
}
STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl);
Unique_sk_X509 chain_copy(NULL);
if (ssl->server) {
X509* x509 = SSL_get_peer_certificate(ssl);
if (x509 == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => NULL", ssl);
return NULL;
}
chain_copy.reset(sk_X509_new_null());
if (chain_copy.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate dup error", ssl);
return NULL;
}
size_t chain_size = sk_X509_num(chain);
for (size_t i = 0; i < chain_size; i++) {
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(sk_X509_value(chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate chain push error", ssl);
return NULL;
}
}
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(x509))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate push error", ssl);
return NULL;
}
chain = chain_copy.get();
}
jlongArray refArray = getCertificateRefs(env, chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => %p", ssl, refArray);
return refArray;
}
static int sslRead(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, char* buf, jint len,
OpenSslError& sslError, int read_timeout_millis) {
JNI_TRACE("ssl=%p sslRead buf=%p len=%d", ssl, buf, len);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslRead appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
while (appData->aliveAndKicking) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslRead => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
int result = SSL_read(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p sslRead => THROWN_EXCEPTION", ssl);
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslRead SSL_read result=%d sslError=%d", ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslRead data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE: {
return result;
}
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, read_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
return -1;
}
static jint NativeCrypto_SSL_read_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray destJava,
jint destOffset, jint destLength, jlong sourceBioRef, jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sourceBioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO dest=%p sourceBio=%p sinkBio=%p shc=%p",
ssl, destJava, rbio, wbio, shc);
if (ssl == NULL) {
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => rbio == null || wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
ScopedByteArrayRW dest(env, destJava);
if (dest.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return -1;
}
if (ARRAY_OFFSET_LENGTH_INVALID(dest, destOffset, destLength)) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => destOffset=%d, destLength=%d, size=%zd",
ssl, destOffset, destLength, dest.size());
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => appData == NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set callback state");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => set callback state failed", ssl);
return -1;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
int result = SSL_read(ssl, dest.get() + destOffset, destLength);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return THROWN_EXCEPTION;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO SSL_read result=%d sslError=%d", ssl, result,
sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE:
break;
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
result = -1;
break;
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
result = 0;
break;
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
result = -1;
break;
} else if (errno == EINTR) {
// System call has been interrupted. Simply retry.
result = 0;
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
return -1;
}
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => %d", ssl, result);
return result;
}
/**
* OpenSSL read function (2): read into buffer at offset n chunks.
* Returns 1 (success) or value <= 0 (failure).
*/
static jint NativeCrypto_SSL_read(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len,
jint read_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read fd=%p shc=%p b=%p offset=%d len=%d read_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, read_timeout_millis);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => fd == null", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => sslHandshakeCallbacks == null", ssl);
return 0;
}
ScopedByteArrayRW bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => threw exception", ssl);
return 0;
}
OpenSslError sslError;
int ret = sslRead(env, ssl, fdObject, shc, reinterpret_cast<char*>(bytes.get() + offset), len,
sslError, read_timeout_millis);
int result;
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslRead() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
result = -1;
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Read timed out");
result = -1;
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
// or RuntimeException thrown by callback
result = -1;
break;
default:
result = ret;
break;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => %d", ssl, result);
return result;
}
static int sslWrite(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, const char* buf, jint len,
OpenSslError& sslError, int write_timeout_millis) {
JNI_TRACE("ssl=%p sslWrite buf=%p len=%d write_timeout_millis=%d",
ssl, buf, len, write_timeout_millis);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslWrite appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
int count = len;
while (appData->aliveAndKicking && len > 0) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslWrite => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
JNI_TRACE("ssl=%p sslWrite SSL_write len=%d", ssl, len);
int result = SSL_write(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p sslWrite exception => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslWrite SSL_write result=%d sslError=%d",
ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslWrite data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully wrote at least one byte.
case SSL_ERROR_NONE: {
buf += result;
len -= result;
break;
}
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
// The concept of a write timeout doesn't really make sense, and
// it's also not standard Java behavior, so we wait forever here.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData,
write_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
JNI_TRACE("ssl=%p sslWrite => count=%d", ssl, count);
return count;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static int NativeCrypto_SSL_write_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray sourceJava, jint len,
jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO source=%p len=%d wbio=%p shc=%p",
ssl, sourceJava, len, wbio, shc);
if (ssl == NULL) {
return -1;
}
if (wbio == NULL) {
jniThrowNullPointerException(env, "wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO appData => NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return 0;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set appdata callback");
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => appData can't set callback", ssl);
return -1;
}
ScopedByteArrayRO source(env, sourceJava);
if (source.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => threw exception", ssl);
return -1;
}
#if defined(OPENSSL_IS_BORINGSSL)
Unique_BIO nullBio(BIO_new_mem_buf(NULL, 0));
#else
Unique_BIO nullBio(BIO_new(BIO_s_null()));
#endif
ScopedSslBio sslBio(ssl, nullBio.get(), wbio);
int result = SSL_write(ssl, reinterpret_cast<const char*>(source.get()), len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO exception => exception pending (reneg)", ssl);
return -1;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO SSL_write result=%d sslError=%d",
ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
case SSL_ERROR_NONE:
return result;
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
return -1;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return 0;
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
return 0;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
}
}
return -1;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static void NativeCrypto_SSL_write(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len, jint write_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write fd=%p shc=%p b=%p offset=%d len=%d write_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, write_timeout_millis);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => sslHandshakeCallbacks == null", ssl);
return;
}
ScopedByteArrayRO bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => threw exception", ssl);
return;
}
OpenSslError sslError;
int ret = sslWrite(env, ssl, fdObject, shc, reinterpret_cast<const char*>(bytes.get() + offset),
len, sslError, write_timeout_millis);
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslWrite() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Write timed out");
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
break;
default:
break;
}
}
/**
* Interrupt any pending I/O before closing the socket.
*/
static void NativeCrypto_SSL_interrupt(
JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_interrupt", ssl);
if (ssl == NULL) {
return;
}
/*
* Mark the connection as quasi-dead, then send something to the emergency
* file descriptor, so any blocking select() calls are woken up.
*/
AppData* appData = toAppData(ssl);
if (appData != NULL) {
appData->aliveAndKicking = 0;
// At most two threads can be waiting.
sslNotify(appData);
sslNotify(appData);
}
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown(JNIEnv* env, jclass, jlong ssl_address,
jobject fdObject, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown fd=%p shc=%p", ssl, fdObject, shc);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
freeOpenSslErrorState();
safeSslClear(ssl);
return;
}
/*
* Try to make socket blocking again. OpenSSL literature recommends this.
*/
int fd = SSL_get_fd(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown s=%d", ssl, fd);
if (fd != -1) {
setBlocking(fd, true);
}
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
freeOpenSslErrorState();
safeSslClear(ssl);
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown_BIO(JNIEnv* env, jclass, jlong ssl_address, jlong rbioRef,
jlong wbioRef, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(rbioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(wbioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown rbio=%p wbio=%p shc=%p", ssl, rbio, wbio, shc);
if (ssl == NULL) {
return;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => rbio == null || wbio == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
freeOpenSslErrorState();
safeSslClear(ssl);
return;
}
ScopedSslBio scopedBio(ssl, rbio, wbio);
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
freeOpenSslErrorState();
safeSslClear(ssl);
}
static jint NativeCrypto_SSL_get_shutdown(JNIEnv* env, jclass, jlong ssl_address) {
const SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown", ssl);
if (ssl == NULL) {
jniThrowNullPointerException(env, "ssl == null");
return 0;
}
int status = SSL_get_shutdown(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown => %d", ssl, status);
return static_cast<jint>(status);
}
/**
* public static native void SSL_free(long ssl);
*/
static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl);
if (ssl == NULL) {
return;
}
AppData* appData = toAppData(ssl);
SSL_set_app_data(ssl, NULL);
delete appData;
SSL_free(ssl);
}
/**
* Gets and returns in a byte array the ID of the actual SSL session.
*/
static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass,
jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
jbyteArray result = env->NewByteArray(ssl_session->session_id_length);
if (result != NULL) {
jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id);
env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src);
}
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d",
ssl_session, result, ssl_session->session_id_length);
return result;
}
/**
* Gets and returns in a long integer the creation's time of the
* actual SSL session.
*/
static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session);
if (ssl_session == NULL) {
return 0;
}
// result must be jlong, not long or *1000 will overflow
jlong result = SSL_SESSION_get_time(ssl_session);
result *= 1000; // OpenSSL uses seconds, Java uses milliseconds.
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, (long long) result);
return result;
}
/**
* Gets and returns in a string the version of the SSL protocol. If it
* returns the string "unknown" it means that no connection is established.
*/
static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const char* protocol = SSL_SESSION_get_version(ssl_session);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol);
return env->NewStringUTF(protocol);
}
/**
* Gets and returns in a string the cipher negotiated for the SSL session.
*/
static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const SSL_CIPHER* cipher = ssl_session->cipher;
const char* name = SSL_CIPHER_get_name(cipher);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name);
return env->NewStringUTF(name);
}
/**
* Frees the SSL session.
*/
static void NativeCrypto_SSL_SESSION_free(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session);
if (ssl_session == NULL) {
return;
}
SSL_SESSION_free(ssl_session);
}
/**
* Serializes the native state of the session (ID, cipher, and keys but
* not certificates). Returns a byte[] containing the DER-encoded state.
* See apache mod_ssl.
*/
static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
return ASN1ToByteArray<SSL_SESSION>(env, ssl_session, i2d_SSL_SESSION);
}
/**
* Deserialize the session.
*/
static jlong NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => threw exception");
return 0;
}
const unsigned char* ucp = reinterpret_cast<const unsigned char*>(bytes.get());
SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, bytes.size());
#if !defined(OPENSSL_IS_BORINGSSL)
// Initialize SSL_SESSION cipher field based on cipher_id http://b/7091840
if (ssl_session != NULL) {
// based on ssl_get_prev_session
uint32_t cipher_id_network_order = htonl(ssl_session->cipher_id);
uint8_t* cipher_id_byte_pointer = reinterpret_cast<uint8_t*>(&cipher_id_network_order);
if (ssl_session->ssl_version >= SSL3_VERSION_MAJOR) {
cipher_id_byte_pointer += 2; // skip first two bytes for SSL3+
} else {
cipher_id_byte_pointer += 1; // skip first byte for SSL2
}
ssl_session->cipher = SSLv23_method()->get_cipher_by_char(cipher_id_byte_pointer);
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION cipher_id=%lx hton=%x 0=%x 1=%x cipher=%s",
ssl_session->cipher_id, cipher_id_network_order,
cipher_id_byte_pointer[0], cipher_id_byte_pointer[1],
SSL_CIPHER_get_name(ssl_session->cipher));
}
#endif
if (ssl_session == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session);
return reinterpret_cast<uintptr_t>(ssl_session);
}
static jlong NativeCrypto_ERR_peek_last_error(JNIEnv*, jclass) {
return ERR_peek_last_error();
}
static jstring NativeCrypto_SSL_CIPHER_get_kx_name(JNIEnv* env, jclass, jlong cipher_address) {
const SSL_CIPHER* cipher = to_SSL_CIPHER(env, cipher_address, true);
const char *kx_name = NULL;
#if defined(OPENSSL_IS_BORINGSSL)
kx_name = SSL_CIPHER_get_kx_name(cipher);
#else
kx_name = SSL_CIPHER_authentication_method(cipher);
#endif
return env->NewStringUTF(kx_name);
}
static jobjectArray NativeCrypto_get_cipher_names(JNIEnv *env, jclass, jstring selectorJava) {
ScopedUtfChars selector(env, selectorJava);
if (selector.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "selector == NULL");
return 0;
}
JNI_TRACE("NativeCrypto_get_cipher_names %s", selector.c_str());
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
Unique_SSL ssl(SSL_new(sslCtx.get()));
if (!SSL_set_cipher_list(ssl.get(), selector.c_str())) {
jniThrowException(env, "java/lang/IllegalArgumentException", "Unable to set SSL cipher list");
return 0;
}
STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl.get());
size_t size = sk_SSL_CIPHER_num(ciphers);
ScopedLocalRef<jobjectArray> cipherNamesArray(env, env->NewObjectArray(size, stringClass, NULL));
if (cipherNamesArray.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
const char *name = SSL_CIPHER_get_name(sk_SSL_CIPHER_value(ciphers, i));
ScopedLocalRef<jstring> cipherName(env, env->NewStringUTF(name));
env->SetObjectArrayElement(cipherNamesArray.get(), i, cipherName.get());
}
JNI_TRACE("NativeCrypto_get_cipher_names(%s) => success (%zd entries)", selector.c_str(), size);
return cipherNamesArray.release();
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* Compare the given CertID with a certificate and it's issuer.
* True is returned if the CertID matches.
*/
static bool ocsp_cert_id_matches_certificate(CBS *cert_id, X509 *x509, X509 *issuerX509) {
// Get the hash algorithm used by this CertID
CBS hash_algorithm, hash;
if (!CBS_get_asn1(cert_id, &hash_algorithm, CBS_ASN1_SEQUENCE) ||
!CBS_get_asn1(&hash_algorithm, &hash, CBS_ASN1_OBJECT)) {
return false;
}
// Get the issuer's name hash from the CertID
CBS issuer_name_hash;
if (!CBS_get_asn1(cert_id, &issuer_name_hash, CBS_ASN1_OCTETSTRING)) {
return false;
}
// Get the issuer's key hash from the CertID
CBS issuer_key_hash;
if (!CBS_get_asn1(cert_id, &issuer_key_hash, CBS_ASN1_OCTETSTRING)) {
return false;
}
// Get the serial number from the CertID
CBS serial;
if (!CBS_get_asn1(cert_id, &serial, CBS_ASN1_INTEGER)) {
return false;
}
// Compare the certificate's serial number with the one from the Cert ID
const uint8_t *p = CBS_data(&serial);
Unique_ASN1_INTEGER serial_number(c2i_ASN1_INTEGER(NULL, &p, CBS_len(&serial)));
ASN1_INTEGER *expected_serial_number = X509_get_serialNumber(x509);
if (serial_number.get() == NULL ||
ASN1_INTEGER_cmp(expected_serial_number, serial_number.get()) != 0) {
return false;
}
// Find the hash algorithm to be used
const EVP_MD *digest = EVP_get_digestbynid(OBJ_cbs2nid(&hash));
if (digest == NULL) {
return false;
}
// Hash the issuer's name and compare the hash with the one from the Cert ID
uint8_t md[EVP_MAX_MD_SIZE];
X509_NAME *issuer_name = X509_get_subject_name(issuerX509);
if (!X509_NAME_digest(issuer_name, digest, md, NULL) ||
!CBS_mem_equal(&issuer_name_hash, md, EVP_MD_size(digest))) {
return false;
}
// Same thing with the issuer's key
ASN1_BIT_STRING *issuer_key = X509_get0_pubkey_bitstr(issuerX509);
if (!EVP_Digest(issuer_key->data, issuer_key->length, md, NULL, digest, NULL) ||
!CBS_mem_equal(&issuer_key_hash, md, EVP_MD_size(digest))) {
return false;
}
return true;
}
/**
* Get a SingleResponse whose CertID matches the given certificate and issuer from a
* SEQUENCE OF SingleResponse.
*
* If found, |out_single_response| is set to the response, and true is returned. Otherwise if an
* error occured or no response matches the certificate, false is returned and |out_single_response|
* is unchanged.
*/
static bool find_ocsp_single_response(CBS* responses, X509 *x509, X509 *issuerX509,
CBS *out_single_response) {
// Iterate over all the SingleResponses, until one matches the certificate
while (CBS_len(responses) > 0) {
// Get the next available SingleResponse from the sequence
CBS single_response;
if (!CBS_get_asn1(responses, &single_response, CBS_ASN1_SEQUENCE)) {
return false;
}
// Make a copy of the stream so we pass it back to the caller
CBS single_response_original = single_response;
// Get the SingleResponse's CertID
// If this fails ignore the current response and move to the next one
CBS cert_id;
if (!CBS_get_asn1(&single_response, &cert_id, CBS_ASN1_SEQUENCE)) {
continue;
}
// Compare the CertID with the given certificate and issuer
if (ocsp_cert_id_matches_certificate(&cert_id, x509, issuerX509)) {
*out_single_response = single_response_original;
return true;
}
}
return false;
}
/**
* Get the BasicOCSPResponse from an OCSPResponse.
* If parsing succeeds and the response is of type basic, |basic_response| is set to it, and true is
* returned.
*/
static bool get_ocsp_basic_response(CBS *ocsp_response, CBS *basic_response) {
CBS tagged_response_bytes, response_bytes, response_type, response;
// Get the ResponseBytes out of the OCSPResponse
if (!CBS_get_asn1(ocsp_response, NULL /* responseStatus */, CBS_ASN1_ENUMERATED) ||
!CBS_get_asn1(ocsp_response, &tagged_response_bytes,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
!CBS_get_asn1(&tagged_response_bytes, &response_bytes,
CBS_ASN1_SEQUENCE)) {
return false;
}
// Parse the response type and data out of the ResponseBytes
if (!CBS_get_asn1(&response_bytes, &response_type, CBS_ASN1_OBJECT) ||
!CBS_get_asn1(&response_bytes, &response, CBS_ASN1_OCTETSTRING)) {
return false;
}
// Only basic OCSP responses are supported
if (OBJ_cbs2nid(&response_type) != NID_id_pkix_OCSP_basic) {
return false;
}
// Parse the octet string as a BasicOCSPResponse
return CBS_get_asn1(&response, basic_response, CBS_ASN1_SEQUENCE);
}
/**
* Get the SEQUENCE OF SingleResponse from a BasicOCSPResponse.
* If parsing succeeds, |single_responses| is set to point to the sequence of SingleResponse, and
* true is returned.
*/
static bool get_ocsp_single_responses(CBS *basic_response, CBS *single_responses) {
// Parse the ResponseData out of the BasicOCSPResponse. Ignore the rest.
CBS response_data;
if (!CBS_get_asn1(basic_response, &response_data, CBS_ASN1_SEQUENCE)) {
return false;
}
// Skip the version, responderID and producedAt fields
if (!CBS_get_optional_asn1(&response_data, NULL /* version */, NULL,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
!CBS_get_any_asn1_element(&response_data, NULL /* responderID */, NULL, NULL) ||
!CBS_get_any_asn1_element(&response_data, NULL /* producedAt */, NULL, NULL)) {
return false;
}
// Extract the list of SingleResponse.
return CBS_get_asn1(&response_data, single_responses, CBS_ASN1_SEQUENCE);
}
/**
* Get the SEQUENCE OF Extension from a SingleResponse.
* If parsing succeeds, |extensions| is set to point the the extension sequence and true is
* returned.
*/
static bool get_ocsp_single_response_extensions(CBS *single_response, CBS *extensions) {
// Skip the certID, certStatus, thisUpdate and optional nextUpdate fields.
if (!CBS_get_any_asn1_element(single_response, NULL /* certID */, NULL, NULL) ||
!CBS_get_any_asn1_element(single_response, NULL /* certStatus */, NULL, NULL) ||
!CBS_get_any_asn1_element(single_response, NULL /* thisUpdate */, NULL, NULL) ||
!CBS_get_optional_asn1(single_response, NULL /* nextUpdate */, NULL,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
return false;
}
// Get the list of Extension
return CBS_get_asn1(single_response, extensions,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1);
}
/*
* X509v3_get_ext_by_OBJ and X509v3_get_ext take const arguments, unlike the other *_get_ext
* functions.
* This means they cannot be used with X509Type_get_ext_oid, so these wrapper functions are used
* instead.
*/
static int _X509v3_get_ext_by_OBJ(X509_EXTENSIONS *exts, ASN1_OBJECT *obj, int lastpos) {
return X509v3_get_ext_by_OBJ(exts, obj, lastpos);
}
static X509_EXTENSION *_X509v3_get_ext(X509_EXTENSIONS* exts, int loc) {
return X509v3_get_ext(exts, loc);
}
/*
public static native byte[] get_ocsp_single_extension(byte[] ocspData, String oid,
long x509Ref, long issuerX509Ref);
*/
static jbyteArray NativeCrypto_get_ocsp_single_extension(JNIEnv *env, jclass,
jbyteArray ocspDataBytes, jstring oid, jlong x509Ref, jlong issuerX509Ref) {
ScopedByteArrayRO ocspData(env, ocspDataBytes);
if (ocspData.get() == NULL) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, reinterpret_cast<const uint8_t*>(ocspData.get()), ocspData.size());
// Start parsing the OCSPResponse
CBS ocsp_response;
if (!CBS_get_asn1(&cbs, &ocsp_response, CBS_ASN1_SEQUENCE)) {
return NULL;
}
// Get the BasicOCSPResponse from the OCSP Response
CBS basic_response;
if (!get_ocsp_basic_response(&ocsp_response, &basic_response)) {
return NULL;
}
// Get the list of SingleResponses from the BasicOCSPResponse
CBS responses;
if (!get_ocsp_single_responses(&basic_response, &responses)) {
return NULL;
}
// Find the response matching the certificate
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
X509* issuerX509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(issuerX509Ref));
CBS single_response;
if (!find_ocsp_single_response(&responses, x509, issuerX509, &single_response)) {
return NULL;
}
// Get the extensions from the SingleResponse
CBS extensions;
if (!get_ocsp_single_response_extensions(&single_response, &extensions)) {
return NULL;
}
const uint8_t* ptr = CBS_data(&extensions);
Unique_X509_EXTENSIONS x509_exts(d2i_X509_EXTENSIONS(NULL, &ptr, CBS_len(&extensions)));
if (x509_exts.get() == NULL) {
return NULL;
}
return X509Type_get_ext_oid<X509_EXTENSIONS, _X509v3_get_ext_by_OBJ, _X509v3_get_ext>(
env, x509_exts.get(), oid);
}
#else
static jbyteArray NativeCrypto_get_ocsp_single_extension(JNIEnv*, jclass, jbyteArray, jstring,
jlong, jlong) {
return NULL;
}
#endif
static jlong NativeCrypto_getDirectBufferAddress(JNIEnv *env, jclass, jobject buffer) {
return reinterpret_cast<jlong>(env->GetDirectBufferAddress(buffer));
}
#define FILE_DESCRIPTOR "Ljava/io/FileDescriptor;"
#define SSL_CALLBACKS "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto$SSLHandshakeCallbacks;"
#define REF_EC_GROUP "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_GROUP;"
#define REF_EC_POINT "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_POINT;"
#define REF_EVP_AEAD_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_AEAD_CTX;"
#define REF_EVP_CIPHER_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_CIPHER_CTX;"
#define REF_EVP_PKEY "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_PKEY;"
#define REF_HMAC_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$HMAC_CTX;"
static JNINativeMethod sNativeCryptoMethods[] = {
NATIVE_METHOD(NativeCrypto, clinit, "()Z"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_dynamic, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_by_id, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_add, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_init, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_finish, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_free, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_private_key, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_get_id, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, ENGINE_ctrl_cmd_string, "(JLjava/lang/String;Ljava/lang/String;I)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DH, "([B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_RSA, "([B[B[B[B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_EC_KEY, "(" REF_EC_GROUP REF_EC_POINT "[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_type, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_public, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_params, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_cmp, "(" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS8_PRIV_KEY_INFO, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS8_PRIV_KEY_INFO, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_PUBKEY, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PUBKEY, "([B)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PUBKEY, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PrivateKey, "(J)J"),
NATIVE_METHOD(NativeCrypto, getRSAPrivateKeyWrapper, "(Ljava/security/PrivateKey;[B)J"),
NATIVE_METHOD(NativeCrypto, getECPrivateKeyWrapper, "(Ljava/security/PrivateKey;" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, RSA_generate_key_ex, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, RSA_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, RSA_private_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, get_RSA_private_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, get_RSA_public_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, DH_generate_parameters_ex, "(IJ)J"),
NATIVE_METHOD(NativeCrypto, DH_generate_key, "(" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_DH_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_by_curve_name, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_arbitrary, "([B[B[B[B[B[BI)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_asn1_flag, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_point_conversion_form, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve_name, "(" REF_EC_GROUP ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve, "(" REF_EC_GROUP ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_order, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_degree, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_cofactor, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_generator, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, get_EC_GROUP_type, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_POINT_new, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_POINT_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_set_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT "[B[B)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_get_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_generate_key, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get1_group, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_private_key, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_public_key, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_set_nonce_from_hash, "(" REF_EVP_PKEY "Z)V"),
NATIVE_METHOD(NativeCrypto, ECDH_compute_key, "([BI" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_create, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_cleanup, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_destroy, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_copy_ex, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestInit_ex, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdateDirect, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestFinal_ex, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_get_digestbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdateDirect, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)[B"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyUpdateDirect, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)Z"),
NATIVE_METHOD(NativeCrypto, EVP_get_cipherbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_CipherInit_ex, "(" REF_EVP_CIPHER_CTX "J[B[BZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CipherUpdate, "(" REF_EVP_CIPHER_CTX "[BI[BII)I"),
NATIVE_METHOD(NativeCrypto, EVP_CipherFinal_ex, "(" REF_EVP_CIPHER_CTX "[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_iv_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_block_size, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_buf_len, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_final_used, "(" REF_EVP_CIPHER_CTX ")Z"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_padding, "(" REF_EVP_CIPHER_CTX "Z)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_key_length, "(" REF_EVP_CIPHER_CTX "I)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_aead_aes_128_gcm, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_aead_aes_256_gcm, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_init, "(J[BI)J"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_cleanup, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_max_overhead, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_nonce_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_max_tag_len, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_seal, "(" REF_EVP_AEAD_CTX "[BI[B[BII[B)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_open, "(" REF_EVP_AEAD_CTX "[BI[B[BII[B)I"),
NATIVE_METHOD(NativeCrypto, HMAC_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, HMAC_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, HMAC_Init_ex, "(" REF_HMAC_CTX "[BJ)V"),
NATIVE_METHOD(NativeCrypto, HMAC_Update, "(" REF_HMAC_CTX "[BII)V"),
NATIVE_METHOD(NativeCrypto, HMAC_UpdateDirect, "(" REF_HMAC_CTX "JI)V"),
NATIVE_METHOD(NativeCrypto, HMAC_Final, "(" REF_HMAC_CTX ")[B"),
NATIVE_METHOD(NativeCrypto, RAND_seed, "([B)V"),
NATIVE_METHOD(NativeCrypto, RAND_load_file, "(Ljava/lang/String;J)I"),
NATIVE_METHOD(NativeCrypto, RAND_bytes, "([B)V"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid, "(Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_longName, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_oid, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, create_BIO_InputStream, ("(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream;Z)J")),
NATIVE_METHOD(NativeCrypto, create_BIO_OutputStream, "(Ljava/io/OutputStream;)J"),
NATIVE_METHOD(NativeCrypto, BIO_read, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, BIO_write, "(J[BII)V"),
NATIVE_METHOD(NativeCrypto, BIO_free_all, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_NAME_print_ex, "(JJ)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, d2i_X509_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, d2i_X509, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509, "(J)[B"),
NATIVE_METHOD(NativeCrypto, i2d_X509_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PKCS7, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS7_bio, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS7, "([J)[B"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_unpack_X509_bio, "(J)[J"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_pack_X509, "([J)[B"),
NATIVE_METHOD(NativeCrypto, X509_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, get_X509_hashCode, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_print_ex, "(JJJJ)V"),
NATIVE_METHOD(NativeCrypto, X509_get_pubkey, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_get_subject_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_pubkey_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_issuerUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_subjectUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_kusage, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_xkusage, "(J)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_pathlen, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_delete_ext, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_crl_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_lastUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_nextUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_revocationDate, "(J)J"),
NATIVE_METHOD(NativeCrypto, get_X509_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_GENERAL_NAME_stack, "(JI)[[Ljava/lang/Object;"),
NATIVE_METHOD(NativeCrypto, X509_get_notBefore, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_notAfter, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_X509_cert_info_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_flags, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_check_issued, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, d2i_X509_CRL_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509_CRL, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_cert, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_serial, "(J[B)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_REVOKED, "(J)[J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_CRL, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_REVOKED, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_supported_extension, "(J)I"),
NATIVE_METHOD(NativeCrypto, ASN1_TIME_to_Calendar, "(JLjava/util/Calendar;)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_session_id_context, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_tls_channel_id, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_tls_channel_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set1_tls_channel_id, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_PrivateKey, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_certificate, "(J[J)V"),
NATIVE_METHOD(NativeCrypto, SSL_check_private_key, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_client_CA_list, "(J[[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_mode, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_get_options, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_signed_cert_timestamps, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_signed_cert_timestamp_list, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_signed_cert_timestamp_list, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_enable_ocsp_stapling, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ocsp_response, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_ocsp_response, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_use_psk_identity_hint, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_client_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_server_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_cipher_lists, "(J[Ljava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ciphers, "(J)[J"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_auth, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_mkey, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_set_accept_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_connect_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_verify, "(JI)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session_creation_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_reject_peer_renegotiations, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_tlsext_host_name, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_servername, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "IZ[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake_bio, "(JJJ" SSL_CALLBACKS "Z[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_renegotiate, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_certificate, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_get_peer_cert_chain, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_read, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)I"),
NATIVE_METHOD(NativeCrypto, SSL_read_BIO, "(J[BIIJJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_write, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)V"),
NATIVE_METHOD(NativeCrypto, SSL_write_BIO, "(J[BIJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_interrupt, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown, "(J" FILE_DESCRIPTOR SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown_BIO, "(JJJ" SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_get_shutdown, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_session_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_time, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_version, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_cipher, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, i2d_SSL_SESSION, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_SSL_SESSION, "([B)J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_enable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_disable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_npn_negotiated_protocol, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set_alpn_protos, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, SSL_get0_alpn_selected, "(J)[B"),
NATIVE_METHOD(NativeCrypto, ERR_peek_last_error, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CIPHER_get_kx_name, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_cipher_names, "(Ljava/lang/String;)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_ocsp_single_extension, "([BLjava/lang/String;JJ)[B"),
NATIVE_METHOD(NativeCrypto, getDirectBufferAddress, "(Ljava/nio/Buffer;)J"),
};
static jclass getGlobalRefToClass(JNIEnv* env, const char* className) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(className));
jclass globalRef = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (globalRef == NULL) {
ALOGE("failed to find class %s", className);
abort();
}
return globalRef;
}
static jmethodID getMethodRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jmethodID localMethod = env->GetMethodID(clazz, name, sig);
if (localMethod == NULL) {
ALOGE("could not find method %s", name);
abort();
}
return localMethod;
}
static jfieldID getFieldRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jfieldID localField = env->GetFieldID(clazz, name, sig);
if (localField == NULL) {
ALOGE("could not find field %s", name);
abort();
}
return localField;
}
static void initialize_conscrypt(JNIEnv* env) {
jniRegisterNativeMethods(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto",
sNativeCryptoMethods, NELEM(sNativeCryptoMethods));
cryptoUpcallsClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/CryptoUpcalls");
nativeRefClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef");
openSslInputStreamClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream");
nativeRef_context = getFieldRef(env, nativeRefClass, "context", "J");
calendar_setMethod = getMethodRef(env, calendarClass, "set", "(IIIIII)V");
inputStream_readMethod = getMethodRef(env, inputStreamClass, "read", "([B)I");
integer_valueOfMethod = env->GetStaticMethodID(integerClass, "valueOf",
"(I)Ljava/lang/Integer;");
openSslInputStream_readLineMethod = getMethodRef(env, openSslInputStreamClass, "gets",
"([B)I");
outputStream_writeMethod = getMethodRef(env, outputStreamClass, "write", "([B)V");
outputStream_flushMethod = getMethodRef(env, outputStreamClass, "flush", "()V");
#ifdef CONSCRYPT_UNBUNDLED
findAsynchronousCloseMonitorFuncs();
#endif
}
static jclass findClass(JNIEnv* env, const char* name) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(name));
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (result == NULL) {
ALOGE("failed to find class '%s'", name);
abort();
}
return result;
}
#ifdef STATIC_LIB
// Give client libs everything they need to initialize our JNI
int libconscrypt_JNI_OnLoad(JavaVM *vm, void*) {
#else
// Use JNI_OnLoad for when we're standalone
int JNI_OnLoad(JavaVM *vm, void*) {
JNI_TRACE("JNI_OnLoad NativeCrypto");
#endif
gJavaVM = vm;
JNIEnv *env;
if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
ALOGE("Could not get JNIEnv");
return JNI_ERR;
}
byteArrayClass = findClass(env, "[B");
calendarClass = findClass(env, "java/util/Calendar");
inputStreamClass = findClass(env, "java/io/InputStream");
integerClass = findClass(env, "java/lang/Integer");
objectClass = findClass(env, "java/lang/Object");
objectArrayClass = findClass(env, "[Ljava/lang/Object;");
outputStreamClass = findClass(env, "java/io/OutputStream");
stringClass = findClass(env, "java/lang/String");
initialize_conscrypt(env);
return JNI_VERSION_1_6;
}
/* vim: softtabstop=4:shiftwidth=4:expandtab */
/* Local Variables: */
/* mode: c++ */
/* tab-width: 4 */
/* indent-tabs-mode: nil */
/* c-basic-offset: 4 */
/* End: */
Revert "external/conscrypt: drop BORINGSSL_201510 ifdefs."
This breaks the unbundled build with OpenSSL.
This reverts commit f1754f30b818d8e67800322f24e8f6c623890861.
Change-Id: I2f3098414004aeb3f019c28bf0a0085a9d7eb3cc
/*
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Native glue for Java class org.conscrypt.NativeCrypto
*/
#define TO_STRING1(x) #x
#define TO_STRING(x) TO_STRING1(x)
#ifndef JNI_JARJAR_PREFIX
#ifndef CONSCRYPT_NOT_UNBUNDLED
#define CONSCRYPT_UNBUNDLED
#endif
#define JNI_JARJAR_PREFIX
#endif
#define LOG_TAG "NativeCrypto"
#include <arpa/inet.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef CONSCRYPT_UNBUNDLED
#include <dlfcn.h>
#endif
#include <jni.h>
#include <openssl/asn1t.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#if defined(OPENSSL_IS_BORINGSSL)
#include <openssl/aead.h>
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
#if defined(GOOGLE_INTERNAL)
#include "third_party/openssl/openssl/src/crypto/ecdsa/ecs_locl.h"
#else
#include "crypto/ecdsa/ecs_locl.h"
#endif
#endif
#ifndef CONSCRYPT_UNBUNDLED
/* If we're compiled unbundled from Android system image, we use the
* CompatibilityCloseMonitor
*/
#include "AsynchronousCloseMonitor.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "cutils/log.h"
#else
#include "log_compat.h"
#endif
#ifndef CONSCRYPT_UNBUNDLED
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
#else
#define NATIVE_METHOD(className, functionName, signature) \
{ (char*) #functionName, (char*) signature, reinterpret_cast<void*>(className ## _ ## functionName) }
#define REGISTER_NATIVE_METHODS(jni_class_name) \
RegisterNativeMethods(env, jni_class_name, gMethods, arraysize(gMethods))
#endif
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#include "NetFd.h"
#include "macros.h"
#undef WITH_JNI_TRACE
#undef WITH_JNI_TRACE_MD
#undef WITH_JNI_TRACE_DATA
/*
* How to use this for debugging with Wireshark:
*
* 1. Pull lines from logcat to a file that looks like (without quotes):
* "RSA Session-ID:... Master-Key:..." <CR>
* "RSA Session-ID:... Master-Key:..." <CR>
* <etc>
* 2. Start Wireshark
* 3. Go to Edit -> Preferences -> SSL -> (Pre-)Master-Key log and fill in
* the file you put the lines in above.
* 4. Follow the stream that corresponds to the desired "Session-ID" in
* the Server Hello.
*/
#undef WITH_JNI_TRACE_KEYS
#ifdef WITH_JNI_TRACE
#define JNI_TRACE(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__))
#else
#define JNI_TRACE(...) ((void)0)
#endif
#ifdef WITH_JNI_TRACE_MD
#define JNI_TRACE_MD(...) \
((void)ALOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__));
#else
#define JNI_TRACE_MD(...) ((void)0)
#endif
// don't overwhelm logcat
#define WITH_JNI_TRACE_DATA_CHUNK_SIZE 512
static JavaVM* gJavaVM;
static jclass cryptoUpcallsClass;
static jclass openSslInputStreamClass;
static jclass nativeRefClass;
static jclass byteArrayClass;
static jclass calendarClass;
static jclass objectClass;
static jclass objectArrayClass;
static jclass integerClass;
static jclass inputStreamClass;
static jclass outputStreamClass;
static jclass stringClass;
static jfieldID nativeRef_context;
static jmethodID calendar_setMethod;
static jmethodID inputStream_readMethod;
static jmethodID integer_valueOfMethod;
static jmethodID openSslInputStream_readLineMethod;
static jmethodID outputStream_writeMethod;
static jmethodID outputStream_flushMethod;
struct OPENSSL_Delete {
void operator()(void* p) const {
OPENSSL_free(p);
}
};
typedef UniquePtr<unsigned char, OPENSSL_Delete> Unique_OPENSSL_str;
struct BIO_Delete {
void operator()(BIO* p) const {
BIO_free_all(p);
}
};
typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
struct BIGNUM_Delete {
void operator()(BIGNUM* p) const {
BN_free(p);
}
};
typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
struct BN_CTX_Delete {
void operator()(BN_CTX* ctx) const {
BN_CTX_free(ctx);
}
};
typedef UniquePtr<BN_CTX, BN_CTX_Delete> Unique_BN_CTX;
struct ASN1_INTEGER_Delete {
void operator()(ASN1_INTEGER* p) const {
ASN1_INTEGER_free(p);
}
};
typedef UniquePtr<ASN1_INTEGER, ASN1_INTEGER_Delete> Unique_ASN1_INTEGER;
struct DH_Delete {
void operator()(DH* p) const {
DH_free(p);
}
};
typedef UniquePtr<DH, DH_Delete> Unique_DH;
struct DSA_Delete {
void operator()(DSA* p) const {
DSA_free(p);
}
};
typedef UniquePtr<DSA, DSA_Delete> Unique_DSA;
struct EC_GROUP_Delete {
void operator()(EC_GROUP* p) const {
EC_GROUP_free(p);
}
};
typedef UniquePtr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP;
struct EC_POINT_Delete {
void operator()(EC_POINT* p) const {
EC_POINT_clear_free(p);
}
};
typedef UniquePtr<EC_POINT, EC_POINT_Delete> Unique_EC_POINT;
struct EC_KEY_Delete {
void operator()(EC_KEY* p) const {
EC_KEY_free(p);
}
};
typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
struct EVP_MD_CTX_Delete {
void operator()(EVP_MD_CTX* p) const {
EVP_MD_CTX_destroy(p);
}
};
typedef UniquePtr<EVP_MD_CTX, EVP_MD_CTX_Delete> Unique_EVP_MD_CTX;
#if defined(OPENSSL_IS_BORINGSSL)
struct EVP_AEAD_CTX_Delete {
void operator()(EVP_AEAD_CTX* p) const {
EVP_AEAD_CTX_cleanup(p);
delete p;
}
};
typedef UniquePtr<EVP_AEAD_CTX, EVP_AEAD_CTX_Delete> Unique_EVP_AEAD_CTX;
#endif
struct EVP_CIPHER_CTX_Delete {
void operator()(EVP_CIPHER_CTX* p) const {
EVP_CIPHER_CTX_free(p);
}
};
typedef UniquePtr<EVP_CIPHER_CTX, EVP_CIPHER_CTX_Delete> Unique_EVP_CIPHER_CTX;
struct EVP_PKEY_Delete {
void operator()(EVP_PKEY* p) const {
EVP_PKEY_free(p);
}
};
typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
struct PKCS8_PRIV_KEY_INFO_Delete {
void operator()(PKCS8_PRIV_KEY_INFO* p) const {
PKCS8_PRIV_KEY_INFO_free(p);
}
};
typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
struct RSA_Delete {
void operator()(RSA* p) const {
RSA_free(p);
}
};
typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
struct ASN1_BIT_STRING_Delete {
void operator()(ASN1_BIT_STRING* p) const {
ASN1_BIT_STRING_free(p);
}
};
typedef UniquePtr<ASN1_BIT_STRING, ASN1_BIT_STRING_Delete> Unique_ASN1_BIT_STRING;
struct ASN1_OBJECT_Delete {
void operator()(ASN1_OBJECT* p) const {
ASN1_OBJECT_free(p);
}
};
typedef UniquePtr<ASN1_OBJECT, ASN1_OBJECT_Delete> Unique_ASN1_OBJECT;
struct ASN1_GENERALIZEDTIME_Delete {
void operator()(ASN1_GENERALIZEDTIME* p) const {
ASN1_GENERALIZEDTIME_free(p);
}
};
typedef UniquePtr<ASN1_GENERALIZEDTIME, ASN1_GENERALIZEDTIME_Delete> Unique_ASN1_GENERALIZEDTIME;
struct SSL_Delete {
void operator()(SSL* p) const {
SSL_free(p);
}
};
typedef UniquePtr<SSL, SSL_Delete> Unique_SSL;
struct SSL_CTX_Delete {
void operator()(SSL_CTX* p) const {
SSL_CTX_free(p);
}
};
typedef UniquePtr<SSL_CTX, SSL_CTX_Delete> Unique_SSL_CTX;
struct X509_Delete {
void operator()(X509* p) const {
X509_free(p);
}
};
typedef UniquePtr<X509, X509_Delete> Unique_X509;
struct X509_NAME_Delete {
void operator()(X509_NAME* p) const {
X509_NAME_free(p);
}
};
typedef UniquePtr<X509_NAME, X509_NAME_Delete> Unique_X509_NAME;
struct X509_EXTENSIONS_Delete {
void operator()(X509_EXTENSIONS* p) const {
sk_X509_EXTENSION_pop_free(p, X509_EXTENSION_free);
}
};
typedef UniquePtr<X509_EXTENSIONS, X509_EXTENSIONS_Delete> Unique_X509_EXTENSIONS;
#if !defined(OPENSSL_IS_BORINGSSL)
struct PKCS7_Delete {
void operator()(PKCS7* p) const {
PKCS7_free(p);
}
};
typedef UniquePtr<PKCS7, PKCS7_Delete> Unique_PKCS7;
#endif
struct sk_SSL_CIPHER_Delete {
void operator()(STACK_OF(SSL_CIPHER)* p) const {
// We don't own SSL_CIPHER references, so no need for pop_free
sk_SSL_CIPHER_free(p);
}
};
typedef UniquePtr<STACK_OF(SSL_CIPHER), sk_SSL_CIPHER_Delete> Unique_sk_SSL_CIPHER;
struct sk_X509_Delete {
void operator()(STACK_OF(X509)* p) const {
sk_X509_pop_free(p, X509_free);
}
};
typedef UniquePtr<STACK_OF(X509), sk_X509_Delete> Unique_sk_X509;
#if defined(OPENSSL_IS_BORINGSSL)
struct sk_X509_CRL_Delete {
void operator()(STACK_OF(X509_CRL)* p) const {
sk_X509_CRL_pop_free(p, X509_CRL_free);
}
};
typedef UniquePtr<STACK_OF(X509_CRL), sk_X509_CRL_Delete> Unique_sk_X509_CRL;
#endif
struct sk_X509_NAME_Delete {
void operator()(STACK_OF(X509_NAME)* p) const {
sk_X509_NAME_pop_free(p, X509_NAME_free);
}
};
typedef UniquePtr<STACK_OF(X509_NAME), sk_X509_NAME_Delete> Unique_sk_X509_NAME;
struct sk_ASN1_OBJECT_Delete {
void operator()(STACK_OF(ASN1_OBJECT)* p) const {
sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free);
}
};
typedef UniquePtr<STACK_OF(ASN1_OBJECT), sk_ASN1_OBJECT_Delete> Unique_sk_ASN1_OBJECT;
struct sk_GENERAL_NAME_Delete {
void operator()(STACK_OF(GENERAL_NAME)* p) const {
sk_GENERAL_NAME_pop_free(p, GENERAL_NAME_free);
}
};
typedef UniquePtr<STACK_OF(GENERAL_NAME), sk_GENERAL_NAME_Delete> Unique_sk_GENERAL_NAME;
/**
* Many OpenSSL APIs take ownership of an argument on success but don't free the argument
* on failure. This means we need to tell our scoped pointers when we've transferred ownership,
* without triggering a warning by not using the result of release().
*/
#define OWNERSHIP_TRANSFERRED(obj) \
do { typeof (obj.release()) _dummy __attribute__((unused)) = obj.release(); } while(0)
/**
* UNUSED_ARGUMENT can be used to mark an, otherwise unused, argument as "used"
* for the purposes of -Werror=unused-parameter. This can be needed when an
* argument's use is based on an #ifdef.
*/
#define UNUSED_ARGUMENT(x) ((void)(x));
/**
* Check array bounds for arguments when an array and offset are given.
*/
#define ARRAY_OFFSET_INVALID(array, offset) (offset < 0 || \
offset > static_cast<ssize_t>(array.size()))
/**
* Check array bounds for arguments when an array, offset, and length are given.
*/
#define ARRAY_OFFSET_LENGTH_INVALID(array, offset, len) (offset < 0 || \
offset > static_cast<ssize_t>(array.size()) || len < 0 || \
len > static_cast<ssize_t>(array.size()) - offset)
/**
* Frees the SSL error state.
*
* OpenSSL keeps an "error stack" per thread, and given that this code
* can be called from arbitrary threads that we don't keep track of,
* we err on the side of freeing the error state promptly (instead of,
* say, at thread death).
*/
static void freeOpenSslErrorState(void) {
ERR_clear_error();
ERR_remove_thread_state(NULL);
}
/**
* Manages the freeing of the OpenSSL error stack. This allows you to
* instantiate this object during an SSL call that may fail and not worry
* about manually calling freeOpenSslErrorState() later.
*
* As an optimization, you can also call .release() for passing as an
* argument to things that free the error stack state as a side-effect.
*/
class OpenSslError {
public:
OpenSslError() : sslError_(SSL_ERROR_NONE), released_(false) {
}
OpenSslError(SSL* ssl, int returnCode) : sslError_(SSL_ERROR_NONE), released_(false) {
reset(ssl, returnCode);
}
~OpenSslError() {
if (!released_ && sslError_ != SSL_ERROR_NONE) {
freeOpenSslErrorState();
}
}
int get() const {
return sslError_;
}
void reset(SSL* ssl, int returnCode) {
if (returnCode <= 0) {
sslError_ = SSL_get_error(ssl, returnCode);
} else {
sslError_ = SSL_ERROR_NONE;
}
}
int release() {
released_ = true;
return sslError_;
}
private:
int sslError_;
bool released_;
};
/**
* Throws a OutOfMemoryError with the given string as a message.
*/
static int jniThrowOutOfMemory(JNIEnv* env, const char* message) {
return jniThrowException(env, "java/lang/OutOfMemoryError", message);
}
/**
* Throws a BadPaddingException with the given string as a message.
*/
static int throwBadPaddingException(JNIEnv* env, const char* message) {
JNI_TRACE("throwBadPaddingException %s", message);
return jniThrowException(env, "javax/crypto/BadPaddingException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static int throwSignatureException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSignatureException %s", message);
return jniThrowException(env, "java/security/SignatureException", message);
}
/**
* Throws a InvalidKeyException with the given string as a message.
*/
static int throwInvalidKeyException(JNIEnv* env, const char* message) {
JNI_TRACE("throwInvalidKeyException %s", message);
return jniThrowException(env, "java/security/InvalidKeyException", message);
}
/**
* Throws a SignatureException with the given string as a message.
*/
static int throwIllegalBlockSizeException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalBlockSizeException %s", message);
return jniThrowException(env, "javax/crypto/IllegalBlockSizeException", message);
}
/**
* Throws a NoSuchAlgorithmException with the given string as a message.
*/
static int throwNoSuchAlgorithmException(JNIEnv* env, const char* message) {
JNI_TRACE("throwUnknownAlgorithmException %s", message);
return jniThrowException(env, "java/security/NoSuchAlgorithmException", message);
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* Throws a ParsingException with the given string as a message.
*/
static int throwParsingException(JNIEnv* env, const char* message) {
return jniThrowException(
env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLX509CertificateFactory$ParsingException",
message);
}
#endif
static int throwForAsn1Error(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE:
#if defined(ASN1_R_UNABLE_TO_DECODE_RSA_KEY)
case ASN1_R_UNABLE_TO_DECODE_RSA_KEY:
#endif
#if defined(ASN1_R_WRONG_PUBLIC_KEY_TYPE)
case ASN1_R_WRONG_PUBLIC_KEY_TYPE:
#endif
#if defined(ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY)
case ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY:
#endif
#if defined(ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE)
case ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE:
#endif
return throwInvalidKeyException(env, message);
break;
#if defined(ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
#endif
}
return defaultThrow(env, message);
}
#if defined(OPENSSL_IS_BORINGSSL)
static int throwForCipherError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case CIPHER_R_BAD_DECRYPT:
return throwBadPaddingException(env, message);
break;
case CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case CIPHER_R_WRONG_FINAL_BLOCK_LENGTH:
return throwIllegalBlockSizeException(env, message);
break;
case CIPHER_R_AES_KEY_SETUP_FAILED:
case CIPHER_R_BAD_KEY_LENGTH:
case CIPHER_R_UNSUPPORTED_KEY_SIZE:
return throwInvalidKeyException(env, message);
break;
}
return defaultThrow(env, message);
}
static int throwForEvpError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case EVP_R_MISSING_PARAMETERS:
return throwInvalidKeyException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
#if defined(EVP_R_X931_UNSUPPORTED)
case EVP_R_X931_UNSUPPORTED:
#endif
return throwNoSuchAlgorithmException(env, message);
break;
#if defined(EVP_R_WRONG_PUBLIC_KEY_TYPE)
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
return throwInvalidKeyException(env, message);
break;
#endif
#if defined(EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM)
case EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
#endif
default:
return defaultThrow(env, message);
break;
}
}
#else
static int throwForEvpError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case EVP_R_BAD_DECRYPT:
return throwBadPaddingException(env, message);
break;
case EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:
case EVP_R_WRONG_FINAL_BLOCK_LENGTH:
return throwIllegalBlockSizeException(env, message);
break;
case EVP_R_BAD_KEY_LENGTH:
case EVP_R_BN_DECODE_ERROR:
case EVP_R_BN_PUBKEY_ERROR:
case EVP_R_INVALID_KEY_LENGTH:
case EVP_R_MISSING_PARAMETERS:
case EVP_R_UNSUPPORTED_KEY_SIZE:
case EVP_R_UNSUPPORTED_KEYLENGTH:
return throwInvalidKeyException(env, message);
break;
case EVP_R_WRONG_PUBLIC_KEY_TYPE:
return throwSignatureException(env, message);
break;
case EVP_R_UNSUPPORTED_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
default:
return defaultThrow(env, message);
break;
}
}
#endif
static int throwForRsaError(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case RSA_R_BLOCK_TYPE_IS_NOT_01:
case RSA_R_PKCS_DECODING_ERROR:
#if defined(RSA_R_BLOCK_TYPE_IS_NOT_02)
case RSA_R_BLOCK_TYPE_IS_NOT_02:
#endif
return throwBadPaddingException(env, message);
break;
case RSA_R_BAD_SIGNATURE:
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
case RSA_R_INVALID_MESSAGE_LENGTH:
case RSA_R_WRONG_SIGNATURE_LENGTH:
#if !defined(OPENSSL_IS_BORINGSSL)
case RSA_R_ALGORITHM_MISMATCH:
case RSA_R_DATA_GREATER_THAN_MOD_LEN:
#endif
return throwSignatureException(env, message);
break;
case RSA_R_UNKNOWN_ALGORITHM_TYPE:
return throwNoSuchAlgorithmException(env, message);
break;
case RSA_R_MODULUS_TOO_LARGE:
case RSA_R_NO_PUBLIC_EXPONENT:
return throwInvalidKeyException(env, message);
break;
}
return defaultThrow(env, message);
}
static int throwForX509Error(JNIEnv* env, int reason, const char *message,
int (*defaultThrow)(JNIEnv*, const char*)) {
switch (reason) {
case X509_R_UNSUPPORTED_ALGORITHM:
return throwNoSuchAlgorithmException(env, message);
break;
default:
return defaultThrow(env, message);
break;
}
}
/*
* Checks this thread's OpenSSL error queue and throws a RuntimeException if
* necessary.
*
* @return true if an exception was thrown, false if not.
*/
static bool throwExceptionIfNecessary(JNIEnv* env, const char* location __attribute__ ((unused)),
int (*defaultThrow)(JNIEnv*, const char*) = jniThrowRuntimeException) {
const char* file;
int line;
const char* data;
int flags;
unsigned long error = ERR_get_error_line_data(&file, &line, &data, &flags);
int result = false;
if (error != 0) {
char message[256];
ERR_error_string_n(error, message, sizeof(message));
int library = ERR_GET_LIB(error);
int reason = ERR_GET_REASON(error);
JNI_TRACE("OpenSSL error in %s error=%lx library=%x reason=%x (%s:%d): %s %s",
location, error, library, reason, file, line, message,
(flags & ERR_TXT_STRING) ? data : "(no data)");
switch (library) {
case ERR_LIB_RSA:
throwForRsaError(env, reason, message, defaultThrow);
break;
case ERR_LIB_ASN1:
throwForAsn1Error(env, reason, message, defaultThrow);
break;
#if defined(OPENSSL_IS_BORINGSSL)
case ERR_LIB_CIPHER:
throwForCipherError(env, reason, message, defaultThrow);
break;
#endif
case ERR_LIB_EVP:
throwForEvpError(env, reason, message, defaultThrow);
break;
case ERR_LIB_X509:
throwForX509Error(env, reason, message, defaultThrow);
break;
case ERR_LIB_DSA:
throwInvalidKeyException(env, message);
break;
default:
defaultThrow(env, message);
break;
}
result = true;
}
freeOpenSslErrorState();
return result;
}
/**
* Throws an SocketTimeoutException with the given string as a message.
*/
static int throwSocketTimeoutException(JNIEnv* env, const char* message) {
JNI_TRACE("throwSocketTimeoutException %s", message);
return jniThrowException(env, "java/net/SocketTimeoutException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static int throwSSLHandshakeExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
return jniThrowException(env, "javax/net/ssl/SSLHandshakeException", message);
}
/**
* Throws a javax.net.ssl.SSLException with the given string as a message.
*/
static int throwSSLExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
return jniThrowException(env, "javax/net/ssl/SSLException", message);
}
/**
* Throws a javax.net.ssl.SSLProcotolException with the given string as a message.
*/
static int throwSSLProtocolExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLProtocolExceptionStr %s", message);
return jniThrowException(env, "javax/net/ssl/SSLProtocolException", message);
}
/**
* Throws an SSLException with a message constructed from the current
* SSL errors. This will also log the errors.
*
* @param env the JNI environment
* @param ssl the possibly NULL SSL
* @param sslErrorCode error code returned from SSL_get_error() or
* SSL_ERROR_NONE to probe with ERR_get_error
* @param message null-ok; general error message
*/
static int throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCode,
const char* message, int (*actualThrow)(JNIEnv*, const char*) = throwSSLExceptionStr) {
if (message == NULL) {
message = "SSL error";
}
// First consult the SSL error code for the general message.
const char* sslErrorStr = NULL;
switch (sslErrorCode) {
case SSL_ERROR_NONE:
if (ERR_peek_error() == 0) {
sslErrorStr = "OK";
} else {
sslErrorStr = "";
}
break;
case SSL_ERROR_SSL:
sslErrorStr = "Failure in SSL library, usually a protocol error";
break;
case SSL_ERROR_WANT_READ:
sslErrorStr = "SSL_ERROR_WANT_READ occurred. You should never see this.";
break;
case SSL_ERROR_WANT_WRITE:
sslErrorStr = "SSL_ERROR_WANT_WRITE occurred. You should never see this.";
break;
case SSL_ERROR_WANT_X509_LOOKUP:
sslErrorStr = "SSL_ERROR_WANT_X509_LOOKUP occurred. You should never see this.";
break;
case SSL_ERROR_SYSCALL:
sslErrorStr = "I/O error during system call";
break;
case SSL_ERROR_ZERO_RETURN:
sslErrorStr = "SSL_ERROR_ZERO_RETURN occurred. You should never see this.";
break;
case SSL_ERROR_WANT_CONNECT:
sslErrorStr = "SSL_ERROR_WANT_CONNECT occurred. You should never see this.";
break;
case SSL_ERROR_WANT_ACCEPT:
sslErrorStr = "SSL_ERROR_WANT_ACCEPT occurred. You should never see this.";
break;
default:
sslErrorStr = "Unknown SSL error";
}
// Prepend either our explicit message or a default one.
char* str;
if (asprintf(&str, "%s: ssl=%p: %s", message, ssl, sslErrorStr) <= 0) {
// problem with asprintf, just throw argument message, log everything
int ret = actualThrow(env, message);
ALOGV("%s: ssl=%p: %s", message, ssl, sslErrorStr);
freeOpenSslErrorState();
return ret;
}
char* allocStr = str;
// For protocol errors, SSL might have more information.
if (sslErrorCode == SSL_ERROR_NONE || sslErrorCode == SSL_ERROR_SSL) {
// Append each error as an additional line to the message.
for (;;) {
char errStr[256];
const char* file;
int line;
const char* data;
int flags;
unsigned long err = ERR_get_error_line_data(&file, &line, &data, &flags);
if (err == 0) {
break;
}
ERR_error_string_n(err, errStr, sizeof(errStr));
int ret = asprintf(&str, "%s\n%s (%s:%d %p:0x%08x)",
(allocStr == NULL) ? "" : allocStr,
errStr,
file,
line,
(flags & ERR_TXT_STRING) ? data : "(no data)",
flags);
if (ret < 0) {
break;
}
free(allocStr);
allocStr = str;
}
// For errors during system calls, errno might be our friend.
} else if (sslErrorCode == SSL_ERROR_SYSCALL) {
if (asprintf(&str, "%s, %s", allocStr, strerror(errno)) >= 0) {
free(allocStr);
allocStr = str;
}
// If the error code is invalid, print it.
} else if (sslErrorCode > SSL_ERROR_WANT_ACCEPT) {
if (asprintf(&str, ", error code is %d", sslErrorCode) >= 0) {
free(allocStr);
allocStr = str;
}
}
int ret;
if (sslErrorCode == SSL_ERROR_SSL) {
ret = throwSSLProtocolExceptionStr(env, allocStr);
} else {
ret = actualThrow(env, allocStr);
}
ALOGV("%s", allocStr);
free(allocStr);
freeOpenSslErrorState();
return ret;
}
/**
* Helper function that grabs the casts an ssl pointer and then checks for nullness.
* If this function returns NULL and <code>throwIfNull</code> is
* passed as <code>true</code>, then this function will call
* <code>throwSSLExceptionStr</code> before returning, so in this case of
* NULL, a caller of this function should simply return and allow JNI
* to do its thing.
*
* @param env the JNI environment
* @param ssl_address; the ssl_address pointer as an integer
* @param throwIfNull whether to throw if the SSL pointer is NULL
* @returns the pointer, which may be NULL
*/
static SSL_CTX* to_SSL_CTX(JNIEnv* env, jlong ssl_ctx_address, bool throwIfNull) {
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
if ((ssl_ctx == NULL) && throwIfNull) {
JNI_TRACE("ssl_ctx == null");
jniThrowNullPointerException(env, "ssl_ctx == null");
}
return ssl_ctx;
}
static SSL* to_SSL(JNIEnv* env, jlong ssl_address, bool throwIfNull) {
SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
if ((ssl == NULL) && throwIfNull) {
JNI_TRACE("ssl == null");
jniThrowNullPointerException(env, "ssl == null");
}
return ssl;
}
static SSL_SESSION* to_SSL_SESSION(JNIEnv* env, jlong ssl_session_address, bool throwIfNull) {
SSL_SESSION* ssl_session
= reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
if ((ssl_session == NULL) && throwIfNull) {
JNI_TRACE("ssl_session == null");
jniThrowNullPointerException(env, "ssl_session == null");
}
return ssl_session;
}
static SSL_CIPHER* to_SSL_CIPHER(JNIEnv* env, jlong ssl_cipher_address, bool throwIfNull) {
SSL_CIPHER* ssl_cipher
= reinterpret_cast<SSL_CIPHER*>(static_cast<uintptr_t>(ssl_cipher_address));
if ((ssl_cipher == NULL) && throwIfNull) {
JNI_TRACE("ssl_cipher == null");
jniThrowNullPointerException(env, "ssl_cipher == null");
}
return ssl_cipher;
}
template<typename T>
static T* fromContextObject(JNIEnv* env, jobject contextObject) {
if (contextObject == NULL) {
JNI_TRACE("contextObject == null");
jniThrowNullPointerException(env, "contextObject == null");
return NULL;
}
T* ref = reinterpret_cast<T*>(env->GetLongField(contextObject, nativeRef_context));
if (ref == NULL) {
JNI_TRACE("ref == null");
jniThrowNullPointerException(env, "ref == null");
return NULL;
}
return ref;
}
/**
* Converts a Java byte[] two's complement to an OpenSSL BIGNUM. This will
* allocate the BIGNUM if *dest == NULL. Returns true on success. If the
* return value is false, there is a pending exception.
*/
static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
JNI_TRACE("arrayToBignum(%p, %p)", source, dest);
if (dest == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => dest is null!", source, dest);
jniThrowNullPointerException(env, "dest == null");
return false;
}
JNI_TRACE("arrayToBignum(%p, %p) *dest == %p", source, dest, *dest);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, dest);
return false;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
/* if the array is empty, it is zero. */
if (tmpSize == 0) {
if (*dest == NULL) {
*dest = BN_new();
}
BN_zero(*dest);
return true;
}
UniquePtr<unsigned char[]> twosComplement;
bool negative = (tmp[0] & 0x80) != 0;
if (negative) {
// Need to convert to two's complement.
twosComplement.reset(new unsigned char[tmpSize]);
unsigned char* twosBytes = reinterpret_cast<unsigned char*>(twosComplement.get());
memcpy(twosBytes, tmp, tmpSize);
tmp = twosBytes;
bool carry = true;
for (ssize_t i = tmpSize - 1; i >= 0; i--) {
twosBytes[i] ^= 0xFF;
if (carry) {
carry = (++twosBytes[i]) == 0;
}
}
}
BIGNUM *ret = BN_bin2bn(tmp, tmpSize, *dest);
if (ret == NULL) {
jniThrowRuntimeException(env, "Conversion to BIGNUM failed");
JNI_TRACE("arrayToBignum(%p, %p) => threw exception", source, dest);
return false;
}
BN_set_negative(ret, negative ? 1 : 0);
*dest = ret;
JNI_TRACE("arrayToBignum(%p, %p) => *dest = %p", source, dest, ret);
return true;
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* arrayToBignumSize sets |*out_size| to the size of the big-endian number
* contained in |source|. It returns true on success and sets an exception and
* returns false otherwise.
*/
static bool arrayToBignumSize(JNIEnv* env, jbyteArray source, size_t* out_size) {
JNI_TRACE("arrayToBignumSize(%p, %p)", source, out_size);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == NULL) {
JNI_TRACE("arrayToBignum(%p, %p) => NULL", source, out_size);
return false;
}
const uint8_t* tmp = reinterpret_cast<const uint8_t*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
if (tmpSize == 0) {
*out_size = 0;
return true;
}
if ((tmp[0] & 0x80) != 0) {
// Negative numbers are invalid.
jniThrowRuntimeException(env, "Negative number");
return false;
}
while (tmpSize > 0 && tmp[0] == 0) {
tmp++;
tmpSize--;
}
*out_size = tmpSize;
return true;
}
#endif
/**
* Converts an OpenSSL BIGNUM to a Java byte[] array in two's complement.
*/
static jbyteArray bignumToArray(JNIEnv* env, const BIGNUM* source, const char* sourceName) {
JNI_TRACE("bignumToArray(%p, %s)", source, sourceName);
if (source == NULL) {
jniThrowNullPointerException(env, sourceName);
return NULL;
}
size_t numBytes = BN_num_bytes(source) + 1;
jbyteArray javaBytes = env->NewByteArray(numBytes);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bignumToArray(%p, %s) => NULL", source, sourceName);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
if (BN_num_bytes(source) > 0 && BN_bn2bin(source, tmp + 1) <= 0) {
throwExceptionIfNecessary(env, "bignumToArray");
return NULL;
}
// Set the sign and convert to two's complement if necessary for the Java code.
if (BN_is_negative(source)) {
bool carry = true;
for (ssize_t i = numBytes - 1; i >= 0; i--) {
tmp[i] ^= 0xFF;
if (carry) {
carry = (++tmp[i]) == 0;
}
}
*tmp |= 0x80;
} else {
*tmp = 0x00;
}
JNI_TRACE("bignumToArray(%p, %s) => %p", source, sourceName, javaBytes);
return javaBytes;
}
/**
* Converts various OpenSSL ASN.1 types to a jbyteArray with DER-encoded data
* inside. The "i2d_func" function pointer is a function of the "i2d_<TYPE>"
* from the OpenSSL ASN.1 API.
*/
template<typename T>
jbyteArray ASN1ToByteArray(JNIEnv* env, T* obj, int (*i2d_func)(T*, unsigned char**)) {
if (obj == NULL) {
jniThrowNullPointerException(env, "ASN1 input == null");
JNI_TRACE("ASN1ToByteArray(%p) => null input", obj);
return NULL;
}
int derLen = i2d_func(obj, NULL);
if (derLen < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => measurement failed", obj);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => creating byte array failed", obj);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1ToByteArray(%p) => using byte array failed", obj);
return NULL;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
int ret = i2d_func(obj, &p);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => final conversion failed", obj);
return NULL;
}
JNI_TRACE("ASN1ToByteArray(%p) => success (%d bytes written)", obj, ret);
return byteArray.release();
}
template<typename T, T* (*d2i_func)(T**, const unsigned char**, long)>
T* ByteArrayToASN1(JNIEnv* env, jbyteArray byteArray) {
ScopedByteArrayRO bytes(env, byteArray);
if (bytes.get() == NULL) {
JNI_TRACE("ByteArrayToASN1(%p) => using byte array failed", byteArray);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
return d2i_func(NULL, &tmp, bytes.size());
}
/**
* Converts ASN.1 BIT STRING to a jbooleanArray.
*/
jbooleanArray ASN1BitStringToBooleanArray(JNIEnv* env, ASN1_BIT_STRING* bitStr) {
int size = bitStr->length * 8;
if (bitStr->flags & ASN1_STRING_FLAG_BITS_LEFT) {
size -= bitStr->flags & 0x07;
}
ScopedLocalRef<jbooleanArray> bitsRef(env, env->NewBooleanArray(size));
if (bitsRef.get() == NULL) {
return NULL;
}
ScopedBooleanArrayRW bitsArray(env, bitsRef.get());
for (int i = 0; i < static_cast<int>(bitsArray.size()); i++) {
bitsArray[i] = ASN1_BIT_STRING_get_bit(bitStr, i);
}
return bitsRef.release();
}
/**
* Safely clear SSL sessions and throw an error if there was something already
* in the error stack.
*/
static void safeSslClear(SSL* ssl) {
if (SSL_clear(ssl) != 1) {
freeOpenSslErrorState();
}
}
/**
* To avoid the round-trip to ASN.1 and back in X509_dup, we just up the reference count.
*/
static X509* X509_dup_nocopy(X509* x509) {
if (x509 == NULL) {
return NULL;
}
#if defined(OPENSSL_IS_BORINGSSL)
return X509_up_ref(x509);
#else
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509);
return x509;
#endif
}
/*
* Sets the read and write BIO for an SSL connection and removes it when it goes out of scope.
* We hang on to BIO with a JNI GlobalRef and we want to remove them as soon as possible.
*/
class ScopedSslBio {
public:
ScopedSslBio(SSL *ssl, BIO* rbio, BIO* wbio) : ssl_(ssl) {
SSL_set_bio(ssl_, rbio, wbio);
BIO_up_ref(rbio);
BIO_up_ref(wbio);
}
~ScopedSslBio() {
SSL_set_bio(ssl_, NULL, NULL);
}
private:
SSL* const ssl_;
};
/**
* Obtains the current thread's JNIEnv
*/
static JNIEnv* getJNIEnv() {
JNIEnv* env;
#ifdef ANDROID
if (gJavaVM->AttachCurrentThread(&env, NULL) < 0) {
#else
if (gJavaVM->AttachCurrentThread(reinterpret_cast<void**>(&env), NULL) < 0) {
#endif
ALOGE("Could not attach JavaVM to find current JNIEnv");
return NULL;
}
return env;
}
/**
* BIO for InputStream
*/
class BIO_Stream {
public:
BIO_Stream(jobject stream) :
mEof(false) {
JNIEnv* env = getJNIEnv();
mStream = env->NewGlobalRef(stream);
}
~BIO_Stream() {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(mStream);
}
bool isEof() const {
JNI_TRACE("isEof? %s", mEof ? "yes" : "no");
return mEof;
}
int flush() {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_Stream::flush called with pending exception");
return -1;
}
env->CallVoidMethod(mStream, outputStream_flushMethod);
if (env->ExceptionCheck()) {
return -1;
}
return 1;
}
protected:
jobject getStream() {
return mStream;
}
void setEof(bool eof) {
mEof = eof;
}
private:
jobject mStream;
bool mEof;
};
class BIO_InputStream : public BIO_Stream {
public:
BIO_InputStream(jobject stream, bool isFinite) :
BIO_Stream(stream),
isFinite_(isFinite) {
}
int read(char *buf, int len) {
return read_internal(buf, len, inputStream_readMethod);
}
int gets(char *buf, int len) {
if (len > PEM_LINE_LENGTH) {
len = PEM_LINE_LENGTH;
}
int read = read_internal(buf, len - 1, openSslInputStream_readLineMethod);
buf[read] = '\0';
JNI_TRACE("BIO::gets \"%s\"", buf);
return read;
}
bool isFinite() const {
return isFinite_;
}
private:
const bool isFinite_;
int read_internal(char *buf, int len, jmethodID method) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_InputStream::read could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_InputStream::read failed call to NewByteArray");
return -1;
}
jint read = env->CallIntMethod(getStream(), method, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_InputStream::read failed call to InputStream#read");
return -1;
}
/* Java uses -1 to indicate EOF condition. */
if (read == -1) {
setEof(true);
read = 0;
} else if (read > 0) {
env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast<jbyte*>(buf));
}
return read;
}
public:
/** Length of PEM-encoded line (64) plus CR plus NULL */
static const int PEM_LINE_LENGTH = 66;
};
class BIO_OutputStream : public BIO_Stream {
public:
BIO_OutputStream(jobject stream) :
BIO_Stream(stream) {
}
int write(const char *buf, int len) {
JNIEnv* env = getJNIEnv();
if (env == NULL) {
JNI_TRACE("BIO_OutputStream::write => could not get JNIEnv");
return -1;
}
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => called with pending exception");
return -1;
}
ScopedLocalRef<jbyteArray> javaBytes(env, env->NewByteArray(len));
if (javaBytes.get() == NULL) {
JNI_TRACE("BIO_OutputStream::write => failed call to NewByteArray");
return -1;
}
env->SetByteArrayRegion(javaBytes.get(), 0, len, reinterpret_cast<const jbyte*>(buf));
env->CallVoidMethod(getStream(), outputStream_writeMethod, javaBytes.get());
if (env->ExceptionCheck()) {
JNI_TRACE("BIO_OutputStream::write => failed call to OutputStream#write");
return -1;
}
return len;
}
};
static int bio_stream_create(BIO *b) {
b->init = 1;
b->num = 0;
b->ptr = NULL;
b->flags = 0;
return 1;
}
static int bio_stream_destroy(BIO *b) {
if (b == NULL) {
return 0;
}
if (b->ptr != NULL) {
delete static_cast<BIO_Stream*>(b->ptr);
b->ptr = NULL;
}
b->init = 0;
b->flags = 0;
return 1;
}
static int bio_stream_read(BIO *b, char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
int ret = stream->read(buf, len);
if (ret == 0) {
if (stream->isFinite()) {
return 0;
}
// If the BIO_InputStream is not finite then EOF doesn't mean that
// there's nothing more coming.
BIO_set_retry_read(b);
return -1;
}
return ret;
}
static int bio_stream_write(BIO *b, const char *buf, int len) {
BIO_clear_retry_flags(b);
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, len);
}
static int bio_stream_puts(BIO *b, const char *buf) {
BIO_OutputStream* stream = static_cast<BIO_OutputStream*>(b->ptr);
return stream->write(buf, strlen(buf));
}
static int bio_stream_gets(BIO *b, char *buf, int len) {
BIO_InputStream* stream = static_cast<BIO_InputStream*>(b->ptr);
return stream->gets(buf, len);
}
static void bio_stream_assign(BIO *b, BIO_Stream* stream) {
b->ptr = static_cast<void*>(stream);
}
static long bio_stream_ctrl(BIO *b, int cmd, long, void *) {
BIO_Stream* stream = static_cast<BIO_Stream*>(b->ptr);
switch (cmd) {
case BIO_CTRL_EOF:
return stream->isEof() ? 1 : 0;
case BIO_CTRL_FLUSH:
return stream->flush();
default:
return 0;
}
}
static BIO_METHOD stream_bio_method = {
( 100 | 0x0400 ), /* source/sink BIO */
"InputStream/OutputStream BIO",
bio_stream_write, /* bio_write */
bio_stream_read, /* bio_read */
bio_stream_puts, /* bio_puts */
bio_stream_gets, /* bio_gets */
bio_stream_ctrl, /* bio_ctrl */
bio_stream_create, /* bio_create */
bio_stream_destroy, /* bio_free */
NULL, /* no bio_callback_ctrl */
};
static jbyteArray rawSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey,
const char* message, size_t message_len) {
ScopedLocalRef<jbyteArray> messageArray(env, env->NewByteArray(message_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW messageBytes(env, messageArray.get());
if (messageBytes.get() == NULL) {
JNI_TRACE("rawSignDigestWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(messageBytes.get(), message, message_len);
}
jmethodID rawSignMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rawSignDigestWithPrivateKey", "(Ljava/security/PrivateKey;[B)[B");
if (rawSignMethod == NULL) {
ALOGE("Could not find rawSignDigestWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass, rawSignMethod, privateKey, messageArray.get()));
}
// rsaDecryptWithPrivateKey uses privateKey to decrypt |ciphertext_len| bytes
// from |ciphertext|. The ciphertext is expected to be padded using the scheme
// given in |padding|, which must be one of |RSA_*_PADDING| constants from
// OpenSSL.
static jbyteArray rsaDecryptWithPrivateKey(JNIEnv* env, jobject privateKey, jint padding,
const char* ciphertext, size_t ciphertext_len) {
ScopedLocalRef<jbyteArray> ciphertextArray(env, env->NewByteArray(ciphertext_len));
if (env->ExceptionCheck()) {
JNI_TRACE("rsaDecryptWithPrivateKey(%p) => threw exception", privateKey);
return NULL;
}
{
ScopedByteArrayRW ciphertextBytes(env, ciphertextArray.get());
if (ciphertextBytes.get() == NULL) {
JNI_TRACE("rsaDecryptWithPrivateKey(%p) => using byte array failed", privateKey);
return NULL;
}
memcpy(ciphertextBytes.get(), ciphertext, ciphertext_len);
}
jmethodID rsaDecryptMethod = env->GetStaticMethodID(cryptoUpcallsClass,
"rsaDecryptWithPrivateKey", "(Ljava/security/PrivateKey;I[B)[B");
if (rsaDecryptMethod == NULL) {
ALOGE("Could not find rsaDecryptWithPrivateKey");
return NULL;
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
cryptoUpcallsClass,
rsaDecryptMethod,
privateKey,
padding,
ciphertextArray.get()));
}
// *********************************************
// From keystore_openssl.cpp in Chromium source.
// *********************************************
#if !defined(OPENSSL_IS_BORINGSSL)
// Custom RSA_METHOD that uses the platform APIs.
// Note that for now, only signing through RSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
// See <openssl/rsa.h> for exact declaration of RSA_METHOD.
int RsaMethodPubEnc(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
int RsaMethodPubDec(int /* flen */,
const unsigned char* /* from */,
unsigned char* /* to */,
RSA* /* rsa */,
int /* padding */) {
RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
return -1;
}
// See RSA_eay_private_encrypt in
// third_party/openssl/openssl/crypto/rsa/rsa_eay.c for the default
// implementation of this function.
int RsaMethodPrivEnc(int flen,
const unsigned char *from,
unsigned char *to,
RSA *rsa,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
return -1;
}
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// For RSA keys, this function behaves as RSA_private_encrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(from), flen));
if (signature.get() == NULL) {
ALOGE("Could not sign message in RsaMethodPrivEnc!");
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (signatureBytes.size() > expected_size) {
ALOGE("RSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer. rawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - signatureBytes.size();
memset(to, 0, zero_pad);
memcpy(to + zero_pad, signatureBytes.get(), signatureBytes.size());
return expected_size;
}
int RsaMethodPrivDec(int flen,
const unsigned char* from,
unsigned char* to,
RSA* rsa,
int padding) {
// Retrieve private key JNI reference.
jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (!private_key) {
ALOGE("Null JNI reference passed to RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return -1;
}
// This function behaves as RSA_private_decrypt.
ScopedLocalRef<jbyteArray> cleartext(env, rsaDecryptWithPrivateKey(env, private_key,
padding, reinterpret_cast<const char*>(from), flen));
if (cleartext.get() == NULL) {
ALOGE("Could not decrypt message in RsaMethodPrivDec!");
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
ScopedByteArrayRO cleartextBytes(env, cleartext.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (cleartextBytes.size() > expected_size) {
ALOGE("RSA ciphertext size mismatch, actual: %zd, expected <= %zd", cleartextBytes.size(),
expected_size);
RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
return -1;
}
// Copy result to OpenSSL-provided buffer.
memcpy(to, cleartextBytes.get(), cleartextBytes.size());
return cleartextBytes.size();
}
int RsaMethodInit(RSA*) {
return 0;
}
int RsaMethodFinish(RSA* rsa) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
jobject key = reinterpret_cast<jobject>(RSA_get_app_data(rsa));
if (key != NULL) {
RSA_set_app_data(rsa, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(key);
}
// Actual return value is ignored by OpenSSL. There are no docs
// explaining what this is supposed to be.
return 0;
}
const RSA_METHOD android_rsa_method = {
/* .name = */ "Android signing-only RSA method",
/* .rsa_pub_enc = */ RsaMethodPubEnc,
/* .rsa_pub_dec = */ RsaMethodPubDec,
/* .rsa_priv_enc = */ RsaMethodPrivEnc,
/* .rsa_priv_dec = */ RsaMethodPrivDec,
/* .rsa_mod_exp = */ NULL,
/* .bn_mod_exp = */ NULL,
/* .init = */ RsaMethodInit,
/* .finish = */ RsaMethodFinish,
// This flag is necessary to tell OpenSSL to avoid checking the content
// (i.e. internal fields) of the private key. Otherwise, it will complain
// it's not valid for the certificate.
/* .flags = */ RSA_METHOD_FLAG_NO_CHECK,
/* .app_data = */ NULL,
/* .rsa_sign = */ NULL,
/* .rsa_verify = */ NULL,
/* .rsa_keygen = */ NULL,
};
// Used to ensure that the global JNI reference associated with a custom
// EC_KEY + ECDSA_METHOD wrapper is released when its EX_DATA is destroyed
// (this function is called when EVP_PKEY_free() is called on the wrapper).
void ExDataFree(void* /* parent */,
void* ptr,
CRYPTO_EX_DATA* ad,
int idx,
long /* argl */,
#if defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL)
const void* /* argp */) {
#else /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
void* /* argp */) {
#endif /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
jobject private_key = reinterpret_cast<jobject>(ptr);
if (private_key == NULL) return;
CRYPTO_set_ex_data(ad, idx, NULL);
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(private_key);
}
int ExDataDup(CRYPTO_EX_DATA* /* to */,
CRYPTO_EX_DATA* /* from */,
void* /* from_d */,
int /* idx */,
long /* argl */,
#if defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL)
const void* /* argp */) {
#else /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
void* /* argp */) {
#endif /* defined(OPENSSL_IS_BORINGSSL) || defined(GOOGLE_INTERNAL) */
// This callback shall never be called with the current OpenSSL
// implementation (the library only ever duplicates EX_DATA items
// for SSL and BIO objects). But provide this to catch regressions
// in the future.
// Return value is currently ignored by OpenSSL.
return 0;
}
class EcdsaExDataIndex {
public:
int ex_data_index() { return ex_data_index_; }
static EcdsaExDataIndex& Instance() {
static EcdsaExDataIndex singleton;
return singleton;
}
private:
EcdsaExDataIndex() {
ex_data_index_ = ECDSA_get_ex_new_index(0, NULL, NULL, ExDataDup, ExDataFree);
}
EcdsaExDataIndex(EcdsaExDataIndex const&);
~EcdsaExDataIndex() {}
EcdsaExDataIndex& operator=(EcdsaExDataIndex const&);
int ex_data_index_;
};
// Returns the index of the custom EX_DATA used to store the JNI reference.
int EcdsaGetExDataIndex(void) {
EcdsaExDataIndex& exData = EcdsaExDataIndex::Instance();
return exData.ex_data_index();
}
ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst, int dgst_len, const BIGNUM* /* inv */,
const BIGNUM* /* rp */, EC_KEY* eckey) {
// Retrieve private key JNI reference.
jobject private_key =
reinterpret_cast<jobject>(ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex()));
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodDoSign!");
return NULL;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return NULL;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key, reinterpret_cast<const char*>(dgst),
dgst_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return NULL;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey));
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd", signatureBytes.size(),
max_expected_size);
return NULL;
}
// Convert signature to ECDSA_SIG object
const unsigned char* sigbuf = reinterpret_cast<const unsigned char*>(signatureBytes.get());
long siglen = static_cast<long>(signatureBytes.size());
return d2i_ECDSA_SIG(NULL, &sigbuf, siglen);
}
int EcdsaMethodSignSetup(EC_KEY* /* eckey */,
BN_CTX* /* ctx */,
BIGNUM** /* kinv */,
BIGNUM** /* r */,
const unsigned char*,
int) {
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB);
return -1;
}
int EcdsaMethodDoVerify(const unsigned char* /* dgst */,
int /* dgst_len */,
const ECDSA_SIG* /* sig */,
EC_KEY* /* eckey */) {
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB);
return -1;
}
const ECDSA_METHOD android_ecdsa_method = {
/* .name = */ "Android signing-only ECDSA method",
/* .ecdsa_do_sign = */ EcdsaMethodDoSign,
/* .ecdsa_sign_setup = */ EcdsaMethodSignSetup,
/* .ecdsa_do_verify = */ EcdsaMethodDoVerify,
/* .flags = */ 0,
/* .app_data = */ NULL,
};
#else /* OPENSSL_IS_BORINGSSL */
namespace {
ENGINE *g_engine;
int g_rsa_exdata_index;
int g_ecdsa_exdata_index;
pthread_once_t g_engine_once = PTHREAD_ONCE_INIT;
void init_engine_globals();
void ensure_engine_globals() {
pthread_once(&g_engine_once, init_engine_globals);
}
// KeyExData contains the data that is contained in the EX_DATA of the RSA
// and ECDSA objects that are created to wrap Android system keys.
struct KeyExData {
// private_key contains a reference to a Java, private-key object.
jobject private_key;
// cached_size contains the "size" of the key. This is the size of the
// modulus (in bytes) for RSA, or the group order size for ECDSA. This
// avoids calling into Java to calculate the size.
size_t cached_size;
};
// ExDataDup is called when one of the RSA or EC_KEY objects is duplicated. We
// don't support this and it should never happen.
int ExDataDup(CRYPTO_EX_DATA* /* to */,
const CRYPTO_EX_DATA* /* from */,
void** /* from_d */,
int /* index */,
long /* argl */,
void* /* argp */) {
return 0;
}
// ExDataFree is called when one of the RSA or EC_KEY objects is freed.
void ExDataFree(void* /* parent */,
void* ptr,
CRYPTO_EX_DATA* /* ad */,
int /* index */,
long /* argl */,
void* /* argp */) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
KeyExData *ex_data = reinterpret_cast<KeyExData*>(ptr);
if (ex_data != NULL) {
JNIEnv* env = getJNIEnv();
env->DeleteGlobalRef(ex_data->private_key);
delete ex_data;
}
}
KeyExData* RsaGetExData(const RSA* rsa) {
return reinterpret_cast<KeyExData*>(RSA_get_ex_data(rsa, g_rsa_exdata_index));
}
size_t RsaMethodSize(const RSA *rsa) {
const KeyExData *ex_data = RsaGetExData(rsa);
return ex_data->cached_size;
}
int RsaMethodEncrypt(RSA* /* rsa */,
size_t* /* out_len */,
uint8_t* /* out */,
size_t /* max_out */,
const uint8_t* /* in */,
size_t /* in_len */,
int /* padding */) {
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
int RsaMethodSignRaw(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
if (padding != RSA_PKCS1_PADDING) {
// TODO(davidben): If we need to, we can implement RSA_NO_PADDING
// by using javax.crypto.Cipher and picking either the
// "RSA/ECB/NoPadding" or "RSA/ECB/PKCS1Padding" transformation as
// appropriate. I believe support for both of these was added in
// the same Android version as the "NONEwithRSA"
// java.security.Signature algorithm, so the same version checks
// for GetRsaLegacyKey should work.
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
return 0;
}
// Retrieve private key JNI reference.
const KeyExData *ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
// For RSA keys, this function behaves as RSA_private_encrypt with
// PKCS#1 padding.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(
env, ex_data->private_key,
reinterpret_cast<const char*>(in), in_len));
if (signature.get() == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO result(env, signature.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (result.size() > expected_size) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
if (max_out < expected_size) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer. RawSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - result.size();
memset(out, 0, zero_pad);
memcpy(out + zero_pad, &result[0], result.size());
*out_len = expected_size;
return 1;
}
int RsaMethodDecrypt(RSA* rsa,
size_t* out_len,
uint8_t* out,
size_t max_out,
const uint8_t* in,
size_t in_len,
int padding) {
// Retrieve private key JNI reference.
const KeyExData *ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
// This function behaves as RSA_private_decrypt.
ScopedLocalRef<jbyteArray> cleartext(
env, rsaDecryptWithPrivateKey(
env, ex_data->private_key, padding,
reinterpret_cast<const char*>(in), in_len));
if (cleartext.get() == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO cleartextBytes(env, cleartext.get());
if (max_out < cleartextBytes.size()) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer.
memcpy(out, cleartextBytes.get(), cleartextBytes.size());
*out_len = cleartextBytes.size();
return 1;
}
int RsaMethodVerifyRaw(RSA* /* rsa */,
size_t* /* out_len */,
uint8_t* /* out */,
size_t /* max_out */,
const uint8_t* /* in */,
size_t /* in_len */,
int /* padding */) {
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
const RSA_METHOD android_rsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
RsaMethodSize,
NULL /* sign */,
NULL /* verify */,
RsaMethodEncrypt,
RsaMethodSignRaw,
RsaMethodDecrypt,
RsaMethodVerifyRaw,
NULL /* mod_exp */,
NULL /* bn_mod_exp */,
NULL /* private_transform */,
RSA_FLAG_OPAQUE,
NULL /* keygen */,
NULL /* multi_prime_keygen */,
NULL /* supports_digest */,
};
// Custom ECDSA_METHOD that uses the platform APIs.
// Note that for now, only signing through ECDSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
jobject EcKeyGetKey(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->private_key;
}
size_t EcdsaMethodGroupOrderSize(const EC_KEY* ec_key) {
KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
ec_key, g_ecdsa_exdata_index));
return ex_data->cached_size;
}
int EcdsaMethodSign(const uint8_t* digest,
size_t digest_len,
uint8_t* sig,
unsigned int* sig_len,
EC_KEY* ec_key) {
// Retrieve private key JNI reference.
jobject private_key = EcKeyGetKey(ec_key);
if (!private_key) {
ALOGE("Null JNI reference passed to EcdsaMethodSign!");
return 0;
}
JNIEnv* env = getJNIEnv();
if (env == NULL) {
return 0;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, rawSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(digest),
digest_len));
if (signature.get() == NULL) {
ALOGE("Could not sign message in EcdsaMethodDoSign!");
return 0;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = ECDSA_size(ec_key);
if (signatureBytes.size() > max_expected_size) {
ALOGE("ECDSA Signature size mismatch, actual: %zd, expected <= %zd",
signatureBytes.size(), max_expected_size);
return 0;
}
memcpy(sig, signatureBytes.get(), signatureBytes.size());
*sig_len = signatureBytes.size();
return 1;
}
int EcdsaMethodVerify(const uint8_t* /* digest */,
size_t /* digest_len */,
const uint8_t* /* sig */,
size_t /* sig_len */,
EC_KEY* /* ec_key */) {
OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NOT_IMPLEMENTED);
return 0;
}
const ECDSA_METHOD android_ecdsa_method = {
{
0 /* references */,
1 /* is_static */
} /* common */,
NULL /* app_data */,
NULL /* init */,
NULL /* finish */,
EcdsaMethodGroupOrderSize,
EcdsaMethodSign,
EcdsaMethodVerify,
ECDSA_FLAG_OPAQUE,
};
void init_engine_globals() {
g_rsa_exdata_index =
RSA_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
ExDataDup, ExDataFree);
g_ecdsa_exdata_index =
EC_KEY_get_ex_new_index(0 /* argl */, NULL /* argp */,
NULL /* new_func */, ExDataDup, ExDataFree);
g_engine = ENGINE_new();
ENGINE_set_RSA_method(g_engine, &android_rsa_method,
sizeof(android_rsa_method));
ENGINE_set_ECDSA_method(g_engine, &android_ecdsa_method,
sizeof(android_ecdsa_method));
}
} // anonymous namespace
#endif
#ifdef CONSCRYPT_UNBUNDLED
/*
* This is a big hack; don't learn from this. Basically what happened is we do
* not have an API way to insert ourselves into the AsynchronousCloseMonitor
* that's compiled into the native libraries for libcore when we're unbundled.
* So we try to look up the symbol from the main library to find it.
*/
typedef void (*acm_ctor_func)(void*, int);
typedef void (*acm_dtor_func)(void*);
static acm_ctor_func async_close_monitor_ctor = NULL;
static acm_dtor_func async_close_monitor_dtor = NULL;
class CompatibilityCloseMonitor {
public:
CompatibilityCloseMonitor(int fd) {
if (async_close_monitor_ctor != NULL) {
async_close_monitor_ctor(objBuffer, fd);
}
}
~CompatibilityCloseMonitor() {
if (async_close_monitor_dtor != NULL) {
async_close_monitor_dtor(objBuffer);
}
}
private:
char objBuffer[256];
#if 0
static_assert(sizeof(objBuffer) > 2*sizeof(AsynchronousCloseMonitor),
"CompatibilityCloseMonitor must be larger than the actual object");
#endif
};
static void findAsynchronousCloseMonitorFuncs() {
void *lib = dlopen("libjavacore.so", RTLD_NOW);
if (lib != NULL) {
async_close_monitor_ctor = (acm_ctor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorC1Ei");
async_close_monitor_dtor = (acm_dtor_func) dlsym(lib, "_ZN24AsynchronousCloseMonitorD1Ev");
}
}
#endif
/**
* Copied from libnativehelper NetworkUtilites.cpp
*/
static bool setBlocking(int fd, bool blocking) {
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
return false;
}
if (!blocking) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
int rc = fcntl(fd, F_SETFL, flags);
return (rc != -1);
}
/**
* OpenSSL locking support. Taken from the O'Reilly book by Viega et al., but I
* suppose there are not many other ways to do this on a Linux system (modulo
* isomorphism).
*/
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#define THROW_SSLEXCEPTION (-2)
#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
#define THROWN_EXCEPTION (-4)
static MUTEX_TYPE* mutex_buf = NULL;
static void locking_function(int mode, int n, const char*, int) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(mutex_buf[n]);
} else {
MUTEX_UNLOCK(mutex_buf[n]);
}
}
static void threadid_callback(CRYPTO_THREADID *threadid) {
#if defined(__APPLE__)
uint64_t owner;
int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6
if (rc == 0) {
CRYPTO_THREADID_set_numeric(threadid, owner);
} else {
ALOGE("Error calling pthread_threadid_np");
}
#else
// bionic exposes gettid(), but glibc doesn't
CRYPTO_THREADID_set_numeric(threadid, syscall(__NR_gettid));
#endif
}
int THREAD_setup(void) {
mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
if (!mutex_buf) {
return 0;
}
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
MUTEX_SETUP(mutex_buf[i]);
}
CRYPTO_THREADID_set_callback(threadid_callback);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int THREAD_cleanup(void) {
if (!mutex_buf) {
return 0;
}
CRYPTO_THREADID_set_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks( ); i++) {
MUTEX_CLEANUP(mutex_buf[i]);
}
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
/**
* Initialization phase for every OpenSSL job: Loads the Error strings, the
* crypto algorithms and reset the OpenSSL library
*/
static jboolean NativeCrypto_clinit(JNIEnv*, jclass)
{
SSL_load_error_strings();
ERR_load_crypto_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
THREAD_setup();
#if !defined(OPENSSL_IS_BORINGSSL)
return JNI_FALSE;
#else
return JNI_TRUE;
#endif
}
static void NativeCrypto_ENGINE_load_dynamic(JNIEnv*, jclass) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("ENGINE_load_dynamic()");
ENGINE_load_dynamic();
#endif
}
#if !defined(OPENSSL_IS_BORINGSSL)
static jlong NativeCrypto_ENGINE_by_id(JNIEnv* env, jclass, jstring idJava) {
JNI_TRACE("ENGINE_by_id(%p)", idJava);
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
JNI_TRACE("ENGINE_by_id(%p) => id == null", idJava);
return 0;
}
JNI_TRACE("ENGINE_by_id(\"%s\")", id.c_str());
ENGINE* e = ENGINE_by_id(id.c_str());
if (e == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("ENGINE_by_id(\"%s\") => %p", id.c_str(), e);
return reinterpret_cast<uintptr_t>(e);
}
#else
static jlong NativeCrypto_ENGINE_by_id(JNIEnv*, jclass, jstring) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_add(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_add(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_add(e);
/*
* We tolerate errors, because the most likely error is that
* the ENGINE is already in the list.
*/
freeOpenSslErrorState();
JNI_TRACE("ENGINE_add(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_add(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_init(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_init(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_init(e);
JNI_TRACE("ENGINE_init(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_init(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_finish(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_finish(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_finish(e);
JNI_TRACE("ENGINE_finish(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_finish(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_free(JNIEnv* env, jclass, jlong engineRef) {
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_free(%p)", e);
if (e == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "engineRef == 0");
return 0;
}
int ret = ENGINE_free(e);
JNI_TRACE("ENGINE_free(%p) => %d", e, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_free(JNIEnv*, jclass, jlong) {
return 0;
}
#endif
#if defined(OPENSSL_IS_BORINGSSL)
extern "C" {
/* EVP_PKEY_from_keystore is from system/security/keystore-engine. */
extern EVP_PKEY* EVP_PKEY_from_keystore(const char *key_id);
}
#endif
static jlong NativeCrypto_ENGINE_load_private_key(JNIEnv* env, jclass, jlong engineRef,
jstring idJava) {
ScopedUtfChars id(env, idJava);
if (id.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "id == NULL");
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_load_private_key(%p, %p)", e, idJava);
Unique_EVP_PKEY pkey(ENGINE_load_private_key(e, id.c_str(), NULL, NULL));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key", throwInvalidKeyException);
return 0;
}
JNI_TRACE("ENGINE_load_private_key(%p, %p) => %p", e, idJava, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
#else
UNUSED_ARGUMENT(engineRef);
#if defined(NO_KEYSTORE_ENGINE)
jniThrowRuntimeException(env, "No keystore ENGINE support compiled in");
return 0;
#else
Unique_EVP_PKEY pkey(EVP_PKEY_from_keystore(id.c_str()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "ENGINE_load_private_key", throwInvalidKeyException);
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
#endif
#endif
}
#if !defined(OPENSSL_IS_BORINGSSL)
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong engineRef)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_get_id(%p)", e);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_get_id(%p) => engine == null", e);
return NULL;
}
const char *id = ENGINE_get_id(e);
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF(id));
JNI_TRACE("ENGINE_get_id(%p) => \"%s\"", e, id);
return idJava.release();
}
#else
static jstring NativeCrypto_ENGINE_get_id(JNIEnv* env, jclass, jlong)
{
ScopedLocalRef<jstring> idJava(env, env->NewStringUTF("keystore"));
return idJava.release();
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv* env, jclass, jlong engineRef,
jstring cmdJava, jstring argJava, jint cmd_optional)
{
ENGINE* e = reinterpret_cast<ENGINE*>(static_cast<uintptr_t>(engineRef));
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d)", e, cmdJava, argJava, cmd_optional);
if (e == NULL) {
jniThrowNullPointerException(env, "engine == null");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, %p, %p, %d) => engine == null", e, cmdJava, argJava,
cmd_optional);
return 0;
}
ScopedUtfChars cmdChars(env, cmdJava);
if (cmdChars.c_str() == NULL) {
return 0;
}
UniquePtr<ScopedUtfChars> arg;
const char* arg_c_str = NULL;
if (argJava != NULL) {
arg.reset(new ScopedUtfChars(env, argJava));
arg_c_str = arg->c_str();
if (arg_c_str == NULL) {
return 0;
}
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d)", e, cmdChars.c_str(), arg_c_str,
cmd_optional);
int ret = ENGINE_ctrl_cmd_string(e, cmdChars.c_str(), arg_c_str, cmd_optional);
if (ret != 1) {
throwExceptionIfNecessary(env, "ENGINE_ctrl_cmd_string");
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => threw error", e,
cmdChars.c_str(), arg_c_str, cmd_optional);
return 0;
}
JNI_TRACE("ENGINE_ctrl_cmd_string(%p, \"%s\", \"%s\", %d) => %d", e, cmdChars.c_str(),
arg_c_str, cmd_optional, ret);
return ret;
}
#else
static jint NativeCrypto_ENGINE_ctrl_cmd_string(JNIEnv*, jclass, jlong, jstring, jstring, jint)
{
return 0;
}
#endif
static jlong NativeCrypto_EVP_PKEY_new_DH(JNIEnv* env, jclass,
jbyteArray p, jbyteArray g,
jbyteArray pub_key, jbyteArray priv_key) {
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p)",
p, g, pub_key, priv_key);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
jniThrowRuntimeException(env, "DH_new failed");
return 0;
}
if (!arrayToBignum(env, p, &dh->p)) {
return 0;
}
if (!arrayToBignum(env, g, &dh->g)) {
return 0;
}
if (pub_key != NULL && !arrayToBignum(env, pub_key, &dh->pub_key)) {
return 0;
}
if (priv_key != NULL && !arrayToBignum(env, priv_key, &dh->priv_key)) {
return 0;
}
if (dh->p == NULL || dh->g == NULL
|| (pub_key != NULL && dh->pub_key == NULL)
|| (priv_key != NULL && dh->priv_key == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/* The public key can be recovered if the private key is available. */
if (dh->pub_key == NULL && dh->priv_key != NULL) {
if (!DH_generate_key(dh.get())) {
jniThrowRuntimeException(env, "EVP_PKEY_new_DH failed during pub_key generation");
return 0;
}
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_DH failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("EVP_PKEY_new_DH(p=%p, g=%p, pub_key=%p, priv_key=%p) => %p",
p, g, pub_key, priv_key, pkey.get());
return reinterpret_cast<jlong>(pkey.release());
}
/**
* private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
*/
static jlong NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass,
jbyteArray n, jbyteArray e, jbyteArray d,
jbyteArray p, jbyteArray q,
jbyteArray dmp1, jbyteArray dmq1,
jbyteArray iqmp) {
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p, dmp1=%p, dmq1=%p, iqmp=%p)",
n, e, d, p, q, dmp1, dmq1, iqmp);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_new failed");
return 0;
}
if (e == NULL && d == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "e == NULL && d == NULL");
JNI_TRACE("NativeCrypto_EVP_PKEY_new_RSA => e == NULL && d == NULL");
return 0;
}
if (!arrayToBignum(env, n, &rsa->n)) {
return 0;
}
if (e != NULL && !arrayToBignum(env, e, &rsa->e)) {
return 0;
}
if (d != NULL && !arrayToBignum(env, d, &rsa->d)) {
return 0;
}
if (p != NULL && !arrayToBignum(env, p, &rsa->p)) {
return 0;
}
if (q != NULL && !arrayToBignum(env, q, &rsa->q)) {
return 0;
}
if (dmp1 != NULL && !arrayToBignum(env, dmp1, &rsa->dmp1)) {
return 0;
}
if (dmq1 != NULL && !arrayToBignum(env, dmq1, &rsa->dmq1)) {
return 0;
}
if (iqmp != NULL && !arrayToBignum(env, iqmp, &rsa->iqmp)) {
return 0;
}
#ifdef WITH_JNI_TRACE
if (p != NULL && q != NULL) {
int check = RSA_check_key(rsa.get());
JNI_TRACE("EVP_PKEY_new_RSA(...) RSA_check_key returns %d", check);
}
#endif
if (rsa->n == NULL || (rsa->e == NULL && rsa->d == NULL)) {
jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/*
* If the private exponent is available, there is the potential to do signing
* operations. However, we can only do blinding if the public exponent is also
* available. Disable blinding if the public exponent isn't available.
*
* TODO[kroot]: We should try to recover the public exponent by trying
* some common ones such 3, 17, or 65537.
*/
if (rsa->d != NULL && rsa->e == NULL) {
JNI_TRACE("EVP_PKEY_new_RSA(...) disabling RSA blinding => %p", rsa.get());
rsa->flags |= RSA_FLAG_NO_BLINDING;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p dmp1=%p, dmq1=%p, iqmp=%p) => %p",
n, e, d, p, q, dmp1, dmq1, iqmp, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EVP_PKEY_new_EC_KEY(JNIEnv* env, jclass, jobject groupRef,
jobject pubkeyRef, jbyteArray keyJavaBytes) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p)", groupRef, pubkeyRef, keyJavaBytes);
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
if (group == NULL) {
return 0;
}
const EC_POINT* pubkey = pubkeyRef == NULL ? NULL :
fromContextObject<EC_POINT>(env, pubkeyRef);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) <- ptr", group, pubkey, keyJavaBytes);
Unique_BIGNUM key(NULL);
if (keyJavaBytes != NULL) {
BIGNUM* keyRef = NULL;
if (!arrayToBignum(env, keyJavaBytes, &keyRef)) {
return 0;
}
key.reset(keyRef);
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
jniThrowRuntimeException(env, "EC_KEY_new failed");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) > EC_KEY_set_group failed", group, pubkey,
keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (pubkey != NULL) {
if (EC_KEY_set_public_key(eckey.get(), pubkey) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_public_key");
return 0;
}
}
if (key.get() != NULL) {
if (EC_KEY_set_private_key(eckey.get(), key.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => EC_KEY_set_private_key failed", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
if (pubkey == NULL) {
Unique_EC_POINT calcPubkey(EC_POINT_new(group));
if (!EC_POINT_mul(group, calcPubkey.get(), key.get(), NULL, NULL, NULL)) {
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => can't calulate public key", group,
pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_set_private_key");
return 0;
}
EC_KEY_set_public_key(eckey.get(), calcPubkey.get());
}
}
if (!EC_KEY_check_key(eckey.get())) {
JNI_TRACE("EVP_KEY_new_EC_KEY(%p, %p, %p) => invalid key created", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EC_KEY_check_key");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
throwExceptionIfNecessary(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
JNI_TRACE("EVP_PKEY_new_EC(%p, %p, %p) => threw error", group, pubkey, keyJavaBytes);
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EVP_PKEY_new_EC_KEY(%p, %p, %p) => %p", group, pubkey, keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static int NativeCrypto_EVP_PKEY_type(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_type(%p)", pkey);
if (pkey == NULL) {
return -1;
}
int result = EVP_PKEY_type(pkey->type);
JNI_TRACE("EVP_PKEY_type(%p) => %d", pkey, result);
return result;
}
/**
* private static native int EVP_PKEY_size(int pkey);
*/
static int NativeCrypto_EVP_PKEY_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EVP_PKEY_size(%p)", pkey);
if (pkey == NULL) {
return -1;
}
int result = EVP_PKEY_size(pkey);
JNI_TRACE("EVP_PKEY_size(%p) => %d", pkey, result);
return result;
}
typedef int print_func(BIO*, const EVP_PKEY*, int, ASN1_PCTX*);
static jstring evp_print_func(JNIEnv* env, jobject pkeyRef, print_func* func,
const char* debug_name) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("%s(%p)", debug_name, pkey);
if (pkey == NULL) {
return NULL;
}
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
return NULL;
}
if (func(buffer.get(), pkey, 0, (ASN1_PCTX*) NULL) != 1) {
throwExceptionIfNecessary(env, debug_name);
return NULL;
}
// Null terminate this
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
jstring description = env->NewStringUTF(tmp);
JNI_TRACE("%s(%p) => \"%s\"", debug_name, pkey, tmp);
return description;
}
static jstring NativeCrypto_EVP_PKEY_print_public(JNIEnv* env, jclass, jobject pkeyRef) {
return evp_print_func(env, pkeyRef, EVP_PKEY_print_public, "EVP_PKEY_print_public");
}
static jstring NativeCrypto_EVP_PKEY_print_params(JNIEnv* env, jclass, jobject pkeyRef) {
return evp_print_func(env, pkeyRef, EVP_PKEY_print_params, "EVP_PKEY_print_params");
}
static void NativeCrypto_EVP_PKEY_free(JNIEnv*, jclass, jlong pkeyRef) {
EVP_PKEY* pkey = reinterpret_cast<EVP_PKEY*>(pkeyRef);
JNI_TRACE("EVP_PKEY_free(%p)", pkey);
if (pkey != NULL) {
EVP_PKEY_free(pkey);
}
}
static jint NativeCrypto_EVP_PKEY_cmp(JNIEnv* env, jclass, jobject pkey1Ref, jobject pkey2Ref) {
JNI_TRACE("EVP_PKEY_cmp(%p, %p)", pkey1Ref, pkey2Ref);
EVP_PKEY* pkey1 = fromContextObject<EVP_PKEY>(env, pkey1Ref);
if (pkey1 == NULL) {
JNI_TRACE("EVP_PKEY_cmp => pkey1 == NULL");
return 0;
}
EVP_PKEY* pkey2 = fromContextObject<EVP_PKEY>(env, pkey2Ref);
if (pkey2 == NULL) {
JNI_TRACE("EVP_PKEY_cmp => pkey2 == NULL");
return 0;
}
JNI_TRACE("EVP_PKEY_cmp(%p, %p) <- ptr", pkey1, pkey2);
int result = EVP_PKEY_cmp(pkey1, pkey2);
JNI_TRACE("EVP_PKEY_cmp(%p, %p) => %d", pkey1, pkey2, result);
return result;
}
/*
* static native byte[] i2d_PKCS8_PRIV_KEY_INFO(int, byte[])
*/
static jbyteArray NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PKCS8_PRIV_KEY_INFO(%p)", pkey);
if (pkey == NULL) {
return NULL;
}
Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "NativeCrypto_i2d_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("key=%p i2d_PKCS8_PRIV_KEY_INFO => error from key to PKCS8", pkey);
return NULL;
}
return ASN1ToByteArray<PKCS8_PRIV_KEY_INFO>(env, pkcs8.get(), i2d_PKCS8_PRIV_KEY_INFO);
}
/*
* static native int d2i_PKCS8_PRIV_KEY_INFO(byte[])
*/
static jlong NativeCrypto_d2i_PKCS8_PRIV_KEY_INFO(JNIEnv* env, jclass, jbyteArray keyJavaBytes) {
JNI_TRACE("d2i_PKCS8_PRIV_KEY_INFO(%p)", keyJavaBytes);
ScopedByteArrayRO bytes(env, keyJavaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => threw exception", keyJavaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &tmp, bytes.size()));
if (pkcs8.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from DER to PKCS8", keyJavaBytes);
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
if (pkey.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS8_PRIV_KEY_INFO");
JNI_TRACE("ssl=%p d2i_PKCS8_PRIV_KEY_INFO => error from PKCS8 to key", keyJavaBytes);
return 0;
}
JNI_TRACE("bytes=%p d2i_PKCS8_PRIV_KEY_INFO => %p", keyJavaBytes, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* static native byte[] i2d_PUBKEY(int)
*/
static jbyteArray NativeCrypto_i2d_PUBKEY(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("i2d_PUBKEY(%p)", pkey);
if (pkey == NULL) {
return NULL;
}
return ASN1ToByteArray<EVP_PKEY>(env, pkey, reinterpret_cast<int (*) (EVP_PKEY*, uint8_t **)>(i2d_PUBKEY));
}
/*
* static native int d2i_PUBKEY(byte[])
*/
static jlong NativeCrypto_d2i_PUBKEY(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("d2i_PUBKEY(%p)", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("d2i_PUBKEY(%p) => threw error", javaBytes);
return 0;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(bytes.get());
Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, bytes.size()));
if (pkey.get() == NULL) {
JNI_TRACE("bytes=%p d2i_PUBKEY => threw exception", javaBytes);
throwExceptionIfNecessary(env, "d2i_PUBKEY");
return 0;
}
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getRSAPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jbyteArray modulusBytes) {
JNI_TRACE("getRSAPrivateKeyWrapper(%p, %p)", javaKey, modulusBytes);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
RSA_set_method(rsa.get(), &android_rsa_method);
if (!arrayToBignum(env, modulusBytes, &rsa->n)) {
return 0;
}
RSA_set_app_data(rsa.get(), env->NewGlobalRef(javaKey));
#else
size_t cached_size;
if (!arrayToBignumSize(env, modulusBytes, &cached_size)) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
return 0;
}
ensure_engine_globals();
Unique_RSA rsa(RSA_new_method(g_engine));
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
ex_data->cached_size = cached_size;
RSA_set_ex_data(rsa.get(), g_rsa_exdata_index, ex_data);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getRSAPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getRSAPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "getRSAPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_getECPrivateKeyWrapper(JNIEnv* env, jclass, jobject javaKey,
jobject groupRef) {
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("getECPrivateKeyWrapper(%p, %p)", javaKey, group);
if (group == NULL) {
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_EC_KEY ecKey(EC_KEY_new());
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return 0;
}
EC_KEY_set_group(ecKey.get(), group);
ECDSA_set_method(ecKey.get(), &android_ecdsa_method);
ECDSA_set_ex_data(ecKey.get(), EcdsaGetExDataIndex(), env->NewGlobalRef(javaKey));
#else
ensure_engine_globals();
Unique_EC_KEY ecKey(EC_KEY_new_method(g_engine));
if (ecKey.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate EC key");
return 0;
}
KeyExData* ex_data = new KeyExData;
ex_data->private_key = env->NewGlobalRef(javaKey);
if (!EC_KEY_set_ex_data(ecKey.get(), g_ecdsa_exdata_index, ex_data)) {
env->DeleteGlobalRef(ex_data->private_key);
delete ex_data;
jniThrowRuntimeException(env, "EC_KEY_set_ex_data");
return 0;
}
BIGNUM order;
BN_init(&order);
if (!EC_GROUP_get_order(group, &order, NULL)) {
BN_free(&order);
jniThrowRuntimeException(env, "EC_GROUP_get_order failed");
return 0;
}
ex_data->cached_size = BN_num_bytes(&order);
BN_free(&order);
#endif
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("getECPrivateKeyWrapper failed");
jniThrowRuntimeException(env, "NativeCrypto_getECPrivateKeyWrapper failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), ecKey.get()) != 1) {
jniThrowRuntimeException(env, "getECPrivateKeyWrapper failed");
return 0;
}
OWNERSHIP_TRANSFERRED(ecKey);
return reinterpret_cast<uintptr_t>(pkey.release());
}
/*
* public static native int RSA_generate_key(int modulusBits, byte[] publicExponent);
*/
static jlong NativeCrypto_RSA_generate_key_ex(JNIEnv* env, jclass, jint modulusBits,
jbyteArray publicExponent) {
JNI_TRACE("RSA_generate_key_ex(%d, %p)", modulusBits, publicExponent);
BIGNUM* eRef = NULL;
if (!arrayToBignum(env, publicExponent, &eRef)) {
return 0;
}
Unique_BIGNUM e(eRef);
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate RSA key");
return 0;
}
if (RSA_generate_key_ex(rsa.get(), modulusBits, e.get(), NULL) < 0) {
throwExceptionIfNecessary(env, "RSA_generate_key_ex");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
jniThrowRuntimeException(env, "RSA_generate_key_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("RSA_generate_key_ex(n=%d, e=%p) => %p", modulusBits, publicExponent, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jint NativeCrypto_RSA_size(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("RSA_size(%p)", pkey);
if (pkey == NULL) {
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
jniThrowRuntimeException(env, "RSA_size failed");
return 0;
}
return static_cast<jint>(RSA_size(rsa.get()));
}
#if defined(BORINGSSL_201510)
typedef int RSACryptOperation(size_t flen, const unsigned char* from, unsigned char* to, RSA* rsa,
int padding);
#else
typedef int RSACryptOperation(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
int padding);
#endif
static jint RSA_crypt_operation(RSACryptOperation operation, const char* caller, JNIEnv* env,
jint flen, jbyteArray fromJavaBytes, jbyteArray toJavaBytes,
jobject pkeyRef, jint padding) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("%s(%d, %p, %p, %p)", caller, flen, fromJavaBytes, toJavaBytes, pkey);
if (pkey == NULL) {
return -1;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
return -1;
}
ScopedByteArrayRO from(env, fromJavaBytes);
if (from.get() == NULL) {
return -1;
}
ScopedByteArrayRW to(env, toJavaBytes);
if (to.get() == NULL) {
return -1;
}
int resultSize = operation(
#if defined(BORINGSSL_201510)
static_cast<size_t>(flen),
#else
static_cast<int>(flen),
#endif
reinterpret_cast<const unsigned char*>(from.get()),
reinterpret_cast<unsigned char*>(to.get()), rsa.get(), padding);
if (resultSize == -1) {
if (throwExceptionIfNecessary(env, caller)) {
JNI_TRACE("%s => threw error", caller);
} else {
throwBadPaddingException(env, caller);
JNI_TRACE("%s => threw padding exception", caller);
}
return -1;
}
JNI_TRACE("%s(%d, %p, %p, %p) => %d", caller, flen, fromJavaBytes, toJavaBytes, pkey,
resultSize);
return static_cast<jint>(resultSize);
}
static jint NativeCrypto_RSA_private_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_public_encrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_public_encrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
static jint NativeCrypto_RSA_private_decrypt(JNIEnv* env, jclass, jint flen,
jbyteArray fromJavaBytes, jbyteArray toJavaBytes, jobject pkeyRef, jint padding) {
return RSA_crypt_operation(RSA_private_decrypt, __FUNCTION__,
env, flen, fromJavaBytes, toJavaBytes, pkeyRef, padding);
}
/*
* public static native byte[][] get_RSA_public_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_public_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
return joa;
}
/*
* public static native byte[][] get_RSA_private_params(long);
*/
static jobjectArray NativeCrypto_get_RSA_private_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_RSA_public_params(%p)", pkey);
if (pkey == NULL) {
return 0;
}
Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
if (rsa.get() == NULL) {
throwExceptionIfNecessary(env, "get_RSA_public_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(8, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray n = bignumToArray(env, rsa->n, "n");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, n);
if (rsa->e != NULL) {
jbyteArray e = bignumToArray(env, rsa->e, "e");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, e);
}
if (rsa->d != NULL) {
jbyteArray d = bignumToArray(env, rsa->d, "d");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, d);
}
if (rsa->p != NULL) {
jbyteArray p = bignumToArray(env, rsa->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, p);
}
if (rsa->q != NULL) {
jbyteArray q = bignumToArray(env, rsa->q, "q");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 4, q);
}
if (rsa->dmp1 != NULL) {
jbyteArray dmp1 = bignumToArray(env, rsa->dmp1, "dmp1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 5, dmp1);
}
if (rsa->dmq1 != NULL) {
jbyteArray dmq1 = bignumToArray(env, rsa->dmq1, "dmq1");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 6, dmq1);
}
if (rsa->iqmp != NULL) {
jbyteArray iqmp = bignumToArray(env, rsa->iqmp, "iqmp");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 7, iqmp);
}
return joa;
}
static jlong NativeCrypto_DH_generate_parameters_ex(JNIEnv* env, jclass, jint primeBits, jlong generator) {
JNI_TRACE("DH_generate_parameters_ex(%d, %lld)", primeBits, (long long) generator);
Unique_DH dh(DH_new());
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowOutOfMemory(env, "Unable to allocate DH key");
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("DH_generate_parameters_ex generating parameters");
if (!DH_generate_parameters_ex(dh.get(), primeBits, generator, NULL)) {
JNI_TRACE("DH_generate_parameters_ex => param generation failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("DH_generate_parameters_ex failed");
jniThrowRuntimeException(env, "NativeCrypto_DH_generate_parameters_ex failed");
freeOpenSslErrorState();
return 0;
}
if (EVP_PKEY_assign_DH(pkey.get(), dh.get()) != 1) {
JNI_TRACE("DH_generate_parameters_ex failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_parameters_ex failed");
return 0;
}
OWNERSHIP_TRANSFERRED(dh);
JNI_TRACE("DH_generate_parameters_ex(n=%d, g=%lld) => %p", primeBits, (long long) generator,
pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static void NativeCrypto_DH_generate_key(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("DH_generate_key(%p)", pkey);
if (pkey == NULL) {
return;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "Unable to get DH key");
freeOpenSslErrorState();
}
if (!DH_generate_key(dh.get())) {
JNI_TRACE("DH_generate_key failed");
throwExceptionIfNecessary(env, "NativeCrypto_DH_generate_key failed");
}
}
static jobjectArray NativeCrypto_get_DH_params(JNIEnv* env, jclass, jobject pkeyRef) {
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("get_DH_params(%p)", pkey);
if (pkey == NULL) {
return NULL;
}
Unique_DH dh(EVP_PKEY_get1_DH(pkey));
if (dh.get() == NULL) {
throwExceptionIfNecessary(env, "get_DH_params failed");
return 0;
}
jobjectArray joa = env->NewObjectArray(4, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
if (dh->p != NULL) {
jbyteArray p = bignumToArray(env, dh->p, "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, p);
}
if (dh->g != NULL) {
jbyteArray g = bignumToArray(env, dh->g, "g");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, g);
}
if (dh->pub_key != NULL) {
jbyteArray pub_key = bignumToArray(env, dh->pub_key, "pub_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, pub_key);
}
if (dh->priv_key != NULL) {
jbyteArray priv_key = bignumToArray(env, dh->priv_key, "priv_key");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 3, priv_key);
}
return joa;
}
#define EC_CURVE_GFP 1
#define EC_CURVE_GF2M 2
/**
* Return group type or 0 if unknown group.
* EC_GROUP_GFP or EC_GROUP_GF2M
*/
#if !defined(OPENSSL_IS_BORINGSSL)
static int get_EC_GROUP_type(const EC_GROUP* group)
{
const int curve_nid = EC_METHOD_get_field_type(EC_GROUP_method_of(group));
if (curve_nid == NID_X9_62_prime_field) {
return EC_CURVE_GFP;
} else if (curve_nid == NID_X9_62_characteristic_two_field) {
return EC_CURVE_GF2M;
}
return 0;
}
#else
static int get_EC_GROUP_type(const EC_GROUP*)
{
return EC_CURVE_GFP;
}
#endif
static jlong NativeCrypto_EC_GROUP_new_by_curve_name(JNIEnv* env, jclass, jstring curveNameJava)
{
JNI_TRACE("EC_GROUP_new_by_curve_name(%p)", curveNameJava);
ScopedUtfChars curveName(env, curveNameJava);
if (curveName.c_str() == NULL) {
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s)", curveName.c_str());
int nid = OBJ_sn2nid(curveName.c_str());
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID name", curveName.c_str());
return 0;
}
EC_GROUP* group = EC_GROUP_new_by_curve_name(nid);
if (group == NULL) {
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => unknown NID %d", curveName.c_str(), nid);
freeOpenSslErrorState();
return 0;
}
JNI_TRACE("EC_GROUP_new_by_curve_name(%s) => %p", curveName.c_str(), group);
return reinterpret_cast<uintptr_t>(group);
}
static jlong NativeCrypto_EC_GROUP_new_arbitrary(
JNIEnv* env, jclass, jbyteArray pBytes, jbyteArray aBytes,
jbyteArray bBytes, jbyteArray xBytes, jbyteArray yBytes,
jbyteArray orderBytes, jint cofactorInt)
{
BIGNUM *p = NULL, *a = NULL, *b = NULL, *x = NULL, *y = NULL;
BIGNUM *order = NULL, *cofactor = NULL;
JNI_TRACE("EC_GROUP_new_arbitrary");
if (cofactorInt < 1) {
jniThrowException(env, "java/lang/IllegalArgumentException", "cofactor < 1");
return 0;
}
cofactor = BN_new();
if (cofactor == NULL) {
return 0;
}
int ok = 1;
if (!arrayToBignum(env, pBytes, &p) ||
!arrayToBignum(env, aBytes, &a) ||
!arrayToBignum(env, bBytes, &b) ||
!arrayToBignum(env, xBytes, &x) ||
!arrayToBignum(env, yBytes, &y) ||
!arrayToBignum(env, orderBytes, &order) ||
!BN_set_word(cofactor, cofactorInt)) {
ok = 0;
}
Unique_BIGNUM pStorage(p);
Unique_BIGNUM aStorage(a);
Unique_BIGNUM bStorage(b);
Unique_BIGNUM xStorage(x);
Unique_BIGNUM yStorage(y);
Unique_BIGNUM orderStorage(order);
Unique_BIGNUM cofactorStorage(cofactor);
if (!ok) {
return 0;
}
Unique_BN_CTX ctx(BN_CTX_new());
Unique_EC_GROUP group(EC_GROUP_new_curve_GFp(p, a, b, ctx.get()));
if (group.get() == NULL) {
JNI_TRACE("EC_GROUP_new_curve_GFp => NULL");
throwExceptionIfNecessary(env, "EC_GROUP_new_curve_GFp");
return 0;
}
Unique_EC_POINT generator(EC_POINT_new(group.get()));
if (generator.get() == NULL) {
JNI_TRACE("EC_POINT_new => NULL");
freeOpenSslErrorState();
return 0;
}
if (!EC_POINT_set_affine_coordinates_GFp(group.get(), generator.get(), x, y, ctx.get())) {
JNI_TRACE("EC_POINT_set_affine_coordinates_GFp => error");
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates_GFp");
return 0;
}
if (!EC_GROUP_set_generator(group.get(), generator.get(), order, cofactor)) {
JNI_TRACE("EC_GROUP_set_generator => error");
throwExceptionIfNecessary(env, "EC_GROUP_set_generator");
return 0;
}
JNI_TRACE("EC_GROUP_new_arbitrary => %p", group.get());
return reinterpret_cast<uintptr_t>(group.release());
}
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv* env, jclass, jobject groupRef,
jint flag)
{
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d)", group, flag);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_asn1_flag => group == NULL");
return;
}
EC_GROUP_set_asn1_flag(group, flag);
JNI_TRACE("EC_GROUP_set_asn1_flag(%p, %d) => success", group, flag);
}
#else
static void NativeCrypto_EC_GROUP_set_asn1_flag(JNIEnv*, jclass, jobject, jint)
{
}
#endif
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv* env, jclass,
jobject groupRef, jint form)
{
EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d)", group, form);
if (group == NULL) {
JNI_TRACE("EC_GROUP_set_point_conversion_form => group == NULL");
return;
}
EC_GROUP_set_point_conversion_form(group, static_cast<point_conversion_form_t>(form));
JNI_TRACE("EC_GROUP_set_point_conversion_form(%p, %d) => success", group, form);
}
#else
static void NativeCrypto_EC_GROUP_set_point_conversion_form(JNIEnv*, jclass, jobject, jint)
{
}
#endif
static jstring NativeCrypto_EC_GROUP_get_curve_name(JNIEnv* env, jclass, jobject groupRef) {
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve_name(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve_name => group == NULL");
return 0;
}
int nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
JNI_TRACE("EC_GROUP_get_curve_name(%p) => unnamed curve", group);
return NULL;
}
const char* shortName = OBJ_nid2sn(nid);
JNI_TRACE("EC_GROUP_get_curve_name(%p) => \"%s\"", group, shortName);
return env->NewStringUTF(shortName);
}
static jobjectArray NativeCrypto_EC_GROUP_get_curve(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_curve(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_get_curve => group == NULL");
return NULL;
}
Unique_BIGNUM p(BN_new());
Unique_BIGNUM a(BN_new());
Unique_BIGNUM b(BN_new());
if (get_EC_GROUP_type(group) != EC_CURVE_GFP) {
jniThrowRuntimeException(env, "invalid group");
return NULL;
}
int ret = EC_GROUP_get_curve_GFp(group, p.get(), a.get(), b.get(), (BN_CTX*) NULL);
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_GROUP_get_curve");
return NULL;
}
jobjectArray joa = env->NewObjectArray(3, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray pArray = bignumToArray(env, p.get(), "p");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, pArray);
jbyteArray aArray = bignumToArray(env, a.get(), "a");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, aArray);
jbyteArray bArray = bignumToArray(env, b.get(), "b");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 2, bArray);
JNI_TRACE("EC_GROUP_get_curve(%p) => %p", group, joa);
return joa;
}
static jbyteArray NativeCrypto_EC_GROUP_get_order(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_order(%p)", group);
if (group == NULL) {
return NULL;
}
Unique_BIGNUM order(BN_new());
if (order.get() == NULL) {
JNI_TRACE("EC_GROUP_get_order(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_order(group, order.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_order(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_order");
return NULL;
}
jbyteArray orderArray = bignumToArray(env, order.get(), "order");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_order(%p) => %p", group, orderArray);
return orderArray;
}
static jint NativeCrypto_EC_GROUP_get_degree(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_degree(%p)", group);
if (group == NULL) {
return 0;
}
jint degree = EC_GROUP_get_degree(group);
if (degree == 0) {
JNI_TRACE("EC_GROUP_get_degree(%p) => unsupported", group);
jniThrowRuntimeException(env, "not supported");
return 0;
}
JNI_TRACE("EC_GROUP_get_degree(%p) => %d", group, degree);
return degree;
}
static jbyteArray NativeCrypto_EC_GROUP_get_cofactor(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_cofactor(%p)", group);
if (group == NULL) {
return NULL;
}
Unique_BIGNUM cofactor(BN_new());
if (cofactor.get() == NULL) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => can't create BN", group);
jniThrowOutOfMemory(env, "BN_new");
return NULL;
}
if (EC_GROUP_get_cofactor(group, cofactor.get(), NULL) != 1) {
JNI_TRACE("EC_GROUP_get_cofactor(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_GROUP_get_cofactor");
return NULL;
}
jbyteArray cofactorArray = bignumToArray(env, cofactor.get(), "cofactor");
if (env->ExceptionCheck()) {
return NULL;
}
JNI_TRACE("EC_GROUP_get_cofactor(%p) => %p", group, cofactorArray);
return cofactorArray;
}
static jint NativeCrypto_get_EC_GROUP_type(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("get_EC_GROUP_type(%p)", group);
if (group == NULL) {
return 0;
}
int type = get_EC_GROUP_type(group);
if (type == 0) {
JNI_TRACE("get_EC_GROUP_type(%p) => curve type", group);
jniThrowRuntimeException(env, "unknown curve type");
} else {
JNI_TRACE("get_EC_GROUP_type(%p) => %d", group, type);
}
return type;
}
static void NativeCrypto_EC_GROUP_clear_free(JNIEnv* env, jclass, jlong groupRef)
{
EC_GROUP* group = reinterpret_cast<EC_GROUP*>(groupRef);
JNI_TRACE("EC_GROUP_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_GROUP_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_GROUP_free(group);
JNI_TRACE("EC_GROUP_clear_free(%p) => success", group);
}
static jlong NativeCrypto_EC_GROUP_get_generator(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_GROUP_get_generator(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_get_generator(%p) => group == null", group);
return 0;
}
const EC_POINT* generator = EC_GROUP_get0_generator(group);
Unique_EC_POINT dup(EC_POINT_dup(generator, group));
if (dup.get() == NULL) {
JNI_TRACE("EC_GROUP_get_generator(%p) => oom error", group);
jniThrowOutOfMemory(env, "unable to dupe generator");
return 0;
}
JNI_TRACE("EC_GROUP_get_generator(%p) => %p", group, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
static jlong NativeCrypto_EC_POINT_new(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_POINT_new(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_new(%p) => group == null", group);
return 0;
}
EC_POINT* point = EC_POINT_new(group);
if (point == NULL) {
jniThrowOutOfMemory(env, "Unable create an EC_POINT");
return 0;
}
return reinterpret_cast<uintptr_t>(point);
}
static void NativeCrypto_EC_POINT_clear_free(JNIEnv* env, jclass, jlong groupRef) {
EC_POINT* group = reinterpret_cast<EC_POINT*>(groupRef);
JNI_TRACE("EC_POINT_clear_free(%p)", group);
if (group == NULL) {
JNI_TRACE("EC_POINT_clear_free => group == NULL");
jniThrowNullPointerException(env, "group == NULL");
return;
}
EC_POINT_free(group);
JNI_TRACE("EC_POINT_clear_free(%p) => success", group);
}
static void NativeCrypto_EC_POINT_set_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef, jbyteArray xjavaBytes, jbyteArray yjavaBytes)
{
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p)", groupRef, pointRef, xjavaBytes,
yjavaBytes);
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
if (group == NULL) {
return;
}
EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
if (point == NULL) {
return;
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) <- ptr", group, point, xjavaBytes,
yjavaBytes);
BIGNUM* xRef = NULL;
if (!arrayToBignum(env, xjavaBytes, &xRef)) {
return;
}
Unique_BIGNUM x(xRef);
BIGNUM* yRef = NULL;
if (!arrayToBignum(env, yjavaBytes, &yRef)) {
return;
}
Unique_BIGNUM y(yRef);
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_set_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
#if !defined(OPENSSL_NO_EC2M)
case EC_CURVE_GF2M:
ret = EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), NULL);
break;
#endif
default:
jniThrowRuntimeException(env, "invalid curve type");
return;
}
if (ret != 1) {
throwExceptionIfNecessary(env, "EC_POINT_set_affine_coordinates");
}
JNI_TRACE("EC_POINT_set_affine_coordinates(%p, %p, %p, %p) => %d", group, point,
xjavaBytes, yjavaBytes, ret);
}
static jobjectArray NativeCrypto_EC_POINT_get_affine_coordinates(JNIEnv* env, jclass,
jobject groupRef, jobject pointRef)
{
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", groupRef, pointRef);
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
if (group == NULL) {
return NULL;
}
const EC_POINT* point = fromContextObject<EC_POINT>(env, pointRef);
if (point == NULL) {
return NULL;
}
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) <- ptr", group, point);
Unique_BIGNUM x(BN_new());
Unique_BIGNUM y(BN_new());
int ret;
switch (get_EC_GROUP_type(group)) {
case EC_CURVE_GFP:
ret = EC_POINT_get_affine_coordinates_GFp(group, point, x.get(), y.get(), NULL);
break;
default:
jniThrowRuntimeException(env, "invalid curve type");
return NULL;
}
if (ret != 1) {
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p)", group, point);
throwExceptionIfNecessary(env, "EC_POINT_get_affine_coordinates");
return NULL;
}
jobjectArray joa = env->NewObjectArray(2, byteArrayClass, NULL);
if (joa == NULL) {
return NULL;
}
jbyteArray xBytes = bignumToArray(env, x.get(), "x");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 0, xBytes);
jbyteArray yBytes = bignumToArray(env, y.get(), "y");
if (env->ExceptionCheck()) {
return NULL;
}
env->SetObjectArrayElement(joa, 1, yBytes);
JNI_TRACE("EC_POINT_get_affine_coordinates(%p, %p) => %p", group, point, joa);
return joa;
}
static jlong NativeCrypto_EC_KEY_generate_key(JNIEnv* env, jclass, jobject groupRef)
{
const EC_GROUP* group = fromContextObject<EC_GROUP>(env, groupRef);
JNI_TRACE("EC_KEY_generate_key(%p)", group);
if (group == NULL) {
return 0;
}
Unique_EC_KEY eckey(EC_KEY_new());
if (eckey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_new() oom", group);
jniThrowOutOfMemory(env, "Unable to create an EC_KEY");
return 0;
}
if (EC_KEY_set_group(eckey.get(), group) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_set_group error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
if (EC_KEY_generate_key(eckey.get()) != 1) {
JNI_TRACE("EC_KEY_generate_key(%p) => EC_KEY_generate_key error", group);
throwExceptionIfNecessary(env, "EC_KEY_set_group");
return 0;
}
Unique_EVP_PKEY pkey(EVP_PKEY_new());
if (pkey.get() == NULL) {
JNI_TRACE("EC_KEY_generate_key(%p) => threw error", group);
throwExceptionIfNecessary(env, "EC_KEY_generate_key");
return 0;
}
if (EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()) != 1) {
jniThrowRuntimeException(env, "EVP_PKEY_assign_EC_KEY failed");
return 0;
}
OWNERSHIP_TRANSFERRED(eckey);
JNI_TRACE("EC_KEY_generate_key(%p) => %p", group, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jlong NativeCrypto_EC_KEY_get1_group(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get1_group(%p)", pkey);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_get1_group(%p) => pkey == null", pkey);
return 0;
}
if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
jniThrowRuntimeException(env, "not EC key");
JNI_TRACE("EC_KEY_get1_group(%p) => not EC key (type == %d)", pkey,
EVP_PKEY_type(pkey->type));
return 0;
}
EC_GROUP* group = EC_GROUP_dup(EC_KEY_get0_group(pkey->pkey.ec));
JNI_TRACE("EC_KEY_get1_group(%p) => %p", pkey, group);
return reinterpret_cast<uintptr_t>(group);
}
static jbyteArray NativeCrypto_EC_KEY_get_private_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_private_key(%p)", pkey);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_get_private_key => pkey == NULL");
return NULL;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return NULL;
}
const BIGNUM *privkey = EC_KEY_get0_private_key(eckey.get());
jbyteArray privBytes = bignumToArray(env, privkey, "privkey");
if (env->ExceptionCheck()) {
JNI_TRACE("EC_KEY_get_private_key(%p) => threw error", pkey);
return NULL;
}
JNI_TRACE("EC_KEY_get_private_key(%p) => %p", pkey, privBytes);
return privBytes;
}
static jlong NativeCrypto_EC_KEY_get_public_key(JNIEnv* env, jclass, jobject pkeyRef)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_get_public_key(%p)", pkey);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_get_public_key => pkey == NULL");
return 0;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return 0;
}
Unique_EC_POINT dup(EC_POINT_dup(EC_KEY_get0_public_key(eckey.get()),
EC_KEY_get0_group(eckey.get())));
if (dup.get() == NULL) {
JNI_TRACE("EC_KEY_get_public_key(%p) => can't dup public key", pkey);
jniThrowRuntimeException(env, "EC_POINT_dup");
return 0;
}
JNI_TRACE("EC_KEY_get_public_key(%p) => %p", pkey, dup.get());
return reinterpret_cast<uintptr_t>(dup.release());
}
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv* env, jclass, jobject pkeyRef,
jboolean enabled)
{
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("EC_KEY_set_nonce_from_hash(%p, %d)", pkey, enabled ? 1 : 0);
if (pkey == NULL) {
JNI_TRACE("EC_KEY_set_nonce_from_hash => pkey == NULL");
return;
}
Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
if (eckey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY");
return;
}
EC_KEY_set_nonce_from_hash(eckey.get(), enabled ? 1 : 0);
}
#else
static void NativeCrypto_EC_KEY_set_nonce_from_hash(JNIEnv*, jclass, jobject, jboolean)
{
}
#endif
static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass,
jbyteArray outArray, jint outOffset, jobject pubkeyRef, jobject privkeyRef)
{
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p)", outArray, outOffset, pubkeyRef, privkeyRef);
EVP_PKEY* pubPkey = fromContextObject<EVP_PKEY>(env, pubkeyRef);
if (pubPkey == NULL) {
JNI_TRACE("ECDH_compute_key => pubPkey == NULL");
return -1;
}
EVP_PKEY* privPkey = fromContextObject<EVP_PKEY>(env, privkeyRef);
if (privPkey == NULL) {
JNI_TRACE("ECDH_compute_key => privPkey == NULL");
return -1;
}
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) <- ptr", outArray, outOffset, pubPkey, privPkey);
ScopedByteArrayRW out(env, outArray);
if (out.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p, %d, %p, %p) can't get output buffer",
outArray, outOffset, pubPkey, privPkey);
return -1;
}
if (ARRAY_OFFSET_INVALID(out, outOffset)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
if (pubPkey == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => pubPkey == null", pubPkey);
jniThrowNullPointerException(env, "pubPkey == null");
return -1;
}
Unique_EC_KEY pubkey(EVP_PKEY_get1_EC_KEY(pubPkey));
if (pubkey.get() == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public", throwInvalidKeyException);
return -1;
}
const EC_POINT* pubkeyPoint = EC_KEY_get0_public_key(pubkey.get());
if (pubkeyPoint == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key point", pubPkey);
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY public", throwInvalidKeyException);
return -1;
}
if (privPkey == NULL) {
JNI_TRACE("ECDH_compute_key(%p) => privKey == null", pubPkey);
jniThrowNullPointerException(env, "privPkey == null");
return -1;
}
Unique_EC_KEY privkey(EVP_PKEY_get1_EC_KEY(privPkey));
if (privkey.get() == NULL) {
throwExceptionIfNecessary(env, "EVP_PKEY_get1_EC_KEY private", throwInvalidKeyException);
return -1;
}
int outputLength = ECDH_compute_key(
&out[outOffset],
out.size() - outOffset,
pubkeyPoint,
privkey.get(),
NULL // No KDF
);
if (outputLength == -1) {
JNI_TRACE("ECDH_compute_key(%p) => outputLength = -1", pubPkey);
throwExceptionIfNecessary(env, "ECDH_compute_key", throwInvalidKeyException);
return -1;
}
JNI_TRACE("ECDH_compute_key(%p) => outputLength=%d", pubPkey, outputLength);
return outputLength;
}
static jlong NativeCrypto_EVP_MD_CTX_create(JNIEnv* env, jclass) {
JNI_TRACE_MD("EVP_MD_CTX_create()");
Unique_EVP_MD_CTX ctx(EVP_MD_CTX_create());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable create a EVP_MD_CTX");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_create() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static void NativeCrypto_EVP_MD_CTX_cleanup(JNIEnv* env, jclass, jobject ctxRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_cleanup(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_cleanup(ctx);
}
}
static void NativeCrypto_EVP_MD_CTX_destroy(JNIEnv*, jclass, jlong ctxRef) {
EVP_MD_CTX* ctx = reinterpret_cast<EVP_MD_CTX*>(ctxRef);
JNI_TRACE_MD("EVP_MD_CTX_destroy(%p)", ctx);
if (ctx != NULL) {
EVP_MD_CTX_destroy(ctx);
}
}
static jint NativeCrypto_EVP_MD_CTX_copy_ex(JNIEnv* env, jclass, jobject dstCtxRef,
jobject srcCtxRef) {
JNI_TRACE_MD("EVP_MD_CTX_copy_ex(%p. %p)", dstCtxRef, srcCtxRef);
EVP_MD_CTX* dst_ctx = fromContextObject<EVP_MD_CTX>(env, dstCtxRef);
if (dst_ctx == NULL) {
JNI_TRACE_MD("EVP_MD_CTX_copy_ex => dst_ctx == NULL");
return 0;
}
const EVP_MD_CTX* src_ctx = fromContextObject<EVP_MD_CTX>(env, srcCtxRef);
if (src_ctx == NULL) {
JNI_TRACE_MD("EVP_MD_CTX_copy_ex => src_ctx == NULL");
return 0;
}
JNI_TRACE_MD("EVP_MD_CTX_copy_ex(%p. %p) <- ptr", dst_ctx, src_ctx);
int result = EVP_MD_CTX_copy_ex(dst_ctx, src_ctx);
if (result == 0) {
jniThrowRuntimeException(env, "Unable to copy EVP_MD_CTX");
freeOpenSslErrorState();
}
JNI_TRACE_MD("EVP_MD_CTX_copy_ex(%p, %p) => %d", dst_ctx, src_ctx, result);
return result;
}
/*
* public static native int EVP_DigestFinal_ex(long, byte[], int)
*/
static jint NativeCrypto_EVP_DigestFinal_ex(JNIEnv* env, jclass, jobject ctxRef, jbyteArray hash,
jint offset) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, ctxRef);
JNI_TRACE_MD("EVP_DigestFinal_ex(%p, %p, %d)", ctx, hash, offset);
if (ctx == NULL) {
JNI_TRACE("EVP_DigestFinal_ex => ctx == NULL");
return -1;
} else if (hash == NULL) {
jniThrowNullPointerException(env, "hash == null");
return -1;
}
ScopedByteArrayRW hashBytes(env, hash);
if (hashBytes.get() == NULL) {
return -1;
}
unsigned int bytesWritten = -1;
int ok = EVP_DigestFinal_ex(ctx,
reinterpret_cast<unsigned char*>(hashBytes.get() + offset),
&bytesWritten);
if (ok == 0) {
throwExceptionIfNecessary(env, "EVP_DigestFinal_ex");
}
JNI_TRACE_MD("EVP_DigestFinal_ex(%p, %p, %d) => %d (%d)", ctx, hash, offset, bytesWritten, ok);
return bytesWritten;
}
static jint NativeCrypto_EVP_DigestInit_ex(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong evpMdRef) {
EVP_MD_CTX* ctx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const EVP_MD* evp_md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE_MD("EVP_DigestInit_ex(%p, %p)", ctx, evp_md);
if (ctx == NULL) {
JNI_TRACE("EVP_DigestInit_ex(%p) => ctx == NULL", evp_md);
return 0;
} else if (evp_md == NULL) {
jniThrowNullPointerException(env, "evp_md == null");
return 0;
}
int ok = EVP_DigestInit_ex(ctx, evp_md, NULL);
if (ok == 0) {
bool exception = throwExceptionIfNecessary(env, "EVP_DigestInit_ex");
if (exception) {
JNI_TRACE("EVP_DigestInit_ex(%p) => threw exception", evp_md);
return 0;
}
}
JNI_TRACE_MD("EVP_DigestInit_ex(%p, %p) => %d", ctx, evp_md, ok);
return ok;
}
/*
* public static native int EVP_get_digestbyname(java.lang.String)
*/
static jlong NativeCrypto_EVP_get_digestbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%p)", algorithm);
if (algorithm == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s)", algorithmChars.c_str());
#if !defined(OPENSSL_IS_BORINGSSL)
const EVP_MD* evp_md = EVP_get_digestbyname(algorithmChars.c_str());
if (evp_md == NULL) {
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => %p", algorithmChars.c_str(), evp_md);
return reinterpret_cast<uintptr_t>(evp_md);
#else
const char *alg = algorithmChars.c_str();
const EVP_MD *md;
if (strcasecmp(alg, "md4") == 0) {
md = EVP_md4();
} else if (strcasecmp(alg, "md5") == 0) {
md = EVP_md5();
} else if (strcasecmp(alg, "sha1") == 0) {
md = EVP_sha1();
} else if (strcasecmp(alg, "sha224") == 0) {
md = EVP_sha224();
} else if (strcasecmp(alg, "sha256") == 0) {
md = EVP_sha256();
} else if (strcasecmp(alg, "sha384") == 0) {
md = EVP_sha384();
} else if (strcasecmp(alg, "sha512") == 0) {
md = EVP_sha512();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
jniThrowRuntimeException(env, "Hash algorithm not found");
return 0;
}
return reinterpret_cast<uintptr_t>(md);
#endif
}
/*
* public static native int EVP_MD_size(long)
*/
static jint NativeCrypto_EVP_MD_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_size(%p) => %d", evp_md, result);
return result;
}
/*
* public static int void EVP_MD_block_size(long)
*/
static jint NativeCrypto_EVP_MD_block_size(JNIEnv* env, jclass, jlong evpMdRef) {
EVP_MD* evp_md = reinterpret_cast<EVP_MD*>(evpMdRef);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p)", evp_md);
if (evp_md == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
int result = EVP_MD_block_size(evp_md);
JNI_TRACE("NativeCrypto_EVP_MD_block_size(%p) => %d", evp_md, result);
return result;
}
static jlong evpDigestSignVerifyInit(
JNIEnv* env,
int (*init_func)(EVP_MD_CTX*, EVP_PKEY_CTX**, const EVP_MD*, ENGINE*, EVP_PKEY*),
const char* jniName,
jobject evpMdCtxRef, jlong evpMdRef, jobject pkeyRef) {
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
if (mdCtx == NULL) {
JNI_TRACE("%s => mdCtx == NULL", jniName);
return 0;
}
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
if (pkey == NULL) {
JNI_TRACE("ctx=%p $s => pkey == NULL", mdCtx, jniName);
return 0;
}
JNI_TRACE("%s(%p, %p, %p) <- ptr", jniName, mdCtx, md, pkey);
if (md == NULL) {
JNI_TRACE("ctx=%p %s => md == NULL", mdCtx, jniName);
jniThrowNullPointerException(env, "md == null");
return 0;
}
EVP_PKEY_CTX* pctx = NULL;
if (init_func(mdCtx, &pctx, md, (ENGINE *) NULL, pkey) <= 0) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
return 0;
}
JNI_TRACE("%s(%p, %p, %p) => success", jniName, mdCtx, md, pkey);
return reinterpret_cast<jlong>(pctx);
}
static jlong NativeCrypto_EVP_DigestSignInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jobject pkeyRef) {
return evpDigestSignVerifyInit(
env, EVP_DigestSignInit, "EVP_DigestSignInit", evpMdCtxRef, evpMdRef, pkeyRef);
}
static jlong NativeCrypto_EVP_DigestVerifyInit(JNIEnv* env, jclass, jobject evpMdCtxRef,
const jlong evpMdRef, jobject pkeyRef) {
return evpDigestSignVerifyInit(
env, EVP_DigestVerifyInit, "EVP_DigestVerifyInit", evpMdCtxRef, evpMdRef, pkeyRef);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jlong inPtr, jint inLength,
const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *, size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
const void *p = reinterpret_cast<const void *>(inPtr);
JNI_TRACE_MD("%s(%p, %p, %d)", jniName, mdCtx, p, inLength);
if (mdCtx == NULL) {
return;
}
if (p == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (!update_func(mdCtx, p, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d) => success", jniName, mdCtx, p, inLength);
}
static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jbyteArray inJavaBytes, jint inOffset,
jint inLength, const char *jniName, int (*update_func)(EVP_MD_CTX*, const void *,
size_t))
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE_MD("%s(%p, %p, %d, %d)", jniName, mdCtx, inJavaBytes, inOffset, inLength);
if (mdCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inJavaBytes);
if (inBytes.get() == NULL) {
return;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inBytes");
return;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char *>(inBytes.get());
if (!update_func(mdCtx, tmp + inOffset, inLength)) {
JNI_TRACE("ctx=%p %s => threw exception", mdCtx, jniName);
throwExceptionIfNecessary(env, jniName);
}
JNI_TRACE_MD("%s(%p, %p, %d, %d) => success", jniName, mdCtx, inJavaBytes, inOffset, inLength);
}
static void NativeCrypto_EVP_DigestUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong inPtr, jint inLength) {
evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestUpdateDirect", EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestUpdate",
EVP_DigestUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestSignUpdate",
EVP_DigestSignUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong inPtr, jint inLength) {
evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestSignUpdateDirect",
EVP_DigestSignUpdate);
}
static void NativeCrypto_EVP_DigestVerifyUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray inJavaBytes, jint inOffset, jint inLength) {
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestVerifyUpdate",
EVP_DigestVerifyUpdate);
}
static void NativeCrypto_EVP_DigestVerifyUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef,
jlong inPtr, jint inLength) {
evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestVerifyUpdateDirect",
EVP_DigestVerifyUpdate);
}
static jbyteArray NativeCrypto_EVP_DigestSignFinal(JNIEnv* env, jclass, jobject evpMdCtxRef)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestSignFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return NULL;
}
size_t maxLen;
if (EVP_DigestSignFinal(mdCtx, NULL, &maxLen) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return NULL;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[maxLen]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate signature buffer");
return 0;
}
size_t actualLen;
if (EVP_DigestSignFinal(mdCtx, buffer.get(), &actualLen) != 1) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal");
return NULL;
}
if (actualLen > maxLen) {
JNI_TRACE("ctx=%p EVP_DigestSignFinal => signature too long: %d vs %d",
actualLen, maxLen);
throwExceptionIfNecessary(env, "EVP_DigestSignFinal signature too long");
return NULL;
}
ScopedLocalRef<jbyteArray> sigJavaBytes(env, env->NewByteArray(actualLen));
if (sigJavaBytes.get() == NULL) {
jniThrowOutOfMemory(env, "Failed to allocate signature byte[]");
return NULL;
}
env->SetByteArrayRegion(
sigJavaBytes.get(), 0, actualLen, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("EVP_DigestSignFinal(%p) => %p", mdCtx, sigJavaBytes.get());
return sigJavaBytes.release();
}
static jboolean NativeCrypto_EVP_DigestVerifyFinal(JNIEnv* env, jclass, jobject evpMdCtxRef,
jbyteArray signature, jint offset, jint len)
{
EVP_MD_CTX* mdCtx = fromContextObject<EVP_MD_CTX>(env, evpMdCtxRef);
JNI_TRACE("EVP_DigestVerifyFinal(%p)", mdCtx);
if (mdCtx == NULL) {
return 0;
}
ScopedByteArrayRO sigBytes(env, signature);
if (sigBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(sigBytes, offset, len)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "signature");
return 0;
}
const unsigned char *sigBuf = reinterpret_cast<const unsigned char *>(sigBytes.get());
int err = EVP_DigestVerifyFinal(mdCtx, sigBuf + offset, len);
jboolean result;
if (err == 1) {
// Signature verified
result = 1;
} else if (err == 0) {
// Signature did not verify
result = 0;
} else {
// Error while verifying signature
JNI_TRACE("ctx=%p EVP_DigestVerifyFinal => threw exception", mdCtx);
throwExceptionIfNecessary(env, "EVP_DigestVerifyFinal");
return 0;
}
// If the signature did not verify, BoringSSL error queue contains an error (BAD_SIGNATURE).
// Clear the error queue to prevent its state from affecting future operations.
freeOpenSslErrorState();
JNI_TRACE("EVP_DigestVerifyFinal(%p) => %d", mdCtx, result);
return result;
}
static jlong NativeCrypto_EVP_get_cipherbyname(JNIEnv* env, jclass, jstring algorithm) {
JNI_TRACE("EVP_get_cipherbyname(%p)", algorithm);
#if !defined(OPENSSL_IS_BORINGSSL)
if (algorithm == NULL) {
JNI_TRACE("EVP_get_cipherbyname(%p) => threw exception algorithm == null", algorithm);
jniThrowNullPointerException(env, NULL);
return -1;
}
ScopedUtfChars algorithmChars(env, algorithm);
if (algorithmChars.c_str() == NULL) {
return 0;
}
JNI_TRACE("EVP_get_cipherbyname(%p) => algorithm = %s", algorithm, algorithmChars.c_str());
const EVP_CIPHER* evp_cipher = EVP_get_cipherbyname(algorithmChars.c_str());
if (evp_cipher == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("EVP_get_cipherbyname(%s) => %p", algorithmChars.c_str(), evp_cipher);
return reinterpret_cast<uintptr_t>(evp_cipher);
#else
ScopedUtfChars scoped_alg(env, algorithm);
const char *alg = scoped_alg.c_str();
const EVP_CIPHER *cipher;
if (strcasecmp(alg, "rc4") == 0) {
cipher = EVP_rc4();
} else if (strcasecmp(alg, "des-cbc") == 0) {
cipher = EVP_des_cbc();
} else if (strcasecmp(alg, "des-ede-cbc") == 0) {
cipher = EVP_des_cbc();
} else if (strcasecmp(alg, "des-ede3-cbc") == 0) {
cipher = EVP_des_ede3_cbc();
} else if (strcasecmp(alg, "aes-128-ecb") == 0) {
cipher = EVP_aes_128_ecb();
} else if (strcasecmp(alg, "aes-128-cbc") == 0) {
cipher = EVP_aes_128_cbc();
} else if (strcasecmp(alg, "aes-128-ctr") == 0) {
cipher = EVP_aes_128_ctr();
} else if (strcasecmp(alg, "aes-128-gcm") == 0) {
cipher = EVP_aes_128_gcm();
} else if (strcasecmp(alg, "aes-192-ecb") == 0) {
cipher = EVP_aes_192_ecb();
} else if (strcasecmp(alg, "aes-192-cbc") == 0) {
cipher = EVP_aes_192_cbc();
} else if (strcasecmp(alg, "aes-192-ctr") == 0) {
cipher = EVP_aes_192_ctr();
} else if (strcasecmp(alg, "aes-192-gcm") == 0) {
cipher = EVP_aes_192_gcm();
} else if (strcasecmp(alg, "aes-256-ecb") == 0) {
cipher = EVP_aes_256_ecb();
} else if (strcasecmp(alg, "aes-256-cbc") == 0) {
cipher = EVP_aes_256_cbc();
} else if (strcasecmp(alg, "aes-256-ctr") == 0) {
cipher = EVP_aes_256_ctr();
} else if (strcasecmp(alg, "aes-256-gcm") == 0) {
cipher = EVP_aes_256_gcm();
} else {
JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg);
return 0;
}
return reinterpret_cast<uintptr_t>(cipher);
#endif
}
static void NativeCrypto_EVP_CipherInit_ex(JNIEnv* env, jclass, jobject ctxRef, jlong evpCipherRef,
jbyteArray keyArray, jbyteArray ivArray, jboolean encrypting) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d)", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
if (ctx == NULL) {
JNI_TRACE("EVP_CipherUpdate => ctx == null");
return;
}
// The key can be null if we need to set extra parameters.
UniquePtr<unsigned char[]> keyPtr;
if (keyArray != NULL) {
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
keyPtr.reset(new unsigned char[keyBytes.size()]);
memcpy(keyPtr.get(), keyBytes.get(), keyBytes.size());
}
// The IV can be null if we're using ECB.
UniquePtr<unsigned char[]> ivPtr;
if (ivArray != NULL) {
ScopedByteArrayRO ivBytes(env, ivArray);
if (ivBytes.get() == NULL) {
return;
}
ivPtr.reset(new unsigned char[ivBytes.size()]);
memcpy(ivPtr.get(), ivBytes.get(), ivBytes.size());
}
if (!EVP_CipherInit_ex(ctx, evpCipher, NULL, keyPtr.get(), ivPtr.get(), encrypting ? 1 : 0)) {
throwExceptionIfNecessary(env, "EVP_CipherInit_ex");
JNI_TRACE("EVP_CipherInit_ex => error initializing cipher");
return;
}
JNI_TRACE("EVP_CipherInit_ex(%p, %p, %p, %p, %d) => success", ctx, evpCipher, keyArray, ivArray,
encrypting ? 1 : 0);
}
/*
* public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
* int inOffset, int inLength);
*/
static jint NativeCrypto_EVP_CipherUpdate(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray inArray, jint inOffset, jint inLength) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d)", ctx, outArray, outOffset, inArray, inOffset);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CipherUpdate => ctx == null", ctx);
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inBytes");
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(outBytes, outOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "outBytes");
return 0;
}
JNI_TRACE("ctx=%p EVP_CipherUpdate in=%p in.length=%zd inOffset=%zd inLength=%zd out=%p out.length=%zd outOffset=%zd",
ctx, inBytes.get(), inBytes.size(), inOffset, inLength, outBytes.get(), outBytes.size(), outOffset);
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
const unsigned char* in = reinterpret_cast<const unsigned char*>(inBytes.get());
int outl;
if (!EVP_CipherUpdate(ctx, out + outOffset, &outl, in + inOffset, inLength)) {
throwExceptionIfNecessary(env, "EVP_CipherUpdate");
JNI_TRACE("ctx=%p EVP_CipherUpdate => threw error", ctx);
return 0;
}
JNI_TRACE("EVP_CipherUpdate(%p, %p, %d, %p, %d) => %d", ctx, outArray, outOffset, inArray,
inOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CipherFinal_ex(JNIEnv* env, jclass, jobject ctxRef,
jbyteArray outArray, jint outOffset) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CipherFinal_ex(%p, %p, %d)", ctx, outArray, outOffset);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => ctx == null", ctx);
return 0;
}
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
unsigned char* out = reinterpret_cast<unsigned char*>(outBytes.get());
int outl;
if (!EVP_CipherFinal_ex(ctx, out + outOffset, &outl)) {
if (throwExceptionIfNecessary(env, "EVP_CipherFinal_ex")) {
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw error", ctx);
} else {
throwBadPaddingException(env, "EVP_CipherFinal_ex");
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw padding exception", ctx);
}
return 0;
}
JNI_TRACE("EVP_CipherFinal(%p, %p, %d) => %d", ctx, outArray, outOffset, outl);
return outl;
}
static jint NativeCrypto_EVP_CIPHER_iv_length(JNIEnv* env, jclass, jlong evpCipherRef) {
const EVP_CIPHER* evpCipher = reinterpret_cast<const EVP_CIPHER*>(evpCipherRef);
JNI_TRACE("EVP_CIPHER_iv_length(%p)", evpCipher);
if (evpCipher == NULL) {
jniThrowNullPointerException(env, "evpCipher == null");
JNI_TRACE("EVP_CIPHER_iv_length => evpCipher == null");
return 0;
}
const int ivLength = EVP_CIPHER_iv_length(evpCipher);
JNI_TRACE("EVP_CIPHER_iv_length(%p) => %d", evpCipher, ivLength);
return ivLength;
}
static jlong NativeCrypto_EVP_CIPHER_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("EVP_CIPHER_CTX_new()");
Unique_EVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate cipher context");
JNI_TRACE("EVP_CipherInit_ex => context allocation error");
return 0;
}
JNI_TRACE("EVP_CIPHER_CTX_new() => %p", ctx.get());
return reinterpret_cast<uintptr_t>(ctx.release());
}
static jint NativeCrypto_EVP_CIPHER_CTX_block_size(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p)", ctx);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_block_size => ctx == null", ctx);
return 0;
}
int blockSize = EVP_CIPHER_CTX_block_size(ctx);
JNI_TRACE("EVP_CIPHER_CTX_block_size(%p) => %d", ctx, blockSize);
return blockSize;
}
static jint NativeCrypto_get_EVP_CIPHER_CTX_buf_len(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p)", ctx);
if (ctx == NULL) {
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_buf_len => ctx == null", ctx);
return 0;
}
int buf_len = ctx->buf_len;
JNI_TRACE("get_EVP_CIPHER_CTX_buf_len(%p) => %d", ctx, buf_len);
return buf_len;
}
static jboolean NativeCrypto_get_EVP_CIPHER_CTX_final_used(JNIEnv* env, jclass, jobject ctxRef) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("get_EVP_CIPHER_CTX_final_used(%p)", ctx);
if (ctx == NULL) {
JNI_TRACE("ctx=%p get_EVP_CIPHER_CTX_final_used => ctx == null", ctx);
return 0;
}
bool final_used = ctx->final_used != 0;
JNI_TRACE("get_EVP_CIPHER_CTX_final_used(%p) => %d", ctx, final_used);
return final_used;
}
static void NativeCrypto_EVP_CIPHER_CTX_set_padding(JNIEnv* env, jclass, jobject ctxRef,
jboolean enablePaddingBool) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
jint enablePadding = enablePaddingBool ? 1 : 0;
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d)", ctx, enablePadding);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_padding => ctx == null", ctx);
return;
}
EVP_CIPHER_CTX_set_padding(ctx, enablePadding); // Not void, but always returns 1.
JNI_TRACE("EVP_CIPHER_CTX_set_padding(%p, %d) => success", ctx, enablePadding);
}
static void NativeCrypto_EVP_CIPHER_CTX_set_key_length(JNIEnv* env, jclass, jobject ctxRef,
jint keySizeBits) {
EVP_CIPHER_CTX* ctx = fromContextObject<EVP_CIPHER_CTX>(env, ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d)", ctx, keySizeBits);
if (ctx == NULL) {
JNI_TRACE("ctx=%p EVP_CIPHER_CTX_set_key_length => ctx == null", ctx);
return;
}
if (!EVP_CIPHER_CTX_set_key_length(ctx, keySizeBits)) {
throwExceptionIfNecessary(env, "NativeCrypto_EVP_CIPHER_CTX_set_key_length");
JNI_TRACE("NativeCrypto_EVP_CIPHER_CTX_set_key_length => threw error");
return;
}
JNI_TRACE("EVP_CIPHER_CTX_set_key_length(%p, %d) => success", ctx, keySizeBits);
}
static void NativeCrypto_EVP_CIPHER_CTX_free(JNIEnv*, jclass, jlong ctxRef) {
EVP_CIPHER_CTX* ctx = reinterpret_cast<EVP_CIPHER_CTX*>(ctxRef);
JNI_TRACE("EVP_CIPHER_CTX_free(%p)", ctx);
EVP_CIPHER_CTX_free(ctx);
}
static jlong NativeCrypto_EVP_aead_aes_128_gcm(JNIEnv* env, jclass) {
#if defined(OPENSSL_IS_BORINGSSL)
UNUSED_ARGUMENT(env);
const EVP_AEAD* ctx = EVP_aead_aes_128_gcm();
JNI_TRACE("EVP_aead_aes_128_gcm => ctx=%p", ctx);
return reinterpret_cast<jlong>(ctx);
#else
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jlong NativeCrypto_EVP_aead_aes_256_gcm(JNIEnv* env, jclass) {
#if defined(OPENSSL_IS_BORINGSSL)
UNUSED_ARGUMENT(env);
const EVP_AEAD* ctx = EVP_aead_aes_256_gcm();
JNI_TRACE("EVP_aead_aes_256_gcm => ctx=%p", ctx);
return reinterpret_cast<jlong>(ctx);
#else
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jlong NativeCrypto_EVP_AEAD_CTX_init(JNIEnv* env, jclass, jlong evpAeadRef,
jbyteArray keyArray, jint tagLen) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_CTX_init(%p, %p, %d)", evpAead, keyArray, tagLen);
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return 0;
}
Unique_EVP_AEAD_CTX aeadCtx(reinterpret_cast<EVP_AEAD_CTX*>(
OPENSSL_malloc(sizeof(EVP_AEAD_CTX))));
memset(aeadCtx.get(), 0, sizeof(EVP_AEAD_CTX));
const uint8_t* tmp = reinterpret_cast<const uint8_t*>(keyBytes.get());
int ret = EVP_AEAD_CTX_init(aeadCtx.get(), evpAead, tmp, keyBytes.size(), tagLen, NULL);
if (ret != 1) {
throwExceptionIfNecessary(env, "EVP_AEAD_CTX_init");
JNI_TRACE("EVP_AEAD_CTX_init(%p, %p, %d) => fail EVP_AEAD_CTX_init", evpAead,
keyArray, tagLen);
return 0;
}
JNI_TRACE("EVP_AEAD_CTX_init(%p, %p, %d) => %p", evpAead, keyArray, tagLen, aeadCtx.get());
return reinterpret_cast<jlong>(aeadCtx.release());
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
UNUSED_ARGUMENT(keyArray);
UNUSED_ARGUMENT(tagLen);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static void NativeCrypto_EVP_AEAD_CTX_cleanup(JNIEnv* env, jclass, jlong evpAeadCtxRef) {
#if defined(OPENSSL_IS_BORINGSSL)
EVP_AEAD_CTX* evpAeadCtx = reinterpret_cast<EVP_AEAD_CTX*>(evpAeadCtxRef);
JNI_TRACE("EVP_AEAD_CTX_cleanup(%p)", evpAeadCtx);
if (evpAeadCtx == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return;
}
EVP_AEAD_CTX_cleanup(evpAeadCtx);
OPENSSL_free(evpAeadCtx);
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadCtxRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
#endif
}
static jint NativeCrypto_EVP_AEAD_max_overhead(JNIEnv* env, jclass, jlong evpAeadRef) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_max_overhead(%p)", evpAead);
if (evpAead == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return 0;
}
int maxOverhead = EVP_AEAD_max_overhead(evpAead);
JNI_TRACE("EVP_AEAD_max_overhead(%p) => %d", evpAead, maxOverhead);
return maxOverhead;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jint NativeCrypto_EVP_AEAD_nonce_length(JNIEnv* env, jclass, jlong evpAeadRef) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_nonce_length(%p)", evpAead);
if (evpAead == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return 0;
}
int nonceLength = EVP_AEAD_nonce_length(evpAead);
JNI_TRACE("EVP_AEAD_nonce_length(%p) => %d", evpAead, nonceLength);
return nonceLength;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jint NativeCrypto_EVP_AEAD_max_tag_len(JNIEnv* env, jclass, jlong evpAeadRef) {
#if defined(OPENSSL_IS_BORINGSSL)
const EVP_AEAD* evpAead = reinterpret_cast<const EVP_AEAD*>(evpAeadRef);
JNI_TRACE("EVP_AEAD_max_tag_len(%p)", evpAead);
if (evpAead == NULL) {
jniThrowNullPointerException(env, "evpAead == null");
return 0;
}
int maxTagLen = EVP_AEAD_max_tag_len(evpAead);
JNI_TRACE("EVP_AEAD_max_tag_len(%p) => %d", evpAead, maxTagLen);
return maxTagLen;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(evpAeadRef);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
#if defined(OPENSSL_IS_BORINGSSL)
typedef int (*evp_aead_ctx_op_func)(const EVP_AEAD_CTX *ctx, uint8_t *out,
size_t *out_len, size_t max_out_len,
const uint8_t *nonce, size_t nonce_len,
const uint8_t *in, size_t in_len,
const uint8_t *ad, size_t ad_len);
static jint evp_aead_ctx_op(JNIEnv* env, jobject ctxRef, jbyteArray outArray, jint outOffset,
jbyteArray nonceArray, jbyteArray inArray, jint inOffset, jint inLength,
jbyteArray aadArray, evp_aead_ctx_op_func realFunc) {
EVP_AEAD_CTX* ctx = fromContextObject<EVP_AEAD_CTX>(env, ctxRef);
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p)", ctx, outArray, outOffset,
nonceArray, inArray, inOffset, inLength, aadArray);
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_INVALID(outBytes, outOffset)) {
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p)", ctx, outArray, outOffset,
nonceArray, inArray, inOffset, inLength, aadArray);
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "out");
return 0;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return 0;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p)", ctx, outArray, outOffset,
nonceArray, inArray, inOffset, inLength, aadArray);
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "in");
return 0;
}
UniquePtr<ScopedByteArrayRO> aad;
const uint8_t* aad_chars = NULL;
size_t aad_chars_size = 0;
if (aadArray != NULL) {
aad.reset(new ScopedByteArrayRO(env, aadArray));
aad_chars = reinterpret_cast<const uint8_t*>(aad->get());
if (aad_chars == NULL) {
return 0;
}
aad_chars_size = aad->size();
}
ScopedByteArrayRO nonceBytes(env, nonceArray);
if (nonceBytes.get() == NULL) {
return 0;
}
uint8_t* outTmp = reinterpret_cast<uint8_t*>(outBytes.get());
const uint8_t* inTmp = reinterpret_cast<const uint8_t*>(inBytes.get());
const uint8_t* nonceTmp = reinterpret_cast<const uint8_t*>(nonceBytes.get());
size_t actualOutLength;
int ret = realFunc(ctx, outTmp + outOffset, &actualOutLength, outBytes.size() - outOffset,
nonceTmp, nonceBytes.size(), inTmp + inOffset, inLength, aad_chars, aad_chars_size);
if (ret != 1) {
throwExceptionIfNecessary(env, "evp_aead_ctx_op");
}
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %d, %d, %p) => ret=%d, outLength=%zd",
ctx, outArray, outOffset, nonceArray, inArray, inOffset, inLength, aadArray, ret,
actualOutLength);
return static_cast<jlong>(actualOutLength);
}
#endif
static jint NativeCrypto_EVP_AEAD_CTX_seal(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray nonceArray, jbyteArray inArray, jint inOffset, jint inLength,
jbyteArray aadArray) {
#if defined(OPENSSL_IS_BORINGSSL)
return evp_aead_ctx_op(env, ctxRef, outArray, outOffset, nonceArray, inArray, inOffset,
inLength, aadArray, EVP_AEAD_CTX_seal);
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(ctxRef);
UNUSED_ARGUMENT(outArray);
UNUSED_ARGUMENT(outOffset);
UNUSED_ARGUMENT(nonceArray);
UNUSED_ARGUMENT(inArray);
UNUSED_ARGUMENT(inOffset);
UNUSED_ARGUMENT(inLength);
UNUSED_ARGUMENT(aadArray);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jint NativeCrypto_EVP_AEAD_CTX_open(JNIEnv* env, jclass, jobject ctxRef, jbyteArray outArray,
jint outOffset, jbyteArray nonceArray, jbyteArray inArray, jint inOffset, jint inLength,
jbyteArray aadArray) {
#if defined(OPENSSL_IS_BORINGSSL)
return evp_aead_ctx_op(env, ctxRef, outArray, outOffset, nonceArray, inArray, inOffset,
inLength, aadArray, EVP_AEAD_CTX_open);
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(ctxRef);
UNUSED_ARGUMENT(outArray);
UNUSED_ARGUMENT(outOffset);
UNUSED_ARGUMENT(nonceArray);
UNUSED_ARGUMENT(inArray);
UNUSED_ARGUMENT(inOffset);
UNUSED_ARGUMENT(inLength);
UNUSED_ARGUMENT(aadArray);
jniThrowRuntimeException(env, "Not supported for OpenSSL");
return 0;
#endif
}
static jlong NativeCrypto_HMAC_CTX_new(JNIEnv* env, jclass) {
JNI_TRACE("HMAC_CTX_new");
HMAC_CTX* hmacCtx = reinterpret_cast<HMAC_CTX*>(OPENSSL_malloc(sizeof(HMAC_CTX)));
if (hmacCtx == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate HMAC_CTX");
return 0;
}
HMAC_CTX_init(hmacCtx);
return reinterpret_cast<jlong>(hmacCtx);
}
static void NativeCrypto_HMAC_CTX_free(JNIEnv*, jclass, jlong hmacCtxRef) {
HMAC_CTX* hmacCtx = reinterpret_cast<HMAC_CTX*>(hmacCtxRef);
JNI_TRACE("HMAC_CTX_free(%p)", hmacCtx);
if (hmacCtx == NULL) {
return;
}
HMAC_CTX_cleanup(hmacCtx);
OPENSSL_free(hmacCtx);
}
static void NativeCrypto_HMAC_Init_ex(JNIEnv* env, jclass, jobject hmacCtxRef, jbyteArray keyArray,
jobject evpMdRef) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
const EVP_MD* md = reinterpret_cast<const EVP_MD*>(evpMdRef);
JNI_TRACE("HMAC_Init_ex(%p, %p, %p)", hmacCtx, keyArray, md);
if (hmacCtx == NULL) {
jniThrowNullPointerException(env, "hmacCtx == null");
return;
}
ScopedByteArrayRO keyBytes(env, keyArray);
if (keyBytes.get() == NULL) {
return;
}
const uint8_t* keyPtr = reinterpret_cast<const uint8_t*>(keyBytes.get());
if (!HMAC_Init_ex(hmacCtx, keyPtr, keyBytes.size(), md, NULL)) {
throwExceptionIfNecessary(env, "HMAC_Init_ex");
JNI_TRACE("HMAC_Init_ex(%p, %p, %p) => fail HMAC_Init_ex", hmacCtx, keyArray, md);
return;
}
}
static void NativeCrypto_HMAC_UpdateDirect(JNIEnv* env, jclass, jobject hmacCtxRef, jlong inPtr,
int inLength) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
const uint8_t* p = reinterpret_cast<const uint8_t*>(inPtr);
JNI_TRACE("HMAC_UpdateDirect(%p, %p, %d)", hmacCtx, p, inLength);
if (hmacCtx == NULL) {
return;
}
if (p == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
if (!HMAC_Update(hmacCtx, p, inLength)) {
JNI_TRACE("HMAC_UpdateDirect(%p, %p, %d) => threw exception", hmacCtx, p, inLength);
throwExceptionIfNecessary(env, "HMAC_UpdateDirect");
return;
}
}
static void NativeCrypto_HMAC_Update(JNIEnv* env, jclass, jobject hmacCtxRef, jbyteArray inArray,
jint inOffset, int inLength) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
JNI_TRACE("HMAC_Update(%p, %p, %d, %d)", hmacCtx, inArray, inOffset, inLength);
if (hmacCtx == NULL) {
return;
}
ScopedByteArrayRO inBytes(env, inArray);
if (inBytes.get() == NULL) {
return;
}
if (ARRAY_OFFSET_LENGTH_INVALID(inBytes, inOffset, inLength)) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inBytes");
return;
}
const uint8_t* inPtr = reinterpret_cast<const uint8_t*>(inBytes.get());
if (!HMAC_Update(hmacCtx, inPtr + inOffset, inLength)) {
JNI_TRACE("HMAC_Update(%p, %p, %d, %d) => threw exception", hmacCtx, inArray, inOffset,
inLength);
throwExceptionIfNecessary(env, "HMAC_Update");
return;
}
}
static jbyteArray NativeCrypto_HMAC_Final(JNIEnv* env, jclass, jobject hmacCtxRef) {
HMAC_CTX* hmacCtx = fromContextObject<HMAC_CTX>(env, hmacCtxRef);
JNI_TRACE("HMAC_Final(%p)", hmacCtx);
if (hmacCtx == NULL) {
return NULL;
}
uint8_t result[EVP_MAX_MD_SIZE];
unsigned len;
if (!HMAC_Final(hmacCtx, result, &len)) {
JNI_TRACE("HMAC_Final(%p) => threw exception", hmacCtx);
throwExceptionIfNecessary(env, "HMAC_Final");
return NULL;
}
ScopedLocalRef<jbyteArray> resultArray(env, env->NewByteArray(len));
if (resultArray.get() == NULL) {
return NULL;
}
ScopedByteArrayRW resultBytes(env, resultArray.get());
if (resultBytes.get() == NULL) {
return NULL;
}
memcpy(resultBytes.get(), result, len);
return resultArray.release();
}
/**
* public static native void RAND_seed(byte[]);
*/
#if !defined(OPENSSL_IS_BORINGSSL)
static void NativeCrypto_RAND_seed(JNIEnv* env, jclass, jbyteArray seed) {
JNI_TRACE("NativeCrypto_RAND_seed seed=%p", seed);
ScopedByteArrayRO randseed(env, seed);
if (randseed.get() == NULL) {
return;
}
RAND_seed(randseed.get(), randseed.size());
}
#else
static void NativeCrypto_RAND_seed(JNIEnv*, jclass, jbyteArray) {
}
#endif
static jint NativeCrypto_RAND_load_file(JNIEnv* env, jclass, jstring filename, jlong max_bytes) {
JNI_TRACE("NativeCrypto_RAND_load_file filename=%p max_bytes=%lld", filename, (long long) max_bytes);
#if !defined(OPENSSL_IS_BORINGSSL)
ScopedUtfChars file(env, filename);
if (file.c_str() == NULL) {
return -1;
}
int result = RAND_load_file(file.c_str(), max_bytes);
JNI_TRACE("NativeCrypto_RAND_load_file file=%s => %d", file.c_str(), result);
return result;
#else
UNUSED_ARGUMENT(env);
UNUSED_ARGUMENT(filename);
// OpenSSLRandom calls this and checks the return value.
return static_cast<jint>(max_bytes);
#endif
}
static void NativeCrypto_RAND_bytes(JNIEnv* env, jclass, jbyteArray output) {
JNI_TRACE("NativeCrypto_RAND_bytes(%p)", output);
ScopedByteArrayRW outputBytes(env, output);
if (outputBytes.get() == NULL) {
return;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(outputBytes.get());
if (RAND_bytes(tmp, outputBytes.size()) <= 0) {
throwExceptionIfNecessary(env, "NativeCrypto_RAND_bytes");
JNI_TRACE("tmp=%p NativeCrypto_RAND_bytes => threw error", tmp);
return;
}
JNI_TRACE("NativeCrypto_RAND_bytes(%p) => success", output);
}
static jint NativeCrypto_OBJ_txt2nid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return 0;
}
int nid = OBJ_txt2nid(oid.c_str());
JNI_TRACE("OBJ_txt2nid(%s) => %d", oid.c_str(), nid);
return nid;
}
static jstring NativeCrypto_OBJ_txt2nid_longName(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_longName(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_longName(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_longName(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const char* longName = OBJ_nid2ln(nid);
JNI_TRACE("OBJ_txt2nid_longName(%s) => %s", oid.c_str(), longName);
return env->NewStringUTF(longName);
}
static jstring ASN1_OBJECT_to_OID_string(JNIEnv* env, const ASN1_OBJECT* obj) {
/*
* The OBJ_obj2txt API doesn't "measure" if you pass in NULL as the buffer.
* Just make a buffer that's large enough here. The documentation recommends
* 80 characters.
*/
char output[128];
int ret = OBJ_obj2txt(output, sizeof(output), obj, 1);
if (ret < 0) {
throwExceptionIfNecessary(env, "ASN1_OBJECT_to_OID_string");
return NULL;
} else if (size_t(ret) >= sizeof(output)) {
jniThrowRuntimeException(env, "ASN1_OBJECT_to_OID_string buffer too small");
return NULL;
}
JNI_TRACE("ASN1_OBJECT_to_OID_string(%p) => %s", obj, output);
return env->NewStringUTF(output);
}
static jlong NativeCrypto_create_BIO_InputStream(JNIEnv* env, jclass,
jobject streamObj,
jboolean isFinite) {
JNI_TRACE("create_BIO_InputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_InputStream(streamObj, isFinite));
JNI_TRACE("create_BIO_InputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static jlong NativeCrypto_create_BIO_OutputStream(JNIEnv* env, jclass, jobject streamObj) {
JNI_TRACE("create_BIO_OutputStream(%p)", streamObj);
if (streamObj == NULL) {
jniThrowNullPointerException(env, "stream == null");
return 0;
}
Unique_BIO bio(BIO_new(&stream_bio_method));
if (bio.get() == NULL) {
return 0;
}
bio_stream_assign(bio.get(), new BIO_OutputStream(streamObj));
JNI_TRACE("create_BIO_OutputStream(%p) => %p", streamObj, bio.get());
return static_cast<jlong>(reinterpret_cast<uintptr_t>(bio.release()));
}
static int NativeCrypto_BIO_read(JNIEnv* env, jclass, jlong bioRef, jbyteArray outputJavaBytes) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_read(%p, %p)", bio, outputJavaBytes);
if (outputJavaBytes == NULL) {
jniThrowNullPointerException(env, "output == null");
JNI_TRACE("BIO_read(%p, %p) => output == null", bio, outputJavaBytes);
return 0;
}
int outputSize = env->GetArrayLength(outputJavaBytes);
UniquePtr<unsigned char[]> buffer(new unsigned char[outputSize]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for read");
return 0;
}
int read = BIO_read(bio, buffer.get(), outputSize);
if (read <= 0) {
jniThrowException(env, "java/io/IOException", "BIO_read");
JNI_TRACE("BIO_read(%p, %p) => threw IO exception", bio, outputJavaBytes);
return 0;
}
env->SetByteArrayRegion(outputJavaBytes, 0, read, reinterpret_cast<jbyte*>(buffer.get()));
JNI_TRACE("BIO_read(%p, %p) => %d", bio, outputJavaBytes, read);
return read;
}
static void NativeCrypto_BIO_write(JNIEnv* env, jclass, jlong bioRef, jbyteArray inputJavaBytes,
jint offset, jint length) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_write(%p, %p, %d, %d)", bio, inputJavaBytes, offset, length);
if (inputJavaBytes == NULL) {
jniThrowNullPointerException(env, "input == null");
return;
}
int inputSize = env->GetArrayLength(inputJavaBytes);
if (offset < 0 || offset > inputSize || length < 0 || length > inputSize - offset) {
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", "inputJavaBytes");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IOOB", bio, inputJavaBytes, offset, length);
return;
}
UniquePtr<unsigned char[]> buffer(new unsigned char[length]);
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate buffer for write");
return;
}
env->GetByteArrayRegion(inputJavaBytes, offset, length, reinterpret_cast<jbyte*>(buffer.get()));
if (BIO_write(bio, buffer.get(), length) != length) {
freeOpenSslErrorState();
jniThrowException(env, "java/io/IOException", "BIO_write");
JNI_TRACE("BIO_write(%p, %p, %d, %d) => IO error", bio, inputJavaBytes, offset, length);
return;
}
JNI_TRACE("BIO_write(%p, %p, %d, %d) => success", bio, inputJavaBytes, offset, length);
}
static void NativeCrypto_BIO_free_all(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("BIO_free_all(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return;
}
BIO_free_all(bio);
}
static jstring X509_NAME_to_jstring(JNIEnv* env, X509_NAME* name, unsigned long flags) {
JNI_TRACE("X509_NAME_to_jstring(%p)", name);
Unique_BIO buffer(BIO_new(BIO_s_mem()));
if (buffer.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate BIO");
JNI_TRACE("X509_NAME_to_jstring(%p) => threw error", name);
return NULL;
}
/* Don't interpret the string. */
flags &= ~(ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_ESC_MSB);
/* Write in given format and null terminate. */
X509_NAME_print_ex(buffer.get(), name, 0, flags);
BIO_write(buffer.get(), "\0", 1);
char *tmp;
BIO_get_mem_data(buffer.get(), &tmp);
JNI_TRACE("X509_NAME_to_jstring(%p) => \"%s\"", name, tmp);
return env->NewStringUTF(tmp);
}
/**
* Converts GENERAL_NAME items to the output format expected in
* X509Certificate#getSubjectAlternativeNames and
* X509Certificate#getIssuerAlternativeNames return.
*/
static jobject GENERAL_NAME_to_jobject(JNIEnv* env, GENERAL_NAME* gen) {
switch (gen->type) {
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI: {
// This must not be a T61String and must not contain NULLs.
const char* data = reinterpret_cast<const char*>(ASN1_STRING_data(gen->d.ia5));
ssize_t len = ASN1_STRING_length(gen->d.ia5);
if ((len == static_cast<ssize_t>(strlen(data)))
&& (ASN1_PRINTABLE_type(ASN1_STRING_data(gen->d.ia5), len) != V_ASN1_T61STRING)) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI \"%s\"", gen, data);
return env->NewStringUTF(data);
} else {
jniThrowException(env, "java/security/cert/CertificateParsingException",
"Invalid dNSName encoding");
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => Email/DNS/URI invalid", gen);
return NULL;
}
}
case GEN_DIRNAME:
/* Write in RFC 2253 format */
return X509_NAME_to_jstring(env, gen->d.directoryName, XN_FLAG_RFC2253);
case GEN_IPADD: {
const void *ip = reinterpret_cast<const void *>(gen->d.ip->data);
if (gen->d.ip->length == 4) {
// IPv4
UniquePtr<char[]> buffer(new char[INET_ADDRSTRLEN]);
if (inet_ntop(AF_INET, ip, buffer.get(), INET_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv4 failed %s", gen, strerror(errno));
}
} else if (gen->d.ip->length == 16) {
// IPv6
UniquePtr<char[]> buffer(new char[INET6_ADDRSTRLEN]);
if (inet_ntop(AF_INET6, ip, buffer.get(), INET6_ADDRSTRLEN) != NULL) {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 %s", gen, buffer.get());
return env->NewStringUTF(buffer.get());
} else {
JNI_TRACE("GENERAL_NAME_to_jobject(%p) => IPv6 failed %s", gen, strerror(errno));
}
}
/* Invalid IP encodings are pruned out without throwing an exception. */
return NULL;
}
case GEN_RID:
return ASN1_OBJECT_to_OID_string(env, gen->d.registeredID);
case GEN_OTHERNAME:
case GEN_X400:
default:
return ASN1ToByteArray<GENERAL_NAME>(env, gen, i2d_GENERAL_NAME);
}
return NULL;
}
#define GN_STACK_SUBJECT_ALT_NAME 1
#define GN_STACK_ISSUER_ALT_NAME 2
static jobjectArray NativeCrypto_get_X509_GENERAL_NAME_stack(JNIEnv* env, jclass, jlong x509Ref,
jint type) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d)", x509, type);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => x509 == null", x509, type);
return NULL;
}
X509_check_ca(x509);
STACK_OF(GENERAL_NAME)* gn_stack;
Unique_sk_GENERAL_NAME stackHolder;
if (type == GN_STACK_SUBJECT_ALT_NAME) {
gn_stack = x509->altname;
} else if (type == GN_STACK_ISSUER_ALT_NAME) {
stackHolder.reset(
static_cast<STACK_OF(GENERAL_NAME)*>(X509_get_ext_d2i(x509, NID_issuer_alt_name,
NULL, NULL)));
gn_stack = stackHolder.get();
} else {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => unknown type", x509, type);
return NULL;
}
int count = sk_GENERAL_NAME_num(gn_stack);
if (count <= 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no entries)", x509, type);
return NULL;
}
/*
* Keep track of how many originally so we can ignore any invalid
* values later.
*/
const int origCount = count;
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, objectArrayClass, NULL));
for (int i = 0, j = 0; i < origCount; i++, j++) {
GENERAL_NAME* gen = sk_GENERAL_NAME_value(gn_stack, i);
ScopedLocalRef<jobject> val(env, GENERAL_NAME_to_jobject(env, gen));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => threw exception parsing gen name",
x509, type);
return NULL;
}
/*
* If it's NULL, we'll have to skip this, reduce the number of total
* entries, and fix up the array later.
*/
if (val.get() == NULL) {
j--;
count--;
continue;
}
ScopedLocalRef<jobjectArray> item(env, env->NewObjectArray(2, objectClass, NULL));
ScopedLocalRef<jobject> type(env, env->CallStaticObjectMethod(integerClass,
integer_valueOfMethod, gen->type));
env->SetObjectArrayElement(item.get(), 0, type.get());
env->SetObjectArrayElement(item.get(), 1, val.get());
env->SetObjectArrayElement(joa.get(), j, item.get());
}
if (count == 0) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to 0; returning NULL",
x509, type, origCount);
joa.reset(NULL);
} else if (origCount != count) {
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) shrunk from %d to %d", x509, type,
origCount, count);
ScopedLocalRef<jobjectArray> joa_copy(env, env->NewObjectArray(count, objectArrayClass,
NULL));
for (int i = 0; i < count; i++) {
ScopedLocalRef<jobject> item(env, env->GetObjectArrayElement(joa.get(), i));
env->SetObjectArrayElement(joa_copy.get(), i, item.get());
}
joa.reset(joa_copy.release());
}
JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => %d entries", x509, type, count);
return joa.release();
}
static jlong NativeCrypto_X509_get_notBefore(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notBefore(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notBefore(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notBefore = X509_get_notBefore(x509);
JNI_TRACE("X509_get_notBefore(%p) => %p", x509, notBefore);
return reinterpret_cast<uintptr_t>(notBefore);
}
static jlong NativeCrypto_X509_get_notAfter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_notAfter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_notAfter(%p) => x509 == null", x509);
return 0;
}
ASN1_TIME* notAfter = X509_get_notAfter(x509);
JNI_TRACE("X509_get_notAfter(%p) => %p", x509, notAfter);
return reinterpret_cast<uintptr_t>(notAfter);
}
static long NativeCrypto_X509_get_version(JNIEnv*, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_version(%p)", x509);
long version = X509_get_version(x509);
JNI_TRACE("X509_get_version(%p) => %ld", x509, version);
return version;
}
template<typename T>
static jbyteArray get_X509Type_serialNumber(JNIEnv* env, T* x509Type, ASN1_INTEGER* (*get_serial_func)(T*)) {
JNI_TRACE("get_X509Type_serialNumber(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_serialNumber(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_INTEGER* serialNumber = get_serial_func(x509Type);
Unique_BIGNUM serialBn(ASN1_INTEGER_to_BN(serialNumber, NULL));
if (serialBn.get() == NULL) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
ScopedLocalRef<jbyteArray> serialArray(env, bignumToArray(env, serialBn.get(), "serialBn"));
if (env->ExceptionCheck()) {
JNI_TRACE("X509_get_serialNumber(%p) => threw exception", x509Type);
return NULL;
}
JNI_TRACE("X509_get_serialNumber(%p) => %p", x509Type, serialArray.get());
return serialArray.release();
}
/* OpenSSL includes set_serialNumber but not get. */
#if !defined(X509_REVOKED_get_serialNumber)
static ASN1_INTEGER* X509_REVOKED_get_serialNumber(X509_REVOKED* x) {
return x->serialNumber;
}
#endif
static jbyteArray NativeCrypto_X509_get_serialNumber(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_serialNumber(%p)", x509);
return get_X509Type_serialNumber<X509>(env, x509, X509_get_serialNumber);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_serialNumber(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_serialNumber(%p)", revoked);
return get_X509Type_serialNumber<X509_REVOKED>(env, revoked, X509_REVOKED_get_serialNumber);
}
static void NativeCrypto_X509_verify(JNIEnv* env, jclass, jlong x509Ref, jobject pkeyRef) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_verify(%p, %p)", x509, pkey);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_verify(%p, %p) => x509 == null", x509, pkey);
return;
}
if (pkey == NULL) {
JNI_TRACE("X509_verify(%p, %p) => pkey == null", x509, pkey);
return;
}
if (X509_verify(x509, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_verify");
JNI_TRACE("X509_verify(%p, %p) => verify failure", x509, pkey);
} else {
JNI_TRACE("X509_verify(%p, %p) => verify success", x509, pkey);
}
}
static jbyteArray NativeCrypto_get_X509_cert_info_enc(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_cert_info_enc(%p)", x509);
return ASN1ToByteArray<X509_CINF>(env, x509->cert_info, i2d_X509_CINF);
}
static jint NativeCrypto_get_X509_ex_flags(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_flags(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_flags(%p) => x509 == null", x509);
return 0;
}
X509_check_ca(x509);
return x509->ex_flags;
}
static jboolean NativeCrypto_X509_check_issued(JNIEnv*, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_check_issued(%p, %p)", x509_1, x509_2);
int ret = X509_check_issued(x509_1, x509_2);
JNI_TRACE("X509_check_issued(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void get_X509_signature(X509 *x509, ASN1_BIT_STRING** signature) {
*signature = x509->signature;
}
static void get_X509_CRL_signature(X509_CRL *crl, ASN1_BIT_STRING** signature) {
*signature = crl->signature;
}
template<typename T>
static jbyteArray get_X509Type_signature(JNIEnv* env, T* x509Type, void (*get_signature_func)(T*, ASN1_BIT_STRING**)) {
JNI_TRACE("get_X509Type_signature(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509Type == null");
JNI_TRACE("get_X509Type_signature(%p) => x509Type == null", x509Type);
return NULL;
}
ASN1_BIT_STRING* signature;
get_signature_func(x509Type, &signature);
ScopedLocalRef<jbyteArray> signatureArray(env, env->NewByteArray(signature->length));
if (env->ExceptionCheck()) {
JNI_TRACE("get_X509Type_signature(%p) => threw exception", x509Type);
return NULL;
}
ScopedByteArrayRW signatureBytes(env, signatureArray.get());
if (signatureBytes.get() == NULL) {
JNI_TRACE("get_X509Type_signature(%p) => using byte array failed", x509Type);
return NULL;
}
memcpy(signatureBytes.get(), signature->data, signature->length);
JNI_TRACE("get_X509Type_signature(%p) => %p (%d bytes)", x509Type, signatureArray.get(),
signature->length);
return signatureArray.release();
}
static jbyteArray NativeCrypto_get_X509_signature(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_signature(%p)", x509);
return get_X509Type_signature<X509>(env, x509, get_X509_signature);
}
static jbyteArray NativeCrypto_get_X509_CRL_signature(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_signature(%p)", crl);
return get_X509Type_signature<X509_CRL>(env, crl, get_X509_CRL_signature);
}
static jlong NativeCrypto_X509_CRL_get0_by_cert(JNIEnv* env, jclass, jlong x509crlRef, jlong x509Ref) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p)", x509crl, x509);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509crl == null", x509crl, x509);
return 0;
} else if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => x509 == null", x509crl, x509);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_cert(x509crl, &revoked, x509);
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => none", x509crl, x509);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, x509, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
static jlong NativeCrypto_X509_CRL_get0_by_serial(JNIEnv* env, jclass, jlong x509crlRef, jbyteArray serialArray) {
X509_CRL* x509crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509crlRef));
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p)", x509crl, serialArray);
if (x509crl == NULL) {
jniThrowNullPointerException(env, "x509crl == null");
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => crl == null", x509crl, serialArray);
return 0;
}
Unique_BIGNUM serialBn(BN_new());
if (serialBn.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN allocation failed", x509crl, serialArray);
return 0;
}
BIGNUM* serialBare = serialBn.get();
if (!arrayToBignum(env, serialArray, &serialBare)) {
if (!env->ExceptionCheck()) {
jniThrowNullPointerException(env, "serial == null");
}
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
Unique_ASN1_INTEGER serialInteger(BN_to_ASN1_INTEGER(serialBn.get(), NULL));
if (serialInteger.get() == NULL) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => BN conversion failed", x509crl, serialArray);
return 0;
}
X509_REVOKED* revoked = NULL;
int ret = X509_CRL_get0_by_serial(x509crl, &revoked, serialInteger.get());
if (ret == 0) {
JNI_TRACE("X509_CRL_get0_by_serial(%p, %p) => none", x509crl, serialArray);
return 0;
}
JNI_TRACE("X509_CRL_get0_by_cert(%p, %p) => %p", x509crl, serialArray, revoked);
return reinterpret_cast<uintptr_t>(revoked);
}
/* This appears to be missing from OpenSSL. */
#if !defined(X509_REVOKED_dup) && !defined(OPENSSL_IS_BORINGSSL)
X509_REVOKED* X509_REVOKED_dup(X509_REVOKED* x) {
return reinterpret_cast<X509_REVOKED*>(ASN1_item_dup(ASN1_ITEM_rptr(X509_REVOKED), x));
}
#endif
static jlongArray NativeCrypto_X509_CRL_get_REVOKED(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_REVOKED(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
return NULL;
}
STACK_OF(X509_REVOKED)* stack = X509_CRL_get_REVOKED(crl);
if (stack == NULL) {
JNI_TRACE("X509_CRL_get_REVOKED(%p) => stack is null", crl);
return NULL;
}
size_t size = sk_X509_REVOKED_num(stack);
ScopedLocalRef<jlongArray> revokedArray(env, env->NewLongArray(size));
ScopedLongArrayRW revoked(env, revokedArray.get());
for (size_t i = 0; i < size; i++) {
X509_REVOKED* item = reinterpret_cast<X509_REVOKED*>(sk_X509_REVOKED_value(stack, i));
revoked[i] = reinterpret_cast<uintptr_t>(X509_REVOKED_dup(item));
}
JNI_TRACE("X509_CRL_get_REVOKED(%p) => %p [size=%zd]", stack, revokedArray.get(), size);
return revokedArray.release();
}
static jbyteArray NativeCrypto_i2d_X509_CRL(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("i2d_X509_CRL(%p)", crl);
return ASN1ToByteArray<X509_CRL>(env, crl, i2d_X509_CRL);
}
static void NativeCrypto_X509_CRL_free(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_free(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_free(%p) => crl == null", crl);
return;
}
X509_CRL_free(crl);
}
static void NativeCrypto_X509_CRL_print(JNIEnv* env, jclass, jlong bioRef, jlong x509CrlRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_print(%p, %p)", bio, crl);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_CRL_print(%p, %p) => bio == null", bio, crl);
return;
}
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_print(%p, %p) => crl == null", bio, crl);
return;
}
if (!X509_CRL_print(bio, crl)) {
throwExceptionIfNecessary(env, "X509_CRL_print");
JNI_TRACE("X509_CRL_print(%p, %p) => threw error", bio, crl);
} else {
JNI_TRACE("X509_CRL_print(%p, %p) => success", bio, crl);
}
}
static jstring NativeCrypto_get_X509_CRL_sig_alg_oid(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p)", crl);
if (crl == NULL || crl->sig_alg == NULL) {
jniThrowNullPointerException(env, "crl == NULL || crl->sig_alg == NULL");
JNI_TRACE("get_X509_CRL_sig_alg_oid(%p) => crl == NULL", crl);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, crl->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_CRL_sig_alg_parameter(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => crl == null", crl);
return NULL;
}
if (crl->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_CRL_sig_alg_parameter(%p) => null", crl);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, crl->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbyteArray NativeCrypto_X509_CRL_get_issuer_name(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_issuer_name(%p)", crl);
return ASN1ToByteArray<X509_NAME>(env, X509_CRL_get_issuer(crl), i2d_X509_NAME);
}
static long NativeCrypto_X509_CRL_get_version(JNIEnv*, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_version(%p)", crl);
long version = X509_CRL_get_version(crl);
JNI_TRACE("X509_CRL_get_version(%p) => %ld", crl, version);
return version;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static X509_EXTENSION *X509Type_get_ext(JNIEnv* env, T* x509Type, jstring oidString) {
JNI_TRACE("X509Type_get_ext(%p)", x509Type);
if (x509Type == NULL) {
jniThrowNullPointerException(env, "x509 == null");
return NULL;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
return NULL;
}
Unique_ASN1_OBJECT asn1(OBJ_txt2obj(oid.c_str(), 1));
if (asn1.get() == NULL) {
JNI_TRACE("X509Type_get_ext(%p, %s) => oid conversion failed", x509Type, oid.c_str());
freeOpenSslErrorState();
return NULL;
}
int extIndex = get_ext_by_OBJ_func(x509Type, (ASN1_OBJECT*) asn1.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509Type_get_ext(%p, %s) => ext not found", x509Type, oid.c_str());
return NULL;
}
X509_EXTENSION* ext = get_ext_func(x509Type, extIndex);
JNI_TRACE("X509Type_get_ext(%p, %s) => %p", x509Type, oid.c_str(), ext);
return ext;
}
template<typename T, int (*get_ext_by_OBJ_func)(T*, ASN1_OBJECT*, int),
X509_EXTENSION* (*get_ext_func)(T*, int)>
static jbyteArray X509Type_get_ext_oid(JNIEnv* env, T* x509Type, jstring oidString) {
X509_EXTENSION* ext = X509Type_get_ext<T, get_ext_by_OBJ_func, get_ext_func>(env, x509Type,
oidString);
if (ext == NULL) {
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => fetching extension failed", x509Type, oidString);
return NULL;
}
JNI_TRACE("X509Type_get_ext_oid(%p, %p) => %p", x509Type, oidString, ext->value);
return ASN1ToByteArray<ASN1_OCTET_STRING>(env, ext->value, i2d_ASN1_OCTET_STRING);
}
static jlong NativeCrypto_X509_CRL_get_ext(JNIEnv* env, jclass, jlong x509CrlRef, jstring oid) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext(%p, %p)", crl, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(
env, crl, oid);
JNI_TRACE("X509_CRL_get_ext(%p, %p) => %p", crl, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_get_ext(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oid) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext(%p, %p)", revoked, oid);
X509_EXTENSION* ext = X509Type_get_ext<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ,
X509_REVOKED_get_ext>(env, revoked, oid);
JNI_TRACE("X509_REVOKED_get_ext(%p, %p) => %p", revoked, oid, ext);
return reinterpret_cast<uintptr_t>(ext);
}
static jlong NativeCrypto_X509_REVOKED_dup(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_dup(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_dup(%p) => revoked == null", revoked);
return 0;
}
X509_REVOKED* dup = X509_REVOKED_dup(revoked);
JNI_TRACE("X509_REVOKED_dup(%p) => %p", revoked, dup);
return reinterpret_cast<uintptr_t>(dup);
}
static jlong NativeCrypto_get_X509_REVOKED_revocationDate(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("get_X509_REVOKED_revocationDate(%p)", revoked);
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => revoked == null", revoked);
return 0;
}
JNI_TRACE("get_X509_REVOKED_revocationDate(%p) => %p", revoked, revoked->revocationDate);
return reinterpret_cast<uintptr_t>(revoked->revocationDate);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
static void NativeCrypto_X509_REVOKED_print(JNIEnv* env, jclass, jlong bioRef, jlong x509RevokedRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_print(%p, %p)", bio, revoked);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => bio == null", bio, revoked);
return;
}
if (revoked == NULL) {
jniThrowNullPointerException(env, "revoked == null");
JNI_TRACE("X509_REVOKED_print(%p, %p) => revoked == null", bio, revoked);
return;
}
BIO_printf(bio, "Serial Number: ");
i2a_ASN1_INTEGER(bio, revoked->serialNumber);
BIO_printf(bio, "\nRevocation Date: ");
ASN1_TIME_print(bio, revoked->revocationDate);
BIO_printf(bio, "\n");
X509V3_extensions_print(bio, "CRL entry extensions", revoked->extensions, 0, 0);
}
#pragma GCC diagnostic pop
static jbyteArray NativeCrypto_get_X509_CRL_crl_enc(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("get_X509_CRL_crl_enc(%p)", crl);
return ASN1ToByteArray<X509_CRL_INFO>(env, crl->crl, i2d_X509_CRL_INFO);
}
static void NativeCrypto_X509_CRL_verify(JNIEnv* env, jclass, jlong x509CrlRef, jobject pkeyRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("X509_CRL_verify(%p, %p)", crl, pkey);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_verify(%p, %p) => crl == null", crl, pkey);
return;
}
if (pkey == NULL) {
JNI_TRACE("X509_CRL_verify(%p, %p) => pkey == null", crl, pkey);
return;
}
if (X509_CRL_verify(crl, pkey) != 1) {
throwExceptionIfNecessary(env, "X509_CRL_verify");
JNI_TRACE("X509_CRL_verify(%p, %p) => verify failure", crl, pkey);
} else {
JNI_TRACE("X509_CRL_verify(%p, %p) => verify success", crl, pkey);
}
}
static jlong NativeCrypto_X509_CRL_get_lastUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_lastUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* lastUpdate = X509_CRL_get_lastUpdate(crl);
JNI_TRACE("X509_CRL_get_lastUpdate(%p) => %p", crl, lastUpdate);
return reinterpret_cast<uintptr_t>(lastUpdate);
}
static jlong NativeCrypto_X509_CRL_get_nextUpdate(JNIEnv* env, jclass, jlong x509CrlRef) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_nextUpdate(%p)", crl);
if (crl == NULL) {
jniThrowNullPointerException(env, "crl == null");
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => crl == null", crl);
return 0;
}
ASN1_TIME* nextUpdate = X509_CRL_get_nextUpdate(crl);
JNI_TRACE("X509_CRL_get_nextUpdate(%p) => %p", crl, nextUpdate);
return reinterpret_cast<uintptr_t>(nextUpdate);
}
static jbyteArray NativeCrypto_i2d_X509_REVOKED(JNIEnv* env, jclass, jlong x509RevokedRef) {
X509_REVOKED* x509Revoked =
reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("i2d_X509_REVOKED(%p)", x509Revoked);
return ASN1ToByteArray<X509_REVOKED>(env, x509Revoked, i2d_X509_REVOKED);
}
static jint NativeCrypto_X509_supported_extension(JNIEnv* env, jclass, jlong x509ExtensionRef) {
X509_EXTENSION* ext = reinterpret_cast<X509_EXTENSION*>(static_cast<uintptr_t>(x509ExtensionRef));
if (ext == NULL) {
jniThrowNullPointerException(env, "ext == NULL");
return 0;
}
return X509_supported_extension(ext);
}
static inline void get_ASN1_TIME_data(char **data, int* output, size_t len) {
char c = **data;
**data = '\0';
*data -= len;
*output = atoi(*data);
*(*data + len) = c;
}
static void NativeCrypto_ASN1_TIME_to_Calendar(JNIEnv* env, jclass, jlong asn1TimeRef, jobject calendar) {
ASN1_TIME* asn1Time = reinterpret_cast<ASN1_TIME*>(static_cast<uintptr_t>(asn1TimeRef));
JNI_TRACE("ASN1_TIME_to_Calendar(%p, %p)", asn1Time, calendar);
if (asn1Time == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
Unique_ASN1_GENERALIZEDTIME gen(ASN1_TIME_to_generalizedtime(asn1Time, NULL));
if (gen.get() == NULL) {
jniThrowNullPointerException(env, "asn1Time == null");
return;
}
if (gen->length < 14 || gen->data == NULL) {
jniThrowNullPointerException(env, "gen->length < 14 || gen->data == NULL");
return;
}
int sec, min, hour, mday, mon, year;
char *p = (char*) &gen->data[14];
get_ASN1_TIME_data(&p, &sec, 2);
get_ASN1_TIME_data(&p, &min, 2);
get_ASN1_TIME_data(&p, &hour, 2);
get_ASN1_TIME_data(&p, &mday, 2);
get_ASN1_TIME_data(&p, &mon, 2);
get_ASN1_TIME_data(&p, &year, 4);
env->CallVoidMethod(calendar, calendar_setMethod, year, mon - 1, mday, hour, min, sec);
}
static jstring NativeCrypto_OBJ_txt2nid_oid(JNIEnv* env, jclass, jstring oidStr) {
JNI_TRACE("OBJ_txt2nid_oid(%p)", oidStr);
ScopedUtfChars oid(env, oidStr);
if (oid.c_str() == NULL) {
return NULL;
}
JNI_TRACE("OBJ_txt2nid_oid(%s)", oid.c_str());
int nid = OBJ_txt2nid(oid.c_str());
if (nid == NID_undef) {
JNI_TRACE("OBJ_txt2nid_oid(%s) => NID_undef", oid.c_str());
freeOpenSslErrorState();
return NULL;
}
const ASN1_OBJECT* obj = OBJ_nid2obj(nid);
if (obj == NULL) {
throwExceptionIfNecessary(env, "OBJ_nid2obj");
return NULL;
}
ScopedLocalRef<jstring> ouputStr(env, ASN1_OBJECT_to_OID_string(env, obj));
JNI_TRACE("OBJ_txt2nid_oid(%s) => %p", oid.c_str(), ouputStr.get());
return ouputStr.release();
}
static jstring NativeCrypto_X509_NAME_print_ex(JNIEnv* env, jclass, jlong x509NameRef, jlong jflags) {
X509_NAME* x509name = reinterpret_cast<X509_NAME*>(static_cast<uintptr_t>(x509NameRef));
unsigned long flags = static_cast<unsigned long>(jflags);
JNI_TRACE("X509_NAME_print_ex(%p, %ld)", x509name, flags);
if (x509name == NULL) {
jniThrowNullPointerException(env, "x509name == null");
JNI_TRACE("X509_NAME_print_ex(%p, %ld) => x509name == null", x509name, flags);
return NULL;
}
return X509_NAME_to_jstring(env, x509name, flags);
}
template <typename T, T* (*d2i_func)(BIO*, T**)>
static jlong d2i_ASN1Object_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_ASN1Object_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
return 0;
}
T* x = d2i_func(bio, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "d2i_ASN1Object_to_jlong");
return 0;
}
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_d2i_X509_CRL_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509_CRL, d2i_X509_CRL_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
return d2i_ASN1Object_to_jlong<X509, d2i_X509_bio>(env, bioRef);
}
static jlong NativeCrypto_d2i_X509(JNIEnv* env, jclass, jbyteArray certBytes) {
X509* x = ByteArrayToASN1<X509, d2i_X509>(env, certBytes);
return reinterpret_cast<uintptr_t>(x);
}
static jbyteArray NativeCrypto_i2d_X509(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509(%p)", x509);
return ASN1ToByteArray<X509>(env, x509, i2d_X509);
}
static jbyteArray NativeCrypto_i2d_X509_PUBKEY(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("i2d_X509_PUBKEY(%p)", x509);
return ASN1ToByteArray<X509_PUBKEY>(env, X509_get_X509_PUBKEY(x509), i2d_X509_PUBKEY);
}
template<typename T, T* (*PEM_read_func)(BIO*, T**, pem_password_cb*, void*)>
static jlong PEM_to_jlong(JNIEnv* env, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_to_jlong(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_to_jlong(%p) => bio == null", bio);
return 0;
}
T* x = PEM_read_func(bio, NULL, NULL, NULL);
if (x == NULL) {
throwExceptionIfNecessary(env, "PEM_to_jlong");
// Sometimes the PEM functions fail without pushing an error
if (!env->ExceptionCheck()) {
jniThrowRuntimeException(env, "Failure parsing PEM");
}
JNI_TRACE("PEM_to_jlong(%p) => threw exception", bio);
return 0;
}
JNI_TRACE("PEM_to_jlong(%p) => %p", bio, x);
return reinterpret_cast<uintptr_t>(x);
}
static jlong NativeCrypto_PEM_read_bio_X509(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509(0x%llx)", (long long) bioRef);
return PEM_to_jlong<X509, PEM_read_bio_X509>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_X509_CRL(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_X509_CRL(0x%llx)", (long long) bioRef);
return PEM_to_jlong<X509_CRL, PEM_read_bio_X509_CRL>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_PUBKEY(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_PUBKEY(0x%llx)", (long long) bioRef);
return PEM_to_jlong<EVP_PKEY, PEM_read_bio_PUBKEY>(env, bioRef);
}
static jlong NativeCrypto_PEM_read_bio_PrivateKey(JNIEnv* env, jclass, jlong bioRef) {
JNI_TRACE("PEM_read_bio_PrivateKey(0x%llx)", (long long) bioRef);
return PEM_to_jlong<EVP_PKEY, PEM_read_bio_PrivateKey>(env, bioRef);
}
template <typename T, typename T_stack>
static jlongArray PKCS7_to_ItemArray(JNIEnv* env, T_stack* stack, T* (*dup_func)(T*))
{
if (stack == NULL) {
return NULL;
}
ScopedLocalRef<jlongArray> ref_array(env, NULL);
size_t size = sk_num(reinterpret_cast<_STACK*>(stack));
ref_array.reset(env->NewLongArray(size));
ScopedLongArrayRW items(env, ref_array.get());
for (size_t i = 0; i < size; i++) {
T* item = reinterpret_cast<T*>(sk_value(reinterpret_cast<_STACK*>(stack), i));
items[i] = reinterpret_cast<uintptr_t>(dup_func(item));
}
JNI_TRACE("PKCS7_to_ItemArray(%p) => %p [size=%zd]", stack, ref_array.get(), size);
return ref_array.release();
}
#define PKCS7_CERTS 1
#define PKCS7_CRLS 2
static jbyteArray NativeCrypto_i2d_PKCS7(JNIEnv* env, jclass, jlongArray certsArray) {
#if !defined(OPENSSL_IS_BORINGSSL)
JNI_TRACE("i2d_PKCS7(%p)", certsArray);
Unique_PKCS7 pkcs7(PKCS7_new());
if (pkcs7.get() == NULL) {
jniThrowNullPointerException(env, "pkcs7 == null");
JNI_TRACE("i2d_PKCS7(%p) => pkcs7 == null", certsArray);
return NULL;
}
if (PKCS7_set_type(pkcs7.get(), NID_pkcs7_signed) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type");
return NULL;
}
// The EncapsulatedContentInfo must be present in the output, but OpenSSL
// will fill in a zero-length OID if you don't call PKCS7_set_content on the
// outer PKCS7 container. So we construct an empty PKCS7 data container and
// set it as the content.
Unique_PKCS7 pkcs7Data(PKCS7_new());
if (PKCS7_set_type(pkcs7Data.get(), NID_pkcs7_data) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_type data");
return NULL;
}
if (PKCS7_set_content(pkcs7.get(), pkcs7Data.get()) != 1) {
throwExceptionIfNecessary(env, "PKCS7_set_content");
return NULL;
}
OWNERSHIP_TRANSFERRED(pkcs7Data);
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (PKCS7_add_certificate(pkcs7.get(), item) != 1) {
throwExceptionIfNecessary(env, "i2d_PKCS7");
return NULL;
}
}
JNI_TRACE("i2d_PKCS7(%p) => %zd certs", certsArray, certs.size());
return ASN1ToByteArray<PKCS7>(env, pkcs7.get(), i2d_PKCS7);
#else // OPENSSL_IS_BORINGSSL
STACK_OF(X509) *stack = sk_X509_new_null();
ScopedLongArrayRO certs(env, certsArray);
for (size_t i = 0; i < certs.size(); i++) {
X509* item = reinterpret_cast<X509*>(certs[i]);
if (sk_X509_push(stack, item) == 0) {
sk_X509_free(stack);
throwExceptionIfNecessary(env, "sk_X509_push");
return NULL;
}
}
CBB out;
CBB_init(&out, 1024 * certs.size());
if (!PKCS7_bundle_certificates(&out, stack)) {
CBB_cleanup(&out);
sk_X509_free(stack);
throwExceptionIfNecessary(env, "PKCS7_bundle_certificates");
return NULL;
}
sk_X509_free(stack);
uint8_t *derBytes;
size_t derLen;
if (!CBB_finish(&out, &derBytes, &derLen)) {
CBB_cleanup(&out);
throwExceptionIfNecessary(env, "CBB_finish");
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == NULL) {
JNI_TRACE("creating byte array failed");
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("using byte array failed");
return NULL;
}
uint8_t* p = reinterpret_cast<unsigned char*>(bytes.get());
memcpy(p, derBytes, derLen);
return byteArray.release();
#endif // OPENSSL_IS_BORINGSSL
}
#if !defined(OPENSSL_IS_BORINGSSL)
static STACK_OF(X509)* PKCS7_get_certs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->cert;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->cert;
} else {
JNI_TRACE("PKCS7_get_certs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
static STACK_OF(X509_CRL)* PKCS7_get_CRLs(PKCS7* pkcs7) {
if (PKCS7_type_is_signed(pkcs7)) {
return pkcs7->d.sign->crl;
} else if (PKCS7_type_is_signedAndEnveloped(pkcs7)) {
return pkcs7->d.signed_and_enveloped->crl;
} else {
JNI_TRACE("PKCS7_get_CRLs(%p) => unknown PKCS7 type", pkcs7);
return NULL;
}
}
#endif
static jlongArray NativeCrypto_PEM_read_bio_PKCS7(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p)", bio);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => bio == null", bio);
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_PKCS7 pkcs7(PEM_read_bio_PKCS7(bio, NULL, NULL, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "PEM_read_bio_PKCS7_CRLs");
JNI_TRACE("PEM_read_bio_PKCS7_CRLs(%p) => threw exception", bio);
return 0;
}
switch (which) {
case PKCS7_CERTS:
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
#else
if (which == PKCS7_CERTS) {
Unique_sk_X509 outCerts(sk_X509_new_null());
if (!PKCS7_get_PEM_certificates(outCerts.get(), bio)) {
throwExceptionIfNecessary(env, "PKCS7_get_PEM_certificates");
return 0;
}
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, outCerts.get(), X509_dup);
} else if (which == PKCS7_CRLS) {
Unique_sk_X509_CRL outCRLs(sk_X509_CRL_new_null());
if (!PKCS7_get_PEM_CRLs(outCRLs.get(), bio)) {
throwExceptionIfNecessary(env, "PKCS7_get_PEM_CRLs");
return 0;
}
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(
env, outCRLs.get(), X509_CRL_dup);
} else {
jniThrowRuntimeException(env, "unknown PKCS7 field");
return 0;
}
#endif
}
static jlongArray NativeCrypto_d2i_PKCS7_bio(JNIEnv* env, jclass, jlong bioRef, jint which) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("d2i_PKCS7_bio(%p, %d)", bio, which);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => bio == null", bio, which);
return 0;
}
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_PKCS7 pkcs7(d2i_PKCS7_bio(bio, NULL));
if (pkcs7.get() == NULL) {
throwExceptionIfNecessary(env, "d2i_PKCS7_bio");
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => threw exception", bio, which);
return 0;
}
switch (which) {
case PKCS7_CERTS:
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => returned", bio, which);
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, PKCS7_get_certs(pkcs7.get()), X509_dup);
case PKCS7_CRLS:
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => returned", bio, which);
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(env, PKCS7_get_CRLs(pkcs7.get()),
X509_CRL_dup);
default:
jniThrowRuntimeException(env, "unknown PKCS7 field");
return NULL;
}
#else
uint8_t *data;
size_t len;
if (!BIO_read_asn1(bio, &data, &len, 256 * 1024 * 1024 /* max length, 256MB for sanity */)) {
if (!throwExceptionIfNecessary(env, "Error reading PKCS#7 data")) {
throwParsingException(env, "Error reading PKCS#7 data");
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading BIO", bio, which);
return 0;
}
Unique_OPENSSL_str data_storage(data);
CBS cbs;
CBS_init(&cbs, data, len);
if (which == PKCS7_CERTS) {
Unique_sk_X509 outCerts(sk_X509_new_null());
if (!PKCS7_get_certificates(outCerts.get(), &cbs)) {
if (!throwExceptionIfNecessary(env, "PKCS7_get_certificates")) {
throwParsingException(env, "Error parsing PKCS#7 certificate data");
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading certs", bio, which);
return 0;
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => success certs", bio, which);
return PKCS7_to_ItemArray<X509, STACK_OF(X509)>(env, outCerts.get(), X509_dup);
} else if (which == PKCS7_CRLS) {
Unique_sk_X509_CRL outCRLs(sk_X509_CRL_new_null());
if (!PKCS7_get_CRLs(outCRLs.get(), &cbs)) {
if (!throwExceptionIfNecessary(env, "PKCS7_get_CRLs")) {
throwParsingException(env, "Error parsing PKCS#7 CRL data");
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading CRLs", bio, which);
return 0;
}
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => success CRLs", bio, which);
return PKCS7_to_ItemArray<X509_CRL, STACK_OF(X509_CRL)>(
env, outCRLs.get(), X509_CRL_dup);
} else {
jniThrowRuntimeException(env, "unknown PKCS7 field");
return 0;
}
#endif
}
typedef STACK_OF(X509) PKIPATH;
ASN1_ITEM_TEMPLATE(PKIPATH) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PkiPath, X509)
ASN1_ITEM_TEMPLATE_END(PKIPATH)
static jlongArray NativeCrypto_ASN1_seq_unpack_X509_bio(JNIEnv* env, jclass, jlong bioRef) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p)", bio);
Unique_sk_X509 path((PKIPATH*) ASN1_item_d2i_bio(ASN1_ITEM_rptr(PKIPATH), bio, NULL));
if (path.get() == NULL) {
throwExceptionIfNecessary(env, "ASN1_seq_unpack_X509_bio");
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => threw error", bio);
return NULL;
}
size_t size = sk_X509_num(path.get());
ScopedLocalRef<jlongArray> certArray(env, env->NewLongArray(size));
ScopedLongArrayRW certs(env, certArray.get());
for (size_t i = 0; i < size; i++) {
X509* item = reinterpret_cast<X509*>(sk_X509_shift(path.get()));
certs[i] = reinterpret_cast<uintptr_t>(item);
}
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => returns %zd items", bio, size);
return certArray.release();
}
static jbyteArray NativeCrypto_ASN1_seq_pack_X509(JNIEnv* env, jclass, jlongArray certs) {
JNI_TRACE("ASN1_seq_pack_X509(%p)", certs);
ScopedLongArrayRO certsArray(env, certs);
if (certsArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to get certs array", certs);
return NULL;
}
Unique_sk_X509 certStack(sk_X509_new_null());
if (certStack.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => failed to make cert stack", certs);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
sk_X509_push(certStack.get(), X509_dup_nocopy(x509));
}
int len;
Unique_OPENSSL_str encoded(ASN1_seq_pack(
reinterpret_cast<STACK_OF(OPENSSL_BLOCK)*>(
reinterpret_cast<uintptr_t>(certStack.get())),
reinterpret_cast<int (*)(void*, unsigned char**)>(i2d_X509), NULL, &len));
if (encoded.get() == NULL || len < 0) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => trouble encoding", certs);
return NULL;
}
uint8_t *out = encoded.get();
size_t out_len = len;
#else
CBB result, seq_contents;
if (!CBB_init(&result, 2048 * certsArray.size())) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => CBB_init failed", certs);
return NULL;
}
if (!CBB_add_asn1(&result, &seq_contents, CBS_ASN1_SEQUENCE)) {
CBB_cleanup(&result);
return NULL;
}
for (size_t i = 0; i < certsArray.size(); i++) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(certsArray[i]));
uint8_t *buf;
int len = i2d_X509(x509, NULL);
if (len < 0 ||
!CBB_add_space(&seq_contents, &buf, len) ||
i2d_X509(x509, &buf) < 0) {
CBB_cleanup(&result);
return NULL;
}
}
uint8_t *out;
size_t out_len;
if (!CBB_finish(&result, &out, &out_len)) {
CBB_cleanup(&result);
return NULL;
}
UniquePtr<uint8_t> out_storage(out);
#endif
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(out_len));
if (byteArray.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => creating byte array failed", certs);
return NULL;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == NULL) {
JNI_TRACE("ASN1_seq_pack_X509(%p) => using byte array failed", certs);
return NULL;
}
uint8_t *p = reinterpret_cast<uint8_t*>(bytes.get());
memcpy(p, out, out_len);
return byteArray.release();
}
static void NativeCrypto_X509_free(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_free(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_free(%p) => x509 == null", x509);
return;
}
X509_free(x509);
}
static jlong NativeCrypto_X509_dup(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_dup(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_dup(%p) => x509 == null", x509);
return 0;
}
return reinterpret_cast<uintptr_t>(X509_dup(x509));
}
static jint NativeCrypto_X509_cmp(JNIEnv* env, jclass, jlong x509Ref1, jlong x509Ref2) {
X509* x509_1 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref1));
X509* x509_2 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref2));
JNI_TRACE("X509_cmp(%p, %p)", x509_1, x509_2);
if (x509_1 == NULL) {
jniThrowNullPointerException(env, "x509_1 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_1 == null", x509_1, x509_2);
return -1;
}
if (x509_2 == NULL) {
jniThrowNullPointerException(env, "x509_2 == null");
JNI_TRACE("X509_cmp(%p, %p) => x509_2 == null", x509_1, x509_2);
return -1;
}
int ret = X509_cmp(x509_1, x509_2);
JNI_TRACE("X509_cmp(%p, %p) => %d", x509_1, x509_2, ret);
return ret;
}
static void NativeCrypto_X509_delete_ext(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_delete_ext(%p, %p)", x509, oidString);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_delete_ext(%p, %p) => x509 == null", x509, oidString);
return;
}
ScopedUtfChars oid(env, oidString);
if (oid.c_str() == NULL) {
JNI_TRACE("X509_delete_ext(%p, %p) => oidString == null", x509, oidString);
return;
}
Unique_ASN1_OBJECT obj(OBJ_txt2obj(oid.c_str(), 1 /* allow numerical form only */));
if (obj.get() == NULL) {
JNI_TRACE("X509_delete_ext(%p, %s) => oid conversion failed", x509, oid.c_str());
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Invalid OID.");
return;
}
int extIndex = X509_get_ext_by_OBJ(x509, obj.get(), -1);
if (extIndex == -1) {
JNI_TRACE("X509_delete_ext(%p, %s) => ext not found", x509, oid.c_str());
return;
}
X509_EXTENSION* ext = X509_delete_ext(x509, extIndex);
if (ext != NULL) {
X509_EXTENSION_free(ext);
// Invalidate the cached encoding
#if defined(OPENSSL_IS_BORINGSSL)
X509_CINF_set_modified(X509_get_cert_info(x509));
#else
x509->cert_info->enc.modified = 1;
#endif
}
}
static jint NativeCrypto_get_X509_hashCode(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_hashCode(%p) => x509 == null", x509);
return 0;
}
// Force caching extensions.
X509_check_ca(x509);
jint hashCode = 0L;
for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
hashCode = 31 * hashCode + x509->sha1_hash[i];
}
return hashCode;
}
static void NativeCrypto_X509_print_ex(JNIEnv* env, jclass, jlong bioRef, jlong x509Ref,
jlong nmflagJava, jlong certflagJava) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bioRef));
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
long nmflag = static_cast<long>(nmflagJava);
long certflag = static_cast<long>(certflagJava);
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld)", bio, x509, nmflag, certflag);
if (bio == NULL) {
jniThrowNullPointerException(env, "bio == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => bio == null", bio, x509, nmflag, certflag);
return;
}
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => x509 == null", bio, x509, nmflag, certflag);
return;
}
if (!X509_print_ex(bio, x509, nmflag, certflag)) {
throwExceptionIfNecessary(env, "X509_print_ex");
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => threw error", bio, x509, nmflag, certflag);
} else {
JNI_TRACE("X509_print_ex(%p, %p, %ld, %ld) => success", bio, x509, nmflag, certflag);
}
}
static jlong NativeCrypto_X509_get_pubkey(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_pubkey(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("X509_get_pubkey(%p) => x509 == null", x509);
return 0;
}
Unique_EVP_PKEY pkey(X509_get_pubkey(x509));
if (pkey.get() == NULL) {
#if defined(OPENSSL_IS_BORINGSSL)
const uint32_t last_error = ERR_peek_last_error();
const uint32_t first_error = ERR_peek_error();
if ((ERR_GET_LIB(last_error) == ERR_LIB_EVP &&
ERR_GET_REASON(last_error) == EVP_R_UNKNOWN_PUBLIC_KEY_TYPE) ||
(ERR_GET_LIB(first_error) == ERR_LIB_EC &&
ERR_GET_REASON(first_error) == EC_R_UNKNOWN_GROUP)) {
freeOpenSslErrorState();
throwNoSuchAlgorithmException(env, "X509_get_pubkey");
return 0;
}
#endif
throwExceptionIfNecessary(env, "X509_get_pubkey");
return 0;
}
JNI_TRACE("X509_get_pubkey(%p) => %p", x509, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}
static jbyteArray NativeCrypto_X509_get_issuer_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_issuer_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_issuer_name(x509), i2d_X509_NAME);
}
static jbyteArray NativeCrypto_X509_get_subject_name(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_subject_name(%p)", x509);
return ASN1ToByteArray<X509_NAME>(env, X509_get_subject_name(x509), i2d_X509_NAME);
}
static jstring NativeCrypto_get_X509_pubkey_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_pubkey_oid(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_pubkey_oid(%p) => x509 == null", x509);
return NULL;
}
X509_PUBKEY* pubkey = X509_get_X509_PUBKEY(x509);
return ASN1_OBJECT_to_OID_string(env, pubkey->algor->algorithm);
}
static jstring NativeCrypto_get_X509_sig_alg_oid(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_oid(%p)", x509);
if (x509 == NULL || x509->sig_alg == NULL) {
jniThrowNullPointerException(env, "x509 == NULL || x509->sig_alg == NULL");
JNI_TRACE("get_X509_sig_alg_oid(%p) => x509 == NULL", x509);
return NULL;
}
return ASN1_OBJECT_to_OID_string(env, x509->sig_alg->algorithm);
}
static jbyteArray NativeCrypto_get_X509_sig_alg_parameter(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_sig_alg_parameter(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_sig_alg_parameter(%p) => x509 == null", x509);
return NULL;
}
if (x509->sig_alg->parameter == NULL) {
JNI_TRACE("get_X509_sig_alg_parameter(%p) => null", x509);
return NULL;
}
return ASN1ToByteArray<ASN1_TYPE>(env, x509->sig_alg->parameter, i2d_ASN1_TYPE);
}
static jbooleanArray NativeCrypto_get_X509_issuerUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_issuerUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_issuerUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->issuerUID == NULL) {
JNI_TRACE("get_X509_issuerUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->issuerUID);
}
static jbooleanArray NativeCrypto_get_X509_subjectUID(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_subjectUID(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_subjectUID(%p) => x509 == null", x509);
return NULL;
}
if (x509->cert_info->subjectUID == NULL) {
JNI_TRACE("get_X509_subjectUID(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, x509->cert_info->subjectUID);
}
static jbooleanArray NativeCrypto_get_X509_ex_kusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_kusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_kusage(%p) => x509 == null", x509);
return NULL;
}
Unique_ASN1_BIT_STRING bitStr(static_cast<ASN1_BIT_STRING*>(
X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL)));
if (bitStr.get() == NULL) {
JNI_TRACE("get_X509_ex_kusage(%p) => null", x509);
return NULL;
}
return ASN1BitStringToBooleanArray(env, bitStr.get());
}
static jobjectArray NativeCrypto_get_X509_ex_xkusage(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_xkusage(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_xkusage(%p) => x509 == null", x509);
return NULL;
}
Unique_sk_ASN1_OBJECT objArray(static_cast<STACK_OF(ASN1_OBJECT)*>(
X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL)));
if (objArray.get() == NULL) {
JNI_TRACE("get_X509_ex_xkusage(%p) => null", x509);
return NULL;
}
size_t size = sk_ASN1_OBJECT_num(objArray.get());
ScopedLocalRef<jobjectArray> exKeyUsage(env, env->NewObjectArray(size, stringClass, NULL));
if (exKeyUsage.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
ScopedLocalRef<jstring> oidStr(env, ASN1_OBJECT_to_OID_string(env,
sk_ASN1_OBJECT_value(objArray.get(), i)));
env->SetObjectArrayElement(exKeyUsage.get(), i, oidStr.get());
}
JNI_TRACE("get_X509_ex_xkusage(%p) => success (%zd entries)", x509, size);
return exKeyUsage.release();
}
static jint NativeCrypto_get_X509_ex_pathlen(JNIEnv* env, jclass, jlong x509Ref) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509_ex_pathlen(%p)", x509);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509_ex_pathlen(%p) => x509 == null", x509);
return 0;
}
/* Just need to do this to cache the ex_* values. */
X509_check_ca(x509);
JNI_TRACE("get_X509_ex_pathlen(%p) => %ld", x509, x509->ex_pathlen);
return x509->ex_pathlen;
}
static jbyteArray NativeCrypto_X509_get_ext_oid(JNIEnv* env, jclass, jlong x509Ref,
jstring oidString) {
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("X509_get_ext_oid(%p, %p)", x509, oidString);
return X509Type_get_ext_oid<X509, X509_get_ext_by_OBJ, X509_get_ext>(env, x509, oidString);
}
static jbyteArray NativeCrypto_X509_CRL_get_ext_oid(JNIEnv* env, jclass, jlong x509CrlRef,
jstring oidString) {
X509_CRL* crl = reinterpret_cast<X509_CRL*>(static_cast<uintptr_t>(x509CrlRef));
JNI_TRACE("X509_CRL_get_ext_oid(%p, %p)", crl, oidString);
return X509Type_get_ext_oid<X509_CRL, X509_CRL_get_ext_by_OBJ, X509_CRL_get_ext>(env, crl,
oidString);
}
static jbyteArray NativeCrypto_X509_REVOKED_get_ext_oid(JNIEnv* env, jclass, jlong x509RevokedRef,
jstring oidString) {
X509_REVOKED* revoked = reinterpret_cast<X509_REVOKED*>(static_cast<uintptr_t>(x509RevokedRef));
JNI_TRACE("X509_REVOKED_get_ext_oid(%p, %p)", revoked, oidString);
return X509Type_get_ext_oid<X509_REVOKED, X509_REVOKED_get_ext_by_OBJ, X509_REVOKED_get_ext>(
env, revoked, oidString);
}
template<typename T, int (*get_ext_by_critical_func)(T*, int, int), X509_EXTENSION* (*get_ext_func)(T*, int)>
static jobjectArray get_X509Type_ext_oids(JNIEnv* env, jlong x509Ref, jint critical) {
T* x509 = reinterpret_cast<T*>(static_cast<uintptr_t>(x509Ref));
JNI_TRACE("get_X509Type_ext_oids(%p, %d)", x509, critical);
if (x509 == NULL) {
jniThrowNullPointerException(env, "x509 == null");
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => x509 == null", x509, critical);
return NULL;
}
int lastPos = -1;
int count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
count++;
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) has %d entries", x509, critical, count);
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, stringClass, NULL));
if (joa.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => fail to allocate result array", x509, critical);
return NULL;
}
lastPos = -1;
count = 0;
while ((lastPos = get_ext_by_critical_func(x509, critical, lastPos)) != -1) {
X509_EXTENSION* ext = get_ext_func(x509, lastPos);
ScopedLocalRef<jstring> extOid(env, ASN1_OBJECT_to_OID_string(env, ext->object));
if (extOid.get() == NULL) {
JNI_TRACE("get_X509Type_ext_oids(%p) => couldn't get OID", x509);
return NULL;
}
env->SetObjectArrayElement(joa.get(), count++, extOid.get());
}
JNI_TRACE("get_X509Type_ext_oids(%p, %d) => success", x509, critical);
return joa.release();
}
static jobjectArray NativeCrypto_get_X509_ext_oids(JNIEnv* env, jclass, jlong x509Ref,
jint critical) {
JNI_TRACE("get_X509_ext_oids(0x%llx, %d)", (long long) x509Ref, critical);
return get_X509Type_ext_oids<X509, X509_get_ext_by_critical, X509_get_ext>(env, x509Ref,
critical);
}
static jobjectArray NativeCrypto_get_X509_CRL_ext_oids(JNIEnv* env, jclass, jlong x509CrlRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509CrlRef, critical);
return get_X509Type_ext_oids<X509_CRL, X509_CRL_get_ext_by_critical, X509_CRL_get_ext>(env,
x509CrlRef, critical);
}
static jobjectArray NativeCrypto_get_X509_REVOKED_ext_oids(JNIEnv* env, jclass, jlong x509RevokedRef,
jint critical) {
JNI_TRACE("get_X509_CRL_ext_oids(0x%llx, %d)", (long long) x509RevokedRef, critical);
return get_X509Type_ext_oids<X509_REVOKED, X509_REVOKED_get_ext_by_critical,
X509_REVOKED_get_ext>(env, x509RevokedRef, critical);
}
#ifdef WITH_JNI_TRACE
/**
* Based on example logging call back from SSL_CTX_set_info_callback man page
*/
static void info_callback_LOG(const SSL* s __attribute__ ((unused)), int where, int ret)
{
int w = where & ~SSL_ST_MASK;
const char* str;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
} else {
str = "undefined";
}
if (where & SSL_CB_LOOP) {
JNI_TRACE("ssl=%p %s:%s %s", s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
JNI_TRACE("ssl=%p SSL3 alert %s:%s:%s %s %s",
s,
str,
SSL_alert_type_string(ret),
SSL_alert_desc_string(ret),
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
JNI_TRACE("ssl=%p %s:failed exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret < 0) {
JNI_TRACE("ssl=%p %s:error exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else if (ret == 1) {
JNI_TRACE("ssl=%p %s:ok exit in %s %s",
s, str, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown exit %d in %s %s",
s, str, ret, SSL_state_string(s), SSL_state_string_long(s));
}
} else if (where & SSL_CB_HANDSHAKE_START) {
JNI_TRACE("ssl=%p handshake start in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else if (where & SSL_CB_HANDSHAKE_DONE) {
JNI_TRACE("ssl=%p handshake done in %s %s",
s, SSL_state_string(s), SSL_state_string_long(s));
} else {
JNI_TRACE("ssl=%p %s:unknown where %d in %s %s",
s, str, where, SSL_state_string(s), SSL_state_string_long(s));
}
}
#endif
/**
* Returns an array containing all the X509 certificate references
*/
static jlongArray getCertificateRefs(JNIEnv* env, const STACK_OF(X509)* chain)
{
if (chain == NULL) {
// Chain can be NULL if the associated cipher doesn't do certs.
return NULL;
}
ssize_t count = sk_X509_num(chain);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jlongArray> refArray(env, env->NewLongArray(count));
ScopedLongArrayRW refs(env, refArray.get());
if (refs.get() == NULL) {
return NULL;
}
for (ssize_t i = 0; i < count; i++) {
refs[i] = reinterpret_cast<uintptr_t>(X509_dup_nocopy(sk_X509_value(chain, i)));
}
return refArray.release();
}
/**
* Returns an array containing all the X500 principal's bytes.
*/
static jobjectArray getPrincipalBytes(JNIEnv* env, const STACK_OF(X509_NAME)* names)
{
if (names == NULL) {
return NULL;
}
int count = sk_X509_NAME_num(names);
if (count <= 0) {
return NULL;
}
ScopedLocalRef<jobjectArray> joa(env, env->NewObjectArray(count, byteArrayClass, NULL));
if (joa.get() == NULL) {
return NULL;
}
for (int i = 0; i < count; i++) {
X509_NAME* principal = sk_X509_NAME_value(names, i);
ScopedLocalRef<jbyteArray> byteArray(env, ASN1ToByteArray<X509_NAME>(env,
principal, i2d_X509_NAME));
if (byteArray.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(joa.get(), i, byteArray.get());
}
return joa.release();
}
/**
* Our additional application data needed for getting synchronization right.
* This maybe warrants a bit of lengthy prose:
*
* (1) We use a flag to reflect whether we consider the SSL connection alive.
* Any read or write attempt loops will be cancelled once this flag becomes 0.
*
* (2) We use an int to count the number of threads that are blocked by the
* underlying socket. This may be at most two (one reader and one writer), since
* the Java layer ensures that no more threads will enter the native code at the
* same time.
*
* (3) The pipe is used primarily as a means of cancelling a blocking select()
* when we want to close the connection (aka "emergency button"). It is also
* necessary for dealing with a possible race condition situation: There might
* be cases where both threads see an SSL_ERROR_WANT_READ or
* SSL_ERROR_WANT_WRITE. Both will enter a select() with the proper argument.
* If one leaves the select() successfully before the other enters it, the
* "success" event is already consumed and the second thread will be blocked,
* possibly forever (depending on network conditions).
*
* The idea for solving the problem looks like this: Whenever a thread is
* successful in moving around data on the network, and it knows there is
* another thread stuck in a select(), it will write a byte to the pipe, waking
* up the other thread. A thread that returned from select(), on the other hand,
* knows whether it's been woken up by the pipe. If so, it will consume the
* byte, and the original state of affairs has been restored.
*
* The pipe may seem like a bit of overhead, but it fits in nicely with the
* other file descriptors of the select(), so there's only one condition to wait
* for.
*
* (4) Finally, a mutex is needed to make sure that at most one thread is in
* either SSL_read() or SSL_write() at any given time. This is an OpenSSL
* requirement. We use the same mutex to guard the field for counting the
* waiting threads.
*
* Note: The current implementation assumes that we don't have to deal with
* problems induced by multiple cores or processors and their respective
* memory caches. One possible problem is that of inconsistent views on the
* "aliveAndKicking" field. This could be worked around by also enclosing all
* accesses to that field inside a lock/unlock sequence of our mutex, but
* currently this seems a bit like overkill. Marking volatile at the very least.
*
* During handshaking, additional fields are used to up-call into
* Java to perform certificate verification and handshake
* completion. These are also used in any renegotiation.
*
* (5) the JNIEnv so we can invoke the Java callback
*
* (6) a NativeCrypto.SSLHandshakeCallbacks instance for callbacks from native to Java
*
* (7) a java.io.FileDescriptor wrapper to check for socket close
*
* We store the NPN protocols list so we can either send it (from the server) or
* select a protocol (on the client). We eagerly acquire a pointer to the array
* data so the callback doesn't need to acquire resources that it cannot
* release.
*
* Because renegotiation can be requested by the peer at any time,
* care should be taken to maintain an appropriate JNIEnv on any
* downcall to openssl since it could result in an upcall to Java. The
* current code does try to cover these cases by conditionally setting
* the JNIEnv on calls that can read and write to the SSL such as
* SSL_do_handshake, SSL_read, SSL_write, and SSL_shutdown.
*
* Finally, we have two emphemeral keys setup by OpenSSL callbacks:
*
* (8) a set of ephemeral RSA keys that is lazily generated if a peer
* wants to use an exportable RSA cipher suite.
*
* (9) a set of ephemeral EC keys that is lazily generated if a peer
* wants to use an TLS_ECDHE_* cipher suite.
*
*/
class AppData {
public:
volatile int aliveAndKicking;
int waitingThreads;
int fdsEmergency[2];
MUTEX_TYPE mutex;
JNIEnv* env;
jobject sslHandshakeCallbacks;
jbyteArray npnProtocolsArray;
jbyte* npnProtocolsData;
size_t npnProtocolsLength;
jbyteArray alpnProtocolsArray;
jbyte* alpnProtocolsData;
size_t alpnProtocolsLength;
Unique_RSA ephemeralRsa;
/**
* Creates the application data context for the SSL*.
*/
public:
static AppData* create() {
UniquePtr<AppData> appData(new AppData());
if (pipe(appData.get()->fdsEmergency) == -1) {
ALOGE("AppData::create pipe(2) failed: %s", strerror(errno));
return NULL;
}
if (!setBlocking(appData.get()->fdsEmergency[0], false)) {
ALOGE("AppData::create fcntl(2) failed: %s", strerror(errno));
return NULL;
}
if (MUTEX_SETUP(appData.get()->mutex) == -1) {
ALOGE("pthread_mutex_init(3) failed: %s", strerror(errno));
return NULL;
}
return appData.release();
}
~AppData() {
aliveAndKicking = 0;
if (fdsEmergency[0] != -1) {
close(fdsEmergency[0]);
}
if (fdsEmergency[1] != -1) {
close(fdsEmergency[1]);
}
clearCallbackState();
MUTEX_CLEANUP(mutex);
}
private:
AppData() :
aliveAndKicking(1),
waitingThreads(0),
env(NULL),
sslHandshakeCallbacks(NULL),
npnProtocolsArray(NULL),
npnProtocolsData(NULL),
npnProtocolsLength(-1),
alpnProtocolsArray(NULL),
alpnProtocolsData(NULL),
alpnProtocolsLength(-1),
ephemeralRsa(NULL) {
fdsEmergency[0] = -1;
fdsEmergency[1] = -1;
}
public:
/**
* Used to set the SSL-to-Java callback state before each SSL_*
* call that may result in a callback. It should be cleared after
* the operation returns with clearCallbackState.
*
* @param env The JNIEnv
* @param shc The SSLHandshakeCallbacks
* @param fd The FileDescriptor
* @param npnProtocols NPN protocols so that they may be advertised (by the
* server) or selected (by the client). Has no effect
* unless NPN is enabled.
* @param alpnProtocols ALPN protocols so that they may be advertised (by the
* server) or selected (by the client). Passing non-NULL
* enables ALPN.
*/
bool setCallbackState(JNIEnv* e, jobject shc, jobject fd, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
UniquePtr<NetFd> netFd;
if (fd != NULL) {
netFd.reset(new NetFd(e, fd));
if (netFd->isClosed()) {
JNI_TRACE("appData=%p setCallbackState => netFd->isClosed() == true", this);
return false;
}
}
env = e;
sslHandshakeCallbacks = shc;
if (npnProtocols != NULL) {
npnProtocolsData = e->GetByteArrayElements(npnProtocols, NULL);
if (npnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => npnProtocolsData == NULL", this);
return false;
}
npnProtocolsArray = npnProtocols;
npnProtocolsLength = e->GetArrayLength(npnProtocols);
}
if (alpnProtocols != NULL) {
alpnProtocolsData = e->GetByteArrayElements(alpnProtocols, NULL);
if (alpnProtocolsData == NULL) {
clearCallbackState();
JNI_TRACE("appData=%p setCallbackState => alpnProtocolsData == NULL", this);
return false;
}
alpnProtocolsArray = alpnProtocols;
alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
}
return true;
}
void clearCallbackState() {
sslHandshakeCallbacks = NULL;
if (npnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(npnProtocolsArray, npnProtocolsData, JNI_ABORT);
npnProtocolsArray = NULL;
npnProtocolsData = NULL;
npnProtocolsLength = -1;
}
if (alpnProtocolsArray != NULL) {
env->ReleaseByteArrayElements(alpnProtocolsArray, alpnProtocolsData, JNI_ABORT);
alpnProtocolsArray = NULL;
alpnProtocolsData = NULL;
alpnProtocolsLength = -1;
}
env = NULL;
}
};
/**
* Dark magic helper function that checks, for a given SSL session, whether it
* can SSL_read() or SSL_write() without blocking. Takes into account any
* concurrent attempts to close the SSLSocket from the Java side. This is
* needed to get rid of the hangs that occur when thread #1 closes the SSLSocket
* while thread #2 is sitting in a blocking read or write. The type argument
* specifies whether we are waiting for readability or writability. It expects
* to be passed either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, since we
* only need to wait in case one of these problems occurs.
*
* @param env
* @param type Either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
* @param fdObject The FileDescriptor, since appData->fileDescriptor should be NULL
* @param appData The application data structure with mutex info etc.
* @param timeout_millis The timeout value for poll call, with the special value
* 0 meaning no timeout at all (wait indefinitely). Note: This is
* the Java semantics of the timeout value, not the usual
* poll() semantics.
* @return The result of the inner poll() call,
* THROW_SOCKETEXCEPTION if a SocketException was thrown, -1 on
* additional errors
*/
static int sslSelect(JNIEnv* env, int type, jobject fdObject, AppData* appData, int timeout_millis) {
// This loop is an expanded version of the NET_FAILURE_RETRY
// macro. It cannot simply be used in this case because poll
// cannot be restarted without recreating the pollfd structure.
int result;
struct pollfd fds[2];
do {
NetFd fd(env, fdObject);
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
int intFd = fd.get();
JNI_TRACE("sslSelect type=%s fd=%d appData=%p timeout_millis=%d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE", intFd, appData, timeout_millis);
memset(&fds, 0, sizeof(fds));
fds[0].fd = intFd;
if (type == SSL_ERROR_WANT_READ) {
fds[0].events = POLLIN | POLLPRI;
} else {
fds[0].events = POLLOUT | POLLPRI;
}
fds[1].fd = appData->fdsEmergency[0];
fds[1].events = POLLIN | POLLPRI;
// Converting from Java semantics to Posix semantics.
if (timeout_millis <= 0) {
timeout_millis = -1;
}
#ifndef CONSCRYPT_UNBUNDLED
AsynchronousCloseMonitor monitor(intFd);
#else
CompatibilityCloseMonitor monitor(intFd);
#endif
result = poll(fds, sizeof(fds)/sizeof(fds[0]), timeout_millis);
JNI_TRACE("sslSelect %s fd=%d appData=%p timeout_millis=%d => %d",
(type == SSL_ERROR_WANT_READ) ? "READ" : "WRITE",
fd.get(), appData, timeout_millis, result);
if (result == -1) {
if (fd.isClosed()) {
result = THROWN_EXCEPTION;
break;
}
if (errno != EINTR) {
break;
}
}
} while (result == -1);
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (result > 0) {
// We have been woken up by a token in the emergency pipe. We
// can't be sure the token is still in the pipe at this point
// because it could have already been read by the thread that
// originally wrote it if it entered sslSelect and acquired
// the mutex before we did. Thus we cannot safely read from
// the pipe in a blocking way (so we make the pipe
// non-blocking at creation).
if (fds[1].revents & POLLIN) {
char token;
do {
(void) read(appData->fdsEmergency[0], &token, 1);
} while (errno == EINTR);
}
}
// Tell the world that there is now one thread less waiting for the
// underlying network.
appData->waitingThreads--;
MUTEX_UNLOCK(appData->mutex);
return result;
}
/**
* Helper function that wakes up a thread blocked in select(), in case there is
* one. Is being called by sslRead() and sslWrite() as well as by JNI glue
* before closing the connection.
*
* @param data The application data structure with mutex info etc.
*/
static void sslNotify(AppData* appData) {
// Write a byte to the emergency pipe, so a concurrent select() can return.
// Note we have to restore the errno of the original system call, since the
// caller relies on it for generating error messages.
int errnoBackup = errno;
char token = '*';
do {
errno = 0;
(void) write(appData->fdsEmergency[1], &token, 1);
} while (errno == EINTR);
errno = errnoBackup;
}
static AppData* toAppData(const SSL* ssl) {
return reinterpret_cast<AppData*>(SSL_get_app_data(ssl));
}
/**
* Verify the X509 certificate via SSL_CTX_set_cert_verify_callback
*/
static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg __attribute__ ((unused)))
{
/* Get the correct index to the SSLobject stored into X509_STORE_CTX. */
SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_store_ctx,
SSL_get_ex_data_X509_STORE_CTX_idx()));
JNI_TRACE("ssl=%p cert_verify_callback x509_store_ctx=%p arg=%p", ssl, x509_store_ctx, arg);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in cert_verify_callback");
JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "verifyCertificateChain", "(J[JLjava/lang/String;)V");
jlongArray refArray = getCertificateRefs(env, x509_store_ctx->untrusted);
#if !defined(OPENSSL_IS_BORINGSSL)
const char* authMethod = SSL_authentication_method(ssl);
#else
const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
const char *authMethod = SSL_CIPHER_get_kx_name(cipher);
#endif
JNI_TRACE("ssl=%p cert_verify_callback calling verifyCertificateChain authMethod=%s",
ssl, authMethod);
jstring authMethodString = env->NewStringUTF(authMethod);
env->CallVoidMethod(sslHandshakeCallbacks, methodID,
static_cast<jlong>(reinterpret_cast<uintptr_t>(SSL_get1_session(ssl))), refArray,
authMethodString);
int result = (env->ExceptionCheck()) ? 0 : 1;
JNI_TRACE("ssl=%p cert_verify_callback => %d", ssl, result);
return result;
}
/**
* Call back to watch for handshake to be completed. This is necessary
* for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake
* returns before the handshake is completed in this case.
*/
static void info_callback(const SSL* ssl, int where, int ret) {
JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret);
#ifdef WITH_JNI_TRACE
info_callback_LOG(ssl, where, ret);
#endif
if (!(where & SSL_CB_HANDSHAKE_DONE) && !(where & SSL_CB_HANDSHAKE_START)) {
JNI_TRACE("ssl=%p info_callback ignored", ssl);
return;
}
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in info_callback");
JNI_TRACE("ssl=%p info_callback env error", ssl);
return;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback already pending exception", ssl);
return;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(cls, "onSSLStateChange", "(JII)V");
JNI_TRACE("ssl=%p info_callback calling onSSLStateChange", ssl);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, reinterpret_cast<jlong>(ssl), where, ret);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback exception", ssl);
}
JNI_TRACE("ssl=%p info_callback completed", ssl);
}
/**
* Call back to ask for a client certificate. There are three possible exit codes:
*
* 1 is success. x509Out and pkeyOut should point to the correct private key and certificate.
* 0 is unable to find key. x509Out and pkeyOut should be NULL.
* -1 is error and it doesn't matter what x509Out and pkeyOut are.
*/
static int client_cert_cb(SSL* ssl, X509** x509Out, EVP_PKEY** pkeyOut) {
JNI_TRACE("ssl=%p client_cert_cb x509Out=%p pkeyOut=%p", ssl, x509Out, pkeyOut);
/* Clear output of key and certificate in case of early exit due to error. */
*x509Out = NULL;
*pkeyOut = NULL;
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in client_cert_cb");
JNI_TRACE("ssl=%p client_cert_cb env error => 0", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb already pending exception => 0", ssl);
return -1;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID
= env->GetMethodID(cls, "clientCertificateRequested", "([B[[B)V");
// Call Java callback which can use SSL_use_certificate and SSL_use_PrivateKey to set values
#if !defined(OPENSSL_IS_BORINGSSL)
const char* ctype = NULL;
char ssl2_ctype = SSL3_CT_RSA_SIGN;
int ctype_num = 0;
jobjectArray issuers = NULL;
switch (ssl->version) {
case SSL2_VERSION:
ctype = &ssl2_ctype;
ctype_num = 1;
break;
case SSL3_VERSION:
case TLS1_VERSION:
case TLS1_1_VERSION:
case TLS1_2_VERSION:
case DTLS1_VERSION:
ctype = ssl->s3->tmp.ctype;
ctype_num = ssl->s3->tmp.ctype_num;
issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
break;
}
#else
const uint8_t* ctype = NULL;
int ctype_num = SSL_get0_certificate_types(ssl, &ctype);
jobjectArray issuers = getPrincipalBytes(env, ssl->s3->tmp.ca_names);
#endif
#ifdef WITH_JNI_TRACE
for (int i = 0; i < ctype_num; i++) {
JNI_TRACE("ssl=%p clientCertificateRequested keyTypes[%d]=%d", ssl, i, ctype[i]);
}
#endif
jbyteArray keyTypes = env->NewByteArray(ctype_num);
if (keyTypes == NULL) {
JNI_TRACE("ssl=%p client_cert_cb bytes == null => 0", ssl);
return 0;
}
env->SetByteArrayRegion(keyTypes, 0, ctype_num, reinterpret_cast<const jbyte*>(ctype));
JNI_TRACE("ssl=%p clientCertificateRequested calling clientCertificateRequested "
"keyTypes=%p issuers=%p", ssl, keyTypes, issuers);
env->CallVoidMethod(sslHandshakeCallbacks, methodID, keyTypes, issuers);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p client_cert_cb exception => 0", ssl);
return -1;
}
// Check for values set from Java
X509* certificate = SSL_get_certificate(ssl);
EVP_PKEY* privatekey = SSL_get_privatekey(ssl);
int result = 0;
if (certificate != NULL && privatekey != NULL) {
*x509Out = certificate;
*pkeyOut = privatekey;
result = 1;
} else {
// Some error conditions return NULL, so make sure it doesn't linger.
freeOpenSslErrorState();
}
JNI_TRACE("ssl=%p client_cert_cb => *x509=%p *pkey=%p %d", ssl, *x509Out, *pkeyOut, result);
return result;
}
/**
* Pre-Shared Key (PSK) client callback.
*/
static unsigned int psk_client_callback(SSL* ssl, const char *hint,
char *identity, unsigned int max_identity_len,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_client_callback");
JNI_TRACE("ssl=%p psk_client_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID =
env->GetMethodID(cls, "clientPSKKeyRequested", "(Ljava/lang/String;[B[B)I");
JNI_TRACE("ssl=%p psk_client_callback calling clientPSKKeyRequested", ssl);
ScopedLocalRef<jstring> identityHintJava(
env,
(hint != NULL) ? env->NewStringUTF(hint) : NULL);
ScopedLocalRef<jbyteArray> identityJava(env, env->NewByteArray(max_identity_len));
if (identityJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate identity bufffer", ssl);
return 0;
}
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_client_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_client_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
ScopedByteArrayRO identityJavaRo(env, identityJava.get());
if (identityJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_client_callback failed to get identity bytes", ssl);
return 0;
}
memcpy(identity, identityJavaRo.get(), max_identity_len);
JNI_TRACE("ssl=%p psk_client_callback completed", ssl);
return keyLen;
}
/**
* Pre-Shared Key (PSK) server callback.
*/
static unsigned int psk_server_callback(SSL* ssl, const char *identity,
unsigned char *psk, unsigned int max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback", ssl);
AppData* appData = toAppData(ssl);
JNIEnv* env = appData->env;
if (env == NULL) {
ALOGE("AppData->env missing in psk_server_callback");
JNI_TRACE("ssl=%p psk_server_callback env error", ssl);
return 0;
}
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback already pending exception", ssl);
return 0;
}
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
jmethodID methodID = env->GetMethodID(
cls, "serverPSKKeyRequested", "(Ljava/lang/String;Ljava/lang/String;[B)I");
JNI_TRACE("ssl=%p psk_server_callback calling serverPSKKeyRequested", ssl);
const char* identityHint = SSL_get_psk_identity_hint(ssl);
// identityHint = NULL;
// identity = NULL;
ScopedLocalRef<jstring> identityHintJava(
env,
(identityHint != NULL) ? env->NewStringUTF(identityHint) : NULL);
ScopedLocalRef<jstring> identityJava(
env,
(identity != NULL) ? env->NewStringUTF(identity) : NULL);
ScopedLocalRef<jbyteArray> keyJava(env, env->NewByteArray(max_psk_len));
if (keyJava.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to allocate key bufffer", ssl);
return 0;
}
jint keyLen = env->CallIntMethod(sslHandshakeCallbacks, methodID,
identityHintJava.get(), identityJava.get(), keyJava.get());
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p psk_server_callback exception", ssl);
return 0;
}
if (keyLen <= 0) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key", ssl);
return 0;
} else if ((unsigned int) keyLen > max_psk_len) {
JNI_TRACE("ssl=%p psk_server_callback got key which is too long", ssl);
return 0;
}
ScopedByteArrayRO keyJavaRo(env, keyJava.get());
if (keyJavaRo.get() == NULL) {
JNI_TRACE("ssl=%p psk_server_callback failed to get key bytes", ssl);
return 0;
}
memcpy(psk, keyJavaRo.get(), keyLen);
JNI_TRACE("ssl=%p psk_server_callback completed", ssl);
return keyLen;
}
static RSA* rsaGenerateKey(int keylength) {
Unique_BIGNUM bn(BN_new());
if (bn.get() == NULL) {
return NULL;
}
int setWordResult = BN_set_word(bn.get(), RSA_F4);
if (setWordResult != 1) {
return NULL;
}
Unique_RSA rsa(RSA_new());
if (rsa.get() == NULL) {
return NULL;
}
int generateResult = RSA_generate_key_ex(rsa.get(), keylength, bn.get(), NULL);
if (generateResult != 1) {
return NULL;
}
return rsa.release();
}
/**
* Call back to ask for an ephemeral RSA key for SSL_RSA_EXPORT_WITH_RC4_40_MD5 (aka EXP-RC4-MD5)
*/
static RSA* tmp_rsa_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_rsa_callback is_export=%d keylength=%d", ssl, is_export, keylength);
AppData* appData = toAppData(ssl);
if (appData->ephemeralRsa.get() == NULL) {
JNI_TRACE("ssl=%p tmp_rsa_callback generating ephemeral RSA key", ssl);
appData->ephemeralRsa.reset(rsaGenerateKey(keylength));
}
JNI_TRACE("ssl=%p tmp_rsa_callback => %p", ssl, appData->ephemeralRsa.get());
return appData->ephemeralRsa.get();
}
static DH* dhGenerateParameters(int keylength) {
#if !defined(OPENSSL_IS_BORINGSSL)
/*
* The SSL_CTX_set_tmp_dh_callback(3SSL) man page discusses two
* different options for generating DH keys. One is generating the
* keys using a single set of DH parameters. However, generating
* DH parameters is slow enough (minutes) that they suggest doing
* it once at install time. The other is to generate DH keys from
* DSA parameters. Generating DSA parameters is faster than DH
* parameters, but to prevent small subgroup attacks, they needed
* to be regenerated for each set of DH keys. Setting the
* SSL_OP_SINGLE_DH_USE option make sure OpenSSL will call back
* for new DH parameters every type it needs to generate DH keys.
*/
// Fast path but must have SSL_OP_SINGLE_DH_USE set
Unique_DSA dsa(DSA_new());
if (!DSA_generate_parameters_ex(dsa.get(), keylength, NULL, 0, NULL, NULL, NULL)) {
return NULL;
}
DH* dh = DSA_dup_DH(dsa.get());
return dh;
#else
/* At the time of writing, OpenSSL and BoringSSL are hard coded to request
* a 1024-bit DH. */
if (keylength <= 1024) {
return DH_get_1024_160(NULL);
}
if (keylength <= 2048) {
return DH_get_2048_224(NULL);
}
/* In the case of a large request, return the strongest DH group that
* we have predefined. Generating a group takes far too long to be
* reasonable. */
return DH_get_2048_256(NULL);
#endif
}
/**
* Call back to ask for Diffie-Hellman parameters
*/
static DH* tmp_dh_callback(SSL* ssl __attribute__ ((unused)),
int is_export __attribute__ ((unused)),
int keylength) {
JNI_TRACE("ssl=%p tmp_dh_callback is_export=%d keylength=%d", ssl, is_export, keylength);
DH* tmp_dh = dhGenerateParameters(keylength);
JNI_TRACE("ssl=%p tmp_dh_callback => %p", ssl, tmp_dh);
return tmp_dh;
}
/*
* public static native int SSL_CTX_new();
*/
static jlong NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass) {
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
if (sslCtx.get() == NULL) {
throwExceptionIfNecessary(env, "SSL_CTX_new");
return 0;
}
SSL_CTX_set_options(sslCtx.get(),
SSL_OP_ALL
// Note: We explicitly do not allow SSLv2 to be used.
| SSL_OP_NO_SSLv2
// We also disable session tickets for better compatibility b/2682876
| SSL_OP_NO_TICKET
// We also disable compression for better compatibility b/2710492 b/2710497
| SSL_OP_NO_COMPRESSION
// Because dhGenerateParameters uses DSA_generate_parameters_ex
| SSL_OP_SINGLE_DH_USE
// Generate a fresh ECDH keypair for each key exchange.
| SSL_OP_SINGLE_ECDH_USE);
int mode = SSL_CTX_get_mode(sslCtx.get());
/*
* Turn on "partial write" mode. This means that SSL_write() will
* behave like Posix write() and possibly return after only
* writing a partial buffer. Note: The alternative, perhaps
* surprisingly, is not that SSL_write() always does full writes
* but that it will force you to retry write calls having
* preserved the full state of the original call. (This is icky
* and undesirable.)
*/
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
// Reuse empty buffers within the SSL_CTX to save memory
mode |= SSL_MODE_RELEASE_BUFFERS;
SSL_CTX_set_mode(sslCtx.get(), mode);
SSL_CTX_set_cert_verify_callback(sslCtx.get(), cert_verify_callback, NULL);
SSL_CTX_set_info_callback(sslCtx.get(), info_callback);
SSL_CTX_set_client_cert_cb(sslCtx.get(), client_cert_cb);
SSL_CTX_set_tmp_rsa_callback(sslCtx.get(), tmp_rsa_callback);
SSL_CTX_set_tmp_dh_callback(sslCtx.get(), tmp_dh_callback);
// If negotiating ECDH, use P-256.
Unique_EC_KEY ec(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (ec.get() == NULL) {
throwExceptionIfNecessary(env, "EC_KEY_new_by_curve_name");
return 0;
}
SSL_CTX_set_tmp_ecdh(sslCtx.get(), ec.get());
JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx.get());
return (jlong) sslCtx.release();
}
/**
* public static native void SSL_CTX_free(long ssl_ctx)
*/
static void NativeCrypto_SSL_CTX_free(JNIEnv* env,
jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_free(ssl_ctx);
}
static void NativeCrypto_SSL_CTX_set_session_id_context(JNIEnv* env, jclass,
jlong ssl_ctx_address, jbyteArray sid_ctx)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context sid_ctx=%p", ssl_ctx, sid_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO buf(env, sid_ctx);
if (buf.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => threw exception", ssl_ctx);
return;
}
unsigned int length = buf.size();
if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"length > SSL_MAX_SSL_SESSION_ID_LENGTH");
JNI_TRACE("NativeCrypto_SSL_CTX_set_session_id_context => length = %d", length);
return;
}
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buf.get());
int result = SSL_CTX_set_session_id_context(ssl_ctx, bytes, length);
if (result == 0) {
throwExceptionIfNecessary(env, "NativeCrypto_SSL_CTX_set_session_id_context");
return;
}
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_session_id_context => ok", ssl_ctx);
}
/**
* public static native int SSL_new(long ssl_ctx) throws SSLException;
*/
static jlong NativeCrypto_SSL_new(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new", ssl_ctx);
if (ssl_ctx == NULL) {
return 0;
}
Unique_SSL ssl(SSL_new(ssl_ctx));
if (ssl.get() == NULL) {
throwSSLExceptionWithSslErrors(env, NULL, SSL_ERROR_NONE,
"Unable to create SSL structure");
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
return 0;
}
/*
* Create our special application data.
*/
AppData* appData = AppData::create();
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to create application data");
freeOpenSslErrorState();
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new appData => 0", ssl_ctx);
return 0;
}
SSL_set_app_data(ssl.get(), reinterpret_cast<char*>(appData));
/*
* Java code in class OpenSSLSocketImpl does the verification. Since
* the callbacks do all the verification of the chain, this flag
* simply controls whether to send protocol-level alerts or not.
* SSL_VERIFY_NONE means don't send alerts and anything else means send
* alerts.
*/
SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => ssl=%p appData=%p", ssl_ctx, ssl.get(), appData);
return (jlong) ssl.release();
}
static void NativeCrypto_SSL_enable_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_enable_tls_channel_id", ssl);
if (ssl == NULL) {
return;
}
long ret = SSL_enable_tls_channel_id(ssl);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error enabling Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_tls_channel_id => error", ssl);
return;
}
}
static jbyteArray NativeCrypto_SSL_get_tls_channel_id(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id", ssl);
if (ssl == NULL) {
return NULL;
}
// Channel ID is 64 bytes long. Unfortunately, OpenSSL doesn't declare this length
// as a constant anywhere.
jbyteArray javaBytes = env->NewByteArray(64);
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => NULL", ssl);
return NULL;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
// Unfortunately, the SSL_get_tls_channel_id method below always returns 64 (upon success)
// regardless of the number of bytes copied into the output buffer "tmp". Thus, the correctness
// of this code currently relies on the "tmp" buffer being exactly 64 bytes long.
long ret = SSL_get_tls_channel_id(ssl, tmp, 64);
if (ret == 0) {
// Channel ID either not set or did not verify
JNI_TRACE("NativeCrypto_SSL_get_tls_channel_id(%p) => not available", ssl);
return NULL;
} else if (ret != 64) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error getting Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_tls_channel_id => error, returned %ld", ssl, ret);
return NULL;
}
JNI_TRACE("ssl=%p NativeCrypto_NativeCrypto_SSL_get_tls_channel_id() => %p", ssl, javaBytes);
return javaBytes;
}
static void NativeCrypto_SSL_set1_tls_channel_id(JNIEnv* env, jclass,
jlong ssl_address, jobject pkeyRef)
{
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => pkey == null", ssl);
return;
}
// SSL_set1_tls_channel_id requires ssl->server to be set to 0.
// Unfortunately, the default value is 1 and it's only changed to 0 just
// before the handshake starts (see NativeCrypto_SSL_do_handshake).
ssl->server = 0;
long ret = SSL_set1_tls_channel_id(ssl, pkey);
if (ret != 1L) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(
env, ssl, SSL_ERROR_NONE, "Error setting private key for Channel ID");
safeSslClear(ssl);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => error", ssl);
return;
}
// SSL_set1_tls_channel_id expects to take ownership of the EVP_PKEY, but
// we have an external reference from the caller such as an OpenSSLKey,
// so we manually increment the reference count here.
EVP_PKEY_up_ref(pkey);
JNI_TRACE("ssl=%p SSL_set1_tls_channel_id => ok", ssl);
}
static void NativeCrypto_SSL_use_PrivateKey(JNIEnv* env, jclass, jlong ssl_address,
jobject pkeyRef) {
SSL* ssl = to_SSL(env, ssl_address, true);
EVP_PKEY* pkey = fromContextObject<EVP_PKEY>(env, pkeyRef);
JNI_TRACE("ssl=%p SSL_use_PrivateKey privatekey=%p", ssl, pkey);
if (ssl == NULL) {
return;
}
if (pkey == NULL) {
JNI_TRACE("ssl=%p SSL_use_PrivateKey => pkey == null", ssl);
return;
}
int ret = SSL_use_PrivateKey(ssl, pkey);
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting private key");
safeSslClear(ssl);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => error", ssl);
return;
}
// SSL_use_PrivateKey expects to take ownership of the EVP_PKEY,
// but we have an external reference from the caller such as an
// OpenSSLKey, so we manually increment the reference count here.
EVP_PKEY_up_ref(pkey);
JNI_TRACE("ssl=%p SSL_use_PrivateKey => ok", ssl);
}
static void NativeCrypto_SSL_use_certificate(JNIEnv* env, jclass,
jlong ssl_address, jlongArray certificatesJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate certificates=%p", ssl, certificatesJava);
if (ssl == NULL) {
return;
}
if (certificatesJava == NULL) {
jniThrowNullPointerException(env, "certificates == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
size_t length = env->GetArrayLength(certificatesJava);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "certificates.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates.length == 0", ssl);
return;
}
ScopedLongArrayRO certificates(env, certificatesJava);
if (certificates.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates == null", ssl);
return;
}
Unique_X509 serverCert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[0]))));
if (serverCert.get() == NULL) {
// Note this shouldn't happen since we checked the number of certificates above.
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
int ret = SSL_use_certificate(ssl, serverCert.get());
if (ret != 1) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(serverCert);
#if !defined(OPENSSL_IS_BORINGSSL)
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => chain allocation error", ssl);
return;
}
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !sk_X509_push(chain.get(), cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
int chainResult = SSL_use_certificate_chain(ssl, chain.get());
if (chainResult == 0) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => SSL_use_certificate_chain error",
ssl);
return;
}
OWNERSHIP_TRANSFERRED(chain);
#else
for (size_t i = 1; i < length; i++) {
Unique_X509 cert(
X509_dup_nocopy(reinterpret_cast<X509*>(static_cast<uintptr_t>(certificates[i]))));
if (cert.get() == NULL || !SSL_add0_chain_cert(ssl, cert.get())) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing certificate");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => certificates parsing error", ssl);
return;
}
OWNERSHIP_TRANSFERRED(cert);
}
#endif
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_certificate => ok", ssl);
}
static void NativeCrypto_SSL_check_private_key(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key", ssl);
if (ssl == NULL) {
return;
}
int ret = SSL_check_private_key(ssl);
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error checking private key");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_check_private_key => ok", ssl);
}
static void NativeCrypto_SSL_set_client_CA_list(JNIEnv* env, jclass,
jlong ssl_address, jobjectArray principals)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list principals=%p", ssl, principals);
if (ssl == NULL) {
return;
}
if (principals == NULL) {
jniThrowNullPointerException(env, "principals == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals == null", ssl);
return;
}
int length = env->GetArrayLength(principals);
if (length == 0) {
jniThrowException(env, "java/lang/IllegalArgumentException", "principals.length == 0");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals.length == 0", ssl);
return;
}
Unique_sk_X509_NAME principalsStack(sk_X509_NAME_new_null());
if (principalsStack.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate principal stack");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => stack allocation error", ssl);
return;
}
for (int i = 0; i < length; i++) {
ScopedLocalRef<jbyteArray> principal(env,
reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(principals, i)));
if (principal.get() == NULL) {
jniThrowNullPointerException(env, "principals element == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals element null", ssl);
return;
}
ScopedByteArrayRO buf(env, principal.get());
if (buf.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => threw exception", ssl);
return;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(buf.get());
Unique_X509_NAME principalX509Name(d2i_X509_NAME(NULL, &tmp, buf.size()));
if (principalX509Name.get() == NULL) {
ALOGE("%s", ERR_error_string(ERR_peek_error(), NULL));
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error parsing principal");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principals parsing error",
ssl);
return;
}
if (!sk_X509_NAME_push(principalsStack.get(), principalX509Name.release())) {
jniThrowOutOfMemory(env, "Unable to push principal");
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => principal push error", ssl);
return;
}
}
SSL_set_client_CA_list(ssl, principalsStack.release());
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_client_CA_list => ok", ssl);
}
/**
* public static native long SSL_get_mode(long ssl);
*/
static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl);
if (ssl == NULL) {
return 0;
}
long mode = SSL_get_mode(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0x%lx", ssl, mode);
return mode;
}
/**
* public static native long SSL_set_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_mode(long ssl, long mode);
*/
static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass,
jlong ssl_address, jlong mode) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, (long long) mode);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_mode(ssl, mode);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_get_options(long ssl);
*/
static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl);
if (ssl == NULL) {
return 0;
}
long options = SSL_get_options(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0x%lx", ssl, options);
return options;
}
/**
* public static native long SSL_set_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_set_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native long SSL_clear_options(long ssl, long options);
*/
static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass,
jlong ssl_address, jlong options) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, (long long) options);
if (ssl == NULL) {
return 0;
}
long result = SSL_clear_options(ssl, options);
JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options => 0x%lx", ssl, result);
return result;
}
/**
* public static native void SSL_enable_signed_cert_timestamps(long ssl);
*/
static void NativeCrypto_SSL_enable_signed_cert_timestamps(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_signed_cert_timestamps", ssl);
if (ssl == NULL) {
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
SSL_enable_signed_cert_timestamps(ssl);
#endif
}
/**
* public static native byte[] SSL_get_signed_cert_timestamp_list(long ssl);
*/
static jbyteArray NativeCrypto_SSL_get_signed_cert_timestamp_list(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_signed_cert_timestamp_list", ssl);
if (ssl == NULL) {
return NULL;
}
#if defined(OPENSSL_IS_BORINGSSL)
const uint8_t *data;
size_t data_len;
SSL_get0_signed_cert_timestamp_list(ssl, &data, &data_len);
if (data_len == 0) {
JNI_TRACE("NativeCrypto_SSL_get_signed_cert_timestamp_list(%p) => NULL",
ssl);
return NULL;
}
jbyteArray result = env->NewByteArray(data_len);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, data_len, (const jbyte*)data);
}
return result;
#else
return NULL;
#endif
}
/*
* public static native void SSL_CTX_set_signed_cert_timestamp_list(long ssl, byte[] response);
*/
static void NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list(JNIEnv *env, jclass,
jlong ssl_ctx_address, jbyteArray list) {
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO listBytes(env, list);
if (listBytes.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list =>"
" list == NULL", ssl_ctx);
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
if (!SSL_CTX_set_signed_cert_timestamp_list(ssl_ctx,
reinterpret_cast<const uint8_t *>(listBytes.get()),
listBytes.size())) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list => fail", ssl_ctx);
} else {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_signed_cert_timestamp_list => ok", ssl_ctx);
}
#endif
}
/*
* public static native void SSL_enable_ocsp_stapling(long ssl);
*/
static void NativeCrypto_SSL_enable_ocsp_stapling(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_enable_ocsp_stapling", ssl);
if (ssl == NULL) {
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
SSL_enable_ocsp_stapling(ssl);
#endif
}
/*
* public static native byte[] SSL_get_ocsp_response(long ssl);
*/
static jbyteArray NativeCrypto_SSL_get_ocsp_response(JNIEnv *env, jclass,
jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ocsp_response", ssl);
if (ssl == NULL) {
return NULL;
}
#if defined(OPENSSL_IS_BORINGSSL)
const uint8_t *data;
size_t data_len;
SSL_get0_ocsp_response(ssl, &data, &data_len);
if (data_len == 0) {
JNI_TRACE("NativeCrypto_SSL_get_ocsp_response(%p) => NULL", ssl);
return NULL;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(data_len));
if (byteArray.get() == NULL) {
JNI_TRACE("NativeCrypto_SSL_get_ocsp_response(%p) => creating byte array failed", ssl);
return NULL;
}
env->SetByteArrayRegion(byteArray.get(), 0, data_len, (const jbyte*)data);
JNI_TRACE("NativeCrypto_SSL_get_ocsp_response(%p) => %p [size=%zd]",
ssl, byteArray.get(), data_len);
return byteArray.release();
#else
return NULL;
#endif
}
/*
* public static native void SSL_CTX_set_ocsp_response(long ssl, byte[] response);
*/
static void NativeCrypto_SSL_CTX_set_ocsp_response(JNIEnv *env, jclass,
jlong ssl_ctx_address, jbyteArray response) {
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response", ssl_ctx);
if (ssl_ctx == NULL) {
return;
}
ScopedByteArrayRO responseBytes(env, response);
if (responseBytes.get() == NULL) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response => response == NULL", ssl_ctx);
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
if (!SSL_CTX_set_ocsp_response(ssl_ctx,
reinterpret_cast<const uint8_t *>(responseBytes.get()),
responseBytes.size())) {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response => fail", ssl_ctx);
} else {
JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_set_ocsp_response => ok", ssl_ctx);
}
#endif
}
static void NativeCrypto_SSL_use_psk_identity_hint(JNIEnv* env, jclass,
jlong ssl_address, jstring identityHintJava)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_use_psk_identity_hint identityHint=%p",
ssl, identityHintJava);
if (ssl == NULL) {
return;
}
int ret;
if (identityHintJava == NULL) {
ret = SSL_use_psk_identity_hint(ssl, NULL);
} else {
ScopedUtfChars identityHint(env, identityHintJava);
if (identityHint.c_str() == NULL) {
throwSSLExceptionStr(env, "Failed to obtain identityHint bytes");
return;
}
ret = SSL_use_psk_identity_hint(ssl, identityHint.c_str());
}
if (ret != 1) {
int sslErrorCode = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "Failed to set PSK identity hint");
safeSslClear(ssl);
}
}
static void NativeCrypto_set_SSL_psk_client_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_client_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_client_callback(ssl, (enabled) ? psk_client_callback : NULL);
}
static void NativeCrypto_set_SSL_psk_server_callback_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_set_SSL_psk_server_callback_enabled(%d)",
ssl, enabled);
if (ssl == NULL) {
return;
}
SSL_set_psk_server_callback(ssl, (enabled) ? psk_server_callback : NULL);
}
static jlongArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl);
STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl);
int count = (cipherStack != NULL) ? sk_SSL_CIPHER_num(cipherStack) : 0;
ScopedLocalRef<jlongArray> ciphersArray(env, env->NewLongArray(count));
ScopedLongArrayRW ciphers(env, ciphersArray.get());
for (int i = 0; i < count; i++) {
ciphers[i] = reinterpret_cast<jlong>(sk_SSL_CIPHER_value(cipherStack, i));
}
JNI_TRACE("NativeCrypto_SSL_get_ciphers(%p) => %p [size=%d]", ssl, ciphersArray.get(), count);
return ciphersArray.release();
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_mkey(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_mkey => %ld", cipher, (long) cipher->algorithm_mkey);
return cipher->algorithm_mkey;
}
static jint NativeCrypto_get_SSL_CIPHER_algorithm_auth(JNIEnv* env, jclass,
jlong ssl_cipher_address)
{
SSL_CIPHER* cipher = to_SSL_CIPHER(env, ssl_cipher_address, true);
JNI_TRACE("cipher=%p get_SSL_CIPHER_algorithm_auth => %ld", cipher, (long) cipher->algorithm_auth);
return cipher->algorithm_auth;
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_cipher_lists(JNIEnv* env, jclass, jlong ssl_address,
jobjectArray cipherSuites) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%p", ssl, cipherSuites);
if (ssl == NULL) {
return;
}
if (cipherSuites == NULL) {
jniThrowNullPointerException(env, "cipherSuites == null");
return;
}
int length = env->GetArrayLength(cipherSuites);
/*
* Special case for empty cipher list. This is considered an error by the
* SSL_set_cipher_list API, but Java allows this silly configuration.
* However, the SSL cipher list is still set even when SSL_set_cipher_list
* returns 0 in this case. Just to make sure, we check the resulting cipher
* list to make sure it's zero length.
*/
if (length == 0) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=empty", ssl);
SSL_set_cipher_list(ssl, "");
freeOpenSslErrorState();
if (sk_SSL_CIPHER_num(SSL_get_ciphers(ssl)) != 0) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=empty => error", ssl);
jniThrowRuntimeException(env, "SSL_set_cipher_list did not update ciphers!");
}
return;
}
static const char noSSLv2[] = "!SSLv2";
size_t cipherStringLen = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
if (c.c_str() == NULL) {
return;
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For the separating colon */
if (cipherStringLen + c.size() < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += c.size();
}
if (cipherStringLen + 1 < cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Overflow in cipher suite strings");
return;
}
cipherStringLen += 1; /* For final NUL. */
UniquePtr<char[]> cipherString(new char[cipherStringLen]);
if (cipherString.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to alloc cipher string");
return;
}
memcpy(cipherString.get(), noSSLv2, strlen(noSSLv2));
size_t j = strlen(noSSLv2);
for (int i = 0; i < length; i++) {
ScopedLocalRef<jstring> cipherSuite(env,
reinterpret_cast<jstring>(env->GetObjectArrayElement(cipherSuites, i)));
ScopedUtfChars c(env, cipherSuite.get());
cipherString[j++] = ':';
memcpy(&cipherString[j], c.c_str(), c.size());
j += c.size();
}
cipherString[j++] = 0;
if (j != cipherStringLen) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"Internal error");
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_lists cipherSuites=%s", ssl, cipherString.get());
if (!SSL_set_cipher_list(ssl, cipherString.get())) {
freeOpenSslErrorState();
jniThrowException(env, "java/lang/IllegalArgumentException",
"Illegal cipher suite strings.");
return;
}
}
static void NativeCrypto_SSL_set_accept_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_accept_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_accept_state(ssl);
}
static void NativeCrypto_SSL_set_connect_state(JNIEnv* env, jclass, jlong sslRef) {
SSL* ssl = to_SSL(env, sslRef, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_connect_state", ssl);
if (ssl == NULL) {
return;
}
SSL_set_connect_state(ssl);
}
/**
* Sets certificate expectations, especially for server to request client auth
*/
static void NativeCrypto_SSL_set_verify(JNIEnv* env,
jclass, jlong ssl_address, jint mode)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify mode=%x", ssl, mode);
if (ssl == NULL) {
return;
}
SSL_set_verify(ssl, (int)mode, NULL);
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass,
jlong ssl_address, jlong ssl_session_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session);
if (ssl == NULL) {
return;
}
int ret = SSL_set_session(ssl, ssl_session);
if (ret != 1) {
/*
* Translate the error, and throw if it turns out to be a real
* problem.
*/
int sslErrorCode = SSL_get_error(ssl, ret);
if (sslErrorCode != SSL_ERROR_ZERO_RETURN) {
throwSSLExceptionWithSslErrors(env, ssl, sslErrorCode, "SSL session set");
safeSslClear(ssl);
}
}
}
/**
* Sets the ciphers suites that are enabled in the SSL
*/
static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass,
jlong ssl_address, jboolean creation_enabled)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d",
ssl, creation_enabled);
if (ssl == NULL) {
return;
}
#if !defined(OPENSSL_IS_BORINGSSL)
SSL_set_session_creation_enabled(ssl, creation_enabled);
#else
if (creation_enabled) {
SSL_clear_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
} else {
SSL_set_mode(ssl, SSL_MODE_NO_SESSION_CREATION);
}
#endif
}
static void NativeCrypto_SSL_set_reject_peer_renegotiations(JNIEnv* env, jclass,
jlong ssl_address, jboolean reject_renegotiations)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_reject_peer_renegotiations reject_renegotiations=%d",
ssl, reject_renegotiations);
if (ssl == NULL) {
return;
}
#if defined(OPENSSL_IS_BORINGSSL)
SSL_set_reject_peer_renegotiations(ssl, reject_renegotiations);
#else
(void) reject_renegotiations;
/* OpenSSL doesn't support this call and accepts renegotiation requests by
* default. */
#endif
}
static void NativeCrypto_SSL_set_tlsext_host_name(JNIEnv* env, jclass,
jlong ssl_address, jstring hostname)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostname=%p",
ssl, hostname);
if (ssl == NULL) {
return;
}
ScopedUtfChars hostnameChars(env, hostname);
if (hostnameChars.c_str() == NULL) {
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name hostnameChars=%s",
ssl, hostnameChars.c_str());
int ret = SSL_set_tlsext_host_name(ssl, hostnameChars.c_str());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE, "Error setting host name");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => error", ssl);
return;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_set_tlsext_host_name => ok", ssl);
}
static jstring NativeCrypto_SSL_get_servername(JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername", ssl);
if (ssl == NULL) {
return NULL;
}
const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_servername => %s", ssl, servername);
return env->NewStringUTF(servername);
}
/**
* A common selection path for both NPN and ALPN since they're essentially the
* same protocol. The list of protocols in "primary" is considered the order
* which should take precedence.
*/
static int proto_select(SSL* ssl __attribute__ ((unused)),
unsigned char **out, unsigned char *outLength,
const unsigned char *primary, const unsigned int primaryLength,
const unsigned char *secondary, const unsigned int secondaryLength) {
if (primary != NULL && secondary != NULL) {
JNI_TRACE("primary=%p, length=%d", primary, primaryLength);
int status = SSL_select_next_proto(out, outLength, primary, primaryLength, secondary,
secondaryLength);
switch (status) {
case OPENSSL_NPN_NEGOTIATED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN negotiated", ssl);
return SSL_TLSEXT_ERR_OK;
break;
case OPENSSL_NPN_UNSUPPORTED:
JNI_TRACE("ssl=%p proto_select NPN/ALPN unsupported", ssl);
break;
case OPENSSL_NPN_NO_OVERLAP:
JNI_TRACE("ssl=%p proto_select NPN/ALPN no overlap", ssl);
break;
}
} else {
if (out != NULL && outLength != NULL) {
*out = NULL;
*outLength = 0;
}
JNI_TRACE("protocols=NULL");
}
return SSL_TLSEXT_ERR_NOACK;
}
/**
* Callback for the server to select an ALPN protocol.
*/
static int alpn_select_callback(SSL* ssl, const unsigned char **out, unsigned char *outlen,
const unsigned char *in, unsigned int inlen, void *) {
JNI_TRACE("ssl=%p alpn_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
return proto_select(ssl, const_cast<unsigned char **>(out), outlen,
reinterpret_cast<unsigned char*>(appData->alpnProtocolsData),
appData->alpnProtocolsLength, in, inlen);
}
/**
* Callback for the client to select an NPN protocol.
*/
static int next_proto_select_callback(SSL* ssl, unsigned char** out, unsigned char* outlen,
const unsigned char* in, unsigned int inlen, void*)
{
JNI_TRACE("ssl=%p next_proto_select_callback", ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("AppData=%p", appData);
// Enable False Start on the client if the server understands NPN
// http://www.imperialviolet.org/2012/04/11/falsestart.html
SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
return proto_select(ssl, out, outlen, in, inlen,
reinterpret_cast<unsigned char*>(appData->npnProtocolsData),
appData->npnProtocolsLength);
}
/**
* Callback for the server to advertise available protocols.
*/
static int next_protos_advertised_callback(SSL* ssl,
const unsigned char **out, unsigned int *outlen, void *)
{
JNI_TRACE("ssl=%p next_protos_advertised_callback", ssl);
AppData* appData = toAppData(ssl);
unsigned char* npnProtocols = reinterpret_cast<unsigned char*>(appData->npnProtocolsData);
if (npnProtocols != NULL) {
*out = npnProtocols;
*outlen = appData->npnProtocolsLength;
return SSL_TLSEXT_ERR_OK;
} else {
*out = NULL;
*outlen = 0;
return SSL_TLSEXT_ERR_NOACK;
}
}
static void NativeCrypto_SSL_CTX_enable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_callback, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_protos_advertised_callback, NULL); // server
}
static void NativeCrypto_SSL_CTX_disable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)
{
SSL_CTX* ssl_ctx = to_SSL_CTX(env, ssl_ctx_address, true);
if (ssl_ctx == NULL) {
return;
}
SSL_CTX_set_next_proto_select_cb(ssl_ctx, NULL, NULL); // client
SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, NULL, NULL); // server
}
static jbyteArray NativeCrypto_SSL_get_npn_negotiated_protocol(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_npn_negotiated_protocol", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_next_proto_negotiated(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
static int NativeCrypto_SSL_set_alpn_protos(JNIEnv* env, jclass, jlong ssl_address,
jbyteArray protos) {
SSL* ssl = to_SSL(env, ssl_address, true);
if (ssl == NULL) {
return 0;
}
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p", ssl, protos);
if (protos == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=NULL", ssl);
return 1;
}
ScopedByteArrayRO protosBytes(env, protos);
if (protosBytes.get() == NULL) {
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => protosBytes == NULL", ssl,
protos);
return 0;
}
const unsigned char *tmp = reinterpret_cast<const unsigned char*>(protosBytes.get());
int ret = SSL_set_alpn_protos(ssl, tmp, protosBytes.size());
JNI_TRACE("ssl=%p SSL_set_alpn_protos protos=%p => ret=%d", ssl, protos, ret);
return ret;
}
static jbyteArray NativeCrypto_SSL_get0_alpn_selected(JNIEnv* env, jclass,
jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p SSL_get0_alpn_selected", ssl);
if (ssl == NULL) {
return NULL;
}
const jbyte* npn;
unsigned npnLength;
SSL_get0_alpn_selected(ssl, reinterpret_cast<const unsigned char**>(&npn), &npnLength);
if (npnLength == 0) {
return NULL;
}
jbyteArray result = env->NewByteArray(npnLength);
if (result != NULL) {
env->SetByteArrayRegion(result, 0, npnLength, npn);
}
return result;
}
#ifdef WITH_JNI_TRACE_KEYS
static inline char hex_char(unsigned char in)
{
if (in < 10) {
return '0' + in;
} else if (in <= 0xF0) {
return 'A' + in - 10;
} else {
return '?';
}
}
static void hex_string(char **dest, unsigned char* input, int len)
{
*dest = (char*) malloc(len * 2 + 1);
char *output = *dest;
for (int i = 0; i < len; i++) {
*output++ = hex_char(input[i] >> 4);
*output++ = hex_char(input[i] & 0xF);
}
*output = '\0';
}
static void debug_print_session_key(SSL_SESSION* session)
{
char *session_id_str;
char *master_key_str;
const char *key_type;
char *keyline;
hex_string(&session_id_str, session->session_id, session->session_id_length);
hex_string(&master_key_str, session->master_key, session->master_key_length);
X509* peer = SSL_SESSION_get0_peer(session);
EVP_PKEY* pkey = X509_PUBKEY_get(peer->cert_info->key);
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
key_type = "RSA";
break;
case EVP_PKEY_DSA:
key_type = "DSA";
break;
case EVP_PKEY_EC:
key_type = "EC";
break;
default:
key_type = "Unknown";
break;
}
asprintf(&keyline, "%s Session-ID:%s Master-Key:%s\n", key_type, session_id_str,
master_key_str);
JNI_TRACE("ssl_session=%p %s", session, keyline);
free(session_id_str);
free(master_key_str);
free(keyline);
}
#endif /* WITH_JNI_TRACE_KEYS */
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake_bio(JNIEnv* env, jclass, jlong ssl_address,
jlong rbioRef, jlong wbioRef, jobject shc, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
BIO* rbio = reinterpret_cast<BIO*>(rbioRef);
BIO* wbio = reinterpret_cast<BIO*>(wbioRef);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio rbio=%p wbio=%p shc=%p client_mode=%d npn=%p",
ssl, rbio, wbio, shc, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => rbio == null || wbio == NULL", ssl);
return 0;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (!client_mode && alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
int ret = 0;
errno = 0;
if (!appData->setCallbackState(env, shc, NULL, npnProtocols, alpnProtocols)) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio exception => 0", ssl);
return 0;
}
if (ret <= 0) { // error. See SSL_do_handshake(3SSL) man page.
// error case
OpenSslError sslError(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio ret=%d errno=%d sslError=%d",
ssl, ret, errno, sslError.get());
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we need to exit to allow
* the SSLEngine code to wrap or unwrap.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0) ||
(sslError.get() == SSL_ERROR_ZERO_RETURN)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
safeSslClear(ssl);
} else if (sslError.get() != SSL_ERROR_WANT_READ &&
sslError.get() != SSL_ERROR_WANT_WRITE) {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio error => 0", ssl);
return 0;
}
// success. handshake completed
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake_bio => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return reinterpret_cast<uintptr_t>(ssl_session);
}
/**
* Perform SSL handshake
*/
static jlong NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jint timeout_millis, jboolean client_mode, jbyteArray npnProtocols,
jbyteArray alpnProtocols) {
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd=%p shc=%p timeout_millis=%d client_mode=%d npn=%p",
ssl, fdObject, shc, timeout_millis, client_mode, npnProtocols);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd == null => 0", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslHandshakeCallbacks == null => 0", ssl);
return 0;
}
NetFd fd(env, fdObject);
if (fd.isClosed()) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake fd.isClosed() => 0", ssl);
return 0;
}
int ret = SSL_set_fd(ssl, fd.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd.get());
if (ret != 1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_NONE,
"Error setting the file descriptor");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake SSL_set_fd => 0", ssl);
return 0;
}
/*
* Make socket non-blocking, so SSL_connect SSL_read() and SSL_write() don't hang
* forever and we can use select() to find out if the socket is ready.
*/
if (!setBlocking(fd.get(), false)) {
throwSSLExceptionStr(env, "Unable to make socket non blocking");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setBlocking => 0", ssl);
return 0;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake appData => 0", ssl);
return 0;
}
if (client_mode) {
SSL_set_connect_state(ssl);
} else {
SSL_set_accept_state(ssl);
if (alpnProtocols != NULL) {
SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), alpn_select_callback, NULL);
}
}
ret = 0;
OpenSslError sslError;
while (appData->aliveAndKicking) {
errno = 0;
if (!appData->setCallbackState(env, shc, fdObject, npnProtocols, alpnProtocols)) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake setCallbackState => 0", ssl);
return 0;
}
ret = SSL_do_handshake(ssl);
appData->clearCallbackState();
// cert_verify_callback threw exception
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake exception => 0", ssl);
return 0;
}
// success case
if (ret == 1) {
break;
}
// retry case
if (errno == EINTR) {
continue;
}
// error case
sslError.reset(ssl, ret);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake ret=%d errno=%d sslError=%d timeout_millis=%d",
ssl, ret, errno, sslError.get(), timeout_millis);
/*
* If SSL_do_handshake doesn't succeed due to the socket being
* either unreadable or unwritable, we use sslSelect to
* wait for it to become ready. If that doesn't happen
* before the specified timeout or an error occurs, we
* cancel the handshake. Otherwise we try the SSL_connect
* again.
*/
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
// SocketException thrown by NetFd.isClosed
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake sslSelect => 0", ssl);
return 0;
}
if (selectResult == -1) {
throwSSLExceptionWithSslErrors(env, ssl, SSL_ERROR_SYSCALL, "handshake error",
throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == -1 => 0", ssl);
return 0;
}
if (selectResult == 0) {
throwSocketTimeoutException(env, "SSL handshake timed out");
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake selectResult == 0 => 0", ssl);
return 0;
}
} else {
// ALOGE("Unknown error %d during handshake", error);
break;
}
}
// clean error. See SSL_do_handshake(3SSL) man page.
if (ret == 0) {
/*
* The other side closed the socket before the handshake could be
* completed, but everything is within the bounds of the TLS protocol.
* We still might want to find out the real reason of the failure.
*/
if (sslError.get() == SSL_ERROR_NONE ||
(sslError.get() == SSL_ERROR_SYSCALL && errno == 0) ||
(sslError.get() == SSL_ERROR_ZERO_RETURN)) {
throwSSLHandshakeExceptionStr(env, "Connection closed by peer");
} else {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"SSL handshake terminated", throwSSLHandshakeExceptionStr);
}
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake clean error => 0", ssl);
return 0;
}
// unclean error. See SSL_do_handshake(3SSL) man page.
if (ret < 0) {
/*
* Translate the error and throw exception. We are sure it is an error
* at this point.
*/
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "SSL handshake aborted",
throwSSLHandshakeExceptionStr);
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake unclean error => 0", ssl);
return 0;
}
SSL_SESSION* ssl_session = SSL_get1_session(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => ssl_session=%p", ssl, ssl_session);
#ifdef WITH_JNI_TRACE_KEYS
debug_print_session_key(ssl_session);
#endif
return (jlong) ssl_session;
}
/**
* Perform SSL renegotiation
*/
static void NativeCrypto_SSL_renegotiate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate", ssl);
if (ssl == NULL) {
return;
}
int result = SSL_renegotiate(ssl);
if (result != 1) {
throwSSLExceptionStr(env, "Problem with SSL_renegotiate");
return;
}
// first call asks client to perform renegotiation
int ret = SSL_do_handshake(ssl);
if (ret != 1) {
OpenSslError sslError(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(),
"Problem with SSL_do_handshake after SSL_renegotiate");
return;
}
// if client agrees, set ssl state and perform renegotiation
ssl->state = SSL_ST_ACCEPT;
SSL_do_handshake(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_renegotiate =>", ssl);
}
/**
* public static native byte[][] SSL_get_certificate(long ssl);
*/
static jlongArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl);
if (ssl == NULL) {
return NULL;
}
X509* certificate = SSL_get_certificate(ssl);
if (certificate == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
// SSL_get_certificate can return NULL during an error as well.
freeOpenSslErrorState();
return NULL;
}
Unique_sk_X509 chain(sk_X509_new_null());
if (chain.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => threw exception", ssl);
return NULL;
}
if (!sk_X509_push(chain.get(), X509_dup_nocopy(certificate))) {
jniThrowOutOfMemory(env, "Unable to push local certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
#if !defined(OPENSSL_IS_BORINGSSL)
STACK_OF(X509)* cert_chain = SSL_get_certificate_chain(ssl, certificate);
for (int i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#else
STACK_OF(X509) *cert_chain = NULL;
if (!SSL_get0_chain_certs(ssl, &cert_chain)) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_chain_certs => NULL", ssl);
freeOpenSslErrorState();
return NULL;
}
for (size_t i=0; i<sk_X509_num(cert_chain); i++) {
if (!sk_X509_push(chain.get(), X509_dup_nocopy(sk_X509_value(cert_chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push local certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
return NULL;
}
}
#endif
jlongArray refArray = getCertificateRefs(env, chain.get());
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => %p", ssl, refArray);
return refArray;
}
// Fills a long[] with the peer certificates in the chain.
static jlongArray NativeCrypto_SSL_get_peer_cert_chain(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain", ssl);
if (ssl == NULL) {
return NULL;
}
STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl);
Unique_sk_X509 chain_copy(NULL);
if (ssl->server) {
X509* x509 = SSL_get_peer_certificate(ssl);
if (x509 == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => NULL", ssl);
return NULL;
}
chain_copy.reset(sk_X509_new_null());
if (chain_copy.get() == NULL) {
jniThrowOutOfMemory(env, "Unable to allocate peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate dup error", ssl);
return NULL;
}
size_t chain_size = sk_X509_num(chain);
for (size_t i = 0; i < chain_size; i++) {
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(sk_X509_value(chain, i)))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate chain");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate chain push error", ssl);
return NULL;
}
}
if (!sk_X509_push(chain_copy.get(), X509_dup_nocopy(x509))) {
jniThrowOutOfMemory(env, "Unable to push server's peer certificate");
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => certificate push error", ssl);
return NULL;
}
chain = chain_copy.get();
}
jlongArray refArray = getCertificateRefs(env, chain);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_peer_cert_chain => %p", ssl, refArray);
return refArray;
}
static int sslRead(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, char* buf, jint len,
OpenSslError& sslError, int read_timeout_millis) {
JNI_TRACE("ssl=%p sslRead buf=%p len=%d", ssl, buf, len);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslRead appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
while (appData->aliveAndKicking) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslRead => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
int result = SSL_read(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p sslRead => THROWN_EXCEPTION", ssl);
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslRead SSL_read result=%d sslError=%d", ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslRead data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE: {
return result;
}
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData, read_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
return -1;
}
static jint NativeCrypto_SSL_read_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray destJava,
jint destOffset, jint destLength, jlong sourceBioRef, jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sourceBioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO dest=%p sourceBio=%p sinkBio=%p shc=%p",
ssl, destJava, rbio, wbio, shc);
if (ssl == NULL) {
return 0;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => rbio == null || wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
ScopedByteArrayRW dest(env, destJava);
if (dest.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return -1;
}
if (ARRAY_OFFSET_LENGTH_INVALID(dest, destOffset, destLength)) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => destOffset=%d, destLength=%d, size=%zd",
ssl, destOffset, destLength, dest.size());
jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => appData == NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set callback state");
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => set callback state failed", ssl);
return -1;
}
ScopedSslBio sslBio(ssl, rbio, wbio);
int result = SSL_read(ssl, dest.get() + destOffset, destLength);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => threw exception", ssl);
return THROWN_EXCEPTION;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO SSL_read result=%d sslError=%d", ssl, result,
sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully read at least one byte.
case SSL_ERROR_NONE:
break;
// Read zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
result = -1;
break;
// Need to wait for availability of underlying layer, then retry.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
result = 0;
break;
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
result = -1;
break;
} else if (errno == EINTR) {
// System call has been interrupted. Simply retry.
result = 0;
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
return -1;
}
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read_BIO => %d", ssl, result);
return result;
}
/**
* OpenSSL read function (2): read into buffer at offset n chunks.
* Returns 1 (success) or value <= 0 (failure).
*/
static jint NativeCrypto_SSL_read(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len,
jint read_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_read fd=%p shc=%p b=%p offset=%d len=%d read_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, read_timeout_millis);
if (ssl == NULL) {
return 0;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => fd == null", ssl);
return 0;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => sslHandshakeCallbacks == null", ssl);
return 0;
}
ScopedByteArrayRW bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => threw exception", ssl);
return 0;
}
OpenSslError sslError;
int ret = sslRead(env, ssl, fdObject, shc, reinterpret_cast<char*>(bytes.get() + offset), len,
sslError, read_timeout_millis);
int result;
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslRead() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Read error");
result = -1;
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Read timed out");
result = -1;
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
// or RuntimeException thrown by callback
result = -1;
break;
default:
result = ret;
break;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_read => %d", ssl, result);
return result;
}
static int sslWrite(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, const char* buf, jint len,
OpenSslError& sslError, int write_timeout_millis) {
JNI_TRACE("ssl=%p sslWrite buf=%p len=%d write_timeout_millis=%d",
ssl, buf, len, write_timeout_millis);
if (len == 0) {
// Don't bother doing anything in this case.
return 0;
}
BIO* rbio = SSL_get_rbio(ssl);
BIO* wbio = SSL_get_wbio(ssl);
AppData* appData = toAppData(ssl);
JNI_TRACE("ssl=%p sslWrite appData=%p", ssl, appData);
if (appData == NULL) {
return THROW_SSLEXCEPTION;
}
int count = len;
while (appData->aliveAndKicking && len > 0) {
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return -1;
}
if (!SSL_is_init_finished(ssl) && !SSL_cutthrough_complete(ssl) &&
!SSL_renegotiate_pending(ssl)) {
JNI_TRACE("ssl=%p sslWrite => init is not finished (state=0x%x)", ssl,
SSL_get_state(ssl));
MUTEX_UNLOCK(appData->mutex);
return THROW_SSLEXCEPTION;
}
unsigned int bytesMoved = BIO_number_read(rbio) + BIO_number_written(wbio);
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
return THROWN_EXCEPTION;
}
JNI_TRACE("ssl=%p sslWrite SSL_write len=%d", ssl, len);
int result = SSL_write(ssl, buf, len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p sslWrite exception => THROWN_EXCEPTION", ssl);
return THROWN_EXCEPTION;
}
sslError.reset(ssl, result);
JNI_TRACE("ssl=%p sslWrite SSL_write result=%d sslError=%d",
ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p sslWrite data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
// If we have been successful in moving data around, check whether it
// might make sense to wake up other blocked threads, so they can give
// it a try, too.
if (BIO_number_read(rbio) + BIO_number_written(wbio) != bytesMoved
&& appData->waitingThreads > 0) {
sslNotify(appData);
}
// If we are blocked by the underlying socket, tell the world that
// there will be one more waiting thread now.
if (sslError.get() == SSL_ERROR_WANT_READ || sslError.get() == SSL_ERROR_WANT_WRITE) {
appData->waitingThreads++;
}
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
// Successfully wrote at least one byte.
case SSL_ERROR_NONE: {
buf += result;
len -= result;
break;
}
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN: {
return -1;
}
// Need to wait for availability of underlying layer, then retry.
// The concept of a write timeout doesn't really make sense, and
// it's also not standard Java behavior, so we wait forever here.
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: {
int selectResult = sslSelect(env, sslError.get(), fdObject, appData,
write_timeout_millis);
if (selectResult == THROWN_EXCEPTION) {
return THROWN_EXCEPTION;
}
if (selectResult == -1) {
return THROW_SSLEXCEPTION;
}
if (selectResult == 0) {
return THROW_SOCKETTIMEOUTEXCEPTION;
}
break;
}
// A problem occurred during a system call, but this is not
// necessarily an error.
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
break;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
return THROW_SSLEXCEPTION;
}
}
}
JNI_TRACE("ssl=%p sslWrite => count=%d", ssl, count);
return count;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static int NativeCrypto_SSL_write_BIO(JNIEnv* env, jclass, jlong sslRef, jbyteArray sourceJava, jint len,
jlong sinkBioRef, jobject shc) {
SSL* ssl = to_SSL(env, sslRef, true);
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(sinkBioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO source=%p len=%d wbio=%p shc=%p",
ssl, sourceJava, len, wbio, shc);
if (ssl == NULL) {
return -1;
}
if (wbio == NULL) {
jniThrowNullPointerException(env, "wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => wbio == null", ssl);
return -1;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => sslHandshakeCallbacks == null", ssl);
return -1;
}
AppData* appData = toAppData(ssl);
if (appData == NULL) {
throwSSLExceptionStr(env, "Unable to retrieve application data");
safeSslClear(ssl);
freeOpenSslErrorState();
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO appData => NULL", ssl);
return -1;
}
errno = 0;
if (MUTEX_LOCK(appData->mutex) == -1) {
return 0;
}
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
MUTEX_UNLOCK(appData->mutex);
throwSSLExceptionStr(env, "Unable to set appdata callback");
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => appData can't set callback", ssl);
return -1;
}
ScopedByteArrayRO source(env, sourceJava);
if (source.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO => threw exception", ssl);
return -1;
}
#if defined(OPENSSL_IS_BORINGSSL)
Unique_BIO nullBio(BIO_new_mem_buf(NULL, 0));
#else
Unique_BIO nullBio(BIO_new(BIO_s_null()));
#endif
ScopedSslBio sslBio(ssl, nullBio.get(), wbio);
int result = SSL_write(ssl, reinterpret_cast<const char*>(source.get()), len);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
freeOpenSslErrorState();
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO exception => exception pending (reneg)", ssl);
return -1;
}
OpenSslError sslError(ssl, result);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO SSL_write result=%d sslError=%d",
ssl, result, sslError.get());
#ifdef WITH_JNI_TRACE_DATA
for (int i = 0; i < result; i+= WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
int n = result - i;
if (n > WITH_JNI_TRACE_DATA_CHUNK_SIZE) {
n = WITH_JNI_TRACE_DATA_CHUNK_SIZE;
}
JNI_TRACE("ssl=%p NativeCrypto_SSL_write_BIO data: %d:\n%.*s", ssl, n, n, buf+i);
}
#endif
MUTEX_UNLOCK(appData->mutex);
switch (sslError.get()) {
case SSL_ERROR_NONE:
return result;
// Wrote zero bytes. End of stream reached.
case SSL_ERROR_ZERO_RETURN:
return -1;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return 0;
case SSL_ERROR_SYSCALL: {
// Connection closed without proper shutdown. Tell caller we
// have reached end-of-stream.
if (result == 0) {
return -1;
}
// System call has been interrupted. Simply retry.
if (errno == EINTR) {
return 0;
}
// Note that for all other system call errors we fall through
// to the default case, which results in an Exception.
FALLTHROUGH_INTENDED;
}
// Everything else is basically an error.
default: {
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
}
}
return -1;
}
/**
* OpenSSL write function (2): write into buffer at offset n chunks.
*/
static void NativeCrypto_SSL_write(JNIEnv* env, jclass, jlong ssl_address, jobject fdObject,
jobject shc, jbyteArray b, jint offset, jint len, jint write_timeout_millis)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_write fd=%p shc=%p b=%p offset=%d len=%d write_timeout_millis=%d",
ssl, fdObject, shc, b, offset, len, write_timeout_millis);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => sslHandshakeCallbacks == null", ssl);
return;
}
ScopedByteArrayRO bytes(env, b);
if (bytes.get() == NULL) {
JNI_TRACE("ssl=%p NativeCrypto_SSL_write => threw exception", ssl);
return;
}
OpenSslError sslError;
int ret = sslWrite(env, ssl, fdObject, shc, reinterpret_cast<const char*>(bytes.get() + offset),
len, sslError, write_timeout_millis);
switch (ret) {
case THROW_SSLEXCEPTION:
// See sslWrite() regarding improper failure to handle normal cases.
throwSSLExceptionWithSslErrors(env, ssl, sslError.release(), "Write error");
break;
case THROW_SOCKETTIMEOUTEXCEPTION:
throwSocketTimeoutException(env, "Write timed out");
break;
case THROWN_EXCEPTION:
// SocketException thrown by NetFd.isClosed
break;
default:
break;
}
}
/**
* Interrupt any pending I/O before closing the socket.
*/
static void NativeCrypto_SSL_interrupt(
JNIEnv* env, jclass, jlong ssl_address) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_interrupt", ssl);
if (ssl == NULL) {
return;
}
/*
* Mark the connection as quasi-dead, then send something to the emergency
* file descriptor, so any blocking select() calls are woken up.
*/
AppData* appData = toAppData(ssl);
if (appData != NULL) {
appData->aliveAndKicking = 0;
// At most two threads can be waiting.
sslNotify(appData);
sslNotify(appData);
}
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown(JNIEnv* env, jclass, jlong ssl_address,
jobject fdObject, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown fd=%p shc=%p", ssl, fdObject, shc);
if (ssl == NULL) {
return;
}
if (fdObject == NULL) {
jniThrowNullPointerException(env, "fd == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => fd == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, fdObject, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
freeOpenSslErrorState();
safeSslClear(ssl);
return;
}
/*
* Try to make socket blocking again. OpenSSL literature recommends this.
*/
int fd = SSL_get_fd(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown s=%d", ssl, fd);
if (fd != -1) {
setBlocking(fd, true);
}
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
freeOpenSslErrorState();
safeSslClear(ssl);
}
/**
* OpenSSL close SSL socket function.
*/
static void NativeCrypto_SSL_shutdown_BIO(JNIEnv* env, jclass, jlong ssl_address, jlong rbioRef,
jlong wbioRef, jobject shc) {
SSL* ssl = to_SSL(env, ssl_address, false);
BIO* rbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(rbioRef));
BIO* wbio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(wbioRef));
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown rbio=%p wbio=%p shc=%p", ssl, rbio, wbio, shc);
if (ssl == NULL) {
return;
}
if (rbio == NULL || wbio == NULL) {
jniThrowNullPointerException(env, "rbio == null || wbio == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => rbio == null || wbio == null", ssl);
return;
}
if (shc == NULL) {
jniThrowNullPointerException(env, "sslHandshakeCallbacks == null");
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => sslHandshakeCallbacks == null", ssl);
return;
}
AppData* appData = toAppData(ssl);
if (appData != NULL) {
if (!appData->setCallbackState(env, shc, NULL, NULL, NULL)) {
// SocketException thrown by NetFd.isClosed
freeOpenSslErrorState();
safeSslClear(ssl);
return;
}
ScopedSslBio scopedBio(ssl, rbio, wbio);
int ret = SSL_shutdown(ssl);
appData->clearCallbackState();
// callbacks can happen if server requests renegotiation
if (env->ExceptionCheck()) {
safeSslClear(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => exception", ssl);
return;
}
switch (ret) {
case 0:
/*
* Shutdown was not successful (yet), but there also
* is no error. Since we can't know whether the remote
* server is actually still there, and we don't want to
* get stuck forever in a second SSL_shutdown() call, we
* simply return. This is not security a problem as long
* as we close the underlying socket, which we actually
* do, because that's where we are just coming from.
*/
break;
case 1:
/*
* Shutdown was successful. We can safely return. Hooray!
*/
break;
default:
/*
* Everything else is a real error condition. We should
* let the Java layer know about this by throwing an
* exception.
*/
int sslError = SSL_get_error(ssl, ret);
throwSSLExceptionWithSslErrors(env, ssl, sslError, "SSL shutdown failed");
break;
}
}
freeOpenSslErrorState();
safeSslClear(ssl);
}
static jint NativeCrypto_SSL_get_shutdown(JNIEnv* env, jclass, jlong ssl_address) {
const SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown", ssl);
if (ssl == NULL) {
jniThrowNullPointerException(env, "ssl == null");
return 0;
}
int status = SSL_get_shutdown(ssl);
JNI_TRACE("ssl=%p NativeCrypto_SSL_get_shutdown => %d", ssl, status);
return static_cast<jint>(status);
}
/**
* public static native void SSL_free(long ssl);
*/
static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jlong ssl_address)
{
SSL* ssl = to_SSL(env, ssl_address, true);
JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl);
if (ssl == NULL) {
return;
}
AppData* appData = toAppData(ssl);
SSL_set_app_data(ssl, NULL);
delete appData;
SSL_free(ssl);
}
/**
* Gets and returns in a byte array the ID of the actual SSL session.
*/
static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass,
jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
jbyteArray result = env->NewByteArray(ssl_session->session_id_length);
if (result != NULL) {
jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id);
env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src);
}
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d",
ssl_session, result, ssl_session->session_id_length);
return result;
}
/**
* Gets and returns in a long integer the creation's time of the
* actual SSL session.
*/
static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session);
if (ssl_session == NULL) {
return 0;
}
// result must be jlong, not long or *1000 will overflow
jlong result = SSL_SESSION_get_time(ssl_session);
result *= 1000; // OpenSSL uses seconds, Java uses milliseconds.
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, (long long) result);
return result;
}
/**
* Gets and returns in a string the version of the SSL protocol. If it
* returns the string "unknown" it means that no connection is established.
*/
static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const char* protocol = SSL_SESSION_get_version(ssl_session);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol);
return env->NewStringUTF(protocol);
}
/**
* Gets and returns in a string the cipher negotiated for the SSL session.
*/
static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
const SSL_CIPHER* cipher = ssl_session->cipher;
const char* name = SSL_CIPHER_get_name(cipher);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name);
return env->NewStringUTF(name);
}
/**
* Frees the SSL session.
*/
static void NativeCrypto_SSL_SESSION_free(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session);
if (ssl_session == NULL) {
return;
}
SSL_SESSION_free(ssl_session);
}
/**
* Serializes the native state of the session (ID, cipher, and keys but
* not certificates). Returns a byte[] containing the DER-encoded state.
* See apache mod_ssl.
*/
static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jlong ssl_session_address) {
SSL_SESSION* ssl_session = to_SSL_SESSION(env, ssl_session_address, true);
JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session);
if (ssl_session == NULL) {
return NULL;
}
return ASN1ToByteArray<SSL_SESSION>(env, ssl_session, i2d_SSL_SESSION);
}
/**
* Deserialize the session.
*/
static jlong NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray javaBytes) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p", javaBytes);
ScopedByteArrayRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => threw exception");
return 0;
}
const unsigned char* ucp = reinterpret_cast<const unsigned char*>(bytes.get());
SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, bytes.size());
#if !defined(OPENSSL_IS_BORINGSSL)
// Initialize SSL_SESSION cipher field based on cipher_id http://b/7091840
if (ssl_session != NULL) {
// based on ssl_get_prev_session
uint32_t cipher_id_network_order = htonl(ssl_session->cipher_id);
uint8_t* cipher_id_byte_pointer = reinterpret_cast<uint8_t*>(&cipher_id_network_order);
if (ssl_session->ssl_version >= SSL3_VERSION_MAJOR) {
cipher_id_byte_pointer += 2; // skip first two bytes for SSL3+
} else {
cipher_id_byte_pointer += 1; // skip first byte for SSL2
}
ssl_session->cipher = SSLv23_method()->get_cipher_by_char(cipher_id_byte_pointer);
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION cipher_id=%lx hton=%x 0=%x 1=%x cipher=%s",
ssl_session->cipher_id, cipher_id_network_order,
cipher_id_byte_pointer[0], cipher_id_byte_pointer[1],
SSL_CIPHER_get_name(ssl_session->cipher));
}
#endif
if (ssl_session == NULL) {
freeOpenSslErrorState();
}
JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session);
return reinterpret_cast<uintptr_t>(ssl_session);
}
static jlong NativeCrypto_ERR_peek_last_error(JNIEnv*, jclass) {
return ERR_peek_last_error();
}
static jstring NativeCrypto_SSL_CIPHER_get_kx_name(JNIEnv* env, jclass, jlong cipher_address) {
const SSL_CIPHER* cipher = to_SSL_CIPHER(env, cipher_address, true);
const char *kx_name = NULL;
#if defined(OPENSSL_IS_BORINGSSL)
kx_name = SSL_CIPHER_get_kx_name(cipher);
#else
kx_name = SSL_CIPHER_authentication_method(cipher);
#endif
return env->NewStringUTF(kx_name);
}
static jobjectArray NativeCrypto_get_cipher_names(JNIEnv *env, jclass, jstring selectorJava) {
ScopedUtfChars selector(env, selectorJava);
if (selector.c_str() == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException", "selector == NULL");
return 0;
}
JNI_TRACE("NativeCrypto_get_cipher_names %s", selector.c_str());
Unique_SSL_CTX sslCtx(SSL_CTX_new(SSLv23_method()));
Unique_SSL ssl(SSL_new(sslCtx.get()));
if (!SSL_set_cipher_list(ssl.get(), selector.c_str())) {
jniThrowException(env, "java/lang/IllegalArgumentException", "Unable to set SSL cipher list");
return 0;
}
STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl.get());
size_t size = sk_SSL_CIPHER_num(ciphers);
ScopedLocalRef<jobjectArray> cipherNamesArray(env, env->NewObjectArray(size, stringClass, NULL));
if (cipherNamesArray.get() == NULL) {
return NULL;
}
for (size_t i = 0; i < size; i++) {
const char *name = SSL_CIPHER_get_name(sk_SSL_CIPHER_value(ciphers, i));
ScopedLocalRef<jstring> cipherName(env, env->NewStringUTF(name));
env->SetObjectArrayElement(cipherNamesArray.get(), i, cipherName.get());
}
JNI_TRACE("NativeCrypto_get_cipher_names(%s) => success (%zd entries)", selector.c_str(), size);
return cipherNamesArray.release();
}
#if defined(OPENSSL_IS_BORINGSSL)
/**
* Compare the given CertID with a certificate and it's issuer.
* True is returned if the CertID matches.
*/
static bool ocsp_cert_id_matches_certificate(CBS *cert_id, X509 *x509, X509 *issuerX509) {
// Get the hash algorithm used by this CertID
CBS hash_algorithm, hash;
if (!CBS_get_asn1(cert_id, &hash_algorithm, CBS_ASN1_SEQUENCE) ||
!CBS_get_asn1(&hash_algorithm, &hash, CBS_ASN1_OBJECT)) {
return false;
}
// Get the issuer's name hash from the CertID
CBS issuer_name_hash;
if (!CBS_get_asn1(cert_id, &issuer_name_hash, CBS_ASN1_OCTETSTRING)) {
return false;
}
// Get the issuer's key hash from the CertID
CBS issuer_key_hash;
if (!CBS_get_asn1(cert_id, &issuer_key_hash, CBS_ASN1_OCTETSTRING)) {
return false;
}
// Get the serial number from the CertID
CBS serial;
if (!CBS_get_asn1(cert_id, &serial, CBS_ASN1_INTEGER)) {
return false;
}
// Compare the certificate's serial number with the one from the Cert ID
const uint8_t *p = CBS_data(&serial);
Unique_ASN1_INTEGER serial_number(c2i_ASN1_INTEGER(NULL, &p, CBS_len(&serial)));
ASN1_INTEGER *expected_serial_number = X509_get_serialNumber(x509);
if (serial_number.get() == NULL ||
ASN1_INTEGER_cmp(expected_serial_number, serial_number.get()) != 0) {
return false;
}
// Find the hash algorithm to be used
const EVP_MD *digest = EVP_get_digestbynid(OBJ_cbs2nid(&hash));
if (digest == NULL) {
return false;
}
// Hash the issuer's name and compare the hash with the one from the Cert ID
uint8_t md[EVP_MAX_MD_SIZE];
X509_NAME *issuer_name = X509_get_subject_name(issuerX509);
if (!X509_NAME_digest(issuer_name, digest, md, NULL) ||
!CBS_mem_equal(&issuer_name_hash, md, EVP_MD_size(digest))) {
return false;
}
// Same thing with the issuer's key
ASN1_BIT_STRING *issuer_key = X509_get0_pubkey_bitstr(issuerX509);
if (!EVP_Digest(issuer_key->data, issuer_key->length, md, NULL, digest, NULL) ||
!CBS_mem_equal(&issuer_key_hash, md, EVP_MD_size(digest))) {
return false;
}
return true;
}
/**
* Get a SingleResponse whose CertID matches the given certificate and issuer from a
* SEQUENCE OF SingleResponse.
*
* If found, |out_single_response| is set to the response, and true is returned. Otherwise if an
* error occured or no response matches the certificate, false is returned and |out_single_response|
* is unchanged.
*/
static bool find_ocsp_single_response(CBS* responses, X509 *x509, X509 *issuerX509,
CBS *out_single_response) {
// Iterate over all the SingleResponses, until one matches the certificate
while (CBS_len(responses) > 0) {
// Get the next available SingleResponse from the sequence
CBS single_response;
if (!CBS_get_asn1(responses, &single_response, CBS_ASN1_SEQUENCE)) {
return false;
}
// Make a copy of the stream so we pass it back to the caller
CBS single_response_original = single_response;
// Get the SingleResponse's CertID
// If this fails ignore the current response and move to the next one
CBS cert_id;
if (!CBS_get_asn1(&single_response, &cert_id, CBS_ASN1_SEQUENCE)) {
continue;
}
// Compare the CertID with the given certificate and issuer
if (ocsp_cert_id_matches_certificate(&cert_id, x509, issuerX509)) {
*out_single_response = single_response_original;
return true;
}
}
return false;
}
/**
* Get the BasicOCSPResponse from an OCSPResponse.
* If parsing succeeds and the response is of type basic, |basic_response| is set to it, and true is
* returned.
*/
static bool get_ocsp_basic_response(CBS *ocsp_response, CBS *basic_response) {
CBS tagged_response_bytes, response_bytes, response_type, response;
// Get the ResponseBytes out of the OCSPResponse
if (!CBS_get_asn1(ocsp_response, NULL /* responseStatus */, CBS_ASN1_ENUMERATED) ||
!CBS_get_asn1(ocsp_response, &tagged_response_bytes,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
!CBS_get_asn1(&tagged_response_bytes, &response_bytes,
CBS_ASN1_SEQUENCE)) {
return false;
}
// Parse the response type and data out of the ResponseBytes
if (!CBS_get_asn1(&response_bytes, &response_type, CBS_ASN1_OBJECT) ||
!CBS_get_asn1(&response_bytes, &response, CBS_ASN1_OCTETSTRING)) {
return false;
}
// Only basic OCSP responses are supported
if (OBJ_cbs2nid(&response_type) != NID_id_pkix_OCSP_basic) {
return false;
}
// Parse the octet string as a BasicOCSPResponse
return CBS_get_asn1(&response, basic_response, CBS_ASN1_SEQUENCE);
}
/**
* Get the SEQUENCE OF SingleResponse from a BasicOCSPResponse.
* If parsing succeeds, |single_responses| is set to point to the sequence of SingleResponse, and
* true is returned.
*/
static bool get_ocsp_single_responses(CBS *basic_response, CBS *single_responses) {
// Parse the ResponseData out of the BasicOCSPResponse. Ignore the rest.
CBS response_data;
if (!CBS_get_asn1(basic_response, &response_data, CBS_ASN1_SEQUENCE)) {
return false;
}
// Skip the version, responderID and producedAt fields
if (!CBS_get_optional_asn1(&response_data, NULL /* version */, NULL,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
!CBS_get_any_asn1_element(&response_data, NULL /* responderID */, NULL, NULL) ||
!CBS_get_any_asn1_element(&response_data, NULL /* producedAt */, NULL, NULL)) {
return false;
}
// Extract the list of SingleResponse.
return CBS_get_asn1(&response_data, single_responses, CBS_ASN1_SEQUENCE);
}
/**
* Get the SEQUENCE OF Extension from a SingleResponse.
* If parsing succeeds, |extensions| is set to point the the extension sequence and true is
* returned.
*/
static bool get_ocsp_single_response_extensions(CBS *single_response, CBS *extensions) {
// Skip the certID, certStatus, thisUpdate and optional nextUpdate fields.
if (!CBS_get_any_asn1_element(single_response, NULL /* certID */, NULL, NULL) ||
!CBS_get_any_asn1_element(single_response, NULL /* certStatus */, NULL, NULL) ||
!CBS_get_any_asn1_element(single_response, NULL /* thisUpdate */, NULL, NULL) ||
!CBS_get_optional_asn1(single_response, NULL /* nextUpdate */, NULL,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
return false;
}
// Get the list of Extension
return CBS_get_asn1(single_response, extensions,
CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1);
}
/*
* X509v3_get_ext_by_OBJ and X509v3_get_ext take const arguments, unlike the other *_get_ext
* functions.
* This means they cannot be used with X509Type_get_ext_oid, so these wrapper functions are used
* instead.
*/
static int _X509v3_get_ext_by_OBJ(X509_EXTENSIONS *exts, ASN1_OBJECT *obj, int lastpos) {
return X509v3_get_ext_by_OBJ(exts, obj, lastpos);
}
static X509_EXTENSION *_X509v3_get_ext(X509_EXTENSIONS* exts, int loc) {
return X509v3_get_ext(exts, loc);
}
/*
public static native byte[] get_ocsp_single_extension(byte[] ocspData, String oid,
long x509Ref, long issuerX509Ref);
*/
static jbyteArray NativeCrypto_get_ocsp_single_extension(JNIEnv *env, jclass,
jbyteArray ocspDataBytes, jstring oid, jlong x509Ref, jlong issuerX509Ref) {
ScopedByteArrayRO ocspData(env, ocspDataBytes);
if (ocspData.get() == NULL) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, reinterpret_cast<const uint8_t*>(ocspData.get()), ocspData.size());
// Start parsing the OCSPResponse
CBS ocsp_response;
if (!CBS_get_asn1(&cbs, &ocsp_response, CBS_ASN1_SEQUENCE)) {
return NULL;
}
// Get the BasicOCSPResponse from the OCSP Response
CBS basic_response;
if (!get_ocsp_basic_response(&ocsp_response, &basic_response)) {
return NULL;
}
// Get the list of SingleResponses from the BasicOCSPResponse
CBS responses;
if (!get_ocsp_single_responses(&basic_response, &responses)) {
return NULL;
}
// Find the response matching the certificate
X509* x509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(x509Ref));
X509* issuerX509 = reinterpret_cast<X509*>(static_cast<uintptr_t>(issuerX509Ref));
CBS single_response;
if (!find_ocsp_single_response(&responses, x509, issuerX509, &single_response)) {
return NULL;
}
// Get the extensions from the SingleResponse
CBS extensions;
if (!get_ocsp_single_response_extensions(&single_response, &extensions)) {
return NULL;
}
const uint8_t* ptr = CBS_data(&extensions);
Unique_X509_EXTENSIONS x509_exts(d2i_X509_EXTENSIONS(NULL, &ptr, CBS_len(&extensions)));
if (x509_exts.get() == NULL) {
return NULL;
}
return X509Type_get_ext_oid<X509_EXTENSIONS, _X509v3_get_ext_by_OBJ, _X509v3_get_ext>(
env, x509_exts.get(), oid);
}
#else
static jbyteArray NativeCrypto_get_ocsp_single_extension(JNIEnv*, jclass, jbyteArray, jstring,
jlong, jlong) {
return NULL;
}
#endif
static jlong NativeCrypto_getDirectBufferAddress(JNIEnv *env, jclass, jobject buffer) {
return reinterpret_cast<jlong>(env->GetDirectBufferAddress(buffer));
}
#define FILE_DESCRIPTOR "Ljava/io/FileDescriptor;"
#define SSL_CALLBACKS "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto$SSLHandshakeCallbacks;"
#define REF_EC_GROUP "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_GROUP;"
#define REF_EC_POINT "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EC_POINT;"
#define REF_EVP_AEAD_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_AEAD_CTX;"
#define REF_EVP_CIPHER_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_CIPHER_CTX;"
#define REF_EVP_PKEY "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_PKEY;"
#define REF_HMAC_CTX "L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$HMAC_CTX;"
static JNINativeMethod sNativeCryptoMethods[] = {
NATIVE_METHOD(NativeCrypto, clinit, "()Z"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_dynamic, "()V"),
NATIVE_METHOD(NativeCrypto, ENGINE_by_id, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_add, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_init, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_finish, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_free, "(J)I"),
NATIVE_METHOD(NativeCrypto, ENGINE_load_private_key, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, ENGINE_get_id, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, ENGINE_ctrl_cmd_string, "(JLjava/lang/String;Ljava/lang/String;I)I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_DH, "([B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_RSA, "([B[B[B[B[B[B[B[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_new_EC_KEY, "(" REF_EC_GROUP REF_EC_POINT "[B)J"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_type, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_public, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_print_params, "(" REF_EVP_PKEY ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_PKEY_cmp, "(" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS8_PRIV_KEY_INFO, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS8_PRIV_KEY_INFO, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_PUBKEY, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, d2i_PUBKEY, "([B)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PUBKEY, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PrivateKey, "(J)J"),
NATIVE_METHOD(NativeCrypto, getRSAPrivateKeyWrapper, "(Ljava/security/PrivateKey;[B)J"),
NATIVE_METHOD(NativeCrypto, getECPrivateKeyWrapper, "(Ljava/security/PrivateKey;" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, RSA_generate_key_ex, "(I[B)J"),
NATIVE_METHOD(NativeCrypto, RSA_size, "(" REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, RSA_private_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_public_encrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, RSA_private_decrypt, "(I[B[B" REF_EVP_PKEY "I)I"),
NATIVE_METHOD(NativeCrypto, get_RSA_private_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, get_RSA_public_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, DH_generate_parameters_ex, "(IJ)J"),
NATIVE_METHOD(NativeCrypto, DH_generate_key, "(" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_DH_params, "(" REF_EVP_PKEY ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_by_curve_name, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_new_arbitrary, "([B[B[B[B[B[BI)J"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_asn1_flag, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_set_point_conversion_form, "(" REF_EC_GROUP "I)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve_name, "(" REF_EC_GROUP ")Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_curve, "(" REF_EC_GROUP ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_order, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_degree, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_cofactor, "(" REF_EC_GROUP ")[B"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_GROUP_get_generator, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, get_EC_GROUP_type, "(" REF_EC_GROUP ")I"),
NATIVE_METHOD(NativeCrypto, EC_POINT_new, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_POINT_clear_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_set_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT "[B[B)V"),
NATIVE_METHOD(NativeCrypto, EC_POINT_get_affine_coordinates, "(" REF_EC_GROUP REF_EC_POINT ")[[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_generate_key, "(" REF_EC_GROUP ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get1_group, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_private_key, "(" REF_EVP_PKEY ")[B"),
NATIVE_METHOD(NativeCrypto, EC_KEY_get_public_key, "(" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EC_KEY_set_nonce_from_hash, "(" REF_EVP_PKEY "Z)V"),
NATIVE_METHOD(NativeCrypto, ECDH_compute_key, "([BI" REF_EVP_PKEY REF_EVP_PKEY ")I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_create, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_cleanup, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_destroy, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_MD_CTX_copy_ex, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestInit_ex, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestUpdateDirect, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestFinal_ex, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_get_digestbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_MD_block_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_MD_size, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignUpdateDirect, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestSignFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;)[B"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyInit, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;J" REF_EVP_PKEY ")J"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyUpdate, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyUpdateDirect, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;JI)V"),
NATIVE_METHOD(NativeCrypto, EVP_DigestVerifyFinal, "(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_MD_CTX;[BII)Z"),
NATIVE_METHOD(NativeCrypto, EVP_get_cipherbyname, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, EVP_CipherInit_ex, "(" REF_EVP_CIPHER_CTX "J[B[BZ)V"),
NATIVE_METHOD(NativeCrypto, EVP_CipherUpdate, "(" REF_EVP_CIPHER_CTX "[BI[BII)I"),
NATIVE_METHOD(NativeCrypto, EVP_CipherFinal_ex, "(" REF_EVP_CIPHER_CTX "[BI)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_iv_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_block_size, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_buf_len, "(" REF_EVP_CIPHER_CTX ")I"),
NATIVE_METHOD(NativeCrypto, get_EVP_CIPHER_CTX_final_used, "(" REF_EVP_CIPHER_CTX ")Z"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_padding, "(" REF_EVP_CIPHER_CTX "Z)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_set_key_length, "(" REF_EVP_CIPHER_CTX "I)V"),
NATIVE_METHOD(NativeCrypto, EVP_CIPHER_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_aead_aes_128_gcm, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_aead_aes_256_gcm, "()J"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_init, "(J[BI)J"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_cleanup, "(J)V"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_max_overhead, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_nonce_length, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_max_tag_len, "(J)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_seal, "(" REF_EVP_AEAD_CTX "[BI[B[BII[B)I"),
NATIVE_METHOD(NativeCrypto, EVP_AEAD_CTX_open, "(" REF_EVP_AEAD_CTX "[BI[B[BII[B)I"),
NATIVE_METHOD(NativeCrypto, HMAC_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, HMAC_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, HMAC_Init_ex, "(" REF_HMAC_CTX "[BJ)V"),
NATIVE_METHOD(NativeCrypto, HMAC_Update, "(" REF_HMAC_CTX "[BII)V"),
NATIVE_METHOD(NativeCrypto, HMAC_UpdateDirect, "(" REF_HMAC_CTX "JI)V"),
NATIVE_METHOD(NativeCrypto, HMAC_Final, "(" REF_HMAC_CTX ")[B"),
NATIVE_METHOD(NativeCrypto, RAND_seed, "([B)V"),
NATIVE_METHOD(NativeCrypto, RAND_load_file, "(Ljava/lang/String;J)I"),
NATIVE_METHOD(NativeCrypto, RAND_bytes, "([B)V"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid, "(Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_longName, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, OBJ_txt2nid_oid, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, create_BIO_InputStream, ("(L" TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream;Z)J")),
NATIVE_METHOD(NativeCrypto, create_BIO_OutputStream, "(Ljava/io/OutputStream;)J"),
NATIVE_METHOD(NativeCrypto, BIO_read, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, BIO_write, "(J[BII)V"),
NATIVE_METHOD(NativeCrypto, BIO_free_all, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_NAME_print_ex, "(JJ)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, d2i_X509_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, d2i_X509, "([B)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509, "(J)[B"),
NATIVE_METHOD(NativeCrypto, i2d_X509_PUBKEY, "(J)[B"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_PKCS7, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, d2i_PKCS7_bio, "(JI)[J"),
NATIVE_METHOD(NativeCrypto, i2d_PKCS7, "([J)[B"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_unpack_X509_bio, "(J)[J"),
NATIVE_METHOD(NativeCrypto, ASN1_seq_pack_X509, "([J)[B"),
NATIVE_METHOD(NativeCrypto, X509_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_cmp, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, get_X509_hashCode, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_print_ex, "(JJJJ)V"),
NATIVE_METHOD(NativeCrypto, X509_get_pubkey, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_get_subject_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_pubkey_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_issuerUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_subjectUID, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_kusage, "(J)[Z"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_xkusage, "(J)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_pathlen, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_delete_ext, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_crl_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_lastUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_nextUpdate, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext_oid, "(JLjava/lang/String;)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_revocationDate, "(J)J"),
NATIVE_METHOD(NativeCrypto, get_X509_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_REVOKED_ext_oids, "(JI)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_GENERAL_NAME_stack, "(JI)[[Ljava/lang/Object;"),
NATIVE_METHOD(NativeCrypto, X509_get_notBefore, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_notAfter, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_get_serialNumber, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_verify, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, get_X509_cert_info_enc, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_signature, "(J)[B"),
NATIVE_METHOD(NativeCrypto, get_X509_ex_flags, "(J)I"),
NATIVE_METHOD(NativeCrypto, X509_check_issued, "(JJ)I"),
NATIVE_METHOD(NativeCrypto, d2i_X509_CRL_bio, "(J)J"),
NATIVE_METHOD(NativeCrypto, PEM_read_bio_X509_CRL, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_cert, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get0_by_serial, "(J[B)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_REVOKED, "(J)[J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_CRL, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, X509_CRL_print, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_oid, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_X509_CRL_sig_alg_parameter, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_issuer_name, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_version, "(J)J"),
NATIVE_METHOD(NativeCrypto, X509_CRL_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_get_ext, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCrypto, X509_REVOKED_dup, "(J)J"),
NATIVE_METHOD(NativeCrypto, i2d_X509_REVOKED, "(J)[B"),
NATIVE_METHOD(NativeCrypto, X509_supported_extension, "(J)I"),
NATIVE_METHOD(NativeCrypto, ASN1_TIME_to_Calendar, "(JLjava/util/Calendar;)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_new, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_session_id_context, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_new, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_tls_channel_id, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_tls_channel_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set1_tls_channel_id, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_PrivateKey, "(J" REF_EVP_PKEY ")V"),
NATIVE_METHOD(NativeCrypto, SSL_use_certificate, "(J[J)V"),
NATIVE_METHOD(NativeCrypto, SSL_check_private_key, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_client_CA_list, "(J[[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_mode, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_mode, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_get_options, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_set_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_clear_options, "(JJ)J"),
NATIVE_METHOD(NativeCrypto, SSL_enable_signed_cert_timestamps, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_signed_cert_timestamp_list, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_signed_cert_timestamp_list, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_enable_ocsp_stapling, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ocsp_response, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_set_ocsp_response, "(J[B)V"),
NATIVE_METHOD(NativeCrypto, SSL_use_psk_identity_hint, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_client_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, set_SSL_psk_server_callback_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_cipher_lists, "(J[Ljava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_ciphers, "(J)[J"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_auth, "(J)I"),
NATIVE_METHOD(NativeCrypto, get_SSL_CIPHER_algorithm_mkey, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_set_accept_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_connect_state, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_verify, "(JI)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session, "(JJ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_session_creation_enabled, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_reject_peer_renegotiations, "(JZ)V"),
NATIVE_METHOD(NativeCrypto, SSL_set_tlsext_host_name, "(JLjava/lang/String;)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_servername, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "IZ[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_do_handshake_bio, "(JJJ" SSL_CALLBACKS "Z[B[B)J"),
NATIVE_METHOD(NativeCrypto, SSL_renegotiate, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_certificate, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_get_peer_cert_chain, "(J)[J"),
NATIVE_METHOD(NativeCrypto, SSL_read, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)I"),
NATIVE_METHOD(NativeCrypto, SSL_read_BIO, "(J[BIIJJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_write, "(J" FILE_DESCRIPTOR SSL_CALLBACKS "[BIII)V"),
NATIVE_METHOD(NativeCrypto, SSL_write_BIO, "(J[BIJ" SSL_CALLBACKS ")I"),
NATIVE_METHOD(NativeCrypto, SSL_interrupt, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown, "(J" FILE_DESCRIPTOR SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_shutdown_BIO, "(JJJ" SSL_CALLBACKS ")V"),
NATIVE_METHOD(NativeCrypto, SSL_get_shutdown, "(J)I"),
NATIVE_METHOD(NativeCrypto, SSL_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_session_id, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_time, "(J)J"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_get_version, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_cipher, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, SSL_SESSION_free, "(J)V"),
NATIVE_METHOD(NativeCrypto, i2d_SSL_SESSION, "(J)[B"),
NATIVE_METHOD(NativeCrypto, d2i_SSL_SESSION, "([B)J"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_enable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_CTX_disable_npn, "(J)V"),
NATIVE_METHOD(NativeCrypto, SSL_get_npn_negotiated_protocol, "(J)[B"),
NATIVE_METHOD(NativeCrypto, SSL_set_alpn_protos, "(J[B)I"),
NATIVE_METHOD(NativeCrypto, SSL_get0_alpn_selected, "(J)[B"),
NATIVE_METHOD(NativeCrypto, ERR_peek_last_error, "()J"),
NATIVE_METHOD(NativeCrypto, SSL_CIPHER_get_kx_name, "(J)Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_cipher_names, "(Ljava/lang/String;)[Ljava/lang/String;"),
NATIVE_METHOD(NativeCrypto, get_ocsp_single_extension, "([BLjava/lang/String;JJ)[B"),
NATIVE_METHOD(NativeCrypto, getDirectBufferAddress, "(Ljava/nio/Buffer;)J"),
};
static jclass getGlobalRefToClass(JNIEnv* env, const char* className) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(className));
jclass globalRef = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (globalRef == NULL) {
ALOGE("failed to find class %s", className);
abort();
}
return globalRef;
}
static jmethodID getMethodRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jmethodID localMethod = env->GetMethodID(clazz, name, sig);
if (localMethod == NULL) {
ALOGE("could not find method %s", name);
abort();
}
return localMethod;
}
static jfieldID getFieldRef(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
jfieldID localField = env->GetFieldID(clazz, name, sig);
if (localField == NULL) {
ALOGE("could not find field %s", name);
abort();
}
return localField;
}
static void initialize_conscrypt(JNIEnv* env) {
jniRegisterNativeMethods(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeCrypto",
sNativeCryptoMethods, NELEM(sNativeCryptoMethods));
cryptoUpcallsClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/CryptoUpcalls");
nativeRefClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef");
openSslInputStreamClass = getGlobalRefToClass(env,
TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/OpenSSLBIOInputStream");
nativeRef_context = getFieldRef(env, nativeRefClass, "context", "J");
calendar_setMethod = getMethodRef(env, calendarClass, "set", "(IIIIII)V");
inputStream_readMethod = getMethodRef(env, inputStreamClass, "read", "([B)I");
integer_valueOfMethod = env->GetStaticMethodID(integerClass, "valueOf",
"(I)Ljava/lang/Integer;");
openSslInputStream_readLineMethod = getMethodRef(env, openSslInputStreamClass, "gets",
"([B)I");
outputStream_writeMethod = getMethodRef(env, outputStreamClass, "write", "([B)V");
outputStream_flushMethod = getMethodRef(env, outputStreamClass, "flush", "()V");
#ifdef CONSCRYPT_UNBUNDLED
findAsynchronousCloseMonitorFuncs();
#endif
}
static jclass findClass(JNIEnv* env, const char* name) {
ScopedLocalRef<jclass> localClass(env, env->FindClass(name));
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
if (result == NULL) {
ALOGE("failed to find class '%s'", name);
abort();
}
return result;
}
#ifdef STATIC_LIB
// Give client libs everything they need to initialize our JNI
int libconscrypt_JNI_OnLoad(JavaVM *vm, void*) {
#else
// Use JNI_OnLoad for when we're standalone
int JNI_OnLoad(JavaVM *vm, void*) {
JNI_TRACE("JNI_OnLoad NativeCrypto");
#endif
gJavaVM = vm;
JNIEnv *env;
if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
ALOGE("Could not get JNIEnv");
return JNI_ERR;
}
byteArrayClass = findClass(env, "[B");
calendarClass = findClass(env, "java/util/Calendar");
inputStreamClass = findClass(env, "java/io/InputStream");
integerClass = findClass(env, "java/lang/Integer");
objectClass = findClass(env, "java/lang/Object");
objectArrayClass = findClass(env, "[Ljava/lang/Object;");
outputStreamClass = findClass(env, "java/io/OutputStream");
stringClass = findClass(env, "java/lang/String");
initialize_conscrypt(env);
return JNI_VERSION_1_6;
}
/* vim: softtabstop=4:shiftwidth=4:expandtab */
/* Local Variables: */
/* mode: c++ */
/* tab-width: 4 */
/* indent-tabs-mode: nil */
/* c-basic-offset: 4 */
/* End: */
|
//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsTargetHandler.h"
#include "MipsLinkingContext.h"
#include "MipsRelocationHandler.h"
#include "lld/ReaderWriter/RelocationHelperFunctions.h"
using namespace lld;
using namespace elf;
using namespace llvm::ELF;
namespace {
inline void applyReloc(uint8_t *location, uint32_t result) {
auto target = reinterpret_cast<llvm::support::ulittle32_t *>(location);
*target = result | *target;
}
/// \brief Calculate AHL value combines addends from 'hi' and 'lo' relocations.
inline int64_t calcAHL(int64_t AHI, int64_t ALO) {
AHI &= 0xffff;
ALO &= 0xffff;
return (AHI << 16) + (int16_t)ALO;
}
/// \brief R_MIPS_32
/// local/external: word32 S + A (truncate)
void reloc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) {
uint32_t result = (uint32_t)(S + A);
applyReloc(location, result);
}
/// \brief R_MIPS_HI16
/// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate)
/// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify)
void relocHi16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
uint64_t GP, bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = (AHL + GP - P) - (int16_t)(AHL + GP - P);
else
result = (AHL + S) - (int16_t)(AHL + S);
result = lld::scatterBits<uint32_t>(result >> 16, 0xffff);
applyReloc(location, result);
}
/// \brief R_MIPS_LO16
/// local/external: lo16 AHL + S (truncate)
/// _gp_disp : lo16 AHL + GP - P + 4 (verify)
void relocLo16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
uint64_t GP, bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = AHL + GP - P + 4;
else
result = AHL + S;
result = lld::scatterBits<uint32_t>(result, 0xffff);
applyReloc(location, result);
}
/// \brief R_MIPS_GOT16
/// local/external: rel16 G (verify)
void relocGOT16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
uint64_t GP) {
// FIXME (simon): for local sym put high 16 bit of AHL to the GOT
int32_t G = (int32_t)(S - GP);
int32_t result = lld::scatterBits<uint32_t>(G, 0xffff);
applyReloc(location, result);
}
/// \brief R_MIPS_CALL16
/// external: rel16 G (verify)
void relocCall16(uint8_t *location, uint64_t P, uint64_t S, int64_t A,
uint64_t GP) {
int32_t G = (int32_t)(S - GP);
int32_t result = lld::scatterBits<uint32_t>(G, 0xffff);
applyReloc(location, result);
}
} // end anon namespace
MipsTargetRelocationHandler::MipsTargetRelocationHandler(
const MipsLinkingContext &context, const MipsTargetHandler &handler)
: _context(context), _targetHandler(handler) {}
void
MipsTargetRelocationHandler::savePairedRelocation(const lld::AtomLayout &atom,
const Reference &ref) const {
auto pi = _pairedRelocations.find(&atom);
if (pi == _pairedRelocations.end())
pi = _pairedRelocations.emplace(&atom, PairedRelocationsT()).first;
pi->second.push_back(&ref);
}
void MipsTargetRelocationHandler::applyPairedRelocations(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom,
int64_t loAddend) const {
auto pi = _pairedRelocations.find(&atom);
if (pi == _pairedRelocations.end())
return;
for (auto ri : pi->second) {
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ri->offsetInAtom();
uint64_t targetVAddress = writer.addressOfAtom(ri->target());
uint64_t relocVAddress = atom._virtualAddr + ri->offsetInAtom();
int64_t ahl = calcAHL(ri->addend(), loAddend);
switch (ri->kind()) {
case R_MIPS_HI16:
relocHi16(location, relocVAddress, targetVAddress, ahl,
_targetHandler.getGPDispSymAddr(),
ri->target()->name() == "_gp_disp");
break;
case R_MIPS_GOT16:
relocGOT16(location, relocVAddress, targetVAddress, ahl,
_targetHandler.getGPDispSymAddr());
break;
default:
llvm_unreachable("Unknown type of paired relocation.");
}
}
_pairedRelocations.erase(pi);
}
error_code MipsTargetRelocationHandler::applyRelocation(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom,
const Reference &ref) const {
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ref.offsetInAtom();
uint64_t targetVAddress = writer.addressOfAtom(ref.target());
uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom();
switch (ref.kind()) {
case R_MIPS_NONE:
break;
case R_MIPS_32:
reloc32(location, relocVAddress, targetVAddress, ref.addend());
break;
case R_MIPS_HI16:
savePairedRelocation(atom, ref);
break;
case R_MIPS_LO16:
relocLo16(location, relocVAddress, targetVAddress, calcAHL(0, ref.addend()),
_targetHandler.getGPDispSymAddr(),
ref.target()->name() == "_gp_disp");
applyPairedRelocations(writer, buf, atom, ref.addend());
break;
case R_MIPS_GOT16:
savePairedRelocation(atom, ref);
break;
case R_MIPS_CALL16:
relocCall16(location, relocVAddress, targetVAddress, ref.addend(),
_targetHandler.getGPDispSymAddr());
break;
case R_MIPS_JALR:
// We do not do JALR optimization now.
break;
case lld::Reference::kindLayoutAfter:
case lld::Reference::kindLayoutBefore:
case lld::Reference::kindInGroup:
break;
default: {
std::string str;
llvm::raw_string_ostream s(str);
auto name = _context.stringFromRelocKind(ref.kind());
s << "Unhandled relocation: "
<< (name ? *name : "<unknown>") << " (" << ref.kind() << ")";
llvm_unreachable(s.str().c_str());
}
}
return error_code::success();
}
[Mips] Explicitly cast ulittle32_t to the uint32_t to fix Visual Studio
compile error.
git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@197344 91177308-0d34-0410-b5e6-96231b3b80d8
//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsTargetHandler.h"
#include "MipsLinkingContext.h"
#include "MipsRelocationHandler.h"
#include "lld/ReaderWriter/RelocationHelperFunctions.h"
using namespace lld;
using namespace elf;
using namespace llvm::ELF;
namespace {
inline void applyReloc(uint8_t *location, uint32_t result) {
auto target = reinterpret_cast<llvm::support::ulittle32_t *>(location);
*target = result | uint32_t(*target);
}
/// \brief Calculate AHL value combines addends from 'hi' and 'lo' relocations.
inline int64_t calcAHL(int64_t AHI, int64_t ALO) {
AHI &= 0xffff;
ALO &= 0xffff;
return (AHI << 16) + (int16_t)ALO;
}
/// \brief R_MIPS_32
/// local/external: word32 S + A (truncate)
void reloc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) {
uint32_t result = (uint32_t)(S + A);
applyReloc(location, result);
}
/// \brief R_MIPS_HI16
/// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate)
/// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify)
void relocHi16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
uint64_t GP, bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = (AHL + GP - P) - (int16_t)(AHL + GP - P);
else
result = (AHL + S) - (int16_t)(AHL + S);
result = lld::scatterBits<uint32_t>(result >> 16, 0xffff);
applyReloc(location, result);
}
/// \brief R_MIPS_LO16
/// local/external: lo16 AHL + S (truncate)
/// _gp_disp : lo16 AHL + GP - P + 4 (verify)
void relocLo16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
uint64_t GP, bool isGPDisp) {
int32_t result = 0;
if (isGPDisp)
result = AHL + GP - P + 4;
else
result = AHL + S;
result = lld::scatterBits<uint32_t>(result, 0xffff);
applyReloc(location, result);
}
/// \brief R_MIPS_GOT16
/// local/external: rel16 G (verify)
void relocGOT16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL,
uint64_t GP) {
// FIXME (simon): for local sym put high 16 bit of AHL to the GOT
int32_t G = (int32_t)(S - GP);
int32_t result = lld::scatterBits<uint32_t>(G, 0xffff);
applyReloc(location, result);
}
/// \brief R_MIPS_CALL16
/// external: rel16 G (verify)
void relocCall16(uint8_t *location, uint64_t P, uint64_t S, int64_t A,
uint64_t GP) {
int32_t G = (int32_t)(S - GP);
int32_t result = lld::scatterBits<uint32_t>(G, 0xffff);
applyReloc(location, result);
}
} // end anon namespace
MipsTargetRelocationHandler::MipsTargetRelocationHandler(
const MipsLinkingContext &context, const MipsTargetHandler &handler)
: _context(context), _targetHandler(handler) {}
void
MipsTargetRelocationHandler::savePairedRelocation(const lld::AtomLayout &atom,
const Reference &ref) const {
auto pi = _pairedRelocations.find(&atom);
if (pi == _pairedRelocations.end())
pi = _pairedRelocations.emplace(&atom, PairedRelocationsT()).first;
pi->second.push_back(&ref);
}
void MipsTargetRelocationHandler::applyPairedRelocations(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom,
int64_t loAddend) const {
auto pi = _pairedRelocations.find(&atom);
if (pi == _pairedRelocations.end())
return;
for (auto ri : pi->second) {
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ri->offsetInAtom();
uint64_t targetVAddress = writer.addressOfAtom(ri->target());
uint64_t relocVAddress = atom._virtualAddr + ri->offsetInAtom();
int64_t ahl = calcAHL(ri->addend(), loAddend);
switch (ri->kind()) {
case R_MIPS_HI16:
relocHi16(location, relocVAddress, targetVAddress, ahl,
_targetHandler.getGPDispSymAddr(),
ri->target()->name() == "_gp_disp");
break;
case R_MIPS_GOT16:
relocGOT16(location, relocVAddress, targetVAddress, ahl,
_targetHandler.getGPDispSymAddr());
break;
default:
llvm_unreachable("Unknown type of paired relocation.");
}
}
_pairedRelocations.erase(pi);
}
error_code MipsTargetRelocationHandler::applyRelocation(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom,
const Reference &ref) const {
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ref.offsetInAtom();
uint64_t targetVAddress = writer.addressOfAtom(ref.target());
uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom();
switch (ref.kind()) {
case R_MIPS_NONE:
break;
case R_MIPS_32:
reloc32(location, relocVAddress, targetVAddress, ref.addend());
break;
case R_MIPS_HI16:
savePairedRelocation(atom, ref);
break;
case R_MIPS_LO16:
relocLo16(location, relocVAddress, targetVAddress, calcAHL(0, ref.addend()),
_targetHandler.getGPDispSymAddr(),
ref.target()->name() == "_gp_disp");
applyPairedRelocations(writer, buf, atom, ref.addend());
break;
case R_MIPS_GOT16:
savePairedRelocation(atom, ref);
break;
case R_MIPS_CALL16:
relocCall16(location, relocVAddress, targetVAddress, ref.addend(),
_targetHandler.getGPDispSymAddr());
break;
case R_MIPS_JALR:
// We do not do JALR optimization now.
break;
case lld::Reference::kindLayoutAfter:
case lld::Reference::kindLayoutBefore:
case lld::Reference::kindInGroup:
break;
default: {
std::string str;
llvm::raw_string_ostream s(str);
auto name = _context.stringFromRelocKind(ref.kind());
s << "Unhandled relocation: "
<< (name ? *name : "<unknown>") << " (" << ref.kind() << ")";
llvm_unreachable(s.str().c_str());
}
}
return error_code::success();
}
|
//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsLinkingContext.h"
#include "MipsRelocationHandler.h"
#include "MipsTargetLayout.h"
#include "llvm/Support/Format.h"
using namespace lld;
using namespace elf;
using namespace llvm::ELF;
using namespace llvm::support;
namespace {
enum class CrossJumpMode {
None, // Not a jump or non-isa-cross jump
ToRegular, // cross isa jump to regular symbol
ToMicro // cross isa jump to microMips symbol
};
struct MipsRelocationParams {
uint8_t _size; // Relocations's size in bytes
uint64_t _mask; // Read/write mask of relocation
uint8_t _shift; // Relocation's addendum left shift size
bool _shuffle; // Relocation's addendum/result needs to be shuffled
};
template <class ELFT> class RelocationHandler : public TargetRelocationHandler {
public:
RelocationHandler(MipsLinkingContext &ctx, MipsTargetLayout<ELFT> &layout)
: _ctx(ctx), _targetLayout(layout) {}
std::error_code applyRelocation(ELFWriter &writer,
llvm::FileOutputBuffer &buf,
const AtomLayout &atom,
const Reference &ref) const override;
private:
MipsLinkingContext &_ctx;
MipsTargetLayout<ELFT> &_targetLayout;
};
}
static MipsRelocationParams getRelocationParams(uint32_t rType) {
switch (rType) {
case R_MIPS_NONE:
return {4, 0x0, 0, false};
case R_MIPS_64:
case R_MIPS_SUB:
return {8, 0xffffffffffffffffull, 0, false};
case R_MIPS_32:
case R_MIPS_GPREL32:
case R_MIPS_PC32:
case R_MIPS_EH:
return {4, 0xffffffff, 0, false};
case LLD_R_MIPS_32_HI16:
return {4, 0xffff0000, 0, false};
case LLD_R_MIPS_64_HI16:
return {8, 0xffffffffffff0000ull, 0, false};
case R_MIPS_26:
case LLD_R_MIPS_GLOBAL_26:
return {4, 0x3ffffff, 2, false};
case R_MIPS_PC18_S3:
return {4, 0x3ffff, 3, false};
case R_MIPS_PC19_S2:
return {4, 0x7ffff, 2, false};
case R_MIPS_PC21_S2:
return {4, 0x1fffff, 2, false};
case R_MIPS_PC26_S2:
return {4, 0x3ffffff, 2, false};
case R_MIPS_HI16:
case R_MIPS_LO16:
case R_MIPS_PCHI16:
case R_MIPS_PCLO16:
case R_MIPS_GPREL16:
case R_MIPS_GOT16:
case R_MIPS_GOT_DISP:
case R_MIPS_GOT_PAGE:
case R_MIPS_GOT_OFST:
case R_MIPS_GOT_HI16:
case R_MIPS_GOT_LO16:
case R_MIPS_CALL_HI16:
case R_MIPS_CALL_LO16:
case R_MIPS_TLS_DTPREL_HI16:
case R_MIPS_TLS_DTPREL_LO16:
case R_MIPS_TLS_TPREL_HI16:
case R_MIPS_TLS_TPREL_LO16:
case LLD_R_MIPS_HI16:
case LLD_R_MIPS_LO16:
return {4, 0xffff, 0, false};
case R_MICROMIPS_TLS_DTPREL_HI16:
case R_MICROMIPS_TLS_DTPREL_LO16:
case R_MICROMIPS_TLS_TPREL_HI16:
case R_MICROMIPS_TLS_TPREL_LO16:
return {4, 0xffff, 0, true};
case R_MICROMIPS_26_S1:
case LLD_R_MICROMIPS_GLOBAL_26_S1:
return {4, 0x3ffffff, 1, true};
case R_MICROMIPS_HI16:
case R_MICROMIPS_LO16:
case R_MICROMIPS_GOT16:
return {4, 0xffff, 0, true};
case R_MICROMIPS_PC16_S1:
return {4, 0xffff, 1, true};
case R_MICROMIPS_PC7_S1:
return {4, 0x7f, 1, false};
case R_MICROMIPS_PC10_S1:
return {4, 0x3ff, 1, false};
case R_MICROMIPS_PC23_S2:
return {4, 0x7fffff, 2, true};
case R_MICROMIPS_PC18_S3:
return {4, 0x3ffff, 3, true};
case R_MICROMIPS_PC19_S2:
return {4, 0x7ffff, 2, true};
case R_MICROMIPS_PC21_S2:
return {4, 0x1fffff, 2, true};
case R_MICROMIPS_PC26_S2:
return {4, 0x3ffffff, 2, true};
case R_MIPS_CALL16:
case R_MIPS_TLS_GD:
case R_MIPS_TLS_LDM:
case R_MIPS_TLS_GOTTPREL:
return {4, 0xffff, 0, false};
case R_MICROMIPS_CALL16:
case R_MICROMIPS_TLS_GD:
case R_MICROMIPS_TLS_LDM:
case R_MICROMIPS_TLS_GOTTPREL:
case R_MICROMIPS_GOT_DISP:
case R_MICROMIPS_GOT_PAGE:
case R_MICROMIPS_GOT_OFST:
case R_MICROMIPS_GOT_HI16:
case R_MICROMIPS_GOT_LO16:
case R_MICROMIPS_CALL_HI16:
case R_MICROMIPS_CALL_LO16:
return {4, 0xffff, 0, true};
case R_MIPS_JALR:
return {4, 0x0, 0, false};
case R_MICROMIPS_JALR:
return {4, 0x0, 0, true};
case R_MIPS_REL32:
return {4, 0xffffffff, 0, false};
case R_MIPS_JUMP_SLOT:
case R_MIPS_COPY:
case R_MIPS_TLS_DTPMOD32:
case R_MIPS_TLS_DTPREL32:
case R_MIPS_TLS_TPREL32:
// Ignore runtime relocations.
return {4, 0x0, 0, false};
case R_MIPS_TLS_DTPMOD64:
case R_MIPS_TLS_DTPREL64:
case R_MIPS_TLS_TPREL64:
return {8, 0x0, 0, false};
case LLD_R_MIPS_GLOBAL_GOT:
case LLD_R_MIPS_STO_PLT:
// Do nothing.
return {4, 0x0, 0, false};
default:
llvm_unreachable("Unknown relocation");
}
}
/// \brief R_MIPS_32
/// local/external: word32 S + A (truncate)
static int32_t reloc32(uint64_t S, int64_t A) { return S + A; }
/// \brief R_MIPS_64
/// local/external: word64 S + A (truncate)
static int64_t reloc64(uint64_t S, int64_t A) { return S + A; }
/// \brief R_MIPS_SUB
/// local/external: word64 S - A (truncate)
static int64_t relocSub(uint64_t S, int64_t A) { return S - A; }
/// \brief R_MIPS_PC32
/// local/external: word32 S + A - P (truncate)
static int32_t relocpc32(uint64_t P, uint64_t S, int64_t A) {
return S + A - P;
}
/// \brief R_MIPS_26, R_MICROMIPS_26_S1
/// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2
static int32_t reloc26loc(uint64_t P, uint64_t S, int32_t A, uint32_t shift) {
return (A | ((P + 4) & (0xfc000000 << shift))) + S;
}
/// \brief LLD_R_MIPS_GLOBAL_26, LLD_R_MICROMIPS_GLOBAL_26_S1
/// external: (sign-extend(A) + S) >> 2
static int32_t reloc26ext(uint64_t S, int32_t A, uint32_t shift) {
A = shift == 1 ? llvm::SignExtend32<27>(A) : llvm::SignExtend32<28>(A);
return A + S;
}
/// \brief R_MIPS_HI16, R_MIPS_TLS_DTPREL_HI16, R_MIPS_TLS_TPREL_HI16,
/// R_MICROMIPS_HI16, R_MICROMIPS_TLS_DTPREL_HI16, R_MICROMIPS_TLS_TPREL_HI16,
/// LLD_R_MIPS_HI16
/// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate)
/// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify)
static int32_t relocHi16(uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp) {
int32_t result = isGPDisp ? AHL + S - P : AHL + S;
return (result + 0x8000) >> 16;
}
/// \brief R_MIPS_PCHI16
/// local/external: hi16 (S + AHL - P)
static int32_t relocPcHi16(uint64_t P, uint64_t S, int64_t AHL) {
int32_t result = S + AHL - P;
return (result + 0x8000) >> 16;
}
/// \brief R_MIPS_LO16, R_MIPS_TLS_DTPREL_LO16, R_MIPS_TLS_TPREL_LO16,
/// R_MICROMIPS_LO16, R_MICROMIPS_TLS_DTPREL_LO16, R_MICROMIPS_TLS_TPREL_LO16,
/// LLD_R_MIPS_LO16
/// local/external: lo16 AHL + S (truncate)
/// _gp_disp : lo16 AHL + GP - P + 4 (verify)
static int32_t relocLo16(uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp,
bool micro) {
return isGPDisp ? AHL + S - P + (micro ? 3 : 4) : AHL + S;
}
/// \brief R_MIPS_PCLO16
/// local/external: lo16 (S + AHL - P)
static int32_t relocPcLo16(uint64_t P, uint64_t S, int64_t AHL) {
AHL = llvm::SignExtend32<16>(AHL);
return S + AHL - P;
}
/// \brief R_MIPS_GOT16, R_MIPS_CALL16, R_MICROMIPS_GOT16, R_MICROMIPS_CALL16
/// rel16 G (verify)
static int64_t relocGOT(uint64_t S, uint64_t GP) {
return S - GP;
}
/// \brief R_MIPS_GOT_LO16, R_MIPS_CALL_LO16
/// R_MICROMIPS_GOT_LO16, R_MICROMIPS_CALL_LO16
/// rel16 G (truncate)
static int64_t relocGOTLo16(uint64_t S, uint64_t GP) {
return S - GP;
}
/// \brief R_MIPS_GOT_HI16, R_MIPS_CALL_HI16,
/// R_MICROMIPS_GOT_HI16, R_MICROMIPS_CALL_HI16
/// rel16 %high(G) (truncate)
static int64_t relocGOTHi16(uint64_t S, uint64_t GP) {
return (S - GP + 0x8000) >> 16;
}
/// R_MIPS_GOT_OFST, R_MICROMIPS_GOT_OFST
/// rel16 offset of (S+A) from the page pointer (verify)
static int32_t relocGOTOfst(uint64_t S, int64_t A) {
int64_t page = (S + A + 0x8000) & ~0xffff;
return S + A - page;
}
/// \brief R_MIPS_GPREL16
/// local: sign-extend(A) + S + GP0 - GP
/// external: sign-extend(A) + S - GP
static int64_t relocGPRel16(uint64_t S, int64_t A, uint64_t GP) {
// We added GP0 to addendum for a local symbol during a Relocation pass.
return llvm::SignExtend32<16>(A) + S - GP;
}
/// \brief R_MIPS_GPREL32
/// local: rel32 A + S + GP0 - GP (truncate)
static int64_t relocGPRel32(uint64_t S, int64_t A, uint64_t GP) {
// We added GP0 to addendum for a local symbol during a Relocation pass.
return A + S - GP;
}
/// \brief R_MIPS_PC18_S3, R_MICROMIPS_PC18_S3
/// local/external: (S + A - P) >> 3 (P with cleared 3 less significant bits)
static int32_t relocPc18(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<21>(A);
// FIXME (simon): Check that S + A has 8-byte alignment
int32_t result = S + A - ((P | 7) ^ 7);
return result;
}
/// \brief R_MIPS_PC19_S2, R_MICROMIPS_PC19_S2
/// local/external: (S + A - P) >> 2
static int32_t relocPc19(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<21>(A);
// FIXME (simon): Check that S + A has 4-byte alignment
return S + A - P;
}
/// \brief R_MIPS_PC21_S2, R_MICROMIPS_PC21_S2
/// local/external: (S + A - P) >> 2
static int32_t relocPc21(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<23>(A);
// FIXME (simon): Check that S + A has 4-byte alignment
return S + A - P;
}
/// \brief R_MIPS_PC26_S2, R_MICROMIPS_PC26_S2
/// local/external: (S + A - P) >> 2
static int32_t relocPc26(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<28>(A);
// FIXME (simon): Check that S + A has 4-byte alignment
return S + A - P;
}
/// \brief R_MICROMIPS_PC7_S1
static int32_t relocPc7(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<8>(A);
return S + A - P;
}
/// \brief R_MICROMIPS_PC10_S1
static int32_t relocPc10(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<11>(A);
return S + A - P;
}
/// \brief R_MICROMIPS_PC16_S1
static int32_t relocPc16(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<17>(A);
return S + A - P;
}
/// \brief R_MICROMIPS_PC23_S2
static uint32_t relocPc23(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<25>(A);
int32_t result = S + A - P;
// Check addiupc 16MB range.
if (result + 0x1000000 >= 0x2000000)
llvm::errs() << "The addiupc instruction immediate "
<< llvm::format_hex(result, 10) << " is out of range.\n";
return result;
}
/// \brief LLD_R_MIPS_32_HI16, LLD_R_MIPS_64_HI16
static int64_t relocMaskLow16(uint64_t S, int64_t A) {
return S + A + 0x8000;
}
static int64_t relocRel32(int64_t A) {
// If output relocation format is REL and the input one is RELA, the only
// method to transfer the relocation addend from the input relocation
// to the output dynamic relocation is to save this addend to the location
// modified by R_MIPS_REL32.
return A;
}
static std::error_code adjustJumpOpCode(uint64_t &ins, uint64_t tgt,
CrossJumpMode mode) {
if (mode == CrossJumpMode::None)
return std::error_code();
bool toMicro = mode == CrossJumpMode::ToMicro;
uint32_t opNative = toMicro ? 0x03 : 0x3d;
uint32_t opCross = toMicro ? 0x1d : 0x3c;
if ((tgt & 1) != toMicro)
return make_dynamic_error_code("Incorrect bit 0 for the jalx target");
if (tgt & 2)
return make_dynamic_error_code(Twine("The jalx target 0x") +
Twine::utohexstr(tgt) +
" is not word-aligned");
uint8_t op = ins >> 26;
if (op != opNative && op != opCross)
return make_dynamic_error_code(Twine("Unsupported jump opcode (0x") +
Twine::utohexstr(op) +
") for ISA modes cross call");
ins = (ins & ~(0x3f << 26)) | (opCross << 26);
return std::error_code();
}
static bool isMicroMipsAtom(const Atom *a) {
if (const auto *da = dyn_cast<DefinedAtom>(a))
return da->codeModel() == DefinedAtom::codeMipsMicro ||
da->codeModel() == DefinedAtom::codeMipsMicroPIC;
return false;
}
static CrossJumpMode getCrossJumpMode(const Reference &ref) {
if (!isa<DefinedAtom>(ref.target()))
return CrossJumpMode::None;
bool isTgtMicro = isMicroMipsAtom(ref.target());
switch (ref.kindValue()) {
case R_MIPS_26:
case LLD_R_MIPS_GLOBAL_26:
return isTgtMicro ? CrossJumpMode::ToMicro : CrossJumpMode::None;
case R_MICROMIPS_26_S1:
case LLD_R_MICROMIPS_GLOBAL_26_S1:
return isTgtMicro ? CrossJumpMode::None : CrossJumpMode::ToRegular;
default:
return CrossJumpMode::None;
}
}
static uint32_t microShuffle(uint32_t ins) {
return ((ins & 0xffff) << 16) | ((ins & 0xffff0000) >> 16);
}
static ErrorOr<int64_t> calculateRelocation(Reference::KindValue kind,
Reference::Addend addend,
uint64_t tgtAddr, uint64_t relAddr,
uint64_t gpAddr, bool isGP,
bool isCrossJump) {
if (!tgtAddr) {
isGP = false;
isCrossJump = false;
}
switch (kind) {
case R_MIPS_NONE:
return 0;
case R_MIPS_32:
return reloc32(tgtAddr, addend);
case R_MIPS_64:
return reloc64(tgtAddr, addend);
case R_MIPS_SUB:
return relocSub(tgtAddr, addend);
case R_MIPS_26:
return reloc26loc(relAddr, tgtAddr, addend, 2);
case R_MICROMIPS_26_S1:
return reloc26loc(relAddr, tgtAddr, addend, isCrossJump ? 2 : 1);
case R_MIPS_HI16:
case R_MICROMIPS_HI16:
return relocHi16(relAddr, tgtAddr, addend, isGP);
case R_MIPS_PCHI16:
return relocPcHi16(relAddr, tgtAddr, addend);
case R_MIPS_LO16:
return relocLo16(relAddr, tgtAddr, addend, isGP, false);
case R_MIPS_PCLO16:
return relocPcLo16(relAddr, tgtAddr, addend);
case R_MICROMIPS_LO16:
return relocLo16(relAddr, tgtAddr, addend, isGP, true);
case R_MIPS_GOT_LO16:
case R_MIPS_CALL_LO16:
case R_MICROMIPS_GOT_LO16:
case R_MICROMIPS_CALL_LO16:
return relocGOTLo16(tgtAddr, gpAddr);
case R_MIPS_GOT_HI16:
case R_MIPS_CALL_HI16:
case R_MICROMIPS_GOT_HI16:
case R_MICROMIPS_CALL_HI16:
return relocGOTHi16(tgtAddr, gpAddr);
case R_MIPS_EH:
case R_MIPS_GOT16:
case R_MIPS_CALL16:
case R_MIPS_GOT_DISP:
case R_MIPS_GOT_PAGE:
case R_MICROMIPS_GOT_DISP:
case R_MICROMIPS_GOT_PAGE:
case R_MICROMIPS_GOT16:
case R_MICROMIPS_CALL16:
case R_MIPS_TLS_GD:
case R_MIPS_TLS_LDM:
case R_MIPS_TLS_GOTTPREL:
case R_MICROMIPS_TLS_GD:
case R_MICROMIPS_TLS_LDM:
case R_MICROMIPS_TLS_GOTTPREL:
return relocGOT(tgtAddr, gpAddr);
case R_MIPS_GOT_OFST:
case R_MICROMIPS_GOT_OFST:
return relocGOTOfst(tgtAddr, addend);
case R_MIPS_PC18_S3:
case R_MICROMIPS_PC18_S3:
return relocPc18(relAddr, tgtAddr, addend);
case R_MIPS_PC19_S2:
case R_MICROMIPS_PC19_S2:
return relocPc19(relAddr, tgtAddr, addend);
case R_MIPS_PC21_S2:
case R_MICROMIPS_PC21_S2:
return relocPc21(relAddr, tgtAddr, addend);
case R_MIPS_PC26_S2:
case R_MICROMIPS_PC26_S2:
return relocPc26(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC7_S1:
return relocPc7(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC10_S1:
return relocPc10(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC16_S1:
return relocPc16(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC23_S2:
return relocPc23(relAddr, tgtAddr, addend);
case R_MIPS_TLS_DTPREL_HI16:
case R_MIPS_TLS_TPREL_HI16:
case R_MICROMIPS_TLS_DTPREL_HI16:
case R_MICROMIPS_TLS_TPREL_HI16:
return relocHi16(0, tgtAddr, addend, false);
case R_MIPS_TLS_DTPREL_LO16:
case R_MIPS_TLS_TPREL_LO16:
return relocLo16(0, tgtAddr, addend, false, false);
case R_MICROMIPS_TLS_DTPREL_LO16:
case R_MICROMIPS_TLS_TPREL_LO16:
return relocLo16(0, tgtAddr, addend, false, true);
case R_MIPS_GPREL16:
return relocGPRel16(tgtAddr, addend, gpAddr);
case R_MIPS_GPREL32:
return relocGPRel32(tgtAddr, addend, gpAddr);
case R_MIPS_JALR:
case R_MICROMIPS_JALR:
// We do not do JALR optimization now.
return 0;
case R_MIPS_REL32:
return relocRel32(addend);
case R_MIPS_JUMP_SLOT:
case R_MIPS_COPY:
case R_MIPS_TLS_DTPMOD32:
case R_MIPS_TLS_DTPREL32:
case R_MIPS_TLS_TPREL32:
case R_MIPS_TLS_DTPMOD64:
case R_MIPS_TLS_DTPREL64:
case R_MIPS_TLS_TPREL64:
// Ignore runtime relocations.
return 0;
case R_MIPS_PC32:
return relocpc32(relAddr, tgtAddr, addend);
case LLD_R_MIPS_GLOBAL_GOT:
// Do nothing.
case LLD_R_MIPS_32_HI16:
case LLD_R_MIPS_64_HI16:
return relocMaskLow16(tgtAddr, addend);
case LLD_R_MIPS_GLOBAL_26:
return reloc26ext(tgtAddr, addend, 2);
case LLD_R_MICROMIPS_GLOBAL_26_S1:
return reloc26ext(tgtAddr, addend, isCrossJump ? 2 : 1);
case LLD_R_MIPS_HI16:
return relocHi16(0, tgtAddr, 0, false);
case LLD_R_MIPS_LO16:
return relocLo16(0, tgtAddr, 0, false, false);
case LLD_R_MIPS_STO_PLT:
// Do nothing.
return 0;
default:
return make_unhandled_reloc_error();
}
}
static uint64_t relocRead(const MipsRelocationParams ¶ms,
const uint8_t *loc) {
uint64_t data;
switch (params._size) {
case 4:
data = endian::read32le(loc);
break;
case 8:
data = endian::read64le(loc);
break;
default:
llvm_unreachable("Unexpected size");
}
if (params._shuffle)
data = microShuffle(data);
return data;
}
template <class ELFT>
static void relocWrite(uint64_t data, const MipsRelocationParams ¶ms,
uint8_t *loc) {
if (params._shuffle)
data = microShuffle(data);
switch (params._size) {
case 4:
endian::write<uint32_t, ELFT::TargetEndianness, unaligned>(loc, data);
break;
case 8:
endian::write<uint64_t, ELFT::TargetEndianness, unaligned>(loc, data);
break;
default:
llvm_unreachable("Unexpected size");
}
}
static uint32_t getRelKind(const Reference &ref, size_t num) {
if (num == 0)
return ref.kindValue();
return (ref.tag() >> (8 * (num - 1))) & 0xff;
}
static uint8_t getRelShift(Reference::KindValue kind, bool isCrossJump) {
uint8_t shift = getRelocationParams(kind)._shift;
if (isCrossJump &&
(kind == R_MICROMIPS_26_S1 || kind == LLD_R_MICROMIPS_GLOBAL_26_S1))
return 2;
return shift;
}
template <class ELFT>
std::error_code RelocationHandler<ELFT>::applyRelocation(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const AtomLayout &atom,
const Reference &ref) const {
if (ref.kindNamespace() != Reference::KindNamespace::ELF)
return std::error_code();
assert(ref.kindArch() == Reference::KindArch::Mips);
uint64_t gpAddr = _targetLayout.getGPAddr();
bool isGpDisp = ref.target()->name() == "_gp_disp";
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ref.offsetInAtom();
uint64_t tgtAddr = writer.addressOfAtom(ref.target());
uint64_t relAddr = atom._virtualAddr + ref.offsetInAtom();
if (isMicroMipsAtom(ref.target()))
tgtAddr |= 1;
CrossJumpMode jumpMode = getCrossJumpMode(ref);
bool isCrossJump = jumpMode != CrossJumpMode::None;
uint64_t sym = tgtAddr;
ErrorOr<int64_t> res = ref.addend();
Reference::KindValue lastRel = R_MIPS_NONE;
for (size_t relNum = 0; relNum < 3; ++relNum) {
Reference::KindValue kind = getRelKind(ref, relNum);
if (kind == R_MIPS_NONE)
break;
res = calculateRelocation(kind, *res, sym, relAddr, gpAddr, isGpDisp,
isCrossJump);
if (auto ec = res.getError())
return ec;
res = *res >> getRelShift(kind, isCrossJump);
// FIXME (simon): Handle r_ssym value.
sym = 0;
lastRel = kind;
}
auto params = getRelocationParams(lastRel);
uint64_t ins = relocRead(params, location);
if (auto ec = adjustJumpOpCode(ins, tgtAddr, jumpMode))
return ec;
ins = (ins & ~params._mask) | (*res & params._mask);
relocWrite<ELFT>(ins, params, location);
return std::error_code();
}
namespace lld {
namespace elf {
template <>
std::unique_ptr<TargetRelocationHandler>
createMipsRelocationHandler<ELF32LE>(MipsLinkingContext &ctx,
MipsTargetLayout<ELF32LE> &layout) {
return llvm::make_unique<RelocationHandler<ELF32LE>>(ctx, layout);
}
template <>
std::unique_ptr<TargetRelocationHandler>
createMipsRelocationHandler<ELF64LE>(MipsLinkingContext &ctx,
MipsTargetLayout<ELF64LE> &layout) {
return llvm::make_unique<RelocationHandler<ELF64LE>>(ctx, layout);
}
Reference::Addend readMipsRelocAddend(Reference::KindValue kind,
const uint8_t *content) {
auto params = getRelocationParams(kind);
uint64_t ins = relocRead(params, content);
return (ins & params._mask) << params._shift;
}
} // elf
} // lld
[Mips] Rearrange relocation related cases in the `switch` operator
No functional changes.
git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@239223 91177308-0d34-0410-b5e6-96231b3b80d8
//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsLinkingContext.h"
#include "MipsRelocationHandler.h"
#include "MipsTargetLayout.h"
#include "llvm/Support/Format.h"
using namespace lld;
using namespace elf;
using namespace llvm::ELF;
using namespace llvm::support;
namespace {
enum class CrossJumpMode {
None, // Not a jump or non-isa-cross jump
ToRegular, // cross isa jump to regular symbol
ToMicro // cross isa jump to microMips symbol
};
struct MipsRelocationParams {
uint8_t _size; // Relocations's size in bytes
uint64_t _mask; // Read/write mask of relocation
uint8_t _shift; // Relocation's addendum left shift size
bool _shuffle; // Relocation's addendum/result needs to be shuffled
};
template <class ELFT> class RelocationHandler : public TargetRelocationHandler {
public:
RelocationHandler(MipsLinkingContext &ctx, MipsTargetLayout<ELFT> &layout)
: _ctx(ctx), _targetLayout(layout) {}
std::error_code applyRelocation(ELFWriter &writer,
llvm::FileOutputBuffer &buf,
const AtomLayout &atom,
const Reference &ref) const override;
private:
MipsLinkingContext &_ctx;
MipsTargetLayout<ELFT> &_targetLayout;
};
}
static MipsRelocationParams getRelocationParams(uint32_t rType) {
switch (rType) {
case R_MIPS_NONE:
return {4, 0x0, 0, false};
case R_MIPS_64:
case R_MIPS_SUB:
return {8, 0xffffffffffffffffull, 0, false};
case R_MIPS_32:
case R_MIPS_GPREL32:
case R_MIPS_REL32:
case R_MIPS_PC32:
case R_MIPS_EH:
return {4, 0xffffffff, 0, false};
case LLD_R_MIPS_32_HI16:
return {4, 0xffff0000, 0, false};
case LLD_R_MIPS_64_HI16:
return {8, 0xffffffffffff0000ull, 0, false};
case R_MIPS_26:
case LLD_R_MIPS_GLOBAL_26:
return {4, 0x3ffffff, 2, false};
case R_MIPS_PC18_S3:
return {4, 0x3ffff, 3, false};
case R_MIPS_PC19_S2:
return {4, 0x7ffff, 2, false};
case R_MIPS_PC21_S2:
return {4, 0x1fffff, 2, false};
case R_MIPS_PC26_S2:
return {4, 0x3ffffff, 2, false};
case R_MIPS_HI16:
case R_MIPS_LO16:
return {4, 0xffff, 0, false};
case R_MIPS_PCHI16:
case R_MIPS_PCLO16:
case R_MIPS_GOT16:
case R_MIPS_CALL16:
case R_MIPS_GOT_DISP:
case R_MIPS_GOT_PAGE:
case R_MIPS_GOT_OFST:
case R_MIPS_GPREL16:
case R_MIPS_TLS_GD:
case R_MIPS_TLS_LDM:
case R_MIPS_TLS_GOTTPREL:
return {4, 0xffff, 0, false};
case R_MIPS_GOT_HI16:
case R_MIPS_GOT_LO16:
case R_MIPS_CALL_HI16:
case R_MIPS_CALL_LO16:
case R_MIPS_TLS_DTPREL_HI16:
case R_MIPS_TLS_DTPREL_LO16:
case R_MIPS_TLS_TPREL_HI16:
case R_MIPS_TLS_TPREL_LO16:
case LLD_R_MIPS_HI16:
case LLD_R_MIPS_LO16:
return {4, 0xffff, 0, false};
case R_MICROMIPS_GOT_HI16:
case R_MICROMIPS_GOT_LO16:
case R_MICROMIPS_CALL_HI16:
case R_MICROMIPS_CALL_LO16:
case R_MICROMIPS_TLS_DTPREL_HI16:
case R_MICROMIPS_TLS_DTPREL_LO16:
case R_MICROMIPS_TLS_TPREL_HI16:
case R_MICROMIPS_TLS_TPREL_LO16:
return {4, 0xffff, 0, true};
case R_MICROMIPS_26_S1:
case LLD_R_MICROMIPS_GLOBAL_26_S1:
return {4, 0x3ffffff, 1, true};
case R_MICROMIPS_HI16:
case R_MICROMIPS_LO16:
case R_MICROMIPS_GOT16:
return {4, 0xffff, 0, true};
case R_MICROMIPS_PC16_S1:
return {4, 0xffff, 1, true};
case R_MICROMIPS_PC7_S1:
return {4, 0x7f, 1, false};
case R_MICROMIPS_PC10_S1:
return {4, 0x3ff, 1, false};
case R_MICROMIPS_PC23_S2:
return {4, 0x7fffff, 2, true};
case R_MICROMIPS_PC18_S3:
return {4, 0x3ffff, 3, true};
case R_MICROMIPS_PC19_S2:
return {4, 0x7ffff, 2, true};
case R_MICROMIPS_PC21_S2:
return {4, 0x1fffff, 2, true};
case R_MICROMIPS_PC26_S2:
return {4, 0x3ffffff, 2, true};
case R_MICROMIPS_CALL16:
case R_MICROMIPS_TLS_GD:
case R_MICROMIPS_TLS_LDM:
case R_MICROMIPS_TLS_GOTTPREL:
case R_MICROMIPS_GOT_DISP:
case R_MICROMIPS_GOT_PAGE:
case R_MICROMIPS_GOT_OFST:
return {4, 0xffff, 0, true};
case R_MIPS_JALR:
return {4, 0x0, 0, false};
case R_MICROMIPS_JALR:
return {4, 0x0, 0, true};
case R_MIPS_JUMP_SLOT:
case R_MIPS_COPY:
case R_MIPS_TLS_DTPMOD32:
case R_MIPS_TLS_DTPREL32:
case R_MIPS_TLS_TPREL32:
// Ignore runtime relocations.
return {4, 0x0, 0, false};
case R_MIPS_TLS_DTPMOD64:
case R_MIPS_TLS_DTPREL64:
case R_MIPS_TLS_TPREL64:
return {8, 0x0, 0, false};
case LLD_R_MIPS_GLOBAL_GOT:
case LLD_R_MIPS_STO_PLT:
// Do nothing.
return {4, 0x0, 0, false};
default:
llvm_unreachable("Unknown relocation");
}
}
/// \brief R_MIPS_32
/// local/external: word32 S + A (truncate)
static int32_t reloc32(uint64_t S, int64_t A) { return S + A; }
/// \brief R_MIPS_64
/// local/external: word64 S + A (truncate)
static int64_t reloc64(uint64_t S, int64_t A) { return S + A; }
/// \brief R_MIPS_SUB
/// local/external: word64 S - A (truncate)
static int64_t relocSub(uint64_t S, int64_t A) { return S - A; }
/// \brief R_MIPS_PC32
/// local/external: word32 S + A - P (truncate)
static int32_t relocpc32(uint64_t P, uint64_t S, int64_t A) {
return S + A - P;
}
/// \brief R_MIPS_26, R_MICROMIPS_26_S1
/// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2
static int32_t reloc26loc(uint64_t P, uint64_t S, int32_t A, uint32_t shift) {
return (A | ((P + 4) & (0xfc000000 << shift))) + S;
}
/// \brief LLD_R_MIPS_GLOBAL_26, LLD_R_MICROMIPS_GLOBAL_26_S1
/// external: (sign-extend(A) + S) >> 2
static int32_t reloc26ext(uint64_t S, int32_t A, uint32_t shift) {
A = shift == 1 ? llvm::SignExtend32<27>(A) : llvm::SignExtend32<28>(A);
return A + S;
}
/// \brief R_MIPS_HI16, R_MIPS_TLS_DTPREL_HI16, R_MIPS_TLS_TPREL_HI16,
/// R_MICROMIPS_HI16, R_MICROMIPS_TLS_DTPREL_HI16, R_MICROMIPS_TLS_TPREL_HI16,
/// LLD_R_MIPS_HI16
/// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate)
/// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify)
static int32_t relocHi16(uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp) {
int32_t result = isGPDisp ? AHL + S - P : AHL + S;
return (result + 0x8000) >> 16;
}
/// \brief R_MIPS_PCHI16
/// local/external: hi16 (S + AHL - P)
static int32_t relocPcHi16(uint64_t P, uint64_t S, int64_t AHL) {
int32_t result = S + AHL - P;
return (result + 0x8000) >> 16;
}
/// \brief R_MIPS_LO16, R_MIPS_TLS_DTPREL_LO16, R_MIPS_TLS_TPREL_LO16,
/// R_MICROMIPS_LO16, R_MICROMIPS_TLS_DTPREL_LO16, R_MICROMIPS_TLS_TPREL_LO16,
/// LLD_R_MIPS_LO16
/// local/external: lo16 AHL + S (truncate)
/// _gp_disp : lo16 AHL + GP - P + 4 (verify)
static int32_t relocLo16(uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp,
bool micro) {
return isGPDisp ? AHL + S - P + (micro ? 3 : 4) : AHL + S;
}
/// \brief R_MIPS_PCLO16
/// local/external: lo16 (S + AHL - P)
static int32_t relocPcLo16(uint64_t P, uint64_t S, int64_t AHL) {
AHL = llvm::SignExtend32<16>(AHL);
return S + AHL - P;
}
/// \brief R_MIPS_GOT16, R_MIPS_CALL16, R_MICROMIPS_GOT16, R_MICROMIPS_CALL16
/// rel16 G (verify)
static int64_t relocGOT(uint64_t S, uint64_t GP) {
return S - GP;
}
/// \brief R_MIPS_GOT_LO16, R_MIPS_CALL_LO16
/// R_MICROMIPS_GOT_LO16, R_MICROMIPS_CALL_LO16
/// rel16 G (truncate)
static int64_t relocGOTLo16(uint64_t S, uint64_t GP) {
return S - GP;
}
/// \brief R_MIPS_GOT_HI16, R_MIPS_CALL_HI16,
/// R_MICROMIPS_GOT_HI16, R_MICROMIPS_CALL_HI16
/// rel16 %high(G) (truncate)
static int64_t relocGOTHi16(uint64_t S, uint64_t GP) {
return (S - GP + 0x8000) >> 16;
}
/// R_MIPS_GOT_OFST, R_MICROMIPS_GOT_OFST
/// rel16 offset of (S+A) from the page pointer (verify)
static int32_t relocGOTOfst(uint64_t S, int64_t A) {
int64_t page = (S + A + 0x8000) & ~0xffff;
return S + A - page;
}
/// \brief R_MIPS_GPREL16
/// local: sign-extend(A) + S + GP0 - GP
/// external: sign-extend(A) + S - GP
static int64_t relocGPRel16(uint64_t S, int64_t A, uint64_t GP) {
// We added GP0 to addendum for a local symbol during a Relocation pass.
return llvm::SignExtend32<16>(A) + S - GP;
}
/// \brief R_MIPS_GPREL32
/// local: rel32 A + S + GP0 - GP (truncate)
static int64_t relocGPRel32(uint64_t S, int64_t A, uint64_t GP) {
// We added GP0 to addendum for a local symbol during a Relocation pass.
return A + S - GP;
}
/// \brief R_MIPS_PC18_S3, R_MICROMIPS_PC18_S3
/// local/external: (S + A - P) >> 3 (P with cleared 3 less significant bits)
static int32_t relocPc18(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<21>(A);
// FIXME (simon): Check that S + A has 8-byte alignment
int32_t result = S + A - ((P | 7) ^ 7);
return result;
}
/// \brief R_MIPS_PC19_S2, R_MICROMIPS_PC19_S2
/// local/external: (S + A - P) >> 2
static int32_t relocPc19(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<21>(A);
// FIXME (simon): Check that S + A has 4-byte alignment
return S + A - P;
}
/// \brief R_MIPS_PC21_S2, R_MICROMIPS_PC21_S2
/// local/external: (S + A - P) >> 2
static int32_t relocPc21(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<23>(A);
// FIXME (simon): Check that S + A has 4-byte alignment
return S + A - P;
}
/// \brief R_MIPS_PC26_S2, R_MICROMIPS_PC26_S2
/// local/external: (S + A - P) >> 2
static int32_t relocPc26(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<28>(A);
// FIXME (simon): Check that S + A has 4-byte alignment
return S + A - P;
}
/// \brief R_MICROMIPS_PC7_S1
static int32_t relocPc7(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<8>(A);
return S + A - P;
}
/// \brief R_MICROMIPS_PC10_S1
static int32_t relocPc10(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<11>(A);
return S + A - P;
}
/// \brief R_MICROMIPS_PC16_S1
static int32_t relocPc16(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<17>(A);
return S + A - P;
}
/// \brief R_MICROMIPS_PC23_S2
static uint32_t relocPc23(uint64_t P, uint64_t S, int64_t A) {
A = llvm::SignExtend32<25>(A);
int32_t result = S + A - P;
// Check addiupc 16MB range.
if (result + 0x1000000 >= 0x2000000)
llvm::errs() << "The addiupc instruction immediate "
<< llvm::format_hex(result, 10) << " is out of range.\n";
return result;
}
/// \brief LLD_R_MIPS_32_HI16, LLD_R_MIPS_64_HI16
static int64_t relocMaskLow16(uint64_t S, int64_t A) {
return S + A + 0x8000;
}
static int64_t relocRel32(int64_t A) {
// If output relocation format is REL and the input one is RELA, the only
// method to transfer the relocation addend from the input relocation
// to the output dynamic relocation is to save this addend to the location
// modified by R_MIPS_REL32.
return A;
}
static std::error_code adjustJumpOpCode(uint64_t &ins, uint64_t tgt,
CrossJumpMode mode) {
if (mode == CrossJumpMode::None)
return std::error_code();
bool toMicro = mode == CrossJumpMode::ToMicro;
uint32_t opNative = toMicro ? 0x03 : 0x3d;
uint32_t opCross = toMicro ? 0x1d : 0x3c;
if ((tgt & 1) != toMicro)
return make_dynamic_error_code("Incorrect bit 0 for the jalx target");
if (tgt & 2)
return make_dynamic_error_code(Twine("The jalx target 0x") +
Twine::utohexstr(tgt) +
" is not word-aligned");
uint8_t op = ins >> 26;
if (op != opNative && op != opCross)
return make_dynamic_error_code(Twine("Unsupported jump opcode (0x") +
Twine::utohexstr(op) +
") for ISA modes cross call");
ins = (ins & ~(0x3f << 26)) | (opCross << 26);
return std::error_code();
}
static bool isMicroMipsAtom(const Atom *a) {
if (const auto *da = dyn_cast<DefinedAtom>(a))
return da->codeModel() == DefinedAtom::codeMipsMicro ||
da->codeModel() == DefinedAtom::codeMipsMicroPIC;
return false;
}
static CrossJumpMode getCrossJumpMode(const Reference &ref) {
if (!isa<DefinedAtom>(ref.target()))
return CrossJumpMode::None;
bool isTgtMicro = isMicroMipsAtom(ref.target());
switch (ref.kindValue()) {
case R_MIPS_26:
case LLD_R_MIPS_GLOBAL_26:
return isTgtMicro ? CrossJumpMode::ToMicro : CrossJumpMode::None;
case R_MICROMIPS_26_S1:
case LLD_R_MICROMIPS_GLOBAL_26_S1:
return isTgtMicro ? CrossJumpMode::None : CrossJumpMode::ToRegular;
default:
return CrossJumpMode::None;
}
}
static uint32_t microShuffle(uint32_t ins) {
return ((ins & 0xffff) << 16) | ((ins & 0xffff0000) >> 16);
}
static ErrorOr<int64_t> calculateRelocation(Reference::KindValue kind,
Reference::Addend addend,
uint64_t tgtAddr, uint64_t relAddr,
uint64_t gpAddr, bool isGP,
bool isCrossJump) {
if (!tgtAddr) {
isGP = false;
isCrossJump = false;
}
switch (kind) {
case R_MIPS_NONE:
return 0;
case R_MIPS_32:
return reloc32(tgtAddr, addend);
case R_MIPS_64:
return reloc64(tgtAddr, addend);
case R_MIPS_SUB:
return relocSub(tgtAddr, addend);
case R_MIPS_26:
return reloc26loc(relAddr, tgtAddr, addend, 2);
case R_MICROMIPS_26_S1:
return reloc26loc(relAddr, tgtAddr, addend, isCrossJump ? 2 : 1);
case R_MIPS_HI16:
case R_MICROMIPS_HI16:
return relocHi16(relAddr, tgtAddr, addend, isGP);
case R_MIPS_PCHI16:
return relocPcHi16(relAddr, tgtAddr, addend);
case R_MIPS_LO16:
return relocLo16(relAddr, tgtAddr, addend, isGP, false);
case R_MIPS_PCLO16:
return relocPcLo16(relAddr, tgtAddr, addend);
case R_MICROMIPS_LO16:
return relocLo16(relAddr, tgtAddr, addend, isGP, true);
case R_MIPS_GOT_LO16:
case R_MIPS_CALL_LO16:
case R_MICROMIPS_GOT_LO16:
case R_MICROMIPS_CALL_LO16:
return relocGOTLo16(tgtAddr, gpAddr);
case R_MIPS_GOT_HI16:
case R_MIPS_CALL_HI16:
case R_MICROMIPS_GOT_HI16:
case R_MICROMIPS_CALL_HI16:
return relocGOTHi16(tgtAddr, gpAddr);
case R_MIPS_EH:
case R_MIPS_GOT16:
case R_MIPS_CALL16:
case R_MIPS_GOT_DISP:
case R_MIPS_GOT_PAGE:
case R_MICROMIPS_GOT_DISP:
case R_MICROMIPS_GOT_PAGE:
case R_MICROMIPS_GOT16:
case R_MICROMIPS_CALL16:
case R_MIPS_TLS_GD:
case R_MIPS_TLS_LDM:
case R_MIPS_TLS_GOTTPREL:
case R_MICROMIPS_TLS_GD:
case R_MICROMIPS_TLS_LDM:
case R_MICROMIPS_TLS_GOTTPREL:
return relocGOT(tgtAddr, gpAddr);
case R_MIPS_GOT_OFST:
case R_MICROMIPS_GOT_OFST:
return relocGOTOfst(tgtAddr, addend);
case R_MIPS_PC18_S3:
case R_MICROMIPS_PC18_S3:
return relocPc18(relAddr, tgtAddr, addend);
case R_MIPS_PC19_S2:
case R_MICROMIPS_PC19_S2:
return relocPc19(relAddr, tgtAddr, addend);
case R_MIPS_PC21_S2:
case R_MICROMIPS_PC21_S2:
return relocPc21(relAddr, tgtAddr, addend);
case R_MIPS_PC26_S2:
case R_MICROMIPS_PC26_S2:
return relocPc26(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC7_S1:
return relocPc7(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC10_S1:
return relocPc10(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC16_S1:
return relocPc16(relAddr, tgtAddr, addend);
case R_MICROMIPS_PC23_S2:
return relocPc23(relAddr, tgtAddr, addend);
case R_MIPS_TLS_DTPREL_HI16:
case R_MIPS_TLS_TPREL_HI16:
case R_MICROMIPS_TLS_DTPREL_HI16:
case R_MICROMIPS_TLS_TPREL_HI16:
return relocHi16(0, tgtAddr, addend, false);
case R_MIPS_TLS_DTPREL_LO16:
case R_MIPS_TLS_TPREL_LO16:
return relocLo16(0, tgtAddr, addend, false, false);
case R_MICROMIPS_TLS_DTPREL_LO16:
case R_MICROMIPS_TLS_TPREL_LO16:
return relocLo16(0, tgtAddr, addend, false, true);
case R_MIPS_GPREL16:
return relocGPRel16(tgtAddr, addend, gpAddr);
case R_MIPS_GPREL32:
return relocGPRel32(tgtAddr, addend, gpAddr);
case R_MIPS_JALR:
case R_MICROMIPS_JALR:
// We do not do JALR optimization now.
return 0;
case R_MIPS_REL32:
return relocRel32(addend);
case R_MIPS_JUMP_SLOT:
case R_MIPS_COPY:
case R_MIPS_TLS_DTPMOD32:
case R_MIPS_TLS_DTPREL32:
case R_MIPS_TLS_TPREL32:
case R_MIPS_TLS_DTPMOD64:
case R_MIPS_TLS_DTPREL64:
case R_MIPS_TLS_TPREL64:
// Ignore runtime relocations.
return 0;
case R_MIPS_PC32:
return relocpc32(relAddr, tgtAddr, addend);
case LLD_R_MIPS_GLOBAL_GOT:
// Do nothing.
case LLD_R_MIPS_32_HI16:
case LLD_R_MIPS_64_HI16:
return relocMaskLow16(tgtAddr, addend);
case LLD_R_MIPS_GLOBAL_26:
return reloc26ext(tgtAddr, addend, 2);
case LLD_R_MICROMIPS_GLOBAL_26_S1:
return reloc26ext(tgtAddr, addend, isCrossJump ? 2 : 1);
case LLD_R_MIPS_HI16:
return relocHi16(0, tgtAddr, 0, false);
case LLD_R_MIPS_LO16:
return relocLo16(0, tgtAddr, 0, false, false);
case LLD_R_MIPS_STO_PLT:
// Do nothing.
return 0;
default:
return make_unhandled_reloc_error();
}
}
static uint64_t relocRead(const MipsRelocationParams ¶ms,
const uint8_t *loc) {
uint64_t data;
switch (params._size) {
case 4:
data = endian::read32le(loc);
break;
case 8:
data = endian::read64le(loc);
break;
default:
llvm_unreachable("Unexpected size");
}
if (params._shuffle)
data = microShuffle(data);
return data;
}
template <class ELFT>
static void relocWrite(uint64_t data, const MipsRelocationParams ¶ms,
uint8_t *loc) {
if (params._shuffle)
data = microShuffle(data);
switch (params._size) {
case 4:
endian::write<uint32_t, ELFT::TargetEndianness, unaligned>(loc, data);
break;
case 8:
endian::write<uint64_t, ELFT::TargetEndianness, unaligned>(loc, data);
break;
default:
llvm_unreachable("Unexpected size");
}
}
static uint32_t getRelKind(const Reference &ref, size_t num) {
if (num == 0)
return ref.kindValue();
return (ref.tag() >> (8 * (num - 1))) & 0xff;
}
static uint8_t getRelShift(Reference::KindValue kind, bool isCrossJump) {
uint8_t shift = getRelocationParams(kind)._shift;
if (isCrossJump &&
(kind == R_MICROMIPS_26_S1 || kind == LLD_R_MICROMIPS_GLOBAL_26_S1))
return 2;
return shift;
}
template <class ELFT>
std::error_code RelocationHandler<ELFT>::applyRelocation(
ELFWriter &writer, llvm::FileOutputBuffer &buf, const AtomLayout &atom,
const Reference &ref) const {
if (ref.kindNamespace() != Reference::KindNamespace::ELF)
return std::error_code();
assert(ref.kindArch() == Reference::KindArch::Mips);
uint64_t gpAddr = _targetLayout.getGPAddr();
bool isGpDisp = ref.target()->name() == "_gp_disp";
uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset;
uint8_t *location = atomContent + ref.offsetInAtom();
uint64_t tgtAddr = writer.addressOfAtom(ref.target());
uint64_t relAddr = atom._virtualAddr + ref.offsetInAtom();
if (isMicroMipsAtom(ref.target()))
tgtAddr |= 1;
CrossJumpMode jumpMode = getCrossJumpMode(ref);
bool isCrossJump = jumpMode != CrossJumpMode::None;
uint64_t sym = tgtAddr;
ErrorOr<int64_t> res = ref.addend();
Reference::KindValue lastRel = R_MIPS_NONE;
for (size_t relNum = 0; relNum < 3; ++relNum) {
Reference::KindValue kind = getRelKind(ref, relNum);
if (kind == R_MIPS_NONE)
break;
res = calculateRelocation(kind, *res, sym, relAddr, gpAddr, isGpDisp,
isCrossJump);
if (auto ec = res.getError())
return ec;
res = *res >> getRelShift(kind, isCrossJump);
// FIXME (simon): Handle r_ssym value.
sym = 0;
lastRel = kind;
}
auto params = getRelocationParams(lastRel);
uint64_t ins = relocRead(params, location);
if (auto ec = adjustJumpOpCode(ins, tgtAddr, jumpMode))
return ec;
ins = (ins & ~params._mask) | (*res & params._mask);
relocWrite<ELFT>(ins, params, location);
return std::error_code();
}
namespace lld {
namespace elf {
template <>
std::unique_ptr<TargetRelocationHandler>
createMipsRelocationHandler<ELF32LE>(MipsLinkingContext &ctx,
MipsTargetLayout<ELF32LE> &layout) {
return llvm::make_unique<RelocationHandler<ELF32LE>>(ctx, layout);
}
template <>
std::unique_ptr<TargetRelocationHandler>
createMipsRelocationHandler<ELF64LE>(MipsLinkingContext &ctx,
MipsTargetLayout<ELF64LE> &layout) {
return llvm::make_unique<RelocationHandler<ELF64LE>>(ctx, layout);
}
Reference::Addend readMipsRelocAddend(Reference::KindValue kind,
const uint8_t *content) {
auto params = getRelocationParams(kind);
uint64_t ins = relocRead(params, content);
return (ins & params._mask) << params._shift;
}
} // elf
} // lld
|
//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
// Details of the algorithm:
// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asan"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/system_error.h"
#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "llvm/Transforms/Utils/SpecialCaseList.h"
#include <algorithm>
#include <string>
using namespace llvm;
static const uint64_t kDefaultShadowScale = 3;
static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
static const size_t kMinStackMallocSize = 1 << 6; // 64B
static const size_t kMaxStackMallocSize = 1 << 16; // 64K
static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
static const char *const kAsanModuleCtorName = "asan.module_ctor";
static const char *const kAsanModuleDtorName = "asan.module_dtor";
static const int kAsanCtorAndCtorPriority = 1;
static const char *const kAsanReportErrorTemplate = "__asan_report_";
static const char *const kAsanReportLoadN = "__asan_report_load_n";
static const char *const kAsanReportStoreN = "__asan_report_store_n";
static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
static const char *const kAsanUnregisterGlobalsName =
"__asan_unregister_globals";
static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
static const char *const kAsanInitName = "__asan_init_v3";
static const char *const kAsanCovName = "__sanitizer_cov";
static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
static const int kMaxAsanStackMallocSizeClass = 10;
static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
static const char *const kAsanGenPrefix = "__asan_gen_";
static const char *const kAsanPoisonStackMemoryName =
"__asan_poison_stack_memory";
static const char *const kAsanUnpoisonStackMemoryName =
"__asan_unpoison_stack_memory";
static const char *const kAsanOptionDetectUAR =
"__asan_option_detect_stack_use_after_return";
#ifndef NDEBUG
static const int kAsanStackAfterReturnMagic = 0xf5;
#endif
// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
static const size_t kNumberOfAccessSizes = 5;
// Command-line flags.
// This flag may need to be replaced with -f[no-]asan-reads.
static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
cl::Hidden, cl::init(true));
static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
cl::desc("use instrumentation with slow path for all accesses"),
cl::Hidden, cl::init(false));
// This flag limits the number of instructions to be instrumented
// in any given BB. Normally, this should be set to unlimited (INT_MAX),
// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
// set it to 10000.
static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
cl::init(10000),
cl::desc("maximal number of instructions to instrument in any given BB"),
cl::Hidden);
// This flag may need to be replaced with -f[no]asan-stack.
static cl::opt<bool> ClStack("asan-stack",
cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
// This flag may need to be replaced with -f[no]asan-use-after-return.
static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
// This flag may need to be replaced with -f[no]asan-globals.
static cl::opt<bool> ClGlobals("asan-globals",
cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
static cl::opt<int> ClCoverage("asan-coverage",
cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
cl::Hidden, cl::init(false));
static cl::opt<bool> ClInitializers("asan-initialization-order",
cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
static cl::opt<bool> ClMemIntrin("asan-memintrin",
cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
cl::Hidden, cl::init(false));
static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
cl::desc("Realign stack to the value of this flag (power of two)"),
cl::Hidden, cl::init(32));
static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
cl::desc("File containing the list of objects to ignore "
"during instrumentation"), cl::Hidden);
// This is an experimental feature that will allow to choose between
// instrumented and non-instrumented code at link-time.
// If this option is on, just before instrumenting a function we create its
// clone; if the function is not changed by asan the clone is deleted.
// If we end up with a clone, we put the instrumented function into a section
// called "ASAN" and the uninstrumented function into a section called "NOASAN".
//
// This is still a prototype, we need to figure out a way to keep two copies of
// a function so that the linker can easily choose one of them.
static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
cl::desc("Keep uninstrumented copies of functions"),
cl::Hidden, cl::init(false));
// These flags allow to change the shadow mapping.
// The shadow mapping looks like
// Shadow = (Mem >> scale) + (1 << offset_log)
static cl::opt<int> ClMappingScale("asan-mapping-scale",
cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
// Optimization flags. Not user visible, used mostly for testing
// and benchmarking the tool.
static cl::opt<bool> ClOpt("asan-opt",
cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
cl::desc("Instrument the same temp just once"), cl::Hidden,
cl::init(true));
static cl::opt<bool> ClOptGlobals("asan-opt-globals",
cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
cl::Hidden, cl::init(false));
// Debug flags.
static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
cl::init(0));
static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
cl::Hidden, cl::init(0));
static cl::opt<std::string> ClDebugFunc("asan-debug-func",
cl::Hidden, cl::desc("Debug func"));
static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
cl::Hidden, cl::init(-1));
static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
cl::Hidden, cl::init(-1));
STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
STATISTIC(NumOptimizedAccessesToGlobalArray,
"Number of optimized accesses to global arrays");
STATISTIC(NumOptimizedAccessesToGlobalVar,
"Number of optimized accesses to global vars");
namespace {
/// A set of dynamically initialized globals extracted from metadata.
class SetOfDynamicallyInitializedGlobals {
public:
void Init(Module& M) {
// Clang generates metadata identifying all dynamically initialized globals.
NamedMDNode *DynamicGlobals =
M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
if (!DynamicGlobals)
return;
for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
MDNode *MDN = DynamicGlobals->getOperand(i);
assert(MDN->getNumOperands() == 1);
Value *VG = MDN->getOperand(0);
// The optimizer may optimize away a global entirely, in which case we
// cannot instrument access to it.
if (!VG)
continue;
DynInitGlobals.insert(cast<GlobalVariable>(VG));
}
}
bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
private:
SmallSet<GlobalValue*, 32> DynInitGlobals;
};
/// This struct defines the shadow mapping using the rule:
/// shadow = (mem >> Scale) ADD-or-OR Offset.
struct ShadowMapping {
int Scale;
uint64_t Offset;
bool OrShadowOffset;
};
static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
llvm::Triple TargetTriple(M.getTargetTriple());
bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
// bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
TargetTriple.getArch() == llvm::Triple::ppc64le;
bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
TargetTriple.getArch() == llvm::Triple::mipsel;
ShadowMapping Mapping;
if (LongSize == 32) {
if (IsAndroid)
Mapping.Offset = 0;
else if (IsMIPS32)
Mapping.Offset = kMIPS32_ShadowOffset32;
else if (IsFreeBSD)
Mapping.Offset = kFreeBSD_ShadowOffset32;
else
Mapping.Offset = kDefaultShadowOffset32;
} else { // LongSize == 64
if (IsPPC64)
Mapping.Offset = kPPC64_ShadowOffset64;
else if (IsFreeBSD)
Mapping.Offset = kFreeBSD_ShadowOffset64;
else if (IsLinux && IsX86_64)
Mapping.Offset = kSmallX86_64ShadowOffset;
else
Mapping.Offset = kDefaultShadowOffset64;
}
Mapping.Scale = kDefaultShadowScale;
if (ClMappingScale) {
Mapping.Scale = ClMappingScale;
}
// OR-ing shadow offset if more efficient (at least on x86) if the offset
// is a power of two, but on ppc64 we have to use add since the shadow
// offset is not necessary 1/8-th of the address space.
Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
return Mapping;
}
static size_t RedzoneSizeForScale(int MappingScale) {
// Redzone used for stack and globals is at least 32 bytes.
// For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
return std::max(32U, 1U << MappingScale);
}
/// AddressSanitizer: instrument the code in module to find memory bugs.
struct AddressSanitizer : public FunctionPass {
AddressSanitizer(bool CheckInitOrder = true,
bool CheckUseAfterReturn = false,
bool CheckLifetime = false,
StringRef BlacklistFile = StringRef())
: FunctionPass(ID),
CheckInitOrder(CheckInitOrder || ClInitializers),
CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
CheckLifetime(CheckLifetime || ClCheckLifetime),
BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
: BlacklistFile) {}
const char *getPassName() const override {
return "AddressSanitizerFunctionPass";
}
void instrumentMop(Instruction *I);
void instrumentPointerComparisonOrSubtraction(Instruction *I);
void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
Value *Addr, uint32_t TypeSize, bool IsWrite,
Value *SizeArgument);
Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Value *ShadowValue, uint32_t TypeSize);
Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
bool IsWrite, size_t AccessSizeIndex,
Value *SizeArgument);
bool instrumentMemIntrinsic(MemIntrinsic *MI);
void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Value *Size,
Instruction *InsertBefore, bool IsWrite);
Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
bool runOnFunction(Function &F) override;
bool maybeInsertAsanInitAtFunctionEntry(Function &F);
bool doInitialization(Module &M) override;
static char ID; // Pass identification, replacement for typeid
private:
void initializeCallbacks(Module &M);
bool ShouldInstrumentGlobal(GlobalVariable *G);
bool LooksLikeCodeInBug11395(Instruction *I);
void FindDynamicInitializers(Module &M);
bool GlobalIsLinkerInitialized(GlobalVariable *G);
bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
bool CheckInitOrder;
bool CheckUseAfterReturn;
bool CheckLifetime;
SmallString<64> BlacklistFile;
LLVMContext *C;
const DataLayout *DL;
int LongSize;
Type *IntptrTy;
ShadowMapping Mapping;
Function *AsanCtorFunction;
Function *AsanInitFunction;
Function *AsanHandleNoReturnFunc;
Function *AsanCovFunction;
Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
std::unique_ptr<SpecialCaseList> BL;
// This array is indexed by AccessIsWrite and log2(AccessSize).
Function *AsanErrorCallback[2][kNumberOfAccessSizes];
// This array is indexed by AccessIsWrite.
Function *AsanErrorCallbackSized[2];
InlineAsm *EmptyAsm;
SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
friend struct FunctionStackPoisoner;
};
class AddressSanitizerModule : public ModulePass {
public:
AddressSanitizerModule(bool CheckInitOrder = true,
StringRef BlacklistFile = StringRef())
: ModulePass(ID),
CheckInitOrder(CheckInitOrder || ClInitializers),
BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
: BlacklistFile) {}
bool runOnModule(Module &M) override;
static char ID; // Pass identification, replacement for typeid
const char *getPassName() const override {
return "AddressSanitizerModule";
}
private:
void initializeCallbacks(Module &M);
bool ShouldInstrumentGlobal(GlobalVariable *G);
void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
size_t MinRedzoneSizeForGlobal() const {
return RedzoneSizeForScale(Mapping.Scale);
}
bool CheckInitOrder;
SmallString<64> BlacklistFile;
std::unique_ptr<SpecialCaseList> BL;
SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Type *IntptrTy;
LLVMContext *C;
const DataLayout *DL;
ShadowMapping Mapping;
Function *AsanPoisonGlobals;
Function *AsanUnpoisonGlobals;
Function *AsanRegisterGlobals;
Function *AsanUnregisterGlobals;
};
// Stack poisoning does not play well with exception handling.
// When an exception is thrown, we essentially bypass the code
// that unpoisones the stack. This is why the run-time library has
// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
// stack in the interceptor. This however does not work inside the
// actual function which catches the exception. Most likely because the
// compiler hoists the load of the shadow value somewhere too high.
// This causes asan to report a non-existing bug on 453.povray.
// It sounds like an LLVM bug.
struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
Function &F;
AddressSanitizer &ASan;
DIBuilder DIB;
LLVMContext *C;
Type *IntptrTy;
Type *IntptrPtrTy;
ShadowMapping Mapping;
SmallVector<AllocaInst*, 16> AllocaVec;
SmallVector<Instruction*, 8> RetVec;
unsigned StackAlignment;
Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
*AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
// Stores a place and arguments of poisoning/unpoisoning call for alloca.
struct AllocaPoisonCall {
IntrinsicInst *InsBefore;
AllocaInst *AI;
uint64_t Size;
bool DoPoison;
};
SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
// Maps Value to an AllocaInst from which the Value is originated.
typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
AllocaForValueMapTy AllocaForValue;
FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
: F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Mapping(ASan.Mapping),
StackAlignment(1 << Mapping.Scale) {}
bool runOnFunction() {
if (!ClStack) return false;
// Collect alloca, ret, lifetime instructions etc.
for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
BasicBlock *BB = *DI;
visit(*BB);
}
if (AllocaVec.empty()) return false;
initializeCallbacks(*F.getParent());
poisonStack();
if (ClDebugStack) {
DEBUG(dbgs() << F);
}
return true;
}
// Finds all static Alloca instructions and puts
// poisoned red zones around all of them.
// Then unpoison everything back before the function returns.
void poisonStack();
// ----------------------- Visitors.
/// \brief Collect all Ret instructions.
void visitReturnInst(ReturnInst &RI) {
RetVec.push_back(&RI);
}
/// \brief Collect Alloca instructions we want (and can) handle.
void visitAllocaInst(AllocaInst &AI) {
if (!isInterestingAlloca(AI)) return;
StackAlignment = std::max(StackAlignment, AI.getAlignment());
AllocaVec.push_back(&AI);
}
/// \brief Collect lifetime intrinsic calls to check for use-after-scope
/// errors.
void visitIntrinsicInst(IntrinsicInst &II) {
if (!ASan.CheckLifetime) return;
Intrinsic::ID ID = II.getIntrinsicID();
if (ID != Intrinsic::lifetime_start &&
ID != Intrinsic::lifetime_end)
return;
// Found lifetime intrinsic, add ASan instrumentation if necessary.
ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
// If size argument is undefined, don't do anything.
if (Size->isMinusOne()) return;
// Check that size doesn't saturate uint64_t and can
// be stored in IntptrTy.
const uint64_t SizeValue = Size->getValue().getLimitedValue();
if (SizeValue == ~0ULL ||
!ConstantInt::isValueValidForType(IntptrTy, SizeValue))
return;
// Find alloca instruction that corresponds to llvm.lifetime argument.
AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
if (!AI) return;
bool DoPoison = (ID == Intrinsic::lifetime_end);
AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
AllocaPoisonCallVec.push_back(APC);
}
// ---------------------- Helpers.
void initializeCallbacks(Module &M);
// Check if we want (and can) handle this alloca.
bool isInterestingAlloca(AllocaInst &AI) const {
return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
AI.getAllocatedType()->isSized() &&
// alloca() may be called with 0 size, ignore it.
getAllocaSizeInBytes(&AI) > 0);
}
uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Type *Ty = AI->getAllocatedType();
uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
return SizeInBytes;
}
/// Finds alloca where the value comes from.
AllocaInst *findAllocaForValue(Value *V);
void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Value *ShadowBase, bool DoPoison);
void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
int Size);
};
} // namespace
char AddressSanitizer::ID = 0;
INITIALIZE_PASS(AddressSanitizer, "asan",
"AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
false, false)
FunctionPass *llvm::createAddressSanitizerFunctionPass(
bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
StringRef BlacklistFile) {
return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
CheckLifetime, BlacklistFile);
}
char AddressSanitizerModule::ID = 0;
INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
"AddressSanitizer: detects use-after-free and out-of-bounds bugs."
"ModulePass", false, false)
ModulePass *llvm::createAddressSanitizerModulePass(
bool CheckInitOrder, StringRef BlacklistFile) {
return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
}
static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
size_t Res = countTrailingZeros(TypeSize / 8);
assert(Res < kNumberOfAccessSizes);
return Res;
}
// \brief Create a constant for Str so that we can pass it to the run-time lib.
static GlobalVariable *createPrivateGlobalForString(
Module &M, StringRef Str, bool AllowMerging) {
Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
// We use private linkage for module-local strings. If they can be merged
// with another one, we set the unnamed_addr attribute.
GlobalVariable *GV =
new GlobalVariable(M, StrConst->getType(), true,
GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
if (AllowMerging)
GV->setUnnamedAddr(true);
GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
return GV;
}
static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
return G->getName().find(kAsanGenPrefix) == 0;
}
Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
// Shadow >> scale
Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
if (Mapping.Offset == 0)
return Shadow;
// (Shadow >> scale) | offset
if (Mapping.OrShadowOffset)
return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
else
return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
}
void AddressSanitizer::instrumentMemIntrinsicParam(
Instruction *OrigIns,
Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
IRBuilder<> IRB(InsertBefore);
if (Size->getType() != IntptrTy)
Size = IRB.CreateIntCast(Size, IntptrTy, false);
// Check the first byte.
instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
// Check the last byte.
IRB.SetInsertPoint(InsertBefore);
Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
}
// Instrument memset/memmove/memcpy
bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Value *Dst = MI->getDest();
MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Value *Src = MemTran ? MemTran->getSource() : 0;
Value *Length = MI->getLength();
Constant *ConstLength = dyn_cast<Constant>(Length);
Instruction *InsertBefore = MI;
if (ConstLength) {
if (ConstLength->isNullValue()) return false;
} else {
// The size is not a constant so it could be zero -- check at run-time.
IRBuilder<> IRB(InsertBefore);
Value *Cmp = IRB.CreateICmpNE(Length,
Constant::getNullValue(Length->getType()));
InsertBefore = SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
}
instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
if (Src)
instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
return true;
}
// If I is an interesting memory access, return the PointerOperand
// and set IsWrite. Otherwise return NULL.
static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
if (!ClInstrumentReads) return NULL;
*IsWrite = false;
return LI->getPointerOperand();
}
if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
if (!ClInstrumentWrites) return NULL;
*IsWrite = true;
return SI->getPointerOperand();
}
if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
if (!ClInstrumentAtomics) return NULL;
*IsWrite = true;
return RMW->getPointerOperand();
}
if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
if (!ClInstrumentAtomics) return NULL;
*IsWrite = true;
return XCHG->getPointerOperand();
}
return NULL;
}
static bool isPointerOperand(Value *V) {
return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
}
// This is a rough heuristic; it may cause both false positives and
// false negatives. The proper implementation requires cooperation with
// the frontend.
static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
if (!Cmp->isRelational())
return false;
} else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
if (BO->getOpcode() != Instruction::Sub)
return false;
} else {
return false;
}
if (!isPointerOperand(I->getOperand(0)) ||
!isPointerOperand(I->getOperand(1)))
return false;
return true;
}
bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
// If a global variable does not have dynamic initialization we don't
// have to instrument it. However, if a global does not have initializer
// at all, we assume it has dynamic initializer (in other TU).
return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
}
void
AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
IRBuilder<> IRB(I);
Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
for (int i = 0; i < 2; i++) {
if (Param[i]->getType()->isPointerTy())
Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
}
IRB.CreateCall2(F, Param[0], Param[1]);
}
void AddressSanitizer::instrumentMop(Instruction *I) {
bool IsWrite = false;
Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
assert(Addr);
if (ClOpt && ClOptGlobals) {
if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
// If initialization order checking is disabled, a simple access to a
// dynamically initialized global is always valid.
if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
NumOptimizedAccessesToGlobalVar++;
return;
}
}
ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
NumOptimizedAccessesToGlobalArray++;
return;
}
}
}
}
Type *OrigPtrTy = Addr->getType();
Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
assert(OrigTy->isSized());
uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
assert((TypeSize % 8) == 0);
if (IsWrite)
NumInstrumentedWrites++;
else
NumInstrumentedReads++;
// Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
if (TypeSize == 8 || TypeSize == 16 ||
TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
// Instrument unusual size (but still multiple of 8).
// We can not do it with a single check, so we do 1-byte check for the first
// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
// to report the actual access size.
IRBuilder<> IRB(I);
Value *LastByte = IRB.CreateIntToPtr(
IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
OrigPtrTy);
Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
instrumentAddress(I, I, Addr, 8, IsWrite, Size);
instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
}
// Validate the result of Module::getOrInsertFunction called for an interface
// function of AddressSanitizer. If the instrumented module defines a function
// with the same name, their prototypes must match, otherwise
// getOrInsertFunction returns a bitcast.
static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
FuncOrBitcast->dump();
report_fatal_error("trying to redefine an AddressSanitizer "
"interface function");
}
Instruction *AddressSanitizer::generateCrashCode(
Instruction *InsertBefore, Value *Addr,
bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
IRBuilder<> IRB(InsertBefore);
CallInst *Call = SizeArgument
? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
: IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
// We don't do Call->setDoesNotReturn() because the BB already has
// UnreachableInst at the end.
// This EmptyAsm is required to avoid callback merge.
IRB.CreateCall(EmptyAsm);
return Call;
}
Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Value *ShadowValue,
uint32_t TypeSize) {
size_t Granularity = 1 << Mapping.Scale;
// Addr & (Granularity - 1)
Value *LastAccessedByte = IRB.CreateAnd(
AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
// (Addr & (Granularity - 1)) + size - 1
if (TypeSize / 8 > 1)
LastAccessedByte = IRB.CreateAdd(
LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
// (uint8_t) ((Addr & (Granularity-1)) + size - 1)
LastAccessedByte = IRB.CreateIntCast(
LastAccessedByte, ShadowValue->getType(), false);
// ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
}
void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Instruction *InsertBefore,
Value *Addr, uint32_t TypeSize,
bool IsWrite, Value *SizeArgument) {
IRBuilder<> IRB(InsertBefore);
Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Type *ShadowTy = IntegerType::get(
*C, std::max(8U, TypeSize >> Mapping.Scale));
Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
Value *ShadowPtr = memToShadow(AddrLong, IRB);
Value *CmpVal = Constant::getNullValue(ShadowTy);
Value *ShadowValue = IRB.CreateLoad(
IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
size_t Granularity = 1 << Mapping.Scale;
TerminatorInst *CrashTerm = 0;
if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
TerminatorInst *CheckTerm =
SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
BasicBlock *NextBB = CheckTerm->getSuccessor(0);
IRB.SetInsertPoint(CheckTerm);
Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
BasicBlock *CrashBlock =
BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
CrashTerm = new UnreachableInst(*C, CrashBlock);
BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
ReplaceInstWithInst(CheckTerm, NewTerm);
} else {
CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
}
Instruction *Crash = generateCrashCode(
CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Crash->setDebugLoc(OrigIns->getDebugLoc());
}
void AddressSanitizerModule::createInitializerPoisonCalls(
Module &M, GlobalValue *ModuleName) {
// We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
// If that function is not present, this TU contains no globals, or they have
// all been optimized away
if (!GlobalInit)
return;
// Set up the arguments to our poison/unpoison functions.
IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
// Add a call to poison all external globals before the given function starts.
Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
// Add calls to unpoison all globals before each return instruction.
for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
I != E; ++I) {
if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
CallInst::Create(AsanUnpoisonGlobals, "", RI);
}
}
}
bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Type *Ty = cast<PointerType>(G->getType())->getElementType();
DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
if (BL->isIn(*G)) return false;
if (!Ty->isSized()) return false;
if (!G->hasInitializer()) return false;
if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
// Touch only those globals that will not be defined in other modules.
// Don't handle ODR type linkages since other modules may be built w/o asan.
if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
G->getLinkage() != GlobalVariable::PrivateLinkage &&
G->getLinkage() != GlobalVariable::InternalLinkage)
return false;
// Two problems with thread-locals:
// - The address of the main thread's copy can't be computed at link-time.
// - Need to poison all copies, not just the main thread's one.
if (G->isThreadLocal())
return false;
// For now, just ignore this Global if the alignment is large.
if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
// Ignore all the globals with the names starting with "\01L_OBJC_".
// Many of those are put into the .cstring section. The linker compresses
// that section by removing the spare \0s after the string terminator, so
// our redzones get broken.
if ((G->getName().find("\01L_OBJC_") == 0) ||
(G->getName().find("\01l_OBJC_") == 0)) {
DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
return false;
}
if (G->hasSection()) {
StringRef Section(G->getSection());
// Ignore the globals from the __OBJC section. The ObjC runtime assumes
// those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
// them.
if ((Section.find("__OBJC,") == 0) ||
(Section.find("__DATA, __objc_") == 0)) {
DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
return false;
}
// See http://code.google.com/p/address-sanitizer/issues/detail?id=32
// Constant CFString instances are compiled in the following way:
// -- the string buffer is emitted into
// __TEXT,__cstring,cstring_literals
// -- the constant NSConstantString structure referencing that buffer
// is placed into __DATA,__cfstring
// Therefore there's no point in placing redzones into __DATA,__cfstring.
// Moreover, it causes the linker to crash on OS X 10.7
if (Section.find("__DATA,__cfstring") == 0) {
DEBUG(dbgs() << "Ignoring CFString: " << *G);
return false;
}
}
return true;
}
void AddressSanitizerModule::initializeCallbacks(Module &M) {
IRBuilder<> IRB(*C);
// Declare our poisoning and unpoisoning functions.
AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
// Declare functions that register/unregister globals.
AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanRegisterGlobalsName, IRB.getVoidTy(),
IntptrTy, IntptrTy, NULL));
AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanUnregisterGlobalsName,
IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
}
// This function replaces all global variables with new variables that have
// trailing redzones. It also creates a function that poisons
// redzones and inserts this function into llvm.global_ctors.
bool AddressSanitizerModule::runOnModule(Module &M) {
if (!ClGlobals) return false;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
if (!DLP)
return false;
DL = &DLP->getDataLayout();
BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
if (BL->isIn(M)) return false;
C = &(M.getContext());
int LongSize = DL->getPointerSizeInBits();
IntptrTy = Type::getIntNTy(*C, LongSize);
Mapping = getShadowMapping(M, LongSize);
initializeCallbacks(M);
DynamicallyInitializedGlobals.Init(M);
SmallVector<GlobalVariable *, 16> GlobalsToChange;
for (Module::GlobalListType::iterator G = M.global_begin(),
E = M.global_end(); G != E; ++G) {
if (ShouldInstrumentGlobal(G))
GlobalsToChange.push_back(G);
}
size_t n = GlobalsToChange.size();
if (n == 0) return false;
// A global is described by a structure
// size_t beg;
// size_t size;
// size_t size_with_redzone;
// const char *name;
// const char *module_name;
// size_t has_dynamic_init;
// We initialize an array of such structures and pass it to a run-time call.
StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
IntptrTy, IntptrTy,
IntptrTy, IntptrTy, NULL);
SmallVector<Constant *, 16> Initializers(n);
Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
assert(CtorFunc);
IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
bool HasDynamicallyInitializedGlobals = false;
// We shouldn't merge same module names, as this string serves as unique
// module ID in runtime.
GlobalVariable *ModuleName = createPrivateGlobalForString(
M, M.getModuleIdentifier(), /*AllowMerging*/false);
for (size_t i = 0; i < n; i++) {
static const uint64_t kMaxGlobalRedzone = 1 << 18;
GlobalVariable *G = GlobalsToChange[i];
PointerType *PtrTy = cast<PointerType>(G->getType());
Type *Ty = PtrTy->getElementType();
uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
uint64_t MinRZ = MinRedzoneSizeForGlobal();
// MinRZ <= RZ <= kMaxGlobalRedzone
// and trying to make RZ to be ~ 1/4 of SizeInBytes.
uint64_t RZ = std::max(MinRZ,
std::min(kMaxGlobalRedzone,
(SizeInBytes / MinRZ / 4) * MinRZ));
uint64_t RightRedzoneSize = RZ;
// Round up to MinRZ
if (SizeInBytes % MinRZ)
RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
// Determine whether this global should be poisoned in initialization.
bool GlobalHasDynamicInitializer =
DynamicallyInitializedGlobals.Contains(G);
// Don't check initialization order if this global is blacklisted.
GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
Constant *NewInitializer = ConstantStruct::get(
NewTy, G->getInitializer(),
Constant::getNullValue(RightRedZoneTy), NULL);
GlobalVariable *Name =
createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
// Create a new global variable with enough space for a redzone.
GlobalValue::LinkageTypes Linkage = G->getLinkage();
if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
Linkage = GlobalValue::InternalLinkage;
GlobalVariable *NewGlobal = new GlobalVariable(
M, NewTy, G->isConstant(), Linkage,
NewInitializer, "", G, G->getThreadLocalMode());
NewGlobal->copyAttributesFrom(G);
NewGlobal->setAlignment(MinRZ);
Value *Indices2[2];
Indices2[0] = IRB.getInt32(0);
Indices2[1] = IRB.getInt32(0);
G->replaceAllUsesWith(
ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
NewGlobal->takeName(G);
G->eraseFromParent();
Initializers[i] = ConstantStruct::get(
GlobalStructTy,
ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
ConstantInt::get(IntptrTy, SizeInBytes),
ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
ConstantExpr::getPointerCast(Name, IntptrTy),
ConstantExpr::getPointerCast(ModuleName, IntptrTy),
ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
NULL);
// Populate the first and last globals declared in this TU.
if (CheckInitOrder && GlobalHasDynamicInitializer)
HasDynamicallyInitializedGlobals = true;
DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
}
ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
GlobalVariable *AllGlobals = new GlobalVariable(
M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
// Create calls for poisoning before initializers run and unpoisoning after.
if (CheckInitOrder && HasDynamicallyInitializedGlobals)
createInitializerPoisonCalls(M, ModuleName);
IRB.CreateCall2(AsanRegisterGlobals,
IRB.CreatePointerCast(AllGlobals, IntptrTy),
ConstantInt::get(IntptrTy, n));
// We also need to unregister globals at the end, e.g. when a shared library
// gets closed.
Function *AsanDtorFunction = Function::Create(
FunctionType::get(Type::getVoidTy(*C), false),
GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
IRB.CreatePointerCast(AllGlobals, IntptrTy),
ConstantInt::get(IntptrTy, n));
appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
DEBUG(dbgs() << M);
return true;
}
void AddressSanitizer::initializeCallbacks(Module &M) {
IRBuilder<> IRB(*C);
// Create __asan_report* callbacks.
for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
AccessSizeIndex++) {
// IsWrite and TypeSize are encoded in the function name.
std::string FunctionName = std::string(kAsanReportErrorTemplate) +
(AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
// If we are merging crash callbacks, they have two parameters.
AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
checkInterfaceFunction(M.getOrInsertFunction(
FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
}
}
AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
kAsanCovName, IRB.getVoidTy(), NULL));
AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
// We insert an empty inline asm after __asan_report* to avoid callback merge.
EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
StringRef(""), StringRef(""),
/*hasSideEffects=*/true);
}
// virtual
bool AddressSanitizer::doInitialization(Module &M) {
// Initialize the private fields. No one has accessed them before.
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
if (!DLP)
return false;
DL = &DLP->getDataLayout();
BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
DynamicallyInitializedGlobals.Init(M);
C = &(M.getContext());
LongSize = DL->getPointerSizeInBits();
IntptrTy = Type::getIntNTy(*C, LongSize);
AsanCtorFunction = Function::Create(
FunctionType::get(Type::getVoidTy(*C), false),
GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
// call __asan_init in the module ctor.
IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
AsanInitFunction = checkInterfaceFunction(
M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
AsanInitFunction->setLinkage(Function::ExternalLinkage);
IRB.CreateCall(AsanInitFunction);
Mapping = getShadowMapping(M, LongSize);
appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
return true;
}
bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
// For each NSObject descendant having a +load method, this method is invoked
// by the ObjC runtime before any of the static constructors is called.
// Therefore we need to instrument such methods with a call to __asan_init
// at the beginning in order to initialize our runtime before any access to
// the shadow memory.
// We cannot just ignore these methods, because they may call other
// instrumented functions.
if (F.getName().find(" load]") != std::string::npos) {
IRBuilder<> IRB(F.begin()->begin());
IRB.CreateCall(AsanInitFunction);
return true;
}
return false;
}
void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
// Skip static allocas at the top of the entry block so they don't become
// dynamic when we split the block. If we used our optimized stack layout,
// then there will only be one alloca and it will come first.
for (; IP != BE; ++IP) {
AllocaInst *AI = dyn_cast<AllocaInst>(IP);
if (!AI || !AI->isStaticAlloca())
break;
}
IRBuilder<> IRB(IP);
Type *Int8Ty = IRB.getInt8Ty();
GlobalVariable *Guard = new GlobalVariable(
*F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
LoadInst *Load = IRB.CreateLoad(Guard);
Load->setAtomic(Monotonic);
Load->setAlignment(1);
Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
Instruction *Ins = SplitBlockAndInsertIfThen(
Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
IRB.SetInsertPoint(Ins);
// We pass &F to __sanitizer_cov. We could avoid this and rely on
// GET_CALLER_PC, but having the PC of the first instruction is just nice.
Instruction *Call = IRB.CreateCall(AsanCovFunction);
Call->setDebugLoc(IP->getDebugLoc());
StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
Store->setAtomic(Monotonic);
Store->setAlignment(1);
}
// Poor man's coverage that works with ASan.
// We create a Guard boolean variable with the same linkage
// as the function and inject this code into the entry block (-asan-coverage=1)
// or all blocks (-asan-coverage=2):
// if (*Guard) {
// __sanitizer_cov(&F);
// *Guard = 1;
// }
// The accesses to Guard are atomic. The rest of the logic is
// in __sanitizer_cov (it's fine to call it more than once).
//
// This coverage implementation provides very limited data:
// it only tells if a given function (block) was ever executed.
// No counters, no per-edge data.
// But for many use cases this is what we need and the added slowdown
// is negligible. This simple implementation will probably be obsoleted
// by the upcoming Clang-based coverage implementation.
// By having it here and now we hope to
// a) get the functionality to users earlier and
// b) collect usage statistics to help improve Clang coverage design.
bool AddressSanitizer::InjectCoverage(Function &F,
const ArrayRef<BasicBlock *> AllBlocks) {
if (!ClCoverage) return false;
if (ClCoverage == 1) {
InjectCoverageAtBlock(F, F.getEntryBlock());
} else {
for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
InjectCoverageAtBlock(F, *AllBlocks[i]);
}
return true;
}
bool AddressSanitizer::runOnFunction(Function &F) {
if (BL->isIn(F)) return false;
if (&F == AsanCtorFunction) return false;
if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
initializeCallbacks(*F.getParent());
// If needed, insert __asan_init before checking for SanitizeAddress attr.
maybeInsertAsanInitAtFunctionEntry(F);
if (!F.hasFnAttribute(Attribute::SanitizeAddress))
return false;
if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
return false;
// We want to instrument every address only once per basic block (unless there
// are calls between uses).
SmallSet<Value*, 16> TempsToInstrument;
SmallVector<Instruction*, 16> ToInstrument;
SmallVector<Instruction*, 8> NoReturnCalls;
SmallVector<BasicBlock*, 16> AllBlocks;
SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
int NumAllocas = 0;
bool IsWrite;
// Fill the set of memory operations to instrument.
for (Function::iterator FI = F.begin(), FE = F.end();
FI != FE; ++FI) {
AllBlocks.push_back(FI);
TempsToInstrument.clear();
int NumInsnsPerBB = 0;
for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
BI != BE; ++BI) {
if (LooksLikeCodeInBug11395(BI)) return false;
if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
if (ClOpt && ClOptSameTemp) {
if (!TempsToInstrument.insert(Addr))
continue; // We've seen this temp in the current BB.
}
} else if (ClInvalidPointerPairs &&
isInterestingPointerComparisonOrSubtraction(BI)) {
PointerComparisonsOrSubtracts.push_back(BI);
continue;
} else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
// ok, take it.
} else {
if (isa<AllocaInst>(BI))
NumAllocas++;
CallSite CS(BI);
if (CS) {
// A call inside BB.
TempsToInstrument.clear();
if (CS.doesNotReturn())
NoReturnCalls.push_back(CS.getInstruction());
}
continue;
}
ToInstrument.push_back(BI);
NumInsnsPerBB++;
if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
break;
}
}
Function *UninstrumentedDuplicate = 0;
bool LikelyToInstrument =
!NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
if (ClKeepUninstrumented && LikelyToInstrument) {
ValueToValueMapTy VMap;
UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
}
// Instrument.
int NumInstrumented = 0;
for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
Instruction *Inst = ToInstrument[i];
if (ClDebugMin < 0 || ClDebugMax < 0 ||
(NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
if (isInterestingMemoryAccess(Inst, &IsWrite))
instrumentMop(Inst);
else
instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
}
NumInstrumented++;
}
FunctionStackPoisoner FSP(F, *this);
bool ChangedStack = FSP.runOnFunction();
// We must unpoison the stack before every NoReturn call (throw, _exit, etc).
// See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
Instruction *CI = NoReturnCalls[i];
IRBuilder<> IRB(CI);
IRB.CreateCall(AsanHandleNoReturnFunc);
}
for (size_t i = 0, n = PointerComparisonsOrSubtracts.size(); i != n; i++) {
instrumentPointerComparisonOrSubtraction(PointerComparisonsOrSubtracts[i]);
NumInstrumented++;
}
bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
if (InjectCoverage(F, AllBlocks))
res = true;
DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
if (ClKeepUninstrumented) {
if (!res) {
// No instrumentation is done, no need for the duplicate.
if (UninstrumentedDuplicate)
UninstrumentedDuplicate->eraseFromParent();
} else {
// The function was instrumented. We must have the duplicate.
assert(UninstrumentedDuplicate);
UninstrumentedDuplicate->setSection("NOASAN");
assert(!F.hasSection());
F.setSection("ASAN");
}
}
return res;
}
// Workaround for bug 11395: we don't want to instrument stack in functions
// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
// FIXME: remove once the bug 11395 is fixed.
bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
if (LongSize != 32) return false;
CallInst *CI = dyn_cast<CallInst>(I);
if (!CI || !CI->isInlineAsm()) return false;
if (CI->getNumArgOperands() <= 5) return false;
// We have inline assembly with quite a few arguments.
return true;
}
void FunctionStackPoisoner::initializeCallbacks(Module &M) {
IRBuilder<> IRB(*C);
for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
std::string Suffix = itostr(i);
AsanStackMallocFunc[i] = checkInterfaceFunction(
M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
IntptrTy, IntptrTy, NULL));
AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
IntptrTy, IntptrTy, NULL));
}
AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
}
void
FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
IRBuilder<> &IRB, Value *ShadowBase,
bool DoPoison) {
size_t n = ShadowBytes.size();
size_t i = 0;
// We need to (un)poison n bytes of stack shadow. Poison as many as we can
// using 64-bit stores (if we are on 64-bit arch), then poison the rest
// with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
uint64_t Val = 0;
for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
if (ASan.DL->isLittleEndian())
Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
else
Val = (Val << 8) | ShadowBytes[i + j];
}
if (!Val) continue;
Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
}
}
}
// Fake stack allocator (asan_fake_stack.h) has 11 size classes
// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
static int StackMallocSizeClass(uint64_t LocalStackSize) {
assert(LocalStackSize <= kMaxStackMallocSize);
uint64_t MaxSize = kMinStackMallocSize;
for (int i = 0; ; i++, MaxSize *= 2)
if (LocalStackSize <= MaxSize)
return i;
llvm_unreachable("impossible LocalStackSize");
}
// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
// We can not use MemSet intrinsic because it may end up calling the actual
// memset. Size is a multiple of 8.
// Currently this generates 8-byte stores on x86_64; it may be better to
// generate wider stores.
void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
IRBuilder<> &IRB, Value *ShadowBase, int Size) {
assert(!(Size % 8));
assert(kAsanStackAfterReturnMagic == 0xf5);
for (int i = 0; i < Size; i += 8) {
Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
}
}
void FunctionStackPoisoner::poisonStack() {
int StackMallocIdx = -1;
assert(AllocaVec.size() > 0);
Instruction *InsBefore = AllocaVec[0];
IRBuilder<> IRB(InsBefore);
SmallVector<ASanStackVariableDescription, 16> SVD;
SVD.reserve(AllocaVec.size());
for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
AllocaInst *AI = AllocaVec[i];
ASanStackVariableDescription D = { AI->getName().data(),
getAllocaSizeInBytes(AI),
AI->getAlignment(), AI, 0};
SVD.push_back(D);
}
// Minimal header size (left redzone) is 4 pointers,
// i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
size_t MinHeaderSize = ASan.LongSize / 2;
ASanStackFrameLayout L;
ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
uint64_t LocalStackSize = L.FrameSize;
bool DoStackMalloc =
ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
AllocaInst *MyAlloca =
new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
assert((ClRealignStack & (ClRealignStack - 1)) == 0);
size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
MyAlloca->setAlignment(FrameAlignment);
assert(MyAlloca->isStaticAlloca());
Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
Value *LocalStackBase = OrigStackBase;
if (DoStackMalloc) {
// LocalStackBase = OrigStackBase
// if (__asan_option_detect_stack_use_after_return)
// LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
StackMallocIdx = StackMallocSizeClass(LocalStackSize);
assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
kAsanOptionDetectUAR, IRB.getInt32Ty());
Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
Constant::getNullValue(IRB.getInt32Ty()));
Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
IRBuilder<> IRBIf(Term);
LocalStackBase = IRBIf.CreateCall2(
AsanStackMallocFunc[StackMallocIdx],
ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
IRB.SetInsertPoint(InsBefore);
PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
Phi->addIncoming(OrigStackBase, CmpBlock);
Phi->addIncoming(LocalStackBase, SetBlock);
LocalStackBase = Phi;
}
// Insert poison calls for lifetime intrinsics for alloca.
bool HavePoisonedAllocas = false;
for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
assert(APC.InsBefore);
assert(APC.AI);
IRBuilder<> IRB(APC.InsBefore);
poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
HavePoisonedAllocas |= APC.DoPoison;
}
// Replace Alloca instructions with base+offset.
for (size_t i = 0, n = SVD.size(); i < n; i++) {
AllocaInst *AI = SVD[i].AI;
Value *NewAllocaPtr = IRB.CreateIntToPtr(
IRB.CreateAdd(LocalStackBase,
ConstantInt::get(IntptrTy, SVD[i].Offset)),
AI->getType());
replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
AI->replaceAllUsesWith(NewAllocaPtr);
}
// The left-most redzone has enough space for at least 4 pointers.
// Write the Magic value to redzone[0].
Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
BasePlus0);
// Write the frame description constant to redzone[1].
Value *BasePlus1 = IRB.CreateIntToPtr(
IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
IntptrPtrTy);
GlobalVariable *StackDescriptionGlobal =
createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
/*AllowMerging*/true);
Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
IntptrTy);
IRB.CreateStore(Description, BasePlus1);
// Write the PC to redzone[2].
Value *BasePlus2 = IRB.CreateIntToPtr(
IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
2 * ASan.LongSize/8)),
IntptrPtrTy);
IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
// Poison the stack redzones at the entry.
Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
// (Un)poison the stack before all ret instructions.
for (size_t i = 0, n = RetVec.size(); i < n; i++) {
Instruction *Ret = RetVec[i];
IRBuilder<> IRBRet(Ret);
// Mark the current frame as retired.
IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
BasePlus0);
if (DoStackMalloc) {
assert(StackMallocIdx >= 0);
// if LocalStackBase != OrigStackBase:
// // In use-after-return mode, poison the whole stack frame.
// if StackMallocIdx <= 4
// // For small sizes inline the whole thing:
// memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
// **SavedFlagPtr(LocalStackBase) = 0
// else
// __asan_stack_free_N(LocalStackBase, OrigStackBase)
// else
// <This is not a fake stack; unpoison the redzones>
Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
TerminatorInst *ThenTerm, *ElseTerm;
SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
IRBuilder<> IRBPoison(ThenTerm);
if (StackMallocIdx <= 4) {
int ClassSize = kMinStackMallocSize << StackMallocIdx;
SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
ClassSize >> Mapping.Scale);
Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
LocalStackBase,
ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
Value *SavedFlagPtr = IRBPoison.CreateLoad(
IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
IRBPoison.CreateStore(
Constant::getNullValue(IRBPoison.getInt8Ty()),
IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
} else {
// For larger frames call __asan_stack_free_*.
IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
ConstantInt::get(IntptrTy, LocalStackSize),
OrigStackBase);
}
IRBuilder<> IRBElse(ElseTerm);
poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
} else if (HavePoisonedAllocas) {
// If we poisoned some allocas in llvm.lifetime analysis,
// unpoison whole stack frame now.
assert(LocalStackBase == OrigStackBase);
poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
} else {
poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
}
}
// We are done. Remove the old unused alloca instructions.
for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
AllocaVec[i]->eraseFromParent();
}
void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
IRBuilder<> &IRB, bool DoPoison) {
// For now just insert the call to ASan runtime.
Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
Value *SizeArg = ConstantInt::get(IntptrTy, Size);
IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
: AsanUnpoisonStackMemoryFunc,
AddrArg, SizeArg);
}
// Handling llvm.lifetime intrinsics for a given %alloca:
// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
// could be poisoned by previous llvm.lifetime.end instruction, as the
// variable may go in and out of scope several times, e.g. in loops).
// (3) if we poisoned at least one %alloca in a function,
// unpoison the whole stack frame at function exit.
AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
// We're intested only in allocas we can handle.
return isInterestingAlloca(*AI) ? AI : 0;
// See if we've already calculated (or started to calculate) alloca for a
// given value.
AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
if (I != AllocaForValue.end())
return I->second;
// Store 0 while we're calculating alloca for value V to avoid
// infinite recursion if the value references itself.
AllocaForValue[V] = 0;
AllocaInst *Res = 0;
if (CastInst *CI = dyn_cast<CastInst>(V))
Res = findAllocaForValue(CI->getOperand(0));
else if (PHINode *PN = dyn_cast<PHINode>(V)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *IncValue = PN->getIncomingValue(i);
// Allow self-referencing phi-nodes.
if (IncValue == PN) continue;
AllocaInst *IncValueAI = findAllocaForValue(IncValue);
// AI for incoming values should exist and should all be equal.
if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
return 0;
Res = IncValueAI;
}
}
if (Res != 0)
AllocaForValue[V] = Res;
return Res;
}
[ASan] Fix https://code.google.com/p/address-sanitizer/issues/detail?id=274
by ignoring globals from __TEXT,__cstring,cstring_literals during instrumenation.
Add a regression test.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@203916 91177308-0d34-0410-b5e6-96231b3b80d8
//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
// Details of the algorithm:
// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asan"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/system_error.h"
#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "llvm/Transforms/Utils/SpecialCaseList.h"
#include <algorithm>
#include <string>
using namespace llvm;
static const uint64_t kDefaultShadowScale = 3;
static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
static const size_t kMinStackMallocSize = 1 << 6; // 64B
static const size_t kMaxStackMallocSize = 1 << 16; // 64K
static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
static const char *const kAsanModuleCtorName = "asan.module_ctor";
static const char *const kAsanModuleDtorName = "asan.module_dtor";
static const int kAsanCtorAndCtorPriority = 1;
static const char *const kAsanReportErrorTemplate = "__asan_report_";
static const char *const kAsanReportLoadN = "__asan_report_load_n";
static const char *const kAsanReportStoreN = "__asan_report_store_n";
static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
static const char *const kAsanUnregisterGlobalsName =
"__asan_unregister_globals";
static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
static const char *const kAsanInitName = "__asan_init_v3";
static const char *const kAsanCovName = "__sanitizer_cov";
static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
static const int kMaxAsanStackMallocSizeClass = 10;
static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
static const char *const kAsanGenPrefix = "__asan_gen_";
static const char *const kAsanPoisonStackMemoryName =
"__asan_poison_stack_memory";
static const char *const kAsanUnpoisonStackMemoryName =
"__asan_unpoison_stack_memory";
static const char *const kAsanOptionDetectUAR =
"__asan_option_detect_stack_use_after_return";
#ifndef NDEBUG
static const int kAsanStackAfterReturnMagic = 0xf5;
#endif
// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
static const size_t kNumberOfAccessSizes = 5;
// Command-line flags.
// This flag may need to be replaced with -f[no-]asan-reads.
static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
cl::Hidden, cl::init(true));
static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
cl::desc("use instrumentation with slow path for all accesses"),
cl::Hidden, cl::init(false));
// This flag limits the number of instructions to be instrumented
// in any given BB. Normally, this should be set to unlimited (INT_MAX),
// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
// set it to 10000.
static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
cl::init(10000),
cl::desc("maximal number of instructions to instrument in any given BB"),
cl::Hidden);
// This flag may need to be replaced with -f[no]asan-stack.
static cl::opt<bool> ClStack("asan-stack",
cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
// This flag may need to be replaced with -f[no]asan-use-after-return.
static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
// This flag may need to be replaced with -f[no]asan-globals.
static cl::opt<bool> ClGlobals("asan-globals",
cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
static cl::opt<int> ClCoverage("asan-coverage",
cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
cl::Hidden, cl::init(false));
static cl::opt<bool> ClInitializers("asan-initialization-order",
cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
static cl::opt<bool> ClMemIntrin("asan-memintrin",
cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
cl::Hidden, cl::init(false));
static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
cl::desc("Realign stack to the value of this flag (power of two)"),
cl::Hidden, cl::init(32));
static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
cl::desc("File containing the list of objects to ignore "
"during instrumentation"), cl::Hidden);
// This is an experimental feature that will allow to choose between
// instrumented and non-instrumented code at link-time.
// If this option is on, just before instrumenting a function we create its
// clone; if the function is not changed by asan the clone is deleted.
// If we end up with a clone, we put the instrumented function into a section
// called "ASAN" and the uninstrumented function into a section called "NOASAN".
//
// This is still a prototype, we need to figure out a way to keep two copies of
// a function so that the linker can easily choose one of them.
static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
cl::desc("Keep uninstrumented copies of functions"),
cl::Hidden, cl::init(false));
// These flags allow to change the shadow mapping.
// The shadow mapping looks like
// Shadow = (Mem >> scale) + (1 << offset_log)
static cl::opt<int> ClMappingScale("asan-mapping-scale",
cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
// Optimization flags. Not user visible, used mostly for testing
// and benchmarking the tool.
static cl::opt<bool> ClOpt("asan-opt",
cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
cl::desc("Instrument the same temp just once"), cl::Hidden,
cl::init(true));
static cl::opt<bool> ClOptGlobals("asan-opt-globals",
cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
cl::Hidden, cl::init(false));
// Debug flags.
static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
cl::init(0));
static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
cl::Hidden, cl::init(0));
static cl::opt<std::string> ClDebugFunc("asan-debug-func",
cl::Hidden, cl::desc("Debug func"));
static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
cl::Hidden, cl::init(-1));
static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
cl::Hidden, cl::init(-1));
STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
STATISTIC(NumOptimizedAccessesToGlobalArray,
"Number of optimized accesses to global arrays");
STATISTIC(NumOptimizedAccessesToGlobalVar,
"Number of optimized accesses to global vars");
namespace {
/// A set of dynamically initialized globals extracted from metadata.
class SetOfDynamicallyInitializedGlobals {
public:
void Init(Module& M) {
// Clang generates metadata identifying all dynamically initialized globals.
NamedMDNode *DynamicGlobals =
M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
if (!DynamicGlobals)
return;
for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
MDNode *MDN = DynamicGlobals->getOperand(i);
assert(MDN->getNumOperands() == 1);
Value *VG = MDN->getOperand(0);
// The optimizer may optimize away a global entirely, in which case we
// cannot instrument access to it.
if (!VG)
continue;
DynInitGlobals.insert(cast<GlobalVariable>(VG));
}
}
bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
private:
SmallSet<GlobalValue*, 32> DynInitGlobals;
};
/// This struct defines the shadow mapping using the rule:
/// shadow = (mem >> Scale) ADD-or-OR Offset.
struct ShadowMapping {
int Scale;
uint64_t Offset;
bool OrShadowOffset;
};
static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
llvm::Triple TargetTriple(M.getTargetTriple());
bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
// bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
TargetTriple.getArch() == llvm::Triple::ppc64le;
bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
TargetTriple.getArch() == llvm::Triple::mipsel;
ShadowMapping Mapping;
if (LongSize == 32) {
if (IsAndroid)
Mapping.Offset = 0;
else if (IsMIPS32)
Mapping.Offset = kMIPS32_ShadowOffset32;
else if (IsFreeBSD)
Mapping.Offset = kFreeBSD_ShadowOffset32;
else
Mapping.Offset = kDefaultShadowOffset32;
} else { // LongSize == 64
if (IsPPC64)
Mapping.Offset = kPPC64_ShadowOffset64;
else if (IsFreeBSD)
Mapping.Offset = kFreeBSD_ShadowOffset64;
else if (IsLinux && IsX86_64)
Mapping.Offset = kSmallX86_64ShadowOffset;
else
Mapping.Offset = kDefaultShadowOffset64;
}
Mapping.Scale = kDefaultShadowScale;
if (ClMappingScale) {
Mapping.Scale = ClMappingScale;
}
// OR-ing shadow offset if more efficient (at least on x86) if the offset
// is a power of two, but on ppc64 we have to use add since the shadow
// offset is not necessary 1/8-th of the address space.
Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
return Mapping;
}
static size_t RedzoneSizeForScale(int MappingScale) {
// Redzone used for stack and globals is at least 32 bytes.
// For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
return std::max(32U, 1U << MappingScale);
}
/// AddressSanitizer: instrument the code in module to find memory bugs.
struct AddressSanitizer : public FunctionPass {
AddressSanitizer(bool CheckInitOrder = true,
bool CheckUseAfterReturn = false,
bool CheckLifetime = false,
StringRef BlacklistFile = StringRef())
: FunctionPass(ID),
CheckInitOrder(CheckInitOrder || ClInitializers),
CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
CheckLifetime(CheckLifetime || ClCheckLifetime),
BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
: BlacklistFile) {}
const char *getPassName() const override {
return "AddressSanitizerFunctionPass";
}
void instrumentMop(Instruction *I);
void instrumentPointerComparisonOrSubtraction(Instruction *I);
void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
Value *Addr, uint32_t TypeSize, bool IsWrite,
Value *SizeArgument);
Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Value *ShadowValue, uint32_t TypeSize);
Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
bool IsWrite, size_t AccessSizeIndex,
Value *SizeArgument);
bool instrumentMemIntrinsic(MemIntrinsic *MI);
void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Value *Size,
Instruction *InsertBefore, bool IsWrite);
Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
bool runOnFunction(Function &F) override;
bool maybeInsertAsanInitAtFunctionEntry(Function &F);
bool doInitialization(Module &M) override;
static char ID; // Pass identification, replacement for typeid
private:
void initializeCallbacks(Module &M);
bool ShouldInstrumentGlobal(GlobalVariable *G);
bool LooksLikeCodeInBug11395(Instruction *I);
void FindDynamicInitializers(Module &M);
bool GlobalIsLinkerInitialized(GlobalVariable *G);
bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
bool CheckInitOrder;
bool CheckUseAfterReturn;
bool CheckLifetime;
SmallString<64> BlacklistFile;
LLVMContext *C;
const DataLayout *DL;
int LongSize;
Type *IntptrTy;
ShadowMapping Mapping;
Function *AsanCtorFunction;
Function *AsanInitFunction;
Function *AsanHandleNoReturnFunc;
Function *AsanCovFunction;
Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
std::unique_ptr<SpecialCaseList> BL;
// This array is indexed by AccessIsWrite and log2(AccessSize).
Function *AsanErrorCallback[2][kNumberOfAccessSizes];
// This array is indexed by AccessIsWrite.
Function *AsanErrorCallbackSized[2];
InlineAsm *EmptyAsm;
SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
friend struct FunctionStackPoisoner;
};
class AddressSanitizerModule : public ModulePass {
public:
AddressSanitizerModule(bool CheckInitOrder = true,
StringRef BlacklistFile = StringRef())
: ModulePass(ID),
CheckInitOrder(CheckInitOrder || ClInitializers),
BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
: BlacklistFile) {}
bool runOnModule(Module &M) override;
static char ID; // Pass identification, replacement for typeid
const char *getPassName() const override {
return "AddressSanitizerModule";
}
private:
void initializeCallbacks(Module &M);
bool ShouldInstrumentGlobal(GlobalVariable *G);
void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
size_t MinRedzoneSizeForGlobal() const {
return RedzoneSizeForScale(Mapping.Scale);
}
bool CheckInitOrder;
SmallString<64> BlacklistFile;
std::unique_ptr<SpecialCaseList> BL;
SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Type *IntptrTy;
LLVMContext *C;
const DataLayout *DL;
ShadowMapping Mapping;
Function *AsanPoisonGlobals;
Function *AsanUnpoisonGlobals;
Function *AsanRegisterGlobals;
Function *AsanUnregisterGlobals;
};
// Stack poisoning does not play well with exception handling.
// When an exception is thrown, we essentially bypass the code
// that unpoisones the stack. This is why the run-time library has
// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
// stack in the interceptor. This however does not work inside the
// actual function which catches the exception. Most likely because the
// compiler hoists the load of the shadow value somewhere too high.
// This causes asan to report a non-existing bug on 453.povray.
// It sounds like an LLVM bug.
struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
Function &F;
AddressSanitizer &ASan;
DIBuilder DIB;
LLVMContext *C;
Type *IntptrTy;
Type *IntptrPtrTy;
ShadowMapping Mapping;
SmallVector<AllocaInst*, 16> AllocaVec;
SmallVector<Instruction*, 8> RetVec;
unsigned StackAlignment;
Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
*AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
// Stores a place and arguments of poisoning/unpoisoning call for alloca.
struct AllocaPoisonCall {
IntrinsicInst *InsBefore;
AllocaInst *AI;
uint64_t Size;
bool DoPoison;
};
SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
// Maps Value to an AllocaInst from which the Value is originated.
typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
AllocaForValueMapTy AllocaForValue;
FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
: F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Mapping(ASan.Mapping),
StackAlignment(1 << Mapping.Scale) {}
bool runOnFunction() {
if (!ClStack) return false;
// Collect alloca, ret, lifetime instructions etc.
for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
BasicBlock *BB = *DI;
visit(*BB);
}
if (AllocaVec.empty()) return false;
initializeCallbacks(*F.getParent());
poisonStack();
if (ClDebugStack) {
DEBUG(dbgs() << F);
}
return true;
}
// Finds all static Alloca instructions and puts
// poisoned red zones around all of them.
// Then unpoison everything back before the function returns.
void poisonStack();
// ----------------------- Visitors.
/// \brief Collect all Ret instructions.
void visitReturnInst(ReturnInst &RI) {
RetVec.push_back(&RI);
}
/// \brief Collect Alloca instructions we want (and can) handle.
void visitAllocaInst(AllocaInst &AI) {
if (!isInterestingAlloca(AI)) return;
StackAlignment = std::max(StackAlignment, AI.getAlignment());
AllocaVec.push_back(&AI);
}
/// \brief Collect lifetime intrinsic calls to check for use-after-scope
/// errors.
void visitIntrinsicInst(IntrinsicInst &II) {
if (!ASan.CheckLifetime) return;
Intrinsic::ID ID = II.getIntrinsicID();
if (ID != Intrinsic::lifetime_start &&
ID != Intrinsic::lifetime_end)
return;
// Found lifetime intrinsic, add ASan instrumentation if necessary.
ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
// If size argument is undefined, don't do anything.
if (Size->isMinusOne()) return;
// Check that size doesn't saturate uint64_t and can
// be stored in IntptrTy.
const uint64_t SizeValue = Size->getValue().getLimitedValue();
if (SizeValue == ~0ULL ||
!ConstantInt::isValueValidForType(IntptrTy, SizeValue))
return;
// Find alloca instruction that corresponds to llvm.lifetime argument.
AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
if (!AI) return;
bool DoPoison = (ID == Intrinsic::lifetime_end);
AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
AllocaPoisonCallVec.push_back(APC);
}
// ---------------------- Helpers.
void initializeCallbacks(Module &M);
// Check if we want (and can) handle this alloca.
bool isInterestingAlloca(AllocaInst &AI) const {
return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
AI.getAllocatedType()->isSized() &&
// alloca() may be called with 0 size, ignore it.
getAllocaSizeInBytes(&AI) > 0);
}
uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Type *Ty = AI->getAllocatedType();
uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
return SizeInBytes;
}
/// Finds alloca where the value comes from.
AllocaInst *findAllocaForValue(Value *V);
void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Value *ShadowBase, bool DoPoison);
void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
int Size);
};
} // namespace
char AddressSanitizer::ID = 0;
INITIALIZE_PASS(AddressSanitizer, "asan",
"AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
false, false)
FunctionPass *llvm::createAddressSanitizerFunctionPass(
bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
StringRef BlacklistFile) {
return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
CheckLifetime, BlacklistFile);
}
char AddressSanitizerModule::ID = 0;
INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
"AddressSanitizer: detects use-after-free and out-of-bounds bugs."
"ModulePass", false, false)
ModulePass *llvm::createAddressSanitizerModulePass(
bool CheckInitOrder, StringRef BlacklistFile) {
return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
}
static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
size_t Res = countTrailingZeros(TypeSize / 8);
assert(Res < kNumberOfAccessSizes);
return Res;
}
// \brief Create a constant for Str so that we can pass it to the run-time lib.
static GlobalVariable *createPrivateGlobalForString(
Module &M, StringRef Str, bool AllowMerging) {
Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
// We use private linkage for module-local strings. If they can be merged
// with another one, we set the unnamed_addr attribute.
GlobalVariable *GV =
new GlobalVariable(M, StrConst->getType(), true,
GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
if (AllowMerging)
GV->setUnnamedAddr(true);
GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
return GV;
}
static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
return G->getName().find(kAsanGenPrefix) == 0;
}
Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
// Shadow >> scale
Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
if (Mapping.Offset == 0)
return Shadow;
// (Shadow >> scale) | offset
if (Mapping.OrShadowOffset)
return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
else
return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
}
void AddressSanitizer::instrumentMemIntrinsicParam(
Instruction *OrigIns,
Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
IRBuilder<> IRB(InsertBefore);
if (Size->getType() != IntptrTy)
Size = IRB.CreateIntCast(Size, IntptrTy, false);
// Check the first byte.
instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
// Check the last byte.
IRB.SetInsertPoint(InsertBefore);
Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
}
// Instrument memset/memmove/memcpy
bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Value *Dst = MI->getDest();
MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Value *Src = MemTran ? MemTran->getSource() : 0;
Value *Length = MI->getLength();
Constant *ConstLength = dyn_cast<Constant>(Length);
Instruction *InsertBefore = MI;
if (ConstLength) {
if (ConstLength->isNullValue()) return false;
} else {
// The size is not a constant so it could be zero -- check at run-time.
IRBuilder<> IRB(InsertBefore);
Value *Cmp = IRB.CreateICmpNE(Length,
Constant::getNullValue(Length->getType()));
InsertBefore = SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
}
instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
if (Src)
instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
return true;
}
// If I is an interesting memory access, return the PointerOperand
// and set IsWrite. Otherwise return NULL.
static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
if (!ClInstrumentReads) return NULL;
*IsWrite = false;
return LI->getPointerOperand();
}
if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
if (!ClInstrumentWrites) return NULL;
*IsWrite = true;
return SI->getPointerOperand();
}
if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
if (!ClInstrumentAtomics) return NULL;
*IsWrite = true;
return RMW->getPointerOperand();
}
if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
if (!ClInstrumentAtomics) return NULL;
*IsWrite = true;
return XCHG->getPointerOperand();
}
return NULL;
}
static bool isPointerOperand(Value *V) {
return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
}
// This is a rough heuristic; it may cause both false positives and
// false negatives. The proper implementation requires cooperation with
// the frontend.
static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
if (!Cmp->isRelational())
return false;
} else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
if (BO->getOpcode() != Instruction::Sub)
return false;
} else {
return false;
}
if (!isPointerOperand(I->getOperand(0)) ||
!isPointerOperand(I->getOperand(1)))
return false;
return true;
}
bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
// If a global variable does not have dynamic initialization we don't
// have to instrument it. However, if a global does not have initializer
// at all, we assume it has dynamic initializer (in other TU).
return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
}
void
AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
IRBuilder<> IRB(I);
Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
for (int i = 0; i < 2; i++) {
if (Param[i]->getType()->isPointerTy())
Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
}
IRB.CreateCall2(F, Param[0], Param[1]);
}
void AddressSanitizer::instrumentMop(Instruction *I) {
bool IsWrite = false;
Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
assert(Addr);
if (ClOpt && ClOptGlobals) {
if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
// If initialization order checking is disabled, a simple access to a
// dynamically initialized global is always valid.
if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
NumOptimizedAccessesToGlobalVar++;
return;
}
}
ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
NumOptimizedAccessesToGlobalArray++;
return;
}
}
}
}
Type *OrigPtrTy = Addr->getType();
Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
assert(OrigTy->isSized());
uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
assert((TypeSize % 8) == 0);
if (IsWrite)
NumInstrumentedWrites++;
else
NumInstrumentedReads++;
// Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
if (TypeSize == 8 || TypeSize == 16 ||
TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
// Instrument unusual size (but still multiple of 8).
// We can not do it with a single check, so we do 1-byte check for the first
// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
// to report the actual access size.
IRBuilder<> IRB(I);
Value *LastByte = IRB.CreateIntToPtr(
IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
OrigPtrTy);
Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
instrumentAddress(I, I, Addr, 8, IsWrite, Size);
instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
}
// Validate the result of Module::getOrInsertFunction called for an interface
// function of AddressSanitizer. If the instrumented module defines a function
// with the same name, their prototypes must match, otherwise
// getOrInsertFunction returns a bitcast.
static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
FuncOrBitcast->dump();
report_fatal_error("trying to redefine an AddressSanitizer "
"interface function");
}
Instruction *AddressSanitizer::generateCrashCode(
Instruction *InsertBefore, Value *Addr,
bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
IRBuilder<> IRB(InsertBefore);
CallInst *Call = SizeArgument
? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
: IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
// We don't do Call->setDoesNotReturn() because the BB already has
// UnreachableInst at the end.
// This EmptyAsm is required to avoid callback merge.
IRB.CreateCall(EmptyAsm);
return Call;
}
Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Value *ShadowValue,
uint32_t TypeSize) {
size_t Granularity = 1 << Mapping.Scale;
// Addr & (Granularity - 1)
Value *LastAccessedByte = IRB.CreateAnd(
AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
// (Addr & (Granularity - 1)) + size - 1
if (TypeSize / 8 > 1)
LastAccessedByte = IRB.CreateAdd(
LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
// (uint8_t) ((Addr & (Granularity-1)) + size - 1)
LastAccessedByte = IRB.CreateIntCast(
LastAccessedByte, ShadowValue->getType(), false);
// ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
}
void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Instruction *InsertBefore,
Value *Addr, uint32_t TypeSize,
bool IsWrite, Value *SizeArgument) {
IRBuilder<> IRB(InsertBefore);
Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Type *ShadowTy = IntegerType::get(
*C, std::max(8U, TypeSize >> Mapping.Scale));
Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
Value *ShadowPtr = memToShadow(AddrLong, IRB);
Value *CmpVal = Constant::getNullValue(ShadowTy);
Value *ShadowValue = IRB.CreateLoad(
IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
size_t Granularity = 1 << Mapping.Scale;
TerminatorInst *CrashTerm = 0;
if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
TerminatorInst *CheckTerm =
SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
BasicBlock *NextBB = CheckTerm->getSuccessor(0);
IRB.SetInsertPoint(CheckTerm);
Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
BasicBlock *CrashBlock =
BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
CrashTerm = new UnreachableInst(*C, CrashBlock);
BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
ReplaceInstWithInst(CheckTerm, NewTerm);
} else {
CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
}
Instruction *Crash = generateCrashCode(
CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Crash->setDebugLoc(OrigIns->getDebugLoc());
}
void AddressSanitizerModule::createInitializerPoisonCalls(
Module &M, GlobalValue *ModuleName) {
// We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
// If that function is not present, this TU contains no globals, or they have
// all been optimized away
if (!GlobalInit)
return;
// Set up the arguments to our poison/unpoison functions.
IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
// Add a call to poison all external globals before the given function starts.
Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
// Add calls to unpoison all globals before each return instruction.
for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
I != E; ++I) {
if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
CallInst::Create(AsanUnpoisonGlobals, "", RI);
}
}
}
bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Type *Ty = cast<PointerType>(G->getType())->getElementType();
DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
if (BL->isIn(*G)) return false;
if (!Ty->isSized()) return false;
if (!G->hasInitializer()) return false;
if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
// Touch only those globals that will not be defined in other modules.
// Don't handle ODR type linkages since other modules may be built w/o asan.
if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
G->getLinkage() != GlobalVariable::PrivateLinkage &&
G->getLinkage() != GlobalVariable::InternalLinkage)
return false;
// Two problems with thread-locals:
// - The address of the main thread's copy can't be computed at link-time.
// - Need to poison all copies, not just the main thread's one.
if (G->isThreadLocal())
return false;
// For now, just ignore this Global if the alignment is large.
if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
// Ignore all the globals with the names starting with "\01L_OBJC_".
// Many of those are put into the .cstring section. The linker compresses
// that section by removing the spare \0s after the string terminator, so
// our redzones get broken.
if ((G->getName().find("\01L_OBJC_") == 0) ||
(G->getName().find("\01l_OBJC_") == 0)) {
DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
return false;
}
if (G->hasSection()) {
StringRef Section(G->getSection());
// Ignore the globals from the __OBJC section. The ObjC runtime assumes
// those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
// them.
if ((Section.find("__OBJC,") == 0) ||
(Section.find("__DATA, __objc_") == 0)) {
DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
return false;
}
// See http://code.google.com/p/address-sanitizer/issues/detail?id=32
// Constant CFString instances are compiled in the following way:
// -- the string buffer is emitted into
// __TEXT,__cstring,cstring_literals
// -- the constant NSConstantString structure referencing that buffer
// is placed into __DATA,__cfstring
// Therefore there's no point in placing redzones into __DATA,__cfstring.
// Moreover, it causes the linker to crash on OS X 10.7
if (Section.find("__DATA,__cfstring") == 0) {
DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
return false;
}
// The linker merges the contents of cstring_literals and removes the
// trailing zeroes.
if (Section.find("__TEXT,__cstring,cstring_literals") == 0) {
DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
return false;
}
}
return true;
}
void AddressSanitizerModule::initializeCallbacks(Module &M) {
IRBuilder<> IRB(*C);
// Declare our poisoning and unpoisoning functions.
AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
// Declare functions that register/unregister globals.
AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanRegisterGlobalsName, IRB.getVoidTy(),
IntptrTy, IntptrTy, NULL));
AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
kAsanUnregisterGlobalsName,
IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
}
// This function replaces all global variables with new variables that have
// trailing redzones. It also creates a function that poisons
// redzones and inserts this function into llvm.global_ctors.
bool AddressSanitizerModule::runOnModule(Module &M) {
if (!ClGlobals) return false;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
if (!DLP)
return false;
DL = &DLP->getDataLayout();
BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
if (BL->isIn(M)) return false;
C = &(M.getContext());
int LongSize = DL->getPointerSizeInBits();
IntptrTy = Type::getIntNTy(*C, LongSize);
Mapping = getShadowMapping(M, LongSize);
initializeCallbacks(M);
DynamicallyInitializedGlobals.Init(M);
SmallVector<GlobalVariable *, 16> GlobalsToChange;
for (Module::GlobalListType::iterator G = M.global_begin(),
E = M.global_end(); G != E; ++G) {
if (ShouldInstrumentGlobal(G))
GlobalsToChange.push_back(G);
}
size_t n = GlobalsToChange.size();
if (n == 0) return false;
// A global is described by a structure
// size_t beg;
// size_t size;
// size_t size_with_redzone;
// const char *name;
// const char *module_name;
// size_t has_dynamic_init;
// We initialize an array of such structures and pass it to a run-time call.
StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
IntptrTy, IntptrTy,
IntptrTy, IntptrTy, NULL);
SmallVector<Constant *, 16> Initializers(n);
Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
assert(CtorFunc);
IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
bool HasDynamicallyInitializedGlobals = false;
// We shouldn't merge same module names, as this string serves as unique
// module ID in runtime.
GlobalVariable *ModuleName = createPrivateGlobalForString(
M, M.getModuleIdentifier(), /*AllowMerging*/false);
for (size_t i = 0; i < n; i++) {
static const uint64_t kMaxGlobalRedzone = 1 << 18;
GlobalVariable *G = GlobalsToChange[i];
PointerType *PtrTy = cast<PointerType>(G->getType());
Type *Ty = PtrTy->getElementType();
uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
uint64_t MinRZ = MinRedzoneSizeForGlobal();
// MinRZ <= RZ <= kMaxGlobalRedzone
// and trying to make RZ to be ~ 1/4 of SizeInBytes.
uint64_t RZ = std::max(MinRZ,
std::min(kMaxGlobalRedzone,
(SizeInBytes / MinRZ / 4) * MinRZ));
uint64_t RightRedzoneSize = RZ;
// Round up to MinRZ
if (SizeInBytes % MinRZ)
RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
// Determine whether this global should be poisoned in initialization.
bool GlobalHasDynamicInitializer =
DynamicallyInitializedGlobals.Contains(G);
// Don't check initialization order if this global is blacklisted.
GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
Constant *NewInitializer = ConstantStruct::get(
NewTy, G->getInitializer(),
Constant::getNullValue(RightRedZoneTy), NULL);
GlobalVariable *Name =
createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
// Create a new global variable with enough space for a redzone.
GlobalValue::LinkageTypes Linkage = G->getLinkage();
if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
Linkage = GlobalValue::InternalLinkage;
GlobalVariable *NewGlobal = new GlobalVariable(
M, NewTy, G->isConstant(), Linkage,
NewInitializer, "", G, G->getThreadLocalMode());
NewGlobal->copyAttributesFrom(G);
NewGlobal->setAlignment(MinRZ);
Value *Indices2[2];
Indices2[0] = IRB.getInt32(0);
Indices2[1] = IRB.getInt32(0);
G->replaceAllUsesWith(
ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
NewGlobal->takeName(G);
G->eraseFromParent();
Initializers[i] = ConstantStruct::get(
GlobalStructTy,
ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
ConstantInt::get(IntptrTy, SizeInBytes),
ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
ConstantExpr::getPointerCast(Name, IntptrTy),
ConstantExpr::getPointerCast(ModuleName, IntptrTy),
ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
NULL);
// Populate the first and last globals declared in this TU.
if (CheckInitOrder && GlobalHasDynamicInitializer)
HasDynamicallyInitializedGlobals = true;
DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
}
ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
GlobalVariable *AllGlobals = new GlobalVariable(
M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
// Create calls for poisoning before initializers run and unpoisoning after.
if (CheckInitOrder && HasDynamicallyInitializedGlobals)
createInitializerPoisonCalls(M, ModuleName);
IRB.CreateCall2(AsanRegisterGlobals,
IRB.CreatePointerCast(AllGlobals, IntptrTy),
ConstantInt::get(IntptrTy, n));
// We also need to unregister globals at the end, e.g. when a shared library
// gets closed.
Function *AsanDtorFunction = Function::Create(
FunctionType::get(Type::getVoidTy(*C), false),
GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
IRB.CreatePointerCast(AllGlobals, IntptrTy),
ConstantInt::get(IntptrTy, n));
appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
DEBUG(dbgs() << M);
return true;
}
void AddressSanitizer::initializeCallbacks(Module &M) {
IRBuilder<> IRB(*C);
// Create __asan_report* callbacks.
for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
AccessSizeIndex++) {
// IsWrite and TypeSize are encoded in the function name.
std::string FunctionName = std::string(kAsanReportErrorTemplate) +
(AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
// If we are merging crash callbacks, they have two parameters.
AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
checkInterfaceFunction(M.getOrInsertFunction(
FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
}
}
AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
kAsanCovName, IRB.getVoidTy(), NULL));
AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
// We insert an empty inline asm after __asan_report* to avoid callback merge.
EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
StringRef(""), StringRef(""),
/*hasSideEffects=*/true);
}
// virtual
bool AddressSanitizer::doInitialization(Module &M) {
// Initialize the private fields. No one has accessed them before.
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
if (!DLP)
return false;
DL = &DLP->getDataLayout();
BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
DynamicallyInitializedGlobals.Init(M);
C = &(M.getContext());
LongSize = DL->getPointerSizeInBits();
IntptrTy = Type::getIntNTy(*C, LongSize);
AsanCtorFunction = Function::Create(
FunctionType::get(Type::getVoidTy(*C), false),
GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
// call __asan_init in the module ctor.
IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
AsanInitFunction = checkInterfaceFunction(
M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
AsanInitFunction->setLinkage(Function::ExternalLinkage);
IRB.CreateCall(AsanInitFunction);
Mapping = getShadowMapping(M, LongSize);
appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
return true;
}
bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
// For each NSObject descendant having a +load method, this method is invoked
// by the ObjC runtime before any of the static constructors is called.
// Therefore we need to instrument such methods with a call to __asan_init
// at the beginning in order to initialize our runtime before any access to
// the shadow memory.
// We cannot just ignore these methods, because they may call other
// instrumented functions.
if (F.getName().find(" load]") != std::string::npos) {
IRBuilder<> IRB(F.begin()->begin());
IRB.CreateCall(AsanInitFunction);
return true;
}
return false;
}
void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
// Skip static allocas at the top of the entry block so they don't become
// dynamic when we split the block. If we used our optimized stack layout,
// then there will only be one alloca and it will come first.
for (; IP != BE; ++IP) {
AllocaInst *AI = dyn_cast<AllocaInst>(IP);
if (!AI || !AI->isStaticAlloca())
break;
}
IRBuilder<> IRB(IP);
Type *Int8Ty = IRB.getInt8Ty();
GlobalVariable *Guard = new GlobalVariable(
*F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
LoadInst *Load = IRB.CreateLoad(Guard);
Load->setAtomic(Monotonic);
Load->setAlignment(1);
Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
Instruction *Ins = SplitBlockAndInsertIfThen(
Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
IRB.SetInsertPoint(Ins);
// We pass &F to __sanitizer_cov. We could avoid this and rely on
// GET_CALLER_PC, but having the PC of the first instruction is just nice.
Instruction *Call = IRB.CreateCall(AsanCovFunction);
Call->setDebugLoc(IP->getDebugLoc());
StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
Store->setAtomic(Monotonic);
Store->setAlignment(1);
}
// Poor man's coverage that works with ASan.
// We create a Guard boolean variable with the same linkage
// as the function and inject this code into the entry block (-asan-coverage=1)
// or all blocks (-asan-coverage=2):
// if (*Guard) {
// __sanitizer_cov(&F);
// *Guard = 1;
// }
// The accesses to Guard are atomic. The rest of the logic is
// in __sanitizer_cov (it's fine to call it more than once).
//
// This coverage implementation provides very limited data:
// it only tells if a given function (block) was ever executed.
// No counters, no per-edge data.
// But for many use cases this is what we need and the added slowdown
// is negligible. This simple implementation will probably be obsoleted
// by the upcoming Clang-based coverage implementation.
// By having it here and now we hope to
// a) get the functionality to users earlier and
// b) collect usage statistics to help improve Clang coverage design.
bool AddressSanitizer::InjectCoverage(Function &F,
const ArrayRef<BasicBlock *> AllBlocks) {
if (!ClCoverage) return false;
if (ClCoverage == 1) {
InjectCoverageAtBlock(F, F.getEntryBlock());
} else {
for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
InjectCoverageAtBlock(F, *AllBlocks[i]);
}
return true;
}
bool AddressSanitizer::runOnFunction(Function &F) {
if (BL->isIn(F)) return false;
if (&F == AsanCtorFunction) return false;
if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
initializeCallbacks(*F.getParent());
// If needed, insert __asan_init before checking for SanitizeAddress attr.
maybeInsertAsanInitAtFunctionEntry(F);
if (!F.hasFnAttribute(Attribute::SanitizeAddress))
return false;
if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
return false;
// We want to instrument every address only once per basic block (unless there
// are calls between uses).
SmallSet<Value*, 16> TempsToInstrument;
SmallVector<Instruction*, 16> ToInstrument;
SmallVector<Instruction*, 8> NoReturnCalls;
SmallVector<BasicBlock*, 16> AllBlocks;
SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
int NumAllocas = 0;
bool IsWrite;
// Fill the set of memory operations to instrument.
for (Function::iterator FI = F.begin(), FE = F.end();
FI != FE; ++FI) {
AllBlocks.push_back(FI);
TempsToInstrument.clear();
int NumInsnsPerBB = 0;
for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
BI != BE; ++BI) {
if (LooksLikeCodeInBug11395(BI)) return false;
if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
if (ClOpt && ClOptSameTemp) {
if (!TempsToInstrument.insert(Addr))
continue; // We've seen this temp in the current BB.
}
} else if (ClInvalidPointerPairs &&
isInterestingPointerComparisonOrSubtraction(BI)) {
PointerComparisonsOrSubtracts.push_back(BI);
continue;
} else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
// ok, take it.
} else {
if (isa<AllocaInst>(BI))
NumAllocas++;
CallSite CS(BI);
if (CS) {
// A call inside BB.
TempsToInstrument.clear();
if (CS.doesNotReturn())
NoReturnCalls.push_back(CS.getInstruction());
}
continue;
}
ToInstrument.push_back(BI);
NumInsnsPerBB++;
if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
break;
}
}
Function *UninstrumentedDuplicate = 0;
bool LikelyToInstrument =
!NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
if (ClKeepUninstrumented && LikelyToInstrument) {
ValueToValueMapTy VMap;
UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
}
// Instrument.
int NumInstrumented = 0;
for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
Instruction *Inst = ToInstrument[i];
if (ClDebugMin < 0 || ClDebugMax < 0 ||
(NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
if (isInterestingMemoryAccess(Inst, &IsWrite))
instrumentMop(Inst);
else
instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
}
NumInstrumented++;
}
FunctionStackPoisoner FSP(F, *this);
bool ChangedStack = FSP.runOnFunction();
// We must unpoison the stack before every NoReturn call (throw, _exit, etc).
// See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
Instruction *CI = NoReturnCalls[i];
IRBuilder<> IRB(CI);
IRB.CreateCall(AsanHandleNoReturnFunc);
}
for (size_t i = 0, n = PointerComparisonsOrSubtracts.size(); i != n; i++) {
instrumentPointerComparisonOrSubtraction(PointerComparisonsOrSubtracts[i]);
NumInstrumented++;
}
bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
if (InjectCoverage(F, AllBlocks))
res = true;
DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
if (ClKeepUninstrumented) {
if (!res) {
// No instrumentation is done, no need for the duplicate.
if (UninstrumentedDuplicate)
UninstrumentedDuplicate->eraseFromParent();
} else {
// The function was instrumented. We must have the duplicate.
assert(UninstrumentedDuplicate);
UninstrumentedDuplicate->setSection("NOASAN");
assert(!F.hasSection());
F.setSection("ASAN");
}
}
return res;
}
// Workaround for bug 11395: we don't want to instrument stack in functions
// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
// FIXME: remove once the bug 11395 is fixed.
bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
if (LongSize != 32) return false;
CallInst *CI = dyn_cast<CallInst>(I);
if (!CI || !CI->isInlineAsm()) return false;
if (CI->getNumArgOperands() <= 5) return false;
// We have inline assembly with quite a few arguments.
return true;
}
void FunctionStackPoisoner::initializeCallbacks(Module &M) {
IRBuilder<> IRB(*C);
for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
std::string Suffix = itostr(i);
AsanStackMallocFunc[i] = checkInterfaceFunction(
M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
IntptrTy, IntptrTy, NULL));
AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
IntptrTy, IntptrTy, NULL));
}
AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
}
void
FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
IRBuilder<> &IRB, Value *ShadowBase,
bool DoPoison) {
size_t n = ShadowBytes.size();
size_t i = 0;
// We need to (un)poison n bytes of stack shadow. Poison as many as we can
// using 64-bit stores (if we are on 64-bit arch), then poison the rest
// with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
uint64_t Val = 0;
for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
if (ASan.DL->isLittleEndian())
Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
else
Val = (Val << 8) | ShadowBytes[i + j];
}
if (!Val) continue;
Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
}
}
}
// Fake stack allocator (asan_fake_stack.h) has 11 size classes
// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
static int StackMallocSizeClass(uint64_t LocalStackSize) {
assert(LocalStackSize <= kMaxStackMallocSize);
uint64_t MaxSize = kMinStackMallocSize;
for (int i = 0; ; i++, MaxSize *= 2)
if (LocalStackSize <= MaxSize)
return i;
llvm_unreachable("impossible LocalStackSize");
}
// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
// We can not use MemSet intrinsic because it may end up calling the actual
// memset. Size is a multiple of 8.
// Currently this generates 8-byte stores on x86_64; it may be better to
// generate wider stores.
void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
IRBuilder<> &IRB, Value *ShadowBase, int Size) {
assert(!(Size % 8));
assert(kAsanStackAfterReturnMagic == 0xf5);
for (int i = 0; i < Size; i += 8) {
Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
}
}
void FunctionStackPoisoner::poisonStack() {
int StackMallocIdx = -1;
assert(AllocaVec.size() > 0);
Instruction *InsBefore = AllocaVec[0];
IRBuilder<> IRB(InsBefore);
SmallVector<ASanStackVariableDescription, 16> SVD;
SVD.reserve(AllocaVec.size());
for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
AllocaInst *AI = AllocaVec[i];
ASanStackVariableDescription D = { AI->getName().data(),
getAllocaSizeInBytes(AI),
AI->getAlignment(), AI, 0};
SVD.push_back(D);
}
// Minimal header size (left redzone) is 4 pointers,
// i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
size_t MinHeaderSize = ASan.LongSize / 2;
ASanStackFrameLayout L;
ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
uint64_t LocalStackSize = L.FrameSize;
bool DoStackMalloc =
ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
AllocaInst *MyAlloca =
new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
assert((ClRealignStack & (ClRealignStack - 1)) == 0);
size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
MyAlloca->setAlignment(FrameAlignment);
assert(MyAlloca->isStaticAlloca());
Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
Value *LocalStackBase = OrigStackBase;
if (DoStackMalloc) {
// LocalStackBase = OrigStackBase
// if (__asan_option_detect_stack_use_after_return)
// LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
StackMallocIdx = StackMallocSizeClass(LocalStackSize);
assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
kAsanOptionDetectUAR, IRB.getInt32Ty());
Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
Constant::getNullValue(IRB.getInt32Ty()));
Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
IRBuilder<> IRBIf(Term);
LocalStackBase = IRBIf.CreateCall2(
AsanStackMallocFunc[StackMallocIdx],
ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
IRB.SetInsertPoint(InsBefore);
PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
Phi->addIncoming(OrigStackBase, CmpBlock);
Phi->addIncoming(LocalStackBase, SetBlock);
LocalStackBase = Phi;
}
// Insert poison calls for lifetime intrinsics for alloca.
bool HavePoisonedAllocas = false;
for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
assert(APC.InsBefore);
assert(APC.AI);
IRBuilder<> IRB(APC.InsBefore);
poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
HavePoisonedAllocas |= APC.DoPoison;
}
// Replace Alloca instructions with base+offset.
for (size_t i = 0, n = SVD.size(); i < n; i++) {
AllocaInst *AI = SVD[i].AI;
Value *NewAllocaPtr = IRB.CreateIntToPtr(
IRB.CreateAdd(LocalStackBase,
ConstantInt::get(IntptrTy, SVD[i].Offset)),
AI->getType());
replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
AI->replaceAllUsesWith(NewAllocaPtr);
}
// The left-most redzone has enough space for at least 4 pointers.
// Write the Magic value to redzone[0].
Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
BasePlus0);
// Write the frame description constant to redzone[1].
Value *BasePlus1 = IRB.CreateIntToPtr(
IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
IntptrPtrTy);
GlobalVariable *StackDescriptionGlobal =
createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
/*AllowMerging*/true);
Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
IntptrTy);
IRB.CreateStore(Description, BasePlus1);
// Write the PC to redzone[2].
Value *BasePlus2 = IRB.CreateIntToPtr(
IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
2 * ASan.LongSize/8)),
IntptrPtrTy);
IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
// Poison the stack redzones at the entry.
Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
// (Un)poison the stack before all ret instructions.
for (size_t i = 0, n = RetVec.size(); i < n; i++) {
Instruction *Ret = RetVec[i];
IRBuilder<> IRBRet(Ret);
// Mark the current frame as retired.
IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
BasePlus0);
if (DoStackMalloc) {
assert(StackMallocIdx >= 0);
// if LocalStackBase != OrigStackBase:
// // In use-after-return mode, poison the whole stack frame.
// if StackMallocIdx <= 4
// // For small sizes inline the whole thing:
// memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
// **SavedFlagPtr(LocalStackBase) = 0
// else
// __asan_stack_free_N(LocalStackBase, OrigStackBase)
// else
// <This is not a fake stack; unpoison the redzones>
Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
TerminatorInst *ThenTerm, *ElseTerm;
SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
IRBuilder<> IRBPoison(ThenTerm);
if (StackMallocIdx <= 4) {
int ClassSize = kMinStackMallocSize << StackMallocIdx;
SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
ClassSize >> Mapping.Scale);
Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
LocalStackBase,
ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
Value *SavedFlagPtr = IRBPoison.CreateLoad(
IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
IRBPoison.CreateStore(
Constant::getNullValue(IRBPoison.getInt8Ty()),
IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
} else {
// For larger frames call __asan_stack_free_*.
IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
ConstantInt::get(IntptrTy, LocalStackSize),
OrigStackBase);
}
IRBuilder<> IRBElse(ElseTerm);
poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
} else if (HavePoisonedAllocas) {
// If we poisoned some allocas in llvm.lifetime analysis,
// unpoison whole stack frame now.
assert(LocalStackBase == OrigStackBase);
poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
} else {
poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
}
}
// We are done. Remove the old unused alloca instructions.
for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
AllocaVec[i]->eraseFromParent();
}
void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
IRBuilder<> &IRB, bool DoPoison) {
// For now just insert the call to ASan runtime.
Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
Value *SizeArg = ConstantInt::get(IntptrTy, Size);
IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
: AsanUnpoisonStackMemoryFunc,
AddrArg, SizeArg);
}
// Handling llvm.lifetime intrinsics for a given %alloca:
// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
// could be poisoned by previous llvm.lifetime.end instruction, as the
// variable may go in and out of scope several times, e.g. in loops).
// (3) if we poisoned at least one %alloca in a function,
// unpoison the whole stack frame at function exit.
AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
// We're intested only in allocas we can handle.
return isInterestingAlloca(*AI) ? AI : 0;
// See if we've already calculated (or started to calculate) alloca for a
// given value.
AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
if (I != AllocaForValue.end())
return I->second;
// Store 0 while we're calculating alloca for value V to avoid
// infinite recursion if the value references itself.
AllocaForValue[V] = 0;
AllocaInst *Res = 0;
if (CastInst *CI = dyn_cast<CastInst>(V))
Res = findAllocaForValue(CI->getOperand(0));
else if (PHINode *PN = dyn_cast<PHINode>(V)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *IncValue = PN->getIncomingValue(i);
// Allow self-referencing phi-nodes.
if (IncValue == PN) continue;
AllocaInst *IncValueAI = findAllocaForValue(IncValue);
// AI for incoming values should exist and should all be equal.
if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
return 0;
Res = IncValueAI;
}
}
if (Res != 0)
AllocaForValue[V] = Res;
return Res;
}
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dlg_InsertDataLabel.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-10-22 16:50:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#ifndef CHART2_DLG_INSERT_DATALABELS_GRID_HXX
#define CHART2_DLG_INSERT_DATALABELS_GRID_HXX
// header for class ModalDialog
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
// header for class CheckBox
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
// header for class SfxItemSet
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
//for auto_ptr
#include <memory>
class SvNumberFormatter;
//.............................................................................
namespace chart
{
//.............................................................................
class DataLabelResources;
class DataLabelsDialog : public ModalDialog
{
private:
OKButton m_aBtnOK;
CancelButton m_aBtnCancel;
HelpButton m_aBtnHelp;
::std::auto_ptr< DataLabelResources > m_apDataLabelResources;
const SfxItemSet& m_rInAttrs;
void Reset();
public:
DataLabelsDialog(Window* pParent, const SfxItemSet& rInAttrs, SvNumberFormatter* pFormatter);
virtual ~DataLabelsDialog();
void FillItemSet(SfxItemSet& rOutAttrs);
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
INTEGRATION: CWS changefileheader (1.5.66); FILE MERGED
2008/04/01 15:04:08 thb 1.5.66.2: #i85898# Stripping all external header guards
2008/03/28 16:43:46 rt 1.5.66.1: #i87441# Change license header to LPGL v3.
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dlg_InsertDataLabel.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CHART2_DLG_INSERT_DATALABELS_GRID_HXX
#define CHART2_DLG_INSERT_DATALABELS_GRID_HXX
// header for class ModalDialog
#include <vcl/dialog.hxx>
// header for class CheckBox
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
// header for class SfxItemSet
#include <svtools/itemset.hxx>
//for auto_ptr
#include <memory>
class SvNumberFormatter;
//.............................................................................
namespace chart
{
//.............................................................................
class DataLabelResources;
class DataLabelsDialog : public ModalDialog
{
private:
OKButton m_aBtnOK;
CancelButton m_aBtnCancel;
HelpButton m_aBtnHelp;
::std::auto_ptr< DataLabelResources > m_apDataLabelResources;
const SfxItemSet& m_rInAttrs;
void Reset();
public:
DataLabelsDialog(Window* pParent, const SfxItemSet& rInAttrs, SvNumberFormatter* pFormatter);
virtual ~DataLabelsDialog();
void FillItemSet(SfxItemSet& rOutAttrs);
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
|
// Copyright (c) 2010 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 "chrome/browser/chromeos/cros/input_method_library.h"
#include <glib.h>
#include <signal.h>
#include "unicode/uloc.h"
#include "base/basictypes.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/keyboard_library.h"
#include "chrome/browser/chromeos/input_method/candidate_window.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/chromeos/language_preferences.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "content/browser/browser_thread.h"
namespace {
const char kIBusDaemonPath[] = "/usr/bin/ibus-daemon";
// Finds a property which has |new_prop.key| from |prop_list|, and replaces the
// property with |new_prop|. Returns true if such a property is found.
bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
chromeos::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
// Update the list except the radio id. As written in
// chromeos_input_method.h, |prop.selection_item_id| is dummy.
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
} // namespace
namespace chromeos {
// The production implementation of InputMethodLibrary.
class InputMethodLibraryImpl : public InputMethodLibrary,
public NotificationObserver {
public:
InputMethodLibraryImpl()
: input_method_status_connection_(NULL),
previous_input_method_("", "", "", ""),
current_input_method_("", "", "", ""),
should_launch_ime_(false),
ime_connected_(false),
defer_ime_startup_(false),
enable_auto_ime_shutdown_(true),
should_change_input_method_(false),
ibus_daemon_process_id_(0),
initialized_successfully_(false),
candidate_window_controller_(NULL) {
// Here, we use the fallback input method descriptor but
// |current_input_method_| will be updated as soon as the login screen
// is shown or the user is logged in, so there is no problem.
current_input_method_ = input_method::GetFallbackInputMethodDescriptor();
active_input_method_ids_.push_back(current_input_method_.id);
// Observe APP_TERMINATING to stop input method daemon gracefully.
// We should not use APP_EXITING here since logout might be canceled by
// JavaScript after APP_EXITING is sent (crosbug.com/11055).
// Note that even if we fail to stop input method daemon from
// Chrome in case of a sudden crash, we have a way to do it from an
// upstart script. See crosbug.com/6515 and crosbug.com/6995 for
// details.
notification_registrar_.Add(this, NotificationType::APP_TERMINATING,
NotificationService::AllSources());
}
// Initializes the object. On success, returns true on and sets
// initialized_successfully_ to true.
//
// Note that we start monitoring input method status in here in Init()
// to avoid a potential race. If we start the monitoring right after
// starting ibus-daemon, there is a higher chance of a race between
// Chrome and ibus-daemon to occur.
bool Init() {
DCHECK(!initialized_successfully_) << "Already initialized";
if (!CrosLibrary::Get()->EnsureLoaded())
return false;
input_method_status_connection_ = chromeos::MonitorInputMethodStatus(
this,
&InputMethodChangedHandler,
&RegisterPropertiesHandler,
&UpdatePropertyHandler,
&ConnectionChangeHandler);
if (!input_method_status_connection_)
return false;
initialized_successfully_ = true;
return true;
}
virtual ~InputMethodLibraryImpl() {
}
virtual void AddObserver(Observer* observer) {
if (!observers_.size()) {
observer->FirstObserverIsAdded(this);
}
observers_.AddObserver(observer);
}
virtual void RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
virtual InputMethodDescriptors* GetActiveInputMethods() {
chromeos::InputMethodDescriptors* result =
new chromeos::InputMethodDescriptors;
// Build the active input method descriptors from the active input
// methods cache |active_input_method_ids_|.
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
// This shouldn't happen as there should be at least one active input
// method, but just in case.
if (result->empty()) {
LOG(ERROR) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
return input_methods->size();
}
virtual InputMethodDescriptors* GetSupportedInputMethods() {
if (!initialized_successfully_) {
// If initialization was failed, return the fallback input method,
// as this function is guaranteed to return at least one descriptor.
InputMethodDescriptors* result = new InputMethodDescriptors;
result->push_back(input_method::GetFallbackInputMethodDescriptor());
return result;
}
// This never returns NULL.
return chromeos::GetSupportedInputMethodDescriptors();
}
virtual void ChangeInputMethod(const std::string& input_method_id) {
// If the input method daemon is not running and the specified input
// method is a keyboard layout, switch the keyboard directly.
if (ibus_daemon_process_id_ == 0 &&
chromeos::input_method::IsKeyboardLayout(input_method_id)) {
// We shouldn't use SetCurrentKeyboardLayoutByName() here. See
// comments at ChangeCurrentInputMethod() for details.
ChangeCurrentInputMethodFromId(input_method_id);
} else {
// Otherwise, start the input method daemon, and change the input
// method via the damon.
StartInputMethodDaemon();
// ChangeInputMethodViaIBus() fails if the IBus daemon is not
// ready yet. In this case, we'll defer the input method change
// until the daemon is ready.
if (!ChangeInputMethodViaIBus(input_method_id)) {
pending_input_method_id_ = input_method_id;
}
}
}
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {
if (!initialized_successfully_)
return;
DCHECK(!key.empty());
chromeos::SetImePropertyActivated(
input_method_status_connection_, key.c_str(), activated);
}
virtual bool InputMethodIsActivated(const std::string& input_method_id) {
scoped_ptr<InputMethodDescriptors> active_input_method_descriptors(
GetActiveInputMethods());
for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) {
if (active_input_method_descriptors->at(i).id == input_method_id) {
return true;
}
}
return false;
}
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
// If the config change is for preload engines, update the active
// input methods cache |active_input_method_ids_| here. We need to
// update the cache before actually flushing the config. since we need
// to return active input methods from GetActiveInputMethods() before
// the input method daemon starts. For instance, we need to show the
// list of available input methods (keyboard layouts) on the login
// screen before the input method starts.
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == ImeConfigValue::kValueTypeStringList) {
active_input_method_ids_ = value.string_list_value;
}
// Before calling FlushImeConfig(), start input method process if necessary.
MaybeStartInputMethodDaemon(section, config_name, value);
const ConfigKeyType key = std::make_pair(section, config_name);
current_config_values_[key] = value;
if (ime_connected_) {
pending_config_requests_[key] = value;
FlushImeConfig();
}
// Stop input method process if necessary.
MaybeStopInputMethodDaemon(section, config_name, value);
// Change the current keyboard layout if necessary.
MaybeChangeCurrentKeyboardLayout(section, config_name, value);
return pending_config_requests_.empty();
}
virtual const InputMethodDescriptor& previous_input_method() const {
return previous_input_method_;
}
virtual const InputMethodDescriptor& current_input_method() const {
return current_input_method_;
}
virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return chromeos::GetKeyboardOverlayId(input_method_id);
}
private:
// Returns true if the given input method config value is a single
// element string list that contains an input method ID of a keyboard
// layout.
bool ContainOnlyOneKeyboardLayout(
const ImeConfigValue& value) {
return (value.type == ImeConfigValue::kValueTypeStringList &&
value.string_list_value.size() == 1 &&
chromeos::input_method::IsKeyboardLayout(
value.string_list_value[0]));
}
// Starts input method daemon based on the |defer_ime_startup_| flag and
// input method configuration being updated. |section| is a section name of
// the input method configuration (e.g. "general", "general/hotkey").
// |config_name| is a name of the configuration (e.g. "preload_engines",
// "previous_engine"). |value| is the configuration value to be set.
void MaybeStartInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName) {
// If there is only one input method which is a keyboard layout,
// we don't start the input method processes. When
// |defer_ime_startup_| is true, we don't start it either.
if (ContainOnlyOneKeyboardLayout(value) ||
defer_ime_startup_) {
// Do not start the input method daemon.
} else {
// Otherwise, start the input method daemon.
StartInputMethodDaemon();
}
}
}
// Stops input method daemon based on the |enable_auto_ime_shutdown_| flag
// and input method configuration being updated.
// See also: MaybeStartInputMethodDaemon().
void MaybeStopInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
// If there is only one input method which is a keyboard layout,
// and |enable_auto_ime_shutdown_| is true, we'll stop the input
// method daemon.
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value) &&
enable_auto_ime_shutdown_) {
StopInputMethodDaemon();
}
}
// Change the keyboard layout per input method configuration being
// updated, if necessary. See also: MaybeStartInputMethodDaemon().
void MaybeChangeCurrentKeyboardLayout(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
// If there is only one input method which is a keyboard layout, we'll
// change the keyboard layout per the only one input method now
// available.
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value)) {
// We shouldn't use SetCurrentKeyboardLayoutByName() here. See
// comments at ChangeCurrentInputMethod() for details.
ChangeCurrentInputMethodFromId(value.string_list_value[0]);
}
}
// Changes the current input method to |input_method_id| via IBus
// daemon. If the id is not in the preload_engine list, this function
// changes the current method to the first preloaded engine. Returns
// true if the current engine is switched to |input_method_id| or the
// first one.
bool ChangeInputMethodViaIBus(const std::string& input_method_id) {
if (!initialized_successfully_)
return false;
std::string input_method_id_to_switch = input_method_id;
if (!InputMethodIsActivated(input_method_id)) {
// This path might be taken if prefs::kLanguageCurrentInputMethod (NOT
// synced with cloud) and kLanguagePreloadEngines (synced with cloud) are
// mismatched. e.g. the former is 'xkb:us::eng' and the latter (on the
// sync server) is 'xkb:jp::jpn,mozc'.
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
DCHECK(!input_methods->empty());
if (!input_methods->empty()) {
input_method_id_to_switch = input_methods->at(0).id;
LOG(INFO) << "Can't change the current input method to "
<< input_method_id << " since the engine is not preloaded. "
<< "Switch to " << input_method_id_to_switch << " instead.";
}
}
if (chromeos::ChangeInputMethod(input_method_status_connection_,
input_method_id_to_switch.c_str())) {
return true;
}
// ChangeInputMethod() fails if the IBus daemon is not yet ready.
LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch;
return false;
}
// Flushes the input method config data. The config data is queued up in
// |pending_config_requests_| until the config backend (ibus-memconf)
// starts.
void FlushImeConfig() {
if (!initialized_successfully_)
return;
bool active_input_methods_are_changed = false;
InputMethodConfigRequests::iterator iter =
pending_config_requests_.begin();
while (iter != pending_config_requests_.end()) {
const std::string& section = iter->first.first;
const std::string& config_name = iter->first.second;
const ImeConfigValue& value = iter->second;
if (chromeos::SetImeConfig(input_method_status_connection_,
section.c_str(),
config_name.c_str(),
value)) {
// Check if it's a change in active input methods.
if (config_name == language_prefs::kPreloadEnginesConfigName) {
active_input_methods_are_changed = true;
VLOG(1) << "Updated preload_engines: " << value.ToString();
}
// Successfully sent. Remove the command and proceed to the next one.
pending_config_requests_.erase(iter++);
} else {
// If SetImeConfig() fails, subsequent calls will likely fail.
break;
}
}
if (pending_config_requests_.empty()) {
// Calls to ChangeInputMethod() will fail if the input method has not
// yet been added to preload_engines. As such, the call is deferred
// until after all config values have been sent to the IME process.
if (should_change_input_method_ && !pending_input_method_id_.empty()) {
ChangeInputMethodViaIBus(pending_input_method_id_);
pending_input_method_id_ = "";
should_change_input_method_ = false;
active_input_methods_are_changed = true;
}
}
// Notify the current input method and the number of active input methods to
// the UI so that the UI could determine e.g. if it should show/hide the
// input method indicator, etc. We have to call FOR_EACH_OBSERVER here since
// updating "preload_engine" does not necessarily trigger a DBus signal such
// as "global-engine-changed". For example,
// 1) If we change the preload_engine from "xkb:us:intl:eng" (i.e. the
// indicator is hidden) to "xkb:us:intl:eng,mozc", we have to update UI
// so it shows the indicator, but no signal is sent from ibus-daemon
// because the current input method is not changed.
// 2) If we change the preload_engine from "xkb:us::eng,mozc" (i.e. the
// indicator is shown and ibus-daemon is started) to "xkb:us::eng", we
// have to update UI so it hides the indicator, but we should not expect
// that ibus-daemon could send a DBus signal since the daemon is killed
// right after this FlushImeConfig() call.
if (active_input_methods_are_changed) {
// The |current_input_method_| member might be stale here as
// SetImeConfig("preload_engine") call above might change the
// current input method in ibus-daemon (ex. this occurs when the
// input method currently in use is removed from the options
// page). However, it should be safe to use the member here,
// for the following reasons:
// 1. If ibus-daemon is to be killed, we'll switch to the only one
// keyboard layout, and observers are notified. See
// MaybeStopInputMethodDaemon() for details.
// 2. Otherwise, "global-engine-changed" signal is delivered from
// ibus-daemon, and observers are notified. See
// InputMethodChangedHandler() for details.
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(Observer, observers_,
ActiveInputMethodsChanged(this,
current_input_method_,
num_active_input_methods));
}
}
// Called when the input method is changed in the IBus daemon
// (ex. "global-engine-changed" is delivered from the IBus daemon).
static void InputMethodChangedHandler(
void* object,
const chromeos::InputMethodDescriptor& current_input_method) {
// The handler is called when the input method method change is
// notified via a DBus connection. Since the DBus notificatiosn are
// handled in the UI thread, we can assume that this function always
// runs on the UI thread, but just in case.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ChangeCurrentInputMethod(current_input_method);
}
// Called when properties are registered in the IBus daemon.
static void RegisterPropertiesHandler(
void* object, const ImePropertyList& prop_list) {
// See comments in InputMethodChangedHandler.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->RegisterProperties(prop_list);
}
// Called when properties are updated in the IBus daemon.
static void UpdatePropertyHandler(
void* object, const ImePropertyList& prop_list) {
// See comments in InputMethodChangedHandler.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->UpdateProperty(prop_list);
}
// Called when 1) connection to ibus-daemon and ibus-memconf are established
// or 2) connection to ibus-daemon is terminated.
static void ConnectionChangeHandler(void* object, bool connected) {
// See comments in InputMethodChangedHandler.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ime_connected_ = connected;
if (connected) {
input_method_library->pending_config_requests_.clear();
input_method_library->pending_config_requests_.insert(
input_method_library->current_config_values_.begin(),
input_method_library->current_config_values_.end());
input_method_library->should_change_input_method_ = true;
input_method_library->FlushImeConfig();
}
}
// Changes the current input method from the given input method
// descriptor. This function updates states like current_input_method_
// and notifies observers about the change (that will update the
// preferences), hence this function should always be used even if you
// just need to change the current keyboard layout.
void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) {
if (current_input_method_.id != new_input_method.id) {
previous_input_method_ = current_input_method_;
current_input_method_ = new_input_method;
// Change the keyboard layout to a preferred layout for the input method.
if (!CrosLibrary::Get()->GetKeyboardLibrary()->
SetCurrentKeyboardLayoutByName(
current_input_method_.keyboard_layout)) {
LOG(ERROR) << "Failed to change keyboard layout to "
<< current_input_method_.keyboard_layout;
}
// Ask the first observer to update preferences. We should not ask every
// observer to do so. Otherwise, we'll end up updating preferences many
// times when many observers are attached (ex. many windows are opened),
// which is unnecessary and expensive.
ObserverListBase<Observer>::Iterator it(observers_);
Observer* first_observer = it.GetNext();
if (first_observer) {
first_observer->PreferenceUpdateNeeded(this,
previous_input_method_,
current_input_method_);
}
}
// Update input method indicators (e.g. "US", "DV") in Chrome windows.
// For now, we have to do this every time to keep indicators updated. See
// comments near the FOR_EACH_OBSERVER call in FlushImeConfig() for details.
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(Observer, observers_,
InputMethodChanged(this,
current_input_method_,
num_active_input_methods));
}
// Changes the current input method from the given input method ID.
// This function is just a wrapper of ChangeCurrentInputMethod().
void ChangeCurrentInputMethodFromId(const std::string& input_method_id) {
const chromeos::InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
ChangeCurrentInputMethod(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
// Registers the properties used by the current input method.
void RegisterProperties(const ImePropertyList& prop_list) {
// |prop_list| might be empty. This means "clear all properties."
current_ime_properties_ = prop_list;
}
// Starts the input method daemon. Unlike MaybeStopInputMethodDaemon(),
// this function always starts the daemon.
void StartInputMethodDaemon() {
should_launch_ime_ = true;
MaybeLaunchInputMethodDaemon();
}
// Updates the properties used by the current input method.
void UpdateProperty(const ImePropertyList& prop_list) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
}
// Launches an input method procsess specified by the given command
// line. On success, returns true and stores the process ID in
// |process_id|. Otherwise, returns false, and the contents of
// |process_id| is untouched. OnImeShutdown will be called when the
// process terminates.
bool LaunchInputMethodProcess(const std::string& command_line,
int* process_id) {
GError *error = NULL;
gchar **argv = NULL;
gint argc = NULL;
// TODO(zork): export "LD_PRELOAD=/usr/lib/libcrash.so"
if (!g_shell_parse_argv(command_line.c_str(), &argc, &argv, &error)) {
LOG(ERROR) << "Could not parse command: " << error->message;
g_error_free(error);
return false;
}
int pid = 0;
const GSpawnFlags kFlags = G_SPAWN_DO_NOT_REAP_CHILD;
const gboolean result = g_spawn_async(NULL, argv, NULL,
kFlags, NULL, NULL,
&pid, &error);
g_strfreev(argv);
if (!result) {
LOG(ERROR) << "Could not launch: " << command_line << ": "
<< error->message;
g_error_free(error);
return false;
}
g_child_watch_add(pid, reinterpret_cast<GChildWatchFunc>(OnImeShutdown),
this);
*process_id = pid;
VLOG(1) << command_line << " (PID=" << pid << ") is started";
return true;
}
// Launches input method daemon if these are not yet running.
void MaybeLaunchInputMethodDaemon() {
// CandidateWindowController requires libcros to be loaded. Besides,
// launching ibus-daemon without libcros loaded doesn't make sense.
if (!initialized_successfully_)
return;
if (!should_launch_ime_) {
return;
}
if (!candidate_window_controller_.get()) {
candidate_window_controller_.reset(new CandidateWindowController);
if (!candidate_window_controller_->Init()) {
LOG(WARNING) << "Failed to initialize the candidate window controller";
}
}
if (ibus_daemon_process_id_ == 0) {
// TODO(zork): Send output to /var/log/ibus.log
const std::string ibus_daemon_command_line =
StringPrintf("%s --panel=disable --cache=none --restart --replace",
kIBusDaemonPath);
if (!LaunchInputMethodProcess(
ibus_daemon_command_line, &ibus_daemon_process_id_)) {
LOG(ERROR) << "Failed to launch " << ibus_daemon_command_line;
}
}
}
// Called when the input method process is shut down.
static void OnImeShutdown(int pid,
int status,
InputMethodLibraryImpl* library) {
g_spawn_close_pid(pid);
if (library->ibus_daemon_process_id_ == pid) {
library->ibus_daemon_process_id_ = 0;
}
// Restart input method daemon if needed.
library->MaybeLaunchInputMethodDaemon();
}
// Stops the backend input method daemon. This function should also be
// called from MaybeStopInputMethodDaemon(), except one case where we
// stop the input method daemon at Chrome shutdown in Observe().
void StopInputMethodDaemon() {
if (!initialized_successfully_)
return;
should_launch_ime_ = false;
if (ibus_daemon_process_id_) {
if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) {
LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to "
<< "PID " << ibus_daemon_process_id_;
kill(ibus_daemon_process_id_, SIGTERM);
}
VLOG(1) << "ibus-daemon (PID=" << ibus_daemon_process_id_ << ") is "
<< "terminated";
ibus_daemon_process_id_ = 0;
}
}
void SetDeferImeStartup(bool defer) {
VLOG(1) << "Setting DeferImeStartup to " << defer;
defer_ime_startup_ = defer;
}
void SetEnableAutoImeShutdown(bool enable) {
enable_auto_ime_shutdown_ = enable;
}
// NotificationObserver implementation:
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
// Stop the input method daemon on browser shutdown.
if (type.value == NotificationType::APP_TERMINATING) {
notification_registrar_.RemoveAll();
StopInputMethodDaemon();
}
}
// A reference to the language api, to allow callbacks when the input method
// status changes.
InputMethodStatusConnection* input_method_status_connection_;
ObserverList<Observer> observers_;
// The input method which was/is selected.
InputMethodDescriptor previous_input_method_;
InputMethodDescriptor current_input_method_;
// The input method properties which the current input method uses. The list
// might be empty when no input method is used.
ImePropertyList current_ime_properties_;
typedef std::pair<std::string, std::string> ConfigKeyType;
typedef std::map<ConfigKeyType, ImeConfigValue> InputMethodConfigRequests;
// SetImeConfig requests that are not yet completed.
// Use a map to queue config requests, so we only send the last request for
// the same config key (i.e. we'll discard ealier requests for the same
// config key). As we discard old requests for the same config key, the order
// of requests doesn't matter, so it's safe to use a map.
InputMethodConfigRequests pending_config_requests_;
// Values that have been set via SetImeConfig(). We keep a copy available to
// resend if the ime restarts and loses its state.
InputMethodConfigRequests current_config_values_;
// This is used to register this object to APP_EXITING notification.
NotificationRegistrar notification_registrar_;
// True if we should launch the input method daemon.
bool should_launch_ime_;
// True if the connection to the IBus daemon is alive.
bool ime_connected_;
// If true, we'll defer the startup until a non-default method is
// activated.
bool defer_ime_startup_;
// True if we should stop input method daemon when there are no input
// methods other than one for the hardware keyboard.
bool enable_auto_ime_shutdown_;
// The ID of the pending input method (ex. "mozc"). When we change the
// current input method via the IBus daemon, we use this variable to
// defer the operation until the IBus daemon becomes ready, as needed.
std::string pending_input_method_id_;
// True if we should change the current input method to
// |pending_input_method_id_| once the queue of the pending config
// requests becomes empty.
bool should_change_input_method_;
// The process id of the IBus daemon. 0 if it's not running. The process
// ID 0 is not used in Linux, hence it's safe to use 0 for this purpose.
int ibus_daemon_process_id_;
// True if initialization is successfully done, meaning that libcros is
// loaded and input method status monitoring is started. This value
// should be checked where we call libcros functions.
bool initialized_successfully_;
// The candidate window.
scoped_ptr<CandidateWindowController> candidate_window_controller_;
// The active input method ids cache.
std::vector<std::string> active_input_method_ids_;
DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryImpl);
};
InputMethodLibraryImpl::Observer::~Observer() {}
// The stub implementation of InputMethodLibrary. Used for testing.
class InputMethodLibraryStubImpl : public InputMethodLibrary {
public:
InputMethodLibraryStubImpl()
: previous_input_method_("", "", "", ""),
current_input_method_("", "", "", ""),
keyboard_overlay_map_(
GetKeyboardOverlayMapForTesting()) {
current_input_method_ = input_method::GetFallbackInputMethodDescriptor();
}
virtual ~InputMethodLibraryStubImpl() {}
virtual void AddObserver(Observer* observer) {}
virtual void RemoveObserver(Observer* observer) {}
virtual InputMethodDescriptors* GetActiveInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods());
return descriptors->size();
}
virtual InputMethodDescriptors* GetSupportedInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
virtual void ChangeInputMethod(const std::string& input_method_id) {}
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {}
virtual bool InputMethodIsActivated(const std::string& input_method_id) {
return true;
}
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
return false;
}
virtual const InputMethodDescriptor& previous_input_method() const {
return previous_input_method_;
}
virtual const InputMethodDescriptor& current_input_method() const {
return current_input_method_;
}
virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
virtual void StartInputMethodDaemon() {}
virtual void StopInputMethodDaemon() {}
virtual void SetDeferImeStartup(bool defer) {}
virtual void SetEnableAutoImeShutdown(bool enable) {}
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
KeyboardOverlayMap::const_iterator iter =
keyboard_overlay_map_->find(input_method_id);
return (iter != keyboard_overlay_map_->end()) ?
iter->second : "";
}
private:
typedef std::map<std::string, std::string> KeyboardOverlayMap;
// Gets input method descriptors for testing. Shouldn't be used for
// production.
InputMethodDescriptors* GetInputMethodDescriptorsForTesting() {
InputMethodDescriptors* descriptions = new InputMethodDescriptors;
// The list is created from output of gen_engines.py in libcros.
// % SHARE=/build/x86-generic/usr/share python gen_engines.py
// $SHARE/chromeos-assets/input_methods/whitelist.txt
// $SHARE/ibus/component/{chewing,hangul,m17n,mozc,pinyin,xkb-layouts}.xml
descriptions->push_back(InputMethodDescriptor(
"xkb:nl::nld", "Netherlands", "nl", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::nld", "Belgium", "be", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fr::fra", "France", "fr", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::fra", "Belgium", "be", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca::fra", "Canada", "ca", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de::ger", "Germany", "de", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::ger", "Belgium", "be", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch::ger", "Switzerland", "ch", "ger"));
descriptions->push_back(InputMethodDescriptor(
"mozc", "Mozc (US keyboard layout)", "us", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-dv", "Mozc (US Dvorak keyboard layout)", "us(dvorak)", "ja"));
descriptions->push_back(InputMethodDescriptor(
"xkb:jp::jpn", "Japan", "jp", "jpn"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru::rus", "Russia", "ru", "rus"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru:phonetic:rus", "Russia - Phonetic", "ru(phonetic)", "rus"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:kesmanee", "kesmanee (m17n)", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:pattachote", "pattachote (m17n)", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:tis820", "tis820 (m17n)", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"chewing", "Chewing", "us", "zh_TW"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:cangjie", "cangjie (m17n)", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:quick", "quick (m17n)", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:tcvn", "tcvn (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:telex", "telex (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:viqr", "viqr (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:vni", "vni (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us::eng", "USA", "us", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:intl:eng",
"USA - International (with dead keys)", "us(intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:altgr-intl:eng",
"USA - International (AltGr dead keys)", "us(altgr-intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:dvorak:eng", "USA - Dvorak", "us(dvorak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:colemak:eng", "USA - Colemak", "us(colemak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"hangul", "Korean", "kr(kr104)", "ko"));
descriptions->push_back(InputMethodDescriptor(
"pinyin", "Pinyin", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:ar:kbd", "kbd (m17n)", "us", "ar"));
descriptions->push_back(InputMethodDescriptor(
"m17n:hi:itrans", "itrans (m17n)", "us", "hi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:fa:isiri", "isiri (m17n)", "us", "fa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:br::por", "Brazil", "br", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg::bul", "Bulgaria", "bg", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg:phonetic:bul",
"Bulgaria - Traditional phonetic", "bg(phonetic)", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca:eng:eng", "Canada - English", "ca(eng)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:cz::cze", "Czechia", "cz", "cze"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ee::est", "Estonia", "ee", "est"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es::spa", "Spain", "es", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es:cat:cat",
"Spain - Catalan variant with middle-dot L", "es(cat)", "cat"));
descriptions->push_back(InputMethodDescriptor(
"xkb:dk::dan", "Denmark", "dk", "dan"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gr::gre", "Greece", "gr", "gre"));
descriptions->push_back(InputMethodDescriptor(
"xkb:il::heb", "Israel", "il", "heb"));
descriptions->push_back(InputMethodDescriptor(
"xkb:kr:kr104:kor",
"Korea, Republic of - 101/104 key Compatible", "kr(kr104)", "kor"));
descriptions->push_back(InputMethodDescriptor(
"xkb:latam::spa", "Latin American", "latam", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lt::lit", "Lithuania", "lt", "lit"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lv:apostrophe:lav",
"Latvia - Apostrophe (') variant", "lv(apostrophe)", "lav"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hr::scr", "Croatia", "hr", "scr"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gb:extd:eng",
"United Kingdom - Extended - Winkeys", "gb(extd)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fi::fin", "Finland", "fi", "fin"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hu::hun", "Hungary", "hu", "hun"));
descriptions->push_back(InputMethodDescriptor(
"xkb:it::ita", "Italy", "it", "ita"));
descriptions->push_back(InputMethodDescriptor(
"xkb:no::nob", "Norway", "no", "nob"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pl::pol", "Poland", "pl", "pol"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pt::por", "Portugal", "pt", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ro::rum", "Romania", "ro", "rum"));
descriptions->push_back(InputMethodDescriptor(
"xkb:se::swe", "Sweden", "se", "swe"));
descriptions->push_back(InputMethodDescriptor(
"xkb:sk::slo", "Slovakia", "sk", "slo"));
descriptions->push_back(InputMethodDescriptor(
"xkb:si::slv", "Slovenia", "si", "slv"));
descriptions->push_back(InputMethodDescriptor(
"xkb:rs::srp", "Serbia", "rs", "srp"));
descriptions->push_back(InputMethodDescriptor(
"xkb:tr::tur", "Turkey", "tr", "tur"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ua::ukr", "Ukraine", "ua", "ukr"));
return descriptions;
}
// Gets keyboard overlay map for testing. Shouldn't be used for
// production.
std::map<std::string, std::string>* GetKeyboardOverlayMapForTesting() {
KeyboardOverlayMap* keyboard_overlay_map =
new KeyboardOverlayMap;
(*keyboard_overlay_map)["xkb:nl::nld"] = "nl";
(*keyboard_overlay_map)["xkb:be::nld"] = "nl";
(*keyboard_overlay_map)["xkb:fr::fra"] = "fr";
(*keyboard_overlay_map)["xkb:be::fra"] = "fr";
(*keyboard_overlay_map)["xkb:ca::fra"] = "fr_CA";
(*keyboard_overlay_map)["xkb:ch:fr:fra"] = "fr";
(*keyboard_overlay_map)["xkb:de::ger"] = "de";
(*keyboard_overlay_map)["xkb:be::ger"] = "de";
(*keyboard_overlay_map)["xkb:ch::ger"] = "de";
(*keyboard_overlay_map)["mozc"] = "en_US";
(*keyboard_overlay_map)["mozc-jp"] = "ja";
(*keyboard_overlay_map)["mozc-dv"] = "en_US_dvorak";
(*keyboard_overlay_map)["xkb:jp::jpn"] = "ja";
(*keyboard_overlay_map)["xkb:ru::rus"] = "ru";
(*keyboard_overlay_map)["xkb:ru:phonetic:rus"] = "ru";
(*keyboard_overlay_map)["m17n:th:kesmanee"] = "th";
(*keyboard_overlay_map)["m17n:th:pattachote"] = "th";
(*keyboard_overlay_map)["m17n:th:tis820"] = "th";
(*keyboard_overlay_map)["chewing"] = "zh_TW";
(*keyboard_overlay_map)["m17n:zh:cangjie"] = "zh_TW";
(*keyboard_overlay_map)["m17n:zh:quick"] = "zh_TW";
(*keyboard_overlay_map)["m17n:vi:tcvn"] = "vi";
(*keyboard_overlay_map)["m17n:vi:telex"] = "vi";
(*keyboard_overlay_map)["m17n:vi:viqr"] = "vi";
(*keyboard_overlay_map)["m17n:vi:vni"] = "vi";
(*keyboard_overlay_map)["xkb:us::eng"] = "en_US";
(*keyboard_overlay_map)["xkb:us:intl:eng"] = "en_US";
(*keyboard_overlay_map)["xkb:us:altgr-intl:eng"] = "en_US";
(*keyboard_overlay_map)["xkb:us:dvorak:eng"] =
"en_US_dvorak";
(*keyboard_overlay_map)["xkb:us:colemak:eng"] =
"en_US";
(*keyboard_overlay_map)["hangul"] = "ko";
(*keyboard_overlay_map)["pinyin"] = "zh_CN";
(*keyboard_overlay_map)["m17n:ar:kbd"] = "ar";
(*keyboard_overlay_map)["m17n:hi:itrans"] = "hi";
(*keyboard_overlay_map)["m17n:fa:isiri"] = "ar";
(*keyboard_overlay_map)["xkb:br::por"] = "pt_BR";
(*keyboard_overlay_map)["xkb:bg::bul"] = "bg";
(*keyboard_overlay_map)["xkb:bg:phonetic:bul"] = "bg";
(*keyboard_overlay_map)["xkb:ca:eng:eng"] = "ca";
(*keyboard_overlay_map)["xkb:cz::cze"] = "cs";
(*keyboard_overlay_map)["xkb:ee::est"] = "et";
(*keyboard_overlay_map)["xkb:es::spa"] = "es";
(*keyboard_overlay_map)["xkb:es:cat:cat"] = "ca";
(*keyboard_overlay_map)["xkb:dk::dan"] = "da";
(*keyboard_overlay_map)["xkb:gr::gre"] = "el";
(*keyboard_overlay_map)["xkb:il::heb"] = "iw";
(*keyboard_overlay_map)["xkb:kr:kr104:kor"] = "ko";
(*keyboard_overlay_map)["xkb:latam::spa"] = "es_419";
(*keyboard_overlay_map)["xkb:lt::lit"] = "lt";
(*keyboard_overlay_map)["xkb:lv:apostrophe:lav"] = "lv";
(*keyboard_overlay_map)["xkb:hr::scr"] = "hr";
(*keyboard_overlay_map)["xkb:gb:extd:eng"] = "en_GB";
(*keyboard_overlay_map)["xkb:fi::fin"] = "fi";
(*keyboard_overlay_map)["xkb:hu::hun"] = "hu";
(*keyboard_overlay_map)["xkb:it::ita"] = "it";
(*keyboard_overlay_map)["xkb:no::nob"] = "no";
(*keyboard_overlay_map)["xkb:pl::pol"] = "pl";
(*keyboard_overlay_map)["xkb:pt::por"] = "pt_PT";
(*keyboard_overlay_map)["xkb:ro::rum"] = "ro";
(*keyboard_overlay_map)["xkb:se::swe"] = "sv";
(*keyboard_overlay_map)["xkb:sk::slo"] = "sk";
(*keyboard_overlay_map)["xkb:si::slv"] = "sl";
(*keyboard_overlay_map)["xkb:rs::srp"] = "sr";
(*keyboard_overlay_map)["xkb:tr::tur"] = "tr";
(*keyboard_overlay_map)["xkb:ua::ukr"] = "uk";
return keyboard_overlay_map;
}
InputMethodDescriptor previous_input_method_;
InputMethodDescriptor current_input_method_;
ImePropertyList current_ime_properties_;
scoped_ptr<KeyboardOverlayMap> keyboard_overlay_map_;
DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryStubImpl);
};
// static
InputMethodLibrary* InputMethodLibrary::GetImpl(bool stub) {
if (stub) {
return new InputMethodLibraryStubImpl();
} else {
InputMethodLibraryImpl* impl = new InputMethodLibraryImpl();
if (!impl->Init()) {
LOG(ERROR) << "Failed to initialize InputMethodLibraryImpl";
}
return impl;
}
}
} // namespace chromeos
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::InputMethodLibraryImpl);
Fix a bug that caused the keyboard layout not remembered when logging in.
This is a regression caused by
http://src.chromium.org/viewvc/chrome?view=rev&revision=73601
BUG=chromium-os:12801
TEST=add US international, change to US international, log out, login, confirm that US international is selected.
Review URL: http://codereview.chromium.org/6635011
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@77123 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2010 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 "chrome/browser/chromeos/cros/input_method_library.h"
#include <glib.h>
#include <signal.h>
#include "unicode/uloc.h"
#include "base/basictypes.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/keyboard_library.h"
#include "chrome/browser/chromeos/input_method/candidate_window.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/chromeos/language_preferences.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "content/browser/browser_thread.h"
namespace {
const char kIBusDaemonPath[] = "/usr/bin/ibus-daemon";
// Finds a property which has |new_prop.key| from |prop_list|, and replaces the
// property with |new_prop|. Returns true if such a property is found.
bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
chromeos::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
// Update the list except the radio id. As written in
// chromeos_input_method.h, |prop.selection_item_id| is dummy.
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
} // namespace
namespace chromeos {
// The production implementation of InputMethodLibrary.
class InputMethodLibraryImpl : public InputMethodLibrary,
public NotificationObserver {
public:
InputMethodLibraryImpl()
: input_method_status_connection_(NULL),
previous_input_method_("", "", "", ""),
current_input_method_("", "", "", ""),
should_launch_ime_(false),
ime_connected_(false),
defer_ime_startup_(false),
enable_auto_ime_shutdown_(true),
should_change_input_method_(false),
ibus_daemon_process_id_(0),
initialized_successfully_(false),
candidate_window_controller_(NULL) {
// Here, we use the fallback input method descriptor but
// |current_input_method_| will be updated as soon as the login screen
// is shown or the user is logged in, so there is no problem.
current_input_method_ = input_method::GetFallbackInputMethodDescriptor();
active_input_method_ids_.push_back(current_input_method_.id);
// Observe APP_TERMINATING to stop input method daemon gracefully.
// We should not use APP_EXITING here since logout might be canceled by
// JavaScript after APP_EXITING is sent (crosbug.com/11055).
// Note that even if we fail to stop input method daemon from
// Chrome in case of a sudden crash, we have a way to do it from an
// upstart script. See crosbug.com/6515 and crosbug.com/6995 for
// details.
notification_registrar_.Add(this, NotificationType::APP_TERMINATING,
NotificationService::AllSources());
}
// Initializes the object. On success, returns true on and sets
// initialized_successfully_ to true.
//
// Note that we start monitoring input method status in here in Init()
// to avoid a potential race. If we start the monitoring right after
// starting ibus-daemon, there is a higher chance of a race between
// Chrome and ibus-daemon to occur.
bool Init() {
DCHECK(!initialized_successfully_) << "Already initialized";
if (!CrosLibrary::Get()->EnsureLoaded())
return false;
input_method_status_connection_ = chromeos::MonitorInputMethodStatus(
this,
&InputMethodChangedHandler,
&RegisterPropertiesHandler,
&UpdatePropertyHandler,
&ConnectionChangeHandler);
if (!input_method_status_connection_)
return false;
initialized_successfully_ = true;
return true;
}
virtual ~InputMethodLibraryImpl() {
}
virtual void AddObserver(Observer* observer) {
if (!observers_.size()) {
observer->FirstObserverIsAdded(this);
}
observers_.AddObserver(observer);
}
virtual void RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
virtual InputMethodDescriptors* GetActiveInputMethods() {
chromeos::InputMethodDescriptors* result =
new chromeos::InputMethodDescriptors;
// Build the active input method descriptors from the active input
// methods cache |active_input_method_ids_|.
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
// This shouldn't happen as there should be at least one active input
// method, but just in case.
if (result->empty()) {
LOG(ERROR) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
return input_methods->size();
}
virtual InputMethodDescriptors* GetSupportedInputMethods() {
if (!initialized_successfully_) {
// If initialization was failed, return the fallback input method,
// as this function is guaranteed to return at least one descriptor.
InputMethodDescriptors* result = new InputMethodDescriptors;
result->push_back(input_method::GetFallbackInputMethodDescriptor());
return result;
}
// This never returns NULL.
return chromeos::GetSupportedInputMethodDescriptors();
}
virtual void ChangeInputMethod(const std::string& input_method_id) {
// Changing the input method isn't guaranteed to succeed here, but we
// should remember the last one regardless. See comments in
// FlushImeConfig() for details.
tentative_current_input_method_id_ = input_method_id;
// If the input method daemon is not running and the specified input
// method is a keyboard layout, switch the keyboard directly.
if (ibus_daemon_process_id_ == 0 &&
chromeos::input_method::IsKeyboardLayout(input_method_id)) {
// We shouldn't use SetCurrentKeyboardLayoutByName() here. See
// comments at ChangeCurrentInputMethod() for details.
ChangeCurrentInputMethodFromId(input_method_id);
} else {
// Otherwise, start the input method daemon, and change the input
// method via the damon.
StartInputMethodDaemon();
// ChangeInputMethodViaIBus() fails if the IBus daemon is not
// ready yet. In this case, we'll defer the input method change
// until the daemon is ready.
if (!ChangeInputMethodViaIBus(input_method_id)) {
VLOG(1) << "Failed to change the input method to " << input_method_id
<< " (deferring)";
}
}
}
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {
if (!initialized_successfully_)
return;
DCHECK(!key.empty());
chromeos::SetImePropertyActivated(
input_method_status_connection_, key.c_str(), activated);
}
virtual bool InputMethodIsActivated(const std::string& input_method_id) {
scoped_ptr<InputMethodDescriptors> active_input_method_descriptors(
GetActiveInputMethods());
for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) {
if (active_input_method_descriptors->at(i).id == input_method_id) {
return true;
}
}
return false;
}
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
// If the config change is for preload engines, update the active
// input methods cache |active_input_method_ids_| here. We need to
// update the cache before actually flushing the config. since we need
// to return active input methods from GetActiveInputMethods() before
// the input method daemon starts. For instance, we need to show the
// list of available input methods (keyboard layouts) on the login
// screen before the input method starts.
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == ImeConfigValue::kValueTypeStringList) {
active_input_method_ids_ = value.string_list_value;
}
// Before calling FlushImeConfig(), start input method process if necessary.
MaybeStartInputMethodDaemon(section, config_name, value);
const ConfigKeyType key = std::make_pair(section, config_name);
current_config_values_[key] = value;
if (ime_connected_) {
pending_config_requests_[key] = value;
FlushImeConfig();
}
// Stop input method process if necessary.
MaybeStopInputMethodDaemon(section, config_name, value);
// Change the current keyboard layout if necessary.
MaybeChangeCurrentKeyboardLayout(section, config_name, value);
return pending_config_requests_.empty();
}
virtual const InputMethodDescriptor& previous_input_method() const {
return previous_input_method_;
}
virtual const InputMethodDescriptor& current_input_method() const {
return current_input_method_;
}
virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return chromeos::GetKeyboardOverlayId(input_method_id);
}
private:
// Returns true if the given input method config value is a single
// element string list that contains an input method ID of a keyboard
// layout.
bool ContainOnlyOneKeyboardLayout(
const ImeConfigValue& value) {
return (value.type == ImeConfigValue::kValueTypeStringList &&
value.string_list_value.size() == 1 &&
chromeos::input_method::IsKeyboardLayout(
value.string_list_value[0]));
}
// Starts input method daemon based on the |defer_ime_startup_| flag and
// input method configuration being updated. |section| is a section name of
// the input method configuration (e.g. "general", "general/hotkey").
// |config_name| is a name of the configuration (e.g. "preload_engines",
// "previous_engine"). |value| is the configuration value to be set.
void MaybeStartInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName) {
// If there is only one input method which is a keyboard layout,
// we don't start the input method processes. When
// |defer_ime_startup_| is true, we don't start it either.
if (ContainOnlyOneKeyboardLayout(value) ||
defer_ime_startup_) {
// Do not start the input method daemon.
} else {
// Otherwise, start the input method daemon.
StartInputMethodDaemon();
}
}
}
// Stops input method daemon based on the |enable_auto_ime_shutdown_| flag
// and input method configuration being updated.
// See also: MaybeStartInputMethodDaemon().
void MaybeStopInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
// If there is only one input method which is a keyboard layout,
// and |enable_auto_ime_shutdown_| is true, we'll stop the input
// method daemon.
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value) &&
enable_auto_ime_shutdown_) {
StopInputMethodDaemon();
}
}
// Change the keyboard layout per input method configuration being
// updated, if necessary. See also: MaybeStartInputMethodDaemon().
void MaybeChangeCurrentKeyboardLayout(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
// If there is only one input method which is a keyboard layout, we'll
// change the keyboard layout per the only one input method now
// available.
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value)) {
// We shouldn't use SetCurrentKeyboardLayoutByName() here. See
// comments at ChangeCurrentInputMethod() for details.
ChangeCurrentInputMethodFromId(value.string_list_value[0]);
}
}
// Changes the current input method to |input_method_id| via IBus
// daemon. If the id is not in the preload_engine list, this function
// changes the current method to the first preloaded engine. Returns
// true if the current engine is switched to |input_method_id| or the
// first one.
bool ChangeInputMethodViaIBus(const std::string& input_method_id) {
if (!initialized_successfully_)
return false;
std::string input_method_id_to_switch = input_method_id;
if (!InputMethodIsActivated(input_method_id)) {
// This path might be taken if prefs::kLanguageCurrentInputMethod (NOT
// synced with cloud) and kLanguagePreloadEngines (synced with cloud) are
// mismatched. e.g. the former is 'xkb:us::eng' and the latter (on the
// sync server) is 'xkb:jp::jpn,mozc'.
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
DCHECK(!input_methods->empty());
if (!input_methods->empty()) {
input_method_id_to_switch = input_methods->at(0).id;
LOG(INFO) << "Can't change the current input method to "
<< input_method_id << " since the engine is not preloaded. "
<< "Switch to " << input_method_id_to_switch << " instead.";
}
}
if (chromeos::ChangeInputMethod(input_method_status_connection_,
input_method_id_to_switch.c_str())) {
return true;
}
// ChangeInputMethod() fails if the IBus daemon is not yet ready.
LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch;
return false;
}
// Flushes the input method config data. The config data is queued up in
// |pending_config_requests_| until the config backend (ibus-memconf)
// starts.
void FlushImeConfig() {
if (!initialized_successfully_)
return;
bool active_input_methods_are_changed = false;
InputMethodConfigRequests::iterator iter =
pending_config_requests_.begin();
while (iter != pending_config_requests_.end()) {
const std::string& section = iter->first.first;
const std::string& config_name = iter->first.second;
const ImeConfigValue& value = iter->second;
if (chromeos::SetImeConfig(input_method_status_connection_,
section.c_str(),
config_name.c_str(),
value)) {
// Check if it's a change in active input methods.
if (config_name == language_prefs::kPreloadEnginesConfigName) {
active_input_methods_are_changed = true;
VLOG(1) << "Updated preload_engines: " << value.ToString();
}
// Successfully sent. Remove the command and proceed to the next one.
pending_config_requests_.erase(iter++);
} else {
// If SetImeConfig() fails, subsequent calls will likely fail.
break;
}
}
if (pending_config_requests_.empty()) {
// We should change the current input method to the one we have last
// remembered in ChangeInputMethod(), for the following reasons:
//
// 1) Calls to ChangeInputMethod() will fail if the input method has not
// yet been added to preload_engines. As such, the call is deferred
// until after all config values have been sent to the IME process.
//
// 2) We might have already changed the current input method to one
// of XKB layouts without going through the IBus daemon (we can do
// it without the IBus daemon started).
if (should_change_input_method_ &&
!tentative_current_input_method_id_.empty()) {
ChangeInputMethodViaIBus(tentative_current_input_method_id_);
tentative_current_input_method_id_ = "";
should_change_input_method_ = false;
active_input_methods_are_changed = true;
}
}
// Notify the current input method and the number of active input methods to
// the UI so that the UI could determine e.g. if it should show/hide the
// input method indicator, etc. We have to call FOR_EACH_OBSERVER here since
// updating "preload_engine" does not necessarily trigger a DBus signal such
// as "global-engine-changed". For example,
// 1) If we change the preload_engine from "xkb:us:intl:eng" (i.e. the
// indicator is hidden) to "xkb:us:intl:eng,mozc", we have to update UI
// so it shows the indicator, but no signal is sent from ibus-daemon
// because the current input method is not changed.
// 2) If we change the preload_engine from "xkb:us::eng,mozc" (i.e. the
// indicator is shown and ibus-daemon is started) to "xkb:us::eng", we
// have to update UI so it hides the indicator, but we should not expect
// that ibus-daemon could send a DBus signal since the daemon is killed
// right after this FlushImeConfig() call.
if (active_input_methods_are_changed) {
// The |current_input_method_| member might be stale here as
// SetImeConfig("preload_engine") call above might change the
// current input method in ibus-daemon (ex. this occurs when the
// input method currently in use is removed from the options
// page). However, it should be safe to use the member here,
// for the following reasons:
// 1. If ibus-daemon is to be killed, we'll switch to the only one
// keyboard layout, and observers are notified. See
// MaybeStopInputMethodDaemon() for details.
// 2. Otherwise, "global-engine-changed" signal is delivered from
// ibus-daemon, and observers are notified. See
// InputMethodChangedHandler() for details.
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(Observer, observers_,
ActiveInputMethodsChanged(this,
current_input_method_,
num_active_input_methods));
}
}
// Called when the input method is changed in the IBus daemon
// (ex. "global-engine-changed" is delivered from the IBus daemon).
static void InputMethodChangedHandler(
void* object,
const chromeos::InputMethodDescriptor& current_input_method) {
// The handler is called when the input method method change is
// notified via a DBus connection. Since the DBus notificatiosn are
// handled in the UI thread, we can assume that this function always
// runs on the UI thread, but just in case.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ChangeCurrentInputMethod(current_input_method);
}
// Called when properties are registered in the IBus daemon.
static void RegisterPropertiesHandler(
void* object, const ImePropertyList& prop_list) {
// See comments in InputMethodChangedHandler.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->RegisterProperties(prop_list);
}
// Called when properties are updated in the IBus daemon.
static void UpdatePropertyHandler(
void* object, const ImePropertyList& prop_list) {
// See comments in InputMethodChangedHandler.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->UpdateProperty(prop_list);
}
// Called when 1) connection to ibus-daemon and ibus-memconf are established
// or 2) connection to ibus-daemon is terminated.
static void ConnectionChangeHandler(void* object, bool connected) {
// See comments in InputMethodChangedHandler.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ime_connected_ = connected;
if (connected) {
input_method_library->pending_config_requests_.clear();
input_method_library->pending_config_requests_.insert(
input_method_library->current_config_values_.begin(),
input_method_library->current_config_values_.end());
input_method_library->should_change_input_method_ = true;
input_method_library->FlushImeConfig();
}
}
// Changes the current input method from the given input method
// descriptor. This function updates states like current_input_method_
// and notifies observers about the change (that will update the
// preferences), hence this function should always be used even if you
// just need to change the current keyboard layout.
void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) {
if (current_input_method_.id != new_input_method.id) {
previous_input_method_ = current_input_method_;
current_input_method_ = new_input_method;
// Change the keyboard layout to a preferred layout for the input method.
if (!CrosLibrary::Get()->GetKeyboardLibrary()->
SetCurrentKeyboardLayoutByName(
current_input_method_.keyboard_layout)) {
LOG(ERROR) << "Failed to change keyboard layout to "
<< current_input_method_.keyboard_layout;
}
// Ask the first observer to update preferences. We should not ask every
// observer to do so. Otherwise, we'll end up updating preferences many
// times when many observers are attached (ex. many windows are opened),
// which is unnecessary and expensive.
ObserverListBase<Observer>::Iterator it(observers_);
Observer* first_observer = it.GetNext();
if (first_observer) {
first_observer->PreferenceUpdateNeeded(this,
previous_input_method_,
current_input_method_);
}
}
// Update input method indicators (e.g. "US", "DV") in Chrome windows.
// For now, we have to do this every time to keep indicators updated. See
// comments near the FOR_EACH_OBSERVER call in FlushImeConfig() for details.
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(Observer, observers_,
InputMethodChanged(this,
current_input_method_,
num_active_input_methods));
}
// Changes the current input method from the given input method ID.
// This function is just a wrapper of ChangeCurrentInputMethod().
void ChangeCurrentInputMethodFromId(const std::string& input_method_id) {
const chromeos::InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
ChangeCurrentInputMethod(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
// Registers the properties used by the current input method.
void RegisterProperties(const ImePropertyList& prop_list) {
// |prop_list| might be empty. This means "clear all properties."
current_ime_properties_ = prop_list;
}
// Starts the input method daemon. Unlike MaybeStopInputMethodDaemon(),
// this function always starts the daemon.
void StartInputMethodDaemon() {
should_launch_ime_ = true;
MaybeLaunchInputMethodDaemon();
}
// Updates the properties used by the current input method.
void UpdateProperty(const ImePropertyList& prop_list) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
}
// Launches an input method procsess specified by the given command
// line. On success, returns true and stores the process ID in
// |process_id|. Otherwise, returns false, and the contents of
// |process_id| is untouched. OnImeShutdown will be called when the
// process terminates.
bool LaunchInputMethodProcess(const std::string& command_line,
int* process_id) {
GError *error = NULL;
gchar **argv = NULL;
gint argc = NULL;
// TODO(zork): export "LD_PRELOAD=/usr/lib/libcrash.so"
if (!g_shell_parse_argv(command_line.c_str(), &argc, &argv, &error)) {
LOG(ERROR) << "Could not parse command: " << error->message;
g_error_free(error);
return false;
}
int pid = 0;
const GSpawnFlags kFlags = G_SPAWN_DO_NOT_REAP_CHILD;
const gboolean result = g_spawn_async(NULL, argv, NULL,
kFlags, NULL, NULL,
&pid, &error);
g_strfreev(argv);
if (!result) {
LOG(ERROR) << "Could not launch: " << command_line << ": "
<< error->message;
g_error_free(error);
return false;
}
g_child_watch_add(pid, reinterpret_cast<GChildWatchFunc>(OnImeShutdown),
this);
*process_id = pid;
VLOG(1) << command_line << " (PID=" << pid << ") is started";
return true;
}
// Launches input method daemon if these are not yet running.
void MaybeLaunchInputMethodDaemon() {
// CandidateWindowController requires libcros to be loaded. Besides,
// launching ibus-daemon without libcros loaded doesn't make sense.
if (!initialized_successfully_)
return;
if (!should_launch_ime_) {
return;
}
if (!candidate_window_controller_.get()) {
candidate_window_controller_.reset(new CandidateWindowController);
if (!candidate_window_controller_->Init()) {
LOG(WARNING) << "Failed to initialize the candidate window controller";
}
}
if (ibus_daemon_process_id_ == 0) {
// TODO(zork): Send output to /var/log/ibus.log
const std::string ibus_daemon_command_line =
StringPrintf("%s --panel=disable --cache=none --restart --replace",
kIBusDaemonPath);
if (!LaunchInputMethodProcess(
ibus_daemon_command_line, &ibus_daemon_process_id_)) {
LOG(ERROR) << "Failed to launch " << ibus_daemon_command_line;
}
}
}
// Called when the input method process is shut down.
static void OnImeShutdown(int pid,
int status,
InputMethodLibraryImpl* library) {
g_spawn_close_pid(pid);
if (library->ibus_daemon_process_id_ == pid) {
library->ibus_daemon_process_id_ = 0;
}
// Restart input method daemon if needed.
library->MaybeLaunchInputMethodDaemon();
}
// Stops the backend input method daemon. This function should also be
// called from MaybeStopInputMethodDaemon(), except one case where we
// stop the input method daemon at Chrome shutdown in Observe().
void StopInputMethodDaemon() {
if (!initialized_successfully_)
return;
should_launch_ime_ = false;
if (ibus_daemon_process_id_) {
if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) {
LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to "
<< "PID " << ibus_daemon_process_id_;
kill(ibus_daemon_process_id_, SIGTERM);
}
VLOG(1) << "ibus-daemon (PID=" << ibus_daemon_process_id_ << ") is "
<< "terminated";
ibus_daemon_process_id_ = 0;
}
}
void SetDeferImeStartup(bool defer) {
VLOG(1) << "Setting DeferImeStartup to " << defer;
defer_ime_startup_ = defer;
}
void SetEnableAutoImeShutdown(bool enable) {
enable_auto_ime_shutdown_ = enable;
}
// NotificationObserver implementation:
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
// Stop the input method daemon on browser shutdown.
if (type.value == NotificationType::APP_TERMINATING) {
notification_registrar_.RemoveAll();
StopInputMethodDaemon();
}
}
// A reference to the language api, to allow callbacks when the input method
// status changes.
InputMethodStatusConnection* input_method_status_connection_;
ObserverList<Observer> observers_;
// The input method which was/is selected.
InputMethodDescriptor previous_input_method_;
InputMethodDescriptor current_input_method_;
// The input method properties which the current input method uses. The list
// might be empty when no input method is used.
ImePropertyList current_ime_properties_;
typedef std::pair<std::string, std::string> ConfigKeyType;
typedef std::map<ConfigKeyType, ImeConfigValue> InputMethodConfigRequests;
// SetImeConfig requests that are not yet completed.
// Use a map to queue config requests, so we only send the last request for
// the same config key (i.e. we'll discard ealier requests for the same
// config key). As we discard old requests for the same config key, the order
// of requests doesn't matter, so it's safe to use a map.
InputMethodConfigRequests pending_config_requests_;
// Values that have been set via SetImeConfig(). We keep a copy available to
// resend if the ime restarts and loses its state.
InputMethodConfigRequests current_config_values_;
// This is used to register this object to APP_EXITING notification.
NotificationRegistrar notification_registrar_;
// True if we should launch the input method daemon.
bool should_launch_ime_;
// True if the connection to the IBus daemon is alive.
bool ime_connected_;
// If true, we'll defer the startup until a non-default method is
// activated.
bool defer_ime_startup_;
// True if we should stop input method daemon when there are no input
// methods other than one for the hardware keyboard.
bool enable_auto_ime_shutdown_;
// The ID of the tentative current input method (ex. "mozc"). This value
// can be different from the actual current input method, if
// ChangeInputMethod() fails.
std::string tentative_current_input_method_id_;
// True if we should change the current input method to
// |tentative_current_input_method_id_| once the queue of the pending config
// requests becomes empty.
bool should_change_input_method_;
// The process id of the IBus daemon. 0 if it's not running. The process
// ID 0 is not used in Linux, hence it's safe to use 0 for this purpose.
int ibus_daemon_process_id_;
// True if initialization is successfully done, meaning that libcros is
// loaded and input method status monitoring is started. This value
// should be checked where we call libcros functions.
bool initialized_successfully_;
// The candidate window.
scoped_ptr<CandidateWindowController> candidate_window_controller_;
// The active input method ids cache.
std::vector<std::string> active_input_method_ids_;
DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryImpl);
};
InputMethodLibraryImpl::Observer::~Observer() {}
// The stub implementation of InputMethodLibrary. Used for testing.
class InputMethodLibraryStubImpl : public InputMethodLibrary {
public:
InputMethodLibraryStubImpl()
: previous_input_method_("", "", "", ""),
current_input_method_("", "", "", ""),
keyboard_overlay_map_(
GetKeyboardOverlayMapForTesting()) {
current_input_method_ = input_method::GetFallbackInputMethodDescriptor();
}
virtual ~InputMethodLibraryStubImpl() {}
virtual void AddObserver(Observer* observer) {}
virtual void RemoveObserver(Observer* observer) {}
virtual InputMethodDescriptors* GetActiveInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods());
return descriptors->size();
}
virtual InputMethodDescriptors* GetSupportedInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
virtual void ChangeInputMethod(const std::string& input_method_id) {}
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {}
virtual bool InputMethodIsActivated(const std::string& input_method_id) {
return true;
}
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
return false;
}
virtual const InputMethodDescriptor& previous_input_method() const {
return previous_input_method_;
}
virtual const InputMethodDescriptor& current_input_method() const {
return current_input_method_;
}
virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
virtual void StartInputMethodDaemon() {}
virtual void StopInputMethodDaemon() {}
virtual void SetDeferImeStartup(bool defer) {}
virtual void SetEnableAutoImeShutdown(bool enable) {}
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
KeyboardOverlayMap::const_iterator iter =
keyboard_overlay_map_->find(input_method_id);
return (iter != keyboard_overlay_map_->end()) ?
iter->second : "";
}
private:
typedef std::map<std::string, std::string> KeyboardOverlayMap;
// Gets input method descriptors for testing. Shouldn't be used for
// production.
InputMethodDescriptors* GetInputMethodDescriptorsForTesting() {
InputMethodDescriptors* descriptions = new InputMethodDescriptors;
// The list is created from output of gen_engines.py in libcros.
// % SHARE=/build/x86-generic/usr/share python gen_engines.py
// $SHARE/chromeos-assets/input_methods/whitelist.txt
// $SHARE/ibus/component/{chewing,hangul,m17n,mozc,pinyin,xkb-layouts}.xml
descriptions->push_back(InputMethodDescriptor(
"xkb:nl::nld", "Netherlands", "nl", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::nld", "Belgium", "be", "nld"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fr::fra", "France", "fr", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::fra", "Belgium", "be", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca::fra", "Canada", "ca", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "fra"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de::ger", "Germany", "de", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:be::ger", "Belgium", "be", "ger"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ch::ger", "Switzerland", "ch", "ger"));
descriptions->push_back(InputMethodDescriptor(
"mozc", "Mozc (US keyboard layout)", "us", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "ja"));
descriptions->push_back(InputMethodDescriptor(
"mozc-dv", "Mozc (US Dvorak keyboard layout)", "us(dvorak)", "ja"));
descriptions->push_back(InputMethodDescriptor(
"xkb:jp::jpn", "Japan", "jp", "jpn"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru::rus", "Russia", "ru", "rus"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ru:phonetic:rus", "Russia - Phonetic", "ru(phonetic)", "rus"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:kesmanee", "kesmanee (m17n)", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:pattachote", "pattachote (m17n)", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"m17n:th:tis820", "tis820 (m17n)", "us", "th"));
descriptions->push_back(InputMethodDescriptor(
"chewing", "Chewing", "us", "zh_TW"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:cangjie", "cangjie (m17n)", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:zh:quick", "quick (m17n)", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:tcvn", "tcvn (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:telex", "telex (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:viqr", "viqr (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:vi:vni", "vni (m17n)", "us", "vi"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us::eng", "USA", "us", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:intl:eng",
"USA - International (with dead keys)", "us(intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:altgr-intl:eng",
"USA - International (AltGr dead keys)", "us(altgr-intl)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:dvorak:eng", "USA - Dvorak", "us(dvorak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:us:colemak:eng", "USA - Colemak", "us(colemak)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"hangul", "Korean", "kr(kr104)", "ko"));
descriptions->push_back(InputMethodDescriptor(
"pinyin", "Pinyin", "us", "zh"));
descriptions->push_back(InputMethodDescriptor(
"m17n:ar:kbd", "kbd (m17n)", "us", "ar"));
descriptions->push_back(InputMethodDescriptor(
"m17n:hi:itrans", "itrans (m17n)", "us", "hi"));
descriptions->push_back(InputMethodDescriptor(
"m17n:fa:isiri", "isiri (m17n)", "us", "fa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:br::por", "Brazil", "br", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg::bul", "Bulgaria", "bg", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:bg:phonetic:bul",
"Bulgaria - Traditional phonetic", "bg(phonetic)", "bul"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ca:eng:eng", "Canada - English", "ca(eng)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:cz::cze", "Czechia", "cz", "cze"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ee::est", "Estonia", "ee", "est"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es::spa", "Spain", "es", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:es:cat:cat",
"Spain - Catalan variant with middle-dot L", "es(cat)", "cat"));
descriptions->push_back(InputMethodDescriptor(
"xkb:dk::dan", "Denmark", "dk", "dan"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gr::gre", "Greece", "gr", "gre"));
descriptions->push_back(InputMethodDescriptor(
"xkb:il::heb", "Israel", "il", "heb"));
descriptions->push_back(InputMethodDescriptor(
"xkb:kr:kr104:kor",
"Korea, Republic of - 101/104 key Compatible", "kr(kr104)", "kor"));
descriptions->push_back(InputMethodDescriptor(
"xkb:latam::spa", "Latin American", "latam", "spa"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lt::lit", "Lithuania", "lt", "lit"));
descriptions->push_back(InputMethodDescriptor(
"xkb:lv:apostrophe:lav",
"Latvia - Apostrophe (') variant", "lv(apostrophe)", "lav"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hr::scr", "Croatia", "hr", "scr"));
descriptions->push_back(InputMethodDescriptor(
"xkb:gb:extd:eng",
"United Kingdom - Extended - Winkeys", "gb(extd)", "eng"));
descriptions->push_back(InputMethodDescriptor(
"xkb:fi::fin", "Finland", "fi", "fin"));
descriptions->push_back(InputMethodDescriptor(
"xkb:hu::hun", "Hungary", "hu", "hun"));
descriptions->push_back(InputMethodDescriptor(
"xkb:it::ita", "Italy", "it", "ita"));
descriptions->push_back(InputMethodDescriptor(
"xkb:no::nob", "Norway", "no", "nob"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pl::pol", "Poland", "pl", "pol"));
descriptions->push_back(InputMethodDescriptor(
"xkb:pt::por", "Portugal", "pt", "por"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ro::rum", "Romania", "ro", "rum"));
descriptions->push_back(InputMethodDescriptor(
"xkb:se::swe", "Sweden", "se", "swe"));
descriptions->push_back(InputMethodDescriptor(
"xkb:sk::slo", "Slovakia", "sk", "slo"));
descriptions->push_back(InputMethodDescriptor(
"xkb:si::slv", "Slovenia", "si", "slv"));
descriptions->push_back(InputMethodDescriptor(
"xkb:rs::srp", "Serbia", "rs", "srp"));
descriptions->push_back(InputMethodDescriptor(
"xkb:tr::tur", "Turkey", "tr", "tur"));
descriptions->push_back(InputMethodDescriptor(
"xkb:ua::ukr", "Ukraine", "ua", "ukr"));
return descriptions;
}
// Gets keyboard overlay map for testing. Shouldn't be used for
// production.
std::map<std::string, std::string>* GetKeyboardOverlayMapForTesting() {
KeyboardOverlayMap* keyboard_overlay_map =
new KeyboardOverlayMap;
(*keyboard_overlay_map)["xkb:nl::nld"] = "nl";
(*keyboard_overlay_map)["xkb:be::nld"] = "nl";
(*keyboard_overlay_map)["xkb:fr::fra"] = "fr";
(*keyboard_overlay_map)["xkb:be::fra"] = "fr";
(*keyboard_overlay_map)["xkb:ca::fra"] = "fr_CA";
(*keyboard_overlay_map)["xkb:ch:fr:fra"] = "fr";
(*keyboard_overlay_map)["xkb:de::ger"] = "de";
(*keyboard_overlay_map)["xkb:be::ger"] = "de";
(*keyboard_overlay_map)["xkb:ch::ger"] = "de";
(*keyboard_overlay_map)["mozc"] = "en_US";
(*keyboard_overlay_map)["mozc-jp"] = "ja";
(*keyboard_overlay_map)["mozc-dv"] = "en_US_dvorak";
(*keyboard_overlay_map)["xkb:jp::jpn"] = "ja";
(*keyboard_overlay_map)["xkb:ru::rus"] = "ru";
(*keyboard_overlay_map)["xkb:ru:phonetic:rus"] = "ru";
(*keyboard_overlay_map)["m17n:th:kesmanee"] = "th";
(*keyboard_overlay_map)["m17n:th:pattachote"] = "th";
(*keyboard_overlay_map)["m17n:th:tis820"] = "th";
(*keyboard_overlay_map)["chewing"] = "zh_TW";
(*keyboard_overlay_map)["m17n:zh:cangjie"] = "zh_TW";
(*keyboard_overlay_map)["m17n:zh:quick"] = "zh_TW";
(*keyboard_overlay_map)["m17n:vi:tcvn"] = "vi";
(*keyboard_overlay_map)["m17n:vi:telex"] = "vi";
(*keyboard_overlay_map)["m17n:vi:viqr"] = "vi";
(*keyboard_overlay_map)["m17n:vi:vni"] = "vi";
(*keyboard_overlay_map)["xkb:us::eng"] = "en_US";
(*keyboard_overlay_map)["xkb:us:intl:eng"] = "en_US";
(*keyboard_overlay_map)["xkb:us:altgr-intl:eng"] = "en_US";
(*keyboard_overlay_map)["xkb:us:dvorak:eng"] =
"en_US_dvorak";
(*keyboard_overlay_map)["xkb:us:colemak:eng"] =
"en_US";
(*keyboard_overlay_map)["hangul"] = "ko";
(*keyboard_overlay_map)["pinyin"] = "zh_CN";
(*keyboard_overlay_map)["m17n:ar:kbd"] = "ar";
(*keyboard_overlay_map)["m17n:hi:itrans"] = "hi";
(*keyboard_overlay_map)["m17n:fa:isiri"] = "ar";
(*keyboard_overlay_map)["xkb:br::por"] = "pt_BR";
(*keyboard_overlay_map)["xkb:bg::bul"] = "bg";
(*keyboard_overlay_map)["xkb:bg:phonetic:bul"] = "bg";
(*keyboard_overlay_map)["xkb:ca:eng:eng"] = "ca";
(*keyboard_overlay_map)["xkb:cz::cze"] = "cs";
(*keyboard_overlay_map)["xkb:ee::est"] = "et";
(*keyboard_overlay_map)["xkb:es::spa"] = "es";
(*keyboard_overlay_map)["xkb:es:cat:cat"] = "ca";
(*keyboard_overlay_map)["xkb:dk::dan"] = "da";
(*keyboard_overlay_map)["xkb:gr::gre"] = "el";
(*keyboard_overlay_map)["xkb:il::heb"] = "iw";
(*keyboard_overlay_map)["xkb:kr:kr104:kor"] = "ko";
(*keyboard_overlay_map)["xkb:latam::spa"] = "es_419";
(*keyboard_overlay_map)["xkb:lt::lit"] = "lt";
(*keyboard_overlay_map)["xkb:lv:apostrophe:lav"] = "lv";
(*keyboard_overlay_map)["xkb:hr::scr"] = "hr";
(*keyboard_overlay_map)["xkb:gb:extd:eng"] = "en_GB";
(*keyboard_overlay_map)["xkb:fi::fin"] = "fi";
(*keyboard_overlay_map)["xkb:hu::hun"] = "hu";
(*keyboard_overlay_map)["xkb:it::ita"] = "it";
(*keyboard_overlay_map)["xkb:no::nob"] = "no";
(*keyboard_overlay_map)["xkb:pl::pol"] = "pl";
(*keyboard_overlay_map)["xkb:pt::por"] = "pt_PT";
(*keyboard_overlay_map)["xkb:ro::rum"] = "ro";
(*keyboard_overlay_map)["xkb:se::swe"] = "sv";
(*keyboard_overlay_map)["xkb:sk::slo"] = "sk";
(*keyboard_overlay_map)["xkb:si::slv"] = "sl";
(*keyboard_overlay_map)["xkb:rs::srp"] = "sr";
(*keyboard_overlay_map)["xkb:tr::tur"] = "tr";
(*keyboard_overlay_map)["xkb:ua::ukr"] = "uk";
return keyboard_overlay_map;
}
InputMethodDescriptor previous_input_method_;
InputMethodDescriptor current_input_method_;
ImePropertyList current_ime_properties_;
scoped_ptr<KeyboardOverlayMap> keyboard_overlay_map_;
DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryStubImpl);
};
// static
InputMethodLibrary* InputMethodLibrary::GetImpl(bool stub) {
if (stub) {
return new InputMethodLibraryStubImpl();
} else {
InputMethodLibraryImpl* impl = new InputMethodLibraryImpl();
if (!impl->Init()) {
LOG(ERROR) << "Failed to initialize InputMethodLibraryImpl";
}
return impl;
}
}
} // namespace chromeos
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::InputMethodLibraryImpl);
|
// Copyright (c) 2010 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 "chrome/browser/extensions/extension_toolbar_model.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
ExtensionToolbarModel::ExtensionToolbarModel(ExtensionsService* service)
: service_(service),
prefs_(service->profile()->GetPrefs()),
extensions_initialized_(false) {
DCHECK(service_);
registrar_.Add(this, NotificationType::EXTENSION_LOADED,
Source<Profile>(service_->profile()));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
Source<Profile>(service_->profile()));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,
Source<Profile>(service_->profile()));
registrar_.Add(this, NotificationType::EXTENSIONS_READY,
Source<Profile>(service_->profile()));
visible_icon_count_ = prefs_->GetInteger(prefs::kExtensionToolbarSize);
}
ExtensionToolbarModel::~ExtensionToolbarModel() {
}
void ExtensionToolbarModel::DestroyingProfile() {
registrar_.RemoveAll();
}
void ExtensionToolbarModel::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void ExtensionToolbarModel::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void ExtensionToolbarModel::MoveBrowserAction(Extension* extension,
int index) {
ExtensionList::iterator pos = std::find(begin(), end(), extension);
if (pos == end()) {
NOTREACHED();
return;
}
toolitems_.erase(pos);
int i = 0;
bool inserted = false;
for (ExtensionList::iterator iter = begin(); iter != end(); ++iter, ++i) {
if (i == index) {
toolitems_.insert(iter, extension);
inserted = true;
break;
}
}
if (!inserted) {
DCHECK_EQ(index, static_cast<int>(toolitems_.size()));
index = toolitems_.size();
toolitems_.push_back(extension);
}
FOR_EACH_OBSERVER(Observer, observers_, BrowserActionMoved(extension, index));
UpdatePrefs();
}
void ExtensionToolbarModel::SetVisibleIconCount(int count) {
visible_icon_count_ = count == static_cast<int>(size()) ? -1 : count;
prefs_->SetInteger(prefs::kExtensionToolbarSize, visible_icon_count_);
}
void ExtensionToolbarModel::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSIONS_READY) {
InitializeExtensionList();
return;
}
if (!service_->is_ready())
return;
Extension* extension = Details<Extension>(details).ptr();
if (type == NotificationType::EXTENSION_LOADED) {
AddExtension(extension);
} else if (type == NotificationType::EXTENSION_UNLOADED ||
type == NotificationType::EXTENSION_UNLOADED_DISABLED) {
RemoveExtension(extension);
} else {
NOTREACHED() << "Received unexpected notification";
}
}
void ExtensionToolbarModel::AddExtension(Extension* extension) {
// We only care about extensions with browser actions.
if (!extension->browser_action())
return;
if (extension->id() == last_extension_removed_ &&
last_extension_removed_index_ < toolitems_.size()) {
toolitems_.insert(begin() + last_extension_removed_index_, extension);
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionAdded(extension, last_extension_removed_index_));
} else {
toolitems_.push_back(extension);
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionAdded(extension, toolitems_.size() - 1));
}
last_extension_removed_ = "";
last_extension_removed_index_ = -1;
UpdatePrefs();
}
void ExtensionToolbarModel::RemoveExtension(Extension* extension) {
ExtensionList::iterator pos = std::find(begin(), end(), extension);
if (pos == end()) {
return;
}
last_extension_removed_ = extension->id();
last_extension_removed_index_ = pos - begin();
toolitems_.erase(pos);
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionRemoved(extension));
UpdatePrefs();
}
// Combine the currently enabled extensions that have browser actions (which
// we get from the ExtensionsService) with the ordering we get from the
// pref service. For robustness we use a somewhat inefficient process:
// 1. Create a vector of extensions sorted by their pref values. This vector may
// have holes.
// 2. Create a vector of extensions that did not have a pref value.
// 3. Remove holes from the sorted vector and append the unsorted vector.
void ExtensionToolbarModel::InitializeExtensionList() {
DCHECK(service_->is_ready());
std::vector<std::string> pref_order = service_->extension_prefs()->
GetToolbarOrder();
// Items that have a pref for their position.
ExtensionList sorted;
sorted.resize(pref_order.size(), NULL);
// The items that don't have a pref for their position.
ExtensionList unsorted;
// Create the lists.
for (size_t i = 0; i < service_->extensions()->size(); ++i) {
Extension* extension = service_->extensions()->at(i);
if (!extension->browser_action())
continue;
std::vector<std::string>::iterator pos =
std::find(pref_order.begin(), pref_order.end(), extension->id());
if (pos != pref_order.end()) {
int index = std::distance(pref_order.begin(), pos);
sorted[index] = extension;
} else {
unsorted.push_back(extension);
}
}
// Merge the lists.
toolitems_.reserve(sorted.size() + unsorted.size());
for (ExtensionList::iterator iter = sorted.begin();
iter != sorted.end(); ++iter) {
if (*iter != NULL)
toolitems_.push_back(*iter);
}
toolitems_.insert(toolitems_.end(), unsorted.begin(), unsorted.end());
// Inform observers.
for (size_t i = 0; i < toolitems_.size(); i++) {
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionAdded(toolitems_[i], i));
}
UpdatePrefs();
extensions_initialized_ = true;
FOR_EACH_OBSERVER(Observer, observers_, ModelLoaded());
}
void ExtensionToolbarModel::UpdatePrefs() {
if (!service_->extension_prefs())
return;
std::vector<std::string> ids;
ids.reserve(toolitems_.size());
for (ExtensionList::iterator iter = begin(); iter != end(); ++iter)
ids.push_back((*iter)->id());
service_->extension_prefs()->SetToolbarOrder(ids);
}
Extension* ExtensionToolbarModel::GetExtensionByIndex(int index) const {
return toolitems_.at(index);
}
int ExtensionToolbarModel::IncognitoIndexToOriginal(int incognito_index) {
int original_index = 0, i = 0;
for (ExtensionList::iterator iter = begin(); iter != end();
++iter, ++original_index) {
if (service_->IsIncognitoEnabled(*iter)) {
if (incognito_index == i)
break;
++i;
}
}
return original_index;
}
int ExtensionToolbarModel::OriginalIndexToIncognito(int original_index) {
int incognito_index = 0, i = 0;
for (ExtensionList::iterator iter = begin(); iter != end();
++iter, ++i) {
if (original_index == i)
break;
if (service_->IsIncognitoEnabled(*iter))
++incognito_index;
}
return incognito_index;
}
add a pref save when changing the visible icon count
BUG=47201
TEST=Resize the browser action area and then force a shutdown. Ensure that the change is persisted for the next launch.
Review URL: http://codereview.chromium.org/3791003
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@62545 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
// Copyright (c) 2010 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 "chrome/browser/extensions/extension_toolbar_model.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
ExtensionToolbarModel::ExtensionToolbarModel(ExtensionsService* service)
: service_(service),
prefs_(service->profile()->GetPrefs()),
extensions_initialized_(false) {
DCHECK(service_);
registrar_.Add(this, NotificationType::EXTENSION_LOADED,
Source<Profile>(service_->profile()));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
Source<Profile>(service_->profile()));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,
Source<Profile>(service_->profile()));
registrar_.Add(this, NotificationType::EXTENSIONS_READY,
Source<Profile>(service_->profile()));
visible_icon_count_ = prefs_->GetInteger(prefs::kExtensionToolbarSize);
}
ExtensionToolbarModel::~ExtensionToolbarModel() {
}
void ExtensionToolbarModel::DestroyingProfile() {
registrar_.RemoveAll();
}
void ExtensionToolbarModel::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void ExtensionToolbarModel::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void ExtensionToolbarModel::MoveBrowserAction(Extension* extension,
int index) {
ExtensionList::iterator pos = std::find(begin(), end(), extension);
if (pos == end()) {
NOTREACHED();
return;
}
toolitems_.erase(pos);
int i = 0;
bool inserted = false;
for (ExtensionList::iterator iter = begin(); iter != end(); ++iter, ++i) {
if (i == index) {
toolitems_.insert(iter, extension);
inserted = true;
break;
}
}
if (!inserted) {
DCHECK_EQ(index, static_cast<int>(toolitems_.size()));
index = toolitems_.size();
toolitems_.push_back(extension);
}
FOR_EACH_OBSERVER(Observer, observers_, BrowserActionMoved(extension, index));
UpdatePrefs();
}
void ExtensionToolbarModel::SetVisibleIconCount(int count) {
visible_icon_count_ = count == static_cast<int>(size()) ? -1 : count;
prefs_->SetInteger(prefs::kExtensionToolbarSize, visible_icon_count_);
prefs_->ScheduleSavePersistentPrefs();
}
void ExtensionToolbarModel::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSIONS_READY) {
InitializeExtensionList();
return;
}
if (!service_->is_ready())
return;
Extension* extension = Details<Extension>(details).ptr();
if (type == NotificationType::EXTENSION_LOADED) {
AddExtension(extension);
} else if (type == NotificationType::EXTENSION_UNLOADED ||
type == NotificationType::EXTENSION_UNLOADED_DISABLED) {
RemoveExtension(extension);
} else {
NOTREACHED() << "Received unexpected notification";
}
}
void ExtensionToolbarModel::AddExtension(Extension* extension) {
// We only care about extensions with browser actions.
if (!extension->browser_action())
return;
if (extension->id() == last_extension_removed_ &&
last_extension_removed_index_ < toolitems_.size()) {
toolitems_.insert(begin() + last_extension_removed_index_, extension);
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionAdded(extension, last_extension_removed_index_));
} else {
toolitems_.push_back(extension);
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionAdded(extension, toolitems_.size() - 1));
}
last_extension_removed_ = "";
last_extension_removed_index_ = -1;
UpdatePrefs();
}
void ExtensionToolbarModel::RemoveExtension(Extension* extension) {
ExtensionList::iterator pos = std::find(begin(), end(), extension);
if (pos == end()) {
return;
}
last_extension_removed_ = extension->id();
last_extension_removed_index_ = pos - begin();
toolitems_.erase(pos);
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionRemoved(extension));
UpdatePrefs();
}
// Combine the currently enabled extensions that have browser actions (which
// we get from the ExtensionsService) with the ordering we get from the
// pref service. For robustness we use a somewhat inefficient process:
// 1. Create a vector of extensions sorted by their pref values. This vector may
// have holes.
// 2. Create a vector of extensions that did not have a pref value.
// 3. Remove holes from the sorted vector and append the unsorted vector.
void ExtensionToolbarModel::InitializeExtensionList() {
DCHECK(service_->is_ready());
std::vector<std::string> pref_order = service_->extension_prefs()->
GetToolbarOrder();
// Items that have a pref for their position.
ExtensionList sorted;
sorted.resize(pref_order.size(), NULL);
// The items that don't have a pref for their position.
ExtensionList unsorted;
// Create the lists.
for (size_t i = 0; i < service_->extensions()->size(); ++i) {
Extension* extension = service_->extensions()->at(i);
if (!extension->browser_action())
continue;
std::vector<std::string>::iterator pos =
std::find(pref_order.begin(), pref_order.end(), extension->id());
if (pos != pref_order.end()) {
int index = std::distance(pref_order.begin(), pos);
sorted[index] = extension;
} else {
unsorted.push_back(extension);
}
}
// Merge the lists.
toolitems_.reserve(sorted.size() + unsorted.size());
for (ExtensionList::iterator iter = sorted.begin();
iter != sorted.end(); ++iter) {
if (*iter != NULL)
toolitems_.push_back(*iter);
}
toolitems_.insert(toolitems_.end(), unsorted.begin(), unsorted.end());
// Inform observers.
for (size_t i = 0; i < toolitems_.size(); i++) {
FOR_EACH_OBSERVER(Observer, observers_,
BrowserActionAdded(toolitems_[i], i));
}
UpdatePrefs();
extensions_initialized_ = true;
FOR_EACH_OBSERVER(Observer, observers_, ModelLoaded());
}
void ExtensionToolbarModel::UpdatePrefs() {
if (!service_->extension_prefs())
return;
std::vector<std::string> ids;
ids.reserve(toolitems_.size());
for (ExtensionList::iterator iter = begin(); iter != end(); ++iter)
ids.push_back((*iter)->id());
service_->extension_prefs()->SetToolbarOrder(ids);
}
Extension* ExtensionToolbarModel::GetExtensionByIndex(int index) const {
return toolitems_.at(index);
}
int ExtensionToolbarModel::IncognitoIndexToOriginal(int incognito_index) {
int original_index = 0, i = 0;
for (ExtensionList::iterator iter = begin(); iter != end();
++iter, ++original_index) {
if (service_->IsIncognitoEnabled(*iter)) {
if (incognito_index == i)
break;
++i;
}
}
return original_index;
}
int ExtensionToolbarModel::OriginalIndexToIncognito(int original_index) {
int incognito_index = 0, i = 0;
for (ExtensionList::iterator iter = begin(); iter != end();
++iter, ++i) {
if (original_index == i)
break;
if (service_->IsIncognitoEnabled(*iter))
++incognito_index;
}
return incognito_index;
}
|
// Copyright (c) 2006-2008 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 "testing/gtest/include/gtest/gtest.h"
#include <string>
#include <vector>
#include "chrome/browser/importer/importer.h"
#include "chrome/browser/importer/toolbar_importer.h"
#include "chrome/common/libxml_utils.h"
#include "googleurl/src/gurl.h"
namespace toolbar_importer_unittest {
static const wchar_t* kTitle = L"MyTitle";
static const char* kUrl = "http://www.google.com/";
static const wchar_t* kFolder = L"Google";
static const wchar_t* kFolder2 = L"Homepage";
static const wchar_t* kFolderArray[3] = {L"Google", L"Search", L"Page"};
static const wchar_t* kOtherTitle = L"MyOtherTitle";
static const char* kOtherUrl = "http://www.google.com/mail";
static const wchar_t* kOtherFolder = L"Mail";
// Since the following is very dense to read I enumerate the test cases here.
// 1. Correct bookmark structure with one label.
// 2. Correct bookmark structure with no labels.
// 3. Correct bookmark structure with two labels.
// 4. Correct bookmark structure with a folder->label translation by toolbar.
// 5. Correct bookmark structure with no favicon.
// 6. Two correct bookmarks.
// The following are error cases by removing sections from the xml:
// 7. Empty string passed as xml.
// 8. No <bookmarks> section in the xml.
// 9. No <bookmark> section below the <bookmarks> section.
// 10. No <title> in a <bookmark> section.
// 11. No <url> in a <bookmark> section.
// 12. No <timestamp> in a <bookmark> section.
// 13. No <labels> in a <bookmark> section.
static const char* kGoodBookmark =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkNoLabel =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkTwoLabels =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> <label>Homepage</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkFolderLabel =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google:Search:Page</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkNoFavicon =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmark2Items =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark>"
" <bookmark> "
"<title>MyOtherTitle</title> "
"<url>http://www.google.com/mail</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Mail</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name>"
"<value>http://www.google.com/mail/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1253328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark>"
"</bookmarks>";
static const char* kEmptyString = "";
static const char* kBadBookmarkNoBookmarks =
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoBookmark =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoTitle =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoUrl =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoTimestamp =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoLabels =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
} // namespace toolbar_importer_unittest
// The parsing tests for Toolbar5Importer use the string above. For a
// description of all the tests run please see the comments immediately before
// the string constants above.
TEST(Toolbar5ImporterTest, BookmarkParse) {
XmlReader reader;
std::string bookmark_xml;
std::vector<ProfileWriter::BookmarkEntry> bookmarks;
const GURL url(toolbar_importer_unittest::kUrl);
const GURL other_url(toolbar_importer_unittest::kOtherUrl);
// Test case 1 is parsing a basic bookmark with a single label.
bookmark_xml = toolbar_importer_unittest::kGoodBookmark;
bookmarks.clear();
XmlReader reader1;
EXPECT_TRUE(reader1.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader1, &bookmarks));
EXPECT_EQ(bookmarks.size(), (size_t) 1);
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(url, bookmarks[0].url);
EXPECT_EQ(bookmarks[0].path.size(), (size_t) 2);
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
// Test case 2 is parsing a single bookmark with no label.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkNoLabel;
bookmarks.clear();
XmlReader reader2;
EXPECT_TRUE(reader2.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader2, &bookmarks));
EXPECT_EQ(bookmarks.size(), (size_t) 1);
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(bookmarks[0].url, url);
EXPECT_EQ(bookmarks[0].path.size(), (size_t) 1);
// Test case 3 is parsing a single bookmark with two labels.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkTwoLabels;
bookmarks.clear();
XmlReader reader3;
EXPECT_TRUE(reader3.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader3, &bookmarks));
EXPECT_EQ(bookmarks.size(), (size_t) 2);
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_FALSE(bookmarks[1].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[1].title);
EXPECT_EQ(bookmarks[0].url, url);
EXPECT_EQ(bookmarks[1].url, url);
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
EXPECT_EQ(toolbar_importer_unittest::kFolder2, bookmarks[1].path[1]);
// Test case 4 is parsing a single bookmark which has a label with a colon,
// this test file name translation between Toolbar and Chrome.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkFolderLabel;
bookmarks.clear();
XmlReader reader4;
EXPECT_TRUE(reader4.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader4, &bookmarks));
EXPECT_EQ(bookmarks.size(), (size_t) 1);
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(bookmarks[0].url, url);
EXPECT_EQ(bookmarks[0].path.size(), (size_t) 4);
EXPECT_TRUE(toolbar_importer_unittest::kFolderArray[0] ==
bookmarks[0].path[1]);
EXPECT_TRUE(toolbar_importer_unittest::kFolderArray[1] ==
bookmarks[0].path[2]);
EXPECT_TRUE(toolbar_importer_unittest::kFolderArray[2] ==
bookmarks[0].path[3]);
// Test case 5 is parsing a single bookmark without a favicon URL.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkNoFavicon;
bookmarks.clear();
XmlReader reader5;
EXPECT_TRUE(reader5.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader5, &bookmarks));
EXPECT_EQ(bookmarks.size(), (size_t) 1);
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(bookmarks[0].url, url);
EXPECT_EQ(bookmarks[0].path.size(), (size_t) 2);
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
// Test case 6 is parsing two bookmarks.
bookmark_xml = toolbar_importer_unittest::kGoodBookmark2Items;
bookmarks.clear();
XmlReader reader6;
EXPECT_TRUE(reader6.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader6, &bookmarks));
EXPECT_EQ(bookmarks.size(), (size_t) 2);
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_FALSE(bookmarks[1].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(toolbar_importer_unittest::kOtherTitle, bookmarks[1].title);
EXPECT_EQ(bookmarks[0].url, url);
EXPECT_EQ(bookmarks[1].url, other_url);
EXPECT_EQ(bookmarks[0].path.size(), (size_t) 2);
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
EXPECT_EQ(bookmarks[0].path.size(), (size_t) 2);
EXPECT_EQ(toolbar_importer_unittest::kOtherFolder, bookmarks[1].path[1]);
// Test case 7 is parsing an empty string for bookmarks.
bookmark_xml = toolbar_importer_unittest::kEmptyString;
bookmarks.clear();
XmlReader reader7;
EXPECT_FALSE(reader7.Load(bookmark_xml));
// Test case 8 is testing the error when no <bookmarks> section is present.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoBookmarks;
bookmarks.clear();
XmlReader reader8;
EXPECT_TRUE(reader8.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader8, &bookmarks));
// Test case 9 tests when no <bookmark> section is present.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoBookmark;
bookmarks.clear();
XmlReader reader9;
EXPECT_TRUE(reader9.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader9, &bookmarks));
// Test case 10 tests when a bookmark has no <title> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoTitle;
bookmarks.clear();
XmlReader reader10;
EXPECT_TRUE(reader10.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader10, &bookmarks));
// Test case 11 tests when a bookmark has no <url> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoUrl;
bookmarks.clear();
XmlReader reader11;
EXPECT_TRUE(reader11.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader11, &bookmarks));
// Test case 12 tests when a bookmark has no <timestamp> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoTimestamp;
bookmarks.clear();
XmlReader reader12;
EXPECT_TRUE(reader12.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader12, &bookmarks));
// Test case 13 tests when a bookmark has no <labels> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoLabels;
bookmarks.clear();
XmlReader reader13;
EXPECT_TRUE(reader13.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader13, &bookmarks));
}
Try to make Mac unittest crash into a failure
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@16686 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2006-2008 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 "testing/gtest/include/gtest/gtest.h"
#include <string>
#include <vector>
#include "chrome/browser/importer/importer.h"
#include "chrome/browser/importer/toolbar_importer.h"
#include "chrome/common/libxml_utils.h"
#include "googleurl/src/gurl.h"
namespace toolbar_importer_unittest {
static const wchar_t* kTitle = L"MyTitle";
static const char* kUrl = "http://www.google.com/";
static const wchar_t* kFolder = L"Google";
static const wchar_t* kFolder2 = L"Homepage";
static const wchar_t* kFolderArray[3] = {L"Google", L"Search", L"Page"};
static const wchar_t* kOtherTitle = L"MyOtherTitle";
static const char* kOtherUrl = "http://www.google.com/mail";
static const wchar_t* kOtherFolder = L"Mail";
// Since the following is very dense to read I enumerate the test cases here.
// 1. Correct bookmark structure with one label.
// 2. Correct bookmark structure with no labels.
// 3. Correct bookmark structure with two labels.
// 4. Correct bookmark structure with a folder->label translation by toolbar.
// 5. Correct bookmark structure with no favicon.
// 6. Two correct bookmarks.
// The following are error cases by removing sections from the xml:
// 7. Empty string passed as xml.
// 8. No <bookmarks> section in the xml.
// 9. No <bookmark> section below the <bookmarks> section.
// 10. No <title> in a <bookmark> section.
// 11. No <url> in a <bookmark> section.
// 12. No <timestamp> in a <bookmark> section.
// 13. No <labels> in a <bookmark> section.
static const char* kGoodBookmark =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkNoLabel =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkTwoLabels =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> <label>Homepage</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkFolderLabel =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google:Search:Page</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmarkNoFavicon =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kGoodBookmark2Items =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark>"
" <bookmark> "
"<title>MyOtherTitle</title> "
"<url>http://www.google.com/mail</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Mail</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name>"
"<value>http://www.google.com/mail/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1253328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark>"
"</bookmarks>";
static const char* kEmptyString = "";
static const char* kBadBookmarkNoBookmarks =
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoBookmark =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoTitle =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoUrl =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoTimestamp =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<labels> <label>Google</label> </labels> "
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
static const char* kBadBookmarkNoLabels =
"<?xml version=\"1.0\" ?> <xml_api_reply version=\"1\"> <bookmarks>"
" <bookmark> "
"<title>MyTitle</title> "
"<url>http://www.google.com/</url> "
"<timestamp>1153328691085181</timestamp> "
"<id>N123nasdf239</id> <notebook_id>Bxxxxxxx</notebook_id> "
"<section_id>Sxxxxxx</section_id> <has_highlight>0</has_highlight>"
"<attributes> "
"<attribute> "
"<name>favicon_url</name> <value>http://www.google.com/favicon.ico</value> "
"</attribute> "
"<attribute> "
"<name>favicon_timestamp</name> <value>1153328653</value> "
"</attribute> "
"<attribute> <name>notebook_name</name> <value>My notebook 0</value> "
"</attribute> "
"<attribute> <name>section_name</name> <value>My section 0 "
"</value> </attribute> </attributes> "
"</bookmark> </bookmarks>";
} // namespace toolbar_importer_unittest
// The parsing tests for Toolbar5Importer use the string above. For a
// description of all the tests run please see the comments immediately before
// the string constants above.
TEST(Toolbar5ImporterTest, BookmarkParse) {
XmlReader reader;
std::string bookmark_xml;
std::vector<ProfileWriter::BookmarkEntry> bookmarks;
const GURL url(toolbar_importer_unittest::kUrl);
const GURL other_url(toolbar_importer_unittest::kOtherUrl);
// Test case 1 is parsing a basic bookmark with a single label.
bookmark_xml = toolbar_importer_unittest::kGoodBookmark;
bookmarks.clear();
XmlReader reader1;
EXPECT_TRUE(reader1.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader1, &bookmarks));
ASSERT_EQ(1U, bookmarks.size());
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(url, bookmarks[0].url);
ASSERT_EQ(2U, bookmarks[0].path.size());
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
// Test case 2 is parsing a single bookmark with no label.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkNoLabel;
bookmarks.clear();
XmlReader reader2;
EXPECT_TRUE(reader2.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader2, &bookmarks));
ASSERT_EQ(1U, bookmarks.size());
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(url, bookmarks[0].url);
EXPECT_EQ(1U, bookmarks[0].path.size());
// Test case 3 is parsing a single bookmark with two labels.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkTwoLabels;
bookmarks.clear();
XmlReader reader3;
EXPECT_TRUE(reader3.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader3, &bookmarks));
ASSERT_EQ(2U, bookmarks.size());
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_FALSE(bookmarks[1].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[1].title);
EXPECT_EQ(url, bookmarks[0].url);
EXPECT_EQ(url, bookmarks[1].url);
ASSERT_EQ(2U, bookmarks[0].path.size());
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
ASSERT_EQ(2U, bookmarks[1].path.size());
EXPECT_EQ(toolbar_importer_unittest::kFolder2, bookmarks[1].path[1]);
// Test case 4 is parsing a single bookmark which has a label with a colon,
// this test file name translation between Toolbar and Chrome.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkFolderLabel;
bookmarks.clear();
XmlReader reader4;
EXPECT_TRUE(reader4.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader4, &bookmarks));
ASSERT_EQ(1U, bookmarks.size());
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(url, bookmarks[0].url);
ASSERT_EQ(4U, bookmarks[0].path.size());
EXPECT_EQ(std::wstring(toolbar_importer_unittest::kFolderArray[0]),
bookmarks[0].path[1]);
EXPECT_EQ(std::wstring(toolbar_importer_unittest::kFolderArray[1]),
bookmarks[0].path[2]);
EXPECT_EQ(std::wstring(toolbar_importer_unittest::kFolderArray[2]),
bookmarks[0].path[3]);
// Test case 5 is parsing a single bookmark without a favicon URL.
bookmark_xml = toolbar_importer_unittest::kGoodBookmarkNoFavicon;
bookmarks.clear();
XmlReader reader5;
EXPECT_TRUE(reader5.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader5, &bookmarks));
ASSERT_EQ(1U, bookmarks.size());
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(url, bookmarks[0].url);
ASSERT_EQ(2U, bookmarks[0].path.size());
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
// Test case 6 is parsing two bookmarks.
bookmark_xml = toolbar_importer_unittest::kGoodBookmark2Items;
bookmarks.clear();
XmlReader reader6;
EXPECT_TRUE(reader6.Load(bookmark_xml));
EXPECT_TRUE(Toolbar5Importer::ParseBookmarksFromReader(&reader6, &bookmarks));
ASSERT_EQ(2U, bookmarks.size());
EXPECT_FALSE(bookmarks[0].in_toolbar);
EXPECT_FALSE(bookmarks[1].in_toolbar);
EXPECT_EQ(toolbar_importer_unittest::kTitle, bookmarks[0].title);
EXPECT_EQ(toolbar_importer_unittest::kOtherTitle, bookmarks[1].title);
EXPECT_EQ(url, bookmarks[0].url);
EXPECT_EQ(other_url, bookmarks[1].url);
ASSERT_EQ(2U, bookmarks[0].path.size());
EXPECT_EQ(toolbar_importer_unittest::kFolder, bookmarks[0].path[1]);
ASSERT_EQ(2U, bookmarks[1].path.size());
EXPECT_EQ(toolbar_importer_unittest::kOtherFolder, bookmarks[1].path[1]);
// Test case 7 is parsing an empty string for bookmarks.
bookmark_xml = toolbar_importer_unittest::kEmptyString;
bookmarks.clear();
XmlReader reader7;
EXPECT_FALSE(reader7.Load(bookmark_xml));
// Test case 8 is testing the error when no <bookmarks> section is present.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoBookmarks;
bookmarks.clear();
XmlReader reader8;
EXPECT_TRUE(reader8.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader8,
&bookmarks));
// Test case 9 tests when no <bookmark> section is present.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoBookmark;
bookmarks.clear();
XmlReader reader9;
EXPECT_TRUE(reader9.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader9,
&bookmarks));
// Test case 10 tests when a bookmark has no <title> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoTitle;
bookmarks.clear();
XmlReader reader10;
EXPECT_TRUE(reader10.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader10,
&bookmarks));
// Test case 11 tests when a bookmark has no <url> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoUrl;
bookmarks.clear();
XmlReader reader11;
EXPECT_TRUE(reader11.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader11,
&bookmarks));
// Test case 12 tests when a bookmark has no <timestamp> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoTimestamp;
bookmarks.clear();
XmlReader reader12;
EXPECT_TRUE(reader12.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader12,
&bookmarks));
// Test case 13 tests when a bookmark has no <labels> section.
bookmark_xml = toolbar_importer_unittest::kBadBookmarkNoLabels;
bookmarks.clear();
XmlReader reader13;
EXPECT_TRUE(reader13.Load(bookmark_xml));
EXPECT_FALSE(Toolbar5Importer::ParseBookmarksFromReader(&reader13,
&bookmarks));
}
|
// 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 "chrome/browser/storage_monitor/media_storage_util.h"
#include <vector>
#include "base/callback.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/storage_monitor/media_device_notifications_utils.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "content/public/browser/browser_thread.h"
#if defined(OS_LINUX) // Implies OS_CHROMEOS
#include "chrome/browser/storage_monitor/media_transfer_protocol_device_observer_linux.h"
#endif
using content::BrowserThread;
const char kRootPath[] = "/";
namespace chrome {
namespace {
// MediaDeviceNotification.DeviceInfo histogram values.
enum DeviceInfoHistogramBuckets {
MASS_STORAGE_DEVICE_NAME_AND_UUID_AVAILABLE,
MASS_STORAGE_DEVICE_UUID_MISSING,
MASS_STORAGE_DEVICE_NAME_MISSING,
MASS_STORAGE_DEVICE_NAME_AND_UUID_MISSING,
MTP_STORAGE_DEVICE_NAME_AND_UUID_AVAILABLE,
MTP_STORAGE_DEVICE_UUID_MISSING,
MTP_STORAGE_DEVICE_NAME_MISSING,
MTP_STORAGE_DEVICE_NAME_AND_UUID_MISSING,
DEVICE_INFO_BUCKET_BOUNDARY
};
// Prefix constants for different device id spaces.
const char kRemovableMassStorageWithDCIMPrefix[] = "dcim:";
const char kRemovableMassStorageNoDCIMPrefix[] = "nodcim:";
const char kFixedMassStoragePrefix[] = "path:";
const char kMtpPtpPrefix[] = "mtp:";
const char kMacImageCapture[] = "ic:";
void ValidatePathOnFileThread(
const base::FilePath& path,
const MediaStorageUtil::BoolCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(callback, file_util::PathExists(path)));
}
typedef std::vector<StorageInfo> StorageInfoList;
bool IsRemovableStorageAttached(const std::string& id) {
StorageInfoList devices = StorageMonitor::GetInstance()->GetAttachedStorage();
for (StorageInfoList::const_iterator it = devices.begin();
it != devices.end(); ++it) {
if (it->device_id == id)
return true;
}
return false;
}
base::FilePath::StringType FindRemovableStorageLocationById(
const std::string& device_id) {
StorageInfoList devices = StorageMonitor::GetInstance()->GetAttachedStorage();
for (StorageInfoList::const_iterator it = devices.begin();
it != devices.end(); ++it) {
if (it->device_id == device_id)
return it->location;
}
return base::FilePath::StringType();
}
void FilterAttachedDevicesOnFileThread(MediaStorageUtil::DeviceIdSet* devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
MediaStorageUtil::DeviceIdSet missing_devices;
for (MediaStorageUtil::DeviceIdSet::const_iterator it = devices->begin();
it != devices->end();
++it) {
MediaStorageUtil::Type type;
std::string unique_id;
if (!MediaStorageUtil::CrackDeviceId(*it, &type, &unique_id)) {
missing_devices.insert(*it);
continue;
}
if (type == MediaStorageUtil::FIXED_MASS_STORAGE) {
if (!file_util::PathExists(base::FilePath::FromUTF8Unsafe(unique_id)))
missing_devices.insert(*it);
continue;
}
if (!IsRemovableStorageAttached(*it))
missing_devices.insert(*it);
}
for (MediaStorageUtil::DeviceIdSet::const_iterator it =
missing_devices.begin();
it != missing_devices.end();
++it) {
devices->erase(*it);
}
}
// For a device with |device_name| and a relative path |sub_folder|, construct
// a display name. If |sub_folder| is empty, then just return |device_name|.
string16 GetDisplayNameForSubFolder(const string16& device_name,
const base::FilePath& sub_folder) {
if (sub_folder.empty())
return device_name;
return (sub_folder.BaseName().LossyDisplayName() +
ASCIIToUTF16(" - ") +
device_name);
}
} // namespace
// static
std::string MediaStorageUtil::MakeDeviceId(Type type,
const std::string& unique_id) {
DCHECK(!unique_id.empty());
switch (type) {
case REMOVABLE_MASS_STORAGE_WITH_DCIM:
return std::string(kRemovableMassStorageWithDCIMPrefix) + unique_id;
case REMOVABLE_MASS_STORAGE_NO_DCIM:
return std::string(kRemovableMassStorageNoDCIMPrefix) + unique_id;
case FIXED_MASS_STORAGE:
return std::string(kFixedMassStoragePrefix) + unique_id;
case MTP_OR_PTP:
return std::string(kMtpPtpPrefix) + unique_id;
case MAC_IMAGE_CAPTURE:
return std::string(kMacImageCapture) + unique_id;
}
NOTREACHED();
return std::string();
}
// static
bool MediaStorageUtil::CrackDeviceId(const std::string& device_id,
Type* type, std::string* unique_id) {
size_t prefix_length = device_id.find_first_of(':');
std::string prefix = prefix_length != std::string::npos ?
device_id.substr(0, prefix_length + 1) : "";
Type found_type;
if (prefix == kRemovableMassStorageWithDCIMPrefix) {
found_type = REMOVABLE_MASS_STORAGE_WITH_DCIM;
} else if (prefix == kRemovableMassStorageNoDCIMPrefix) {
found_type = REMOVABLE_MASS_STORAGE_NO_DCIM;
} else if (prefix == kFixedMassStoragePrefix) {
found_type = FIXED_MASS_STORAGE;
} else if (prefix == kMtpPtpPrefix) {
found_type = MTP_OR_PTP;
} else if (prefix == kMacImageCapture) {
found_type = MAC_IMAGE_CAPTURE;
} else {
NOTREACHED();
return false;
}
if (type)
*type = found_type;
if (unique_id)
*unique_id = device_id.substr(prefix_length + 1);
return true;
}
// static
bool MediaStorageUtil::IsMediaDevice(const std::string& device_id) {
Type type;
return CrackDeviceId(device_id, &type, NULL) &&
(type == REMOVABLE_MASS_STORAGE_WITH_DCIM || type == MTP_OR_PTP ||
type == MAC_IMAGE_CAPTURE);
}
// static
bool MediaStorageUtil::IsRemovableDevice(const std::string& device_id) {
Type type;
return CrackDeviceId(device_id, &type, NULL) && type != FIXED_MASS_STORAGE;
}
// static
bool MediaStorageUtil::IsMassStorageDevice(const std::string& device_id) {
Type type;
return CrackDeviceId(device_id, &type, NULL) &&
(type == REMOVABLE_MASS_STORAGE_WITH_DCIM ||
type == REMOVABLE_MASS_STORAGE_NO_DCIM ||
type == FIXED_MASS_STORAGE);
}
// static
bool MediaStorageUtil::CanCreateFileSystem(const std::string& device_id,
const base::FilePath& path) {
Type type;
if (!CrackDeviceId(device_id, &type, NULL))
return false;
if (type == MAC_IMAGE_CAPTURE)
return true;
return path.IsAbsolute() && !path.ReferencesParent();
}
// static
void MediaStorageUtil::IsDeviceAttached(const std::string& device_id,
const BoolCallback& callback) {
Type type;
std::string unique_id;
if (!CrackDeviceId(device_id, &type, &unique_id)) {
callback.Run(false);
return;
}
if (type == FIXED_MASS_STORAGE) {
// For this type, the unique_id is the path.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&ValidatePathOnFileThread,
base::FilePath::FromUTF8Unsafe(unique_id),
callback));
} else {
DCHECK(type == MTP_OR_PTP ||
type == REMOVABLE_MASS_STORAGE_WITH_DCIM ||
type == REMOVABLE_MASS_STORAGE_NO_DCIM);
// We should be able to find removable storage.
callback.Run(IsRemovableStorageAttached(device_id));
}
}
// static
void MediaStorageUtil::FilterAttachedDevices(DeviceIdSet* devices,
const base::Closure& done) {
if (BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
FilterAttachedDevicesOnFileThread(devices);
done.Run();
return;
}
BrowserThread::PostTaskAndReply(BrowserThread::FILE,
FROM_HERE,
base::Bind(&FilterAttachedDevicesOnFileThread,
devices),
done);
}
// TODO(kmadhusu) Write unit tests for GetDeviceInfoFromPath().
bool MediaStorageUtil::GetDeviceInfoFromPath(const base::FilePath& path,
StorageInfo* device_info,
base::FilePath* relative_path) {
if (!path.IsAbsolute())
return false;
bool found_device = false;
StorageInfo info;
StorageMonitor* monitor = StorageMonitor::GetInstance();
found_device = monitor->GetStorageInfoForPath(path, &info);
// TODO(gbillock): Move this upstream into the RemovableStorageNotifications
// implementation to handle in its GetDeviceInfoForPath call.
#if defined(OS_LINUX)
if (!found_device) {
MediaTransferProtocolDeviceObserverLinux* mtp_manager =
MediaTransferProtocolDeviceObserverLinux::GetInstance();
found_device = mtp_manager->GetStorageInfoForPath(path, &info);
}
#endif
if (found_device && IsRemovableDevice(info.device_id)) {
base::FilePath sub_folder_path;
if (path.value() != info.location) {
base::FilePath device_path(info.location);
bool success = device_path.AppendRelativePath(path, &sub_folder_path);
DCHECK(success);
}
// TODO(gbillock): Don't do this. Leave for clients to do.
#if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX) // Implies OS_CHROMEOS
info.name = GetDisplayNameForDevice(
monitor->GetStorageSize(info.location),
GetDisplayNameForSubFolder(info.name, sub_folder_path));
#endif
if (device_info)
*device_info = info;
if (relative_path)
*relative_path = sub_folder_path;
return true;
}
// On Posix systems, there's one root so any absolute path could be valid.
#if !defined(OS_POSIX)
if (!found_device)
return false;
#endif
// Handle non-removable devices. Note: this is just overwriting
// good values from RemovableStorageNotifications.
// TODO(gbillock): Make sure return values from that class are definitive,
// and don't do this here.
info.device_id = MakeDeviceId(FIXED_MASS_STORAGE, path.AsUTF8Unsafe());
info.name = path.BaseName().LossyDisplayName();
if (device_info)
*device_info = info;
if (relative_path)
*relative_path = base::FilePath();
return true;
}
// static
base::FilePath MediaStorageUtil::FindDevicePathById(
const std::string& device_id) {
Type type;
std::string unique_id;
if (!CrackDeviceId(device_id, &type, &unique_id))
return base::FilePath();
if (type == FIXED_MASS_STORAGE) {
// For this type, the unique_id is the path.
return base::FilePath::FromUTF8Unsafe(unique_id);
}
// For ImageCapture, the synthetic filesystem will be rooted at a fake
// top-level directory which is the device_id.
if (type == MAC_IMAGE_CAPTURE) {
#if !defined(OS_WIN)
return base::FilePath(kRootPath + device_id);
#endif
}
DCHECK(type == MTP_OR_PTP ||
type == REMOVABLE_MASS_STORAGE_WITH_DCIM ||
type == REMOVABLE_MASS_STORAGE_NO_DCIM);
return base::FilePath(FindRemovableStorageLocationById(device_id));
}
// static
void MediaStorageUtil::RecordDeviceInfoHistogram(bool mass_storage,
const std::string& device_uuid,
const string16& device_name) {
unsigned int event_number = 0;
if (!mass_storage)
event_number = 4;
if (device_name.empty())
event_number += 2;
if (device_uuid.empty())
event_number += 1;
enum DeviceInfoHistogramBuckets event =
static_cast<enum DeviceInfoHistogramBuckets>(event_number);
if (event >= DEVICE_INFO_BUCKET_BOUNDARY) {
NOTREACHED();
return;
}
UMA_HISTOGRAM_ENUMERATION("MediaDeviceNotifications.DeviceInfo", event,
DEVICE_INFO_BUCKET_BOUNDARY);
}
} // namespace chrome
Cleanup: Move a global variable into an anonymous namespace in MediaStorageUtil.
Review URL: https://chromiumcodereview.appspot.com/12508005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@186510 0039d316-1c4b-4281-b951-d872f2087c98
// 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 "chrome/browser/storage_monitor/media_storage_util.h"
#include <vector>
#include "base/callback.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/storage_monitor/media_device_notifications_utils.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "content/public/browser/browser_thread.h"
#if defined(OS_LINUX) // Implies OS_CHROMEOS
#include "chrome/browser/storage_monitor/media_transfer_protocol_device_observer_linux.h"
#endif
using content::BrowserThread;
namespace chrome {
namespace {
// MediaDeviceNotification.DeviceInfo histogram values.
enum DeviceInfoHistogramBuckets {
MASS_STORAGE_DEVICE_NAME_AND_UUID_AVAILABLE,
MASS_STORAGE_DEVICE_UUID_MISSING,
MASS_STORAGE_DEVICE_NAME_MISSING,
MASS_STORAGE_DEVICE_NAME_AND_UUID_MISSING,
MTP_STORAGE_DEVICE_NAME_AND_UUID_AVAILABLE,
MTP_STORAGE_DEVICE_UUID_MISSING,
MTP_STORAGE_DEVICE_NAME_MISSING,
MTP_STORAGE_DEVICE_NAME_AND_UUID_MISSING,
DEVICE_INFO_BUCKET_BOUNDARY
};
// Prefix constants for different device id spaces.
const char kRemovableMassStorageWithDCIMPrefix[] = "dcim:";
const char kRemovableMassStorageNoDCIMPrefix[] = "nodcim:";
const char kFixedMassStoragePrefix[] = "path:";
const char kMtpPtpPrefix[] = "mtp:";
const char kMacImageCapture[] = "ic:";
#if !defined(OS_WIN)
const char kRootPath[] = "/";
#endif
void ValidatePathOnFileThread(
const base::FilePath& path,
const MediaStorageUtil::BoolCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(callback, file_util::PathExists(path)));
}
typedef std::vector<StorageInfo> StorageInfoList;
bool IsRemovableStorageAttached(const std::string& id) {
StorageInfoList devices = StorageMonitor::GetInstance()->GetAttachedStorage();
for (StorageInfoList::const_iterator it = devices.begin();
it != devices.end(); ++it) {
if (it->device_id == id)
return true;
}
return false;
}
base::FilePath::StringType FindRemovableStorageLocationById(
const std::string& device_id) {
StorageInfoList devices = StorageMonitor::GetInstance()->GetAttachedStorage();
for (StorageInfoList::const_iterator it = devices.begin();
it != devices.end(); ++it) {
if (it->device_id == device_id)
return it->location;
}
return base::FilePath::StringType();
}
void FilterAttachedDevicesOnFileThread(MediaStorageUtil::DeviceIdSet* devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
MediaStorageUtil::DeviceIdSet missing_devices;
for (MediaStorageUtil::DeviceIdSet::const_iterator it = devices->begin();
it != devices->end();
++it) {
MediaStorageUtil::Type type;
std::string unique_id;
if (!MediaStorageUtil::CrackDeviceId(*it, &type, &unique_id)) {
missing_devices.insert(*it);
continue;
}
if (type == MediaStorageUtil::FIXED_MASS_STORAGE) {
if (!file_util::PathExists(base::FilePath::FromUTF8Unsafe(unique_id)))
missing_devices.insert(*it);
continue;
}
if (!IsRemovableStorageAttached(*it))
missing_devices.insert(*it);
}
for (MediaStorageUtil::DeviceIdSet::const_iterator it =
missing_devices.begin();
it != missing_devices.end();
++it) {
devices->erase(*it);
}
}
// For a device with |device_name| and a relative path |sub_folder|, construct
// a display name. If |sub_folder| is empty, then just return |device_name|.
string16 GetDisplayNameForSubFolder(const string16& device_name,
const base::FilePath& sub_folder) {
if (sub_folder.empty())
return device_name;
return (sub_folder.BaseName().LossyDisplayName() +
ASCIIToUTF16(" - ") +
device_name);
}
} // namespace
// static
std::string MediaStorageUtil::MakeDeviceId(Type type,
const std::string& unique_id) {
DCHECK(!unique_id.empty());
switch (type) {
case REMOVABLE_MASS_STORAGE_WITH_DCIM:
return std::string(kRemovableMassStorageWithDCIMPrefix) + unique_id;
case REMOVABLE_MASS_STORAGE_NO_DCIM:
return std::string(kRemovableMassStorageNoDCIMPrefix) + unique_id;
case FIXED_MASS_STORAGE:
return std::string(kFixedMassStoragePrefix) + unique_id;
case MTP_OR_PTP:
return std::string(kMtpPtpPrefix) + unique_id;
case MAC_IMAGE_CAPTURE:
return std::string(kMacImageCapture) + unique_id;
}
NOTREACHED();
return std::string();
}
// static
bool MediaStorageUtil::CrackDeviceId(const std::string& device_id,
Type* type, std::string* unique_id) {
size_t prefix_length = device_id.find_first_of(':');
std::string prefix = prefix_length != std::string::npos ?
device_id.substr(0, prefix_length + 1) : "";
Type found_type;
if (prefix == kRemovableMassStorageWithDCIMPrefix) {
found_type = REMOVABLE_MASS_STORAGE_WITH_DCIM;
} else if (prefix == kRemovableMassStorageNoDCIMPrefix) {
found_type = REMOVABLE_MASS_STORAGE_NO_DCIM;
} else if (prefix == kFixedMassStoragePrefix) {
found_type = FIXED_MASS_STORAGE;
} else if (prefix == kMtpPtpPrefix) {
found_type = MTP_OR_PTP;
} else if (prefix == kMacImageCapture) {
found_type = MAC_IMAGE_CAPTURE;
} else {
NOTREACHED();
return false;
}
if (type)
*type = found_type;
if (unique_id)
*unique_id = device_id.substr(prefix_length + 1);
return true;
}
// static
bool MediaStorageUtil::IsMediaDevice(const std::string& device_id) {
Type type;
return CrackDeviceId(device_id, &type, NULL) &&
(type == REMOVABLE_MASS_STORAGE_WITH_DCIM || type == MTP_OR_PTP ||
type == MAC_IMAGE_CAPTURE);
}
// static
bool MediaStorageUtil::IsRemovableDevice(const std::string& device_id) {
Type type;
return CrackDeviceId(device_id, &type, NULL) && type != FIXED_MASS_STORAGE;
}
// static
bool MediaStorageUtil::IsMassStorageDevice(const std::string& device_id) {
Type type;
return CrackDeviceId(device_id, &type, NULL) &&
(type == REMOVABLE_MASS_STORAGE_WITH_DCIM ||
type == REMOVABLE_MASS_STORAGE_NO_DCIM ||
type == FIXED_MASS_STORAGE);
}
// static
bool MediaStorageUtil::CanCreateFileSystem(const std::string& device_id,
const base::FilePath& path) {
Type type;
if (!CrackDeviceId(device_id, &type, NULL))
return false;
if (type == MAC_IMAGE_CAPTURE)
return true;
return path.IsAbsolute() && !path.ReferencesParent();
}
// static
void MediaStorageUtil::IsDeviceAttached(const std::string& device_id,
const BoolCallback& callback) {
Type type;
std::string unique_id;
if (!CrackDeviceId(device_id, &type, &unique_id)) {
callback.Run(false);
return;
}
if (type == FIXED_MASS_STORAGE) {
// For this type, the unique_id is the path.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&ValidatePathOnFileThread,
base::FilePath::FromUTF8Unsafe(unique_id),
callback));
} else {
DCHECK(type == MTP_OR_PTP ||
type == REMOVABLE_MASS_STORAGE_WITH_DCIM ||
type == REMOVABLE_MASS_STORAGE_NO_DCIM);
// We should be able to find removable storage.
callback.Run(IsRemovableStorageAttached(device_id));
}
}
// static
void MediaStorageUtil::FilterAttachedDevices(DeviceIdSet* devices,
const base::Closure& done) {
if (BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
FilterAttachedDevicesOnFileThread(devices);
done.Run();
return;
}
BrowserThread::PostTaskAndReply(BrowserThread::FILE,
FROM_HERE,
base::Bind(&FilterAttachedDevicesOnFileThread,
devices),
done);
}
// TODO(kmadhusu) Write unit tests for GetDeviceInfoFromPath().
bool MediaStorageUtil::GetDeviceInfoFromPath(const base::FilePath& path,
StorageInfo* device_info,
base::FilePath* relative_path) {
if (!path.IsAbsolute())
return false;
bool found_device = false;
StorageInfo info;
StorageMonitor* monitor = StorageMonitor::GetInstance();
found_device = monitor->GetStorageInfoForPath(path, &info);
// TODO(gbillock): Move this upstream into the RemovableStorageNotifications
// implementation to handle in its GetDeviceInfoForPath call.
#if defined(OS_LINUX)
if (!found_device) {
MediaTransferProtocolDeviceObserverLinux* mtp_manager =
MediaTransferProtocolDeviceObserverLinux::GetInstance();
found_device = mtp_manager->GetStorageInfoForPath(path, &info);
}
#endif
if (found_device && IsRemovableDevice(info.device_id)) {
base::FilePath sub_folder_path;
if (path.value() != info.location) {
base::FilePath device_path(info.location);
bool success = device_path.AppendRelativePath(path, &sub_folder_path);
DCHECK(success);
}
// TODO(gbillock): Don't do this. Leave for clients to do.
#if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX) // Implies OS_CHROMEOS
info.name = GetDisplayNameForDevice(
monitor->GetStorageSize(info.location),
GetDisplayNameForSubFolder(info.name, sub_folder_path));
#endif
if (device_info)
*device_info = info;
if (relative_path)
*relative_path = sub_folder_path;
return true;
}
// On Posix systems, there's one root so any absolute path could be valid.
#if !defined(OS_POSIX)
if (!found_device)
return false;
#endif
// Handle non-removable devices. Note: this is just overwriting
// good values from RemovableStorageNotifications.
// TODO(gbillock): Make sure return values from that class are definitive,
// and don't do this here.
info.device_id = MakeDeviceId(FIXED_MASS_STORAGE, path.AsUTF8Unsafe());
info.name = path.BaseName().LossyDisplayName();
if (device_info)
*device_info = info;
if (relative_path)
*relative_path = base::FilePath();
return true;
}
// static
base::FilePath MediaStorageUtil::FindDevicePathById(
const std::string& device_id) {
Type type;
std::string unique_id;
if (!CrackDeviceId(device_id, &type, &unique_id))
return base::FilePath();
if (type == FIXED_MASS_STORAGE) {
// For this type, the unique_id is the path.
return base::FilePath::FromUTF8Unsafe(unique_id);
}
// For ImageCapture, the synthetic filesystem will be rooted at a fake
// top-level directory which is the device_id.
if (type == MAC_IMAGE_CAPTURE) {
#if !defined(OS_WIN)
return base::FilePath(kRootPath + device_id);
#endif
}
DCHECK(type == MTP_OR_PTP ||
type == REMOVABLE_MASS_STORAGE_WITH_DCIM ||
type == REMOVABLE_MASS_STORAGE_NO_DCIM);
return base::FilePath(FindRemovableStorageLocationById(device_id));
}
// static
void MediaStorageUtil::RecordDeviceInfoHistogram(bool mass_storage,
const std::string& device_uuid,
const string16& device_name) {
unsigned int event_number = 0;
if (!mass_storage)
event_number = 4;
if (device_name.empty())
event_number += 2;
if (device_uuid.empty())
event_number += 1;
enum DeviceInfoHistogramBuckets event =
static_cast<enum DeviceInfoHistogramBuckets>(event_number);
if (event >= DEVICE_INFO_BUCKET_BOUNDARY) {
NOTREACHED();
return;
}
UMA_HISTOGRAM_ENUMERATION("MediaDeviceNotifications.DeviceInfo", event,
DEVICE_INFO_BUCKET_BOUNDARY);
}
} // namespace chrome
|
// Copyright 2013 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 "chrome/browser/ui/views/frame/global_menu_bar_x11.h"
#include <dlfcn.h>
#include <glib-object.h>
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/history/top_sites.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/tab_restore_service.h"
#include "chrome/browser/sessions/tab_restore_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
#include "chrome/browser/ui/views/frame/browser_desktop_root_window_host_x11.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_source.h"
#include "grit/generated_resources.h"
#include "ui/base/accelerators/menu_label_accelerator_util_linux.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/events/keycodes/keyboard_code_conversion_x.h"
#include "ui/gfx/text_elider.h"
// libdbusmenu-glib types
typedef struct _DbusmenuMenuitem DbusmenuMenuitem;
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_new_func)();
typedef bool (*dbusmenu_menuitem_child_add_position_func)(
DbusmenuMenuitem* parent,
DbusmenuMenuitem* child,
unsigned int position);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_child_append_func)(
DbusmenuMenuitem* parent,
DbusmenuMenuitem* child);
typedef bool (*dbusmenu_menuitem_child_delete_func)(
DbusmenuMenuitem* parent,
DbusmenuMenuitem* child);
typedef GList* (*dbusmenu_menuitem_get_children_func)(
DbusmenuMenuitem* item);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_func)(
DbusmenuMenuitem* item,
const char* property,
const char* value);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_variant_func)(
DbusmenuMenuitem* item,
const char* property,
GVariant* value);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_bool_func)(
DbusmenuMenuitem* item,
const char* property,
bool value);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_int_func)(
DbusmenuMenuitem* item,
const char* property,
int value);
typedef struct _DbusmenuServer DbusmenuServer;
typedef DbusmenuServer* (*dbusmenu_server_new_func)(const char* object);
typedef void (*dbusmenu_server_set_root_func)(DbusmenuServer* self,
DbusmenuMenuitem* root);
// A line in the static menu definitions.
struct GlobalMenuBarCommand {
int str_id;
int command;
int tag;
};
namespace {
// Retrieved functions from libdbusmenu-glib.
// DbusmenuMenuItem methods:
dbusmenu_menuitem_new_func menuitem_new = NULL;
dbusmenu_menuitem_get_children_func menuitem_get_children = NULL;
dbusmenu_menuitem_child_add_position_func menuitem_child_add_position = NULL;
dbusmenu_menuitem_child_append_func menuitem_child_append = NULL;
dbusmenu_menuitem_child_delete_func menuitem_child_delete = NULL;
dbusmenu_menuitem_property_set_func menuitem_property_set = NULL;
dbusmenu_menuitem_property_set_variant_func menuitem_property_set_variant =
NULL;
dbusmenu_menuitem_property_set_bool_func menuitem_property_set_bool = NULL;
dbusmenu_menuitem_property_set_int_func menuitem_property_set_int = NULL;
// DbusmenuServer methods:
dbusmenu_server_new_func server_new = NULL;
dbusmenu_server_set_root_func server_set_root = NULL;
// Properties that we set on menu items:
const char kPropertyEnabled[] = "enabled";
const char kPropertyLabel[] = "label";
const char kPropertyShortcut[] = "shortcut";
const char kPropertyType[] = "type";
const char kPropertyToggleType[] = "toggle-type";
const char kPropertyToggleState[] = "toggle-state";
const char kPropertyVisible[] = "visible";
const char kTypeCheckmark[] = "checkmark";
const char kTypeSeparator[] = "separator";
// Data set on GObjectgs.
const char kTypeTag[] = "type-tag";
const char kHistoryItem[] = "history-item";
// The maximum number of most visited items to display.
const unsigned int kMostVisitedCount = 8;
// The number of recently closed items to get.
const unsigned int kRecentlyClosedCount = 8;
// Menus more than this many chars long will get trimmed.
const int kMaximumMenuWidthInChars = 50;
// Constants used in menu definitions.
const int MENU_SEPARATOR =-1;
const int MENU_END = -2;
const int MENU_DISABLED_ID = -3;
// These tag values are used to refer to menu itesm.
const int TAG_NORMAL = 0;
const int TAG_MOST_VISITED = 1;
const int TAG_RECENTLY_CLOSED = 2;
const int TAG_MOST_VISITED_HEADER = 3;
const int TAG_RECENTLY_CLOSED_HEADER = 4;
GlobalMenuBarCommand file_menu[] = {
{ IDS_NEW_TAB, IDC_NEW_TAB },
{ IDS_NEW_WINDOW, IDC_NEW_WINDOW },
{ IDS_NEW_INCOGNITO_WINDOW, IDC_NEW_INCOGNITO_WINDOW },
{ IDS_REOPEN_CLOSED_TABS_LINUX, IDC_RESTORE_TAB },
{ IDS_OPEN_FILE_LINUX, IDC_OPEN_FILE },
{ IDS_OPEN_LOCATION_LINUX, IDC_FOCUS_LOCATION },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_CREATE_SHORTCUTS, IDC_CREATE_SHORTCUTS },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_CLOSE_WINDOW_LINUX, IDC_CLOSE_WINDOW },
{ IDS_CLOSE_TAB_LINUX, IDC_CLOSE_TAB },
{ IDS_SAVE_PAGE, IDC_SAVE_PAGE },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_PRINT, IDC_PRINT },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand edit_menu[] = {
{ IDS_CUT, IDC_CUT },
{ IDS_COPY, IDC_COPY },
{ IDS_PASTE, IDC_PASTE },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_FIND, IDC_FIND },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_PREFERENCES, IDC_OPTIONS },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand view_menu[] = {
{ IDS_SHOW_BOOKMARK_BAR, IDC_SHOW_BOOKMARK_BAR },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_STOP_MENU_LINUX, IDC_STOP },
{ IDS_RELOAD_MENU_LINUX, IDC_RELOAD },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_FULLSCREEN, IDC_FULLSCREEN },
{ IDS_TEXT_DEFAULT_LINUX, IDC_ZOOM_NORMAL },
{ IDS_TEXT_BIGGER_LINUX, IDC_ZOOM_PLUS },
{ IDS_TEXT_SMALLER_LINUX, IDC_ZOOM_MINUS },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand history_menu[] = {
{ IDS_HISTORY_HOME_LINUX, IDC_HOME },
{ IDS_HISTORY_BACK_LINUX, IDC_BACK },
{ IDS_HISTORY_FORWARD_LINUX, IDC_FORWARD },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_HISTORY_VISITED_LINUX, MENU_DISABLED_ID, TAG_MOST_VISITED_HEADER },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_HISTORY_CLOSED_LINUX, MENU_DISABLED_ID, TAG_RECENTLY_CLOSED_HEADER },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_SHOWFULLHISTORY_LINK, IDC_SHOW_HISTORY },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand tools_menu[] = {
{ IDS_SHOW_DOWNLOADS, IDC_SHOW_DOWNLOADS },
{ IDS_SHOW_HISTORY, IDC_SHOW_HISTORY },
{ IDS_SHOW_EXTENSIONS, IDC_MANAGE_EXTENSIONS },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_TASK_MANAGER, IDC_TASK_MANAGER },
{ IDS_CLEAR_BROWSING_DATA, IDC_CLEAR_BROWSING_DATA },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_VIEW_SOURCE, IDC_VIEW_SOURCE },
{ IDS_DEV_TOOLS, IDC_DEV_TOOLS },
{ IDS_DEV_TOOLS_CONSOLE, IDC_DEV_TOOLS_CONSOLE },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand help_menu[] = {
#if defined(GOOGLE_CHROME_BUILD)
{ IDS_FEEDBACK, IDC_FEEDBACK },
#endif
{ IDS_HELP_PAGE , IDC_HELP_PAGE_VIA_MENU },
{ MENU_END, MENU_END }
};
void EnsureMethodsLoaded() {
static bool attempted_load = false;
if (attempted_load)
return;
attempted_load = true;
void* dbusmenu_lib = dlopen("libdbusmenu-glib.so", RTLD_LAZY);
if (!dbusmenu_lib)
return;
// DbusmenuMenuItem methods.
menuitem_new = reinterpret_cast<dbusmenu_menuitem_new_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_new"));
menuitem_child_add_position =
reinterpret_cast<dbusmenu_menuitem_child_add_position_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_child_add_position"));
menuitem_child_append = reinterpret_cast<dbusmenu_menuitem_child_append_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_child_append"));
menuitem_child_delete = reinterpret_cast<dbusmenu_menuitem_child_delete_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_child_delete"));
menuitem_get_children = reinterpret_cast<dbusmenu_menuitem_get_children_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_get_children"));
menuitem_property_set = reinterpret_cast<dbusmenu_menuitem_property_set_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set"));
menuitem_property_set_variant =
reinterpret_cast<dbusmenu_menuitem_property_set_variant_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set_variant"));
menuitem_property_set_bool =
reinterpret_cast<dbusmenu_menuitem_property_set_bool_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set_bool"));
menuitem_property_set_int =
reinterpret_cast<dbusmenu_menuitem_property_set_int_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set_int"));
// DbusmenuServer methods.
server_new = reinterpret_cast<dbusmenu_server_new_func>(
dlsym(dbusmenu_lib, "dbusmenu_server_new"));
server_set_root = reinterpret_cast<dbusmenu_server_set_root_func>(
dlsym(dbusmenu_lib, "dbusmenu_server_set_root"));
}
} // namespace
struct GlobalMenuBarX11::HistoryItem {
HistoryItem() : session_id(0) {}
// The title for the menu item.
string16 title;
// The URL that will be navigated to if the user selects this item.
GURL url;
// This ID is unique for a browser session and can be passed to the
// TabRestoreService to re-open the closed window or tab that this
// references. A non-0 session ID indicates that this is an entry can be
// restored that way. Otherwise, the URL will be used to open the item and
// this ID will be 0.
SessionID::id_type session_id;
// If the HistoryItem is a window, this will be the vector of tabs. Note
// that this is a list of weak references. The |menu_item_map_| is the owner
// of all items. If it is not a window, then the entry is a single page and
// the vector will be empty.
std::vector<HistoryItem*> tabs;
private:
DISALLOW_COPY_AND_ASSIGN(HistoryItem);
};
GlobalMenuBarX11::GlobalMenuBarX11(BrowserView* browser_view,
BrowserDesktopRootWindowHostX11* host)
: browser_(browser_view->browser()),
profile_(browser_->profile()),
browser_view_(browser_view),
host_(host),
server_(NULL),
root_item_(NULL),
history_menu_(NULL),
top_sites_(NULL),
tab_restore_service_(NULL),
weak_ptr_factory_(this) {
EnsureMethodsLoaded();
if (server_new)
host_->AddObserver(this);
}
GlobalMenuBarX11::~GlobalMenuBarX11() {
if (server_) {
Disable();
if (tab_restore_service_)
tab_restore_service_->RemoveObserver(this);
g_object_unref(server_);
host_->RemoveObserver(this);
}
}
// static
std::string GlobalMenuBarX11::GetPathForWindow(unsigned long xid) {
return base::StringPrintf("/com/canonical/menu/%lX", xid);
}
DbusmenuMenuitem* GlobalMenuBarX11::BuildSeparator() {
DbusmenuMenuitem* item = menuitem_new();
menuitem_property_set(item, kPropertyType, kTypeSeparator);
menuitem_property_set_bool(item, kPropertyVisible, true);
return item;
}
DbusmenuMenuitem* GlobalMenuBarX11::BuildMenuItem(
const std::string& label,
int tag_id) {
DbusmenuMenuitem* item = menuitem_new();
menuitem_property_set(item, kPropertyLabel, label.c_str());
menuitem_property_set_bool(item, kPropertyVisible, true);
if (tag_id)
g_object_set_data(G_OBJECT(item), kTypeTag, GINT_TO_POINTER(tag_id));
return item;
}
void GlobalMenuBarX11::InitServer(unsigned long xid) {
std::string path = GetPathForWindow(xid);
server_ = server_new(path.c_str());
root_item_ = menuitem_new();
menuitem_property_set(root_item_, kPropertyLabel, "Root");
menuitem_property_set_bool(root_item_, kPropertyVisible, true);
// First build static menu content.
BuildStaticMenu(root_item_, IDS_FILE_MENU_LINUX, file_menu);
BuildStaticMenu(root_item_, IDS_EDIT_MENU_LINUX, edit_menu);
BuildStaticMenu(root_item_, IDS_VIEW_MENU_LINUX, view_menu);
history_menu_ = BuildStaticMenu(
root_item_, IDS_HISTORY_MENU_LINUX, history_menu);
BuildStaticMenu(root_item_, IDS_TOOLS_MENU_LINUX, tools_menu);
BuildStaticMenu(root_item_, IDS_HELP_MENU_LINUX, help_menu);
// We have to connect to |history_menu_item|'s "activate" signal instead of
// |history_menu|'s "show" signal because we are not supposed to modify the
// menu during "show"
g_signal_connect(history_menu_, "about-to-show",
G_CALLBACK(OnHistoryMenuAboutToShowThunk), this);
for (CommandIDMenuItemMap::const_iterator it = id_to_menu_item_.begin();
it != id_to_menu_item_.end(); ++it) {
menuitem_property_set_bool(it->second, kPropertyEnabled,
chrome::IsCommandEnabled(browser_, it->first));
ui::Accelerator accelerator;
if (browser_view_->GetAccelerator(it->first, &accelerator))
RegisterAccelerator(it->second, accelerator);
chrome::AddCommandObserver(browser_, it->first, this);
}
pref_change_registrar_.Init(browser_->profile()->GetPrefs());
pref_change_registrar_.Add(
prefs::kShowBookmarkBar,
base::Bind(&GlobalMenuBarX11::OnBookmarkBarVisibilityChanged,
base::Unretained(this)));
OnBookmarkBarVisibilityChanged();
top_sites_ = profile_->GetTopSites();
if (top_sites_) {
GetTopSitesData();
// Register for notification when TopSites changes so that we can update
// ourself.
registrar_.Add(this, chrome::NOTIFICATION_TOP_SITES_CHANGED,
content::Source<history::TopSites>(top_sites_));
}
server_set_root(server_, root_item_);
}
void GlobalMenuBarX11::Disable() {
for (CommandIDMenuItemMap::const_iterator it = id_to_menu_item_.begin();
it != id_to_menu_item_.end(); ++it) {
chrome::RemoveCommandObserver(browser_, it->first, this);
}
id_to_menu_item_.clear();
pref_change_registrar_.RemoveAll();
}
DbusmenuMenuitem* GlobalMenuBarX11::BuildStaticMenu(
DbusmenuMenuitem* parent,
int menu_str_id,
GlobalMenuBarCommand* commands) {
DbusmenuMenuitem* top = menuitem_new();
menuitem_property_set(
top, kPropertyLabel,
ui::RemoveWindowsStyleAccelerators(
l10n_util::GetStringUTF8(menu_str_id)).c_str());
menuitem_property_set_bool(top, kPropertyVisible, true);
for (int i = 0; commands[i].str_id != MENU_END; ++i) {
DbusmenuMenuitem* menu_item = NULL;
int command_id = commands[i].command;
if (commands[i].str_id == MENU_SEPARATOR) {
menu_item = BuildSeparator();
} else {
std::string label = ui::ConvertAcceleratorsFromWindowsStyle(
l10n_util::GetStringUTF8(commands[i].str_id));
menu_item = BuildMenuItem(label, commands[i].tag);
if (command_id == MENU_DISABLED_ID) {
menuitem_property_set_bool(menu_item, kPropertyEnabled, false);
} else {
if (command_id == IDC_SHOW_BOOKMARK_BAR)
menuitem_property_set(menu_item, kPropertyToggleType, kTypeCheckmark);
id_to_menu_item_.insert(std::make_pair(command_id, menu_item));
g_object_set_data(G_OBJECT(menu_item), "command-id",
GINT_TO_POINTER(command_id));
g_signal_connect(menu_item, "item-activated",
G_CALLBACK(OnItemActivatedThunk), this);
}
}
menuitem_child_append(top, menu_item);
g_object_unref(menu_item);
}
menuitem_child_append(parent, top);
g_object_unref(top);
return top;
}
void GlobalMenuBarX11::RegisterAccelerator(DbusmenuMenuitem* item,
const ui::Accelerator& accelerator) {
// A translation of libdbusmenu-gtk's menuitem_property_set_shortcut()
// translated from GDK types to ui::Accelerator types.
GVariantBuilder builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);
if (accelerator.IsCtrlDown())
g_variant_builder_add(&builder, "s", "Control");
if (accelerator.IsAltDown())
g_variant_builder_add(&builder, "s", "Alt");
if (accelerator.IsShiftDown())
g_variant_builder_add(&builder, "s", "Shift");
char* name = XKeysymToString(XKeysymForWindowsKeyCode(
accelerator.key_code(), false));
if (!name) {
NOTIMPLEMENTED();
return;
}
g_variant_builder_add(&builder, "s", name);
GVariant* inside_array = g_variant_builder_end(&builder);
g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);
g_variant_builder_add_value(&builder, inside_array);
GVariant* outside_array = g_variant_builder_end(&builder);
menuitem_property_set_variant(item, kPropertyShortcut, outside_array);
}
GlobalMenuBarX11::HistoryItem* GlobalMenuBarX11::HistoryItemForTab(
const TabRestoreService::Tab& entry) {
const sessions::SerializedNavigationEntry& current_navigation =
entry.navigations.at(entry.current_navigation_index);
HistoryItem* item = new HistoryItem();
item->title = current_navigation.title();
item->url = current_navigation.virtual_url();
item->session_id = entry.id;
return item;
}
void GlobalMenuBarX11::AddHistoryItemToMenu(HistoryItem* item,
DbusmenuMenuitem* menu,
int tag,
int index) {
string16 title = item->title;
std::string url_string = item->url.possibly_invalid_spec();
if (title.empty())
title = UTF8ToUTF16(url_string);
gfx::ElideString(title, kMaximumMenuWidthInChars, &title);
DbusmenuMenuitem* menu_item = BuildMenuItem(UTF16ToUTF8(title), tag);
g_signal_connect(menu_item, "item-activated",
G_CALLBACK(OnHistoryItemActivatedThunk), this);
g_object_set_data_full(G_OBJECT(menu_item), kHistoryItem, item,
DeleteHistoryItem);
menuitem_child_add_position(menu, menu_item, index);
g_object_unref(menu_item);
}
void GlobalMenuBarX11::GetTopSitesData() {
DCHECK(top_sites_);
top_sites_->GetMostVisitedURLs(
base::Bind(&GlobalMenuBarX11::OnTopSitesReceived,
weak_ptr_factory_.GetWeakPtr()));
}
void GlobalMenuBarX11::OnTopSitesReceived(
const history::MostVisitedURLList& visited_list) {
ClearMenuSection(history_menu_, TAG_MOST_VISITED);
int index = GetIndexOfMenuItemWithTag(history_menu_,
TAG_MOST_VISITED_HEADER) + 1;
for (size_t i = 0; i < visited_list.size() && i < kMostVisitedCount; ++i) {
const history::MostVisitedURL& visited = visited_list[i];
if (visited.url.spec().empty())
break; // This is the signal that there are no more real visited sites.
HistoryItem* item = new HistoryItem();
item->title = visited.title;
item->url = visited.url;
AddHistoryItemToMenu(item,
history_menu_,
TAG_MOST_VISITED,
index++);
}
}
void GlobalMenuBarX11::OnBookmarkBarVisibilityChanged() {
CommandIDMenuItemMap::iterator it =
id_to_menu_item_.find(IDC_SHOW_BOOKMARK_BAR);
if (it != id_to_menu_item_.end()) {
PrefService* prefs = browser_->profile()->GetPrefs();
// Note: Unlike the GTK version, we don't appear to need to do tricks where
// we block activation while setting the toggle.
menuitem_property_set_int(it->second, kPropertyToggleState,
prefs->GetBoolean(prefs::kShowBookmarkBar));
}
}
int GlobalMenuBarX11::GetIndexOfMenuItemWithTag(DbusmenuMenuitem* menu,
int tag_id) {
GList* childs = menuitem_get_children(menu);
int i = 0;
for (; childs != NULL; childs = childs->next, i++) {
int tag =
GPOINTER_TO_INT(g_object_get_data(G_OBJECT(childs->data), kTypeTag));
if (tag == tag_id)
return i;
}
NOTREACHED();
return -1;
}
void GlobalMenuBarX11::ClearMenuSection(DbusmenuMenuitem* menu, int tag_id) {
std::vector<DbusmenuMenuitem*> menuitems_to_delete;
GList* childs = menuitem_get_children(menu);
for (; childs != NULL; childs = childs->next) {
DbusmenuMenuitem* current_item = reinterpret_cast<DbusmenuMenuitem*>(
childs->data);
ClearMenuSection(current_item, tag_id);
int tag =
GPOINTER_TO_INT(g_object_get_data(G_OBJECT(childs->data), kTypeTag));
if (tag == tag_id)
menuitems_to_delete.push_back(current_item);
}
for (std::vector<DbusmenuMenuitem*>::const_iterator it =
menuitems_to_delete.begin(); it != menuitems_to_delete.end(); ++it) {
menuitem_child_delete(menu, *it);
}
}
// static
void GlobalMenuBarX11::DeleteHistoryItem(void* void_item) {
HistoryItem* item =
reinterpret_cast<GlobalMenuBarX11::HistoryItem*>(void_item);
delete item;
}
void GlobalMenuBarX11::EnabledStateChangedForCommand(int id, bool enabled) {
CommandIDMenuItemMap::iterator it = id_to_menu_item_.find(id);
if (it != id_to_menu_item_.end())
menuitem_property_set_bool(it->second, kPropertyEnabled, enabled);
}
void GlobalMenuBarX11::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == chrome::NOTIFICATION_TOP_SITES_CHANGED) {
GetTopSitesData();
} else {
NOTREACHED();
}
}
void GlobalMenuBarX11::TabRestoreServiceChanged(TabRestoreService* service) {
const TabRestoreService::Entries& entries = service->entries();
ClearMenuSection(history_menu_, TAG_RECENTLY_CLOSED);
// We'll get the index the "Recently Closed" header. (This can vary depending
// on the number of "Most Visited" items.
int index = GetIndexOfMenuItemWithTag(history_menu_,
TAG_RECENTLY_CLOSED_HEADER) + 1;
unsigned int added_count = 0;
for (TabRestoreService::Entries::const_iterator it = entries.begin();
it != entries.end() && added_count < kRecentlyClosedCount; ++it) {
TabRestoreService::Entry* entry = *it;
if (entry->type == TabRestoreService::WINDOW) {
TabRestoreService::Window* entry_win =
static_cast<TabRestoreService::Window*>(entry);
std::vector<TabRestoreService::Tab>& tabs = entry_win->tabs;
if (tabs.empty())
continue;
// Create the item for the parent/window.
HistoryItem* item = new HistoryItem();
item->session_id = entry_win->id;
std::string title = item->tabs.size() == 1 ?
l10n_util::GetStringUTF8(
IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE) :
l10n_util::GetStringFUTF8(
IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE,
base::IntToString16(item->tabs.size()));
DbusmenuMenuitem* parent_item = BuildMenuItem(
title, TAG_RECENTLY_CLOSED);
menuitem_child_add_position(history_menu_, parent_item, index++);
g_object_unref(parent_item);
// The mac version of this code allows the user to click on the parent
// menu item to have the same effect as clicking the restore window
// submenu item. GTK+ helpfully activates a menu item when it shows a
// submenu so toss that feature out.
DbusmenuMenuitem* restore_item = BuildMenuItem(
l10n_util::GetStringUTF8(
IDS_HISTORY_CLOSED_RESTORE_WINDOW_LINUX).c_str(),
TAG_RECENTLY_CLOSED);
g_signal_connect(restore_item, "item-activated",
G_CALLBACK(OnHistoryItemActivatedThunk), this);
g_object_set_data_full(G_OBJECT(restore_item), kHistoryItem, item,
DeleteHistoryItem);
menuitem_child_append(parent_item, restore_item);
g_object_unref(restore_item);
DbusmenuMenuitem* separator = BuildSeparator();
menuitem_child_append(parent_item, separator);
g_object_unref(separator);
// Loop over the window's tabs and add them to the submenu.
int subindex = 2;
std::vector<TabRestoreService::Tab>::const_iterator iter;
for (iter = tabs.begin(); iter != tabs.end(); ++iter) {
TabRestoreService::Tab tab = *iter;
HistoryItem* tab_item = HistoryItemForTab(tab);
item->tabs.push_back(tab_item);
AddHistoryItemToMenu(tab_item,
parent_item,
TAG_RECENTLY_CLOSED,
subindex++);
}
++added_count;
} else if (entry->type == TabRestoreService::TAB) {
TabRestoreService::Tab* tab = static_cast<TabRestoreService::Tab*>(entry);
HistoryItem* item = HistoryItemForTab(*tab);
AddHistoryItemToMenu(item,
history_menu_,
TAG_RECENTLY_CLOSED,
index++);
++added_count;
}
}
}
void GlobalMenuBarX11::TabRestoreServiceDestroyed(
TabRestoreService* service) {
tab_restore_service_ = NULL;
}
void GlobalMenuBarX11::OnWindowMapped(unsigned long xid) {
if (!server_)
InitServer(xid);
GlobalMenuBarRegistrarX11::GetInstance()->OnWindowMapped(xid);
}
void GlobalMenuBarX11::OnWindowUnmapped(unsigned long xid) {
GlobalMenuBarRegistrarX11::GetInstance()->OnWindowUnmapped(xid);
}
void GlobalMenuBarX11::OnItemActivated(DbusmenuMenuitem* item,
unsigned int timestamp) {
int id = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(item), "command-id"));
chrome::ExecuteCommand(browser_, id);
}
void GlobalMenuBarX11::OnHistoryItemActivated(DbusmenuMenuitem* sender,
unsigned int timestamp) {
// Note: We don't have access to the event modifiers used to click the menu
// item since that happens in a different process.
HistoryItem* item = reinterpret_cast<HistoryItem*>(
g_object_get_data(G_OBJECT(sender), kHistoryItem));
// If this item can be restored using TabRestoreService, do so. Otherwise,
// just load the URL.
TabRestoreService* service =
TabRestoreServiceFactory::GetForProfile(profile_);
if (item->session_id && service) {
service->RestoreEntryById(browser_->tab_restore_service_delegate(),
item->session_id, browser_->host_desktop_type(),
UNKNOWN);
} else {
DCHECK(item->url.is_valid());
browser_->OpenURL(content::OpenURLParams(
item->url,
content::Referrer(),
NEW_FOREGROUND_TAB,
content::PAGE_TRANSITION_AUTO_BOOKMARK,
false));
}
}
void GlobalMenuBarX11::OnHistoryMenuAboutToShow(DbusmenuMenuitem* item) {
if (!tab_restore_service_) {
tab_restore_service_ = TabRestoreServiceFactory::GetForProfile(profile_);
if (tab_restore_service_) {
tab_restore_service_->LoadTabsFromLastSession();
tab_restore_service_->AddObserver(this);
// If LoadTabsFromLastSession doesn't load tabs, it won't call
// TabRestoreServiceChanged(). This ensures that all new windows after
// the first one will have their menus populated correctly.
TabRestoreServiceChanged(tab_restore_service_);
}
}
}
Load libdbusmenu-glib.so.4 if libdbusmenu-glib.so does not exist.
The Linux Aura Unity global menu does not appear for me.
Apparently libdbusmenu-glib.so isn't a default package/link.
The package db lists *.4 with all Precise-Saucy releases:
http://packages.ubuntu.com/search?keywords=libdbusmenu-glib
/usr/lib/x86_64-linux-gnu/libdbusmenu-glib.so.4
BUG=295890
TEST=Linux Aura Unity global menu appears on most/all Ubuntu releases Precise-Saucy.
R=erg@chromium.org
TBR=jamescook@chromium.org
Review URL: https://chromiumcodereview.appspot.com/24096032
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@224596 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright 2013 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 "chrome/browser/ui/views/frame/global_menu_bar_x11.h"
#include <dlfcn.h>
#include <glib-object.h>
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/history/top_sites.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/tab_restore_service.h"
#include "chrome/browser/sessions/tab_restore_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
#include "chrome/browser/ui/views/frame/browser_desktop_root_window_host_x11.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_source.h"
#include "grit/generated_resources.h"
#include "ui/base/accelerators/menu_label_accelerator_util_linux.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/events/keycodes/keyboard_code_conversion_x.h"
#include "ui/gfx/text_elider.h"
// libdbusmenu-glib types
typedef struct _DbusmenuMenuitem DbusmenuMenuitem;
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_new_func)();
typedef bool (*dbusmenu_menuitem_child_add_position_func)(
DbusmenuMenuitem* parent,
DbusmenuMenuitem* child,
unsigned int position);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_child_append_func)(
DbusmenuMenuitem* parent,
DbusmenuMenuitem* child);
typedef bool (*dbusmenu_menuitem_child_delete_func)(
DbusmenuMenuitem* parent,
DbusmenuMenuitem* child);
typedef GList* (*dbusmenu_menuitem_get_children_func)(
DbusmenuMenuitem* item);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_func)(
DbusmenuMenuitem* item,
const char* property,
const char* value);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_variant_func)(
DbusmenuMenuitem* item,
const char* property,
GVariant* value);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_bool_func)(
DbusmenuMenuitem* item,
const char* property,
bool value);
typedef DbusmenuMenuitem* (*dbusmenu_menuitem_property_set_int_func)(
DbusmenuMenuitem* item,
const char* property,
int value);
typedef struct _DbusmenuServer DbusmenuServer;
typedef DbusmenuServer* (*dbusmenu_server_new_func)(const char* object);
typedef void (*dbusmenu_server_set_root_func)(DbusmenuServer* self,
DbusmenuMenuitem* root);
// A line in the static menu definitions.
struct GlobalMenuBarCommand {
int str_id;
int command;
int tag;
};
namespace {
// Retrieved functions from libdbusmenu-glib.
// DbusmenuMenuItem methods:
dbusmenu_menuitem_new_func menuitem_new = NULL;
dbusmenu_menuitem_get_children_func menuitem_get_children = NULL;
dbusmenu_menuitem_child_add_position_func menuitem_child_add_position = NULL;
dbusmenu_menuitem_child_append_func menuitem_child_append = NULL;
dbusmenu_menuitem_child_delete_func menuitem_child_delete = NULL;
dbusmenu_menuitem_property_set_func menuitem_property_set = NULL;
dbusmenu_menuitem_property_set_variant_func menuitem_property_set_variant =
NULL;
dbusmenu_menuitem_property_set_bool_func menuitem_property_set_bool = NULL;
dbusmenu_menuitem_property_set_int_func menuitem_property_set_int = NULL;
// DbusmenuServer methods:
dbusmenu_server_new_func server_new = NULL;
dbusmenu_server_set_root_func server_set_root = NULL;
// Properties that we set on menu items:
const char kPropertyEnabled[] = "enabled";
const char kPropertyLabel[] = "label";
const char kPropertyShortcut[] = "shortcut";
const char kPropertyType[] = "type";
const char kPropertyToggleType[] = "toggle-type";
const char kPropertyToggleState[] = "toggle-state";
const char kPropertyVisible[] = "visible";
const char kTypeCheckmark[] = "checkmark";
const char kTypeSeparator[] = "separator";
// Data set on GObjectgs.
const char kTypeTag[] = "type-tag";
const char kHistoryItem[] = "history-item";
// The maximum number of most visited items to display.
const unsigned int kMostVisitedCount = 8;
// The number of recently closed items to get.
const unsigned int kRecentlyClosedCount = 8;
// Menus more than this many chars long will get trimmed.
const int kMaximumMenuWidthInChars = 50;
// Constants used in menu definitions.
const int MENU_SEPARATOR =-1;
const int MENU_END = -2;
const int MENU_DISABLED_ID = -3;
// These tag values are used to refer to menu itesm.
const int TAG_NORMAL = 0;
const int TAG_MOST_VISITED = 1;
const int TAG_RECENTLY_CLOSED = 2;
const int TAG_MOST_VISITED_HEADER = 3;
const int TAG_RECENTLY_CLOSED_HEADER = 4;
GlobalMenuBarCommand file_menu[] = {
{ IDS_NEW_TAB, IDC_NEW_TAB },
{ IDS_NEW_WINDOW, IDC_NEW_WINDOW },
{ IDS_NEW_INCOGNITO_WINDOW, IDC_NEW_INCOGNITO_WINDOW },
{ IDS_REOPEN_CLOSED_TABS_LINUX, IDC_RESTORE_TAB },
{ IDS_OPEN_FILE_LINUX, IDC_OPEN_FILE },
{ IDS_OPEN_LOCATION_LINUX, IDC_FOCUS_LOCATION },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_CREATE_SHORTCUTS, IDC_CREATE_SHORTCUTS },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_CLOSE_WINDOW_LINUX, IDC_CLOSE_WINDOW },
{ IDS_CLOSE_TAB_LINUX, IDC_CLOSE_TAB },
{ IDS_SAVE_PAGE, IDC_SAVE_PAGE },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_PRINT, IDC_PRINT },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand edit_menu[] = {
{ IDS_CUT, IDC_CUT },
{ IDS_COPY, IDC_COPY },
{ IDS_PASTE, IDC_PASTE },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_FIND, IDC_FIND },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_PREFERENCES, IDC_OPTIONS },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand view_menu[] = {
{ IDS_SHOW_BOOKMARK_BAR, IDC_SHOW_BOOKMARK_BAR },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_STOP_MENU_LINUX, IDC_STOP },
{ IDS_RELOAD_MENU_LINUX, IDC_RELOAD },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_FULLSCREEN, IDC_FULLSCREEN },
{ IDS_TEXT_DEFAULT_LINUX, IDC_ZOOM_NORMAL },
{ IDS_TEXT_BIGGER_LINUX, IDC_ZOOM_PLUS },
{ IDS_TEXT_SMALLER_LINUX, IDC_ZOOM_MINUS },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand history_menu[] = {
{ IDS_HISTORY_HOME_LINUX, IDC_HOME },
{ IDS_HISTORY_BACK_LINUX, IDC_BACK },
{ IDS_HISTORY_FORWARD_LINUX, IDC_FORWARD },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_HISTORY_VISITED_LINUX, MENU_DISABLED_ID, TAG_MOST_VISITED_HEADER },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_HISTORY_CLOSED_LINUX, MENU_DISABLED_ID, TAG_RECENTLY_CLOSED_HEADER },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_SHOWFULLHISTORY_LINK, IDC_SHOW_HISTORY },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand tools_menu[] = {
{ IDS_SHOW_DOWNLOADS, IDC_SHOW_DOWNLOADS },
{ IDS_SHOW_HISTORY, IDC_SHOW_HISTORY },
{ IDS_SHOW_EXTENSIONS, IDC_MANAGE_EXTENSIONS },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_TASK_MANAGER, IDC_TASK_MANAGER },
{ IDS_CLEAR_BROWSING_DATA, IDC_CLEAR_BROWSING_DATA },
{ MENU_SEPARATOR, MENU_SEPARATOR },
{ IDS_VIEW_SOURCE, IDC_VIEW_SOURCE },
{ IDS_DEV_TOOLS, IDC_DEV_TOOLS },
{ IDS_DEV_TOOLS_CONSOLE, IDC_DEV_TOOLS_CONSOLE },
{ MENU_END, MENU_END }
};
GlobalMenuBarCommand help_menu[] = {
#if defined(GOOGLE_CHROME_BUILD)
{ IDS_FEEDBACK, IDC_FEEDBACK },
#endif
{ IDS_HELP_PAGE , IDC_HELP_PAGE_VIA_MENU },
{ MENU_END, MENU_END }
};
void EnsureMethodsLoaded() {
static bool attempted_load = false;
if (attempted_load)
return;
attempted_load = true;
void* dbusmenu_lib = dlopen("libdbusmenu-glib.so", RTLD_LAZY);
if (!dbusmenu_lib)
dbusmenu_lib = dlopen("libdbusmenu-glib.so.4", RTLD_LAZY);
if (!dbusmenu_lib)
return;
// DbusmenuMenuItem methods.
menuitem_new = reinterpret_cast<dbusmenu_menuitem_new_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_new"));
menuitem_child_add_position =
reinterpret_cast<dbusmenu_menuitem_child_add_position_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_child_add_position"));
menuitem_child_append = reinterpret_cast<dbusmenu_menuitem_child_append_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_child_append"));
menuitem_child_delete = reinterpret_cast<dbusmenu_menuitem_child_delete_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_child_delete"));
menuitem_get_children = reinterpret_cast<dbusmenu_menuitem_get_children_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_get_children"));
menuitem_property_set = reinterpret_cast<dbusmenu_menuitem_property_set_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set"));
menuitem_property_set_variant =
reinterpret_cast<dbusmenu_menuitem_property_set_variant_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set_variant"));
menuitem_property_set_bool =
reinterpret_cast<dbusmenu_menuitem_property_set_bool_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set_bool"));
menuitem_property_set_int =
reinterpret_cast<dbusmenu_menuitem_property_set_int_func>(
dlsym(dbusmenu_lib, "dbusmenu_menuitem_property_set_int"));
// DbusmenuServer methods.
server_new = reinterpret_cast<dbusmenu_server_new_func>(
dlsym(dbusmenu_lib, "dbusmenu_server_new"));
server_set_root = reinterpret_cast<dbusmenu_server_set_root_func>(
dlsym(dbusmenu_lib, "dbusmenu_server_set_root"));
}
} // namespace
struct GlobalMenuBarX11::HistoryItem {
HistoryItem() : session_id(0) {}
// The title for the menu item.
string16 title;
// The URL that will be navigated to if the user selects this item.
GURL url;
// This ID is unique for a browser session and can be passed to the
// TabRestoreService to re-open the closed window or tab that this
// references. A non-0 session ID indicates that this is an entry can be
// restored that way. Otherwise, the URL will be used to open the item and
// this ID will be 0.
SessionID::id_type session_id;
// If the HistoryItem is a window, this will be the vector of tabs. Note
// that this is a list of weak references. The |menu_item_map_| is the owner
// of all items. If it is not a window, then the entry is a single page and
// the vector will be empty.
std::vector<HistoryItem*> tabs;
private:
DISALLOW_COPY_AND_ASSIGN(HistoryItem);
};
GlobalMenuBarX11::GlobalMenuBarX11(BrowserView* browser_view,
BrowserDesktopRootWindowHostX11* host)
: browser_(browser_view->browser()),
profile_(browser_->profile()),
browser_view_(browser_view),
host_(host),
server_(NULL),
root_item_(NULL),
history_menu_(NULL),
top_sites_(NULL),
tab_restore_service_(NULL),
weak_ptr_factory_(this) {
EnsureMethodsLoaded();
if (server_new)
host_->AddObserver(this);
}
GlobalMenuBarX11::~GlobalMenuBarX11() {
if (server_) {
Disable();
if (tab_restore_service_)
tab_restore_service_->RemoveObserver(this);
g_object_unref(server_);
host_->RemoveObserver(this);
}
}
// static
std::string GlobalMenuBarX11::GetPathForWindow(unsigned long xid) {
return base::StringPrintf("/com/canonical/menu/%lX", xid);
}
DbusmenuMenuitem* GlobalMenuBarX11::BuildSeparator() {
DbusmenuMenuitem* item = menuitem_new();
menuitem_property_set(item, kPropertyType, kTypeSeparator);
menuitem_property_set_bool(item, kPropertyVisible, true);
return item;
}
DbusmenuMenuitem* GlobalMenuBarX11::BuildMenuItem(
const std::string& label,
int tag_id) {
DbusmenuMenuitem* item = menuitem_new();
menuitem_property_set(item, kPropertyLabel, label.c_str());
menuitem_property_set_bool(item, kPropertyVisible, true);
if (tag_id)
g_object_set_data(G_OBJECT(item), kTypeTag, GINT_TO_POINTER(tag_id));
return item;
}
void GlobalMenuBarX11::InitServer(unsigned long xid) {
std::string path = GetPathForWindow(xid);
server_ = server_new(path.c_str());
root_item_ = menuitem_new();
menuitem_property_set(root_item_, kPropertyLabel, "Root");
menuitem_property_set_bool(root_item_, kPropertyVisible, true);
// First build static menu content.
BuildStaticMenu(root_item_, IDS_FILE_MENU_LINUX, file_menu);
BuildStaticMenu(root_item_, IDS_EDIT_MENU_LINUX, edit_menu);
BuildStaticMenu(root_item_, IDS_VIEW_MENU_LINUX, view_menu);
history_menu_ = BuildStaticMenu(
root_item_, IDS_HISTORY_MENU_LINUX, history_menu);
BuildStaticMenu(root_item_, IDS_TOOLS_MENU_LINUX, tools_menu);
BuildStaticMenu(root_item_, IDS_HELP_MENU_LINUX, help_menu);
// We have to connect to |history_menu_item|'s "activate" signal instead of
// |history_menu|'s "show" signal because we are not supposed to modify the
// menu during "show"
g_signal_connect(history_menu_, "about-to-show",
G_CALLBACK(OnHistoryMenuAboutToShowThunk), this);
for (CommandIDMenuItemMap::const_iterator it = id_to_menu_item_.begin();
it != id_to_menu_item_.end(); ++it) {
menuitem_property_set_bool(it->second, kPropertyEnabled,
chrome::IsCommandEnabled(browser_, it->first));
ui::Accelerator accelerator;
if (browser_view_->GetAccelerator(it->first, &accelerator))
RegisterAccelerator(it->second, accelerator);
chrome::AddCommandObserver(browser_, it->first, this);
}
pref_change_registrar_.Init(browser_->profile()->GetPrefs());
pref_change_registrar_.Add(
prefs::kShowBookmarkBar,
base::Bind(&GlobalMenuBarX11::OnBookmarkBarVisibilityChanged,
base::Unretained(this)));
OnBookmarkBarVisibilityChanged();
top_sites_ = profile_->GetTopSites();
if (top_sites_) {
GetTopSitesData();
// Register for notification when TopSites changes so that we can update
// ourself.
registrar_.Add(this, chrome::NOTIFICATION_TOP_SITES_CHANGED,
content::Source<history::TopSites>(top_sites_));
}
server_set_root(server_, root_item_);
}
void GlobalMenuBarX11::Disable() {
for (CommandIDMenuItemMap::const_iterator it = id_to_menu_item_.begin();
it != id_to_menu_item_.end(); ++it) {
chrome::RemoveCommandObserver(browser_, it->first, this);
}
id_to_menu_item_.clear();
pref_change_registrar_.RemoveAll();
}
DbusmenuMenuitem* GlobalMenuBarX11::BuildStaticMenu(
DbusmenuMenuitem* parent,
int menu_str_id,
GlobalMenuBarCommand* commands) {
DbusmenuMenuitem* top = menuitem_new();
menuitem_property_set(
top, kPropertyLabel,
ui::RemoveWindowsStyleAccelerators(
l10n_util::GetStringUTF8(menu_str_id)).c_str());
menuitem_property_set_bool(top, kPropertyVisible, true);
for (int i = 0; commands[i].str_id != MENU_END; ++i) {
DbusmenuMenuitem* menu_item = NULL;
int command_id = commands[i].command;
if (commands[i].str_id == MENU_SEPARATOR) {
menu_item = BuildSeparator();
} else {
std::string label = ui::ConvertAcceleratorsFromWindowsStyle(
l10n_util::GetStringUTF8(commands[i].str_id));
menu_item = BuildMenuItem(label, commands[i].tag);
if (command_id == MENU_DISABLED_ID) {
menuitem_property_set_bool(menu_item, kPropertyEnabled, false);
} else {
if (command_id == IDC_SHOW_BOOKMARK_BAR)
menuitem_property_set(menu_item, kPropertyToggleType, kTypeCheckmark);
id_to_menu_item_.insert(std::make_pair(command_id, menu_item));
g_object_set_data(G_OBJECT(menu_item), "command-id",
GINT_TO_POINTER(command_id));
g_signal_connect(menu_item, "item-activated",
G_CALLBACK(OnItemActivatedThunk), this);
}
}
menuitem_child_append(top, menu_item);
g_object_unref(menu_item);
}
menuitem_child_append(parent, top);
g_object_unref(top);
return top;
}
void GlobalMenuBarX11::RegisterAccelerator(DbusmenuMenuitem* item,
const ui::Accelerator& accelerator) {
// A translation of libdbusmenu-gtk's menuitem_property_set_shortcut()
// translated from GDK types to ui::Accelerator types.
GVariantBuilder builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);
if (accelerator.IsCtrlDown())
g_variant_builder_add(&builder, "s", "Control");
if (accelerator.IsAltDown())
g_variant_builder_add(&builder, "s", "Alt");
if (accelerator.IsShiftDown())
g_variant_builder_add(&builder, "s", "Shift");
char* name = XKeysymToString(XKeysymForWindowsKeyCode(
accelerator.key_code(), false));
if (!name) {
NOTIMPLEMENTED();
return;
}
g_variant_builder_add(&builder, "s", name);
GVariant* inside_array = g_variant_builder_end(&builder);
g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);
g_variant_builder_add_value(&builder, inside_array);
GVariant* outside_array = g_variant_builder_end(&builder);
menuitem_property_set_variant(item, kPropertyShortcut, outside_array);
}
GlobalMenuBarX11::HistoryItem* GlobalMenuBarX11::HistoryItemForTab(
const TabRestoreService::Tab& entry) {
const sessions::SerializedNavigationEntry& current_navigation =
entry.navigations.at(entry.current_navigation_index);
HistoryItem* item = new HistoryItem();
item->title = current_navigation.title();
item->url = current_navigation.virtual_url();
item->session_id = entry.id;
return item;
}
void GlobalMenuBarX11::AddHistoryItemToMenu(HistoryItem* item,
DbusmenuMenuitem* menu,
int tag,
int index) {
string16 title = item->title;
std::string url_string = item->url.possibly_invalid_spec();
if (title.empty())
title = UTF8ToUTF16(url_string);
gfx::ElideString(title, kMaximumMenuWidthInChars, &title);
DbusmenuMenuitem* menu_item = BuildMenuItem(UTF16ToUTF8(title), tag);
g_signal_connect(menu_item, "item-activated",
G_CALLBACK(OnHistoryItemActivatedThunk), this);
g_object_set_data_full(G_OBJECT(menu_item), kHistoryItem, item,
DeleteHistoryItem);
menuitem_child_add_position(menu, menu_item, index);
g_object_unref(menu_item);
}
void GlobalMenuBarX11::GetTopSitesData() {
DCHECK(top_sites_);
top_sites_->GetMostVisitedURLs(
base::Bind(&GlobalMenuBarX11::OnTopSitesReceived,
weak_ptr_factory_.GetWeakPtr()));
}
void GlobalMenuBarX11::OnTopSitesReceived(
const history::MostVisitedURLList& visited_list) {
ClearMenuSection(history_menu_, TAG_MOST_VISITED);
int index = GetIndexOfMenuItemWithTag(history_menu_,
TAG_MOST_VISITED_HEADER) + 1;
for (size_t i = 0; i < visited_list.size() && i < kMostVisitedCount; ++i) {
const history::MostVisitedURL& visited = visited_list[i];
if (visited.url.spec().empty())
break; // This is the signal that there are no more real visited sites.
HistoryItem* item = new HistoryItem();
item->title = visited.title;
item->url = visited.url;
AddHistoryItemToMenu(item,
history_menu_,
TAG_MOST_VISITED,
index++);
}
}
void GlobalMenuBarX11::OnBookmarkBarVisibilityChanged() {
CommandIDMenuItemMap::iterator it =
id_to_menu_item_.find(IDC_SHOW_BOOKMARK_BAR);
if (it != id_to_menu_item_.end()) {
PrefService* prefs = browser_->profile()->GetPrefs();
// Note: Unlike the GTK version, we don't appear to need to do tricks where
// we block activation while setting the toggle.
menuitem_property_set_int(it->second, kPropertyToggleState,
prefs->GetBoolean(prefs::kShowBookmarkBar));
}
}
int GlobalMenuBarX11::GetIndexOfMenuItemWithTag(DbusmenuMenuitem* menu,
int tag_id) {
GList* childs = menuitem_get_children(menu);
int i = 0;
for (; childs != NULL; childs = childs->next, i++) {
int tag =
GPOINTER_TO_INT(g_object_get_data(G_OBJECT(childs->data), kTypeTag));
if (tag == tag_id)
return i;
}
NOTREACHED();
return -1;
}
void GlobalMenuBarX11::ClearMenuSection(DbusmenuMenuitem* menu, int tag_id) {
std::vector<DbusmenuMenuitem*> menuitems_to_delete;
GList* childs = menuitem_get_children(menu);
for (; childs != NULL; childs = childs->next) {
DbusmenuMenuitem* current_item = reinterpret_cast<DbusmenuMenuitem*>(
childs->data);
ClearMenuSection(current_item, tag_id);
int tag =
GPOINTER_TO_INT(g_object_get_data(G_OBJECT(childs->data), kTypeTag));
if (tag == tag_id)
menuitems_to_delete.push_back(current_item);
}
for (std::vector<DbusmenuMenuitem*>::const_iterator it =
menuitems_to_delete.begin(); it != menuitems_to_delete.end(); ++it) {
menuitem_child_delete(menu, *it);
}
}
// static
void GlobalMenuBarX11::DeleteHistoryItem(void* void_item) {
HistoryItem* item =
reinterpret_cast<GlobalMenuBarX11::HistoryItem*>(void_item);
delete item;
}
void GlobalMenuBarX11::EnabledStateChangedForCommand(int id, bool enabled) {
CommandIDMenuItemMap::iterator it = id_to_menu_item_.find(id);
if (it != id_to_menu_item_.end())
menuitem_property_set_bool(it->second, kPropertyEnabled, enabled);
}
void GlobalMenuBarX11::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == chrome::NOTIFICATION_TOP_SITES_CHANGED) {
GetTopSitesData();
} else {
NOTREACHED();
}
}
void GlobalMenuBarX11::TabRestoreServiceChanged(TabRestoreService* service) {
const TabRestoreService::Entries& entries = service->entries();
ClearMenuSection(history_menu_, TAG_RECENTLY_CLOSED);
// We'll get the index the "Recently Closed" header. (This can vary depending
// on the number of "Most Visited" items.
int index = GetIndexOfMenuItemWithTag(history_menu_,
TAG_RECENTLY_CLOSED_HEADER) + 1;
unsigned int added_count = 0;
for (TabRestoreService::Entries::const_iterator it = entries.begin();
it != entries.end() && added_count < kRecentlyClosedCount; ++it) {
TabRestoreService::Entry* entry = *it;
if (entry->type == TabRestoreService::WINDOW) {
TabRestoreService::Window* entry_win =
static_cast<TabRestoreService::Window*>(entry);
std::vector<TabRestoreService::Tab>& tabs = entry_win->tabs;
if (tabs.empty())
continue;
// Create the item for the parent/window.
HistoryItem* item = new HistoryItem();
item->session_id = entry_win->id;
std::string title = item->tabs.size() == 1 ?
l10n_util::GetStringUTF8(
IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE) :
l10n_util::GetStringFUTF8(
IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE,
base::IntToString16(item->tabs.size()));
DbusmenuMenuitem* parent_item = BuildMenuItem(
title, TAG_RECENTLY_CLOSED);
menuitem_child_add_position(history_menu_, parent_item, index++);
g_object_unref(parent_item);
// The mac version of this code allows the user to click on the parent
// menu item to have the same effect as clicking the restore window
// submenu item. GTK+ helpfully activates a menu item when it shows a
// submenu so toss that feature out.
DbusmenuMenuitem* restore_item = BuildMenuItem(
l10n_util::GetStringUTF8(
IDS_HISTORY_CLOSED_RESTORE_WINDOW_LINUX).c_str(),
TAG_RECENTLY_CLOSED);
g_signal_connect(restore_item, "item-activated",
G_CALLBACK(OnHistoryItemActivatedThunk), this);
g_object_set_data_full(G_OBJECT(restore_item), kHistoryItem, item,
DeleteHistoryItem);
menuitem_child_append(parent_item, restore_item);
g_object_unref(restore_item);
DbusmenuMenuitem* separator = BuildSeparator();
menuitem_child_append(parent_item, separator);
g_object_unref(separator);
// Loop over the window's tabs and add them to the submenu.
int subindex = 2;
std::vector<TabRestoreService::Tab>::const_iterator iter;
for (iter = tabs.begin(); iter != tabs.end(); ++iter) {
TabRestoreService::Tab tab = *iter;
HistoryItem* tab_item = HistoryItemForTab(tab);
item->tabs.push_back(tab_item);
AddHistoryItemToMenu(tab_item,
parent_item,
TAG_RECENTLY_CLOSED,
subindex++);
}
++added_count;
} else if (entry->type == TabRestoreService::TAB) {
TabRestoreService::Tab* tab = static_cast<TabRestoreService::Tab*>(entry);
HistoryItem* item = HistoryItemForTab(*tab);
AddHistoryItemToMenu(item,
history_menu_,
TAG_RECENTLY_CLOSED,
index++);
++added_count;
}
}
}
void GlobalMenuBarX11::TabRestoreServiceDestroyed(
TabRestoreService* service) {
tab_restore_service_ = NULL;
}
void GlobalMenuBarX11::OnWindowMapped(unsigned long xid) {
if (!server_)
InitServer(xid);
GlobalMenuBarRegistrarX11::GetInstance()->OnWindowMapped(xid);
}
void GlobalMenuBarX11::OnWindowUnmapped(unsigned long xid) {
GlobalMenuBarRegistrarX11::GetInstance()->OnWindowUnmapped(xid);
}
void GlobalMenuBarX11::OnItemActivated(DbusmenuMenuitem* item,
unsigned int timestamp) {
int id = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(item), "command-id"));
chrome::ExecuteCommand(browser_, id);
}
void GlobalMenuBarX11::OnHistoryItemActivated(DbusmenuMenuitem* sender,
unsigned int timestamp) {
// Note: We don't have access to the event modifiers used to click the menu
// item since that happens in a different process.
HistoryItem* item = reinterpret_cast<HistoryItem*>(
g_object_get_data(G_OBJECT(sender), kHistoryItem));
// If this item can be restored using TabRestoreService, do so. Otherwise,
// just load the URL.
TabRestoreService* service =
TabRestoreServiceFactory::GetForProfile(profile_);
if (item->session_id && service) {
service->RestoreEntryById(browser_->tab_restore_service_delegate(),
item->session_id, browser_->host_desktop_type(),
UNKNOWN);
} else {
DCHECK(item->url.is_valid());
browser_->OpenURL(content::OpenURLParams(
item->url,
content::Referrer(),
NEW_FOREGROUND_TAB,
content::PAGE_TRANSITION_AUTO_BOOKMARK,
false));
}
}
void GlobalMenuBarX11::OnHistoryMenuAboutToShow(DbusmenuMenuitem* item) {
if (!tab_restore_service_) {
tab_restore_service_ = TabRestoreServiceFactory::GetForProfile(profile_);
if (tab_restore_service_) {
tab_restore_service_->LoadTabsFromLastSession();
tab_restore_service_->AddObserver(this);
// If LoadTabsFromLastSession doesn't load tabs, it won't call
// TabRestoreServiceChanged(). This ensures that all new windows after
// the first one will have their menus populated correctly.
TabRestoreServiceChanged(tab_restore_service_);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.