summaryrefslogtreecommitdiffhomepage
path: root/windows/nsis-plugins/src/string/string.cpp
blob: 6071e6303dc33307109548c39a00de2ca64a6c23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "stdafx.h"
#include <nsis/pluginapi.h>
#include <stdexcept>
#include <string>

// Suppress warnings caused by broken legacy code
#pragma warning (push)
#pragma warning (disable: 4005)
#include <nsis/pluginapi.h>
#pragma warning (pop)

namespace
{

std::wstring PopString()
{
	//
	// NSIS functions popstring() and popstringn() require that you definitely size the buffer
	// before popping the string. Let's do it ourselves instead.
	//

	if (!g_stacktop || !*g_stacktop)
	{
		throw std::runtime_error("NSIS variable stack is corrupted");
	}

	stack_t *th = *g_stacktop;

	std::wstring copy(th->text);

	*g_stacktop = th->next;
	GlobalFree((HGLOBAL)th);

	return copy;
}

} // anonymous namespace

//
// Find "string" "substring" begin_offset
//
// Return the position of "substring" in "string", starting from 'begin_offset'.
// If the substring is not found or if an error occurs, return -1.
//

void __declspec(dllexport) NSISCALL Find
(
	HWND hwndParent,
	int string_size,
	LPTSTR variables,
	stack_t **stacktop,
	extra_parameters *extra,
	...
)
{
	EXDLL_INIT();

	try
	{
		const auto searchString = PopString();
		const auto substring = PopString();
		const auto offset = popint();
		const auto position = searchString.find(substring, offset);

		if (std::wstring::npos == position)
		{
			pushint(-1);
			return;
		}

		pushint((int)position);
	}
	catch (const std::exception &)
	{
		pushint(-1);
	}
	catch (...)
	{
		pushint(-1);
	}
}