source: trunk/CrypPlugins/KeySearcher/ExternalClient/Cryptool.cpp @ 2207

Last change on this file since 2207 was 2207, checked in by Sven Rech, 11 years ago

Some work on the external keysearcher client (not tested)

File size: 12.8 KB
Line 
1/* ============================================================
2
3Copyright (c) 2009 Advanced Micro Devices, Inc.  All rights reserved.
4 
5Redistribution and use of this material is permitted under the following
6conditions:
7 
8Redistributions must retain the above copyright notice and all terms of this
9license.
10 
11In no event shall anyone redistributing or accessing or using this material
12commence or participate in any arbitration or legal action relating to this
13material against Advanced Micro Devices, Inc. or any copyright holders or
14contributors. The foregoing shall survive any expiration or termination of
15this license or any agreement or access or use related to this material.
16
17ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION
18OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL.
19
20THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT
21HOLDERS AND CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY
22REPRESENTATIONS, GUARANTEE, OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO
23SUPPORT, INDEMNITY, ERROR FREE OR UNINTERRUPTED OPERA TION, OR THAT IT IS FREE
24FROM DEFECTS OR VIRUSES.  ALL OBLIGATIONS ARE HEREBY DISCLAIMED - WHETHER
25EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED
26WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
27ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT.
28IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR
29CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE,
30EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
31OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR
32BUSINESS INTERRUPTION) HOWEVER CAUSED OR BASED ON ANY THEORY OF LIABILITY
33ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY
34OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED MICRO DEVICES,
35INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS
36(US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS
37THIS ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND
38ANY COPYRIGHT HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES,
39OBLIGATIONS, CLAIMS, OR DEMANDS IN EXCESS OF TEN DOLLARS (US $10.00). THE
40FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, IF ANY OF THESE TERMS ARE
41CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME VOID OR
42DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR
43CONTRIBUTORS FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE
44THIS MATERIAL SHALL TERMINATE IMMEDIATELY. MOREOVER, THE FOREGOING SHALL
45SURVIVE ANY EXPIRATION OR TERMINATION OF THIS LICENSE OR ANY AGREEMENT OR
46ACCESS OR USE RELATED TO THIS MATERIAL.
47
48NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS
49MATERIAL SUCH NOTICE IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO
50RESTRICTIONS UNDER THE LAWS AND REGULATIONS OF THE UNITED STATES OR OTHER
51COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT CONTROL LAWS SUCH
52AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS
53DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S.
54MUNITIONS LIST. THIS MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED,
55EXPORTED AND/OR RE-EXPORTED IN ANY MANNER PROHIBITED UNDER ANY APPLICABLE LAWS,
56INCLUDING U.S. EXPORT CONTROL LAWS REGARDING SPECIFICALLY DESIGNATED PERSONS,
57COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY CONTROLS.
58MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY
59LICENSE OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL.
60
61NOTICE REGARDING THE U.S. GOVERNMENT AND DOD AGENCIES: This material is
62provided with "RESTRICTED RIGHTS" and/or "LIMITED RIGHTS" as applicable to
63computer software and technical data, respectively. Use, duplication,
64distribution or disclosure by the U.S. Government and/or DOD agencies is
65subject to the full extent of restrictions in all applicable regulations,
66including those found at FAR52.227 and DFARS252.227 et seq. and any successor
67regulations thereof. Use of this material by the U.S. Government and/or DOD
68agencies is acknowledgment of the proprietary rights of any copyright holders
69and contributors, including those of Advanced Micro Devices, Inc., as well as
70the provisions of FAR52.227-14 through 23 regarding privately developed and/or
71commercial computer software.
72
73This license forms the entire agreement regarding the subject matter hereof and
74supersedes all proposals and prior discussions and writings between the parties
75with respect thereto. This license does not affect any ownership, rights, title,
76or interest in, or relating to, this material. No terms of this license can be
77modified or waived, and no breach of this license can be excused, unless done
78so in a writing signed by all affected parties. Each term of this license is
79separately enforceable. If any term of this license is determined to be or
80becomes unenforceable or illegal, such term shall be reformed to the minimum
81extent necessary in order for this license to remain in effect in accordance
82with its terms as modified by such reformation. This license shall be governed
83by and construed in accordance with the laws of the State of Texas without
84regard to rules on conflicts of law of any state or jurisdiction or the United
85Nations Convention on the International Sale of Goods. All disputes arising out
86of this license shall be subject to the jurisdiction of the federal and state
87courts in Austin, Texas, and all defenses are hereby waived concerning personal
88jurisdiction and venue of these courts.
89
90============================================================ */
91
92
93//
94// Copyright (c) 2009 Advanced Micro Devices, Inc. All rights reserved.
95//
96
97#include <cstdio>
98#include <cstdlib>
99#include <iostream>
100#include <SDKFile.hpp>
101#include <SDKCommon.hpp>
102#include <SDKApplication.hpp>
103
104#define __NO_STD_VECTOR
105#define __NO_STD_STRING
106
107#include "Cryptool.h"
108
109Cryptool::Cryptool()
110{
111    cl_int err;
112
113    kernel = 0;
114
115    // Platform info
116    cl::vector<cl::Platform> platforms;
117    std::cout<<"HelloCL!\nGetting Platform Information\n";
118    err = cl::Platform::get(&platforms);
119    if(err != CL_SUCCESS)
120    {
121        std::cerr << "Platform::get() failed (" << err << ")" << std::endl;
122        throw std::exception();
123    }
124
125    cl::vector<cl::Platform>::iterator i;
126    if(platforms.size() > 0)
127    {
128        for(i = platforms.begin(); i != platforms.end(); ++i)
129        {
130            if(!strcmp((*i).getInfo<CL_PLATFORM_VENDOR>(&err).c_str(), "Advanced Micro Devices, Inc."))
131            {
132                break;
133            }
134        }
135    }
136    if(err != CL_SUCCESS)
137    {
138        std::cerr << "Platform::getInfo() failed (" << err << ")" << std::endl;
139        throw std::exception();
140    }
141
142    /*
143     * If we could find our platform, use it. Otherwise pass a NULL and get whatever the
144     * implementation thinks we should be using.
145     */
146
147    cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(*i)(), 0 };
148
149    std::cout<<"Creating a context AMD platform\n";
150    context = new cl::Context(CL_DEVICE_TYPE_CPU, cps, NULL, NULL, &err);
151    if (err != CL_SUCCESS) {
152        std::cerr << "Context::Context() failed (" << err << ")\n";
153        throw std::exception();
154    }
155
156    std::cout<<"Getting device info\n";
157    devices = context->getInfo<CL_CONTEXT_DEVICES>();
158    if (err != CL_SUCCESS) {
159        std::cerr << "Context::getInfo() failed (" << err << ")\n";
160        throw std::exception();
161    }
162    if (devices.size() == 0) {
163        std::cerr << "No device available\n";
164        throw std::exception();
165    }
166
167    for(uint32_t i=0; i< devices.size(); ++i)
168    {
169        std::string out;
170        devices[i].getInfo(CL_DEVICE_NAME, &out);
171        printf("name: %s\n", out.c_str());
172        devices[i].getInfo(CL_DEVICE_VENDOR, &out);
173        printf("vendor: %s\n", out.c_str());
174        devices[i].getInfo(CL_DEVICE_OPENCL_C_VERSION, &out);
175        printf("version c: %s\n", out.c_str());
176    }
177}
178
179void Cryptool::buildKernel(const Job& j)
180{
181    if (j.Src == "")
182    {
183        if (kernel != 0)
184            return;
185        else
186        {
187            std::cout << "Source transmission failure!" << std::endl;
188            throw new std::exception();
189        }
190    }
191
192    cl_int err;
193
194    std::cout<<"compiling CL source\n";
195    cl::Program::Sources sources(1, std::make_pair(j.Src.c_str(), j.Src.length()));
196
197    cl::Program program = cl::Program(*context, sources, &err);
198    if (err != CL_SUCCESS) {
199        std::cerr << "Program::Program() failed (" << err << ")\n";
200        throw new std::exception();
201    }
202
203    err = program.build(devices);
204    if (err != CL_SUCCESS) {
205
206        if(err == CL_BUILD_PROGRAM_FAILURE)
207        {
208            cl::string str = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]);
209
210            std::cout << " \n\t\t\tBUILD LOG\n";
211            std::cout << " ************************************************\n";
212                        std::cout << str.c_str() << std::endl;
213            std::cout << " ************************************************\n";
214        }
215
216        std::cerr << "Program::build() failed (" << err << ")\n";
217        throw new std::exception();
218    }
219
220    if (kernel != 0)
221        delete kernel;
222
223    kernel = new cl::Kernel(program, "bruteforceKernel", &err);
224    if (err != CL_SUCCESS) {
225        std::cerr << "Kernel::Kernel() failed (" << err << ")\n";
226        throw new std::exception();
227    }
228}
229
230JobResult Cryptool::doOpenCLJob(const Job& j)
231{
232    cl_int err;
233
234    buildKernel(j);
235
236    cl::CommandQueue queue(*context, devices[0], 0, &err);
237    if (err != CL_SUCCESS) {
238        std::cerr << "CommandQueue::CommandQueue() failed (" << err << ")\n";
239        throw new std::exception();
240    }
241
242    // key
243    cl::Buffer keybuffer = cl::Buffer(*context, CL_MEM_READ_ONLY, j.KeySize, NULL, &err);
244    if(err != CL_SUCCESS)
245    {
246        std::cerr << "Failed to allocate keybuffer(" << err << ")\n";
247        throw new std::exception();
248    }
249
250    err = queue.enqueueWriteBuffer(keybuffer, 1, 0, j.KeySize, j.Key);
251
252    if(err != CL_SUCCESS)
253    {
254        std::cerr << "Failed write to keybuffer(" << err << ")\n";
255        throw new std::exception();
256    }
257
258    err = kernel->setArg(0, keybuffer);
259    if (err != CL_SUCCESS) {
260        std::cerr << "Kernel::setArg() failed (" << err << ")\n";
261        throw new std::exception();
262    }
263
264    // results
265    cl::Buffer entropies = cl::Buffer(*context, CL_MEM_WRITE_ONLY, sizeof(float)*j.ResultSize, NULL, &err);
266
267    if(err != CL_SUCCESS)
268    {
269        std::cerr << "Failed allocate to entropybuffer(" << err << ")\n";
270        throw new std::exception();
271    }
272
273    err = kernel->setArg(1, entropies);
274
275    if (err != CL_SUCCESS) {
276        std::cerr << "Kernel::setArg() failed (" << err << ")\n";
277        throw new std::exception();
278    }
279
280    //execute:
281    std::cout<<"Running CL program\n";
282    err = queue.enqueueNDRangeKernel(
283        *kernel, cl::NullRange, cl::NDRange(4, 4), cl::NDRange(2, 2)
284    );
285
286    if (err != CL_SUCCESS) {
287        std::cerr << "CommandQueue::enqueueNDRangeKernel()" \
288            " failed (" << err << ")\n";
289        throw new std::exception();
290    }
291
292    err = queue.finish();
293    if (err != CL_SUCCESS) {
294        std::cerr << "Event::wait() failed (" << err << ")\n";
295        throw new std::exception();
296    }
297
298    std::cout<<"Done\nPassed!\n";
299
300    float* localEntropy = new float[j.ResultSize];
301
302    queue.enqueueReadBuffer(entropies, 1, 0, sizeof(float)*j.ResultSize, localEntropy);
303
304    //check results:
305    JobResult res;
306    res.ResultList.resize(j.ResultSize);
307    initTop(res.ResultList, j.LargerThen);
308
309    for(int i=0; i<j.Size; ++i)
310    {
311        std::list<std::pair<float, int> >::iterator it = isInTop(res.ResultList, localEntropy[i], j.LargerThen);
312        if (it != res.ResultList.end())
313            pushInTop(res.ResultList, it, localEntropy[i], i);
314    }
315
316    return res;
317}
318
319
320
321void Cryptool::pushInTop(std::list<std::pair<float, int> >& top, std::list<std::pair<float, int> >::iterator it, float val, int k) {
322        top.insert(it, std::pair<float, int>(val, k));
323        top.pop_back();
324}
325
326std::list<std::pair<float, int> >::iterator Cryptool::isInTop(std::list<std::pair<float, int> >& top, float val, bool LargerThen) {
327        if (LargerThen)
328        {
329                for (std::list<std::pair<float, int> >::iterator k = top.begin(); k != top.end(); k++)
330                        if (val > k->first)
331                                return k;
332        }
333        else
334        {
335                for (std::list<std::pair<float, int> >::iterator k = top.begin(); k != top.end(); k++)
336                        if (val < k->first)
337                                return k;
338        }
339
340        return top.end();
341}
342
343void Cryptool::initTop(std::list<std::pair<float, int> >& top, bool LargerThen) {
344        for (std::list<std::pair<float, int> >::iterator k = top.begin(); k != top.end(); k++)
345        {
346            if (LargerThen)
347                k->first = -1000000.0;
348            else
349                k->first = 1000000.0;
350        }
351}
Note: See TracBrowser for help on using the repository browser.