Check-in [e5e44cc317]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:add TWAPI upstream changes
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: e5e44cc317b5d042fef3b05945ba00dee6ceedf9
User & Date: chw 2016-05-17 07:28:48.718
Context
2016-05-19
06:41
add tk upstream changes check-in: 3287f84d16 user: chw tags: trunk
2016-05-17
07:28
add TWAPI upstream changes check-in: e5e44cc317 user: chw tags: trunk
2016-05-16
18:52
add libjpeg-turbo 1.4.2 to AndroWish build check-in: f92664f26b user: chw tags: trunk
Changes
Unified Diff Ignore Whitespace Patch
jni/3dcanvas/tclconfig/README.txt became a regular file.
jni/3dcanvas/tclconfig/tcl.m4 became a regular file.
jni/SDL2/CMakeLists.txt became a regular file.
jni/sdl2tk/tests/winDialog.test became a regular file.
jni/sdl2tk/unix/configure.in became executable.
jni/tcl/doc/GetCwd.3 became executable.
jni/tcl/doc/GetVersion.3 became executable.
jni/tcl/doc/lset.n became executable.
jni/tcl/library/tzdata/Europe/Volgograd became executable.
jni/tcl/tests/lsetComp.test became executable.
jni/tclkit/vqtcl/tclconfig/tcl.m4 became a regular file.
jni/tcludp/tclconfig/tcl.m4 became a regular file.
jni/tdom/tclconfig/README.txt became a regular file.
jni/tkimg/ico/configure became a regular file.
jni/tkimg/png/configure became a regular file.
jni/tkimg/tiff/configure became a regular file.
jni/tkpath/tclconfig/tcl.m4 became a regular file.
jni/tktreectrl/tclconfig/tcl.m4 became a regular file.
jni/tls/tclconfig/tcl.m4 became a regular file.
jni/zint/backend/dmatrix.c became executable.
jni/zint/backend/library.c became executable.
Changes to undroid/twapi/configure.
7688
7689
7690
7691
7692
7693
7694

7695
7696
7697
7698
7699
7700
7701
	    twapi/base/tclobjs.c
	    twapi/base/threadpool.c
	    twapi/base/trap.c
	    twapi/base/twapi.c
	    twapi/base/twine.c
	    twapi/base/util.c
	    twapi/base/win.c


	    twapi/account/account.c

	    twapi/apputil/apputil.c

	    twapi/clipboard/clipboard.c








>







7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
	    twapi/base/tclobjs.c
	    twapi/base/threadpool.c
	    twapi/base/trap.c
	    twapi/base/twapi.c
	    twapi/base/twine.c
	    twapi/base/util.c
	    twapi/base/win.c
	    twapi/base/winchars.c

	    twapi/account/account.c

	    twapi/apputil/apputil.c

	    twapi/clipboard/clipboard.c

Changes to undroid/twapi/configure.in.
105
106
107
108
109
110
111

112
113
114
115
116
117
118
	    twapi/base/tclobjs.c
	    twapi/base/threadpool.c
	    twapi/base/trap.c
	    twapi/base/twapi.c
	    twapi/base/twine.c
	    twapi/base/util.c
	    twapi/base/win.c


	    twapi/account/account.c

	    twapi/apputil/apputil.c

	    twapi/clipboard/clipboard.c








>







105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
	    twapi/base/tclobjs.c
	    twapi/base/threadpool.c
	    twapi/base/trap.c
	    twapi/base/twapi.c
	    twapi/base/twine.c
	    twapi/base/util.c
	    twapi/base/win.c
	    twapi/base/winchars.c

	    twapi/account/account.c

	    twapi/apputil/apputil.c

	    twapi/clipboard/clipboard.c

Changes to undroid/twapi/twapi/account/account.c.
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    LOCALGROUP_INFO_1 *groupinfoP = (LOCALGROUP_INFO_1 *) infoP;
    Tcl_Obj    *objs[2];
    int nobjs = 1;

    switch (info_level) {
    case 1:
        ++nobjs;
        objs[1] = ObjFromUnicode(groupinfoP->lgrpi1_comment);
        /* FALL THRU */
    case 0:
        objs[0] = ObjFromUnicode(groupinfoP->lgrpi1_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(nobjs, objs);







|


|







57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    LOCALGROUP_INFO_1 *groupinfoP = (LOCALGROUP_INFO_1 *) infoP;
    Tcl_Obj    *objs[2];
    int nobjs = 1;

    switch (info_level) {
    case 1:
        ++nobjs;
        objs[1] = ObjFromWinChars(groupinfoP->lgrpi1_comment);
        /* FALL THRU */
    case 0:
        objs[0] = ObjFromWinChars(groupinfoP->lgrpi1_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(nobjs, objs);
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

    switch (info_level) {
    case 1:
        ++objc;
        objv[1] = ObjFromLong(groupinfoP->grui1_attributes);
        /* FALLTHRU */
    case 0:
        objv[0] = ObjFromUnicode(groupinfoP->grui1_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(objc, objv);







|







87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

    switch (info_level) {
    case 1:
        ++objc;
        objv[1] = ObjFromLong(groupinfoP->grui1_attributes);
        /* FALLTHRU */
    case 0:
        objv[0] = ObjFromWinChars(groupinfoP->grui1_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(objc, objv);
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    nobjs = 1;                  /* name field always present */
    switch (info_level) {
    case 24:
        usri24P = (struct _TWAPI_USER_INFO_24 *)infoP;
        if (! usri24P->usri24_internet_identity)
            return ObjFromEmptyString();
        objs[0] = ObjFromDWORD(usri24P->usri24_flags);
        objs[1] = ObjFromUnicode(usri24P->usri24_internet_provider_name);
        objs[2] = ObjFromUnicode(usri24P->usri24_internet_principal_name);
        objs[3] = ObjFromSIDNoFail(usri24P->usri24_user_sid);
        nobjs = 4;
        break;

    case 3:
    case 4:
        nobjs += 5;
        /* NOTE even when fields names are the same, level 3 and
           level 4 HAVE DIFFERENT FIELD OFFSETS */
        if (info_level == 3) {
            objs[24] = ObjFromDWORD(((USER_INFO_3*)infoP)->usri3_user_id);
            objs[25] = ObjFromDWORD(((USER_INFO_3*)infoP)->usri3_primary_group_id);
            objs[26] = ObjFromUnicode(((USER_INFO_3*)infoP)->usri3_profile);
            objs[27] = ObjFromUnicode(((USER_INFO_3*)infoP)->usri3_home_dir_drive);
            objs[28] = ObjFromDWORD(((USER_INFO_3*)infoP)->usri3_password_expired);
        } else {
            objs[24] = ObjFromSIDNoFail(((USER_INFO_4*)infoP)->usri4_user_sid);
            objs[25] = ObjFromDWORD(((USER_INFO_4*)infoP)->usri4_primary_group_id);
            objs[26] = ObjFromUnicode(((USER_INFO_4*)infoP)->usri4_profile);
            objs[27] = ObjFromUnicode(((USER_INFO_4*)infoP)->usri4_home_dir_drive);
            objs[28] = ObjFromDWORD(((USER_INFO_4*)infoP)->usri4_password_expired);
        }
        /* FALL THROUGH */
    case 2:
        nobjs += 16;
        objs[8] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_auth_flags);
        objs[9] = ObjFromUnicode(((USER_INFO_2*)infoP)->usri2_full_name);
        objs[10] = ObjFromUnicode(((USER_INFO_2*)infoP)->usri2_usr_comment);
        objs[11] = ObjFromUnicode(((USER_INFO_2*)infoP)->usri2_parms);
        objs[12] = ObjFromUnicode(((USER_INFO_2*)infoP)->usri2_workstations);
        objs[13] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_last_logon);
        objs[14] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_last_logoff);
        objs[15] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_acct_expires);
        if (((USER_INFO_2*)infoP)->usri2_max_storage == (DWORD) -1)
            objs[16] = ObjFromLong(-1); /* Do not want UINT_MAX */
        else 
            objs[16] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_max_storage);
        objs[17] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_units_per_week);
        objs[18] = ObjFromByteArray(((USER_INFO_2*)infoP)->usri2_logon_hours,21);
        objs[19] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_bad_pw_count);
        objs[20] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_num_logons);
        objs[21] = ObjFromUnicode(((USER_INFO_2*)infoP)->usri2_logon_server);
        objs[22] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_country_code);
        objs[23] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_code_page);
        /* FALL THROUGH */
    case 1:
        nobjs += 7;
        objs[1] = ObjFromUnicode(((USER_INFO_1*)infoP)->usri1_password ? ((USER_INFO_1*)infoP)->usri1_password : L"");
        objs[2] = ObjFromDWORD(((USER_INFO_1*)infoP)->usri1_password_age);
        objs[3] = ObjFromDWORD(((USER_INFO_1*)infoP)->usri1_priv);
        objs[4] = ObjFromUnicode(((USER_INFO_1*)infoP)->usri1_home_dir);
        objs[5] = ObjFromUnicode(((USER_INFO_1*)infoP)->usri1_comment);
        objs[6] = ObjFromDWORD(((USER_INFO_1*)infoP)->usri1_flags);
        objs[7] = ObjFromUnicode(((USER_INFO_1*)infoP)->usri1_script_path);
        /* FALL THROUGH */
    case 0:
        objs[0] = ObjFromUnicode(((USER_INFO_0*)infoP)->usri0_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(nobjs, objs);







|
|












|
|




|
|






|
|
|
|











|





|


|
|

|


|







131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    nobjs = 1;                  /* name field always present */
    switch (info_level) {
    case 24:
        usri24P = (struct _TWAPI_USER_INFO_24 *)infoP;
        if (! usri24P->usri24_internet_identity)
            return ObjFromEmptyString();
        objs[0] = ObjFromDWORD(usri24P->usri24_flags);
        objs[1] = ObjFromWinChars(usri24P->usri24_internet_provider_name);
        objs[2] = ObjFromWinChars(usri24P->usri24_internet_principal_name);
        objs[3] = ObjFromSIDNoFail(usri24P->usri24_user_sid);
        nobjs = 4;
        break;

    case 3:
    case 4:
        nobjs += 5;
        /* NOTE even when fields names are the same, level 3 and
           level 4 HAVE DIFFERENT FIELD OFFSETS */
        if (info_level == 3) {
            objs[24] = ObjFromDWORD(((USER_INFO_3*)infoP)->usri3_user_id);
            objs[25] = ObjFromDWORD(((USER_INFO_3*)infoP)->usri3_primary_group_id);
            objs[26] = ObjFromWinChars(((USER_INFO_3*)infoP)->usri3_profile);
            objs[27] = ObjFromWinChars(((USER_INFO_3*)infoP)->usri3_home_dir_drive);
            objs[28] = ObjFromDWORD(((USER_INFO_3*)infoP)->usri3_password_expired);
        } else {
            objs[24] = ObjFromSIDNoFail(((USER_INFO_4*)infoP)->usri4_user_sid);
            objs[25] = ObjFromDWORD(((USER_INFO_4*)infoP)->usri4_primary_group_id);
            objs[26] = ObjFromWinChars(((USER_INFO_4*)infoP)->usri4_profile);
            objs[27] = ObjFromWinChars(((USER_INFO_4*)infoP)->usri4_home_dir_drive);
            objs[28] = ObjFromDWORD(((USER_INFO_4*)infoP)->usri4_password_expired);
        }
        /* FALL THROUGH */
    case 2:
        nobjs += 16;
        objs[8] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_auth_flags);
        objs[9] = ObjFromWinChars(((USER_INFO_2*)infoP)->usri2_full_name);
        objs[10] = ObjFromWinChars(((USER_INFO_2*)infoP)->usri2_usr_comment);
        objs[11] = ObjFromWinChars(((USER_INFO_2*)infoP)->usri2_parms);
        objs[12] = ObjFromWinChars(((USER_INFO_2*)infoP)->usri2_workstations);
        objs[13] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_last_logon);
        objs[14] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_last_logoff);
        objs[15] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_acct_expires);
        if (((USER_INFO_2*)infoP)->usri2_max_storage == (DWORD) -1)
            objs[16] = ObjFromLong(-1); /* Do not want UINT_MAX */
        else 
            objs[16] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_max_storage);
        objs[17] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_units_per_week);
        objs[18] = ObjFromByteArray(((USER_INFO_2*)infoP)->usri2_logon_hours,21);
        objs[19] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_bad_pw_count);
        objs[20] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_num_logons);
        objs[21] = ObjFromWinChars(((USER_INFO_2*)infoP)->usri2_logon_server);
        objs[22] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_country_code);
        objs[23] = ObjFromDWORD(((USER_INFO_2*)infoP)->usri2_code_page);
        /* FALL THROUGH */
    case 1:
        nobjs += 7;
        objs[1] = ObjFromWinChars(((USER_INFO_1*)infoP)->usri1_password ? ((USER_INFO_1*)infoP)->usri1_password : L"");
        objs[2] = ObjFromDWORD(((USER_INFO_1*)infoP)->usri1_password_age);
        objs[3] = ObjFromDWORD(((USER_INFO_1*)infoP)->usri1_priv);
        objs[4] = ObjFromWinChars(((USER_INFO_1*)infoP)->usri1_home_dir);
        objs[5] = ObjFromWinChars(((USER_INFO_1*)infoP)->usri1_comment);
        objs[6] = ObjFromDWORD(((USER_INFO_1*)infoP)->usri1_flags);
        objs[7] = ObjFromWinChars(((USER_INFO_1*)infoP)->usri1_script_path);
        /* FALL THROUGH */
    case 0:
        objs[0] = ObjFromWinChars(((USER_INFO_0*)infoP)->usri0_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(nobjs, objs);
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        } else {
            objs[3] = ObjFromDWORD(((GROUP_INFO_3*)infoP)->grpi3_attributes);
            objs[2] = ObjFromSIDNoFail(((GROUP_INFO_3*)infoP)->grpi3_group_sid);
        }
        /* FALL THROUGH */
    case 1:
        nobjs += 1;
        objs[1] = ObjFromUnicode(((GROUP_INFO_1*)infoP)->grpi1_comment);
        /* FALL THROUGH */
    case 0:
        objs[0] = ObjFromUnicode(((GROUP_INFO_0*)infoP)->grpi0_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(nobjs, objs);







|


|







235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        } else {
            objs[3] = ObjFromDWORD(((GROUP_INFO_3*)infoP)->grpi3_attributes);
            objs[2] = ObjFromSIDNoFail(((GROUP_INFO_3*)infoP)->grpi3_group_sid);
        }
        /* FALL THROUGH */
    case 1:
        nobjs += 1;
        objs[1] = ObjFromWinChars(((GROUP_INFO_1*)infoP)->grpi1_comment);
        /* FALL THROUGH */
    case 0:
        objs[0] = ObjFromWinChars(((GROUP_INFO_0*)infoP)->grpi0_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(nobjs, objs);
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    Tcl_Obj    *objs[1];

    /* Even though only one field, for consistency with other
       structures, we have to return as a list */

    switch (info_level) {
    case 0:
        objs[0] = ObjFromUnicode(((LOCALGROUP_USERS_INFO_0 *)infoP)->lgrui0_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(1, objs);







|







262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    Tcl_Obj    *objs[1];

    /* Even though only one field, for consistency with other
       structures, we have to return as a list */

    switch (info_level) {
    case 0:
        objs[0] = ObjFromWinChars(((LOCALGROUP_USERS_INFO_0 *)infoP)->lgrui0_name);
        break;
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

    return ObjNewList(1, objs);
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
        objv[objc++] = ObjFromSIDNoFail(((LOCALGROUP_MEMBERS_INFO_0 *)infoP)->lgrmi0_sid);
        break;
    case 1:
    case 2:
        objv[objc++] = ObjFromSIDNoFail(((LOCALGROUP_MEMBERS_INFO_1 *)infoP)->lgrmi1_sid);
        objv[objc++] = ObjFromLong(((LOCALGROUP_MEMBERS_INFO_1 *)infoP)->lgrmi1_sidusage);
        if (info_level == 1) {
            objv[objc++] = ObjFromUnicode(((LOCALGROUP_MEMBERS_INFO_1 *)infoP)->lgrmi1_name);
        } else {
            objv[objc++] = ObjFromUnicode(((LOCALGROUP_MEMBERS_INFO_2 *)infoP)->lgrmi2_domainandname);
        }
        break;
    case 3:
        objv[objc++] = ObjFromUnicode(((LOCALGROUP_MEMBERS_INFO_3 *)infoP)->lgrmi3_domainandname);
        break;
        
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }








|

|



|







291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
        objv[objc++] = ObjFromSIDNoFail(((LOCALGROUP_MEMBERS_INFO_0 *)infoP)->lgrmi0_sid);
        break;
    case 1:
    case 2:
        objv[objc++] = ObjFromSIDNoFail(((LOCALGROUP_MEMBERS_INFO_1 *)infoP)->lgrmi1_sid);
        objv[objc++] = ObjFromLong(((LOCALGROUP_MEMBERS_INFO_1 *)infoP)->lgrmi1_sidusage);
        if (info_level == 1) {
            objv[objc++] = ObjFromWinChars(((LOCALGROUP_MEMBERS_INFO_1 *)infoP)->lgrmi1_name);
        } else {
            objv[objc++] = ObjFromWinChars(((LOCALGROUP_MEMBERS_INFO_2 *)infoP)->lgrmi2_domainandname);
        }
        break;
    case 3:
        objv[objc++] = ObjFromWinChars(((LOCALGROUP_MEMBERS_INFO_3 *)infoP)->lgrmi3_domainandname);
        break;
        
    default:
        Twapi_WrongLevelError(interp, info_level);
        return NULL;
    }

402
403
404
405
406
407
408
409
410

411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    if (level != 1) {
        ObjSetStaticResult(interp, "Invalid or unsupported user or group information level specified");
        return TCL_ERROR;
    }
    return TwapiNetUserOrGroupGetInfoHelper(interp, servername, groupname, level, 2);
}

static int Twapi_NetUserAddObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    DWORD       priv, flags;
    NET_API_STATUS status;
    USER_INFO_1    userinfo;
    DWORD          error_parm;
    char          *error_field;
    WCHAR         *decryptedP;
    int            decrypted_len;
    SWSMark mark;
    
    CHECK_NARGS(interp, objc, 9);

    /* As always to avoid shimmering problems, extract integer object first */
    CHECK_INTEGER_OBJ(interp, priv, objv[4]);
    CHECK_INTEGER_OBJ(interp, flags, objv[7]);

    ObjToUnicodeCleanup();

    userinfo.usri1_name        = ObjToUnicode(objv[2]);

    /* Now get the decrypted password object */

    mark = SWSPushMark();
    decryptedP = ObjDecryptPasswordSWS(objv[3], &decrypted_len);
    userinfo.usri1_password    = decryptedP;
    userinfo.usri1_password_age = 0;
    userinfo.usri1_priv        = priv;
    userinfo.usri1_home_dir    = ObjToLPWSTR_NULL_IF_EMPTY(objv[5]);
    userinfo.usri1_comment     = ObjToLPWSTR_NULL_IF_EMPTY(objv[6]);
    userinfo.usri1_flags       = flags;
    userinfo.usri1_script_path = ObjToLPWSTR_NULL_IF_EMPTY(objv[8]);

    status = NetUserAdd(ObjToLPWSTR_NULL_IF_EMPTY(objv[1]), 1, (LPBYTE) &userinfo, &error_parm);

    SecureZeroMemory(decryptedP, decrypted_len);
    SWSPopMark(mark);

    if (status == NERR_Success)
        return TCL_OK;

    /* Indicate the parameter */
    switch (error_parm) {
    case 0: error_field = "user name "; break;







|

>







|




|
|

<
<
|


>
|












|







402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426


427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    if (level != 1) {
        ObjSetStaticResult(interp, "Invalid or unsupported user or group information level specified");
        return TCL_ERROR;
    }
    return TwapiNetUserOrGroupGetInfoHelper(interp, servername, groupname, level, 2);
}

static int Twapi_NetUserAddObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    DWORD       priv, flags;
    NET_API_STATUS status;
    USER_INFO_1    userinfo;
    DWORD          error_parm;
    char          *error_field;
    WCHAR         *decryptedP;
    int            decrypted_len;
    MemLifoMarkHandle mark = NULL;
    
    CHECK_NARGS(interp, objc, 9);

    /* As always to avoid shimmering problems, extract integer object first */
    CHECK_DWORD_OBJ(interp, priv, objv[4]);
    CHECK_DWORD_OBJ(interp, flags, objv[7]);



    userinfo.usri1_name        = ObjToWinChars(objv[2]);

    /* Now get the decrypted password object */
    TWAPI_ASSERT(SWS() == ticP->memlifoP);
    mark = MemLifoPushMark(ticP->memlifoP);
    decryptedP = ObjDecryptPasswordSWS(objv[3], &decrypted_len);
    userinfo.usri1_password    = decryptedP;
    userinfo.usri1_password_age = 0;
    userinfo.usri1_priv        = priv;
    userinfo.usri1_home_dir    = ObjToLPWSTR_NULL_IF_EMPTY(objv[5]);
    userinfo.usri1_comment     = ObjToLPWSTR_NULL_IF_EMPTY(objv[6]);
    userinfo.usri1_flags       = flags;
    userinfo.usri1_script_path = ObjToLPWSTR_NULL_IF_EMPTY(objv[8]);

    status = NetUserAdd(ObjToLPWSTR_NULL_IF_EMPTY(objv[1]), 1, (LPBYTE) &userinfo, &error_parm);

    SecureZeroMemory(decryptedP, decrypted_len);
    MemLifoPopMark(mark);

    if (status == NERR_Success)
        return TCL_OK;

    /* Indicate the parameter */
    switch (error_parm) {
    case 0: error_field = "user name "; break;
543
544
545
546
547
548
549
550
551

552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617

618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638

639

640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656

657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684

685

686
687
688
689
690
691
692
        break;
    default:
        return ERROR_INVALID_PARAMETER;
    }
    return NetUserSetInfo(servername, username, func, (LPBYTE) &userinfo, NULL);
}

int Twapi_NetUserSetInfoObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    int func;
    LPWSTR s1, s3;
    DWORD   dw;
    TwapiResult result;
    Tcl_Obj *s1Obj, *s2Obj;
    WCHAR *passwordP = NULL;
    int    password_len;
    SWSMark mark = NULL;

    /* Note: to prevent shimmering issues, we do not extract the internal
       string pointers s1 and s2 until integer args have been parsed */

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(func), GETOBJ(s1Obj), 
                     GETOBJ(s2Obj), ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    ObjToUnicodeCleanup();

    result.type = TRT_BADFUNCTIONCODE;

    switch (func) {
    case 1005: // This block of function codes maps directly to
    case 1008: // the function codes accepted by Twapi_NetUserSetInfoDWORD.
    case 1010: // A bit klugy but the easiest way to keep backwards
    case 1017: // compatibility.
    case 1024: 
        CHECK_INTEGER_OBJ(interp, dw, objv[4]);
        s1 = ObjToUnicode(s1Obj);
        if (*s1 == 0)
            s1 = NULL;
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = Twapi_NetUserSetInfoDWORD(func, s1, ObjToUnicode(s2Obj), dw);
        break;
        
    case 0:    // See note above except that this maps to 
    case 1003: // Twapi_NetUserSetInfoLPWSTR instead of the
    case 1006: // Twapi_NetUserSetInfoDWORD functions
    case 1007:
    case 1009:
    case 1011:
    case 1052:
    case 1053:
        if (func == 1003) {
            mark = SWSPushMark();
            s3 = ObjDecryptPasswordSWS(objv[4], &password_len);
        } else
            s3 = ObjToUnicode(objv[4]);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = Twapi_NetUserSetInfoLPWSTR(func, s1,
                                                       ObjToUnicode(s2Obj),
                                                       s3);
        if (func == 1003) {
            SecureZeroMemory(s3, password_len);
            SWSPopMark(mark);
        }
        break;
    }

    return TwapiSetResult(interp, &result);
}

static int Twapi_NetUserModalsGetObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TCL_RESULT res;
    MemLifo *memlifoP = ticP->memlifoP;
    MemLifoMarkHandle mark;
    DWORD level, sz;
    Tcl_Obj *structObj;
    LPWSTR server_name;
    LPBYTE pv;
    NET_API_STATUS status;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETEMPTYASNULL(server_name),
                         GETINT(level), GETOBJ(structObj), ARGEND);
    if (res == TCL_OK) {
        switch (level) {
        case 0: sz = sizeof(USER_MODALS_INFO_0); break;
        case 1: sz = sizeof(USER_MODALS_INFO_1); break;
        case 2: sz = sizeof(USER_MODALS_INFO_2); break;
        case 3: sz = sizeof(USER_MODALS_INFO_3); break;
        default:

            res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);

        }
        if (res == TCL_OK) {
            status = NetUserModalsGet(server_name, level, &pv);
            if (status == NERR_Success) {
                res = ObjFromCStruct(interp, pv, sz, structObj, CSTRUCT_RETURN_DICT, NULL);
                NetApiBufferFree(pv);
            } else
                res = Twapi_AppendSystemError(interp, status);
        }
    }

    MemLifoPopMark(mark);
    return res;
}

static int Twapi_NetUserModalsSetObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TCL_RESULT res;
    MemLifo *memlifoP = ticP->memlifoP;
    MemLifoMarkHandle mark;
    DWORD level, sz, actual_sz;
    Tcl_Obj *objP;
    LPWSTR server_name;
    void *pv;
    NET_API_STATUS status;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETEMPTYASNULL(server_name),
                         GETINT(level), GETOBJ(objP), ARGEND);
    if (res == TCL_OK) {
        switch (level) {
        case 0: sz = sizeof(USER_MODALS_INFO_0); break;
        case 1: sz = sizeof(USER_MODALS_INFO_1); break;
        case 2: sz = sizeof(USER_MODALS_INFO_2); break;
        case 3: sz = sizeof(USER_MODALS_INFO_3); break;
        case 1001: sz = sizeof(USER_MODALS_INFO_1001); break;
        case 1002: sz = sizeof(USER_MODALS_INFO_1002); break;
        case 1003: sz = sizeof(USER_MODALS_INFO_1003); break;
        case 1004: sz = sizeof(USER_MODALS_INFO_1004); break;
        case 1005: sz = sizeof(USER_MODALS_INFO_1005); break;
        case 1006: sz = sizeof(USER_MODALS_INFO_1006); break;
        case 1007: sz = sizeof(USER_MODALS_INFO_1007); break;
        default:

            res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);

        }
        if (res == TCL_OK) {
            res = TwapiCStructParse(interp, memlifoP, objP, 0, &actual_sz, &pv);
            if (res == TCL_OK) {
                if (sz != actual_sz)
                    res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);
                else {







|

>





<

|










<
<








|
|



|











|


|



|



|







|

>









<
<










>

>















|

>









<
<

















>

>







543
544
545
546
547
548
549
550
551
552
553
554
555
556
557

558
559
560
561
562
563
564
565
566
567
568
569


570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625


626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665


666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        break;
    default:
        return ERROR_INVALID_PARAMETER;
    }
    return NetUserSetInfo(servername, username, func, (LPBYTE) &userinfo, NULL);
}

int Twapi_NetUserSetInfoObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int func;
    LPWSTR s1, s3;
    DWORD   dw;
    TwapiResult result;
    Tcl_Obj *s1Obj, *s2Obj;

    int    password_len;
    MemLifoMarkHandle mark = NULL;

    /* Note: to prevent shimmering issues, we do not extract the internal
       string pointers s1 and s2 until integer args have been parsed */

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(func), GETOBJ(s1Obj), 
                     GETOBJ(s2Obj), ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;



    result.type = TRT_BADFUNCTIONCODE;

    switch (func) {
    case 1005: // This block of function codes maps directly to
    case 1008: // the function codes accepted by Twapi_NetUserSetInfoDWORD.
    case 1010: // A bit klugy but the easiest way to keep backwards
    case 1017: // compatibility.
    case 1024: 
        CHECK_DWORD_OBJ(interp, dw, objv[4]);
        s1 = ObjToWinChars(s1Obj);
        if (*s1 == 0)
            s1 = NULL;
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = Twapi_NetUserSetInfoDWORD(func, s1, ObjToWinChars(s2Obj), dw);
        break;
        
    case 0:    // See note above except that this maps to 
    case 1003: // Twapi_NetUserSetInfoLPWSTR instead of the
    case 1006: // Twapi_NetUserSetInfoDWORD functions
    case 1007:
    case 1009:
    case 1011:
    case 1052:
    case 1053:
        if (func == 1003) {
            mark = MemLifoPushMark(ticP->memlifoP);
            s3 = ObjDecryptPasswordSWS(objv[4], &password_len);
        } else
            s3 = ObjToWinChars(objv[4]);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = Twapi_NetUserSetInfoLPWSTR(func, s1,
                                                       ObjToWinChars(s2Obj),
                                                       s3);
        if (func == 1003) {
            SecureZeroMemory(s3, password_len);
            MemLifoPopMark(mark);
        }
        break;
    }

    return TwapiSetResult(interp, &result);
}

static int Twapi_NetUserModalsGetObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    TCL_RESULT res;
    MemLifo *memlifoP = ticP->memlifoP;
    MemLifoMarkHandle mark;
    DWORD level, sz;
    Tcl_Obj *structObj;
    LPWSTR server_name;
    LPBYTE pv;
    NET_API_STATUS status;



    mark = MemLifoPushMark(memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETEMPTYASNULL(server_name),
                         GETINT(level), GETOBJ(structObj), ARGEND);
    if (res == TCL_OK) {
        switch (level) {
        case 0: sz = sizeof(USER_MODALS_INFO_0); break;
        case 1: sz = sizeof(USER_MODALS_INFO_1); break;
        case 2: sz = sizeof(USER_MODALS_INFO_2); break;
        case 3: sz = sizeof(USER_MODALS_INFO_3); break;
        default:
            sz = 0; /* To keep gcc happy */
            res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);
            break;
        }
        if (res == TCL_OK) {
            status = NetUserModalsGet(server_name, level, &pv);
            if (status == NERR_Success) {
                res = ObjFromCStruct(interp, pv, sz, structObj, CSTRUCT_RETURN_DICT, NULL);
                NetApiBufferFree(pv);
            } else
                res = Twapi_AppendSystemError(interp, status);
        }
    }

    MemLifoPopMark(mark);
    return res;
}

static int Twapi_NetUserModalsSetObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    TCL_RESULT res;
    MemLifo *memlifoP = ticP->memlifoP;
    MemLifoMarkHandle mark;
    DWORD level, sz, actual_sz;
    Tcl_Obj *objP;
    LPWSTR server_name;
    void *pv;
    NET_API_STATUS status;



    mark = MemLifoPushMark(memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETEMPTYASNULL(server_name),
                         GETINT(level), GETOBJ(objP), ARGEND);
    if (res == TCL_OK) {
        switch (level) {
        case 0: sz = sizeof(USER_MODALS_INFO_0); break;
        case 1: sz = sizeof(USER_MODALS_INFO_1); break;
        case 2: sz = sizeof(USER_MODALS_INFO_2); break;
        case 3: sz = sizeof(USER_MODALS_INFO_3); break;
        case 1001: sz = sizeof(USER_MODALS_INFO_1001); break;
        case 1002: sz = sizeof(USER_MODALS_INFO_1002); break;
        case 1003: sz = sizeof(USER_MODALS_INFO_1003); break;
        case 1004: sz = sizeof(USER_MODALS_INFO_1004); break;
        case 1005: sz = sizeof(USER_MODALS_INFO_1005); break;
        case 1006: sz = sizeof(USER_MODALS_INFO_1006); break;
        case 1007: sz = sizeof(USER_MODALS_INFO_1007); break;
        default:
            sz = 0; /* To keep gcc happy */
            res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);
            break;
        }
        if (res == TCL_OK) {
            res = TwapiCStructParse(interp, memlifoP, objP, 0, &actual_sz, &pv);
            if (res == TCL_OK) {
                if (sz != actual_sz)
                    res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);
                else {
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
    TwapiNetEnumContext netenum;
    int struct_size;
    Tcl_Obj *(*objfn)(Tcl_Interp *, LPBYTE, DWORD);
    Tcl_Obj *objs[4];
    Tcl_Obj *enumObj = NULL;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, ARGSKIP, ARGTERM) != TCL_OK)
        return TCL_ERROR;


    /* NOTE : to prevent shimmering issues all wide strings are
       extracted from s1Obj AFTER all other arguments have been extracted
    */







<
<







712
713
714
715
716
717
718


719
720
721
722
723
724
725
    TwapiNetEnumContext netenum;
    int struct_size;
    Tcl_Obj *(*objfn)(Tcl_Interp *, LPBYTE, DWORD);
    Tcl_Obj *objs[4];
    Tcl_Obj *enumObj = NULL;
    int func = PtrToInt(clientdata);



    if (TwapiGetArgs(interp, objc-1, objv+1, ARGSKIP, ARGTERM) != TCL_OK)
        return TCL_ERROR;


    /* NOTE : to prevent shimmering issues all wide strings are
       extracted from s1Obj AFTER all other arguments have been extracted
    */
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865


866
867
868
869
870
871
872
        if (func == 3) {
            objfn = ObjFromGROUP_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(GROUP_INFO_0); break;
            case 1: struct_size = sizeof(GROUP_INFO_1); break;
            case 2: struct_size = sizeof(GROUP_INFO_2); break;
            case 3: struct_size = sizeof(GROUP_INFO_3); break;
            default: goto invalid_level_error;
            }
        } else {
            objfn = ObjFromLOCALGROUP_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(LOCALGROUP_INFO_0); break;
            case 1: struct_size = sizeof(LOCALGROUP_INFO_1); break;
            default: goto invalid_level_error;
            }
        }
        break;

    case 5:
        // NetUserEnum system level filter resumehandle
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(netenum.level), GETINT(dw), GETINT(dwresume),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        switch (netenum.level) {
        case 0: struct_size = sizeof(USER_INFO_0); break;
        case 1: struct_size = sizeof(USER_INFO_1); break;
        case 2: struct_size = sizeof(USER_INFO_2); break;
        case 3: struct_size = sizeof(USER_INFO_3); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromUSER_INFO;
        netenum.status = NetUserEnum(s1, netenum.level, dw,
                                       &netenum.netbufP,
                                       g_netenum_buf_size,
                                       &netenum.entriesread,
                                       &netenum.totalentries,
                                       &dwresume);
        netenum.hresume = (DWORD_PTR) dwresume;
        break;

    case 6:  // NetUserGetGroups server user level
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s2Obj), GETINT(netenum.level),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        switch (netenum.level) {
        case 0: struct_size = sizeof(GROUP_USERS_INFO_0); break;
        case 1: struct_size = sizeof(GROUP_USERS_INFO_1); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromGROUP_USERS_INFO;
        netenum.hresume = 0; /* Not used for these calls */
        netenum.status = NetUserGetGroups(
            s1, ObjToUnicode(s2Obj), netenum.level, &netenum.netbufP,
            g_netenum_buf_size, &netenum.entriesread, &netenum.totalentries);
        break;

    case 7:
        // NetUserGetLocalGroups server user level flags
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s2Obj), GETINT(netenum.level), GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        if (netenum.level != 0)
            goto invalid_level_error;
        struct_size = sizeof(LOCALGROUP_USERS_INFO_0);
        objfn = ObjFromLOCALGROUP_USERS_INFO;
        netenum.hresume = 0; /* Not used for these calls */
        netenum.status = NetUserGetLocalGroups (
            s1, ObjToUnicode(s2Obj),
            netenum.level, dw, &netenum.netbufP, g_netenum_buf_size,
            &netenum.entriesread, &netenum.totalentries);
        break;
    case 8:
    case 9:
        // NetLocalGroupGetMembers server group level resumehandle
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s2Obj), GETINT(netenum.level), GETDWORD_PTR(netenum.hresume),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        netenum.status = (func == 8 ? NetLocalGroupGetMembers : NetGroupGetUsers) (
            s1, ObjToUnicode(s2Obj),
            netenum.level, &netenum.netbufP, g_netenum_buf_size,
            &netenum.entriesread, &netenum.totalentries, &netenum.hresume);
        if (func == 8) {
            objfn = ObjFromLOCALGROUP_MEMBERS_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_0); break;
            case 1: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_1); break;
            case 2: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_2); break;
            case 3: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_3); break;
            default: goto invalid_level_error;
            }
        } else {            
            objfn = ObjFromGROUP_USERS_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(GROUP_USERS_INFO_0); break;
            case 1: struct_size = sizeof(GROUP_USERS_INFO_1); break;
            default: goto invalid_level_error;
            }
        }
        break;


    }

    if (netenum.status != NERR_Success && netenum.status != ERROR_MORE_DATA) {
        Twapi_AppendSystemError(interp, netenum.status);
        goto error_return;
    }








|






|
















|




















|




|











|




|












|









|






|



>
>







756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
        if (func == 3) {
            objfn = ObjFromGROUP_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(GROUP_INFO_0); break;
            case 1: struct_size = sizeof(GROUP_INFO_1); break;
            case 2: struct_size = sizeof(GROUP_INFO_2); break;
            case 3: struct_size = sizeof(GROUP_INFO_3); break;
            default: goto invalid_return;
            }
        } else {
            objfn = ObjFromLOCALGROUP_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(LOCALGROUP_INFO_0); break;
            case 1: struct_size = sizeof(LOCALGROUP_INFO_1); break;
            default: goto invalid_return;
            }
        }
        break;

    case 5:
        // NetUserEnum system level filter resumehandle
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(netenum.level), GETINT(dw), GETINT(dwresume),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        switch (netenum.level) {
        case 0: struct_size = sizeof(USER_INFO_0); break;
        case 1: struct_size = sizeof(USER_INFO_1); break;
        case 2: struct_size = sizeof(USER_INFO_2); break;
        case 3: struct_size = sizeof(USER_INFO_3); break;
        default: goto invalid_return;
        }
        objfn = ObjFromUSER_INFO;
        netenum.status = NetUserEnum(s1, netenum.level, dw,
                                       &netenum.netbufP,
                                       g_netenum_buf_size,
                                       &netenum.entriesread,
                                       &netenum.totalentries,
                                       &dwresume);
        netenum.hresume = (DWORD_PTR) dwresume;
        break;

    case 6:  // NetUserGetGroups server user level
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s2Obj), GETINT(netenum.level),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        switch (netenum.level) {
        case 0: struct_size = sizeof(GROUP_USERS_INFO_0); break;
        case 1: struct_size = sizeof(GROUP_USERS_INFO_1); break;
        default: goto invalid_return;
        }
        objfn = ObjFromGROUP_USERS_INFO;
        netenum.hresume = 0; /* Not used for these calls */
        netenum.status = NetUserGetGroups(
            s1, ObjToWinChars(s2Obj), netenum.level, &netenum.netbufP,
            g_netenum_buf_size, &netenum.entriesread, &netenum.totalentries);
        break;

    case 7:
        // NetUserGetLocalGroups server user level flags
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s2Obj), GETINT(netenum.level), GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        if (netenum.level != 0)
            goto invalid_return;
        struct_size = sizeof(LOCALGROUP_USERS_INFO_0);
        objfn = ObjFromLOCALGROUP_USERS_INFO;
        netenum.hresume = 0; /* Not used for these calls */
        netenum.status = NetUserGetLocalGroups (
            s1, ObjToWinChars(s2Obj),
            netenum.level, dw, &netenum.netbufP, g_netenum_buf_size,
            &netenum.entriesread, &netenum.totalentries);
        break;
    case 8:
    case 9:
        // NetLocalGroupGetMembers server group level resumehandle
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s2Obj), GETINT(netenum.level), GETDWORD_PTR(netenum.hresume),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        netenum.status = (func == 8 ? NetLocalGroupGetMembers : NetGroupGetUsers) (
            s1, ObjToWinChars(s2Obj),
            netenum.level, &netenum.netbufP, g_netenum_buf_size,
            &netenum.entriesread, &netenum.totalentries, &netenum.hresume);
        if (func == 8) {
            objfn = ObjFromLOCALGROUP_MEMBERS_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_0); break;
            case 1: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_1); break;
            case 2: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_2); break;
            case 3: struct_size = sizeof(LOCALGROUP_MEMBERS_INFO_3); break;
            default: goto invalid_return;
            }
        } else {            
            objfn = ObjFromGROUP_USERS_INFO;
            switch (netenum.level) {
            case 0: struct_size = sizeof(GROUP_USERS_INFO_0); break;
            case 1: struct_size = sizeof(GROUP_USERS_INFO_1); break;
            default: goto invalid_return;
            }
        }
        break;
    default:
        goto invalid_return;
    }

    if (netenum.status != NERR_Success && netenum.status != ERROR_MORE_DATA) {
        Twapi_AppendSystemError(interp, netenum.status);
        goto error_return;
    }

895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913

914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965

966
967

968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
    if (netenum.netbufP)
        NetApiBufferFree((LPBYTE) netenum.netbufP);
    if (enumObj)
        ObjDecrRefs(enumObj);

    return TCL_ERROR;

invalid_level_error:
    TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid info level.");
    goto error_return;
}


static TCL_RESULT Twapi_NetLocalGroupMembersObjCmd(
    TwapiInterpContext *ticP,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{

    int i;
    int func;
    int level;
    Tcl_Obj **accts;
    int naccts;
    LPCWSTR servername, groupname;
    DWORD winerr;
    union {
        LOCALGROUP_MEMBERS_INFO_0 *lgmi0P;
        LOCALGROUP_MEMBERS_INFO_3 *lgmi3P;
        void *bufP;
    } u;
    Tcl_Obj *acctsObj;
    TCL_RESULT res;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    naccts = 0;
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETINT(func),
                         GETEMPTYASNULL(servername),
                         GETWSTR(groupname), GETINT(level),
                         GETOBJ(acctsObj), ARGEND);
    if (res == TCL_OK)
        res = ObjGetElements(interp, acctsObj, &naccts, &accts);

    if (res != TCL_OK || naccts == 0)
        goto vamoose;

    if (level == 0) {
        u.lgmi0P = MemLifoAlloc(ticP->memlifoP, naccts * sizeof(LOCALGROUP_MEMBERS_INFO_0), NULL);
        for (i = 0; i < naccts; ++i) {
            /* For efficiency reasons we do not use ObjToPSID */
            if (ConvertStringSidToSidW(ObjToUnicode(accts[i]), &u.lgmi0P[0].lgrmi0_sid) == 0) {
                res = TwapiReturnSystemError(interp);
                naccts = i;     /* So right num buffers get freed */
                goto vamoose;
            }
        }
    } else if (level == 3) {
        u.lgmi3P = MemLifoAlloc(ticP->memlifoP, naccts * sizeof(LOCALGROUP_MEMBERS_INFO_3), NULL);
        for (i = 0; i < naccts; ++i) {
            u.lgmi3P[i].lgrmi3_domainandname = ObjToUnicode(accts[i]);
        }
    } else {
        res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);
        goto vamoose;
    }
    
    if (func == 0) {
        winerr = NetLocalGroupAddMembers(servername, groupname, level, u.bufP, naccts);

    } else {
        winerr = NetLocalGroupDelMembers(servername, groupname, level, u.bufP, naccts);

    }
    res = winerr == ERROR_SUCCESS ? TCL_OK : Twapi_AppendSystemError(interp, winerr);

vamoose:
    /* At this point
     * res is TCL_RESULT with interp holding result
     * naccts should be number of valid pointers in u.lgmi0P
     */
    if (level == 0) {
        for (i = 0; i < naccts; ++i) {
            LocalFree(u.lgmi0P[i].lgrmi0_sid);
        }
    }

    MemLifoPopMark(mark);
    return res;
}



static int Twapi_AcctCallSSObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *s1Obj, *s2Obj;
    LPWSTR s1, s2, s3;
    DWORD   dw;
    TwapiResult result;
    union {
        GROUP_INFO_1 gi1;
        LOCALGROUP_INFO_1 lgi1;
    } u;
    int func = PtrToInt(clientdata);

    /* NOTE: To prevent shimmering issues, we all WSTR args must be 
       extracted after other arguments */

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETOBJ(s1Obj),
                     GETOBJ(s2Obj), ARGTERM) != TCL_OK)
        return TCL_ERROR;

    objc -= 3;
    objv += 3;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 10:
    case 11:
    case 12:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        s2 = ObjToUnicode(s2Obj);
        switch (func) {
        case 10:
            return Twapi_NetUserGetInfo(interp, s1, s2, dw);
        case 11:
            return Twapi_NetGroupGetInfo(interp, s1, s2, dw);
        case 12:
            return Twapi_NetLocalGroupGetInfo(interp, s1, s2, dw);
        }
        break;
    case 13:
    case 14:
    case 15:
        if (objc)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        s2 = ObjToUnicode(s2Obj);
        switch (func) {
        case 13:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetGroupDel(s1,s2);
            break;
        case 14:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetLocalGroupDel(s1,s2);
            break;
        case 15: // NetUserDel
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetUserDel(s1, s2);
            break;
        }
        break;
    default:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        s2 = ObjToUnicode(s2Obj);
        s3 = ObjToUnicode(objv[0]);
        switch (func) {
        case 16:
            u.lgi1.lgrpi1_name = s2;
            NULLIFY_EMPTY(s3);
            u.lgi1.lgrpi1_comment = s3;
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetLocalGroupAdd(s1, 1, (LPBYTE)&u.lgi1, NULL);







|
|





|




>







<
|
|
<
<




<
<













|


|






|

|







|
>

|
>






|



|






<
<
















<
<














|

|















|



















|
|







895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921

922
923


924
925
926
927


928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982


983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998


999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
    if (netenum.netbufP)
        NetApiBufferFree((LPBYTE) netenum.netbufP);
    if (enumObj)
        ObjDecrRefs(enumObj);

    return TCL_ERROR;

invalid_return:
    TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid function code or info level.");
    goto error_return;
}


static TCL_RESULT Twapi_NetLocalGroupMembersObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int i;
    int func;
    int level;
    Tcl_Obj **accts;
    int naccts;
    LPCWSTR servername, groupname;
    DWORD winerr;

    LOCALGROUP_MEMBERS_INFO_0 *lgmi0P = NULL;
    LOCALGROUP_MEMBERS_INFO_3 *lgmi3P = NULL;


    Tcl_Obj *acctsObj;
    TCL_RESULT res;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    naccts = 0;
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETINT(func),
                         GETEMPTYASNULL(servername),
                         GETWSTR(groupname), GETINT(level),
                         GETOBJ(acctsObj), ARGEND);
    if (res == TCL_OK)
        res = ObjGetElements(interp, acctsObj, &naccts, &accts);

    if (res != TCL_OK || naccts == 0)
        goto vamoose;

    if (level == 0) {
        lgmi0P = MemLifoAlloc(ticP->memlifoP, naccts * sizeof(LOCALGROUP_MEMBERS_INFO_0), NULL);
        for (i = 0; i < naccts; ++i) {
            /* For efficiency reasons we do not use ObjToPSID */
            if (ConvertStringSidToSidW(ObjToWinChars(accts[i]), &lgmi0P[0].lgrmi0_sid) == 0) {
                res = TwapiReturnSystemError(interp);
                naccts = i;     /* So right num buffers get freed */
                goto vamoose;
            }
        }
    } else if (level == 3) {
        lgmi3P = MemLifoAlloc(ticP->memlifoP, naccts * sizeof(LOCALGROUP_MEMBERS_INFO_3), NULL);
        for (i = 0; i < naccts; ++i) {
            lgmi3P[i].lgrmi3_domainandname = ObjToWinChars(accts[i]);
        }
    } else {
        res = TwapiReturnError(interp, TWAPI_INVALID_ARGS);
        goto vamoose;
    }
    
    if (func == 0) {
        winerr = NetLocalGroupAddMembers(servername, groupname, level, 
                                         level == 0 ? (LPBYTE) lgmi0P : (LPBYTE) lgmi3P, naccts);
    } else {
        winerr = NetLocalGroupDelMembers(servername, groupname, level,
                                         level == 0 ? (LPBYTE) lgmi0P : (LPBYTE)lgmi3P, naccts);
    }
    res = winerr == ERROR_SUCCESS ? TCL_OK : Twapi_AppendSystemError(interp, winerr);

vamoose:
    /* At this point
     * res is TCL_RESULT with interp holding result
     * naccts should be number of valid pointers in lgmi0P
     */
    if (level == 0) {
        for (i = 0; i < naccts; ++i) {
            LocalFree(lgmi0P[i].lgrmi0_sid);
        }
    }

    MemLifoPopMark(mark);
    return res;
}



static int Twapi_AcctCallSSObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *s1Obj, *s2Obj;
    LPWSTR s1, s2, s3;
    DWORD   dw;
    TwapiResult result;
    union {
        GROUP_INFO_1 gi1;
        LOCALGROUP_INFO_1 lgi1;
    } u;
    int func = PtrToInt(clientdata);

    /* NOTE: To prevent shimmering issues, we all WSTR args must be 
       extracted after other arguments */



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETOBJ(s1Obj),
                     GETOBJ(s2Obj), ARGTERM) != TCL_OK)
        return TCL_ERROR;

    objc -= 3;
    objv += 3;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 10:
    case 11:
    case 12:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        s2 = ObjToWinChars(s2Obj);
        switch (func) {
        case 10:
            return Twapi_NetUserGetInfo(interp, s1, s2, dw);
        case 11:
            return Twapi_NetGroupGetInfo(interp, s1, s2, dw);
        case 12:
            return Twapi_NetLocalGroupGetInfo(interp, s1, s2, dw);
        }
        break;
    case 13:
    case 14:
    case 15:
        if (objc)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        s2 = ObjToWinChars(s2Obj);
        switch (func) {
        case 13:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetGroupDel(s1,s2);
            break;
        case 14:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetLocalGroupDel(s1,s2);
            break;
        case 15: // NetUserDel
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetUserDel(s1, s2);
            break;
        }
        break;
    default:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        s1 = ObjToLPWSTR_NULL_IF_EMPTY(s1Obj);
        s2 = ObjToWinChars(s2Obj);
        s3 = ObjToWinChars(objv[0]);
        switch (func) {
        case 16:
            u.lgi1.lgrpi1_name = s2;
            NULLIFY_EMPTY(s3);
            u.lgi1.lgrpi1_comment = s3;
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetLocalGroupAdd(s1, 1, (LPBYTE)&u.lgi1, NULL);
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
    HANDLE h;
    DWORD dw;
    int func = PtrToInt(clientdata);
    TwapiResult result;
    WCHAR buf[MAX_PATH+1];
    BOOL (WINAPI *getdirfn)(LPWSTR, LPDWORD);

    ObjToUnicodeCleanup();

    objc -= 1;
    objv += 1;
    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {
        CHECK_NARGS(interp, objc, 0);
        dw = ARRAYSIZE(buf);







<
<







1085
1086
1087
1088
1089
1090
1091


1092
1093
1094
1095
1096
1097
1098
    HANDLE h;
    DWORD dw;
    int func = PtrToInt(clientdata);
    TwapiResult result;
    WCHAR buf[MAX_PATH+1];
    BOOL (WINAPI *getdirfn)(LPWSTR, LPDWORD);



    objc -= 1;
    objv += 1;
    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {
        CHECK_NARGS(interp, objc, 0);
        dw = ARRAYSIZE(buf);
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
    return TwapiSetResult(interp, &result);
}



/* Used for testing purposes */
static TCL_RESULT Twapi_SetNetEnumBufSizeObjCmd(
    Tcl_Interp *clientdata,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{
    ObjToUnicodeCleanup();

    if (objc > 1) {
        if (ObjToLong(interp, objv[1], &g_netenum_buf_size) != TCL_OK)
            return TCL_ERROR;
        if (g_netenum_buf_size < 0)
            g_netenum_buf_size = MAX_PREFERRED_LENGTH;
    }

    ObjSetResult(interp, Tcl_NewIntObj(g_netenum_buf_size));
    return TCL_OK;







|




<
<

|







1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140


1141
1142
1143
1144
1145
1146
1147
1148
1149
    return TwapiSetResult(interp, &result);
}



/* Used for testing purposes */
static TCL_RESULT Twapi_SetNetEnumBufSizeObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{


    if (objc > 1) {
        if (ObjToInt(interp, objv[1], &g_netenum_buf_size) != TCL_OK)
            return TCL_ERROR;
        if (g_netenum_buf_size < 0)
            g_netenum_buf_size = MAX_PREFERRED_LENGTH;
    }

    ObjSetResult(interp, Tcl_NewIntObj(g_netenum_buf_size));
    return TCL_OK;
Changes to undroid/twapi/twapi/apputil/apputil.c.
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    argv = CommandLineToArgvW(cmdlineP, &argc);
    if (argv == NULL) {
        return TwapiReturnSystemError(interp);
    }

    resultObj = ObjNewList(0, NULL);
    for (i= 0; i < argc; ++i) {
        ObjAppendElement(interp, resultObj, ObjFromUnicode(argv[i]));
    }

    ObjSetResult(interp, resultObj);

    GlobalFree(argv);
    return TCL_OK;
}

static int Twapi_AppCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    LPWSTR s;
    DWORD dw;
    TwapiResult result;
    LPVOID pv;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    result.type = TRT_BADFUNCTIONCODE;
    --objc;
    ++objv;
    switch (func) {
    case 2:
        CHECK_NARGS(interp, objc, 0);
        if (Twapi_Wow64DisableWow64FsRedirection(&pv))







|
















<
<







119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142


143
144
145
146
147
148
149
    argv = CommandLineToArgvW(cmdlineP, &argc);
    if (argv == NULL) {
        return TwapiReturnSystemError(interp);
    }

    resultObj = ObjNewList(0, NULL);
    for (i= 0; i < argc; ++i) {
        ObjAppendElement(interp, resultObj, ObjFromWinChars(argv[i]));
    }

    ObjSetResult(interp, resultObj);

    GlobalFree(argv);
    return TCL_OK;
}

static int Twapi_AppCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    LPWSTR s;
    DWORD dw;
    TwapiResult result;
    LPVOID pv;
    int func = PtrToInt(clientdata);



    result.type = TRT_BADFUNCTIONCODE;
    --objc;
    ++objv;
    switch (func) {
    case 2:
        CHECK_NARGS(interp, objc, 0);
        if (Twapi_Wow64DisableWow64FsRedirection(&pv))
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = Twapi_Wow64RevertWow64FsRedirection(pv);
        break;
    case 5: // WritePrivateProfileString
        CHECK_NARGS(interp, objc, 4);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = WritePrivateProfileStringW(
            ObjToUnicode(objv[0]), ObjToLPWSTR_WITH_NULL(objv[1]),
            ObjToLPWSTR_WITH_NULL(objv[2]), ObjToUnicode(objv[3]));
        break;
    case 6:
        CHECK_NARGS(interp, objc, 3);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = WriteProfileStringW(
            ObjToLPWSTR_WITH_NULL(objv[0]),
            ObjToLPWSTR_WITH_NULL(objv[1]),
            ObjToLPWSTR_WITH_NULL(objv[2]));
        break;
    case 7:
        CHECK_NARGS(interp, objc, 4);
        /* As always, extract the int first to avoid shimmering issues */
        CHECK_INTEGER_OBJ(interp, dw, objv[2]);
        result.type = TRT_LONG;
        result.value.ival = GetPrivateProfileIntW(
            ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
            ObjToUnicode(objv[1]), dw,
            ObjToUnicode(objv[3]));
        break;
    case 8:
        CHECK_NARGS(interp, objc, 3);
        /* As always, extract the int first to avoid shimmering issues */
        CHECK_INTEGER_OBJ(interp, dw, objv[2]);
        result.type = TRT_LONG;
        result.value.ival = GetProfileIntW(
            ObjToUnicode(objv[0]), ObjToUnicode(objv[1]), dw);
        break;
    case 9:
        CHECK_NARGS(interp, objc, 1);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = Twapi_Wow64EnableWow64FsRedirection((BOOLEAN)dw);
        break;
    case 10:
        CHECK_NARGS(interp, objc, 1);
        return Twapi_CommandLineToArgv(interp, ObjToUnicode(objv[0]));
    case 11:
        CHECK_NARGS(interp, objc, 1);
        s = ObjToUnicode(objv[0]);
        NULLIFY_EMPTY(s);
        return TwapiGetProfileSectionHelper(interp, NULL, s);
    case 12: // GetPrivateProfileSection
        CHECK_NARGS(interp, objc, 2);
        return TwapiGetProfileSectionHelper(
            interp,
            ObjToUnicode(objv[0]),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[1]));
    }

    return TwapiSetResult(interp, &result);
}









|
|












|



|
|




|


|



|





|


|






|







164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = Twapi_Wow64RevertWow64FsRedirection(pv);
        break;
    case 5: // WritePrivateProfileString
        CHECK_NARGS(interp, objc, 4);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = WritePrivateProfileStringW(
            ObjToWinChars(objv[0]), ObjToLPWSTR_WITH_NULL(objv[1]),
            ObjToLPWSTR_WITH_NULL(objv[2]), ObjToWinChars(objv[3]));
        break;
    case 6:
        CHECK_NARGS(interp, objc, 3);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = WriteProfileStringW(
            ObjToLPWSTR_WITH_NULL(objv[0]),
            ObjToLPWSTR_WITH_NULL(objv[1]),
            ObjToLPWSTR_WITH_NULL(objv[2]));
        break;
    case 7:
        CHECK_NARGS(interp, objc, 4);
        /* As always, extract the int first to avoid shimmering issues */
        CHECK_DWORD_OBJ(interp, dw, objv[2]);
        result.type = TRT_LONG;
        result.value.ival = GetPrivateProfileIntW(
            ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
            ObjToWinChars(objv[1]), dw,
            ObjToWinChars(objv[3]));
        break;
    case 8:
        CHECK_NARGS(interp, objc, 3);
        /* As always, extract the int first to avoid shimmering issues */
        CHECK_DWORD_OBJ(interp, dw, objv[2]);
        result.type = TRT_LONG;
        result.value.ival = GetProfileIntW(
            ObjToWinChars(objv[0]), ObjToWinChars(objv[1]), dw);
        break;
    case 9:
        CHECK_NARGS(interp, objc, 1);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = Twapi_Wow64EnableWow64FsRedirection((BOOLEAN)dw);
        break;
    case 10:
        CHECK_NARGS(interp, objc, 1);
        return Twapi_CommandLineToArgv(interp, ObjToWinChars(objv[0]));
    case 11:
        CHECK_NARGS(interp, objc, 1);
        s = ObjToWinChars(objv[0]);
        NULLIFY_EMPTY(s);
        return TwapiGetProfileSectionHelper(interp, NULL, s);
    case 12: // GetPrivateProfileSection
        CHECK_NARGS(interp, objc, 2);
        return TwapiGetProfileSectionHelper(
            interp,
            ObjToWinChars(objv[0]),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[1]));
    }

    return TwapiSetResult(interp, &result);
}


Changes to undroid/twapi/twapi/base/adsi.c.
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
    if (status != ERROR_SUCCESS) {
        return Twapi_AppendSystemError(interp, status);
    }

    if (dcP) {
        Tcl_Obj *objv[18];
        objv[0] = STRING_LITERAL_OBJ("DomainControllerName");
        objv[1] = ObjFromUnicode(dcP->DomainControllerName);
        objv[2] = STRING_LITERAL_OBJ("DomainControllerAddress");
        objv[3] = ObjFromUnicode(dcP->DomainControllerAddress);
        objv[4] = STRING_LITERAL_OBJ("DomainControllerAddressType");
        objv[5] = ObjFromLong(dcP->DomainControllerAddressType);
        objv[6] = STRING_LITERAL_OBJ("DomainGuid");
        objv[7] = ObjFromUUID(&dcP->DomainGuid);
        objv[8] = STRING_LITERAL_OBJ("DomainName");
        objv[9] = ObjFromUnicode(dcP->DomainName);
        objv[10] = STRING_LITERAL_OBJ("DnsForestName");
        objv[11] = ObjFromUnicode(dcP->DnsForestName);
        objv[12] = STRING_LITERAL_OBJ("Flags");
        objv[13] = ObjFromLong(dcP->Flags);
        objv[14] = STRING_LITERAL_OBJ("DcSiteName");
        objv[15] = ObjFromUnicode(dcP->DcSiteName);
        objv[16] = STRING_LITERAL_OBJ("ClientSiteName");
        objv[17] = ObjFromUnicode(dcP->ClientSiteName);

        ObjSetResult(interp, ObjNewList(18, objv));

        NetApiBufferFree(dcP);
    }

    return TCL_OK;







|

|





|

|



|

|







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
    if (status != ERROR_SUCCESS) {
        return Twapi_AppendSystemError(interp, status);
    }

    if (dcP) {
        Tcl_Obj *objv[18];
        objv[0] = STRING_LITERAL_OBJ("DomainControllerName");
        objv[1] = ObjFromWinChars(dcP->DomainControllerName);
        objv[2] = STRING_LITERAL_OBJ("DomainControllerAddress");
        objv[3] = ObjFromWinChars(dcP->DomainControllerAddress);
        objv[4] = STRING_LITERAL_OBJ("DomainControllerAddressType");
        objv[5] = ObjFromLong(dcP->DomainControllerAddressType);
        objv[6] = STRING_LITERAL_OBJ("DomainGuid");
        objv[7] = ObjFromUUID(&dcP->DomainGuid);
        objv[8] = STRING_LITERAL_OBJ("DomainName");
        objv[9] = ObjFromWinChars(dcP->DomainName);
        objv[10] = STRING_LITERAL_OBJ("DnsForestName");
        objv[11] = ObjFromWinChars(dcP->DnsForestName);
        objv[12] = STRING_LITERAL_OBJ("Flags");
        objv[13] = ObjFromLong(dcP->Flags);
        objv[14] = STRING_LITERAL_OBJ("DcSiteName");
        objv[15] = ObjFromWinChars(dcP->DcSiteName);
        objv[16] = STRING_LITERAL_OBJ("ClientSiteName");
        objv[17] = ObjFromWinChars(dcP->ClientSiteName);

        ObjSetResult(interp, ObjNewList(18, objv));

        NetApiBufferFree(dcP);
    }

    return TCL_OK;
Changes to undroid/twapi/twapi/base/async.c.
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177


/* This routine is called the notification thread. Which may or may not
   be a Tcl interpreter thread */
TWAPI_EXTERN TwapiCallback *TwapiCallbackNew(
    TwapiInterpContext *ticP,   /* May be NULL if not a interp thread */
    TwapiCallbackFn *callback,  /* Callback function */
    size_t sz                   /* Including TwapiCallback header */
)
{
    TwapiCallback *cbP;

    if (sz < sizeof(TwapiCallback)) {
        if (ticP && ticP->interp)
            TwapiReturnErrorEx(ticP->interp, TWAPI_BUG, Tcl_ObjPrintf("Requested Callback size too small (%d).", sz));







|







163
164
165
166
167
168
169
170
171
172
173
174
175
176
177


/* This routine is called the notification thread. Which may or may not
   be a Tcl interpreter thread */
TWAPI_EXTERN TwapiCallback *TwapiCallbackNew(
    TwapiInterpContext *ticP,   /* May be NULL if not a interp thread */
    TwapiCallbackFn *callback,  /* Callback function */
    int sz                   /* Including TwapiCallback header */
)
{
    TwapiCallback *cbP;

    if (sz < sizeof(TwapiCallback)) {
        if (ticP && ticP->interp)
            TwapiReturnErrorEx(ticP->interp, TWAPI_BUG, Tcl_ObjPrintf("Requested Callback size too small (%d).", sz));
Changes to undroid/twapi/twapi/base/calls.c.
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    int objc,
    Tcl_Obj *CONST objv[]
    );
static Tcl_Obj *TwapiRandomByteArrayObj(Tcl_Interp *interp, int nbytes);

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgsVA(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[],
                 int fmtch, va_list ap)
{
    int        argno;
    void      *p;
    Tcl_Obj   *objP = 0;
    char      *typeP;              /* Type of a pointer */
    int       *lenP;
    int        ival;
    long       lval;
    Tcl_WideInt wival;
    DWORD_PTR  dwval;
    void      *ptrval;
    double     dblval;
#ifdef UNSAFE
    WCHAR     *uval;
#endif







|







<







14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

29
30
31
32
33
34
35
    int objc,
    Tcl_Obj *CONST objv[]
    );
static Tcl_Obj *TwapiRandomByteArrayObj(Tcl_Interp *interp, int nbytes);

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgsVA(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[],
                          int fmtch, va_list ap)
{
    int        argno;
    void      *p;
    Tcl_Obj   *objP = 0;
    char      *typeP;              /* Type of a pointer */
    int       *lenP;
    int        ival;

    Tcl_WideInt wival;
    DWORD_PTR  dwval;
    void      *ptrval;
    double     dblval;
#ifdef UNSAFE
    WCHAR     *uval;
#endif
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
            dblval = 0.0; // Default
            if (objP && ObjToDouble(interp, objP, &dblval) != TCL_OK)
                goto argerror;
            if (p)
                *(double *)p = dblval;
            break;
        case ARGINT:  // int
            lval = 0; // Default
            if (objP && ObjToLong(interp, objP, &lval) != TCL_OK)
                goto argerror;
            if (p)
                *(int *)p = lval;
            break;
        case ARGWIDE: // 64-bit int
            wival = 0;
            if (objP && ObjToWideInt(interp, objP, &wival) != TCL_OK)
                goto argerror;
            if (p)
                *(Tcl_WideInt *)p = wival;







|
|


|







73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
            dblval = 0.0; // Default
            if (objP && ObjToDouble(interp, objP, &dblval) != TCL_OK)
                goto argerror;
            if (p)
                *(double *)p = dblval;
            break;
        case ARGINT:  // int
            ival = 0; // Default
            if (objP && ObjToInt(interp, objP, &ival) != TCL_OK)
                goto argerror;
            if (p)
                *(int *)p = ival;
            break;
        case ARGWIDE: // 64-bit int
            wival = 0;
            if (objP && ObjToWideInt(interp, objP, &wival) != TCL_OK)
                goto argerror;
            if (p)
                *(Tcl_WideInt *)p = wival;
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
                    ptrval = ObjToByteArray(objP, &len);
            }
            if (p)
                *(unsigned char **)p = (unsigned char *)ptrval;
            if (lenP)
                *lenP = len;
            break;
        case ARGWSTR: // Unicode string
            if (p) {
                *(WCHAR **)p = objP ? ObjToUnicode(objP) : L"" ;
            }
            break;
        case ARGNULLIFEMPTY:
            if (p)
                *(WCHAR **)p = ObjToLPWSTR_NULL_IF_EMPTY(objP); // NULL objP ok
            break;
        case ARGNULLTOKEN:
            if (p)
                *(WCHAR **)p = ObjToLPWSTR_WITH_NULL(objP);     // NULL objP ok
            break;
        case ARGWSTRN:
            /* We want string and its length */
            lenP = va_arg(ap, int *);
            uval = L""; // Defaults
            len = 0;
            if (objP)
                uval = ObjToUnicodeN(objP, &len);
            if (p)
                *(WCHAR **)p = uval;
            if (lenP)
                *lenP = len;
            break;
#endif // Unsafe
        case ARGWORD: // WORD - 16 bits
            lval = 0;
            if (objP && ObjToLong(interp, objP, &lval) != TCL_OK)
                goto argerror;
            if (lval & ~0xffff) {
                TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                                   Tcl_ObjPrintf("Value %ld does not fit in 16 bits.", lval));
                goto argerror;
            }
            if (p)
                *(short *)p = (short) lval;
            break;
            
        case ARGVAR: // Does not handle default.
            if (objP == NULL) {
                ObjSetStaticResult(interp, "Default values invalid used for ARGVAR types.");
                goto argerror;
            }
            // FALLTHRU
        case ARGVARWITHDEFAULT: // Allows objP to be NULL. The converter_fn should also allow that
            converter_fn = va_arg(ap, TwapiGetArgsFn);
            if (p) {
                if (converter_fn(interp, objP, p) != TCL_OK)
                    goto argerror;
            }
            break;

#ifdef UNSAFE
        case ARGAARGV:
        case ARGWARGV:
            if (objP) {
                ival = va_arg(ap, int);
                iP = va_arg(ap, int *);
                if (iP == NULL)
                    iP = &ival;
                if (fmtch == ARGAARGV) {
                    if (ObjToArgvA(interp, objP, p, ival, iP) != TCL_OK)
                        goto argerror;
                } else {
                    if (ObjToArgvW(interp, objP, p, ival, iP) != TCL_OK)
                        goto argerror;
                }
            } else if (iP)
                *iP = 0;
            break;
#endif
        default:
            ObjSetStaticResult(interp, "TwapiGetArgs: unexpected format character.");
            goto argerror;
        }

    }








|

|
















|







|
|

|

|



|
















<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212



















213
214
215
216
217
218
219
                    ptrval = ObjToByteArray(objP, &len);
            }
            if (p)
                *(unsigned char **)p = (unsigned char *)ptrval;
            if (lenP)
                *lenP = len;
            break;
        case ARGWSTR: // WCHAR string
            if (p) {
                *(WCHAR **)p = objP ? ObjToWinChars(objP) : L"" ;
            }
            break;
        case ARGNULLIFEMPTY:
            if (p)
                *(WCHAR **)p = ObjToLPWSTR_NULL_IF_EMPTY(objP); // NULL objP ok
            break;
        case ARGNULLTOKEN:
            if (p)
                *(WCHAR **)p = ObjToLPWSTR_WITH_NULL(objP);     // NULL objP ok
            break;
        case ARGWSTRN:
            /* We want string and its length */
            lenP = va_arg(ap, int *);
            uval = L""; // Defaults
            len = 0;
            if (objP)
                uval = ObjToWinCharsN(objP, &len);
            if (p)
                *(WCHAR **)p = uval;
            if (lenP)
                *lenP = len;
            break;
#endif // Unsafe
        case ARGWORD: // WORD - 16 bits
            ival = 0;
            if (objP && ObjToInt(interp, objP, &ival) != TCL_OK)
                goto argerror;
            if (ival & ~0xffff) {
                TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                                   Tcl_ObjPrintf("Value %d does not fit in 16 bits.", ival));
                goto argerror;
            }
            if (p)
                *(short *)p = (short) ival;
            break;
            
        case ARGVAR: // Does not handle default.
            if (objP == NULL) {
                ObjSetStaticResult(interp, "Default values invalid used for ARGVAR types.");
                goto argerror;
            }
            // FALLTHRU
        case ARGVARWITHDEFAULT: // Allows objP to be NULL. The converter_fn should also allow that
            converter_fn = va_arg(ap, TwapiGetArgsFn);
            if (p) {
                if (converter_fn(interp, objP, p) != TCL_OK)
                    goto argerror;
            }
            break;




















        default:
            ObjSetStaticResult(interp, "TwapiGetArgs: unexpected format character.");
            goto argerror;
        }

    }

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
argerror:
    /* interp is already supposed to contain an error message */
    return TCL_ERROR;
}

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[],
                 int fmtch, ...)
{
    TCL_RESULT ret;
    va_list ap;
    va_start(ap,fmtch);
    ret = TwapiGetArgsVA(interp, objc, objv, fmtch, ap);
    va_end(ap);
    return ret;
}

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgsObj(Tcl_Interp *interp, Tcl_Obj *objP, int fmtch, ...)
{
    Tcl_Obj **objs;
    int nobjs;
    TCL_RESULT ret;
    va_list ap;

    ret = ObjGetElements(interp, objP, &nobjs, &objs);







|










|







239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
argerror:
    /* interp is already supposed to contain an error message */
    return TCL_ERROR;
}

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[],
                        int fmtch, ...)
{
    TCL_RESULT ret;
    va_list ap;
    va_start(ap,fmtch);
    ret = TwapiGetArgsVA(interp, objc, objv, fmtch, ap);
    va_end(ap);
    return ret;
}

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgsObj(Tcl_Interp *interp, Tcl_Obj *objP, int fmtch,...)
{
    Tcl_Obj **objs;
    int nobjs;
    TCL_RESULT ret;
    va_list ap;

    ret = ObjGetElements(interp, objP, &nobjs, &objs);
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
    Tcl_Interp *interp = ticP->interp;
    int        argno;
    void      *p;
    Tcl_Obj   *objP = 0;
    char      *typeP;              /* Type of a pointer */
    int       *lenP;
    int        ival;
    long       lval;
    Tcl_WideInt wival;
    DWORD_PTR  dwval;
    void      *ptrval;
    double     dblval;
    WCHAR     *uval;
    char      *sval;
    TwapiGetArgsFn converter_fn;







<







277
278
279
280
281
282
283

284
285
286
287
288
289
290
    Tcl_Interp *interp = ticP->interp;
    int        argno;
    void      *p;
    Tcl_Obj   *objP = 0;
    char      *typeP;              /* Type of a pointer */
    int       *lenP;
    int        ival;

    Tcl_WideInt wival;
    DWORD_PTR  dwval;
    void      *ptrval;
    double     dblval;
    WCHAR     *uval;
    char      *sval;
    TwapiGetArgsFn converter_fn;
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
            dblval = 0.0; // Default
            if (objP && ObjToDouble(interp, objP, &dblval) != TCL_OK)
                goto argerror;
            if (p)
                *(double *)p = dblval;
            break;
        case ARGINT:  // int
            lval = 0; // Default
            if (objP && ObjToLong(interp, objP, &lval) != TCL_OK)
                goto argerror;
            if (p)
                *(int *)p = lval;
            break;
        case ARGWIDE: // 64-bit int
            wival = 0;
            if (objP && ObjToWideInt(interp, objP, &wival) != TCL_OK)
                goto argerror;
            if (p)
                *(Tcl_WideInt *)p = wival;







|
|


|







342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
            dblval = 0.0; // Default
            if (objP && ObjToDouble(interp, objP, &dblval) != TCL_OK)
                goto argerror;
            if (p)
                *(double *)p = dblval;
            break;
        case ARGINT:  // int
            ival = 0; // Default
            if (objP && ObjToInt(interp, objP, &ival) != TCL_OK)
                goto argerror;
            if (p)
                *(int *)p = ival;
            break;
        case ARGWIDE: // 64-bit int
            wival = 0;
            if (objP && ObjToWideInt(interp, objP, &wival) != TCL_OK)
                goto argerror;
            if (p)
                *(Tcl_WideInt *)p = wival;
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
            if (objP)
                sval = ObjToStringN(objP, &len);
            if (p)
                *(char **)p = sval;
            if (lenP)
                *lenP = len;
            break;
        case ARGWSTR: // Unicode string
        case ARGEMPTYASNULL:
        case ARGTOKENNULL:
            /* TBD - optimization. May be if !Tcl_IsShared(objP), we can
               directly return ObjToUnicode() without copying into memlifo */
            if (p) {
                uval = L"";
                len = 0;
                if (objP)
                    uval = ObjToUnicodeN(objP, &len);
                if ((fmtch == ARGEMPTYASNULL && len == 0) ||
                    (fmtch == ARGTOKENNULL && lstrcmpW(uval, NULL_TOKEN_L) == 0)) {
                    *(WCHAR **)p = NULL;
                } else {
                    *(WCHAR **)p = MemLifoCopy(ticP->memlifoP, uval, sizeof(WCHAR)*(len+1));
                }
            }
            break;
        case ARGWSTRN:
            /* We want string and its length */
            lenP = va_arg(ap, int *);
            uval = L""; // Defaults
            len = 0;
            if (objP)
                uval = ObjToUnicodeN(objP, &len);
            if (p)
                *(WCHAR **)p = MemLifoCopy(ticP->memlifoP, uval, sizeof(WCHAR)*(len+1));
            if (lenP)
                *lenP = len;
            break;
        case ARGWORD: // WORD - 16 bits
            ival = 0;
            if (objP && ObjToLong(interp, objP, &lval) != TCL_OK)
                goto argerror;
            if (lval & ~0xffff) {
                TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                                   Tcl_ObjPrintf("Value %ld does not fit in 16 bits.", lval));
                goto argerror;
            }
            if (p)
                *(short *)p = (short) lval;
            break;
            
        case ARGVAR: // Does not handle default.
            if (objP == NULL) {
                ObjSetStaticResult(interp, "Default values invalid used for ARGVAR types.");
                goto argerror;
            }
            // FALLTHRU
        case ARGVARWITHDEFAULT: // Allows objP to be NULL. The converter_fn should also allow that
            converter_fn = va_arg(ap, TwapiGetArgsFn);
            if (p) {
                if (converter_fn(interp, objP, p) != TCL_OK)
                    goto argerror;
            }
            break;

        case ARGVA:
        case ARGVW:

            if (objP) {
                Tcl_Obj **argvobjs;
                int       nargvobjs;
                int       j;

                iP = va_arg(ap, int *);
                if (ObjGetElements(interp, objP, &nargvobjs, &argvobjs) != TCL_OK)
                    goto argerror;
                if (iP != NULL)
                    *iP = nargvobjs;
                if (p) {
                    if (fmtch == ARGVA) {
                        char **argv = MemLifoAlloc(ticP->memlifoP, sizeof(*argv)*(nargvobjs+1), NULL);
                        for (j = 0; j < nargvobjs; ++j) {
                            char *s;
                            int slen;
                            s = ObjToStringN(argvobjs[j], &slen);
                            argv[j] = MemLifoCopy(ticP->memlifoP, s, slen+1);
                        }
                        argv[j] = NULL;
                        *(char ***)p = argv;
                    } else {
                        WCHAR **argv = MemLifoAlloc(ticP->memlifoP, sizeof(*argv)*(nargvobjs+1), NULL);
                        for (j = 0; j < nargvobjs; ++j) {
                            WCHAR *s;
                            int slen;
                            s = ObjToUnicodeN(argvobjs[j], &slen);
                            argv[j] = MemLifoCopy(ticP->memlifoP, s, sizeof(WCHAR)*(slen+1));
                        }
                        argv[j] = NULL;
                        *(WCHAR ***)p = argv;
                    }
                }
            } else if (iP)







|



|




|














|







|

|

|



|


















>





<




















|







413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484

485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
            if (objP)
                sval = ObjToStringN(objP, &len);
            if (p)
                *(char **)p = sval;
            if (lenP)
                *lenP = len;
            break;
        case ARGWSTR: // WCHAR string
        case ARGEMPTYASNULL:
        case ARGTOKENNULL:
            /* TBD - optimization. May be if !Tcl_IsShared(objP), we can
               directly return ObjToWinChars() without copying into memlifo */
            if (p) {
                uval = L"";
                len = 0;
                if (objP)
                    uval = ObjToWinCharsN(objP, &len);
                if ((fmtch == ARGEMPTYASNULL && len == 0) ||
                    (fmtch == ARGTOKENNULL && lstrcmpW(uval, NULL_TOKEN_L) == 0)) {
                    *(WCHAR **)p = NULL;
                } else {
                    *(WCHAR **)p = MemLifoCopy(ticP->memlifoP, uval, sizeof(WCHAR)*(len+1));
                }
            }
            break;
        case ARGWSTRN:
            /* We want string and its length */
            lenP = va_arg(ap, int *);
            uval = L""; // Defaults
            len = 0;
            if (objP)
                uval = ObjToWinCharsN(objP, &len);
            if (p)
                *(WCHAR **)p = MemLifoCopy(ticP->memlifoP, uval, sizeof(WCHAR)*(len+1));
            if (lenP)
                *lenP = len;
            break;
        case ARGWORD: // WORD - 16 bits
            ival = 0;
            if (objP && ObjToInt(interp, objP, &ival) != TCL_OK)
                goto argerror;
            if (ival & ~0xffff) {
                TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                                   Tcl_ObjPrintf("Value %d does not fit in 16 bits.", ival));
                goto argerror;
            }
            if (p)
                *(short *)p = (short) ival;
            break;
            
        case ARGVAR: // Does not handle default.
            if (objP == NULL) {
                ObjSetStaticResult(interp, "Default values invalid used for ARGVAR types.");
                goto argerror;
            }
            // FALLTHRU
        case ARGVARWITHDEFAULT: // Allows objP to be NULL. The converter_fn should also allow that
            converter_fn = va_arg(ap, TwapiGetArgsFn);
            if (p) {
                if (converter_fn(interp, objP, p) != TCL_OK)
                    goto argerror;
            }
            break;

        case ARGVA:
        case ARGVW:
            iP = va_arg(ap, int *);
            if (objP) {
                Tcl_Obj **argvobjs;
                int       nargvobjs;
                int       j;


                if (ObjGetElements(interp, objP, &nargvobjs, &argvobjs) != TCL_OK)
                    goto argerror;
                if (iP != NULL)
                    *iP = nargvobjs;
                if (p) {
                    if (fmtch == ARGVA) {
                        char **argv = MemLifoAlloc(ticP->memlifoP, sizeof(*argv)*(nargvobjs+1), NULL);
                        for (j = 0; j < nargvobjs; ++j) {
                            char *s;
                            int slen;
                            s = ObjToStringN(argvobjs[j], &slen);
                            argv[j] = MemLifoCopy(ticP->memlifoP, s, slen+1);
                        }
                        argv[j] = NULL;
                        *(char ***)p = argv;
                    } else {
                        WCHAR **argv = MemLifoAlloc(ticP->memlifoP, sizeof(*argv)*(nargvobjs+1), NULL);
                        for (j = 0; j < nargvobjs; ++j) {
                            WCHAR *s;
                            int slen;
                            s = ObjToWinCharsN(argvobjs[j], &slen);
                            argv[j] = MemLifoCopy(ticP->memlifoP, s, sizeof(WCHAR)*(slen+1));
                        }
                        argv[j] = NULL;
                        *(WCHAR ***)p = argv;
                    }
                }
            } else if (iP)
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
    va_start(ap,fmtch);
    ret = TwapiGetArgsExVA(ticP, objc, objv, fmtch, ap);
    va_end(ap);
    return ret;
}

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgsExObj(TwapiInterpContext *ticP, Tcl_Obj *objP,
                 int fmtch, ...)
{
    Tcl_Obj **objs;
    int nobjs;
    TCL_RESULT ret;
    va_list ap;

    ret = ObjGetElements(ticP->interp, objP, &nobjs, &objs);
    if (ret != TCL_OK)
        return ret;
    va_start(ap,fmtch);
    ret = TwapiGetArgsExVA(ticP, nobjs, objs, fmtch, ap);
    va_end(ap);
    return ret;
}

static TCL_RESULT Twapi_CallNoargsObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;

    union {
        WCHAR buf[MAX_PATH+1];
        SYSTEM_POWER_STATUS power_status;
    } u;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();
    
    if (objc != 1)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:







|
<


















<





<
<







552
553
554
555
556
557
558
559

560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577

578
579
580
581
582


583
584
585
586
587
588
589
    va_start(ap,fmtch);
    ret = TwapiGetArgsExVA(ticP, objc, objv, fmtch, ap);
    va_end(ap);
    return ret;
}

TWAPI_EXTERN_VA
TCL_RESULT TwapiGetArgsExObj(TwapiInterpContext *ticP, Tcl_Obj *objP, int fmtch,...)

{
    Tcl_Obj **objs;
    int nobjs;
    TCL_RESULT ret;
    va_list ap;

    ret = ObjGetElements(ticP->interp, objP, &nobjs, &objs);
    if (ret != TCL_OK)
        return ret;
    va_start(ap,fmtch);
    ret = TwapiGetArgsExVA(ticP, nobjs, objs, fmtch, ap);
    va_end(ap);
    return ret;
}

static TCL_RESULT Twapi_CallNoargsObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;

    union {
        WCHAR buf[MAX_PATH+1];
        SYSTEM_POWER_STATUS power_status;
    } u;
    int func = PtrToInt(clientdata);


    
    if (objc != 1)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
        break;
    case 16:
        result.type = TRT_EMPTY;
        DebugBreak();
        break;
    case 17:
        result.value.unicode.len = ARRAYSIZE(u.buf);
        if (GetDefaultPrinterW(u.buf, &result.value.unicode.len)) {
            result.value.unicode.len -= 1; /* Discard \0 */
            result.value.unicode.str = u.buf;
            result.type = TRT_UNICODE;
        } else {
            result.type = TRT_GETLASTERROR;
        }
        break;







|







650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        break;
    case 16:
        result.type = TRT_EMPTY;
        DebugBreak();
        break;
    case 17:
        result.value.unicode.len = ARRAYSIZE(u.buf);
        if (GetDefaultPrinterW(u.buf, (DWORD  *)&result.value.unicode.len)) {
            result.value.unicode.len -= 1; /* Discard \0 */
            result.value.unicode.str = u.buf;
            result.type = TRT_UNICODE;
        } else {
            result.type = TRT_GETLASTERROR;
        }
        break;
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
    union {
        RPC_STATUS rpc_status;
        MemLifo *lifoP;
        WCHAR buf[MAX_PATH+1];
        HKEY hkey;
    } u;

    ObjToUnicodeCleanup();

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, dw, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        result.value.hval = GetStdHandle(dw);
        if (result.value.hval == INVALID_HANDLE_VALUE)
            result.type = TRT_GETLASTERROR;







<
<


|







686
687
688
689
690
691
692


693
694
695
696
697
698
699
700
701
702
    union {
        RPC_STATUS rpc_status;
        MemLifo *lifoP;
        WCHAR buf[MAX_PATH+1];
        HKEY hkey;
    } u;



    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_DWORD_OBJ(interp, dw, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        result.value.hval = GetStdHandle(dw);
        if (result.value.hval == INVALID_HANDLE_VALUE)
            result.type = TRT_GETLASTERROR;
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
            /* If caller does not mind a local only uuid, don't return error */
            u.rpc_status = RPC_S_OK;
        }
        result.type = u.rpc_status == RPC_S_OK ? TRT_UUID : TRT_GETLASTERROR;
        break;
    case 3:
        result.value.unicode.len = sizeof(u.buf)/sizeof(u.buf[0]);
        if (GetUserNameExW(dw, u.buf, &result.value.unicode.len)) {
            result.value.unicode.str = u.buf;
            result.type = TRT_UNICODE;
        } else
            result.type = TRT_GETLASTERROR;
        break;
    case 4:
        result.value.obj = Twapi_MapWindowsErrorToString(dw);







|







713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
            /* If caller does not mind a local only uuid, don't return error */
            u.rpc_status = RPC_S_OK;
        }
        result.type = u.rpc_status == RPC_S_OK ? TRT_UUID : TRT_GETLASTERROR;
        break;
    case 3:
        result.value.unicode.len = sizeof(u.buf)/sizeof(u.buf[0]);
        if (GetUserNameExW(dw, u.buf, (ULONG *) &result.value.unicode.len)) {
            result.value.unicode.str = u.buf;
            result.type = TRT_UNICODE;
        } else
            result.type = TRT_GETLASTERROR;
        break;
    case 4:
        result.value.obj = Twapi_MapWindowsErrorToString(dw);
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
            HWND hwnd2;
        };
        LSA_OBJECT_ATTRIBUTES lsa_oattr;
        Tcl_WideInt wide;
        SECURITY_DESCRIPTOR *secdP;
        ACL *aclP;
    } u;
    SHORT i16;
    DWORD dw, dw2;
    DWORD_PTR dwp;
    LPWSTR s;
    void *pv;
    Tcl_Obj *objs[2];
    GUID guid;
    SYSTEMTIME systime;
    int i;
    SWSMark mark = NULL;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1001: // concealed?
        mark = SWSPushMark();
        s = ObjDecryptUnicodeSWS(interp, objv[0], &i);
        if (s)
            SecureZeroMemory(s, sizeof(WCHAR) * i);
        result.value.bval = (s != NULL);
        result.type = TRT_BOOL;
        break;

    case 1002: // IsValidACL







|











<
<









|







786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804


805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
            HWND hwnd2;
        };
        LSA_OBJECT_ATTRIBUTES lsa_oattr;
        Tcl_WideInt wide;
        SECURITY_DESCRIPTOR *secdP;
        ACL *aclP;
    } u;
    USHORT u16;
    DWORD dw, dw2;
    DWORD_PTR dwp;
    LPWSTR s;
    void *pv;
    Tcl_Obj *objs[2];
    GUID guid;
    SYSTEMTIME systime;
    int i;
    SWSMark mark = NULL;
    TCL_RESULT res;



    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1001: // concealed?
        mark = SWSPushMark();
        s = ObjDecryptWinCharsSWS(interp, objv[0], &i);
        if (s)
            SecureZeroMemory(s, sizeof(WCHAR) * i);
        result.value.bval = (s != NULL);
        result.type = TRT_BOOL;
        break;

    case 1002: // IsValidACL
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        result.type = TRT_OBJ;
        break;

    case 1004: // Twapi_ParseBinarySECURITY_DESCRIPTOR_RELATIVE
        u.secdP = (SECURITY_DESCRIPTOR *) ObjToByteArray(objv[0], &dw);
        if (dw >= sizeof(SECURITY_DESCRIPTOR_RELATIVE) && IsValidSecurityDescriptor(u.secdP) && (u.secdP->Control & SE_SELF_RELATIVE)) {
            result.type = TRT_OBJ;
            result.value.obj = ObjFromSECURITY_DESCRIPTOR(interp, u.secdP);
        } else {
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_DATA, "Invalid security descriptor");
        }
        break;

    case 1005: // hex64
        if (ObjToWideInt(interp, objv[0], &u.wide) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_OBJ;
        result.value.obj = ObjFromULONGLONGHex(u.wide);
        break;
        
    case 1006: // reveal
        mark = SWSPushMark();
        s = ObjDecryptUnicodeSWS(interp, objv[0], &dw);
        if (s == NULL) {
            res = TCL_ERROR;
            goto vamoose;
        }
        result.value.obj = ObjFromUnicodeN(s, dw);
        result.type = TRT_OBJ;
        SecureZeroMemory(s, sizeof(WCHAR) * dw);
        break;

    case 1007: // conceal
        /* TBD - if objv[0] is unshared, zero it out to erase from memory? */
        s = ObjToUnicodeN(objv[0], &dw);
        result.value.obj = ObjEncryptUnicode(interp, s, dw);
        result.type = TRT_OBJ;
        break;

    case 1008: // AddressToPointer
        if (ObjToDWORD_PTR(interp, objv[0], &dwp) != TCL_OK)
            return TCL_ERROR;
        TwapiResult_SET_PTR(result, void*, (void*)dwp);
        break;
    case 1009: // IsValidSid
        u.sidP = NULL;
        result.type = TRT_BOOL;
        mark = SWSPushMark();
        result.value.bval = (ObjToPSIDSWS(interp, objv[0], &u.sidP) == TCL_OK);
        break;
    case 1010:
        if (ObjToDouble(interp, objv[0], &u.d) != TCL_OK)
            return TCL_ERROR;
        result.type = VariantTimeToSystemTime(u.d, &result.value.systime) ?
            TRT_SYSTEMTIME : TRT_GETLASTERROR;
        break;







|
|
















|




|

|




|
|












|







843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        result.type = TRT_OBJ;
        break;

    case 1004: // Twapi_ParseBinarySECURITY_DESCRIPTOR_RELATIVE
        u.secdP = (SECURITY_DESCRIPTOR *) ObjToByteArray(objv[0], &i);
        if (i >= sizeof(SECURITY_DESCRIPTOR_RELATIVE) && IsValidSecurityDescriptor(u.secdP) && (u.secdP->Control & SE_SELF_RELATIVE)) {
            result.type = TRT_OBJ;
            result.value.obj = ObjFromSECURITY_DESCRIPTOR(interp, u.secdP);
        } else {
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_DATA, "Invalid security descriptor");
        }
        break;

    case 1005: // hex64
        if (ObjToWideInt(interp, objv[0], &u.wide) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_OBJ;
        result.value.obj = ObjFromULONGLONGHex(u.wide);
        break;
        
    case 1006: // reveal
        mark = SWSPushMark();
        s = ObjDecryptWinCharsSWS(interp, objv[0], &i);
        if (s == NULL) {
            res = TCL_ERROR;
            goto vamoose;
        }
        result.value.obj = ObjFromWinCharsN(s, i);
        result.type = TRT_OBJ;
        SecureZeroMemory(s, sizeof(WCHAR) * i);
        break;

    case 1007: // conceal
        /* TBD - if objv[0] is unshared, zero it out to erase from memory? */
        s = ObjToWinCharsN(objv[0], &i);
        result.value.obj = ObjEncryptWinChars(interp, s, i);
        result.type = TRT_OBJ;
        break;

    case 1008: // AddressToPointer
        if (ObjToDWORD_PTR(interp, objv[0], &dwp) != TCL_OK)
            return TCL_ERROR;
        TwapiResult_SET_PTR(result, void*, (void*)dwp);
        break;
    case 1009: // IsValidSid
        u.sidP = NULL;
        result.type = TRT_BOOL;
        mark = SWSPushMark();
        result.value.bval = (ObjToPSIDSWS(interp, objv[0], (void **) &u.sidP) == TCL_OK);
        break;
    case 1010:
        if (ObjToDouble(interp, objv[0], &u.d) != TCL_OK)
            return TCL_ERROR;
        result.type = VariantTimeToSystemTime(u.d, &result.value.systime) ?
            TRT_SYSTEMTIME : TRT_GETLASTERROR;
        break;
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
        if (ObjToGUID(interp, objv[0], &result.value.guid) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_GUID;
        break;
    case 1013:
        return Twapi_AppendObjLog(interp, objv[0]);
    case 1014: // GlobalAddAtom
        result.value.ival = GlobalAddAtomW(ObjToUnicode(objv[0]));
        result.type = result.value.ival ? TRT_LONG : TRT_GETLASTERROR;
        break;
    case 1015:
        u.sidP = NULL;
        result.type = TRT_BOOL;
        result.value.bval = ConvertStringSidToSidW(ObjToUnicode(objv[0]),
                                                   &u.sidP);
        if (u.sidP)
            LocalFree(u.sidP);
        break;
    case 1016:
        if (ObjToFILETIME(interp, objv[0], &u.filetime) != TCL_OK)
            return TCL_ERROR;
        if (FileTimeToSystemTime(&u.filetime, &result.value.systime))







|





|
|







910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
        if (ObjToGUID(interp, objv[0], &result.value.guid) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_GUID;
        break;
    case 1013:
        return Twapi_AppendObjLog(interp, objv[0]);
    case 1014: // GlobalAddAtom
        result.value.ival = GlobalAddAtomW(ObjToWinChars(objv[0]));
        result.type = result.value.ival ? TRT_LONG : TRT_GETLASTERROR;
        break;
    case 1015:
        u.sidP = NULL;
        result.type = TRT_BOOL;
        result.value.bval = ConvertStringSidToSidW(ObjToWinChars(objv[0]),
                                                   (void **)&u.sidP);
        if (u.sidP)
            LocalFree(u.sidP);
        break;
    case 1016:
        if (ObjToFILETIME(interp, objv[0], &u.filetime) != TCL_OK)
            return TCL_ERROR;
        if (FileTimeToSystemTime(&u.filetime, &result.value.systime))
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        break;
    case 1019: // Twapi_IsValidGUID
        result.type = TRT_BOOL;
        result.value.bval = (ObjToGUID(NULL, objv[0], &guid) == TCL_OK);
        break;
    case 1020:
        result.type = TRT_OBJ;
        result.value.obj = ObjFromEXPAND_SZW(ObjToUnicode(objv[0]));
        break;
    case 1021: // free
        if (ObjToLPVOID(interp, objv[0], &pv) != TCL_OK ||
            TwapiUnregisterPointer(interp, pv, TwapiAlloc) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EMPTY;
        if (pv)







|







957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
        break;
    case 1019: // Twapi_IsValidGUID
        result.type = TRT_BOOL;
        result.value.bval = (ObjToGUID(NULL, objv[0], &guid) == TCL_OK);
        break;
    case 1020:
        result.type = TRT_OBJ;
        result.value.obj = ObjFromEXPAND_SZW(ObjToWinChars(objv[0]));
        break;
    case 1021: // free
        if (ObjToLPVOID(interp, objv[0], &pv) != TCL_OK ||
            TwapiUnregisterPointer(interp, pv, TwapiAlloc) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EMPTY;
        if (pv)
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
    case 1025: // swap8
        if (ObjToWideInt(interp, objv[0], &u.wide) != TCL_OK)
            return TCL_ERROR;
        result.value.wide=swap8(u.wide);
        result.type = TRT_WIDE;
        break;
    case 1026: // swap4
        if (ObjToLong(interp, objv[0], &dw) != TCL_OK)
            return TCL_ERROR;
        result.value.ival=swap4(dw);
        result.type = TRT_LONG;
        break;
    case 1027: // swap2
        if (ObjToUSHORT(interp, objv[0], &i16) != TCL_OK)
            return TCL_ERROR;
        result.value.ival=swap2(i16);
        result.type = TRT_LONG;
        break;
    case 1028: // hex
        pv = Tcl_GetByteArrayFromObj(objv[0], &i);
        result.type = TRT_OBJ;
        result.value.obj = ObjFromByteArrayHex(pv, i);
        break;







|

|



|

|







996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
    case 1025: // swap8
        if (ObjToWideInt(interp, objv[0], &u.wide) != TCL_OK)
            return TCL_ERROR;
        result.value.wide=swap8(u.wide);
        result.type = TRT_WIDE;
        break;
    case 1026: // swap4
        if (ObjToInt(interp, objv[0], &i) != TCL_OK)
            return TCL_ERROR;
        result.value.ival=swap4(i);
        result.type = TRT_LONG;
        break;
    case 1027: // swap2
        if (ObjToUSHORT(interp, objv[0], &u16) != TCL_OK)
            return TCL_ERROR;
        result.value.ival=swap2(u16);
        result.type = TRT_LONG;
        break;
    case 1028: // hex
        pv = Tcl_GetByteArrayFromObj(objv[0], &i);
        result.type = TRT_OBJ;
        result.value.obj = ObjFromByteArrayHex(pv, i);
        break;
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
            HKEY hkey2;
        };
        LSA_OBJECT_ATTRIBUTES lsa_oattr;
    } u;
    DWORD dw, dw2, dw3, dw4;
    DWORD_PTR dwp, dwp2;
    LPWSTR s, s2;
    unsigned char *cP;
    void *pv, *pv2;
    Tcl_Obj *objs[2];
    SECURITY_ATTRIBUTES *secattrP;
    HANDLE h, h2, h3;
    GUID guid;
    GUID *guidP;
    LSA_UNICODE_STRING lsa_ustr; /* Used with lsa_oattr so not in union */
    TwapiResult result;
    int i;
    SWSMark mark = NULL;

    ObjToUnicodeCleanup();

    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 10001:
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETVOIDP(pv), GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SystemParametersInfoW(dw, dw2, pv, dw3);
        break;
    case 10002:
        u.sidP = NULL;
        CHECK_NARGS(interp, objc, 2);
        mark = SWSPushMark();
        result.value.ival = ObjToPSIDSWS(interp, objv[1], &u.sidP);
        if (result.value.ival == TCL_OK) {
            result.value.ival = Twapi_LookupAccountSid(interp, ObjToUnicode(objv[0]), u.sidP);
        }
        SWSPopMark(mark);
        result.type = TRT_TCL_RESULT;
        break;
    case 10003:
    case 10004:
        CHECK_NARGS(interp, objc, 2);
        s = ObjToLPWSTR_NULL_IF_EMPTY(objv[0]);
        s2 = ObjToUnicode(objv[1]);
        if (func == 10003)
            return Twapi_LookupAccountName(interp, s, s2);
        else {
            NULLIFY_EMPTY(s2);
            return Twapi_NetGetDCName(interp, s, s2);
        }
        break;







|








|


<
<
















|

|








|







1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063


1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
            HKEY hkey2;
        };
        LSA_OBJECT_ATTRIBUTES lsa_oattr;
    } u;
    DWORD dw, dw2, dw3, dw4;
    DWORD_PTR dwp, dwp2;
    LPWSTR s, s2;
    char *cP;
    void *pv, *pv2;
    Tcl_Obj *objs[2];
    SECURITY_ATTRIBUTES *secattrP;
    HANDLE h, h2, h3;
    GUID guid;
    GUID *guidP;
    LSA_UNICODE_STRING lsa_ustr; /* Used with lsa_oattr so not in union */
    TwapiResult result;
    int i, j;
    SWSMark mark = NULL;



    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 10001:
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETVOIDP(pv), GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SystemParametersInfoW(dw, dw2, pv, dw3);
        break;
    case 10002:
        u.sidP = NULL;
        CHECK_NARGS(interp, objc, 2);
        mark = SWSPushMark();
        result.value.ival = ObjToPSIDSWS(interp, objv[1], (void **) &u.sidP);
        if (result.value.ival == TCL_OK) {
            result.value.ival = Twapi_LookupAccountSid(interp, ObjToWinChars(objv[0]), u.sidP);
        }
        SWSPopMark(mark);
        result.type = TRT_TCL_RESULT;
        break;
    case 10003:
    case 10004:
        CHECK_NARGS(interp, objc, 2);
        s = ObjToLPWSTR_NULL_IF_EMPTY(objv[0]);
        s2 = ObjToWinChars(objv[1]);
        if (func == 10003)
            return Twapi_LookupAccountName(interp, s, s2);
        else {
            NULLIFY_EMPTY(s2);
            return Twapi_NetGetDCName(interp, s, s2);
        }
        break;
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HGLOBAL;
        result.value.hval = GlobalAlloc(dw, dwp);
        break;
    case 10007:
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        result.type = TRT_DWORD;
        result.value.uval = LHashValOfName(dw, ObjToUnicode(objv[1]));
        break;
    case 10008:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), GETHANDLE(h2),
                         GETHANDLE(h3), GETINT(dw), GETBOOL(dw2),
                         GETINT(dw3),
                         ARGEND) != TCL_OK)







|

|







1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HGLOBAL;
        result.value.hval = GlobalAlloc(dw, dwp);
        break;
    case 10007:
        CHECK_NARGS(interp, objc, 2);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        result.type = TRT_DWORD;
        result.value.uval = LHashValOfName(dw, ObjToWinChars(objv[1]));
        break;
    case 10008:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), GETHANDLE(h2),
                         GETHANDLE(h3), GETINT(dw), GETBOOL(dw2),
                         GETINT(dw3),
                         ARGEND) != TCL_OK)
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SetStdHandle(dw, h);
        break;
    case 10011:
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);
        result.type = TRT_HANDLE;
        result.value.hval = LoadLibraryExW(ObjToUnicode(objv[0]), NULL, dw);
        break;
    case 10012: // CreateFile
        secattrP = NULL;
        mark = SWSPushMark();
        if (TwapiGetArgs(interp, objc, objv,
                         ARGSKIP, GETINT(dw), GETINT(dw2),
                         GETVAR(secattrP, ObjToPSECURITY_ATTRIBUTESSWS),
                         GETINT(dw3), GETINT(dw4), GETHANDLE(h),
                         ARGEND) == TCL_OK) {
            result.type = TRT_VALID_HANDLE;
            result.value.hval = CreateFileW(
                ObjToUnicode(objv[0]), dw, dw2, secattrP, dw3, dw4, h);
        } else {
            result.type = TRT_TCL_RESULT;
            result.value.ival = TCL_ERROR;
        }
        SWSPopMark(mark);
        break;
    case 10013:







|

|











|







1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SetStdHandle(dw, h);
        break;
    case 10011:
        CHECK_NARGS(interp, objc, 2);
        CHECK_DWORD_OBJ(interp, dw, objv[1]);
        result.type = TRT_HANDLE;
        result.value.hval = LoadLibraryExW(ObjToWinChars(objv[0]), NULL, dw);
        break;
    case 10012: // CreateFile
        secattrP = NULL;
        mark = SWSPushMark();
        if (TwapiGetArgs(interp, objc, objv,
                         ARGSKIP, GETINT(dw), GETINT(dw2),
                         GETVAR(secattrP, ObjToPSECURITY_ATTRIBUTESSWS),
                         GETINT(dw3), GETINT(dw4), GETHANDLE(h),
                         ARGEND) == TCL_OK) {
            result.type = TRT_VALID_HANDLE;
            result.value.hval = CreateFileW(
                ObjToWinChars(objv[0]), dw, dw2, secattrP, dw3, dw4, h);
        } else {
            result.type = TRT_TCL_RESULT;
            result.value.ival = TCL_ERROR;
        }
        SWSPopMark(mark);
        break;
    case 10013:
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
        break;
    case 10021:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLET(u.hwnd, HWND), GETINT(dw),
                         GETDWORD_PTR(dwp),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = Twapi_SetWindowLongPtr(u.hwnd, dw, dwp, &result.value.dwp)
            ? TRT_DWORD_PTR : TRT_GETLASTERROR;
        break;
    case 10022: // DsGetDcName
        guidP = &guid;
        if (TwapiGetArgs(interp, objc, objv, ARGSKIP, ARGSKIP,
                         GETVAR(guidP, ObjToUUID_NULL), ARGSKIP,
                         GETINT(dw), ARGEND) != TCL_OK)







|







1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
        break;
    case 10021:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLET(u.hwnd, HWND), GETINT(dw),
                         GETDWORD_PTR(dwp),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = Twapi_SetWindowLongPtr(u.hwnd, dw, (LONG_PTR) dwp, (LONG_PTR *) &result.value.dwp)
            ? TRT_DWORD_PTR : TRT_GETLASTERROR;
        break;
    case 10022: // DsGetDcName
        guidP = &guid;
        if (TwapiGetArgs(interp, objc, objv, ARGSKIP, ARGSKIP,
                         GETVAR(guidP, ObjToUUID_NULL), ARGSKIP,
                         GETINT(dw), ARGEND) != TCL_OK)
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETBOOL(dw2), ARGSKIP,
                         ARGUSEDEFAULT, GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HANDLE;
        result.value.hval = (func == 10027 ? OpenMutexW : OpenSemaphoreW)
            (dw, dw2, ObjToUnicode(objv[2]));
        if (result.value.hval) {
            if (dw3 & 1) {
                /* Caller also wants indicator of whether object
                   already existed */
                objs[0] = ObjFromHANDLE(result.value.hval);
                objs[1] = ObjFromBoolean(GetLastError() == ERROR_ALREADY_EXISTS);
                result.value.objv.objPP = objs;







|







1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETBOOL(dw2), ARGSKIP,
                         ARGUSEDEFAULT, GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HANDLE;
        result.value.hval = (func == 10027 ? OpenMutexW : OpenSemaphoreW)
            (dw, dw2, ObjToWinChars(objv[2]));
        if (result.value.hval) {
            if (dw3 & 1) {
                /* Caller also wants indicator of whether object
                   already existed */
                objs[0] = ObjFromHANDLE(result.value.hval);
                objs[1] = ObjFromBoolean(GetLastError() == ERROR_ALREADY_EXISTS);
                result.value.objv.objPP = objs;
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
        break;
    case 10036: // OpenEventLog
    case 10037: // RegisterEventSource
        CHECK_NARGS(interp, objc, 2);
        result.type = TRT_HANDLE;
        result.value.hval = (func == 10036 ?
                             OpenEventLogW : RegisterEventSourceW)
            (ObjToLPWSTR_NULL_IF_EMPTY(objv[0]), ObjToUnicode(objv[1]));
        break;
    case 10038: // pointer_from_address
        if (objc == 1)
            cP = NULL;
        else if (objc == 2)
            cP = ObjToString(objv[1]);
        else
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);        
        if (ObjToDWORD_PTR(interp, objv[0], &dwp) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_OBJ;
        result.value.obj = ObjFromOpaque((void *) dwp, cP);
        break;
    case 10039: // CredUIConfirmCredential
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);
        /* Note we do not treat any value as an error since it can happen
           in normal operation that some cred is no longer cached */
        result.type = TRT_DWORD;
        result.value.ival = CredUIConfirmCredentialsW(ObjToUnicode(objv[0]), dw);
        break;
    case 10040: // enum
        CHECK_NARGS(interp, objc, 2);
        result.type = TRT_DWORD;
        if (ObjToEnum(interp, objv[0], objv[1], &result.value.uval) != TCL_OK)
            return TCL_ERROR;
        break;
    case 10041: // lconcat
        dw2 = 0;
        for (i = 0 ; i < objc; ++i) {
            if (ObjListLength(interp, objv[i], &dw3) != TCL_OK)
                return TCL_ERROR;
            dw2 += dw3;
        }
        result.type = TRT_OBJ;
        result.value.obj = ObjNewList(dw2, NULL); /* Preallocated space */
        for (i = 0, dw2 = 0; i < objc; ++i) {
            Tcl_Obj **elems;
            int nelems;
            /* Should not error, since we already did list convert above.







|















|



|



|
|





|

|







1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
        break;
    case 10036: // OpenEventLog
    case 10037: // RegisterEventSource
        CHECK_NARGS(interp, objc, 2);
        result.type = TRT_HANDLE;
        result.value.hval = (func == 10036 ?
                             OpenEventLogW : RegisterEventSourceW)
            (ObjToLPWSTR_NULL_IF_EMPTY(objv[0]), ObjToWinChars(objv[1]));
        break;
    case 10038: // pointer_from_address
        if (objc == 1)
            cP = NULL;
        else if (objc == 2)
            cP = ObjToString(objv[1]);
        else
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);        
        if (ObjToDWORD_PTR(interp, objv[0], &dwp) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_OBJ;
        result.value.obj = ObjFromOpaque((void *) dwp, cP);
        break;
    case 10039: // CredUIConfirmCredential
        CHECK_NARGS(interp, objc, 2);
        CHECK_DWORD_OBJ(interp, dw, objv[1]);
        /* Note we do not treat any value as an error since it can happen
           in normal operation that some cred is no longer cached */
        result.type = TRT_DWORD;
        result.value.ival = CredUIConfirmCredentialsW(ObjToWinChars(objv[0]), dw);
        break;
    case 10040: // enum
        CHECK_NARGS(interp, objc, 2);
        result.type = TRT_INT;
        if (ObjToEnum(interp, objv[0], objv[1], &result.value.ival) != TCL_OK)
            return TCL_ERROR;
        break;
    case 10041: // lconcat
        dw2 = 0;
        for (i = 0 ; i < objc; ++i) {
            if (ObjListLength(interp, objv[i], &j) != TCL_OK)
                return TCL_ERROR;
            dw2 += j;
        }
        result.type = TRT_OBJ;
        result.value.obj = ObjNewList(dw2, NULL); /* Preallocated space */
        for (i = 0, dw2 = 0; i < objc; ++i) {
            Tcl_Obj **elems;
            int nelems;
            /* Should not error, since we already did list convert above.
1549
1550
1551
1552
1553
1554
1555
1556
1557

1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578

    return TwapiSetResult(interp, &result);
}

/* This was the original dispatcher. Most stuff has now been broken out
   from here. This now handles commands that need a TwapiInterpContext
*/
static int Twapi_CallObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TwapiResult result;
    int func;
    TwapiId twapi_id;
    DWORD dw, dw2;
    long lw;
    HANDLE h;
    Tcl_Obj *objP = NULL;
#ifdef TWAPI_ENABLE_INSTRUMENTATION
    void *pv;
    MemLifoMarkHandle mark;
#endif

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    objc -= 2;
    objv += 2;








|

>




<

<




|
<
|







1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531

1532

1533
1534
1535
1536
1537

1538
1539
1540
1541
1542
1543
1544
1545

    return TwapiSetResult(interp, &result);
}

/* This was the original dispatcher. Most stuff has now been broken out
   from here. This now handles commands that need a TwapiInterpContext
*/
static int Twapi_CallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext *) clientdata;
    TwapiResult result;
    int func;
    TwapiId twapi_id;
    DWORD dw, dw2;

    HANDLE h;

#ifdef TWAPI_ENABLE_INSTRUMENTATION
    void *pv;
    MemLifoMarkHandle mark;
#endif
    int i;

    
    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    objc -= 2;
    objv += 2;

1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        result.type = TRT_OBJ;
        result.value.obj = TwapiGetAtom(ticP, ObjToString(objv[0]));
        break;
    case 6: // RtlGenRandom
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        if (ObjToLong(interp, objv[0], &lw) != TCL_OK)
            return TCL_ERROR;
        dw = lw;
        result.value.obj = TwapiRandomByteArrayObj(interp, dw);
        if (result.value.obj)
            result.type = TRT_OBJ;
        else 
            return TCL_ERROR;
        break;
    case 7:
        if (TwapiGetArgs(interp, objc, objv, GETHANDLE(h),
                         GETINT(dw), GETINT(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        return TwapiThreadPoolRegister(
            ticP, h, dw, dw2, TwapiCallRegisteredWaitScript, NULL);
    case 8: // trapresult
    case 9: // trapoptions
        CHECK_NARGS(interp, objc, 0);
        dw = 0;
        ObjListLength(NULL, BASE_CONTEXT(ticP)->trapstack, &dw);
        if (dw > 1) {
            ObjListIndex(NULL, BASE_CONTEXT(ticP)->trapstack,
                         dw - 1 - (func == 8), &result.value.obj);
            result.type = TRT_OBJ;
        } else
            return TwapiReturnError(interp, TWAPI_INVALID_COMMAND_SCOPE);
        break;
    case 10:
#if TWAPI_ENABLE_INSTRUMENTATION
        result.type = TRT_OBJ;







|

<
|















|
|
|

|







1570
1571
1572
1573
1574
1575
1576
1577
1578

1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        result.type = TRT_OBJ;
        result.value.obj = TwapiGetAtom(ticP, ObjToString(objv[0]));
        break;
    case 6: // RtlGenRandom
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        if (ObjToInt(interp, objv[0], &i) != TCL_OK)
            return TCL_ERROR;

        result.value.obj = TwapiRandomByteArrayObj(interp, i);
        if (result.value.obj)
            result.type = TRT_OBJ;
        else 
            return TCL_ERROR;
        break;
    case 7:
        if (TwapiGetArgs(interp, objc, objv, GETHANDLE(h),
                         GETINT(dw), GETINT(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        return TwapiThreadPoolRegister(
            ticP, h, dw, dw2, TwapiCallRegisteredWaitScript, NULL);
    case 8: // trapresult
    case 9: // trapoptions
        CHECK_NARGS(interp, objc, 0);
        i = 0;
        ObjListLength(NULL, BASE_CONTEXT(ticP)->trapstack, &i);
        if (i > 1) {
            ObjListIndex(NULL, BASE_CONTEXT(ticP)->trapstack,
                         i - 1 - (func == 8), &result.value.obj);
            result.type = TRT_OBJ;
        } else
            return TwapiReturnError(interp, TWAPI_INVALID_COMMAND_SCOPE);
        break;
    case 10:
#if TWAPI_ENABLE_INSTRUMENTATION
        result.type = TRT_OBJ;
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
static int Twapi_CallHObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE h;
    DWORD dw, dw2;
    TwapiResult result;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLE(h),
                     ARGTERM) != TCL_OK) {
        return TCL_ERROR;
    }

    --objc;







<
<







1641
1642
1643
1644
1645
1646
1647


1648
1649
1650
1651
1652
1653
1654
static int Twapi_CallHObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE h;
    DWORD dw, dw2;
    TwapiResult result;
    int func = PtrToInt(clientdata);



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLE(h),
                     ARGTERM) != TCL_OK) {
        return TCL_ERROR;
    }

    --objc;
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
            break;
        case 13:
            result.value.uval = LsaClose(h);
            result.type = TRT_DWORD; /* Not TRT_NTSTATUS because do not
                                        want error on invalid handle */
            break;
        case 14:
            result.type = GetHandleInformation(h, &result.value.ival)
                ? TRT_LONG : TRT_GETLASTERROR;
            break;
        case 15:
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = FreeLibrary(h);
            break;
        case 16:
            result.type = GetDevicePowerState(h, &result.value.bval)







|
|







1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
            break;
        case 13:
            result.value.uval = LsaClose(h);
            result.type = TRT_DWORD; /* Not TRT_NTSTATUS because do not
                                        want error on invalid handle */
            break;
        case 14:
            result.type = GetHandleInformation(h, &result.value.uval)
                ? TRT_DWORD : TRT_GETLASTERROR;
            break;
        case 15:
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = FreeLibrary(h);
            break;
        case 16:
            result.type = GetDevicePowerState(h, &result.value.bval)
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
#endif
        }
    } else if (func < 2000) {

        // A single additional DWORD arg is present
        if (objc != 2)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);

        switch (func) {
        case 1001:
            result.type = ReleaseSemaphore(h, dw, &result.value.uval) ?
                TRT_LONG : TRT_GETLASTERROR;
            break;
        case 1002:
            result.value.ival = WaitForSingleObject(h, dw);
            if (result.value.ival == (DWORD) -1) {
                result.type = TRT_GETLASTERROR;
            } else {







|



|







1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
#endif
        }
    } else if (func < 2000) {

        // A single additional DWORD arg is present
        if (objc != 2)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_DWORD_OBJ(interp, dw, objv[1]);

        switch (func) {
        case 1001:
            result.type = ReleaseSemaphore(h, dw, (LPLONG) &result.value.ival) ?
                TRT_LONG : TRT_GETLASTERROR;
            break;
        case 1002:
            result.value.ival = WaitForSingleObject(h, dw);
            if (result.value.ival == (DWORD) -1) {
                result.type = TRT_GETLASTERROR;
            } else {
1843
1844
1845
1846
1847
1848
1849
1850
1851

1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885

1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912

1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940

1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
            TwapiResult_SET_PTR(result, void*, MemLifoResizeLast(h, dw, dw2));
            break;
        }
    }
    return TwapiSetResult(interp, &result);
}

static int Twapi_TranslateNameObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TCL_RESULT res;
    Tcl_Obj *nameObj;
    WCHAR *bufP, *nameP;
    DWORD sz, nbytes, fmt, desired_fmt;

    ObjToUnicodeCleanup();

    bufP = MemLifoPushFrame(ticP->memlifoP, sizeof(WCHAR)*MAX_PATH, &nbytes);
    sz = nbytes/sizeof(WCHAR);
    res = TwapiGetArgs(interp, objc-1, objv+1,
                       GETOBJ(nameObj), GETINT(fmt), GETINT(desired_fmt),
                       ARGEND);
    if (res == TCL_OK) {
        /* Since other args parsed, we can hold on to nameP without fear
           of shimmering */
        nameP = ObjToUnicode(nameObj);
        if (! TranslateNameW(nameP, fmt, desired_fmt, bufP, &sz)) {
            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                bufP = MemLifoAlloc(ticP->memlifoP, sizeof(WCHAR)*sz, NULL);
                if (! TranslateNameW(nameP, fmt, desired_fmt, bufP, &sz))
                    res = TwapiReturnSystemError(interp);
            } else {
                res = TwapiReturnSystemError(interp);
            }
        }
        if (res == TCL_OK)
            ObjSetResult(interp, ObjFromUnicodeN(bufP, sz-1));
    }
    MemLifoPopFrame(ticP->memlifoP);
    return res;
}

static int Twapi_FormatMessageFromStringObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    WCHAR **argv;
    int     argc;
    Tcl_Obj *fmtObj;
    TCL_RESULT res;
    DWORD flags;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETINT(flags), GETOBJ(fmtObj),
                         GETARGVW(argv, argc), ARGEND);
    if (res == TCL_OK) {
        /* Only look at select bits from dwFlags as others are used when
           formatting from module */
        flags &= FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_STRING;
        flags |=  FORMAT_MESSAGE_ARGUMENT_ARRAY;
        /* Other objs extracted so do not have to worry about fmtObj shimmer*/
        res = TwapiFormatMessageHelper(ticP->interp, flags,
                                       ObjToUnicode(fmtObj), 0, 0, argc, argv);
    }
    MemLifoPopMark(mark);
    return res;
}

static int Twapi_FormatMessageFromModuleObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    WCHAR **argv;
    int     argc;
    TCL_RESULT res;
    DWORD flags, msgid, langid;
    MemLifoMarkHandle mark;
    HANDLE hmod;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETINT(flags), GETHANDLE(hmod), GETINT(msgid),
                         GETINT(langid),
                         GETARGVW(argv, argc),
                         ARGEND);
    if (res == TCL_OK) {
        /* Only look at select bits from dwFlags as others are used when
           formatting from string */
        flags &= FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE;
        flags |=  FORMAT_MESSAGE_ARGUMENT_ARRAY;
        res = TwapiFormatMessageHelper(interp, flags, hmod, msgid, langid, argc, argv);
    }
    MemLifoPopMark(mark);
    return res;
}

static int Twapi_ReportEventObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    HANDLE hEventLog;
    WORD   wType;
    WORD  wCategory;
    DWORD dwEventID;
    PSID  lpUserSid = NULL;
    Tcl_Obj *dataObj;
    int   datalen;
    void *data;
    int     argc;
    LPCWSTR *argv;
    MemLifoMarkHandle mark;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    TWAPI_ASSERT(ticP->memlifoP == SWS());
    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETHANDLE(hEventLog), GETWORD(wType), GETWORD(wCategory),
                         GETINT(dwEventID), GETVAR(lpUserSid, ObjToPSIDSWS),
                         GETARGVW(argv, argc), GETOBJ(dataObj),
                         ARGEND);







|

>





<
<








|










|





|

>
|






<
<










|





|

>
|






<
<

















|

>













<
<







1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821


1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856


1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882


1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915


1916
1917
1918
1919
1920
1921
1922
            TwapiResult_SET_PTR(result, void*, MemLifoResizeLast(h, dw, dw2));
            break;
        }
    }
    return TwapiSetResult(interp, &result);
}

static int Twapi_TranslateNameObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    TCL_RESULT res;
    Tcl_Obj *nameObj;
    WCHAR *bufP, *nameP;
    DWORD sz, nbytes, fmt, desired_fmt;



    bufP = MemLifoPushFrame(ticP->memlifoP, sizeof(WCHAR)*MAX_PATH, &nbytes);
    sz = nbytes/sizeof(WCHAR);
    res = TwapiGetArgs(interp, objc-1, objv+1,
                       GETOBJ(nameObj), GETINT(fmt), GETINT(desired_fmt),
                       ARGEND);
    if (res == TCL_OK) {
        /* Since other args parsed, we can hold on to nameP without fear
           of shimmering */
        nameP = ObjToWinChars(nameObj);
        if (! TranslateNameW(nameP, fmt, desired_fmt, bufP, &sz)) {
            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                bufP = MemLifoAlloc(ticP->memlifoP, sizeof(WCHAR)*sz, NULL);
                if (! TranslateNameW(nameP, fmt, desired_fmt, bufP, &sz))
                    res = TwapiReturnSystemError(interp);
            } else {
                res = TwapiReturnSystemError(interp);
            }
        }
        if (res == TCL_OK)
            ObjSetResult(interp, ObjFromWinCharsN(bufP, sz-1));
    }
    MemLifoPopFrame(ticP->memlifoP);
    return res;
}

static int Twapi_FormatMessageFromStringObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    const WCHAR **argv;
    int     argc;
    Tcl_Obj *fmtObj;
    TCL_RESULT res;
    DWORD flags;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETINT(flags), GETOBJ(fmtObj),
                         GETARGVW(argv, argc), ARGEND);
    if (res == TCL_OK) {
        /* Only look at select bits from dwFlags as others are used when
           formatting from module */
        flags &= FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_STRING;
        flags |=  FORMAT_MESSAGE_ARGUMENT_ARRAY;
        /* Other objs extracted so do not have to worry about fmtObj shimmer*/
        res = TwapiFormatMessageHelper(ticP->interp, flags,
                                       ObjToWinChars(fmtObj), 0, 0, argc, argv);
    }
    MemLifoPopMark(mark);
    return res;
}

static int Twapi_FormatMessageFromModuleObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    const WCHAR **argv;
    int     argc;
    TCL_RESULT res;
    DWORD flags, msgid, langid;
    MemLifoMarkHandle mark;
    HANDLE hmod;



    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETINT(flags), GETHANDLE(hmod), GETINT(msgid),
                         GETINT(langid),
                         GETARGVW(argv, argc),
                         ARGEND);
    if (res == TCL_OK) {
        /* Only look at select bits from dwFlags as others are used when
           formatting from string */
        flags &= FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE;
        flags |=  FORMAT_MESSAGE_ARGUMENT_ARRAY;
        res = TwapiFormatMessageHelper(interp, flags, hmod, msgid, langid, argc, argv);
    }
    MemLifoPopMark(mark);
    return res;
}

static int Twapi_ReportEventObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HANDLE hEventLog;
    WORD   wType;
    WORD  wCategory;
    DWORD dwEventID;
    PSID  lpUserSid = NULL;
    Tcl_Obj *dataObj;
    int   datalen;
    void *data;
    int     argc;
    LPCWSTR *argv;
    MemLifoMarkHandle mark;
    TCL_RESULT res;



    TWAPI_ASSERT(ticP->memlifoP == SWS());
    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETHANDLE(hEventLog), GETWORD(wType), GETWORD(wCategory),
                         GETINT(dwEventID), GETVAR(lpUserSid, ObjToPSIDSWS),
                         GETARGVW(argv, argc), GETOBJ(dataObj),
                         ARGEND);
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
    }
    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_ReadMemoryObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    char *p;
    WCHAR *wp;
    int modifier;
    int type;
    int offset;
    int len;
    Tcl_Obj *objP;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(type), GETVOIDP(p), GETINT(offset),
                     ARGUSEDEFAULT, GETINT(len), GETINT(modifier),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    p += offset;







|







<
<







1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946


1947
1948
1949
1950
1951
1952
1953
    }
    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_ReadMemoryObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    BYTE *p;
    WCHAR *wp;
    int modifier;
    int type;
    int offset;
    int len;
    Tcl_Obj *objP;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(type), GETVOIDP(p), GETINT(offset),
                     ARGUSEDEFAULT, GETINT(len), GETINT(modifier),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    p += offset;
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
    case 2:                     /* chars */
        /* When len > 0, modifier != 0 means also check null terminator */
        if (len > 0 && modifier) {
            for (modifier = 0; modifier < len && p[modifier]; ++modifier)
                ;
            len = modifier;
        }
        objP = ObjFromStringN(p, len);
        break;
        
    case 3:                     /* wide chars */
        if (len > 0)
            len /= sizeof(WCHAR); /* Convert to num chars */
        wp = (WCHAR *) p;

        /* When len > 0, modifier != 0 means also check null terminator */
        if (len > 0 && modifier) {
            for (modifier = 0; modifier < len && wp[modifier]; ++modifier)
                ;
            len = modifier;
        }
        objP = ObjFromUnicodeN(wp, len);
        break;
        
    case 4:                     /* pointer */
        objP = ObjFromLPVOID(*(void* *) p);
        break;

    case 5:                     /* int64 */







|













|







1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
    case 2:                     /* chars */
        /* When len > 0, modifier != 0 means also check null terminator */
        if (len > 0 && modifier) {
            for (modifier = 0; modifier < len && p[modifier]; ++modifier)
                ;
            len = modifier;
        }
        objP = ObjFromStringN((char*) p, len);
        break;
        
    case 3:                     /* wide chars */
        if (len > 0)
            len /= sizeof(WCHAR); /* Convert to num chars */
        wp = (WCHAR *) p;

        /* When len > 0, modifier != 0 means also check null terminator */
        if (len > 0 && modifier) {
            for (modifier = 0; modifier < len && wp[modifier]; ++modifier)
                ;
            len = modifier;
        }
        objP = ObjFromWinCharsN(wp, len);
        break;
        
    case 4:                     /* pointer */
        objP = ObjFromLPVOID(*(void* *) p);
        break;

    case 5:                     /* int64 */
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099

static TCL_RESULT Twapi_WriteMemoryObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    char *bufP;
    DWORD_PTR offset, buf_size;
    int func;
    int sz;
    long lval;
    char *cp;
    WCHAR *wp;
    void  *pv;
    Tcl_WideInt wide;
    Tcl_Obj *dataObj;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(func), GETVOIDP(bufP), GETDWORD_PTR(offset),
                     GETDWORD_PTR(buf_size), ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    dataObj = objv[5];

    /* Note the ARGSKIP ensures the objv[] in that position exists */
    switch (func) {
    case 0: // Int
        if ((offset + sizeof(int)) > buf_size)
            goto overrun;
        if (ObjToLong(interp, dataObj, &lval) != TCL_OK)
            return TCL_ERROR;
        *(int UNALIGNED *)(offset + bufP) = (int) lval;
        break;
    case 1: // Binary
        cp = ObjToByteArray(dataObj, &sz);
        if ((offset + sz) > buf_size)
            goto overrun;
        CopyMemory(offset + bufP, cp, sz);
        break;
    case 2: // Chars
        cp = ObjToStringN(dataObj, &sz);
        /* Note we also include the terminating null */
        if ((offset + sz + 1) > buf_size)
            goto overrun;
        CopyMemory(offset + bufP, cp, sz+1);
        break;
    case 3: // Unicode
        wp = ObjToUnicodeN(dataObj, &sz);
        /* Note we also include the terminating null */
        if ((offset + (sizeof(WCHAR)*(sz + 1))) > buf_size)
            goto overrun;
        CopyMemory(offset + bufP, wp, sizeof(WCHAR)*(sz+1));
        break;
    case 4: // Pointer
        if ((offset + sizeof(void*)) > buf_size)







|
|





<
<













|

|








|





|
|







2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016


2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055

static TCL_RESULT Twapi_WriteMemoryObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    char *bufP;
    DWORD_PTR offset, buf_size;
    int func;
    int sz;
    int val;
    BYTE *cp;
    WCHAR *wp;
    void  *pv;
    Tcl_WideInt wide;
    Tcl_Obj *dataObj;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(func), GETVOIDP(bufP), GETDWORD_PTR(offset),
                     GETDWORD_PTR(buf_size), ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    dataObj = objv[5];

    /* Note the ARGSKIP ensures the objv[] in that position exists */
    switch (func) {
    case 0: // Int
        if ((offset + sizeof(int)) > buf_size)
            goto overrun;
        if (ObjToInt(interp, dataObj, &val) != TCL_OK)
            return TCL_ERROR;
        *(int UNALIGNED *)(offset + bufP) = val;
        break;
    case 1: // Binary
        cp = ObjToByteArray(dataObj, &sz);
        if ((offset + sz) > buf_size)
            goto overrun;
        CopyMemory(offset + bufP, cp, sz);
        break;
    case 2: // Chars
        cp = (BYTE *)ObjToStringN(dataObj, &sz);
        /* Note we also include the terminating null */
        if ((offset + sz + 1) > buf_size)
            goto overrun;
        CopyMemory(offset + bufP, cp, sz+1);
        break;
    case 3: // WCHAR
        wp = ObjToWinCharsN(dataObj, &sz);
        /* Note we also include the terminating null */
        if ((offset + (sizeof(WCHAR)*(sz + 1))) > buf_size)
            goto overrun;
        CopyMemory(offset + bufP, wp, sizeof(WCHAR)*(sz+1));
        break;
    case 4: // Pointer
        if ((offset + sizeof(void*)) > buf_size)
2116
2117
2118
2119
2120
2121
2122
2123
2124

2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146

    return TCL_OK;

overrun:
    return TwapiReturnError(interp, TWAPI_BUFFER_OVERRUN);
}

static TCL_RESULT Twapi_CredPrompt(TwapiInterpContext *ticP, Tcl_Obj *uiObj, int objc, Tcl_Obj *CONST objv[])
{

    int nobjs, user_len, password_len ;
    Tcl_Obj **objs;
    LPWSTR target, user;
    DWORD autherr, save, flags;
    TCL_RESULT res;
    CREDUI_INFOW cui, *cuiP;
    WCHAR *user_buf, *password_buf;
    DWORD status;
    BOOL bsave;
    Tcl_Obj *resultObjs[3], *passwordObj;
    Tcl_Interp *interp = ticP->interp;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    user_buf = NULL;
    password_buf = NULL;

    res = TwapiGetArgsEx(ticP, objc, objv, 
                       GETWSTR(target), ARGUNUSED, GETINT(autherr), 
                       GETWSTRN(user, user_len), GETOBJ(passwordObj),







|

>













<
<







2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094


2095
2096
2097
2098
2099
2100
2101

    return TCL_OK;

overrun:
    return TwapiReturnError(interp, TWAPI_BUFFER_OVERRUN);
}

static TCL_RESULT Twapi_CredPrompt(ClientData clientdata, Tcl_Obj *uiObj, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int nobjs, user_len, password_len ;
    Tcl_Obj **objs;
    LPWSTR target, user;
    DWORD autherr, save, flags;
    TCL_RESULT res;
    CREDUI_INFOW cui, *cuiP;
    WCHAR *user_buf, *password_buf;
    DWORD status;
    BOOL bsave;
    Tcl_Obj *resultObjs[3], *passwordObj;
    Tcl_Interp *interp = ticP->interp;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    user_buf = NULL;
    password_buf = NULL;

    res = TwapiGetArgsEx(ticP, objc, objv, 
                       GETWSTR(target), ARGUNUSED, GETINT(autherr), 
                       GETWSTRN(user, user_len), GETOBJ(passwordObj),
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195

    password_buf = MemLifoAlloc(ticP->memlifoP, sizeof(WCHAR) * (CREDUI_MAX_PASSWORD_LENGTH + 1), NULL);
    if (ObjCharLength(passwordObj) == 0) {
        password_buf[0] = 0;
    } else {
        WCHAR *decryptP;
        TWAPI_ASSERT(ticP->memlifoP == SWS());
        decryptP = ObjDecryptUnicodeSWS(interp, passwordObj, &password_len);
        if (decryptP == NULL)
            goto vamoose;
        if (password_len > CREDUI_MAX_PASSWORD_LENGTH) {
            SecureZeroMemory(decryptP, sizeof(WCHAR) * password_len);
            res = TwapiReturnError(interp, TWAPI_BUFFER_OVERRUN);
            goto vamoose;
        }







|







2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150

    password_buf = MemLifoAlloc(ticP->memlifoP, sizeof(WCHAR) * (CREDUI_MAX_PASSWORD_LENGTH + 1), NULL);
    if (ObjCharLength(passwordObj) == 0) {
        password_buf[0] = 0;
    } else {
        WCHAR *decryptP;
        TWAPI_ASSERT(ticP->memlifoP == SWS());
        decryptP = ObjDecryptWinCharsSWS(interp, passwordObj, &password_len);
        if (decryptP == NULL)
            goto vamoose;
        if (password_len > CREDUI_MAX_PASSWORD_LENGTH) {
            SecureZeroMemory(decryptP, sizeof(WCHAR) * password_len);
            res = TwapiReturnError(interp, TWAPI_BUFFER_OVERRUN);
            goto vamoose;
        }
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
            target, NULL, autherr,
            user_buf, CREDUI_MAX_USERNAME_LENGTH+1,
            password_buf, CREDUI_MAX_PASSWORD_LENGTH+1, &bsave, flags);
    }

    switch (status) {
    case NO_ERROR:
        resultObjs[1] = ObjEncryptUnicode(interp, password_buf, -1);
        if (resultObjs[1] == NULL)
            break;
        resultObjs[0] = ObjFromUnicode(user_buf);
        resultObjs[2] = ObjFromBoolean(bsave);
        ObjSetResult(interp, ObjNewList(3, resultObjs));
        res = TCL_OK;
        break;
    case ERROR_CANCELLED:
        res = TCL_OK;           /* Return empty result */
        break;







|


|







2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
            target, NULL, autherr,
            user_buf, CREDUI_MAX_USERNAME_LENGTH+1,
            password_buf, CREDUI_MAX_PASSWORD_LENGTH+1, &bsave, flags);
    }

    switch (status) {
    case NO_ERROR:
        resultObjs[1] = ObjEncryptWinChars(interp, password_buf, -1);
        if (resultObjs[1] == NULL)
            break;
        resultObjs[0] = ObjFromWinChars(user_buf);
        resultObjs[2] = ObjFromBoolean(bsave);
        ObjSetResult(interp, ObjNewList(3, resultObjs));
        res = TCL_OK;
        break;
    case ERROR_CANCELLED:
        res = TCL_OK;           /* Return empty result */
        break;
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259

2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
        SecureZeroMemory(password_buf, sizeof(WCHAR) * (CREDUI_MAX_PASSWORD_LENGTH+1));

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CredUIPromptObjCmd(
    TwapiInterpContext *ticP,
    Tcl_Interp *interp,
    int  objc,
    Tcl_Obj *CONST objv[])
{
    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    return Twapi_CredPrompt(ticP, objv[1], objc-2, &objv[2]);
}

static TCL_RESULT Twapi_CredUICmdLinePromptObjCmd(
    TwapiInterpContext *ticP,
    Tcl_Interp *interp,
    int  objc,
    Tcl_Obj *CONST objv[])
{
    ObjToUnicodeCleanup();

    return Twapi_CredPrompt(ticP, NULL, objc-1, &objv[1]);
}



void TwapiDefineFncodeCmds(Tcl_Interp *interp, int count,
                                        struct fncode_dispatch_s *tabP, TwapiTclObjCmd *cmdfn)
{
    Tcl_DString ds;
    
    Tcl_DStringInit(&ds);







|




<
<


>
|



|




<
<
|

<
<







2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210


2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222


2223
2224


2225
2226
2227
2228
2229
2230
2231
        SecureZeroMemory(password_buf, sizeof(WCHAR) * (CREDUI_MAX_PASSWORD_LENGTH+1));

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CredUIPromptObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int  objc,
    Tcl_Obj *CONST objv[])
{


    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    return Twapi_CredPrompt((TwapiInterpContext*) clientdata, 
                            objv[1], objc-2, &objv[2]);
}

static TCL_RESULT Twapi_CredUICmdLinePromptObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int  objc,
    Tcl_Obj *CONST objv[])
{


    return Twapi_CredPrompt((TwapiInterpContext *)clientdata, NULL, objc-1, &objv[1]);
}



void TwapiDefineFncodeCmds(Tcl_Interp *interp, int count,
                                        struct fncode_dispatch_s *tabP, TwapiTclObjCmd *cmdfn)
{
    Tcl_DString ds;
    
    Tcl_DStringInit(&ds);
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
    
    Tcl_DStringInit(&ds);
    Tcl_DStringAppend(&ds, "twapi::", ARRAYSIZE("twapi::")-1);

    while (count--) {
        Tcl_DStringSetLength(&ds, ARRAYSIZE("twapi::")-1);
        Tcl_DStringAppend(&ds, tabP->command_name, -1);
        Tcl_CreateAlias(interp, Tcl_DStringValue(&ds), interp, aliascmd, 1, &tabP->fncode);
        ++tabP;
    }
    Tcl_ResetResult(interp);
}

int Twapi_InitCalls(Tcl_Interp *interp, TwapiInterpContext *ticP)
{







|







2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
    
    Tcl_DStringInit(&ds);
    Tcl_DStringAppend(&ds, "twapi::", ARRAYSIZE("twapi::")-1);

    while (count--) {
        Tcl_DStringSetLength(&ds, ARRAYSIZE("twapi::")-1);
        Tcl_DStringAppend(&ds, tabP->command_name, -1);
        Tcl_CreateAlias(interp, Tcl_DStringValue(&ds), interp, aliascmd, 1, (const char * const *) &tabP->fncode);
        ++tabP;
    }
    Tcl_ResetResult(interp);
}

int Twapi_InitCalls(Tcl_Interp *interp, TwapiInterpContext *ticP)
{
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
        }
    }

    /*
     * Got everything we need, now format it
     * {NAME DOMAIN ACCOUNT}
     */
    objs[0] = ObjFromUnicode(nameP);   /* Will exit on alloc fail */
    objs[1] = ObjFromUnicode(domainP); /* Will exit on alloc fail */
    objs[2] = ObjFromInt(account_type);
    result = ObjSetResult(interp, ObjNewList(3, objs));

 done:
    if (mark)
        SWSPopMark(mark);








|
|







2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
        }
    }

    /*
     * Got everything we need, now format it
     * {NAME DOMAIN ACCOUNT}
     */
    objs[0] = ObjFromWinChars(nameP);   /* Will exit on alloc fail */
    objs[1] = ObjFromWinChars(domainP); /* Will exit on alloc fail */
    objs[2] = ObjFromInt(account_type);
    result = ObjSetResult(interp, ObjNewList(3, objs));

 done:
    if (mark)
        SWSPopMark(mark);

2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
    /*
     * Got everything we need, now format it
     * {SID DOMAIN ACCOUNT}
     */
    result = ObjFromSID(interp, sidP, &objs[0]);
    if (result != TCL_OK)
        goto done;
    objs[1] = ObjFromUnicode(domainP); /* Will exit on alloc fail */
    objs[2] = ObjFromInt(account_type);

    result = ObjSetResult(interp, ObjNewList(3, objs));

 done:
    if (mark)
        SWSPopMark(mark);

    return result;
}

int Twapi_NetGetDCName(Tcl_Interp *interp, LPCWSTR servername, LPCWSTR domainname)
{
    NET_API_STATUS status;
    LPBYTE         bufP;
    status = NetGetDCName(servername, domainname, &bufP);
    if (status != NERR_Success) {
        return Twapi_AppendSystemError(interp, status);
    }
    ObjSetResult(interp, ObjFromUnicode((wchar_t *)bufP));
    NetApiBufferFree(bufP);
    return TCL_OK;
}

/* Window enumeration callback. Note this is called from other modules also */
BOOL CALLBACK Twapi_EnumWindowsCallback(HWND hwnd, LPARAM p_ctx) {
    TwapiEnumCtx *p_enum_win_ctx =







|



















|







2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
    /*
     * Got everything we need, now format it
     * {SID DOMAIN ACCOUNT}
     */
    result = ObjFromSID(interp, sidP, &objs[0]);
    if (result != TCL_OK)
        goto done;
    objs[1] = ObjFromWinChars(domainP); /* Will exit on alloc fail */
    objs[2] = ObjFromInt(account_type);

    result = ObjSetResult(interp, ObjNewList(3, objs));

 done:
    if (mark)
        SWSPopMark(mark);

    return result;
}

int Twapi_NetGetDCName(Tcl_Interp *interp, LPCWSTR servername, LPCWSTR domainname)
{
    NET_API_STATUS status;
    LPBYTE         bufP;
    status = NetGetDCName(servername, domainname, &bufP);
    if (status != NERR_Success) {
        return Twapi_AppendSystemError(interp, status);
    }
    ObjSetResult(interp, ObjFromWinChars((wchar_t *)bufP));
    NetApiBufferFree(bufP);
    return TCL_OK;
}

/* Window enumeration callback. Note this is called from other modules also */
BOOL CALLBACK Twapi_EnumWindowsCallback(HWND hwnd, LPARAM p_ctx) {
    TwapiEnumCtx *p_enum_win_ctx =
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
    LSA_HANDLE lsaH;
    int        infoclass;
    ULONG      ul, ul2;
    PPOLICY_AUDIT_EVENT_OPTIONS audit_optP;

    if (objc != 2 ||
        ObjToOpaque(interp, objv[0], (void **) &lsaH, "LSA_HANDLE") != TCL_OK ||
        ObjToLong(interp, objv[1], &infoclass) != TCL_OK) {
        return TwapiReturnError(interp, TWAPI_INVALID_ARGS);
    }    

    ntstatus = LsaQueryInformationPolicy(lsaH, infoclass, &buf);
    if (ntstatus != STATUS_SUCCESS) {
        return Twapi_AppendSystemError(interp,
                                       TwapiNTSTATUSToError(ntstatus));







|







2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
    LSA_HANDLE lsaH;
    int        infoclass;
    ULONG      ul, ul2;
    PPOLICY_AUDIT_EVENT_OPTIONS audit_optP;

    if (objc != 2 ||
        ObjToOpaque(interp, objv[0], (void **) &lsaH, "LSA_HANDLE") != TCL_OK ||
        ObjToInt(interp, objv[1], &infoclass) != TCL_OK) {
        return TwapiReturnError(interp, TWAPI_INVALID_ARGS);
    }    

    ntstatus = LsaQueryInformationPolicy(lsaH, infoclass, &buf);
    if (ntstatus != STATUS_SUCCESS) {
        return Twapi_AppendSystemError(interp,
                                       TwapiNTSTATUSToError(ntstatus));
Changes to undroid/twapi/twapi/base/cstruct.c.
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
                                   If 0, scalar */
    unsigned int offset;        /* Offset from beginning of structure */
    unsigned int size;          /* Size of the field. As int as we may allow
                                   nesting in the future */
    char type;                  /* The type of the field */
} TwapiCStructField;
#define CSTRUCT_REP(o_)    ((TwapiCStructRep *)((o_)->internalRep.twoPtrValue.ptr1))
#define CSTRUCT_REP_ASSIGN(o_)    (o_)->internalRep.twoPtrValue.ptr1

typedef struct TwapiCStructRep_s {
    int nrefs;                  /* Reference count for this structure */
    unsigned int nfields;                /* Number of elements in fields[] */
    unsigned int size;                   /* Size of the defined structure */
    unsigned int alignment;              /* Alignment required (calculated based
                                   on contained fields) */
    TwapiCStructField fields[1];
} TwapiCStructRep;

static int CStructRepDecrRefs(TwapiCStructRep *csP)
{
    csP->nrefs -= 1;
    if (csP->nrefs <= 0) {
        int i;
        for (i = 0; i < csP->nrefs; ++i) {
            if (csP->fields[i].name)
                ObjDecrRefs(csP->fields[i].name);







|










|







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
                                   If 0, scalar */
    unsigned int offset;        /* Offset from beginning of structure */
    unsigned int size;          /* Size of the field. As int as we may allow
                                   nesting in the future */
    char type;                  /* The type of the field */
} TwapiCStructField;
#define CSTRUCT_REP(o_)    ((TwapiCStructRep *)((o_)->internalRep.twoPtrValue.ptr1))
#define CSTRUCT_REP_SET(o_)    (o_)->internalRep.twoPtrValue.ptr1

typedef struct TwapiCStructRep_s {
    int nrefs;                  /* Reference count for this structure */
    unsigned int nfields;                /* Number of elements in fields[] */
    unsigned int size;                   /* Size of the defined structure */
    unsigned int alignment;              /* Alignment required (calculated based
                                   on contained fields) */
    TwapiCStructField fields[1];
} TwapiCStructRep;

static void CStructRepDecrRefs(TwapiCStructRep *csP)
{
    csP->nrefs -= 1;
    if (csP->nrefs <= 0) {
        int i;
        for (i = 0; i < csP->nrefs; ++i) {
            if (csP->fields[i].name)
                ObjDecrRefs(csP->fields[i].name);
186
187
188
189
190
191
192


193
194
195
196
197
198
199
                goto error_return; /* Error message already in interp */
            TWAPI_ASSERT(defObjs[3]->typePtr == &gCStructType);
            child = CSTRUCT_REP(defObjs[3]);
            child->nrefs += 1;  /* Since we will link to it below */
            elem_size = child->size;
            field_alignment = child->alignment;
            break;


        }

        if (field_alignment == 0)
            field_alignment = elem_size;
        if (field_alignment > struct_alignment)
            struct_alignment = field_alignment;








>
>







186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                goto error_return; /* Error message already in interp */
            TWAPI_ASSERT(defObjs[3]->typePtr == &gCStructType);
            child = CSTRUCT_REP(defObjs[3]);
            child->nrefs += 1;  /* Since we will link to it below */
            elem_size = child->size;
            field_alignment = child->alignment;
            break;
        default:
            goto invalid_def;   /* Should not happen... */
        }

        if (field_alignment == 0)
            field_alignment = elem_size;
        if (field_alignment > struct_alignment)
            struct_alignment = field_alignment;

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    csP->size = (offset + struct_alignment - 1) & ~(struct_alignment - 1);

    /* OK, valid opaque rep. Convert the passed object's internal rep */
    if (csObj->typePtr && csObj->typePtr->freeIntRepProc) {
        csObj->typePtr->freeIntRepProc(csObj);
    }
    csObj->typePtr = &gCStructType;
    CSTRUCT_REP_ASSIGN(csObj) = csP;
    csObj->internalRep.twoPtrValue.ptr2 = NULL;

    return TCL_OK;

invalid_def:
    TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS,
                        "Invalid CStruct definition");







|







220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
    csP->size = (offset + struct_alignment - 1) & ~(struct_alignment - 1);

    /* OK, valid opaque rep. Convert the passed object's internal rep */
    if (csObj->typePtr && csObj->typePtr->freeIntRepProc) {
        csObj->typePtr->freeIntRepProc(csObj);
    }
    csObj->typePtr = &gCStructType;
    CSTRUCT_REP_SET(csObj) = csP;
    csObj->internalRep.twoPtrValue.ptr2 = NULL;

    return TCL_OK;

invalid_def:
    TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS,
                        "Invalid CStruct definition");
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

268
269


270
271
272
273
274
275
276
/* Caller responsible for all MemLifo releasing */
static TCL_RESULT ParseCStructHelper (Tcl_Interp *interp, MemLifo *memlifoP,
                                      TwapiCStructRep *csP, 
                                      Tcl_Obj *valObj, DWORD flags,
                                      DWORD size, void *pv)
{
    Tcl_Obj **objPP;
    unsigned int i, nobjs;
    TCL_RESULT res;

    csP->nrefs += 1;            /* So it is not shimmered away underneath us */
    
    if (csP->size != size) {
        TwapiReturnError(interp, TWAPI_BUFFER_OVERRUN);
        goto error_return;
    }

    if (ObjGetElements(interp, valObj, &nobjs, &objPP) != TCL_OK ||
        nobjs != csP->nfields)  /* Not correct number of values */
        goto invalid_def;
    
    for (i = 0; i < nobjs; ++i) {
        int count = csP->fields[i].count;
        void *pv2 = ADDPTR(pv, csP->fields[i].offset, void*);
        Tcl_Obj **arrayObj;
        int       nelems;        /* # elements in array */
        void *s;
        int j, elem_size, len;

        TCL_RESULT (*fn)(Tcl_Interp *, Tcl_Obj *, void *);



        /* count > 0 => array and source obj is a list (even if count == 1) */
        if (count) {
            if (ObjGetElements(interp, objPP[i], &nelems, &arrayObj) != TCL_OK)
                goto error_return;
            if (count > nelems) {
                TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Too few elements in cstruct array field");
                goto error_return;







|




















>

|
>
>







242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/* Caller responsible for all MemLifo releasing */
static TCL_RESULT ParseCStructHelper (Tcl_Interp *interp, MemLifo *memlifoP,
                                      TwapiCStructRep *csP, 
                                      Tcl_Obj *valObj, DWORD flags,
                                      DWORD size, void *pv)
{
    Tcl_Obj **objPP;
    int i, nobjs;
    TCL_RESULT res;

    csP->nrefs += 1;            /* So it is not shimmered away underneath us */
    
    if (csP->size != size) {
        TwapiReturnError(interp, TWAPI_BUFFER_OVERRUN);
        goto error_return;
    }

    if (ObjGetElements(interp, valObj, &nobjs, &objPP) != TCL_OK ||
        nobjs != csP->nfields)  /* Not correct number of values */
        goto invalid_def;
    
    for (i = 0; i < nobjs; ++i) {
        int count = csP->fields[i].count;
        void *pv2 = ADDPTR(pv, csP->fields[i].offset, void*);
        Tcl_Obj **arrayObj;
        int       nelems;        /* # elements in array */
        void *s;
        int j, elem_size, len;
#if 0
        TCL_RESULT (*fn)(Tcl_Interp *, Tcl_Obj *, void *);
#else
        TCL_RESULT (*fn)();
#endif
        /* count > 0 => array and source obj is a list (even if count == 1) */
        if (count) {
            if (ObjGetElements(interp, objPP[i], &nelems, &arrayObj) != TCL_OK)
                goto error_return;
            if (count > nelems) {
                TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Too few elements in cstruct array field");
                goto error_return;
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
                *(char **)pv2 = MemLifoCopy(memlifoP, s, len+1);
            }
            continue;

        case CSTRUCT_WSTRING:
            if (count) {
                for (j = 0; j < count; j++, pv2 = ADDPTR(pv2, elem_size, void*)) {
                    s = ObjToUnicodeN(arrayObj[j], &len);
                    *(char **)pv2 = MemLifoCopy(memlifoP, s, sizeof(WCHAR)*(len+1));
                }
            } else {
                s = ObjToUnicodeN(objPP[i], &len);
                *(char **)pv2 = MemLifoCopy(memlifoP, s, sizeof(WCHAR)*(len+1));
            }
            continue;

        case CSTRUCT_CBSIZE:
            TWAPI_ASSERT(count == 0);
            fn = ObjToInt;







|



|







339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
                *(char **)pv2 = MemLifoCopy(memlifoP, s, len+1);
            }
            continue;

        case CSTRUCT_WSTRING:
            if (count) {
                for (j = 0; j < count; j++, pv2 = ADDPTR(pv2, elem_size, void*)) {
                    s = ObjToWinCharsN(arrayObj[j], &len);
                    *(char **)pv2 = MemLifoCopy(memlifoP, s, sizeof(WCHAR)*(len+1));
                }
            } else {
                s = ObjToWinCharsN(objPP[i], &len);
                *(char **)pv2 = MemLifoCopy(memlifoP, s, sizeof(WCHAR)*(len+1));
            }
            continue;

        case CSTRUCT_CBSIZE:
            TWAPI_ASSERT(count == 0);
            fn = ObjToInt;
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
        case CSTRUCT_INT: EXTRACT(int, ObjFromInt); break;
        case CSTRUCT_UINT: EXTRACT(DWORD, ObjFromWideInt); break;
        case CSTRUCT_INT64: EXTRACT(__int64, ObjFromWideInt); break;
        case CSTRUCT_UINT64: EXTRACT(__int64, ObjFromWideInt); break; // TBD-handles unsigned ?
        case CSTRUCT_DOUBLE: EXTRACT(double, ObjFromDouble); break;
        case CSTRUCT_HANDLE: EXTRACT(HANDLE, ObjFromHANDLE); break;
        case CSTRUCT_STRING: EXTRACT(char*, ObjFromString); break;
        case CSTRUCT_WSTRING: EXTRACT(WCHAR*, ObjFromUnicode); break;
        case CSTRUCT_CBSIZE: EXTRACT(DWORD, ObjFromDWORD); break;
        case CSTRUCT_PSID:
            if (include_key) objs[objindex++] = csP->fields[i].name;
            if (count) {
                arrayObj = ObjNewList(count, NULL);
                for (j = 0; j < count; j++, pv2 = ADDPTR(pv2, elem_size, void*)) {
                    Tcl_Obj *elemObj;







|







518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
        case CSTRUCT_INT: EXTRACT(int, ObjFromInt); break;
        case CSTRUCT_UINT: EXTRACT(DWORD, ObjFromWideInt); break;
        case CSTRUCT_INT64: EXTRACT(__int64, ObjFromWideInt); break;
        case CSTRUCT_UINT64: EXTRACT(__int64, ObjFromWideInt); break; // TBD-handles unsigned ?
        case CSTRUCT_DOUBLE: EXTRACT(double, ObjFromDouble); break;
        case CSTRUCT_HANDLE: EXTRACT(HANDLE, ObjFromHANDLE); break;
        case CSTRUCT_STRING: EXTRACT(char*, ObjFromString); break;
        case CSTRUCT_WSTRING: EXTRACT(WCHAR*, ObjFromWinChars); break;
        case CSTRUCT_CBSIZE: EXTRACT(DWORD, ObjFromDWORD); break;
        case CSTRUCT_PSID:
            if (include_key) objs[objindex++] = csP->fields[i].name;
            if (count) {
                arrayObj = ObjNewList(count, NULL);
                for (j = 0; j < count; j++, pv2 = ADDPTR(pv2, elem_size, void*)) {
                    Tcl_Obj *elemObj;
Changes to undroid/twapi/twapi/base/errors.c.
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
       at the script level and force IGNORE_INSERTS here.

       As a side-benefit, not using __try reduces CRT dependency.
    */

    dwFlags |= FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS;
    if (FormatMessageW(dwFlags, lpSource, dwMessageId, dwLanguageId, (LPWSTR) &msgP, argc, (va_list *)argv)) {
        ObjSetResult(interp, ObjFromUnicode(msgP));
        LocalFree(msgP);
        return TCL_OK;
    } else {
        return TwapiReturnSystemError(interp);
    }
}








|







67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
       at the script level and force IGNORE_INSERTS here.

       As a side-benefit, not using __try reduces CRT dependency.
    */

    dwFlags |= FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS;
    if (FormatMessageW(dwFlags, lpSource, dwMessageId, dwLanguageId, (LPWSTR) &msgP, argc, (va_list *)argv)) {
        ObjSetResult(interp, ObjFromWinChars(msgP));
        LocalFree(msgP);
        return TCL_OK;
    } else {
        return TwapiReturnSystemError(interp);
    }
}

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        /* Strip trailing CR LF if any */
        if (wMsgPtr[length-1] == L'\n')
            --length;
        if (length > 0) {
            if (wMsgPtr[length-1] == L'\r')
                --length;
        }
        objP = ObjFromUnicodeN(wMsgPtr, length);
        LocalFree(wMsgPtr);
        return objP;
    }

    /* Try the ascii version. TBD - is this really meaningful if above failed ? */

    length = FormatMessageA(flags, hModule, error,







|







107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        /* Strip trailing CR LF if any */
        if (wMsgPtr[length-1] == L'\n')
            --length;
        if (length > 0) {
            if (wMsgPtr[length-1] == L'\r')
                --length;
        }
        objP = ObjFromWinCharsN(wMsgPtr, length);
        LocalFree(wMsgPtr);
        return objP;
    }

    /* Try the ascii version. TBD - is this really meaningful if above failed ? */

    length = FormatMessageA(flags, hModule, error,
347
348
349
350
351
352
353





354

355
356
357
358
359
360
361
    errorCodeObj = Twapi_MakeWindowsErrorCodeObj(error, extra);

    /* Third element of error code is also the message */
    if (ObjListIndex(NULL, errorCodeObj, 2, &msgObj) == TCL_OK &&
        msgObj != NULL) {
        Tcl_Obj *resultObj = ObjDuplicate(ObjGetResult(interp));
        if (ObjCharLength(resultObj)) {





            Tcl_AppendToObj(resultObj, " ", 1);

        }
        Tcl_AppendObjToObj(resultObj, msgObj);
        (void) ObjSetResult(interp, resultObj);
    }
    Tcl_SetObjErrorCode(interp, errorCodeObj);

    return TCL_ERROR;           /* Always return TCL_ERROR */







>
>
>
>
>

>







347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    errorCodeObj = Twapi_MakeWindowsErrorCodeObj(error, extra);

    /* Third element of error code is also the message */
    if (ObjListIndex(NULL, errorCodeObj, 2, &msgObj) == TCL_OK &&
        msgObj != NULL) {
        Tcl_Obj *resultObj = ObjDuplicate(ObjGetResult(interp));
        if (ObjCharLength(resultObj)) {
#if TCL_UTF_MAX <= 4
            Tcl_AppendUnicodeToObj(resultObj, L" ", 1);
#else
            /* Tcl_UniChar is int. So cannot use AppendUnicode. Have 
               to force a shimmer to string */
            Tcl_AppendToObj(resultObj, " ", 1);
#endif
        }
        Tcl_AppendObjToObj(resultObj, msgObj);
        (void) ObjSetResult(interp, resultObj);
    }
    Tcl_SetObjErrorCode(interp, errorCodeObj);

    return TCL_ERROR;           /* Always return TCL_ERROR */
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

        Tcl_DStringInit(&ds);
        Tcl_DStringAppend(&ds, (char *) L" ", sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) provider, lstrlenW(provider) * sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) L": ", 2 * sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) errorbuf, lstrlenW(errorbuf) * sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) L"\0", sizeof (WCHAR));
        Tcl_AppendObjToObj(resultObj, ObjFromUnicode((WCHAR *) Tcl_DStringValue(&ds)));
        Tcl_DStringFree(&ds);
        (void) ObjSetResult(interp, resultObj);
    }

    return TCL_ERROR;
}








|







412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

        Tcl_DStringInit(&ds);
        Tcl_DStringAppend(&ds, (char *) L" ", sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) provider, lstrlenW(provider) * sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) L": ", 2 * sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) errorbuf, lstrlenW(errorbuf) * sizeof (WCHAR));
        Tcl_DStringAppend(&ds, (char *) L"\0", sizeof (WCHAR));
        Tcl_AppendObjToObj(resultObj, ObjFromWinChars((WCHAR *) Tcl_DStringValue(&ds)));
        Tcl_DStringFree(&ds);
        (void) ObjSetResult(interp, resultObj);
    }

    return TCL_ERROR;
}

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
            GetErrorInfo(0, &ei);
        }
    }
    if (ei) {
        BSTR msg;
        ei->lpVtbl->GetDescription(ei, &msg);
        Twapi_AppendSystemErrorEx(interp, hr,
                                  ObjFromUnicodeN(msg, SysStringLen(msg)));

        SysFreeString(msg);
        ei->lpVtbl->Release(ei);
    } else {
        Twapi_AppendSystemError(interp, hr);
    }








|







464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
            GetErrorInfo(0, &ei);
        }
    }
    if (ei) {
        BSTR msg;
        ei->lpVtbl->GetDescription(ei, &msg);
        Twapi_AppendSystemErrorEx(interp, hr,
                                 ObjFromWinCharsN(msg,SysStringLen(msg)));

        SysFreeString(msg);
        ei->lpVtbl->Release(ei);
    } else {
        Twapi_AppendSystemError(interp, hr);
    }

Changes to undroid/twapi/twapi/base/ffi.c.
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

TCL_RESULT Twapi_FfiLoadObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    TwapiTls *tlsP;
    DWORD dw;

    ObjToUnicodeCleanup();

    CHECK_NARGS(interp, objc, 2);
    tlsP = Twapi_GetTls();
    --objc;
    ++objv;
    if (ObjDictGet(interp, tlsP->ffiObj, objv[0], &objP) != TCL_OK)
        return TCL_ERROR;
    if (objP == NULL) {
        /* Entry does not exist. Check if the DLL handle is there */
        Tcl_Obj **dll_and_func;
        Tcl_Obj *dllObj;
        HMODULE  hdll = NULL;
        FARPROC fn;
        if (ObjGetElements(NULL, objv[0], &dw, &dll_and_func) != TCL_OK ||
            dw != 2) {
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid DLL and function specification");
        }
        if (ObjDictGet(interp, tlsP->ffiObj, dll_and_func[0], &dllObj) != TCL_OK)
            return TCL_ERROR;
        if (dllObj == NULL) {
            hdll = LoadLibraryW(ObjToUnicode(dll_and_func[0]));
            ObjDictPut(interp, tlsP->ffiObj, dll_and_func[0], ObjFromHMODULE(hdll)); /* May be NULL */
        } else {
            if (ObjToHMODULE(interp, dllObj, &hdll) != TCL_OK)
                return TCL_ERROR;
        }
        if (hdll) {
            /* Have DLL, get the function address */







<
<



















|







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

TCL_RESULT Twapi_FfiLoadObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    TwapiTls *tlsP;
    DWORD dw;



    CHECK_NARGS(interp, objc, 2);
    tlsP = Twapi_GetTls();
    --objc;
    ++objv;
    if (ObjDictGet(interp, tlsP->ffiObj, objv[0], &objP) != TCL_OK)
        return TCL_ERROR;
    if (objP == NULL) {
        /* Entry does not exist. Check if the DLL handle is there */
        Tcl_Obj **dll_and_func;
        Tcl_Obj *dllObj;
        HMODULE  hdll = NULL;
        FARPROC fn;
        if (ObjGetElements(NULL, objv[0], &dw, &dll_and_func) != TCL_OK ||
            dw != 2) {
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid DLL and function specification");
        }
        if (ObjDictGet(interp, tlsP->ffiObj, dll_and_func[0], &dllObj) != TCL_OK)
            return TCL_ERROR;
        if (dllObj == NULL) {
            hdll = LoadLibraryW(ObjToWinChars(dll_and_func[0]));
            ObjDictPut(interp, tlsP->ffiObj, dll_and_func[0], ObjFromHMODULE(hdll)); /* May be NULL */
        } else {
            if (ObjToHMODULE(interp, dllObj, &hdll) != TCL_OK)
                return TCL_ERROR;
        }
        if (hdll) {
            /* Have DLL, get the function address */
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

TCL_RESULT Twapi_Ffi0ObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    FARPROC fn;
    Tcl_WideInt ret;
    DWORD winerr;
    Tcl_Obj *objs[2];

    ObjToUnicodeCleanup();

    CHECK_NARGS(interp, objc, 2);

    /* ffi0 PROCADDR */
    if (ObjToFARPROC(interp, objv[1], &fn) != TCL_OK)
        return TCL_ERROR;

    TWAPI_ASSERT(fn);







|
<
<







53
54
55
56
57
58
59
60


61
62
63
64
65
66
67

TCL_RESULT Twapi_Ffi0ObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    FARPROC fn;
    Tcl_WideInt ret;
    DWORD winerr;
    Tcl_Obj *objs[2];
    


    CHECK_NARGS(interp, objc, 2);

    /* ffi0 PROCADDR */
    if (ObjToFARPROC(interp, objv[1], &fn) != TCL_OK)
        return TCL_ERROR;

    TWAPI_ASSERT(fn);
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
TCL_RESULT Twapi_FfiHObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    FARPROC fn;
    Tcl_WideInt ret;
    DWORD winerr;
    HANDLE h;
    Tcl_Obj *objs[2];

    ObjToUnicodeCleanup();

    CHECK_NARGS(interp, objc, 3);

    /* ffi0 PROCADDR RETURNTYPE */
    if (ObjToFARPROC(interp, objv[1], &fn) != TCL_OK ||
        ObjToHANDLE(interp, objv[2], &h) != TCL_OK)
        return TCL_ERROR;








|
<
<







76
77
78
79
80
81
82
83


84
85
86
87
88
89
90
TCL_RESULT Twapi_FfiHObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    FARPROC fn;
    Tcl_WideInt ret;
    DWORD winerr;
    HANDLE h;
    Tcl_Obj *objs[2];
    


    CHECK_NARGS(interp, objc, 3);

    /* ffi0 PROCADDR RETURNTYPE */
    if (ObjToFARPROC(interp, objv[1], &fn) != TCL_OK ||
        ObjToHANDLE(interp, objv[2], &h) != TCL_OK)
        return TCL_ERROR;

Changes to undroid/twapi/twapi/base/makefile.
18
19
20
21
22
23
24
25

26
27
28
29
30
31
32
	$(OBJDIR)\recordarray.obj \
	$(OBJDIR)\tclobjs.obj \
	$(OBJDIR)\threadpool.obj \
	$(OBJDIR)\trap.obj \
	$(OBJDIR)\twapi.obj \
	$(OBJDIR)\twine.obj \
	$(OBJDIR)\util.obj \
	$(OBJDIR)\win.obj


TCLFILES=..\tcl\twapi.tcl \
	..\tcl\base.tcl \
	..\tcl\handle.tcl \
	..\tcl\win.tcl \
	..\tcl\adsi.tcl








|
>







18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
	$(OBJDIR)\recordarray.obj \
	$(OBJDIR)\tclobjs.obj \
	$(OBJDIR)\threadpool.obj \
	$(OBJDIR)\trap.obj \
	$(OBJDIR)\twapi.obj \
	$(OBJDIR)\twine.obj \
	$(OBJDIR)\util.obj \
	$(OBJDIR)\win.obj \
	$(OBJDIR)\winchars.obj

TCLFILES=..\tcl\twapi.tcl \
	..\tcl\base.tcl \
	..\tcl\handle.tcl \
	..\tcl\win.tcl \
	..\tcl\adsi.tcl

Changes to undroid/twapi/twapi/base/memlifo.c.
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    MemLifoChunk *c;
    MemLifoMarkHandle m;
    DWORD chunk_sz;
    void *p;

    if (sz > MEMLIFO_MAX_ALLOC) {
        if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
            Tcl_Panic("Attempt to allocate %d bytes for memlifo", sz);
        return NULL;
    }

    /* 
     * NOTE: note that when called from MemLifoExpandLast(), on entry the 
     * lm_last_alloc field may not be set correctly since that function 
     * may remove the last allocation from the big block list under 







|







158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    MemLifoChunk *c;
    MemLifoMarkHandle m;
    DWORD chunk_sz;
    void *p;

    if (sz > MEMLIFO_MAX_ALLOC) {
        if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
            Tcl_Panic("Attempt to allocate %lu bytes for memlifo", sz);
        return NULL;
    }

    /* 
     * NOTE: note that when called from MemLifoExpandLast(), on entry the 
     * lm_last_alloc field may not be set correctly since that function 
     * may remove the last allocation from the big block list under 
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

        MEMLIFO_ASSERT(ROUNDED(chunk_sz));
        chunk_sz += ROUNDUP(sizeof(MemLifoChunk));

	c = l->lifo_allocFn(chunk_sz, l->lifo_allocator_data, &chunk_sz);
	if (c == 0) {
            if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
                Tcl_Panic("Attempt to allocate %d bytes for memlifo", chunk_sz);
	    return 0;
        }

	c->lc_end = ADDPTR(c, chunk_sz, void*);

	c->lc_prev = m->lm_chunks;	/* Place on the list of chunks */
	m->lm_chunks = c;







|







234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

        MEMLIFO_ASSERT(ROUNDED(chunk_sz));
        chunk_sz += ROUNDUP(sizeof(MemLifoChunk));

	c = l->lifo_allocFn(chunk_sz, l->lifo_allocator_data, &chunk_sz);
	if (c == 0) {
            if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
                Tcl_Panic("Attempt to allocate %lu bytes for memlifo", chunk_sz);
	    return 0;
        }

	c->lc_end = ADDPTR(c, chunk_sz, void*);

	c->lc_prev = m->lm_chunks;	/* Place on the list of chunks */
	m->lm_chunks = c;
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        chunk_sz = sz + ROUNDUP(sizeof(MemLifoChunk));

	c = (MemLifoChunk *) l->lifo_allocFn(chunk_sz,
                                                  l->lifo_allocator_data,
                                                  &actual_size);
	if (c == 0) {
            if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
                Tcl_Panic("Attempt to allocate %d bytes for memlifo", chunk_sz);
	    return 0;
        }
	c->lc_end = ADDPTR(c, actual_size, void*);

	c->lc_prev = m->lm_big_blocks;	/* Place on the list of big blocks */
	m->lm_big_blocks = c;
	/* 







|







261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        chunk_sz = sz + ROUNDUP(sizeof(MemLifoChunk));

	c = (MemLifoChunk *) l->lifo_allocFn(chunk_sz,
                                                  l->lifo_allocator_data,
                                                  &actual_size);
	if (c == 0) {
            if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
                Tcl_Panic("Attempt to allocate %lu bytes for memlifo", chunk_sz);
	    return 0;
        }
	c->lc_end = ADDPTR(c, actual_size, void*);

	c->lc_prev = m->lm_big_blocks;	/* Place on the list of big blocks */
	m->lm_big_blocks = c;
	/* 
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
	 * would change the state of the previous mark.
	 */
	c = l->lifo_allocFn(l->lifo_chunk_size,
                            l->lifo_allocator_data,
                            &chunk_sz);
	if (c == 0) {
            if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
                Tcl_Panic("Attempt to allocate %d bytes for memlifo", l->lifo_chunk_size);
	    return 0;
        }	
	c->lc_end = ADDPTR(c, chunk_sz, void*);	

	/* 
	 * Place on the list of chunks. Note however, that we do NOT 
	 * modify m->lm_chunkList since that should hold the original lifo 







|







337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
	 * would change the state of the previous mark.
	 */
	c = l->lifo_allocFn(l->lifo_chunk_size,
                            l->lifo_allocator_data,
                            &chunk_sz);
	if (c == 0) {
            if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
                Tcl_Panic("Attempt to allocate %lu bytes for memlifo", l->lifo_chunk_size);
	    return 0;
        }	
	c->lc_end = ADDPTR(c, chunk_sz, void*);	

	/* 
	 * Place on the list of chunks. Note however, that we do NOT 
	 * modify m->lm_chunkList since that should hold the original lifo 
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    MemLifoMarkHandle m, n;
    DWORD total;
       
    MEMLIFO_ASSERT(l->lifo_magic == MEMLIFO_MAGIC);
    
    if (sz > MEMLIFO_MAX_ALLOC) {
        if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
            Tcl_Panic("Attempt to allocate %d bytes for memlifo", sz);
        return NULL;
    }

    m = l->lifo_top_mark;
    MEMLIFO_ASSERT(m);
    MEMLIFO_ASSERT(ALIGNED(m->lm_freeptr));
    MEMLIFO_ASSERT(ALIGNED(m->lm_chunks->lc_end));







|







429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    MemLifoMarkHandle m, n;
    DWORD total;
       
    MEMLIFO_ASSERT(l->lifo_magic == MEMLIFO_MAGIC);
    
    if (sz > MEMLIFO_MAX_ALLOC) {
        if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
            Tcl_Panic("Attempt to allocate %lu bytes for memlifo", sz);
        return NULL;
    }

    m = l->lifo_top_mark;
    MEMLIFO_ASSERT(m);
    MEMLIFO_ASSERT(ALIGNED(m->lm_freeptr));
    MEMLIFO_ASSERT(ALIGNED(m->lm_chunks->lc_end));
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
    if (n) {
        p = MemLifoAlloc(l, sz, actual_szP);
        if (p)
            return p;
        MemLifoPopMark(n);
    }
    if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
        Tcl_Panic("Attempt to allocate %d bytes for memlifo", sz);
    return NULL;
}

void *MemLifoExpandLast(MemLifo *l, DWORD incr, int fix)
{
    MemLifoMarkHandle m;
    DWORD old_sz, sz, chunk_sz;







|







484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
    if (n) {
        p = MemLifoAlloc(l, sz, actual_szP);
        if (p)
            return p;
        MemLifoPopMark(n);
    }
    if (l->lifo_flags & MEMLIFO_F_PANIC_ON_FAIL)
        Tcl_Panic("Attempt to allocate %lu bytes for memlifo", sz);
    return NULL;
}

void *MemLifoExpandLast(MemLifo *l, DWORD incr, int fix)
{
    MemLifoMarkHandle m;
    DWORD old_sz, sz, chunk_sz;
Changes to undroid/twapi/twapi/base/parseargs.c.
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

389
390
391
392
393
394
395
396
397
398

    for (k = 0; k < nopts; ++k)
        valuesP[k] = NULL;      /* Values corresponding to each option */

    /* TBD - use Tcl_GetIndexFromObj to parse parseargs options. Faster */
    for (j = 3 ; j < objc ; ++j) {
        char *s = ObjToString(objv[j]);
        long lv;
        if (STREQ("-nulldefault", s)) {
            nulldefault = 1;
        }
        else if (STREQ("-maxleftover", s)) {
            ++j;
            if (j == objc) {
                ObjSetStaticResult(interp, "Missing value for -maxleftover");
                goto invalid_args_error;
            }
            if (ObjToLong(interp, objv[j], &lv) != TCL_OK) {

                goto invalid_args_error;
            }
            maxleftover = lv;
        }
        else if (STREQ("-setvars", s)) {
            setvars = 1;
        }
        else if (STREQ("-ignoreunknown", s)) {
            ignoreunknown = 1;
        }







<









|
>


<







371
372
373
374
375
376
377

378
379
380
381
382
383
384
385
386
387
388
389
390

391
392
393
394
395
396
397

    for (k = 0; k < nopts; ++k)
        valuesP[k] = NULL;      /* Values corresponding to each option */

    /* TBD - use Tcl_GetIndexFromObj to parse parseargs options. Faster */
    for (j = 3 ; j < objc ; ++j) {
        char *s = ObjToString(objv[j]);

        if (STREQ("-nulldefault", s)) {
            nulldefault = 1;
        }
        else if (STREQ("-maxleftover", s)) {
            ++j;
            if (j == objc) {
                ObjSetStaticResult(interp, "Missing value for -maxleftover");
                goto invalid_args_error;
            }

            if (ObjToInt(interp, objv[j], &maxleftover) != TCL_OK) {
                goto invalid_args_error;
            }

        }
        else if (STREQ("-setvars", s)) {
            setvars = 1;
        }
        else if (STREQ("-ignoreunknown", s)) {
            ignoreunknown = 1;
        }
Changes to undroid/twapi/twapi/base/printer.c.
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        }
    }

    printerInfoP = (PRINTER_INFO_4W *)buf;
    resultObj = ObjNewList(0, NULL);
    for (i = 0; i < num_printers; ++i, ++printerInfoP) {
        Tcl_Obj *objs[3];
        objs[0] = ObjFromUnicode(printerInfoP->pPrinterName);
        objs[1] = ObjFromUnicode(printerInfoP->pServerName);
        objs[2] = ObjFromDWORD(printerInfoP->Attributes);
        ObjAppendElement(interp, resultObj, ObjNewList(3, objs));
    }

    ObjSetResult(interp, resultObj);
    MemLifoPopFrame(ticP->memlifoP);








|
|







42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        }
    }

    printerInfoP = (PRINTER_INFO_4W *)buf;
    resultObj = ObjNewList(0, NULL);
    for (i = 0; i < num_printers; ++i, ++printerInfoP) {
        Tcl_Obj *objs[3];
        objs[0] = ObjFromWinChars(printerInfoP->pPrinterName);
        objs[1] = ObjFromWinChars(printerInfoP->pServerName);
        objs[2] = ObjFromDWORD(printerInfoP->Attributes);
        ObjAppendElement(interp, resultObj, ObjNewList(3, objs));
    }

    ObjSetResult(interp, resultObj);
    MemLifoPopFrame(ticP->memlifoP);

Changes to undroid/twapi/twapi/base/recordarray.c.
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
            char *string;
        } operand;
        int (WINAPI *cmpfn) (const char *, const char *);
        int filter_pos;
        int filter_op;
        int nocase;
        int negate;
    } *filters;
    int nfilters;
    TCL_RESULT res;

    Tcl_Obj *new_rec[2];        /* 2 because we may need one for the key */
    Tcl_Obj **output = NULL;
    int output_count;








|







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
            char *string;
        } operand;
        int (WINAPI *cmpfn) (const char *, const char *);
        int filter_pos;
        int filter_op;
        int nocase;
        int negate;
    } *filters = NULL;
    int nfilters;
    TCL_RESULT res;

    Tcl_Obj *new_rec[2];        /* 2 because we may need one for the key */
    Tcl_Obj **output = NULL;
    int output_count;

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
    static const char *cmds[] = {
        "get",
        "set",
        "select",
        NULL,
    };

    ObjToUnicodeCleanup();

    objP = NULL;
    switch (objc) {
    case 1:
        objP = fieldsObj;
        break;
    case 2:
        if (ObjListLength(interp, fieldsObj, &i) != TCL_OK ||







<
<







465
466
467
468
469
470
471


472
473
474
475
476
477
478
    static const char *cmds[] = {
        "get",
        "set",
        "select",
        NULL,
    };



    objP = NULL;
    switch (objc) {
    case 1:
        objP = fieldsObj;
        break;
    case 2:
        if (ObjListLength(interp, fieldsObj, &i) != TCL_OK ||
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
    Tcl_WrongNumArgs(interp, 1, objv, "command RECORD PARAM ?PARAM ...?");
    return TCL_ERROR;
}

static void RecordInstanceObjCmdDelete(ClientData fieldsObj)
{
    ObjDecrRefs(fieldsObj);
    ObjToUnicodeCleanup();
}


/* TBD - document */
TCL_RESULT Twapi_RecordObjCmd(
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{
    int len;
    TCL_RESULT res;
    Tcl_Obj *nameObj, *fieldsObj;
    Tcl_Namespace *nsP;
    char *sep;

    ObjToUnicodeCleanup();

    switch (objc) {
    case 2: fieldsObj = objv[1]; break;
    case 3: fieldsObj = objv[2]; break;
    default:
        Tcl_WrongNumArgs(interp, 1, objv, "?RECORDNAME? FIELDS");
        return TCL_ERROR;
    }
    
    res = ObjListLength(interp, fieldsObj, &len); 
    if (res != TCL_OK)
        return res;
    if (len == 0) {
        ObjSetStaticResult(interp, "empty record definition");
        return TCL_ERROR;
    }

    nsP = Tcl_GetCurrentNamespace(interp);
    sep = nsP->parentPtr == NULL ? "" : "::";
    if (objc < 3) 
        nameObj = Tcl_ObjPrintf("%s%srecord%d", nsP->fullName, sep, (int) Twapi_NewId());
    else {
        char *nameP = ObjToString(objv[1]);
        if (nameP[0] == ':' && nameP[1] == ':')
            nameObj = objv[1];
        else
            nameObj = Tcl_ObjPrintf("%s%s%s", nsP->fullName, sep, nameP);
    }







<
















<
<



















|







553
554
555
556
557
558
559

560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575


576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
    Tcl_WrongNumArgs(interp, 1, objv, "command RECORD PARAM ?PARAM ...?");
    return TCL_ERROR;
}

static void RecordInstanceObjCmdDelete(ClientData fieldsObj)
{
    ObjDecrRefs(fieldsObj);

}


/* TBD - document */
TCL_RESULT Twapi_RecordObjCmd(
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{
    int len;
    TCL_RESULT res;
    Tcl_Obj *nameObj, *fieldsObj;
    Tcl_Namespace *nsP;
    char *sep;



    switch (objc) {
    case 2: fieldsObj = objv[1]; break;
    case 3: fieldsObj = objv[2]; break;
    default:
        Tcl_WrongNumArgs(interp, 1, objv, "?RECORDNAME? FIELDS");
        return TCL_ERROR;
    }
    
    res = ObjListLength(interp, fieldsObj, &len); 
    if (res != TCL_OK)
        return res;
    if (len == 0) {
        ObjSetStaticResult(interp, "empty record definition");
        return TCL_ERROR;
    }

    nsP = Tcl_GetCurrentNamespace(interp);
    sep = nsP->parentPtr == NULL ? "" : "::";
    if (objc < 3) 
        nameObj = Tcl_ObjPrintf("%s%srecord%u", nsP->fullName, sep, Twapi_NewId());
    else {
        char *nameP = ObjToString(objv[1]);
        if (nameP[0] == ':' && nameP[1] == ':')
            nameObj = objv[1];
        else
            nameObj = Tcl_ObjPrintf("%s%s%s", nsP->fullName, sep, nameP);
    }
Changes to undroid/twapi/twapi/base/tclobjs.c.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#define TWAPI_MAX_SAFEARRAY_DIMS 10

/*
 * Used for deciphering  unknown types when passing to COM. Note
 * any or all of these may be NULL.
 */
static struct TwapiTclTypeMap {
    char *typename;
    Tcl_ObjType *typeptr;
} gTclTypes[TWAPI_TCLTYPE_BOUND];

/*
 * TwapiOpaque is a Tcl "type" whose internal representation is stored
 * as the pointer value and an associated C pointer/handle type.
 * The Tcl_Obj.internalRep.twoPtrValue.ptr1 holds the C pointer value
 * andTcl_Obj.internalRep.twoPtrValue.ptr2 holds a Tcl_Obj describing







|
|







59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#define TWAPI_MAX_SAFEARRAY_DIMS 10

/*
 * Used for deciphering  unknown types when passing to COM. Note
 * any or all of these may be NULL.
 */
static struct TwapiTclTypeMap {
    const char *typename;
    const Tcl_ObjType *typeptr;
} gTclTypes[TWAPI_TCLTYPE_BOUND];

/*
 * TwapiOpaque is a Tcl "type" whose internal representation is stored
 * as the pointer value and an associated C pointer/handle type.
 * The Tcl_Obj.internalRep.twoPtrValue.ptr1 holds the C pointer value
 * andTcl_Obj.internalRep.twoPtrValue.ptr2 holds a Tcl_Obj describing
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    ObjDecrRefs(listObj);
}

static void FreeOpaqueType(Tcl_Obj *objP)
{
    if (OPAQUE_REP_CTYPE(objP))
        ObjDecrRefs(OPAQUE_REP_CTYPE(objP));
    OPAQUE_REP_VALUE_ASSIGN(objP) = NULL;
    OPAQUE_REP_CTYPE_ASSIGN(objP) = NULL;
    objP->typePtr = NULL;
}

static void DupOpaqueType(Tcl_Obj *srcP, Tcl_Obj *dstP)
{
    dstP->typePtr = &gOpaqueType;
    OPAQUE_REP_VALUE_ASSIGN(dstP) = OPAQUE_REP_VALUE(srcP);
    OPAQUE_REP_CTYPE_ASSIGN(dstP) = OPAQUE_REP_CTYPE(srcP);
    if (OPAQUE_REP_CTYPE(dstP))
        ObjIncrRefs(OPAQUE_REP_CTYPE(dstP));
}

TCL_RESULT SetOpaqueFromAny(Tcl_Interp *interp, Tcl_Obj *objP)
{
    Tcl_Obj **objs;







|
|






|
|







175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    ObjDecrRefs(listObj);
}

static void FreeOpaqueType(Tcl_Obj *objP)
{
    if (OPAQUE_REP_CTYPE(objP))
        ObjDecrRefs(OPAQUE_REP_CTYPE(objP));
    OPAQUE_REP_VALUE_SET(objP) = NULL;
    OPAQUE_REP_CTYPE_SET(objP) = NULL;
    objP->typePtr = NULL;
}

static void DupOpaqueType(Tcl_Obj *srcP, Tcl_Obj *dstP)
{
    dstP->typePtr = &gOpaqueType;
    OPAQUE_REP_VALUE_SET(dstP) = OPAQUE_REP_VALUE(srcP);
    OPAQUE_REP_CTYPE_SET(dstP) = OPAQUE_REP_CTYPE(srcP);
    if (OPAQUE_REP_CTYPE(dstP))
        ObjIncrRefs(OPAQUE_REP_CTYPE(dstP));
}

TCL_RESULT SetOpaqueFromAny(Tcl_Interp *interp, Tcl_Obj *objP)
{
    Tcl_Obj **objs;
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    }

    /* OK, valid opaque rep. Convert the passed object's internal rep */
    if (objP->typePtr && objP->typePtr->freeIntRepProc) {
        objP->typePtr->freeIntRepProc(objP);
    }
    objP->typePtr = &gOpaqueType;
    OPAQUE_REP_VALUE_ASSIGN(objP) = pv;
    OPAQUE_REP_CTYPE_ASSIGN(objP) = ctype;
    return TCL_OK;

invalid_value: /* s must point to value */
    if (interp)
        Tcl_AppendResult(interp, "Invalid pointer or opaque value '",
                         s, "'.", NULL);
    return TCL_ERROR;







|
|







234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    }

    /* OK, valid opaque rep. Convert the passed object's internal rep */
    if (objP->typePtr && objP->typePtr->freeIntRepProc) {
        objP->typePtr->freeIntRepProc(objP);
    }
    objP->typePtr = &gOpaqueType;
    OPAQUE_REP_VALUE_SET(objP) = pv;
    OPAQUE_REP_CTYPE_SET(objP) = ctype;
    return TCL_OK;

invalid_value: /* s must point to value */
    if (interp)
        Tcl_AppendResult(interp, "Invalid pointer or opaque value '",
                         s, "'.", NULL);
    return TCL_ERROR;
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
int Twapi_GetTclTypeObjCmd(
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[]
)
{
    ObjToUnicodeCleanup();

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (objv[1]->typePtr) {
        if (objv[1]->typePtr == &gVariantType) {
            const char *typename;
            if (LookupBaseVT(NULL, (VARTYPE) VARIANT_REP_VT(objv[1]), &typename) == TCL_OK &&







<
<







335
336
337
338
339
340
341


342
343
344
345
346
347
348
int Twapi_GetTclTypeObjCmd(
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[]
)
{


    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (objv[1]->typePtr) {
        if (objv[1]->typePtr == &gVariantType) {
            const char *typename;
            if (LookupBaseVT(NULL, (VARTYPE) VARIANT_REP_VT(objv[1]), &typename) == TCL_OK &&
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[]
)
{
    Tcl_Obj *objP = NULL;
    Tcl_ObjType *typeP;
    const char *typename;
    int i;
    VARTYPE vt;

    ObjToUnicodeCleanup();

    if (objc != 3)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    /* NOTE
     * ALWAYS DUP/CREATE NEW object and do not convert it in place.
     * This reduces the chances of it shimmering back to a different
     * type. An example test case is illustrated in test







|




<
<







361
362
363
364
365
366
367
368
369
370
371
372


373
374
375
376
377
378
379
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[]
)
{
    Tcl_Obj *objP = NULL;
    const Tcl_ObjType *typeP;
    const char *typename;
    int i;
    VARTYPE vt;



    if (objc != 3)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    /* NOTE
     * ALWAYS DUP/CREATE NEW object and do not convert it in place.
     * This reduces the chances of it shimmering back to a different
     * type. An example test case is illustrated in test
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
     * even a registered type in Tcl.
     *
     * We can't do anything about wideInt because Tcl_NewWideIntObj,
     * and SetWideIntFromAny, will also return an
     * int Tcl_Obj if the value fits in the 32 bits.
     */
    if (STREQ(typename, "int")) {
        long lval;
        if (ObjToInt(interp, objv[2], &lval) == TCL_ERROR)
            return TCL_ERROR;
        return ObjSetResult(interp, ObjFromInt(lval));
    }

    if (STREQ(typename, "double")) {
        double dval;
        if (ObjToDouble(interp, objv[2], &dval) == TCL_ERROR)
            return TCL_ERROR;
        return ObjSetResult(interp, ObjFromDouble(dval));







|
|

|







407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
     * even a registered type in Tcl.
     *
     * We can't do anything about wideInt because Tcl_NewWideIntObj,
     * and SetWideIntFromAny, will also return an
     * int Tcl_Obj if the value fits in the 32 bits.
     */
    if (STREQ(typename, "int")) {
        int ival;
        if (ObjToInt(interp, objv[2], &ival) == TCL_ERROR)
            return TCL_ERROR;
        return ObjSetResult(interp, ObjFromInt(ival));
    }

    if (STREQ(typename, "double")) {
        double dval;
        if (ObjToDouble(interp, objv[2], &dval) == TCL_ERROR)
            return TCL_ERROR;
        return ObjSetResult(interp, ObjFromDouble(dval));
440
441
442
443
444
445
446

447
448
449
450
451
452
453
454
    objP = NULL;
    typeP = Tcl_GetObjType(typename);
    if (typeP) {
        objP = ObjDuplicate(objv[2]);
        if (objP->typePtr != typeP) {
            if (typeP->setFromAnyProc == NULL)
                goto convert_error;

            if (Tcl_ConvertToType(interp, objP, typeP) == TCL_ERROR) {
                goto error_handler;
            }
        }
    } else {
        /* Not a registered Tcl type. See if one of ours */
        if (LookupBaseVTToken(NULL, typename, &vt) == TCL_OK) {
            switch (vt) {







>
|







436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    objP = NULL;
    typeP = Tcl_GetObjType(typename);
    if (typeP) {
        objP = ObjDuplicate(objv[2]);
        if (objP->typePtr != typeP) {
            if (typeP->setFromAnyProc == NULL)
                goto convert_error;
            /* Cast needed as incomplete const qualifiers in Tcl 8.5 headers*/
            if (Tcl_ConvertToType(interp, objP, (Tcl_ObjType *) typeP) == TCL_ERROR) {
                goto error_handler;
            }
        }
    } else {
        /* Not a registered Tcl type. See if one of ours */
        if (LookupBaseVTToken(NULL, typename, &vt) == TCL_OK) {
            switch (vt) {
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
        /* Other values are to be returned */
        resultObj = ObjFromLong(resultP->value.ival);
        break;

    case TRT_UNICODE_DYNAMIC:
    case TRT_UNICODE:
        if (resultP->value.unicode.str) {
            resultObj = ObjFromUnicodeN(resultP->value.unicode.str,
                                        resultP->value.unicode.len);
        }
        break;

    case TRT_CHARS_DYNAMIC:
    case TRT_CHARS:
        if (resultP->value.chars.str)







|







556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
        /* Other values are to be returned */
        resultObj = ObjFromLong(resultP->value.ival);
        break;

    case TRT_UNICODE_DYNAMIC:
    case TRT_UNICODE:
        if (resultP->value.unicode.str) {
            resultObj = ObjFromWinCharsN(resultP->value.unicode.str,
                                        resultP->value.unicode.len);
        }
        break;

    case TRT_CHARS_DYNAMIC:
    case TRT_CHARS:
        if (resultP->value.chars.str)
668
669
670
671
672
673
674




675
676
677
678
679
680
681
682
683
684
        default:
            ObjSetStaticResult(interp, "Internal error: TwapiSetResult - inconsistent nesting of case statements");
            return TCL_ERROR;
        }
        resultObj = ObjFromOpaque(resultP->value.hval, typenameP);
        break;





    case TRT_LONG:
        resultObj = ObjFromLong(resultP->value.ival);
        break;

    case TRT_DWORD:
        resultObj = ObjFromWideInt((Tcl_WideInt) resultP->value.uval);
        break;
        
    case TRT_WIDE:
        resultObj = ObjFromWideInt(resultP->value.wide);







>
>
>
>

|








665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
        default:
            ObjSetStaticResult(interp, "Internal error: TwapiSetResult - inconsistent nesting of case statements");
            return TCL_ERROR;
        }
        resultObj = ObjFromOpaque(resultP->value.hval, typenameP);
        break;

    case TRT_INT:
        resultObj = ObjFromLong(resultP->value.ival);
        break;
        
    case TRT_LONG:
        resultObj = ObjFromLong(resultP->value.lval);
        break;

    case TRT_DWORD:
        resultObj = ObjFromWideInt((Tcl_WideInt) resultP->value.uval);
        break;
        
    case TRT_WIDE:
        resultObj = ObjFromWideInt(resultP->value.wide);
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

    case TRT_VARIANT:
        resultObj = ObjFromVARIANT(&resultP->value.var, 0);
        break;

    case TRT_LPOLESTR:
        if (resultP->value.lpolestr) {
            resultObj = ObjFromUnicode(resultP->value.lpolestr);
        } else
            Tcl_ResetResult(interp);
        break;

    case TRT_PIDL:
        if (resultP->value.pidl) {
            resultObj = ObjFromPIDL(resultP->value.pidl);







|







723
724
725
726
727
728
729
730
731
732
733
734
735
736
737

    case TRT_VARIANT:
        resultObj = ObjFromVARIANT(&resultP->value.var, 0);
        break;

    case TRT_LPOLESTR:
        if (resultP->value.lpolestr) {
            resultObj = ObjFromWinChars(resultP->value.lpolestr);
        } else
            Tcl_ResetResult(interp);
        break;

    case TRT_PIDL:
        if (resultP->value.pidl) {
            resultObj = ObjFromPIDL(resultP->value.pidl);
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
    case TRT_TWAPI_ERROR:
        if (resultP->value.ival != TWAPI_NO_ERROR)
            return TwapiReturnError(interp, resultP->value.ival);
        break;

    case TRT_CONFIGRET:
        if (resultP->value.ival != 0) {
            ObjSetResult(interp, Tcl_ObjPrintf("PnP Manager returned error code %ld", resultP->value.ival));
            return TCL_ERROR;
        }
        break;

    case TRT_GETLASTERROR_SETUPAPI:
        dw = GetLastError();
        return Twapi_AppendSystemError(interp, HRESULT_FROM_SETUPAPI(dw));







|







765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    case TRT_TWAPI_ERROR:
        if (resultP->value.ival != TWAPI_NO_ERROR)
            return TwapiReturnError(interp, resultP->value.ival);
        break;

    case TRT_CONFIGRET:
        if (resultP->value.ival != 0) {
            ObjSetResult(interp, Tcl_ObjPrintf("PnP Manager returned error code %d", resultP->value.ival));
            return TCL_ERROR;
        }
        break;

    case TRT_GETLASTERROR_SETUPAPI:
        dw = GetLastError();
        return Twapi_AppendSystemError(interp, HRESULT_FROM_SETUPAPI(dw));
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
    return resultObj;
}

TWAPI_EXTERN LPWSTR ObjToLPWSTR_NULL_IF_EMPTY(Tcl_Obj *objP)
{
    if (objP) {
        int len;
        LPWSTR p = ObjToUnicodeN(objP, &len);
        if (len > 0)
            return p;
    }
    return NULL;
}

TWAPI_EXTERN LPWSTR ObjToLPWSTR_WITH_NULL(Tcl_Obj *objP)
{
    if (objP) {
        LPWSTR s = ObjToUnicode(objP);
        if (lstrcmpW(s, NULL_TOKEN_L) == 0) {
            s = NULL;
        }
        return s;
    }
    return NULL;
}

// Return SysAllocStringLen-allocated string
TWAPI_EXTERN int ObjToBSTR(Tcl_Interp *interp, Tcl_Obj *objP, BSTR *bstrP)
{
    int len;
    WCHAR *wcharP;

    if (objP == NULL) {
        wcharP = L"";
        len = 0;
    } else {
        wcharP = ObjToUnicodeN(objP, &len);
    }
    if (bstrP) {
        *bstrP = SysAllocStringLen(wcharP, len);
        return TCL_OK;
    } else {
        return Twapi_AppendSystemError(interp, E_OUTOFMEMORY);
    }
}

TWAPI_EXTERN Tcl_Obj *ObjFromBSTR (BSTR bstr)
{
    return bstr ?
        ObjFromUnicodeN(bstr, SysStringLen(bstr))
        : ObjFromEmptyString();
}

TWAPI_EXTERN Tcl_Obj *ObjFromStringLimited(const char *strP, int max, int *remainP)
{
    const char *p, *endP;








|









|


















|












|







854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
    return resultObj;
}

TWAPI_EXTERN LPWSTR ObjToLPWSTR_NULL_IF_EMPTY(Tcl_Obj *objP)
{
    if (objP) {
        int len;
        LPWSTR p = ObjToWinCharsN(objP, &len);
        if (len > 0)
            return p;
    }
    return NULL;
}

TWAPI_EXTERN LPWSTR ObjToLPWSTR_WITH_NULL(Tcl_Obj *objP)
{
    if (objP) {
        LPWSTR s = ObjToWinChars(objP);
        if (lstrcmpW(s, NULL_TOKEN_L) == 0) {
            s = NULL;
        }
        return s;
    }
    return NULL;
}

// Return SysAllocStringLen-allocated string
TWAPI_EXTERN int ObjToBSTR(Tcl_Interp *interp, Tcl_Obj *objP, BSTR *bstrP)
{
    int len;
    WCHAR *wcharP;

    if (objP == NULL) {
        wcharP = L"";
        len = 0;
    } else {
        wcharP = ObjToWinCharsN(objP, &len);
    }
    if (bstrP) {
        *bstrP = SysAllocStringLen(wcharP, len);
        return TCL_OK;
    } else {
        return Twapi_AppendSystemError(interp, E_OUTOFMEMORY);
    }
}

TWAPI_EXTERN Tcl_Obj *ObjFromBSTR (BSTR bstr)
{
    return bstr ?
        ObjFromWinCharsN(bstr, SysStringLen(bstr))
        : ObjFromEmptyString();
}

TWAPI_EXTERN Tcl_Obj *ObjFromStringLimited(const char *strP, int max, int *remainP)
{
    const char *p, *endP;

924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
        else
            *remainP = (int) (endP-p)-1; /* -1 to skip over \0 */
    }

    return ObjFromStringN(strP, (int) (p-strP));
}

TWAPI_EXTERN Tcl_Obj *ObjFromUnicodeLimited(const WCHAR *strP, int max, int *remainP)
{
    const WCHAR *p, *endP;

    if (max < 0) {
        if (remainP)
            *remainP = 0;
        return ObjFromUnicode(strP);
    }        

    p = strP;
    endP = max + strP;
    while (p < endP && *p)
        ++p;

    if (remainP) {
        if (p == endP)
            *remainP = 0;
        else
            *remainP = (int) (endP-p)-1; /* -1 to skip over \0 */
    }

    return ObjFromUnicodeN(strP, (int) (p-strP));
}

/* Some Win32 APIs, ETW in particular return strings with a trailing space.
   Return a Tcl_Obj without this single trailing space if present */
TWAPI_EXTERN Tcl_Obj *ObjFromUnicodeNoTrailingSpace(const WCHAR *strP)
{
    int len;

    len = lstrlenW(strP);
    if (len && strP[len-1] == L' ')
        --len;
    return ObjFromUnicodeN(strP, len);
}

/*
 * Gets an integer from an object within the specified range
 * Returns TCL_OK if integer within range [low,high], else error
 */
TWAPI_EXTERN int ObjToRangedInt(Tcl_Interp *interp, Tcl_Obj *obj, int low, int high, int *iP)







|






|














|




|






|







925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
        else
            *remainP = (int) (endP-p)-1; /* -1 to skip over \0 */
    }

    return ObjFromStringN(strP, (int) (p-strP));
}

TWAPI_EXTERN Tcl_Obj *ObjFromWinCharsLimited(const WCHAR *strP, int max, int *remainP)
{
    const WCHAR *p, *endP;

    if (max < 0) {
        if (remainP)
            *remainP = 0;
        return ObjFromWinChars(strP);
    }        

    p = strP;
    endP = max + strP;
    while (p < endP && *p)
        ++p;

    if (remainP) {
        if (p == endP)
            *remainP = 0;
        else
            *remainP = (int) (endP-p)-1; /* -1 to skip over \0 */
    }

    return ObjFromWinCharsN(strP, (int) (p-strP));
}

/* Some Win32 APIs, ETW in particular return strings with a trailing space.
   Return a Tcl_Obj without this single trailing space if present */
TWAPI_EXTERN Tcl_Obj *ObjFromWinCharsNoTrailingSpace(const WCHAR *strP)
{
    int len;

    len = lstrlenW(strP);
    if (len && strP[len-1] == L' ')
        --len;
    return ObjFromWinCharsN(strP, len);
}

/*
 * Gets an integer from an object within the specified range
 * Returns TCL_OK if integer within range [low,high], else error
 */
TWAPI_EXTERN int ObjToRangedInt(Tcl_Interp *interp, Tcl_Obj *obj, int low, int high, int *iP)
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
TWAPI_EXTERN int ObjToDECIMAL(Tcl_Interp *interp, Tcl_Obj *obj, DECIMAL *decP)
{
    HRESULT hr;
    DECIMAL dec;

    if (decP == NULL)
        decP = &dec;
    hr = VarDecFromStr(ObjToUnicode(obj), 0, 0, decP);
    if (FAILED(hr)) {
        if (interp)
            Twapi_AppendSystemError(interp, hr);
        return TCL_ERROR;
    }
    return TCL_OK;
}

TWAPI_EXTERN Tcl_Obj *ObjFromPIDL(LPCITEMIDLIST pidl)
{
    /* Scan until we find an item with length 0 */
    unsigned char *p = (char *) pidl;
    do {
        /* p[1,0] is length of this item */
        int len = 256*p[1] + p[0];
        if (len == 0)
            break;              /* 0 length -> end of list */

        p += len;







|











|







1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
TWAPI_EXTERN int ObjToDECIMAL(Tcl_Interp *interp, Tcl_Obj *obj, DECIMAL *decP)
{
    HRESULT hr;
    DECIMAL dec;

    if (decP == NULL)
        decP = &dec;
    hr = VarDecFromStr(ObjToWinChars(obj), 0, 0, decP);
    if (FAILED(hr)) {
        if (interp)
            Twapi_AppendSystemError(interp, hr);
        return TCL_ERROR;
    }
    return TCL_OK;
}

TWAPI_EXTERN Tcl_Obj *ObjFromPIDL(LPCITEMIDLIST pidl)
{
    /* Scan until we find an item with length 0 */
    unsigned char *p = (unsigned char *) pidl;
    do {
        /* p[1,0] is length of this item */
        int len = 256*p[1] + p[0];
        if (len == 0)
            break;              /* 0 length -> end of list */

        p += len;
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
    wchar_t  str[40];
    Tcl_Obj *obj;


    if (guidP == NULL || StringFromGUID2(guidP, str, sizeof(str)/sizeof(str[0])) == 0)
        return ObjFromEmptyString("", 0);

    obj = ObjFromUnicode(str);
    return obj;
}

TWAPI_EXTERN int ObjToGUID(Tcl_Interp *interp, Tcl_Obj *objP, GUID *guidP)
{
    HRESULT hr;
    WCHAR *wsP;
    if (objP) {
        wsP = ObjToUnicode(objP);

        /* Accept both GUID and UUID forms */
        if (*wsP == L'{') {
            /* GUID form */
            /* We *used* to use CLSIDFromString but it turns out that 
               accepts Prog IDs as valid GUIDs as well */
            if ((hr = IIDFromString(wsP, guidP)) != NOERROR) {







|








|







1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
    wchar_t  str[40];
    Tcl_Obj *obj;


    if (guidP == NULL || StringFromGUID2(guidP, str, sizeof(str)/sizeof(str[0])) == 0)
        return ObjFromEmptyString("", 0);

    obj = ObjFromWinChars(str);
    return obj;
}

TWAPI_EXTERN int ObjToGUID(Tcl_Interp *interp, Tcl_Obj *objP, GUID *guidP)
{
    HRESULT hr;
    WCHAR *wsP;
    if (objP) {
        wsP = ObjToWinChars(objP);

        /* Accept both GUID and UUID forms */
        if (*wsP == L'{') {
            /* GUID form */
            /* We *used* to use CLSIDFromString but it turns out that 
               accepts Prog IDs as valid GUIDs as well */
            if ((hr = IIDFromString(wsP, guidP)) != NOERROR) {
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
    unsigned char *uuidStr;
    Tcl_Obj       *objP;
    if (UuidToStringA(uuidP, &uuidStr) != RPC_S_OK)
        return NULL;

    /* NOTE UUID and GUID have same binary format but are formatted
       differently based on the component. */
    objP = ObjFromString(uuidStr);
    RpcStringFree(&uuidStr);
    return objP;
}

TWAPI_EXTERN int ObjToUUID(Tcl_Interp *interp, Tcl_Obj *objP, UUID *uuidP)
{
    /* NOTE UUID and GUID have same binary format but are formatted
       differently based on the component.  We accept both forms here */

    if (objP) {
        RPC_STATUS status = UuidFromStringA(ObjToString(objP), uuidP);
        if (status != RPC_S_OK) {
            /* Try as GUID form */
            return ObjToGUID(interp, objP, uuidP);
        }
    } else {
        ZeroMemory(uuidP, sizeof(*uuidP));
    }







|










|







1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
    unsigned char *uuidStr;
    Tcl_Obj       *objP;
    if (UuidToStringA(uuidP, &uuidStr) != RPC_S_OK)
        return NULL;

    /* NOTE UUID and GUID have same binary format but are formatted
       differently based on the component. */
    objP = ObjFromString((char *)uuidStr);
    RpcStringFree(&uuidStr);
    return objP;
}

TWAPI_EXTERN int ObjToUUID(Tcl_Interp *interp, Tcl_Obj *objP, UUID *uuidP)
{
    /* NOTE UUID and GUID have same binary format but are formatted
       differently based on the component.  We accept both forms here */

    if (objP) {
        RPC_STATUS status = UuidFromStringA((unsigned char *)ObjToString(objP), uuidP);
        if (status != RPC_S_OK) {
            /* Try as GUID form */
            return ObjToGUID(interp, objP, uuidP);
        }
    } else {
        ZeroMemory(uuidP, sizeof(*uuidP));
    }
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
    } else 
        return ObjToUUID(interp, objP, *uuidPP);
}

TWAPI_EXTERN Tcl_Obj *ObjFromLSA_UNICODE_STRING(const LSA_UNICODE_STRING *lsauniP)
{
    /* Note LSA_UNICODE_STRING Length field is in *bytes* NOT characters */
    return ObjFromUnicodeN(lsauniP->Buffer, lsauniP->Length / sizeof(WCHAR));
}

TWAPI_EXTERN void ObjToLSA_UNICODE_STRING(Tcl_Obj *objP, LSA_UNICODE_STRING *lsauniP)
{
    int nchars;
    lsauniP->Buffer = ObjToUnicodeN(objP, &nchars);
    lsauniP->Length = (USHORT) (sizeof(WCHAR)*nchars); /* in bytes */
    lsauniP->MaximumLength = lsauniP->Length;
}


/* interp may be NULL */
TWAPI_EXTERN TCL_RESULT ObjFromSID (Tcl_Interp *interp, SID *sidP, Tcl_Obj **objPP)







|





|







1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
    } else 
        return ObjToUUID(interp, objP, *uuidPP);
}

TWAPI_EXTERN Tcl_Obj *ObjFromLSA_UNICODE_STRING(const LSA_UNICODE_STRING *lsauniP)
{
    /* Note LSA_UNICODE_STRING Length field is in *bytes* NOT characters */
    return ObjFromWinCharsN(lsauniP->Buffer, lsauniP->Length / sizeof(WCHAR));
}

TWAPI_EXTERN void ObjToLSA_UNICODE_STRING(Tcl_Obj *objP, LSA_UNICODE_STRING *lsauniP)
{
    int nchars;
    lsauniP->Buffer = ObjToWinCharsN(objP, &nchars);
    lsauniP->Length = (USHORT) (sizeof(WCHAR)*nchars); /* in bytes */
    lsauniP->MaximumLength = lsauniP->Length;
}


/* interp may be NULL */
TWAPI_EXTERN TCL_RESULT ObjFromSID (Tcl_Interp *interp, SID *sidP, Tcl_Obj **objPP)
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
        return ObjFromEmptyString();
    else
        return objP;
}


/*
 * Convert a Tcl list to a "MULTI_SZ" list of Unicode strings, terminated
 * with two nulls.  Pointer to memlifo alloced multi_sz is stored
 * in *multiszPtrPtr on success. Note that
 * memory may or may not have been allocated from pool even when error
 * is returned and must be freed.
 */
TWAPI_EXTERN TCL_RESULT ObjToMultiSzEx (
     Tcl_Interp *interp,







|







1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
        return ObjFromEmptyString();
    else
        return objP;
}


/*
 * Convert a Tcl list to a "MULTI_SZ" list of LPWSTR strings, terminated
 * with two nulls.  Pointer to memlifo alloced multi_sz is stored
 * in *multiszPtrPtr on success. Note that
 * memory may or may not have been allocated from pool even when error
 * is returned and must be freed.
 */
TWAPI_EXTERN TCL_RESULT ObjToMultiSzEx (
     Tcl_Interp *interp,
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
    buf = MemLifoAlloc(lifoP, len*sizeof(*buf), NULL);

    for (i=0, dst=buf; ; ++i) {
        if (ObjListIndex(interp, listPtr, i, &objPtr) == TCL_ERROR)
            return TCL_ERROR;
        if (objPtr == NULL)
            break;              /* No more items */
        src = ObjToUnicodeN(objPtr, &len);
        if (src) {
            ++len;               /* Include the terminating null */
            CopyMemory(dst, src, len*sizeof(*src));
            dst += len;
        }
    }

    /* Add the final terminating null */
    *dst = 0;

    *multiszPtrPtr = buf;
    return TCL_OK;
}

/*
 * Convert a "MULTI_SZ" list of Unicode strings, terminated with two nulls to
 * a Tcl list. For example, a list of three strings - "abc", "def" and
 * "hij" would look like 'abc\0def\0hij\0\0'. This function will create
 * a list Tcl_Obj and return it. Will return NULL on error.
 *
 * maxlen is provided because registry data can be badly formatted
 * by applications. So we optionally ensure we do not read beyond
 * maxlen characters. This also lets it be used from EvtFormatMessage







|















|







1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
    buf = MemLifoAlloc(lifoP, len*sizeof(*buf), NULL);

    for (i=0, dst=buf; ; ++i) {
        if (ObjListIndex(interp, listPtr, i, &objPtr) == TCL_ERROR)
            return TCL_ERROR;
        if (objPtr == NULL)
            break;              /* No more items */
        src = ObjToWinCharsN(objPtr, &len);
        if (src) {
            ++len;               /* Include the terminating null */
            CopyMemory(dst, src, len*sizeof(*src));
            dst += len;
        }
    }

    /* Add the final terminating null */
    *dst = 0;

    *multiszPtrPtr = buf;
    return TCL_OK;
}

/*
 * Convert a "MULTI_SZ" list of WCHAR strings, terminated with two nulls to
 * a Tcl list. For example, a list of three strings - "abc", "def" and
 * "hij" would look like 'abc\0def\0hij\0\0'. This function will create
 * a list Tcl_Obj and return it. Will return NULL on error.
 *
 * maxlen is provided because registry data can be badly formatted
 * by applications. So we optionally ensure we do not read beyond
 * maxlen characters. This also lets it be used from EvtFormatMessage
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
        while ((lpcw - start) < maxlen && *lpcw)
            ++lpcw;
        if (s == lpcw) {
            /* Zero-length string - end of multi-sz */
            break;
        }

        ObjAppendElement(NULL, listPtr, ObjFromUnicodeN(s, (int) (lpcw-s)));
        ++lpcw;            /* Point beyond this string, possibly beyond end */
    }

    return listPtr;
}

TWAPI_EXTERN TCL_RESULT ObjToUCHAR(Tcl_Interp *interp, Tcl_Obj *obj, UCHAR *ucP)







|







1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
        while ((lpcw - start) < maxlen && *lpcw)
            ++lpcw;
        if (s == lpcw) {
            /* Zero-length string - end of multi-sz */
            break;
        }

        ObjAppendElement(NULL, listPtr, ObjFromWinCharsN(s, (int) (lpcw-s)));
        ++lpcw;            /* Point beyond this string, possibly beyond end */
    }

    return listPtr;
}

TWAPI_EXTERN TCL_RESULT ObjToUCHAR(Tcl_Interp *interp, Tcl_Obj *obj, UCHAR *ucP)
1582
1583
1584
1585
1586
1587
1588


1589
1590
1591
1592
1593
1594
1595
1596

    return ObjNewList(2, objv);
}


TWAPI_EXTERN Tcl_Obj *ObjFromLUID (const LUID *luidP)
{


    return Tcl_ObjPrintf("%.8x-%.8x", luidP->HighPart, luidP->LowPart);
}

/*
 * Convert a string LUID to a LUID structure. Returns luidP on success,
 * else NULL on failure (invalid string format). interp may be NULL
 */
TWAPI_EXTERN int ObjToLUID(Tcl_Interp *interp, Tcl_Obj *objP, LUID *luidP)







>
>
|







1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599

    return ObjNewList(2, objv);
}


TWAPI_EXTERN Tcl_Obj *ObjFromLUID (const LUID *luidP)
{
    /* (unsigned int) casts to keep gcc happy. Else whines about signed LONG
       being associated with %x */
    return Tcl_ObjPrintf("%.8x-%.8x", (unsigned int) luidP->HighPart, (unsigned int) luidP->LowPart);
}

/*
 * Convert a string LUID to a LUID structure. Returns luidP on success,
 * else NULL on failure (invalid string format). interp may be NULL
 */
TWAPI_EXTERN int ObjToLUID(Tcl_Interp *interp, Tcl_Obj *objP, LUID *luidP)
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
    if (required > sz) {
        // Need a bigger buffer
        bufP = SWSPushFrame(required*sizeof(WCHAR), NULL);
        sz = required;
        required = ExpandEnvironmentStringsW(ws, bufP, sz);
    }
    if (required <= 0 || required > sz)
        objP = ObjFromUnicode(ws); /* Something went wrong, return as is */
    else {
        --required;         /* Terminating null */
        objP = ObjFromUnicodeN(bufP, required);
    }

    if (bufP != buf)
        SWSPopFrame();
    return objP;
}








|


|







1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
    if (required > sz) {
        // Need a bigger buffer
        bufP = SWSPushFrame(required*sizeof(WCHAR), NULL);
        sz = required;
        required = ExpandEnvironmentStringsW(ws, bufP, sz);
    }
    if (required <= 0 || required > sz)
        objP = ObjFromWinChars(ws); /* Something went wrong, return as is */
    else {
        --required;         /* Terminating null */
        objP = ObjFromWinCharsN(bufP, required);
    }

    if (bufP != buf)
        SWSPopFrame();
    return objP;
}

1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
        if (typestr == NULL)
            typestr = "expand_sz";
        /*
         * As per MS docs, may not always be null terminated.
         * If it is, we need to strip off the null.
         */
        ws = (WCHAR *)bufP;
        count /= 2;             /*  Assumed to be Unicode. */
        if (count && ws[count-1] == 0)
            --count;        /* Do not include \0 */
        objv[1] = ObjFromUnicodeN(ws, count);
        break;
            
    case REG_DWORD_BIG_ENDIAN:
        /* Since we are returning *typed* values, do not byte swap */
        /* FALLTHRU */
    case REG_DWORD:
        if (count != 4)







|


|







1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
        if (typestr == NULL)
            typestr = "expand_sz";
        /*
         * As per MS docs, may not always be null terminated.
         * If it is, we need to strip off the null.
         */
        ws = (WCHAR *)bufP;
        count /= 2;             /*  Assumed to be WCHAR. */
        if (count && ws[count-1] == 0)
            --count;        /* Do not include \0 */
        objv[1] = ObjFromWinCharsN(ws, count);
        break;
            
    case REG_DWORD_BIG_ENDIAN:
        /* Since we are returning *typed* values, do not byte swap */
        /* FALLTHRU */
    case REG_DWORD:
        if (count != 4)
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
    case REG_SZ:
    case REG_EXPAND_SZ:
        /*
         * As per MS docs, may not always be null terminated.
         * If it is, we need to strip off the null.
         */
        ws = (WCHAR *)bufP;
        count /= 2;             /*  Assumed to be Unicode. */
        if (count && ws[count-1] == 0) {
            terminated = 1;
            --count;        /* Do not include \0 */
        }
        if (regtype != REG_EXPAND_SZ || count == 0)
            return ObjFromUnicodeN(ws, count);
        else {
            /* Expand expects null terminated */
            if (terminated)
                return ObjFromEXPAND_SZW(ws);
            else {
                Tcl_Obj *objP;
                WCHAR *ws2 = SWSPushFrame(sizeof(WCHAR)*(count+1), NULL);







|





|







1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
    case REG_SZ:
    case REG_EXPAND_SZ:
        /*
         * As per MS docs, may not always be null terminated.
         * If it is, we need to strip off the null.
         */
        ws = (WCHAR *)bufP;
        count /= 2;             /*  Assumed to be WCHAR. */
        if (count && ws[count-1] == 0) {
            terminated = 1;
            --count;        /* Do not include \0 */
        }
        if (regtype != REG_EXPAND_SZ || count == 0)
            return ObjFromWinCharsN(ws, count);
        else {
            /* Expand expects null terminated */
            if (terminated)
                return ObjFromEXPAND_SZW(ws);
            else {
                Tcl_Obj *objP;
                WCHAR *ws2 = SWSPushFrame(sizeof(WCHAR)*(count+1), NULL);
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
    if ((objc+1) > argc) {
        return TwapiReturnErrorEx(interp,
                                  TWAPI_INTERNAL_LIMIT,
                                  Tcl_ObjPrintf("Number of strings (%d) in list exceeds size of argument array (%d).", objc, argc-1));
    }

    for (i = 0; i < objc; ++i)
        argv[i] = ObjToUnicode(objv[i]);
    argv[i] = NULL;
    *argcP = objc;
    return TCL_OK;
}

TWAPI_EXTERN LPWSTR *ObjToMemLifoArgvW(TwapiInterpContext *ticP, Tcl_Obj *objP, int *argcP)
{
    int       j, objc;
    Tcl_Obj **objv;
    LPWSTR *argv;

    if (ObjGetElements(ticP->interp, objP, &objc, &objv) != TCL_OK)
        return NULL;

    argv = MemLifoAlloc(ticP->memlifoP, (objc+1) * sizeof(LPCWSTR), NULL);
    for (j = 0; j < objc; ++j) {
        WCHAR *s;
        int slen;
        s = ObjToUnicodeN(objv[j], &slen);
        argv[j] = MemLifoCopy(ticP->memlifoP, s, sizeof(WCHAR)*(slen+1));
    }
    argv[j] = NULL;
    *argcP = objc;
    return argv;
}

TWAPI_EXTERN Tcl_Obj *ObjFromOpaque(void *pv, char *name)
{
    Tcl_Obj *objP;

    objP = Tcl_NewObj();
    Tcl_InvalidateStringRep(objP);
    OPAQUE_REP_VALUE_ASSIGN(objP) = pv;
    if (name) {
        OPAQUE_REP_CTYPE_ASSIGN(objP) = ObjFromString(name);
        ObjIncrRefs(OPAQUE_REP_CTYPE(objP));
    } else {
        OPAQUE_REP_CTYPE_ASSIGN(objP) = NULL;
    }        
    objP->typePtr = &gOpaqueType;
    return objP;
}

TWAPI_EXTERN TCL_RESULT ObjToOpaque(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name)
{







|


















|













|

|


|







1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
    if ((objc+1) > argc) {
        return TwapiReturnErrorEx(interp,
                                  TWAPI_INTERNAL_LIMIT,
                                  Tcl_ObjPrintf("Number of strings (%d) in list exceeds size of argument array (%d).", objc, argc-1));
    }

    for (i = 0; i < objc; ++i)
        argv[i] = ObjToWinChars(objv[i]);
    argv[i] = NULL;
    *argcP = objc;
    return TCL_OK;
}

TWAPI_EXTERN LPWSTR *ObjToMemLifoArgvW(TwapiInterpContext *ticP, Tcl_Obj *objP, int *argcP)
{
    int       j, objc;
    Tcl_Obj **objv;
    LPWSTR *argv;

    if (ObjGetElements(ticP->interp, objP, &objc, &objv) != TCL_OK)
        return NULL;

    argv = MemLifoAlloc(ticP->memlifoP, (objc+1) * sizeof(LPCWSTR), NULL);
    for (j = 0; j < objc; ++j) {
        WCHAR *s;
        int slen;
        s = ObjToWinCharsN(objv[j], &slen);
        argv[j] = MemLifoCopy(ticP->memlifoP, s, sizeof(WCHAR)*(slen+1));
    }
    argv[j] = NULL;
    *argcP = objc;
    return argv;
}

TWAPI_EXTERN Tcl_Obj *ObjFromOpaque(void *pv, char *name)
{
    Tcl_Obj *objP;

    objP = Tcl_NewObj();
    Tcl_InvalidateStringRep(objP);
    OPAQUE_REP_VALUE_SET(objP) = pv;
    if (name) {
        OPAQUE_REP_CTYPE_SET(objP) = ObjFromString(name);
        ObjIncrRefs(OPAQUE_REP_CTYPE(objP));
    } else {
        OPAQUE_REP_CTYPE_SET(objP) = NULL;
    }        
    objP->typePtr = &gOpaqueType;
    return objP;
}

TWAPI_EXTERN TCL_RESULT ObjToOpaque(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name)
{
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerOrNull(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name, void *verifier)
{
    TwapiInterpContext *ticP = TwapiGetBaseContext(interp);
    TWAPI_ASSERT(ticP);
    return ObjToVerifiedPointerOrNullTic(ticP, objP, pvP, name, verifier);
}

TWAPI_EXTERN int ObjToIDispatch(Tcl_Interp *interp, Tcl_Obj *obj, void **dP)
{
    IDispatch **dispP = (IDispatch **) dP;

    /*
     * Either IDispatchEx or IDispatch is acceptable. We try in that
     * order so error message, if any will refer to IDispatch.
     */
    if (ObjToOpaque(NULL, obj, dispP, "IDispatchEx") == TCL_OK)
        return TCL_OK;
    return ObjToOpaque(interp, obj, dispP, "IDispatch");







|

<
<







1982
1983
1984
1985
1986
1987
1988
1989
1990


1991
1992
1993
1994
1995
1996
1997
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerOrNull(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name, void *verifier)
{
    TwapiInterpContext *ticP = TwapiGetBaseContext(interp);
    TWAPI_ASSERT(ticP);
    return ObjToVerifiedPointerOrNullTic(ticP, objP, pvP, name, verifier);
}

TWAPI_EXTERN int ObjToIDispatch(Tcl_Interp *interp, Tcl_Obj *obj, void **dispP)
{


    /*
     * Either IDispatchEx or IDispatch is acceptable. We try in that
     * order so error message, if any will refer to IDispatch.
     */
    if (ObjToOpaque(NULL, obj, dispP, "IDispatchEx") == TCL_OK)
        return TCL_OK;
    return ObjToOpaque(interp, obj, dispP, "IDispatch");
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
   only if the wsP[nchars] was a null. If nchars was passed as a negative
   number, the terminating null is implicitly included in the length and will
   be present in the returned buffer as well.

   On error returns -1. Detail about error should be retrieved with
   GetLastError()
*/
TWAPI_EXTERN int TwapiWCHARToUtf8(CONST WCHAR *wsP, int nchars, char *buf, int buf_sz)
{
    int nbytes;
    
    if (buf_sz < 1)
        buf = NULL;
    else if (buf == NULL)
        buf_sz = 0;







|







2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
   only if the wsP[nchars] was a null. If nchars was passed as a negative
   number, the terminating null is implicitly included in the length and will
   be present in the returned buffer as well.

   On error returns -1. Detail about error should be retrieved with
   GetLastError()
*/
TWAPI_EXTERN int TwapiWinCharsToUtf8(CONST WCHAR *wsP, int nchars, char *buf, int buf_sz)
{
    int nbytes;
    
    if (buf_sz < 1)
        buf = NULL;
    else if (buf == NULL)
        buf_sz = 0;
2050
2051
2052
2053
2054
2055
2056
2057



2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
    
    if (nbytes == 0)
        return -1; /* Caller should use GetLastError() */

    return nbytes;
}

/* The Unicode string should not contain embedded nulls */



TWAPI_EXTERN Tcl_Obj *TwapiUtf8ObjFromUnicode(CONST WCHAR *wsP, int nchars)
{
    int nbytes;
    char *p;
    Tcl_Obj *objP;
    
    nbytes = TwapiWCHARToUtf8(wsP, nchars, NULL, 0);
    if (nbytes == -1)
        goto do_panic;
    
    p = ckalloc(nbytes+1); /* +1 for case where WCTMB doesn't terminate \0 */ 
    nbytes = TwapiWCHARToUtf8(wsP, nchars, p, nbytes);
    if (nbytes == -1)
        goto do_panic;

    if (nbytes == 0)
        p[0] = '\0';
    else if (p[nbytes-1] == '\0')
        nbytes -= 1; /* Don't include terminating null */
    else
        p[nbytes] = '\0'; /* Terminate string */
    
    objP = Tcl_NewObj();
    if (objP->bytes)
        Tcl_InvalidateStringRep(objP);
    objP->bytes = p;
    objP->length = nbytes; /* Note length does not include terminating \0 */

    return objP;

do_panic:
    Tcl_Panic("TwapiWCHARToUtf8 returned -1, with error code %d", GetLastError());
    return NULL; /* To keep compiler happy. Never reaches here */
}

TWAPI_EXTERN Tcl_Obj *ObjFromTIME_ZONE_INFORMATION(const TIME_ZONE_INFORMATION *tzP)
{
    Tcl_Obj *objs[7];

    objs[0] = ObjFromLong(tzP->Bias);
    objs[1] = ObjFromUnicodeLimited(tzP->StandardName, ARRAYSIZE(tzP->StandardName), NULL);
    objs[2] = ObjFromSYSTEMTIME(&tzP->StandardDate);
    objs[3] = ObjFromLong(tzP->StandardBias);
    objs[4] = ObjFromUnicodeLimited(tzP->DaylightName, ARRAYSIZE(tzP->DaylightName), NULL);
    objs[5] = ObjFromSYSTEMTIME(&tzP->DaylightDate);
    objs[6] = ObjFromLong(tzP->DaylightBias);
    return ObjNewList(7, objs);
}

TWAPI_EXTERN TCL_RESULT ObjToTIME_ZONE_INFORMATION(Tcl_Interp *interp,
                                      Tcl_Obj *tzObj,







|
>
>
>
|





|




|



















|








|


|







2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
    
    if (nbytes == 0)
        return -1; /* Caller should use GetLastError() */

    return nbytes;
}

/* The WCHAR string should not contain embedded nulls */
/* TBD - where is this called from? Can it have embedded nulls? Maybe
   if TwapiUnicharToUtf8 returns error, use Tcl for conversion instead
   of panicing ? */
TWAPI_EXTERN Tcl_Obj *TwapiUtf8ObjFromWinChars(CONST WCHAR *wsP, int nchars)
{
    int nbytes;
    char *p;
    Tcl_Obj *objP;
    
    nbytes = TwapiWinCharsToUtf8(wsP, nchars, NULL, 0);
    if (nbytes == -1)
        goto do_panic;
    
    p = ckalloc(nbytes+1); /* +1 for case where WCTMB doesn't terminate \0 */ 
    nbytes = TwapiWinCharsToUtf8(wsP, nchars, p, nbytes);
    if (nbytes == -1)
        goto do_panic;

    if (nbytes == 0)
        p[0] = '\0';
    else if (p[nbytes-1] == '\0')
        nbytes -= 1; /* Don't include terminating null */
    else
        p[nbytes] = '\0'; /* Terminate string */
    
    objP = Tcl_NewObj();
    if (objP->bytes)
        Tcl_InvalidateStringRep(objP);
    objP->bytes = p;
    objP->length = nbytes; /* Note length does not include terminating \0 */

    return objP;

do_panic:
    Tcl_Panic("TwapiWinCharsToUtf8 returned -1, with error code %lu", GetLastError());
    return NULL; /* To keep compiler happy. Never reaches here */
}

TWAPI_EXTERN Tcl_Obj *ObjFromTIME_ZONE_INFORMATION(const TIME_ZONE_INFORMATION *tzP)
{
    Tcl_Obj *objs[7];

    objs[0] = ObjFromLong(tzP->Bias);
    objs[1] = ObjFromWinCharsLimited(tzP->StandardName, ARRAYSIZE(tzP->StandardName), NULL);
    objs[2] = ObjFromSYSTEMTIME(&tzP->StandardDate);
    objs[3] = ObjFromLong(tzP->StandardBias);
    objs[4] = ObjFromWinCharsLimited(tzP->DaylightName, ARRAYSIZE(tzP->DaylightName), NULL);
    objs[5] = ObjFromSYSTEMTIME(&tzP->DaylightDate);
    objs[6] = ObjFromLong(tzP->DaylightBias);
    return ObjNewList(7, objs);
}

TWAPI_EXTERN TCL_RESULT ObjToTIME_ZONE_INFORMATION(Tcl_Interp *interp,
                                      Tcl_Obj *tzObj,
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
        TwapiGetArgs(interp, nobjs, objPP,
                     GETINT(tzP->Bias),
                     GETOBJ(stdObj), GETVAR(tzP->StandardDate, ObjToSYSTEMTIME), GETINT(tzP->StandardBias),
                     GETOBJ(daylightObj), GETVAR(tzP->DaylightDate, ObjToSYSTEMTIME), GETINT(tzP->DaylightBias),
                     ARGEND) == TCL_OK) {
        WCHAR *std_name, *daylight_name;
        int std_len, daylight_len;
        std_name = ObjToUnicodeN(stdObj, &std_len);
        daylight_name = ObjToUnicodeN(daylightObj, &daylight_len);
        /* Remember we need a terminating \0 */
        if (std_len < ARRAYSIZE(tzP->StandardName) &&
            daylight_len < ARRAYSIZE(tzP->DaylightName)) {
            wcscpy(tzP->StandardName, std_name);
            wcscpy(tzP->DaylightName, daylight_name);
            return TCL_OK;
        }







|
|







2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
        TwapiGetArgs(interp, nobjs, objPP,
                     GETINT(tzP->Bias),
                     GETOBJ(stdObj), GETVAR(tzP->StandardDate, ObjToSYSTEMTIME), GETINT(tzP->StandardBias),
                     GETOBJ(daylightObj), GETVAR(tzP->DaylightDate, ObjToSYSTEMTIME), GETINT(tzP->DaylightBias),
                     ARGEND) == TCL_OK) {
        WCHAR *std_name, *daylight_name;
        int std_len, daylight_len;
        std_name = ObjToWinCharsN(stdObj, &std_len);
        daylight_name = ObjToWinCharsN(daylightObj, &daylight_len);
        /* Remember we need a terminating \0 */
        if (std_len < ARRAYSIZE(tzP->StandardName) &&
            daylight_len < ARRAYSIZE(tzP->DaylightName)) {
            wcscpy(tzP->StandardName, std_name);
            wcscpy(tzP->DaylightName, daylight_name);
            return TCL_OK;
        }
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
    }

    return ObjNewList(2, objv);
}


/* Can return NULL */
TWAPI_EXTERN Tcl_Obj *ObjFromIPv6Addr(const char *addrP, DWORD scope_id)
{
    SOCKADDR_IN6 si;

    si.sin6_family = AF_INET6;
    si.sin6_port = 0;
    si.sin6_flowinfo = 0;
    CopyMemory(si.sin6_addr.u.Byte, addrP, 16);







|







2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
    }

    return ObjNewList(2, objv);
}


/* Can return NULL */
TWAPI_EXTERN Tcl_Obj *ObjFromIPv6Addr(const BYTE *addrP, DWORD scope_id)
{
    SOCKADDR_IN6 si;

    si.sin6_family = AF_INET6;
    si.sin6_port = 0;
    si.sin6_flowinfo = 0;
    CopyMemory(si.sin6_addr.u.Byte, addrP, 16);
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
{
    VARTYPE vt = *vtP;
    int i, ndim, cur_dim;
    Tcl_Obj *objP;
    void *valP;
    SAFEARRAY *saP = NULL;
    SAFEARRAYBOUND bounds[TWAPI_MAX_SAFEARRAY_DIMS];
    unsigned long indices[TWAPI_MAX_SAFEARRAY_DIMS];
    Tcl_Obj *objs[TWAPI_MAX_SAFEARRAY_DIMS];
    HRESULT hr;
    int tcltype;

    TWAPI_ASSERT(vt & VT_ARRAY);
    vt &= ~ VT_ARRAY;








|







2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
{
    VARTYPE vt = *vtP;
    int i, ndim, cur_dim;
    Tcl_Obj *objP;
    void *valP;
    SAFEARRAY *saP = NULL;
    SAFEARRAYBOUND bounds[TWAPI_MAX_SAFEARRAY_DIMS];
    LONG indices[TWAPI_MAX_SAFEARRAY_DIMS];
    Tcl_Obj *objs[TWAPI_MAX_SAFEARRAY_DIMS];
    HRESULT hr;
    int tcltype;

    TWAPI_ASSERT(vt & VT_ARRAY);
    vt &= ~ VT_ARRAY;

2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
        /*
         * Now increment indices[] to point to next entry. We increment
         * the index for each dimension and if it exceeds the number of
         * elements in that dimension, we reset its index to 0 and 
         * carry over and increment the previous dimension.
         */
        for (cur_dim = ndim-1; cur_dim >= 0; --cur_dim) {
            if (++indices[cur_dim] < bounds[cur_dim].cElements)
                break;          /* No overflow for this dimension */
            indices[cur_dim] = 0;
        }

        /*
         * The above loop terminates when
         *  cur_dim < 0 - implies even the outermost dimension elements have







|







2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
        /*
         * Now increment indices[] to point to next entry. We increment
         * the index for each dimension and if it exceeds the number of
         * elements in that dimension, we reset its index to 0 and 
         * carry over and increment the previous dimension.
         */
        for (cur_dim = ndim-1; cur_dim >= 0; --cur_dim) {
            if (++indices[cur_dim] < (LONG) bounds[cur_dim].cElements)
                break;          /* No overflow for this dimension */
            indices[cur_dim] = 0;
        }

        /*
         * The above loop terminates when
         *  cur_dim < 0 - implies even the outermost dimension elements have
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
 * Returns NULL on any errors.
 *
 * IMPORTANT: saP must be SafeArrayLock'ed on entry !
 */
static Tcl_Obj *ObjFromSAFEARRAYDimension(SAFEARRAY *saP, int dim,
                                          long indices[], int indices_size)
{
    unsigned long i;
    Tcl_Obj *objP;
    Tcl_Obj *resultObj = NULL;
    VARIANT *variantP;
    unsigned long upper, lower;
    VARTYPE vt;
    
    if (indices_size < saP-> cDims)
        return NULL;            /* Not supported as exceed max dimensions */

    if (indices_size <= dim)
        return NULL;            /* Should not happen really - internal error */







|



|







2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
 * Returns NULL on any errors.
 *
 * IMPORTANT: saP must be SafeArrayLock'ed on entry !
 */
static Tcl_Obj *ObjFromSAFEARRAYDimension(SAFEARRAY *saP, int dim,
                                          long indices[], int indices_size)
{
    LONG i;
    Tcl_Obj *objP;
    Tcl_Obj *resultObj = NULL;
    VARIANT *variantP;
    LONG upper, lower;
    VARTYPE vt;
    
    if (indices_size < saP-> cDims)
        return NULL;            /* Not supported as exceed max dimensions */

    if (indices_size <= dim)
        return NULL;            /* Should not happen really - internal error */
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
            case VT_INT: /* FALLTHROUGH */
            case VT_I4: objP = ObjFromLong(*(long *)valP); break;
            case VT_R4: objP = Tcl_NewDoubleObj(*(float *)valP); break;
            case VT_R8: objP = Tcl_NewDoubleObj(*(double *)valP); break;
            case VT_CY: objP = ObjFromCY((CY *) valP); break;
            case VT_DATE: objP = Tcl_NewDoubleObj(*(double *)valP); break;
            case VT_BSTR:
                objP = ObjFromUnicodeN(*(BSTR *)valP, SysStringLen(*(BSTR *)valP));
                break;
            case VT_DISPATCH:
                /* AddRef as it will be Release'd when safearray is freed */
                if (*(IDispatch **)valP)
                    (*(IDispatch **)valP)->lpVtbl->AddRef(*(IDispatch **)valP);
                objP = ObjFromIDispatch(*(IDispatch **)valP);
                break;







|







2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
            case VT_INT: /* FALLTHROUGH */
            case VT_I4: objP = ObjFromLong(*(long *)valP); break;
            case VT_R4: objP = Tcl_NewDoubleObj(*(float *)valP); break;
            case VT_R8: objP = Tcl_NewDoubleObj(*(double *)valP); break;
            case VT_CY: objP = ObjFromCY((CY *) valP); break;
            case VT_DATE: objP = Tcl_NewDoubleObj(*(double *)valP); break;
            case VT_BSTR:
                objP = ObjFromWinCharsN(*(BSTR *)valP, SysStringLen(*(BSTR *)valP));
                break;
            case VT_DISPATCH:
                /* AddRef as it will be Release'd when safearray is freed */
                if (*(IDispatch **)valP)
                    (*(IDispatch **)valP)->lpVtbl->AddRef(*(IDispatch **)valP);
                objP = ObjFromIDispatch(*(IDispatch **)valP);
                break;
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
                    }
                }
                break;
            case TWAPI_TCLTYPE_INT:
                vt = VT_I4;
                for (i = 1; i < nobjs; ++ i) {
                    int ival;
                    if (ObjToLong(NULL, objs[i], &ival) != TCL_OK) {
                        vt = VT_VARIANT;
                        break;
                    }
                }
                break;
            case TWAPI_TCLTYPE_WIDEINT:
                vt = VT_I8;







|







2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
                    }
                }
                break;
            case TWAPI_TCLTYPE_INT:
                vt = VT_I4;
                for (i = 1; i < nobjs; ++ i) {
                    int ival;
                    if (ObjToInt(NULL, objs[i], &ival) != TCL_OK) {
                        vt = VT_VARIANT;
                        break;
                    }
                }
                break;
            case TWAPI_TCLTYPE_WIDEINT:
                vt = VT_I8;
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087

    /* For compatibility reasons, allow interchangeable signed/unsigned ints */
    case VT_I4:
    case VT_UI4:
    case VT_INT:
    case VT_UINT:
    case VT_HRESULT:
        res = ObjToInt(interp, objP, &lval);
        if (res == TCL_OK) {
            switch (vt) {
            case VT_I4:
            case VT_INT:
            case VT_HRESULT:
                vt = VT_I4;        /* VT_INT and VT_HRESULT cannot be marshalled */
                V_I4(varP) = lval;







|







3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091

    /* For compatibility reasons, allow interchangeable signed/unsigned ints */
    case VT_I4:
    case VT_UI4:
    case VT_INT:
    case VT_UINT:
    case VT_HRESULT:
        res = ObjToLong(interp, objP, &lval);
        if (res == TCL_OK) {
            switch (vt) {
            case VT_I4:
            case VT_INT:
            case VT_HRESULT:
                vt = VT_I4;        /* VT_INT and VT_HRESULT cannot be marshalled */
                V_I4(varP) = lval;
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
         * from Tcl_Obj.typePtr should have been considered by the caller.
         */
        res = TCL_OK;
        if (ObjToLong(NULL, objP, &varP->lVal) == TCL_OK) {
            vt = VT_I4;
        } else if (ObjToDouble(NULL, objP, &varP->dblVal) == TCL_OK) {
            vt = VT_R8;
        } else if (ObjToIDispatch(NULL, objP, &varP->pdispVal) == TCL_OK) {
            vt = VT_DISPATCH;
        } else if (ObjToIUnknown(NULL, objP, &varP->punkVal) == TCL_OK) {
            vt = VT_UNKNOWN;
#if 0
        } else if (ObjCharLength(objP) == 0) {
            vt = VT_NULL;
#endif
        } else {
            /* Cannot guess type, just pass as a BSTR */







|

|







3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
         * from Tcl_Obj.typePtr should have been considered by the caller.
         */
        res = TCL_OK;
        if (ObjToLong(NULL, objP, &varP->lVal) == TCL_OK) {
            vt = VT_I4;
        } else if (ObjToDouble(NULL, objP, &varP->dblVal) == TCL_OK) {
            vt = VT_R8;
        } else if (ObjToIDispatch(NULL, objP, (void **)&varP->pdispVal) == TCL_OK) {
            vt = VT_DISPATCH;
        } else if (ObjToIUnknown(NULL, objP, (void **)&varP->punkVal) == TCL_OK) {
            vt = VT_UNKNOWN;
#if 0
        } else if (ObjCharLength(objP) == 0) {
            vt = VT_NULL;
#endif
        } else {
            /* Cannot guess type, just pass as a BSTR */
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
            V_VT(varP) == VT_CY ? & V_CY(varP) : V_CYREF(varP)
            );
        break;

    case VT_BSTR|VT_BYREF:
    case VT_BSTR:
        if (V_VT(varP) == VT_BSTR)
            objv[1] = ObjFromUnicodeN(V_BSTR(varP),
                                        SysStringLen(V_BSTR(varP)));
        else
            objv[1] = ObjFromUnicodeN(* V_BSTRREF(varP),
                                        SysStringLen(* V_BSTRREF(varP)));
        break;

    case VT_DISPATCH|VT_BYREF:
        /* If VT_BYREF is set, then a reference to an existing
         * IUnknown is being returned. In this case, at the script level
         * we should not Release it but there is no way for the script







|


|







3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
            V_VT(varP) == VT_CY ? & V_CY(varP) : V_CYREF(varP)
            );
        break;

    case VT_BSTR|VT_BYREF:
    case VT_BSTR:
        if (V_VT(varP) == VT_BSTR)
            objv[1] = ObjFromWinCharsN(V_BSTR(varP),
                                        SysStringLen(V_BSTR(varP)));
        else
            objv[1] = ObjFromWinCharsN(* V_BSTRREF(varP),
                                        SysStringLen(* V_BSTRREF(varP)));
        break;

    case VT_DISPATCH|VT_BYREF:
        /* If VT_BYREF is set, then a reference to an existing
         * IUnknown is being returned. In this case, at the script level
         * we should not Release it but there is no way for the script
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
    /* Allocate the array of structures */
    sz = nitems * sizeof(LSA_UNICODE_STRING);
    ustrP = MemLifoAlloc(memlifoP, sz, NULL);
    
    for (i = 0; i < nitems; ++i) {
        WCHAR *srcP;
        int    slen;
        srcP = ObjToUnicodeN(listobjv[i], &slen);
        if (slen >= (USHRT_MAX/sizeof(WCHAR))) {
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "LSA_UNICODE_STRING length must be less than 32767.");
        }
        slen *= sizeof(WCHAR); /* # bytes */
        ustrP[i].Buffer = MemLifoCopy(memlifoP, srcP, slen+sizeof(WCHAR));
        ustrP[i].Length = (USHORT) slen; /* Num *bytes*, not WCHARs */
        ustrP[i].MaximumLength = ustrP[i].Length;







|







3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
    /* Allocate the array of structures */
    sz = nitems * sizeof(LSA_UNICODE_STRING);
    ustrP = MemLifoAlloc(memlifoP, sz, NULL);
    
    for (i = 0; i < nitems; ++i) {
        WCHAR *srcP;
        int    slen;
        srcP = ObjToWinCharsN(listobjv[i], &slen);
        if (slen >= (USHRT_MAX/sizeof(WCHAR))) {
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "LSA_UNICODE_STRING length must be less than 32767.");
        }
        slen *= sizeof(WCHAR); /* # bytes */
        ustrP[i].Buffer = MemLifoCopy(memlifoP, srcP, slen+sizeof(WCHAR));
        ustrP[i].Length = (USHORT) slen; /* Num *bytes*, not WCHARs */
        ustrP[i].MaximumLength = ustrP[i].Length;
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
   or a list of ints. If the object is an empty string, error returned.
   Else the SID is allocated  on the SWS and a pointer to it is
   stored in *sidPP. Caller responsible for SWS memory on success
   and failure.
*/
TWAPI_EXTERN TCL_RESULT ObjToPSIDNonNullSWS(Tcl_Interp *interp, Tcl_Obj *obj, PSID *sidPP)
{
    DWORD   len;
    SID  *sidP;
    DWORD winerror;

    *sidPP = TwapiSidFromStringSWS(ObjToString(obj));
    if (*sidPP)
        return TCL_OK;

    winerror = GetLastError();

    /* Not a string rep. See if it is a binary of the right size */
    sidP = (SID *) ObjToByteArray(obj, &len);
    if (len >= sizeof(*sidP)) {
        /* Seems big enough, validate revision and size */
        if (IsValidSid(sidP) && GetLengthSid(sidP) == len) {
            *sidPP = SWSAlloc(len, NULL);
            /* Note SID is a variable length struct so we cannot do this
                    *(SID *) (*sidPP) = *sidP;
               (from bitter experience!)
             */
            if (CopySid(len, *sidPP, sidP))
                return TCL_OK;
            winerror = GetLastError();
        }
    }
    return Twapi_AppendSystemError(interp, winerror);
}

/* Tcl_Obj to SID - the object may hold the SID string rep, a binary
   or a list of ints. If the object is an empty string, *sidPP is
   stored as NULL. Else the SID is allocated on the SWS and a pointer to it is
   stored in *sidPP. Caller responsible for all SWS management.
*/
TWAPI_EXTERN TCL_RESULT ObjToPSIDSWS(Tcl_Interp *interp, Tcl_Obj *obj, PSID *sidPP)
{
    char *s;
    DWORD   len;

    s = ObjToStringN(obj, &len);
    if (len == 0) {
        *sidPP = NULL;
        return TCL_OK;
    }

    return ObjToPSIDNonNullSWS(interp, obj, sidPP);
}







|













|




















<
|

|







3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564

3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
   or a list of ints. If the object is an empty string, error returned.
   Else the SID is allocated  on the SWS and a pointer to it is
   stored in *sidPP. Caller responsible for SWS memory on success
   and failure.
*/
TWAPI_EXTERN TCL_RESULT ObjToPSIDNonNullSWS(Tcl_Interp *interp, Tcl_Obj *obj, PSID *sidPP)
{
    int   len;
    SID  *sidP;
    DWORD winerror;

    *sidPP = TwapiSidFromStringSWS(ObjToString(obj));
    if (*sidPP)
        return TCL_OK;

    winerror = GetLastError();

    /* Not a string rep. See if it is a binary of the right size */
    sidP = (SID *) ObjToByteArray(obj, &len);
    if (len >= sizeof(*sidP)) {
        /* Seems big enough, validate revision and size */
        if (IsValidSid(sidP) && GetLengthSid(sidP) == (DWORD) len) {
            *sidPP = SWSAlloc(len, NULL);
            /* Note SID is a variable length struct so we cannot do this
                    *(SID *) (*sidPP) = *sidP;
               (from bitter experience!)
             */
            if (CopySid(len, *sidPP, sidP))
                return TCL_OK;
            winerror = GetLastError();
        }
    }
    return Twapi_AppendSystemError(interp, winerror);
}

/* Tcl_Obj to SID - the object may hold the SID string rep, a binary
   or a list of ints. If the object is an empty string, *sidPP is
   stored as NULL. Else the SID is allocated on the SWS and a pointer to it is
   stored in *sidPP. Caller responsible for all SWS management.
*/
TWAPI_EXTERN TCL_RESULT ObjToPSIDSWS(Tcl_Interp *interp, Tcl_Obj *obj, PSID *sidPP)
{

    int   len;

    (void) ObjToStringN(obj, &len);
    if (len == 0) {
        *sidPP = NULL;
        return TCL_OK;
    }

    return ObjToPSIDNonNullSWS(interp, obj, sidPP);
}
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
            goto format_error;
        acesz += sizeof(*aceP);
        aceP = (ACCESS_ALLOWED_ACE *) SWSAlloc(acesz, NULL);
        aceP->Header.AceType = acetype;
        aceP->Header.AceFlags = aceflags;
        aceP->Header.AceSize  = acesz; /* TBD - this is a upper bound since we
                                          allocated max SID size. Is that OK?*/
        if (ObjToInt(interp, objv[2], &aceP->Mask) != TCL_OK)
            goto format_error;

        sidP = TwapiSidFromStringSWS(ObjToString(objv[3]));
        if (sidP == NULL)
            goto system_error;

        if (! CopySid(aceP->Header.AceSize - sizeof(*aceP) + sizeof(aceP->SidStart),







|







3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
            goto format_error;
        acesz += sizeof(*aceP);
        aceP = (ACCESS_ALLOWED_ACE *) SWSAlloc(acesz, NULL);
        aceP->Header.AceType = acetype;
        aceP->Header.AceFlags = aceflags;
        aceP->Header.AceSize  = acesz; /* TBD - this is a upper bound since we
                                          allocated max SID size. Is that OK?*/
        if (ObjToDWORD(interp, objv[2], &aceP->Mask) != TCL_OK)
            goto format_error;

        sidP = TwapiSidFromStringSWS(ObjToString(objv[3]));
        if (sidP == NULL)
            goto system_error;

        if (! CopySid(aceP->Header.AceSize - sizeof(*aceP) + sizeof(aceP->SidStart),
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
        goto error_return;
    }

    /* Control bits */
    objv[0] = ObjFromInt(secd_control);

    /* Owner SID */
    if (! GetSecurityDescriptorOwner(secdP, &sidP, &defaulted))
        goto system_error;
    if (sidP == NULL)
        objv[1] = ObjFromEmptyString();
    else {
        if (ObjFromSID(interp, sidP, &objv[1]) != TCL_OK)
            goto error_return;
    }

    /* Group SID */
    if (! GetSecurityDescriptorGroup(secdP, &sidP, &defaulted))
        goto system_error;
    if (sidP == NULL)
        objv[2] = ObjFromEmptyString();
    else {
        if (ObjFromSID(interp, sidP, &objv[2]) != TCL_OK)
            goto error_return;
    }







|









|







3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
        goto error_return;
    }

    /* Control bits */
    objv[0] = ObjFromInt(secd_control);

    /* Owner SID */
    if (! GetSecurityDescriptorOwner(secdP, (void **)&sidP, &defaulted))
        goto system_error;
    if (sidP == NULL)
        objv[1] = ObjFromEmptyString();
    else {
        if (ObjFromSID(interp, sidP, &objv[1]) != TCL_OK)
            goto error_return;
    }

    /* Group SID */
    if (! GetSecurityDescriptorGroup(secdP, (void **)&sidP, &defaulted))
        goto system_error;
    if (sidP == NULL)
        objv[2] = ObjFromEmptyString();
    else {
        if (ObjFromSID(interp, sidP, &objv[2]) != TCL_OK)
            goto error_return;
    }
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
    (*secattrPP)->nLength = sizeof(**secattrPP);

    if (ObjToInt(interp, objv[1], &inherit) == TCL_ERROR)
        goto error_return;
    (*secattrPP)->bInheritHandle = (inherit != 0);

    if (ObjToPSECURITY_DESCRIPTORSWS(interp, objv[0],
                                     (SECURITY_DESCRIPTOR *) &(*secattrPP)->lpSecurityDescriptor)
        == TCL_ERROR) {
        goto error_return;
    }

    return TCL_OK;

 error_return:







|







4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
    (*secattrPP)->nLength = sizeof(**secattrPP);

    if (ObjToInt(interp, objv[1], &inherit) == TCL_ERROR)
        goto error_return;
    (*secattrPP)->bInheritHandle = (inherit != 0);

    if (ObjToPSECURITY_DESCRIPTORSWS(interp, objv[0],
                                     (SECURITY_DESCRIPTOR **)&(*secattrPP)->lpSecurityDescriptor)
        == TCL_ERROR) {
        goto error_return;
    }

    return TCL_OK;

 error_return:
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
TWAPI_EXTERN void ObjDecrArrayRefs(int objc, Tcl_Obj *objv[])
{
    int i;
    for (i = 0; i < objc; ++i)
        ObjDecrRefs(objv[i]);
}

#if (TCL_UTF_MAX > 4)
TWAPI_EXTERN void ObjToUnicodeCleanup(void)
{
    TwapiTls *tls = Twapi_GetTls();
    if (tls == NULL)
        return;
    while (tls->dsList != NULL) {
        TwapiDS *tds = tls->dsList;
	tls->dsList = tds->next;
	Tcl_DStringFree(&tds->ds);
        tds->next = tls->dsFree;
        tls->dsFree = tds;
    }
}
#endif

TWAPI_EXTERN WCHAR *ObjToUnicode(Tcl_Obj *objP)
{
#if (TCL_UTF_MAX > 4)
    TwapiTls *tls = Twapi_GetTls();
    int len;
    char *str;
    TwapiDS *tds;
    if (tls == NULL)
        return NULL;
    str = Tcl_GetStringFromObj(objP, &len);
    tds = tls->dsFree;
    if (tds == NULL)
        tds = ckalloc(sizeof (TwapiDS));
    else
        tls->dsFree = tds->next;
    str = Tcl_UtfToExternalDString(tls->enc, str, len, &tds->ds);
    tds->next = tls->dsList;
    tls->dsList = tds;
    return (WCHAR *) str;
#else
    return Tcl_GetUnicode(objP);
#endif
}

TWAPI_EXTERN WCHAR *ObjToUnicodeN(Tcl_Obj *objP, int *lenP)
{
#if (TCL_UTF_MAX > 4)
    TwapiTls *tls = Twapi_GetTls();
    int len;
    char *str;
    TwapiDS *tds;
    if (tls == NULL)
        return NULL;
    str = Tcl_GetStringFromObj(objP, &len);
    tds = tls->dsFree;
    if (tds == NULL)
        tds = ckalloc(sizeof (TwapiDS));
    else
        tls->dsFree = tds->next;
    str = Tcl_UtfToExternalDString(tls->enc, str, len, &tds->ds);
    tds->next = tls->dsList;
    tls->dsList = tds;
    if (lenP != NULL)
        *lenP = Tcl_DStringLength(&tds->ds) / sizeof (WCHAR);
    return (WCHAR *) str;
#else
    return Tcl_GetUnicodeFromObj(objP, lenP);
#endif
}

TWAPI_EXTERN Tcl_Obj *ObjFromUnicodeN(const WCHAR *ws, int len)
{
    if (ws == NULL)
        return ObjFromEmptyString(); /* TBD - log ? */

    return TwapiUtf8ObjFromUnicode(ws, len);
}

TWAPI_EXTERN Tcl_Obj *ObjFromUnicode(const WCHAR *ws)
{
    if (ws == NULL)
        return ObjFromEmptyString(); /* TBD - log ? */

    return TwapiUtf8ObjFromUnicode(ws, -1);
}

TWAPI_EXTERN char *ObjToString(Tcl_Obj *objP)
{
    return Tcl_GetString(objP);
}

TWAPI_EXTERN char *ObjToStringN(Tcl_Obj *objP, int *lenP)
{







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







4192
4193
4194
4195
4196
4197
4198


















































































4199
4200
4201
4202
4203
4204
4205
TWAPI_EXTERN void ObjDecrArrayRefs(int objc, Tcl_Obj *objv[])
{
    int i;
    for (i = 0; i < objc; ++i)
        ObjDecrRefs(objv[i]);
}



















































































TWAPI_EXTERN char *ObjToString(Tcl_Obj *objP)
{
    return Tcl_GetString(objP);
}

TWAPI_EXTERN char *ObjToStringN(Tcl_Obj *objP, int *lenP)
{
4300
4301
4302
4303
4304
4305
4306





4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
}

TWAPI_EXTERN int ObjCharLength(Tcl_Obj *objP)
{
    return Tcl_GetCharLength(objP);
}






TWAPI_EXTERN TCL_RESULT ObjToLong(Tcl_Interp *interp, Tcl_Obj *objP, long *lvalP)
{
    return Tcl_GetLongFromObj(interp, objP, lvalP);
}

TWAPI_EXTERN TCL_RESULT ObjToBoolean(Tcl_Interp *interp, Tcl_Obj *objP, int *valP)
{
    return Tcl_GetBooleanFromObj(interp, objP, valP);
}








>
>
>
>
>
|

|







4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
}

TWAPI_EXTERN int ObjCharLength(Tcl_Obj *objP)
{
    return Tcl_GetCharLength(objP);
}

TWAPI_EXTERN TCL_RESULT ObjToInt(Tcl_Interp *interp, Tcl_Obj *objP, int *valP)
{
    return Tcl_GetIntFromObj(interp, objP, valP);
}

TWAPI_EXTERN TCL_RESULT ObjToLong(Tcl_Interp *interp, Tcl_Obj *objP, long *valP)
{
    return Tcl_GetLongFromObj(interp, objP, valP);
}

TWAPI_EXTERN TCL_RESULT ObjToBoolean(Tcl_Interp *interp, Tcl_Obj *objP, int *valP)
{
    return Tcl_GetBooleanFromObj(interp, objP, valP);
}

4369
4370
4371
4372
4373
4374
4375





4376
4377
4378
4379
4380
4381
4382
    return Tcl_DictObjGet(interp, dictObj, keyObj, valueObjP);
}

TWAPI_EXTERN TCL_RESULT ObjDictPut(Tcl_Interp *interp, Tcl_Obj *dictObj, Tcl_Obj *keyObj, Tcl_Obj *valueObj)
{
    return Tcl_DictObjPut(interp, dictObj, keyObj, valueObj);
}






TWAPI_EXTERN Tcl_Obj *ObjFromLong(long val)
{
    return Tcl_NewLongObj(val);
}

TWAPI_EXTERN Tcl_Obj *ObjFromWideInt(Tcl_WideInt val)







>
>
>
>
>







4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
    return Tcl_DictObjGet(interp, dictObj, keyObj, valueObjP);
}

TWAPI_EXTERN TCL_RESULT ObjDictPut(Tcl_Interp *interp, Tcl_Obj *dictObj, Tcl_Obj *keyObj, Tcl_Obj *valueObj)
{
    return Tcl_DictObjPut(interp, dictObj, keyObj, valueObj);
}

TWAPI_EXTERN Tcl_Obj *ObjFromInt(int val)
{
    return Tcl_NewIntObj(val);
}

TWAPI_EXTERN Tcl_Obj *ObjFromLong(long val)
{
    return Tcl_NewLongObj(val);
}

TWAPI_EXTERN Tcl_Obj *ObjFromWideInt(Tcl_WideInt val)
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
    /* Assumes major version==8 check already made at init time */
    if (bytes != NULL ||
        (gTclVersion.minor == 6 && gTclVersion.reltype == TCL_FINAL_RELEASE) ||
        gTclVersion.minor > 6) {
        return Tcl_NewByteArrayObj(bytes, len);
    } else {
        Tcl_Obj *o;
        o =  Tcl_NewByteArrayObj("", 0);
        Tcl_SetByteArrayLength(o, len);
        return o;
    }
}

TWAPI_EXTERN Tcl_Obj *ObjAllocateByteArray(int len, void **ppv)
{







|







4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
    /* Assumes major version==8 check already made at init time */
    if (bytes != NULL ||
        (gTclVersion.minor == 6 && gTclVersion.reltype == TCL_FINAL_RELEASE) ||
        gTclVersion.minor > 6) {
        return Tcl_NewByteArrayObj(bytes, len);
    } else {
        Tcl_Obj *o;
        o =  Tcl_NewByteArrayObj((unsigned char *)"", 0);
        Tcl_SetByteArrayLength(o, len);
        return o;
    }
}

TWAPI_EXTERN Tcl_Obj *ObjAllocateByteArray(int len, void **ppv)
{
4447
4448
4449
4450
4451
4452
4453








4454
4455
4456
4457
4458
4459
4460
    return resultObj;
}

TWAPI_EXTERN unsigned char *ObjToByteArray(Tcl_Obj *objP, int *lenP)
{
    return Tcl_GetByteArrayFromObj(objP, lenP);
}









/*
 * RtlEncryptMemory (aka SystemFunction040) and
 * RtlDecryptMemory (aka SystemFunction041)
 * The Feb 2003 SDK does not define these in the headers, nor does it
 * include them in the export libs. So we have to dynamically load them
*/







>
>
>
>
>
>
>
>







4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
    return resultObj;
}

TWAPI_EXTERN unsigned char *ObjToByteArray(Tcl_Obj *objP, int *lenP)
{
    return Tcl_GetByteArrayFromObj(objP, lenP);
}

TWAPI_EXTERN unsigned char *ObjToByteArrayDW(Tcl_Obj *objP, DWORD *lenP)
{
    /* This stupid duplication of ObjToByteArray is to avoid
       gcc warning of mixing DWORD* and int* */
    TWAPI_ASSERT(sizeof(DWORD) == sizeof(int));
    return Tcl_GetByteArrayFromObj(objP, (int *)lenP);
}

/*
 * RtlEncryptMemory (aka SystemFunction040) and
 * RtlDecryptMemory (aka SystemFunction041)
 * The Feb 2003 SDK does not define these in the headers, nor does it
 * include them in the export libs. So we have to dynamically load them
*/
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545

4546
4547
4548
4549
4550

4551
4552
4553
4554
4555
4556
4557
TWAPI_EXTERN Tcl_Obj *ObjEncryptBytes(Tcl_Interp *interp, void *pv, int nbytes)
{
    int nenc, nalloc;
    Tcl_Obj *objP = NULL;
    unsigned char *bytes = pv;
    WCHAR *wsP;

    /* Note data is always encrypted in Unicode form */
    
    nalloc = nbytes*sizeof(WCHAR);
    if (nalloc == 0)
        nalloc = sizeof(WCHAR); /* Can't alloc 0 */

    wsP = SWSPushFrame(nalloc, NULL);
    
    for (nenc = 0; nenc < nbytes; ++nenc)
        wsP[nenc] = bytes[nenc];
    objP = ObjEncryptUnicode(interp, wsP, nbytes);

    SWSPopFrame();
    return objP;
}


static TCL_RESULT TwapiDecryptBlockLengthError(Tcl_Interp *interp, int len)
{
    return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                              Tcl_ObjPrintf("Invalid length (%d) of encrypted object. Must be non-zero multiple of block size (%d).", len, RTL_ENCRYPT_MEMORY_SIZE));
}


static TCL_RESULT TwapiDecryptPadLengthError(Tcl_Interp *interp, int pad_len)
{
    return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                       Tcl_ObjPrintf("Invalid pad (%d) in decrypted object. Object corrupted or was not encrypted.", pad_len));
}








|









|





>





>







4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
TWAPI_EXTERN Tcl_Obj *ObjEncryptBytes(Tcl_Interp *interp, void *pv, int nbytes)
{
    int nenc, nalloc;
    Tcl_Obj *objP = NULL;
    unsigned char *bytes = pv;
    WCHAR *wsP;

    /* Note data is always encrypted in WCHAR form */
    
    nalloc = nbytes*sizeof(WCHAR);
    if (nalloc == 0)
        nalloc = sizeof(WCHAR); /* Can't alloc 0 */

    wsP = SWSPushFrame(nalloc, NULL);
    
    for (nenc = 0; nenc < nbytes; ++nenc)
        wsP[nenc] = bytes[nenc];
    objP = ObjEncryptWinChars(interp, wsP, nbytes);

    SWSPopFrame();
    return objP;
}

#ifdef OBSOLETE
static TCL_RESULT TwapiDecryptBlockLengthError(Tcl_Interp *interp, int len)
{
    return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                              Tcl_ObjPrintf("Invalid length (%d) of encrypted object. Must be non-zero multiple of block size (%d).", len, RTL_ENCRYPT_MEMORY_SIZE));
}
#endif

static TCL_RESULT TwapiDecryptPadLengthError(Tcl_Interp *interp, int pad_len)
{
    return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                       Tcl_ObjPrintf("Invalid pad (%d) in decrypted object. Object corrupted or was not encrypted.", pad_len));
}

4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
            *noutP = nout;
            return outP;
        }
    }
    return NULL;
}

/* Encrypts the Unicode string rep to a byte array. We choose Unicode
   as the base format for strings because most API's need Unicode and makes it
   easier to SecureZeroMemory the buffer. 
*/
TWAPI_EXTERN Tcl_Obj *ObjEncryptUnicode(Tcl_Interp *interp, WCHAR *uniP, int nchars)
{
    int nenc;
    Tcl_Obj *objP = NULL;
    TCL_RESULT res;
    
    if (nchars < 0)
        nchars = lstrlenW(uniP);

    res = TwapiEncryptData(interp, (BYTE *) uniP, nchars*sizeof(WCHAR), NULL, &nenc);
    if (res == TCL_OK) {
        unsigned char *encP;
        objP = ObjAllocateByteArray(nenc, &encP);
        res = TwapiEncryptData(interp, (BYTE *) uniP, nchars*sizeof(WCHAR), encP, &nenc);
        if (res == TCL_OK)
            Tcl_SetByteArrayLength(objP, nenc);
        else {
            ObjDecrRefs(objP);
            objP = NULL;
        }
    }
    return objP;
}

/*
 * Decrypts Unicode string in objP to SWS. Caller responsible for
 * SWS storage management and should also zero out the password
 * after use.
 * Returns length of string (in unichars, not bytes) NOT including terminating
 * char in *ncharsP
 */
TWAPI_EXTERN WCHAR * ObjDecryptUnicodeSWS(Tcl_Interp *interp,
                          Tcl_Obj *objP,
                          int *ncharsP /* May be NULL */
    )
{
    int nenc, ndec;
    char *enc, *dec;
    TCL_RESULT res;
    
    enc = ObjToByteArray(objP, &nenc);
    
    res = TwapiDecryptData(interp, enc, nenc, NULL, &ndec);
    if (res != TCL_OK)
        return NULL;

    /* additional WCHAR is for terminating \0 */
    dec = SWSAlloc(ndec+sizeof(WCHAR), NULL);
    
    res = TwapiDecryptData(interp, enc, nenc, dec, &ndec);
    if (res != TCL_OK)
        return NULL;

    ndec /= sizeof(WCHAR);
    *(ndec + (WCHAR*) dec) = 0;             /* Terminate the Unicode string */
    if (ncharsP)
        *ncharsP = ndec;

    return (WCHAR*)dec;
}

/*
 * Decrypts encrypted objP to SWS in UTF8 encoding.
 * Caller responsible for SWS storage management and should also zero out 
 * the plaintext after use.
 * Returns length of string (in bytes) NOT including terminating
 * char in *ncharsP
 */
TWAPI_EXTERN char *ObjDecryptUtf8SWS(Tcl_Interp *interp, Tcl_Obj *objP, int *nbytesP)
{
    WCHAR *uniP;
    char *utfP;
    int nuni, nutf;

    uniP = ObjDecryptUnicodeSWS(interp, objP, &nuni);
    if (uniP == NULL)
        return NULL;
    TWAPI_ASSERT(uniP[nuni] == 0); /* Should be terminated */

    /* REMEMBER we have to zero out uniP beyond this point */
    
    nutf = TwapiWCHARToUtf8(uniP, nuni, NULL, 0);
    if (nutf == -1)
        utfP = NULL;
    else {
        utfP = SWSAlloc(nutf+1, NULL); /* Additional byte for \0 */
        nutf = TwapiWCHARToUtf8(uniP, nuni, utfP, nutf);
        if (nutf == -1)
            utfP = NULL;
         else {
            utfP[nutf] = '\0';
            if (nbytesP)
                *nbytesP = nutf;
        }







|
|


|











|












|

|
|


|





|
















|



















|






|




|







4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
            *noutP = nout;
            return outP;
        }
    }
    return NULL;
}

/* Encrypts the  rep to a byte array. We choose WCHAR strings
   as the base format for strings because most API's need WCHAR and makes it
   easier to SecureZeroMemory the buffer. 
*/
TWAPI_EXTERN Tcl_Obj *ObjEncryptWinChars(Tcl_Interp *interp, WCHAR *uniP, int nchars)
{
    int nenc;
    Tcl_Obj *objP = NULL;
    TCL_RESULT res;
    
    if (nchars < 0)
        nchars = lstrlenW(uniP);

    res = TwapiEncryptData(interp, (BYTE *) uniP, nchars*sizeof(WCHAR), NULL, &nenc);
    if (res == TCL_OK) {
        unsigned char *encP;
        objP = ObjAllocateByteArray(nenc, (void **)&encP);
        res = TwapiEncryptData(interp, (BYTE *) uniP, nchars*sizeof(WCHAR), encP, &nenc);
        if (res == TCL_OK)
            Tcl_SetByteArrayLength(objP, nenc);
        else {
            ObjDecrRefs(objP);
            objP = NULL;
        }
    }
    return objP;
}

/*
 * Decrypts encrypted WCHAR string in objP to SWS. Caller responsible for
 * SWS storage management and should also zero out the password
 * after use. Decrypted string is appended with a terminating \0.
 * Returns length of string (in chars, not bytes) NOT including terminating
 * char in *ncharsP
 */
TWAPI_EXTERN WCHAR * ObjDecryptWinCharsSWS(Tcl_Interp *interp,
                          Tcl_Obj *objP,
                          int *ncharsP /* May be NULL */
    )
{
    int nenc, ndec;
    BYTE *enc, *dec;
    TCL_RESULT res;
    
    enc = ObjToByteArray(objP, &nenc);
    
    res = TwapiDecryptData(interp, enc, nenc, NULL, &ndec);
    if (res != TCL_OK)
        return NULL;

    /* additional WCHAR is for terminating \0 */
    dec = SWSAlloc(ndec+sizeof(WCHAR), NULL);
    
    res = TwapiDecryptData(interp, enc, nenc, dec, &ndec);
    if (res != TCL_OK)
        return NULL;

    ndec /= sizeof(WCHAR);
    *(ndec + (WCHAR*) dec) = 0;             /* Terminate the string */
    if (ncharsP)
        *ncharsP = ndec;

    return (WCHAR*)dec;
}

/*
 * Decrypts encrypted objP to SWS in UTF8 encoding.
 * Caller responsible for SWS storage management and should also zero out 
 * the plaintext after use.
 * Returns length of string (in bytes) NOT including terminating
 * char in *ncharsP
 */
TWAPI_EXTERN char *ObjDecryptUtf8SWS(Tcl_Interp *interp, Tcl_Obj *objP, int *nbytesP)
{
    WCHAR *uniP;
    char *utfP;
    int nuni, nutf;

    uniP = ObjDecryptWinCharsSWS(interp, objP, &nuni);
    if (uniP == NULL)
        return NULL;
    TWAPI_ASSERT(uniP[nuni] == 0); /* Should be terminated */

    /* REMEMBER we have to zero out uniP beyond this point */
    
    nutf = TwapiWinCharsToUtf8(uniP, nuni, NULL, 0);
    if (nutf == -1)
        utfP = NULL;
    else {
        utfP = SWSAlloc(nutf+1, NULL); /* Additional byte for \0 */
        nutf = TwapiWinCharsToUtf8(uniP, nuni, utfP, nutf);
        if (nutf == -1)
            utfP = NULL;
         else {
            utfP[nutf] = '\0';
            if (nbytesP)
                *nbytesP = nutf;
        }
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
 */
TWAPI_EXTERN void *ObjDecryptBytesExSWS(Tcl_Interp *interp, Tcl_Obj *objP, int nleading, int *nbytesP)
{
    WCHAR *uniP, *from, *end;
    unsigned char *p, *to;
    int nuni, nalloc;

    uniP = ObjDecryptUnicodeSWS(interp, objP, &nuni);
    if (uniP == NULL)
        return NULL;

    /* REMEMBER we have to zero out uniP[] beyond this point */

    nalloc = nleading + nuni;
    if (nalloc == 0)







|







4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
 */
TWAPI_EXTERN void *ObjDecryptBytesExSWS(Tcl_Interp *interp, Tcl_Obj *objP, int nleading, int *nbytesP)
{
    WCHAR *uniP, *from, *end;
    unsigned char *p, *to;
    int nuni, nalloc;

    uniP = ObjDecryptWinCharsSWS(interp, objP, &nuni);
    if (uniP == NULL)
        return NULL;

    /* REMEMBER we have to zero out uniP[] beyond this point */

    nalloc = nleading + nuni;
    if (nalloc == 0)
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
    
    if (nbytesP)
        *nbytesP = nuni;
    return p;
}

/*
 * Like ObjDecryptUnicodeSWS but
 * if decryption fails, assumes password in unencrypted form and returns it.
 * Return data is on the SWS.
 * See ObjDecryptUnicodeSWS comments regarding SWS memory management.
 * ncharsP may be NULL
 */
TWAPI_EXTERN WCHAR * ObjDecryptPasswordSWS(Tcl_Obj *objP, int *ncharsP)
{
    WCHAR *uniP, *toP;
    int nchars;

    toP =  ObjDecryptUnicodeSWS(NULL, objP, ncharsP);
    if (toP)
        return toP;
    /* Not encrypted, assume plaintext password */
    uniP = ObjToUnicodeN(objP, &nchars);
    toP = MemLifoCopy(SWS(), uniP, sizeof(WCHAR)*(nchars+1));
    if (ncharsP)
        *ncharsP = nchars;
    return toP;
}

/*







|


|







|



|







4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
    
    if (nbytesP)
        *nbytesP = nuni;
    return p;
}

/*
 * Like ObjDecryptWinCharsSWS but
 * if decryption fails, assumes password in unencrypted form and returns it.
 * Return data is on the SWS.
 * See ObjDecryptWinCharsSWS comments regarding SWS memory management.
 * ncharsP may be NULL
 */
TWAPI_EXTERN WCHAR * ObjDecryptPasswordSWS(Tcl_Obj *objP, int *ncharsP)
{
    WCHAR *uniP, *toP;
    int nchars;

    toP =  ObjDecryptWinCharsSWS(NULL, objP, ncharsP);
    if (toP)
        return toP;
    /* Not encrypted, assume plaintext password */
    uniP = ObjToWinCharsN(objP, &nchars);
    toP = MemLifoCopy(SWS(), uniP, sizeof(WCHAR)*(nchars+1));
    if (ncharsP)
        *ncharsP = nchars;
    return toP;
}

/*
4897
4898
4899
4900
4901
4902
4903

4904
4905
4906
4907
4908
4909
4910
    )
{
    Tcl_Obj *passwordObj;
    Tcl_Obj **objv;
    int objc;
    TCL_RESULT res;
    SEC_WINNT_AUTH_IDENTITY_W *swaiP;

    
    if ((res = ObjGetElements(ticP->interp, authObj, &objc, &objv)) != TCL_OK)
        return res;

    if (objc == 0) {
        *swaiPP = NULL;
        return TCL_OK;







>







4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
    )
{
    Tcl_Obj *passwordObj;
    Tcl_Obj **objv;
    int objc;
    TCL_RESULT res;
    SEC_WINNT_AUTH_IDENTITY_W *swaiP;
    int i;
    
    if ((res = ObjGetElements(ticP->interp, authObj, &objc, &objv)) != TCL_OK)
        return res;

    if (objc == 0) {
        *swaiPP = NULL;
        return TCL_OK;
4920
4921
4922
4923
4924
4925
4926
4927

4928
4929
4930
4931

    if (res != TCL_OK)
        return res;

    /* The decrypted password will be on the SWS which should be the same
       as ticP->memlifoP
    */
    TWAPI_ASSERT(SWS() == ticP->memlifoP);
    swaiP->Password = ObjDecryptPasswordSWS(passwordObj, &swaiP->PasswordLength);


    *swaiPP = swaiP;
    return TCL_OK;
}








|
>




>
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
    if (res != TCL_OK)
        return res;

    /* The decrypted password will be on the SWS which should be the same
       as ticP->memlifoP
    */
    TWAPI_ASSERT(SWS() == ticP->memlifoP);
    swaiP->Password = ObjDecryptPasswordSWS(passwordObj, &i);
    swaiP->PasswordLength = i; /* Using temp i to keep gcc happy */

    *swaiPP = swaiP;
    return TCL_OK;
}

Changes to undroid/twapi/twapi/base/twapi.c.
9
10
11
12
13
14
15

16
17
18
19
20
21
22
#include "twapi_base.h"
#include <ntverp.h>             /* Needed for VER_PRODUCTBUILD SDK version */
#include "tclTomMath.h"

#define TWAPI_TCL_MAJOR 8
#define TWAPI_MIN_TCL_MINOR 5


#ifndef MODULENAME
#define MODULENAME "twapi_base"
#endif

#ifndef MODULEVERSION
#define MODULEVERSION PACKAGE_VERSION
#endif







>







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "twapi_base.h"
#include <ntverp.h>             /* Needed for VER_PRODUCTBUILD SDK version */
#include "tclTomMath.h"

#define TWAPI_TCL_MAJOR 8
#define TWAPI_MIN_TCL_MINOR 5

/* Following two definitions required for MinGW builds */
#ifndef MODULENAME
#define MODULENAME "twapi_base"
#endif

#ifndef MODULEVERSION
#define MODULEVERSION PACKAGE_VERSION
#endif
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
82
83
84
85
 * Globals
 */
OSVERSIONINFOW gTwapiOSVersionInfo;
GUID gTwapiNullGuid;             /* Initialized to all zeroes */
struct TwapiTclVersion gTclVersion;
static int gTclIsThreaded;
static DWORD gTlsIndex = TLS_OUT_OF_INDEXES; /* As returned by TlsAlloc */
static ULONG volatile gTlsNextSlot;  /* Index into private slots in Tls area. */

/* List of allocated interpreter - used primarily for unnotified cleanup */
CRITICAL_SECTION gTwapiInterpContextsCS; /* To protect the same */
ZLIST_DECL(TwapiInterpContext) gTwapiInterpContexts;

/* Used to generate unique id's */
TwapiId volatile gIdGenerator;

/*
 * Whether the callback dll/libray has been initialized.
 * The value must be managed using the InterlockedCompareExchange functions to
 * ensure thread safety. The value returned by InterlockedCompareExhange
 * 0 -> first to call, do init,  1 -> init in progress by some other thread
 * 2 -> Init done
 */
static TwapiOneTimeInitState gTwapiInitialized;

static void TwapiBaseModuleCleanup(TwapiInterpContext *ticP);
static void Twapi_Cleanup(ClientData clientdata);
static void Twapi_InterpCleanup(ClientData clientdata, Tcl_Interp *interp);
static void Twapi_InterpContextCleanup(TwapiInterpContext *ticP, Tcl_Interp *interp);
static TwapiInterpContext *TwapiInterpContextNew(Tcl_Interp *, HMODULE, TwapiModuleDef * );
static void TwapiInterpContextDelete(TwapiInterpContext *ticP);
static TwapiInterpContext *Twapi_AllocateInterpContext(Tcl_Interp *interp, HMODULE hmodule, TwapiModuleDef *);
static int TwapiOneTimeInit(Tcl_Interp *interp);

HMODULE gTwapiModuleHandle;     /* DLL handle to ourselves */
static TwapiModuleDef gBaseModule = {
    MODULENAME,
    Twapi_InitCalls,
    TwapiBaseModuleCleanup,
};







|




















|



|







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
82
83
84
85
86
 * Globals
 */
OSVERSIONINFOW gTwapiOSVersionInfo;
GUID gTwapiNullGuid;             /* Initialized to all zeroes */
struct TwapiTclVersion gTclVersion;
static int gTclIsThreaded;
static DWORD gTlsIndex = TLS_OUT_OF_INDEXES; /* As returned by TlsAlloc */
static LONG volatile gTlsNextSlot;  /* Index into private slots in Tls area. */

/* List of allocated interpreter - used primarily for unnotified cleanup */
CRITICAL_SECTION gTwapiInterpContextsCS; /* To protect the same */
ZLIST_DECL(TwapiInterpContext) gTwapiInterpContexts;

/* Used to generate unique id's */
TwapiId volatile gIdGenerator;

/*
 * Whether the callback dll/libray has been initialized.
 * The value must be managed using the InterlockedCompareExchange functions to
 * ensure thread safety. The value returned by InterlockedCompareExhange
 * 0 -> first to call, do init,  1 -> init in progress by some other thread
 * 2 -> Init done
 */
static TwapiOneTimeInitState gTwapiInitialized;

static void TwapiBaseModuleCleanup(TwapiInterpContext *ticP);
static void Twapi_Cleanup(ClientData clientdata);
static void Twapi_InterpCleanup(ClientData clientdata, Tcl_Interp *interp);
static void Twapi_InterpContextCleanup(void*, Tcl_Interp *interp);
static TwapiInterpContext *TwapiInterpContextNew(Tcl_Interp *, HMODULE, TwapiModuleDef * );
static void TwapiInterpContextDelete(TwapiInterpContext *ticP);
static TwapiInterpContext *Twapi_AllocateInterpContext(Tcl_Interp *interp, HMODULE hmodule, TwapiModuleDef *);
static int TwapiOneTimeInit(void *);

HMODULE gTwapiModuleHandle;     /* DLL handle to ourselves */
static TwapiModuleDef gBaseModule = {
    MODULENAME,
    Twapi_InitCalls,
    TwapiBaseModuleCleanup,
};
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
        TwapiTls *tlsP = TlsGetValue(gTlsIndex);
        if (tlsP) {
            TWAPI_ASSERT(tlsP->nrefs > 0);
            tlsP->nrefs -= 1;
            if (tlsP->nrefs == 0) {
                MemLifoClose(&tlsP->memlifo);
                ObjDecrRefs(tlsP->ffiObj);
#if (TCL_UTF_MAX > 4)
                ObjToUnicodeCleanup();
                while (tlsP->dsFree != NULL) {
                    TwapiDS *tds = tlsP->dsFree;
                    tlsP->dsFree = tds->next;
                    ckfree((char *) tds);
                }
                Tcl_FreeEncoding(tlsP->enc);
#endif
                TwapiFree(tlsP);
                TlsSetValue(gTlsIndex, NULL);
            }
        }
    }
}








<
<
<
<
<
<
<
<
<







106
107
108
109
110
111
112









113
114
115
116
117
118
119
        TwapiTls *tlsP = TlsGetValue(gTlsIndex);
        if (tlsP) {
            TWAPI_ASSERT(tlsP->nrefs > 0);
            tlsP->nrefs -= 1;
            if (tlsP->nrefs == 0) {
                MemLifoClose(&tlsP->memlifo);
                ObjDecrRefs(tlsP->ffiObj);









                TwapiFree(tlsP);
                TlsSetValue(gTlsIndex, NULL);
            }
        }
    }
}

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
        if (MemLifoInit(&tlsP->memlifo, NULL, NULL, NULL, 8000,
                             MEMLIFO_F_PANIC_ON_FAIL) != ERROR_SUCCESS) {
            TwapiFree(tlsP);
            return TCL_ERROR;
        }
        tlsP->ffiObj = ObjNewDict();
        ObjIncrRefs(tlsP->ffiObj);
#if (TCL_UTF_MAX > 4)
        tlsP->enc = Tcl_GetEncoding(NULL, "unicode");
        tlsP->dsFree = NULL;
        tlsP->dsList = NULL;
#endif
    }

    tlsP->nrefs += 1;
    return TCL_OK;
}

int Twapi_AssignTlsSubSlot()







<
<
<
<
<







134
135
136
137
138
139
140





141
142
143
144
145
146
147
        if (MemLifoInit(&tlsP->memlifo, NULL, NULL, NULL, 8000,
                             MEMLIFO_F_PANIC_ON_FAIL) != ERROR_SUCCESS) {
            TwapiFree(tlsP);
            return TCL_ERROR;
        }
        tlsP->ffiObj = ObjNewDict();
        ObjIncrRefs(tlsP->ffiObj);





    }

    tlsP->nrefs += 1;
    return TCL_OK;
}

int Twapi_AssignTlsSubSlot()
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
                    dataP = TwapiLzmaUncompressBuffer(interp, dataP, sz, &sz);
                    if (dataP == NULL)
                        return TCL_ERROR; /* interp already has error */
                }
                
                /* The resource is expected to be UTF-8 (actually strict ASCII) */
                /* TBD - double check use of GLOBAL and DIRECT */
                result = Tcl_EvalEx(interp, dataP, sz, TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
                if (compressed)
                    TwapiLzmaFreeBuffer(dataP);
                if (result == TCL_OK)
                    Tcl_ResetResult(interp);
                return result;
            }
        }







|







315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
                    dataP = TwapiLzmaUncompressBuffer(interp, dataP, sz, &sz);
                    if (dataP == NULL)
                        return TCL_ERROR; /* interp already has error */
                }
                
                /* The resource is expected to be UTF-8 (actually strict ASCII) */
                /* TBD - double check use of GLOBAL and DIRECT */
                result = Tcl_EvalEx(interp, (char *)dataP, sz, TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
                if (compressed)
                    TwapiLzmaFreeBuffer(dataP);
                if (result == TCL_OK)
                    Tcl_ResetResult(interp);
                return result;
            }
        }
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    while (sz--) {
        if (path[sz] == L'/' || path[sz] == L'\\') {
            ++sz;
            break;
        }
    }
    path[sz] = 0;
    return ObjFromUnicodeN(path, sz);
}

int Twapi_GetTwapiBuildInfo(
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[]







|







380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
    while (sz--) {
        if (path[sz] == L'/' || path[sz] == L'\\') {
            ++sz;
            break;
        }
    }
    path[sz] = 0;
    return ObjFromWinCharsN(path, sz);
}

int Twapi_GetTwapiBuildInfo(
    ClientData dummy,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[]
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
    if (hmodule == gTwapiModuleHandle) {
        ZLIST_PREPEND(&gTwapiInterpContexts, ticP);
    } else {
        ZLIST_APPEND(&gTwapiInterpContexts, ticP);
    }
    LeaveCriticalSection(&gTwapiInterpContextsCS);

    Tcl_CallWhenDeleted(interp, Twapi_InterpContextCleanup, ticP);

    return ticP;
}

/* Note CALLER MAY BE SOME OTHER THREAD, NOT NECESSARILY THE INTERP ONE */
/* Most cleanup should have happened via Twapi_InterpContextCleanup */
static void TwapiInterpContextDelete(TwapiInterpContext *ticP)







|







572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    if (hmodule == gTwapiModuleHandle) {
        ZLIST_PREPEND(&gTwapiInterpContexts, ticP);
    } else {
        ZLIST_APPEND(&gTwapiInterpContexts, ticP);
    }
    LeaveCriticalSection(&gTwapiInterpContextsCS);

    Tcl_CallWhenDeleted(interp, Twapi_InterpContextCleanup, (void *) ticP);

    return ticP;
}

/* Note CALLER MAY BE SOME OTHER THREAD, NOT NECESSARILY THE INTERP ONE */
/* Most cleanup should have happened via Twapi_InterpContextCleanup */
static void TwapiInterpContextDelete(TwapiInterpContext *ticP)
619
620
621
622
623
624
625
626
627

628
629
630
631
632
633
634
{
    if (InterlockedExchangeAdd(&ticP->nrefs, -decr) <= decr)
        TwapiInterpContextDelete(ticP);
}

/* Note this cleans up only one TwapiInterpContext for interp, not the whole
   interp */
static void Twapi_InterpContextCleanup(TwapiInterpContext *ticP, Tcl_Interp *interp)
{

    TwapiInterpContext *tic2P;
    TwapiThreadPoolRegistration *tprP;

    TWAPI_ASSERT(ticP->interp == interp);

    /* Should this be called from TwapiInterpContextDelete instead ? */
    if (ticP->module.modP->finalizer) {







|

>







606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
{
    if (InterlockedExchangeAdd(&ticP->nrefs, -decr) <= decr)
        TwapiInterpContextDelete(ticP);
}

/* Note this cleans up only one TwapiInterpContext for interp, not the whole
   interp */
static void Twapi_InterpContextCleanup(void *pv, Tcl_Interp *interp)
{
    TwapiInterpContext *ticP = (TwapiInterpContext *)pv;
    TwapiInterpContext *tic2P;
    TwapiThreadPoolRegistration *tprP;

    TWAPI_ASSERT(ticP->interp == interp);

    /* Should this be called from TwapiInterpContextDelete instead ? */
    if (ticP->module.modP->finalizer) {
679
680
681
682
683
684
685
686
687

688
689
690
691
692
693
694
#undef CMP
    LeaveCriticalSection(&gTwapiInterpContextsCS);
    return ticP;
}


/* One time (per process) initialization for base module */
static int TwapiOneTimeInit(Tcl_Interp *interp)
{

    WSADATA ws_data;
    WORD    ws_ver = MAKEWORD(1,1);

    gTlsIndex = TlsAlloc();
    if (gTlsIndex == TLS_OUT_OF_INDEXES)
        return TCL_ERROR;       /* No point storing error message.
                                   Discarded anyways by Tcl */







|

>







667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
#undef CMP
    LeaveCriticalSection(&gTwapiInterpContextsCS);
    return ticP;
}


/* One time (per process) initialization for base module */
static int TwapiOneTimeInit(void *pv)
{
    Tcl_Interp *interp = (Tcl_Interp *) pv;
    WSADATA ws_data;
    WORD    ws_ver = MAKEWORD(1,1);

    gTlsIndex = TlsAlloc();
    if (gTlsIndex == TLS_OUT_OF_INDEXES)
        return TCL_ERROR;       /* No point storing error message.
                                   Discarded anyways by Tcl */
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
         * for a private ticP
         */
    }

    TWAPI_ASSERT(ticP);

    /* TBD - may be the last param to SourceResource should be 0? */
    if (modP->initializer && modP->initializer(interp, ticP) != TCL_OK ||
        Twapi_SourceResource(interp, hmod, modP->name, 1) != TCL_OK ||
        Tcl_PkgProvide(interp, modP->name, MODULEVERSION) != TCL_OK
        ) {
        if (context_type)
            TwapiInterpContextUnref(ticP, 1);
        return NULL;
    }

    /* Link the trace flags. Note these are shared amongs interps */
    _snprintf(buf, ARRAYSIZE(buf), "%s(%s)", TWAPI_LOG_CONFIG_VAR, modP->name);
    objP = Tcl_GetVar2Ex(interp, buf, NULL, TCL_GLOBAL_ONLY);
    if (objP) {
        /*
         * Variable already exists, copy its value to trace flags.
         * Errors are ignored as flags will remain 0
         */
        ObjToLong(NULL, objP, &modP->log_flags);
    }
    Tcl_LinkVar(interp, buf, (char *) &modP->log_flags, TCL_LINK_ULONG);
    return ticP;
}

int Twapi_GetVersionEx(Tcl_Interp *interp)
{







|
















|







777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
         * for a private ticP
         */
    }

    TWAPI_ASSERT(ticP);

    /* TBD - may be the last param to SourceResource should be 0? */
    if ((modP->initializer && modP->initializer(interp, ticP) != TCL_OK) ||
        Twapi_SourceResource(interp, hmod, modP->name, 1) != TCL_OK ||
        Tcl_PkgProvide(interp, modP->name, MODULEVERSION) != TCL_OK
        ) {
        if (context_type)
            TwapiInterpContextUnref(ticP, 1);
        return NULL;
    }

    /* Link the trace flags. Note these are shared amongs interps */
    _snprintf(buf, ARRAYSIZE(buf), "%s(%s)", TWAPI_LOG_CONFIG_VAR, modP->name);
    objP = Tcl_GetVar2Ex(interp, buf, NULL, TCL_GLOBAL_ONLY);
    if (objP) {
        /*
         * Variable already exists, copy its value to trace flags.
         * Errors are ignored as flags will remain 0
         */
        ObjToDWORD(NULL, objP, &modP->log_flags);
    }
    Tcl_LinkVar(interp, buf, (char *) &modP->log_flags, TCL_LINK_ULONG);
    return ticP;
}

int Twapi_GetVersionEx(Tcl_Interp *interp)
{
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
    records = SWSPushFrame(count * sizeof(Tcl_Obj*), NULL);
    for (i = 0; i < count; ++i) {
        Tcl_Obj *sidObj;

        /* Create a list corresponding to the fields for the process entry */
        objv[0] = ObjFromLong(processP[i].SessionId);
        objv[1] = ObjFromLong(processP[i].ProcessId);
        objv[2] = ObjFromUnicode(processP[i].pProcessName);
        if (processP[i].pUserSid) {
            if (ObjFromSID(interp, processP[i].pUserSid, &sidObj) != TCL_OK) {
                Twapi_WTSFreeMemory(processP);
                ObjDecrArrayRefs(i, records);
                SWSPopFrame();
                return TCL_ERROR;
            }







|







847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
    records = SWSPushFrame(count * sizeof(Tcl_Obj*), NULL);
    for (i = 0; i < count; ++i) {
        Tcl_Obj *sidObj;

        /* Create a list corresponding to the fields for the process entry */
        objv[0] = ObjFromLong(processP[i].SessionId);
        objv[1] = ObjFromLong(processP[i].ProcessId);
        objv[2] = ObjFromWinChars(processP[i].pProcessName);
        if (processP[i].pUserSid) {
            if (ObjFromSID(interp, processP[i].pUserSid, &sidObj) != TCL_OK) {
                Twapi_WTSFreeMemory(processP);
                ObjDecrArrayRefs(i, records);
                SWSPopFrame();
                return TCL_ERROR;
            }
Changes to undroid/twapi/twapi/base/util.c.
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
}

WCHAR *TwapiAllocWStringFromObj(Tcl_Obj *objP, int *lenP) {
    WCHAR *wP;
    int len;
    if (lenP == NULL)
        lenP = &len;
    wP = ObjToUnicodeN(objP, lenP);
    return TwapiAllocWString(wP, *lenP);
}

char *TwapiAllocAString(char *src, int len)
{
    char *dst;
    if (len < 0) {







|







126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
}

WCHAR *TwapiAllocWStringFromObj(Tcl_Obj *objP, int *lenP) {
    WCHAR *wP;
    int len;
    if (lenP == NULL)
        lenP = &len;
    wP = ObjToWinCharsN(objP, lenP);
    return TwapiAllocWString(wP, *lenP);
}

char *TwapiAllocAString(char *src, int len)
{
    char *dst;
    if (len < 0) {
360
361
362
363
364
365
366









367
368
369
370
371
372
373
374
375
376
        break;
    case TRT_UNICODE_DYNAMIC:
        responseP->value.unicode.str =
            TwapiAllocWStringFromObj(
                objP, &responseP->value.unicode.len);
        break;
    case TRT_LONG:









    case TRT_DWORD:
        tcl_status = ObjToLong(cbP->ticP->interp, objP,
                                        &responseP->value.ival);
        /* Errors will be handled below */
        break;
    case TRT_BOOL:
        tcl_status = ObjToBoolean(cbP->ticP->interp, objP,
                                  &responseP->value.bval);
        /* Errors will be handled below */
        break;







>
>
>
>
>
>
>
>
>

|
|







360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
        break;
    case TRT_UNICODE_DYNAMIC:
        responseP->value.unicode.str =
            TwapiAllocWStringFromObj(
                objP, &responseP->value.unicode.len);
        break;
    case TRT_LONG:
        tcl_status = ObjToLong(cbP->ticP->interp, objP,
                               (long *) &responseP->value.lval);
        /* Errors will be handled below */
        break;
    case TRT_INT:
        tcl_status = ObjToInt(cbP->ticP->interp, objP,
                               &responseP->value.ival);
        /* Errors will be handled below */
        break;
    case TRT_DWORD:
        tcl_status = ObjToDWORD(cbP->ticP->interp, objP,
                                &responseP->value.uval);
        /* Errors will be handled below */
        break;
    case TRT_BOOL:
        tcl_status = ObjToBoolean(cbP->ticP->interp, objP,
                                  &responseP->value.bval);
        /* Errors will be handled below */
        break;
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
vamoose:
    ObjDecrRefs(msgObj);
    return TCL_OK;
}

int Twapi_AppendLog(Tcl_Interp *interp, WCHAR *msg)
{
    return Twapi_AppendObjLog(interp, ObjFromUnicode(msg));
}

/* Sets interp result as handle if not null else GetLastError value */
TCL_RESULT TwapiReturnNonnullHandle(Tcl_Interp *interp, HANDLE h, char *typestr)
{
    if (h == NULL)
        return TwapiReturnSystemError(interp);







|







465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
vamoose:
    ObjDecrRefs(msgObj);
    return TCL_OK;
}

int Twapi_AppendLog(Tcl_Interp *interp, WCHAR *msg)
{
    return Twapi_AppendObjLog(interp, ObjFromWinChars(msg));
}

/* Sets interp result as handle if not null else GetLastError value */
TCL_RESULT TwapiReturnNonnullHandle(Tcl_Interp *interp, HANDLE h, char *typestr)
{
    if (h == NULL)
        return TwapiReturnSystemError(interp);
Changes to undroid/twapi/twapi/base/win.c.
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    )
{
    static ATOM hidden_win_class;
    HWND win;

    /*
     * Register the class for receiving messages. Note we are using
     * Unicode versions of the call so all received windows text
     * message will be unicode
     */
    if (hidden_win_class == 0) {
        WNDCLASSEXW w;
        TwapiZeroMemory(&w, sizeof(w));
        w.cbSize = sizeof(w);
        w.hInstance = gTwapiModuleHandle;







|







65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    )
{
    static ATOM hidden_win_class;
    HWND win;

    /*
     * Register the class for receiving messages. Note we are using
     * WCHAR versions of the call so all received windows text
     * message will be unicode
     */
    if (hidden_win_class == 0) {
        WNDCLASSEXW w;
        TwapiZeroMemory(&w, sizeof(w));
        w.cbSize = sizeof(w);
        w.hInstance = gTwapiModuleHandle;
167
168
169
170
171
172
173
174

175
176
177
178
179
180
181
        DWORD pos;

        cbP = TwapiCallbackNew(ticP, TwapiScriptWMCallbackFn, sizeof(*cbP));
        cbP->receiver_id = msg;
        cbP->clientdata = wParam;
        cbP->clientdata2 = lParam;
        pos = GetMessagePos();
        cbP->wm_state.message_pos = MAKEPOINTS(pos);

        cbP->wm_state.ticks = GetTickCount();
        TwapiEnqueueCallback(ticP, cbP, TWAPI_ENQUEUE_DIRECT, 0, NULL);
        return (LRESULT) NULL;
    } else {
        switch (msg) {
        case WM_CREATE:
            /*







|
>







167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        DWORD pos;

        cbP = TwapiCallbackNew(ticP, TwapiScriptWMCallbackFn, sizeof(*cbP));
        cbP->receiver_id = msg;
        cbP->clientdata = wParam;
        cbP->clientdata2 = lParam;
        pos = GetMessagePos();
        cbP->wm_state.message_pos.x = LOWORD(pos);
        cbP->wm_state.message_pos.y = HIWORD(pos);
        cbP->wm_state.ticks = GetTickCount();
        TwapiEnqueueCallback(ticP, cbP, TWAPI_ENQUEUE_DIRECT, 0, NULL);
        return (LRESULT) NULL;
    } else {
        switch (msg) {
        case WM_CREATE:
            /*
247
248
249
250
251
252
253
254

255
256
257
258
259
260
261
    interp = ticP->interp;
    if (interp == NULL ||
        Tcl_InterpDeleted(interp)) {
        return 0;
    }

    pos = GetMessagePos();
    pts = MAKEPOINTS(pos);

    objs[0] = ObjFromString(TWAPI_TCL_NAMESPACE "::_script_wm_handler");
    objs[1] = ObjFromDWORD(msg);
    objs[2] = ObjFromDWORD_PTR(wParam); /* wParam is unsigned */
    objs[3] = ObjFromLONG_PTR(lParam); /* lParam is signed */
    objs[4] = ObjFromPOINTS(&pts);
    objs[5] = ObjFromDWORD(GetTickCount());








|
>







248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
    interp = ticP->interp;
    if (interp == NULL ||
        Tcl_InterpDeleted(interp)) {
        return 0;
    }

    pos = GetMessagePos();
    pts.x = LOWORD(pos);
    pts.y = HIWORD(pos);
    objs[0] = ObjFromString(TWAPI_TCL_NAMESPACE "::_script_wm_handler");
    objs[1] = ObjFromDWORD(msg);
    objs[2] = ObjFromDWORD_PTR(wParam); /* wParam is unsigned */
    objs[3] = ObjFromLONG_PTR(lParam); /* lParam is signed */
    objs[4] = ObjFromPOINTS(&pts);
    objs[5] = ObjFromDWORD(GetTickCount());

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
    */
    interp_state = Tcl_SaveInterpState(interp, TCL_OK);

    lresult = 0;
    if (Tcl_EvalObjv(interp, ARRAYSIZE(objs), objs, 
                     TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL) == TCL_OK) {
        /* Note if not integer result, lresult stays 0 */
        ObjToDWORD_PTR(interp, ObjGetResult(interp), &lresult);
    }

    /* Restore Interp state */
    Tcl_RestoreInterpState(interp, interp_state);

    Tcl_Release(interp);
    TwapiInterpContextUnref(ticP, 1);







|







274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
    */
    interp_state = Tcl_SaveInterpState(interp, TCL_OK);

    lresult = 0;
    if (Tcl_EvalObjv(interp, ARRAYSIZE(objs), objs, 
                     TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL) == TCL_OK) {
        /* Note if not integer result, lresult stays 0 */
        ObjToLONG_PTR(interp, ObjGetResult(interp), &lresult);
    }

    /* Restore Interp state */
    Tcl_RestoreInterpState(interp, interp_state);

    Tcl_Release(interp);
    TwapiInterpContextUnref(ticP, 1);
Added undroid/twapi/twapi/base/winchars.c.
























































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
 * Copyright (c) 2016, Ashok P. Nadkarni
 * All rights reserved.
 *
 * See the file LICENSE for license
 */

#include "twapi.h"
#include "twapi_base.h"

typedef struct WinChars {
    int nchars; /* Num of characters not counting terminating \0.
                   Always >=0 (i.e. -1 not used to indicate null termination)*/
    WCHAR chars[1]; /* Variable length array holding the string */
} WinChars;

static void DupWinCharsType(Tcl_Obj *srcP, Tcl_Obj *dstP);
static void FreeWinCharsType(Tcl_Obj *objP);
static void UpdateWinCharsTypeString(Tcl_Obj *objP);
static struct Tcl_ObjType gWinCharsType = {
    "TwapiWinChars",
    FreeWinCharsType,
    DupWinCharsType,
    UpdateWinCharsTypeString,
    NULL,     /* jenglish says keep this NULL */
};

/* 
 * Allocate a intrep of appropriate size. Note nchars does not include \0
 * but the defined array size of 1 takes care of that.
 */
TWAPI_INLINE WinChars *WinCharsAlloc(int nchars) {
    return (WinChars *) ckalloc(sizeof(WinChars) + sizeof(WCHAR)*(nchars));
}

/* Free an internal rep */
TWAPI_INLINE void WinCharsFree(WinChars *rep) {
    ckfree((char *) rep);
}

/* Get a pointer to the internal rep from a Tcl_Obj */
TWAPI_INLINE WinChars *WinCharsGet(Tcl_Obj *objP) {
    return (WinChars *) objP->internalRep.twoPtrValue.ptr1;
}
        
/* Set the internal rep for a Tcl_Obj */
TWAPI_INLINE void WinCharsSet(Tcl_Obj *objP, WinChars *rep) {
    objP->typePtr = &gWinCharsType;
    objP->internalRep.twoPtrValue.ptr1 = (void *) rep ;
}

static WinChars *WinCharsNew(const WCHAR *wsP, int len)
{
    WinChars *rep;
    /*
     * Unlike Tcl's String object, we never directly operate on this
     * representation so we don't need to allocate extra space and so on.
     */
    if (wsP == NULL)
        len = 0;
    else if (len == -1)
        len = lstrlenW(wsP);
    rep = WinCharsAlloc(len); /* Will include space for terminating \0 */
    if (len)
        memmove(rep->chars, wsP, len * sizeof(WCHAR));
    rep->chars[len] = 0;
    rep->nchars = len;
    return rep;
}

static void FreeWinCharsType(Tcl_Obj *objP)
{
    TWAPI_ASSERT(objP->typePtr == &gWinCharsType);
    WinCharsFree(WinCharsGet(objP));
    objP->typePtr = NULL;
}

static void DupWinCharsType(Tcl_Obj *srcP, Tcl_Obj *dstP)
{
    WinChars *rep;

    TWAPI_ASSERT(srcP->typePtr == &gWinCharsType);
    rep = WinCharsGet(srcP);
    WinCharsSet(dstP, WinCharsNew(rep->chars, rep->nchars));
}

static void UpdateWinCharsTypeString(Tcl_Obj *objP)
{
    int nbytes;
    char *utf8;
    WinChars *rep;
    Tcl_DString ds;

    rep = WinCharsGet(objP);
    if (rep->nchars == 0) {
        objP->bytes = ckalloc(1);
        objP->bytes[0] = '\0';
        objP->length = 0;
        return;
    }

#if 0
    /* Disabled because XP does not support WC_ERR_INVALID_CHARS and
     *  will silently discard those characters
     */
    
    /* Note rep->nchars does not include terminating \0 so return values
     * will not include it either
     */
    nbytes = WideCharToMultiByte(
        CP_UTF8, /* CodePag */
        WC_ERR_INVALID_CHARS,       /* dwFlags */
        rep->chars,     /* lpWideCharStr */
        rep->nchars,  /* cchWideChar */
        NULL,     /* lpMultiByteStr */
        NULL,  /* cbMultiByte */
        NULL,    /* lpDefaultChar */
        NULL     /* lpUsedDefaultChar */
        );
    if (nbytes != 0) {
        utf8 = ckalloc(nbytes+1); /* One extra for terminating \0 */
        nbytes = WideCharToMultiByte(
            CP_UTF8, /* CodePag */
            WC_ERR_INVALID_CHARS,       /* dwFlags */
            rep->chars,     /* lpWideCharStr */
            rep->nchars,  /* cchWideChar */
            utf8,     /* lpMultiByteStr */
            nbytes,  /* cbMultiByte */
            NULL,    /* lpDefaultChar */
            NULL     /* lpUsedDefaultChar */
            );
        if (nbytes != 0) {
            utf8[nbytes] = '\0';
            objP->bytes = utf8;
            objP->length = nbytes;
            return;
        }
        ckfree(utf8);
    }
    /* 
     * Failures are possible because of invalid characters like embedded
     * nulls which are not illegal in Tcl, so do it the (slower) Tcl way then.
     */

#endif // #if 0
    
    Tcl_WinTCharToUtf(rep->chars, rep->nchars * sizeof(WCHAR), &ds);
    nbytes = Tcl_DStringLength(&ds);
    utf8 = ckalloc(nbytes+1);
    memmove(utf8, Tcl_DStringValue(&ds), nbytes);
    Tcl_DStringFree(&ds);
    utf8[nbytes] = '\0';

    objP->bytes = utf8;
    objP->length = nbytes;
}

TWAPI_EXTERN WCHAR *ObjToWinChars(Tcl_Obj *objP)
{
    WinChars *rep;
    Tcl_DString ds;
    int nbytes, len;
    char *utf8;
    
    if (objP->typePtr == &gWinCharsType)
        return WinCharsGet(objP)->chars;

    utf8 = ObjToStringN(objP, &nbytes);
    Tcl_WinUtfToTChar(utf8, nbytes, &ds);
    len = Tcl_DStringLength(&ds) / sizeof(WCHAR);
    rep = WinCharsNew(Tcl_DStringValue(&ds), len);
    Tcl_DStringFree(&ds);
    
    /* Convert the passed object's internal rep */
    if (objP->typePtr && objP->typePtr->freeIntRepProc)
        objP->typePtr->freeIntRepProc(objP);
    WinCharsSet(objP, rep);
    return rep->chars;
}

TWAPI_EXTERN WCHAR *ObjToWinCharsN(Tcl_Obj *objP, int *lenP)
{
    WCHAR *wsP;
    wsP = ObjToWinChars(objP); /* Will convert as needed */
    if (lenP)
        *lenP = WinCharsGet(objP)->nchars;
    return wsP;
}

/* Identical to ObjToWinCharsN except length pointer type.
   Just to keep gcc happy without needing a cast */
TWAPI_EXTERN WCHAR *ObjToWinCharsNDW(Tcl_Obj *objP, DWORD *lenP)
{
    WCHAR *wsP;
    wsP = ObjToWinChars(objP); /* Will convert as needed */
    if (lenP)
        *lenP = WinCharsGet(objP)->nchars;
    return wsP;
}

TWAPI_EXTERN Tcl_Obj *ObjFromWinCharsN(const WCHAR *wsP, int nchars)
{
    Tcl_Obj *objP;
    WinChars *rep;
    
    if (wsP == NULL)
        return ObjFromEmptyString();
    
    rep = WinCharsNew(wsP, nchars);
    objP = Tcl_NewObj();
    Tcl_InvalidateStringRep(objP);
    WinCharsSet(objP, rep);
    return objP;
}

TWAPI_EXTERN Tcl_Obj *ObjFromWinChars(const WCHAR *wsP)
{
    return ObjFromWinCharsN(wsP, -1);
}

Changes to undroid/twapi/twapi/clipboard/clipboard.c.
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#ifndef MODULENAME
#define MODULENAME "twapi_clipboard"
#endif

int Twapi_EnumClipboardFormats(Tcl_Interp *interp);
int Twapi_ClipboardMonitorStart(TwapiInterpContext *ticP);
int Twapi_ClipboardMonitorStop(TwapiInterpContext *ticP);
static DWORD TwapiClipboardCallbackFn(TwapiCallback *pcbP);

int Twapi_EnumClipboardFormats(Tcl_Interp *interp)
{
    UINT clip_fmt;
    Tcl_Obj *resultObj = ObjNewList(0, NULL);

    clip_fmt = 0;







|







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#ifndef MODULENAME
#define MODULENAME "twapi_clipboard"
#endif

int Twapi_EnumClipboardFormats(Tcl_Interp *interp);
int Twapi_ClipboardMonitorStart(TwapiInterpContext *ticP);
int Twapi_ClipboardMonitorStop(TwapiInterpContext *ticP);
static int TwapiClipboardCallbackFn(TwapiCallback *pcbP);

int Twapi_EnumClipboardFormats(Tcl_Interp *interp)
{
    UINT clip_fmt;
    Tcl_Obj *resultObj = ObjNewList(0, NULL);

    clip_fmt = 0;
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

    return TCL_OK;
}

/* Called (indirectly) from the Tcl notifier loop with a new clipboard event.
 * Follows behaviour specified by TwapiCallbackFn typedef.
 */
static DWORD TwapiClipboardCallbackFn(TwapiCallback *cbP)
{
    Tcl_Obj *objP = ObjFromString(TWAPI_TCL_NAMESPACE "::_clipboard_handler");
    return TwapiEvalAndUpdateCallback(cbP, 1, &objP, TRT_EMPTY);
}

static TCL_RESULT Twapi_ClipboardCallObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    int func;
    HWND   hwnd;
    DWORD dw;
    HANDLE h;
    TwapiResult result;
    WCHAR buf[MAX_PATH+1];

    ObjToUnicodeCleanup();

    /* Every command has at least one argument */
    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    objc -= 2;







|





|

>







<
<







139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161


162
163
164
165
166
167
168

    return TCL_OK;
}

/* Called (indirectly) from the Tcl notifier loop with a new clipboard event.
 * Follows behaviour specified by TwapiCallbackFn typedef.
 */
static int TwapiClipboardCallbackFn(TwapiCallback *cbP)
{
    Tcl_Obj *objP = ObjFromString(TWAPI_TCL_NAMESPACE "::_clipboard_handler");
    return TwapiEvalAndUpdateCallback(cbP, 1, &objP, TRT_EMPTY);
}

static TCL_RESULT Twapi_ClipboardCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int func;
    HWND   hwnd;
    DWORD dw;
    HANDLE h;
    TwapiResult result;
    WCHAR buf[MAX_PATH+1];



    /* Every command has at least one argument */
    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    objc -= 2;
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    case 7:
        return Twapi_ClipboardMonitorStop(ticP);
    case 8:
    case 9:
    case 10:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        switch (func) {
        case 8:
            result.type = TRT_BOOL;
            result.value.bval = IsClipboardFormatAvailable(dw);
            break;
        case 9:
            result.type = TRT_HANDLE;







|







192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    case 7:
        return Twapi_ClipboardMonitorStop(ticP);
    case 8:
    case 9:
    case 10:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        switch (func) {
        case 8:
            result.type = TRT_BOOL;
            result.value.bval = IsClipboardFormatAvailable(dw);
            break;
        case 9:
            result.type = TRT_HANDLE;
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
        result.type = TRT_HANDLE;
        result.value.hval = SetClipboardData(dw, h);
        break;
    case 12:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        result.type = TRT_NONZERO_RESULT;
        result.value.ival = RegisterClipboardFormatW(ObjToUnicode(objv[0]));
        break;
    case 13:
        if (TwapiGetArgs(interp, objc, objv, GETHWND(hwnd), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.value.ival = OpenClipboard(hwnd);
        result.type = TRT_EXCEPTION_ON_FALSE;
        break;







|







219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
        result.type = TRT_HANDLE;
        result.value.hval = SetClipboardData(dw, h);
        break;
    case 12:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        result.type = TRT_NONZERO_RESULT;
        result.value.ival = RegisterClipboardFormatW(ObjToWinChars(objv[0]));
        break;
    case 13:
        if (TwapiGetArgs(interp, objc, objv, GETHWND(hwnd), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.value.ival = OpenClipboard(hwnd);
        result.type = TRT_EXCEPTION_ON_FALSE;
        break;
Changes to undroid/twapi/twapi/com/com.c.
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

Tcl_Obj *ObjFromTwapiBlanket(struct TwapiBlanket *blanketP)
{
    Tcl_Obj *objs[7];

    objs[0] = ObjFromLong(blanketP->authn);
    objs[1] = ObjFromLong(blanketP->authz);
    objs[2] = ObjFromUnicode(blanketP->server);
    objs[3] = ObjFromLong(blanketP->authn_level);
    objs[4] = ObjFromLong(blanketP->imp_level);
    if (blanketP->auth_info) {
        switch (blanketP->authn) {
        case RPC_C_AUTHN_WINNT:
        case RPC_C_AUTHN_GSS_KERBEROS:
            objs[5] = ObjFromUnicode(blanketP->auth_info);
            break;
        case RPC_C_AUTHN_GSS_SCHANNEL:
            // TBD - certificate
            // May be use CertSerializeCertificateStoreElement
            // or CertCreateCertificateContext or
            // CertDuplicateCertificateContext or
            // read the pcbEncoded part of the CERT_CONTEXT







|






|







86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

Tcl_Obj *ObjFromTwapiBlanket(struct TwapiBlanket *blanketP)
{
    Tcl_Obj *objs[7];

    objs[0] = ObjFromLong(blanketP->authn);
    objs[1] = ObjFromLong(blanketP->authz);
    objs[2] = ObjFromWinChars(blanketP->server);
    objs[3] = ObjFromLong(blanketP->authn_level);
    objs[4] = ObjFromLong(blanketP->imp_level);
    if (blanketP->auth_info) {
        switch (blanketP->authn) {
        case RPC_C_AUTHN_WINNT:
        case RPC_C_AUTHN_GSS_KERBEROS:
            objs[5] = ObjFromWinChars(blanketP->auth_info);
            break;
        case RPC_C_AUTHN_GSS_SCHANNEL:
            // TBD - certificate
            // May be use CertSerializeCertificateStoreElement
            // or CertCreateCertificateContext or
            // CertDuplicateCertificateContext or
            // read the pcbEncoded part of the CERT_CONTEXT
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#if 1
        objv[1] = ObjFromDWORD(tdP->hreftype);
#else
        objv[1] = NULL;
        if (tiP->lpVtbl->GetRefTypeInfo(tiP, tdP->hreftype, &utiP) == S_OK) {
            BSTR bstr;
            if (utiP->lpVtbl->GetDocumentation(utiP, MEMBERID_NIL, &bstr, NULL, NULL, NULL) == S_OK) {
                objv[1] = ObjFromUnicodeN(bstr, SysStringLen(bstr));
                SysFreeString(bstr);
            }
            utiP->lpVtbl->Release(utiP);
        }
        if (objv[1] == NULL) {
            /* Could not get name of custom type. */
            objv[1] = ObjFromEmptyString();







|







174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#if 1
        objv[1] = ObjFromDWORD(tdP->hreftype);
#else
        objv[1] = NULL;
        if (tiP->lpVtbl->GetRefTypeInfo(tiP, tdP->hreftype, &utiP) == S_OK) {
            BSTR bstr;
            if (utiP->lpVtbl->GetDocumentation(utiP, MEMBERID_NIL, &bstr, NULL, NULL, NULL) == S_OK) {
                objv[1] = ObjFromWinCharsN(bstr, SysStringLen(bstr));
                SysFreeString(bstr);
            }
            utiP->lpVtbl->Release(utiP);
        }
        if (objv[1] == NULL) {
            /* Could not get name of custom type. */
            objv[1] = ObjFromEmptyString();
318
319
320
321
322
323
324
325
326
327
328
329

330
331
332
333
334
335
336
    ObjAppendElement(interp, resultObj, obj);

    return resultObj;
}


int Twapi_IDispatch_InvokeObjCmd(
    TwapiInterpContext *ticP,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{

    IDispatch *idispP;
    LCID       lcid;
    WORD       flags;
    int        i, j;
    DISPID     dispid;
    DISPPARAMS dispparams;
    Tcl_Obj  **params;







|




>







318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
    ObjAppendElement(interp, resultObj, obj);

    return resultObj;
}


int Twapi_IDispatch_InvokeObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    IDispatch *idispP;
    LCID       lcid;
    WORD       flags;
    int        i, j;
    DISPID     dispid;
    DISPPARAMS dispparams;
    Tcl_Obj  **params;
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
     */

    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 1, objv, "IDISPATCH PROTOTYPE ?ARG1 ARG2...?");
        return TCL_ERROR;
    }

    if (ObjToIDispatch(interp, objv[1], &idispP) != TCL_OK)
        return TCL_ERROR;

    if (ObjGetElements(interp, objv[2], &protoc, &protov) != TCL_OK)
        return TCL_ERROR;

    /* Extract prototype information */
    if (TwapiGetArgs(interp, protoc, protov,







|







371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
     */

    if (objc < 3) {
        Tcl_WrongNumArgs(interp, 1, objv, "IDISPATCH PROTOTYPE ?ARG1 ARG2...?");
        return TCL_ERROR;
    }

    if (ObjToIDispatch(interp, objv[1], (void **)&idispP) != TCL_OK)
        return TCL_ERROR;

    if (ObjGetElements(interp, objv[2], &protoc, &protov) != TCL_OK)
        return TCL_ERROR;

    /* Extract prototype information */
    if (TwapiGetArgs(interp, protoc, protov,
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614

            Twapi_AppendSystemErrorEx(interp, hr, ObjNewList(ARRAYSIZE(errorcode_extra), errorcode_extra));

            if (einfo.bstrDescription) {
                errorResultObj = ObjDuplicate(ObjGetResult(interp));
                Tcl_AppendToObj(errorResultObj, " ", 1);
                Tcl_AppendObjToObj(errorResultObj,
                    ObjFromUnicodeN(einfo.bstrDescription,
                                  SysStringLen(einfo.bstrDescription)));
                ObjSetResult(interp, errorResultObj);
            } else {
                /* No error description. Perhaps the scode field
                 * tells us something more.
                 */
                if (einfo.scode &&







|







601
602
603
604
605
606
607
608
609
610
611
612
613
614
615

            Twapi_AppendSystemErrorEx(interp, hr, ObjNewList(ARRAYSIZE(errorcode_extra), errorcode_extra));

            if (einfo.bstrDescription) {
                errorResultObj = ObjDuplicate(ObjGetResult(interp));
                Tcl_AppendToObj(errorResultObj, " ", 1);
                Tcl_AppendObjToObj(errorResultObj,
                    ObjFromWinCharsN(einfo.bstrDescription,
                                  SysStringLen(einfo.bstrDescription)));
                ObjSetResult(interp, errorResultObj);
            } else {
                /* No error description. Perhaps the scode field
                 * tells us something more.
                 */
                if (einfo.scode &&
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
    /* Convert the list object into an array of points to strings */
    if (ObjGetElements(interp, namesObj, &nitems, &items) == TCL_ERROR)
        return TCL_ERROR;

    names = MemLifoPushFrame(ticP->memlifoP, nitems*sizeof(*names), NULL);

    for (i = 0; i < nitems; i++)
        names[i] = ObjToUnicode(items[i]);

    /* Allocate an array to hold returned ids */
    ids = MemLifoAlloc(ticP->memlifoP, nitems * sizeof(*ids), NULL);

    /* Map the names to ids */
    switch (ifc_type) {
    case 0:







|







698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
    /* Convert the list object into an array of points to strings */
    if (ObjGetElements(interp, namesObj, &nitems, &items) == TCL_ERROR)
        return TCL_ERROR;

    names = MemLifoPushFrame(ticP->memlifoP, nitems*sizeof(*names), NULL);

    for (i = 0; i < nitems; i++)
        names[i] = ObjToWinChars(items[i]);

    /* Allocate an array to hold returned ids */
    ids = MemLifoAlloc(ticP->memlifoP, nitems * sizeof(*ids), NULL);

    /* Map the names to ids */
    switch (ifc_type) {
    case 0:
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

    if (SUCCEEDED(hr)) {
        Tcl_Obj *resultObj;
        int      i;

        resultObj = ObjNewList(0, NULL);
        for (i = 0; i < nitems; ++i) {
            ObjAppendElement(interp, resultObj, ObjFromUnicode(names[i]));
            ObjAppendElement(interp, resultObj, ObjFromLong(ids[i]));
        }
        ObjSetResult(interp, resultObj);
        status = TCL_OK;
    }
    else {
        Twapi_AppendSystemError(interp, hr);







|







723
724
725
726
727
728
729
730
731
732
733
734
735
736
737

    if (SUCCEEDED(hr)) {
        Tcl_Obj *resultObj;
        int      i;

        resultObj = ObjNewList(0, NULL);
        for (i = 0; i < nitems; ++i) {
            ObjAppendElement(interp, resultObj, ObjFromWinChars(names[i]));
            ObjAppendElement(interp, resultObj, ObjFromLong(ids[i]));
        }
        ObjSetResult(interp, resultObj);
        status = TCL_OK;
    }
    else {
        Twapi_AppendSystemError(interp, hr);
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
    objv[4] = STRING_LITERAL_OBJ("dwReserved");
    objv[5] = ObjFromLong(taP->dwReserved);
    objv[6] = STRING_LITERAL_OBJ("memidConstructor");
    objv[7] = ObjFromLong(taP->memidConstructor);
    objv[8] = STRING_LITERAL_OBJ("memidDestructor");
    objv[9] = ObjFromLong(taP->memidDestructor);
    objv[10] = STRING_LITERAL_OBJ("lpstrSchema");
    objv[11] = ObjFromUnicode(taP->lpstrSchema ? taP->lpstrSchema : L"");
    objv[12] = STRING_LITERAL_OBJ("cbSizeInstance");
    objv[13] = ObjFromLong(taP->cbSizeInstance);
    objv[14] = STRING_LITERAL_OBJ("typekind");
    objv[15] = ObjFromLong(taP->typekind);
    objv[16] = STRING_LITERAL_OBJ("cFuncs");
    objv[17] = ObjFromLong(taP->cFuncs);
    objv[18] = STRING_LITERAL_OBJ("cVars");







|







761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
    objv[4] = STRING_LITERAL_OBJ("dwReserved");
    objv[5] = ObjFromLong(taP->dwReserved);
    objv[6] = STRING_LITERAL_OBJ("memidConstructor");
    objv[7] = ObjFromLong(taP->memidConstructor);
    objv[8] = STRING_LITERAL_OBJ("memidDestructor");
    objv[9] = ObjFromLong(taP->memidDestructor);
    objv[10] = STRING_LITERAL_OBJ("lpstrSchema");
    objv[11] = ObjFromWinChars(taP->lpstrSchema ? taP->lpstrSchema : L"");
    objv[12] = STRING_LITERAL_OBJ("cbSizeInstance");
    objv[13] = ObjFromLong(taP->cbSizeInstance);
    objv[14] = STRING_LITERAL_OBJ("typekind");
    objv[15] = ObjFromLong(taP->typekind);
    objv[16] = STRING_LITERAL_OBJ("cFuncs");
    objv[17] = ObjFromLong(taP->cFuncs);
    objv[18] = STRING_LITERAL_OBJ("cVars");
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
int Twapi_ITypeInfo_GetNames(
    Tcl_Interp *interp,
    ITypeInfo *tiP,
    MEMBERID memid)
{
    HRESULT hr;
    BSTR    names[64];
    int     name_count;

    TwapiZeroMemory(names, sizeof(names));

    hr = tiP->lpVtbl->GetNames(tiP, memid, names, sizeof(names)/sizeof(names[0]), &name_count);

    if (SUCCEEDED(hr)) {
        Tcl_Obj *resultObj;
        int      i;

        resultObj = ObjNewList(0, NULL);
        for (i = 0; i < name_count; ++i) {
            ObjAppendElement(
                interp,
                resultObj,
                ObjFromUnicodeN(names[i], SysStringLen(names[i])));
            SysFreeString(names[i]);
            names[i] = NULL;
        }
        ObjSetResult(interp, resultObj);
        return TCL_OK;
    }
    else {







|







|






|







805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
int Twapi_ITypeInfo_GetNames(
    Tcl_Interp *interp,
    ITypeInfo *tiP,
    MEMBERID memid)
{
    HRESULT hr;
    BSTR    names[64];
    UINT     name_count;

    TwapiZeroMemory(names, sizeof(names));

    hr = tiP->lpVtbl->GetNames(tiP, memid, names, sizeof(names)/sizeof(names[0]), &name_count);

    if (SUCCEEDED(hr)) {
        Tcl_Obj *resultObj;
        UINT      i;

        resultObj = ObjNewList(0, NULL);
        for (i = 0; i < name_count; ++i) {
            ObjAppendElement(
                interp,
                resultObj,
                ObjFromWinCharsN(names[i], SysStringLen(names[i])));
            SysFreeString(names[i]);
            names[i] = NULL;
        }
        ObjSetResult(interp, resultObj);
        return TCL_OK;
    }
    else {
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
        return TCL_OK;
    }
    else {
        return Twapi_AppendSystemError(interp, hr);
    }
}

static TwapiInitOutputParam(VARIANT *varP, VARTYPE vt)
{
    /* We used to just set output params to type VT_EMPTY but turns out
       OneNote does not like that. It wants it to be initialized to
       the type it expects to return in that parameter.
    */
    V_VT(varP) = vt;
    switch (vt) {







|







863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
        return TCL_OK;
    }
    else {
        return Twapi_AppendSystemError(interp, hr);
    }
}

static void TwapiInitOutputParam(VARIANT *varP, VARTYPE vt)
{
    /* We used to just set output params to type VT_EMPTY but turns out
       OneNote does not like that. It wants it to be initialized to
       the type it expects to return in that parameter.
    */
    V_VT(varP) = vt;
    switch (vt) {
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683

1684
1685
1686
1687
1688
1689
1690
    for (i = 0; i < nobjs; ++i) {
        Tcl_Obj **elems;
        int nelems;
        DWORD authn, authz;
        if (ObjGetElements(interp, objs[i], &nelems, &elems) != TCL_OK)
            return TCL_ERROR;
        if (nelems != 3 ||
            ObjToLong(interp, elems[0], &authn) != TCL_OK ||
            ObjToLong(interp, elems[1], &authz) != TCL_OK) {
            ObjSetStaticResult(ticP->interp, "Invalid SOLE_AUTHENTICATION_INFO structure");
            return TCL_ERROR;
        }
        if (authz != RPC_C_AUTHZ_NONE ||
            (authn != RPC_C_AUTHN_WINNT &&
             authn != RPC_C_AUTHN_GSS_KERBEROS &&
             authn != RPC_C_AUTHN_GSS_NEGOTIATE)) {
            return TwapiReturnErrorMsg(interp, TWAPI_UNSUPPORTED_TYPE, "Unsupported authentication service.");
        }
        salP->aAuthInfo[i].dwAuthnSvc = authn;
        salP->aAuthInfo[i].dwAuthzSvc = authz;
        if (ParsePSEC_WINNT_AUTH_IDENTITY(ticP, elems[2], (SEC_WINNT_AUTH_IDENTITY_W **)&salP->aAuthInfo[i].pAuthInfo) != TCL_OK)
            return TCL_ERROR;
    }

    *salPP = salP;
    return TCL_OK;
}


static TCL_RESULT Twapi_CoCreateInstanceExObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    MemLifoMarkHandle mark;
    IUnknown *ifc_outer;
    IID clsid;
    TCL_RESULT res;
    DWORD nmqi;
    MULTI_QI *mqiP;
    DWORD dwClsCtx;







|
|




















|

>







1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
    for (i = 0; i < nobjs; ++i) {
        Tcl_Obj **elems;
        int nelems;
        DWORD authn, authz;
        if (ObjGetElements(interp, objs[i], &nelems, &elems) != TCL_OK)
            return TCL_ERROR;
        if (nelems != 3 ||
            ObjToDWORD(interp, elems[0], &authn) != TCL_OK ||
            ObjToDWORD(interp, elems[1], &authz) != TCL_OK) {
            ObjSetStaticResult(ticP->interp, "Invalid SOLE_AUTHENTICATION_INFO structure");
            return TCL_ERROR;
        }
        if (authz != RPC_C_AUTHZ_NONE ||
            (authn != RPC_C_AUTHN_WINNT &&
             authn != RPC_C_AUTHN_GSS_KERBEROS &&
             authn != RPC_C_AUTHN_GSS_NEGOTIATE)) {
            return TwapiReturnErrorMsg(interp, TWAPI_UNSUPPORTED_TYPE, "Unsupported authentication service.");
        }
        salP->aAuthInfo[i].dwAuthnSvc = authn;
        salP->aAuthInfo[i].dwAuthzSvc = authz;
        if (ParsePSEC_WINNT_AUTH_IDENTITY(ticP, elems[2], (SEC_WINNT_AUTH_IDENTITY_W **)&salP->aAuthInfo[i].pAuthInfo) != TCL_OK)
            return TCL_ERROR;
    }

    *salPP = salP;
    return TCL_OK;
}


static TCL_RESULT Twapi_CoCreateInstanceExObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    MemLifoMarkHandle mark;
    IUnknown *ifc_outer;
    IID clsid;
    TCL_RESULT res;
    DWORD nmqi;
    MULTI_QI *mqiP;
    DWORD dwClsCtx;
1714
1715
1716
1717
1718
1719
1720
1721
1722

1723
1724
1725
1726
1727
1728
1729
        SecureZeroSEC_WINNT_AUTH_IDENTITY((SEC_WINNT_AUTH_IDENTITY_W *)cosiP->pAuthInfo->pAuthIdentityData);
        
    MemLifoPopMark(mark);
    return res;
}


static TCL_RESULT Twapi_CoSetProxyBlanketObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *proxyObj, *credsObj;
    IUnknown *ifc;
    TCL_RESULT res;
    SEC_WINNT_AUTH_IDENTITY_W *swaiP;
    HRESULT hr;
    DWORD authz, authn, authn_level, impersonation_level, capabilities;
    LPWSTR principal_name;







|

>







1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
        SecureZeroSEC_WINNT_AUTH_IDENTITY((SEC_WINNT_AUTH_IDENTITY_W *)cosiP->pAuthInfo->pAuthIdentityData);
        
    MemLifoPopMark(mark);
    return res;
}


static TCL_RESULT Twapi_CoSetProxyBlanketObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *proxyObj, *credsObj;
    IUnknown *ifc;
    TCL_RESULT res;
    SEC_WINNT_AUTH_IDENTITY_W *swaiP;
    HRESULT hr;
    DWORD authz, authn, authn_level, impersonation_level, capabilities;
    LPWSTR principal_name;
1777
1778
1779
1780
1781
1782
1783
1784
1785

1786
1787
1788
1789
1790
1791
1792
        res = TCL_ERROR;

    MemLifoPopMark(mark);
    return res;
}


static TCL_RESULT Twapi_CoInitializeSecurityObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    DWORD authn_level, impersonation_level, capabilities;
    Tcl_Obj *authListObj;
    MemLifoMarkHandle mark;
    SECURITY_DESCRIPTOR *secdP;
    SOLE_AUTHENTICATION_LIST *sole_auth_listP;
    GUID appid;
    TCL_RESULT res;







|

>







1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
        res = TCL_ERROR;

    MemLifoPopMark(mark);
    return res;
}


static TCL_RESULT Twapi_CoInitializeSecurityObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    DWORD authn_level, impersonation_level, capabilities;
    Tcl_Obj *authListObj;
    MemLifoMarkHandle mark;
    SECURITY_DESCRIPTOR *secdP;
    SOLE_AUTHENTICATION_LIST *sole_auth_listP;
    GUID appid;
    TCL_RESULT res;
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
            break;
        result.type = TRT_OBJ;
        result.value.obj = ObjNewList(dw2, NULL);
        for (dw = 0; dw < dw2; ++dw) {
            Tcl_Obj *objs[3];
            objs[0] = ObjFromInt(authsvcP[dw].dwAuthnSvc);
            objs[1] = ObjFromInt(authsvcP[dw].dwAuthzSvc);
            objs[2] = ObjFromUnicode(authsvcP[dw].pPrincipalName);
            ObjAppendElement(NULL, result.value.obj, ObjNewList(3, objs));
        }
        CoTaskMemFree(authsvcP);
    }
    
    if (FAILED(hr)) {
        result.type = TRT_EXCEPTION_ON_ERROR;







|







1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
            break;
        result.type = TRT_OBJ;
        result.value.obj = ObjNewList(dw2, NULL);
        for (dw = 0; dw < dw2; ++dw) {
            Tcl_Obj *objs[3];
            objs[0] = ObjFromInt(authsvcP[dw].dwAuthnSvc);
            objs[1] = ObjFromInt(authsvcP[dw].dwAuthzSvc);
            objs[2] = ObjFromWinChars(authsvcP[dw].pPrincipalName);
            ObjAppendElement(NULL, result.value.obj, ObjNewList(3, objs));
        }
        CoTaskMemFree(authsvcP);
    }
    
    if (FAILED(hr)) {
        result.type = TRT_EXCEPTION_ON_ERROR;
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
    } ifc;
    HRESULT hr;
    TwapiResult result;
    DWORD dw1,dw2,dw3;
    BSTR bstr1 = NULL;          /* Initialize for tracking frees! */
    BSTR bstr2 = NULL;
    BSTR bstr3 = NULL;
    int tcl_status;
    void *pv;
    void *pv2;
    GUID guid, guid2;
    TYPEKIND tk;
    LPWSTR s;
    WORD w, w2;
    Tcl_Obj *objs[7];







|







1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
    } ifc;
    HRESULT hr;
    TwapiResult result;
    DWORD dw1,dw2,dw3;
    BSTR bstr1 = NULL;          /* Initialize for tracking frees! */
    BSTR bstr2 = NULL;
    BSTR bstr3 = NULL;
    int i, tcl_status;
    void *pv;
    void *pv2;
    GUID guid, guid2;
    TYPEKIND tk;
    LPWSTR s;
    WORD w, w2;
    Tcl_Obj *objs[7];
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
        case 2:
            result.type = TRT_DWORD;
            result.value.uval = ifc.unknown->lpVtbl->AddRef(ifc.unknown);
            break;
        case 3:
            if (objc < 3)
                goto badargs;
            hr = CLSIDFromString(ObjToUnicode(objv[1]), &guid);
            if (hr != S_OK)
                break;
            result.type = TRT_INTERFACE;
            result.value.ifc.name = ObjToString(objv[2]);
            hr = ifc.unknown->lpVtbl->QueryInterface(ifc.unknown, &guid,
                                                     &result.value.ifc.p);
            break;







|







2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
        case 2:
            result.type = TRT_DWORD;
            result.value.uval = ifc.unknown->lpVtbl->AddRef(ifc.unknown);
            break;
        case 3:
            if (objc < 3)
                goto badargs;
            hr = CLSIDFromString(ObjToWinChars(objv[1]), &guid);
            if (hr != S_OK)
                break;
            result.type = TRT_INTERFACE;
            result.value.ifc.name = ObjToString(objv[2]);
            hr = ifc.unknown->lpVtbl->QueryInterface(ifc.unknown, &guid,
                                                     &result.value.ifc.p);
            break;
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
            result.value.obj = ObjFromTwapiBlanket(&blanket);
            CoTaskMemFree(blanket.server);   /* Ok if NULL */
            break;
        }
    } else if (func < 200) {
        /* IDispatch */
        /* We accept both IDispatch and IDispatchEx interfaces here */
        if (ObjToIDispatch(interp, objv[0], (void **)&ifc.dispatch) != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 101:
            result.type = TRT_DWORD;
            hr = ifc.dispatch->lpVtbl->GetTypeInfoCount(ifc.dispatch, &result.value.uval);
            break;
        case 102:
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETINT(dw1), GETINT(dw2),
                             ARGEND) != TCL_OK)
                goto ret_error;








|




|
|







2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
            result.value.obj = ObjFromTwapiBlanket(&blanket);
            CoTaskMemFree(blanket.server);   /* Ok if NULL */
            break;
        }
    } else if (func < 200) {
        /* IDispatch */
        /* We accept both IDispatch and IDispatchEx interfaces here */
        if (ObjToIDispatch(interp, objv[0], (void **) &ifc.dispatch) != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 101:
            result.type = TRT_LONG;
            hr = ifc.dispatch->lpVtbl->GetTypeInfoCount(ifc.dispatch, (UINT*) &result.value.lval);
            break;
        case 102:
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETINT(dw1), GETINT(dw2),
                             ARGEND) != TCL_OK)
                goto ret_error;

2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104

2105
2106
2107
2108
2109

2110
2111

2112
2113
2114
2115
2116
2117
2118
        case 201: // GetDispID
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETVAR(bstr1, ObjToBSTR), GETINT(dw1),
                             ARGEND) != TCL_OK)
                goto ret_error;
            result.type = TRT_LONG;
            hr = ifc.dispatchex->lpVtbl->GetDispID(ifc.dispatchex, bstr1,
                                                   dw1, &result.value.ival);
            break;
        case 202: // GetMemberName
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            VariantInit(&result.value.var);
            hr = ifc.dispatchex->lpVtbl->GetMemberName(
                ifc.dispatchex, dw1, &result.value.var.bstrVal);
            if (hr == S_OK) {
                result.value.var.vt = VT_BSTR;
                result.type = TRT_VARIANT;
            }
            break;
        case 203: // GetMemberProperties
        case 204: // GetNextDispID
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETINT(dw1), GETINT(dw2),
                             ARGEND) != TCL_OK)
                goto ret_error;

            result.type = TRT_DWORD;
            if (func == 203)
                hr = ifc.dispatchex->lpVtbl->GetMemberProperties(
                    ifc.dispatchex, dw1, dw2, &result.value.uval);
            else

                hr = ifc.dispatchex->lpVtbl->GetNextDispID(
                    ifc.dispatchex, dw1, dw2, &result.value.ival);

            break;
        case 205: // GetNameSpaceParent
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IUnknown";
            hr = ifc.dispatchex->lpVtbl->GetNameSpaceParent(ifc.dispatchex,
                                                            (IUnknown **)&result.value.ifc.p);
            break;







|




|














>
|
<


|
>

|
>







2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110

2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
        case 201: // GetDispID
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETVAR(bstr1, ObjToBSTR), GETINT(dw1),
                             ARGEND) != TCL_OK)
                goto ret_error;
            result.type = TRT_LONG;
            hr = ifc.dispatchex->lpVtbl->GetDispID(ifc.dispatchex, bstr1,
                                                   dw1, &result.value.lval);
            break;
        case 202: // GetMemberName
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            VariantInit(&result.value.var);
            hr = ifc.dispatchex->lpVtbl->GetMemberName(
                ifc.dispatchex, dw1, &result.value.var.bstrVal);
            if (hr == S_OK) {
                result.value.var.vt = VT_BSTR;
                result.type = TRT_VARIANT;
            }
            break;
        case 203: // GetMemberProperties
        case 204: // GetNextDispID
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETINT(dw1), GETINT(dw2),
                             ARGEND) != TCL_OK)
                goto ret_error;
            if (func == 203) {
                result.type = TRT_DWORD;

                hr = ifc.dispatchex->lpVtbl->GetMemberProperties(
                    ifc.dispatchex, dw1, dw2, &result.value.uval);
            } else {
                result.type = TRT_LONG;
                hr = ifc.dispatchex->lpVtbl->GetNextDispID(
                    ifc.dispatchex, dw1, dw2, &result.value.lval);
            }
            break;
        case 205: // GetNameSpaceParent
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IUnknown";
            hr = ifc.dispatchex->lpVtbl->GetNameSpaceParent(ifc.dispatchex,
                                                            (IUnknown **)&result.value.ifc.p);
            break;
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159

        /* Every other method either has no params or one integer param */
        if (objc > 2)
            goto badargs;

        dw1 = 0;
        if (objc == 2)
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);

        switch (func) {
        case 301: //GetRefTypeOfImplType
            result.type = TRT_DWORD;
            hr = ifc.typeinfo->lpVtbl->GetRefTypeOfImplType(
                ifc.typeinfo, dw1, &result.value.uval);
            break;







|







2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165

        /* Every other method either has no params or one integer param */
        if (objc > 2)
            goto badargs;

        dw1 = 0;
        if (objc == 2)
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);

        switch (func) {
        case 301: //GetRefTypeOfImplType
            result.type = TRT_DWORD;
            hr = ifc.typeinfo->lpVtbl->GetRefTypeOfImplType(
                ifc.typeinfo, dw1, &result.value.uval);
            break;
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
            result.value.ifc.name = "ITypeComp";
            hr = ifc.typeinfo->lpVtbl->GetTypeComp(
                ifc.typeinfo, (ITypeComp **)&result.value.ifc.p);
            break;
        case 304: // GetContainingTypeLib
            hr = ifc.typeinfo->lpVtbl->GetContainingTypeLib(ifc.typeinfo,
                                                            (ITypeLib **) &pv,
                                                            &dw1);
            if (hr == S_OK) {
                result.type = TRT_OBJV;
                objs[0] = ObjFromOpaque(pv, "ITypeLib");
                objs[1] = ObjFromLong(dw1);
                result.value.objv.nobj = 2;
                result.value.objv.objPP = objs;
            }







|







2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
            result.value.ifc.name = "ITypeComp";
            hr = ifc.typeinfo->lpVtbl->GetTypeComp(
                ifc.typeinfo, (ITypeComp **)&result.value.ifc.p);
            break;
        case 304: // GetContainingTypeLib
            hr = ifc.typeinfo->lpVtbl->GetContainingTypeLib(ifc.typeinfo,
                                                            (ITypeLib **) &pv,
                                                            (UINT*) &dw1);
            if (hr == S_OK) {
                result.type = TRT_OBJV;
                objs[0] = ObjFromOpaque(pv, "ITypeLib");
                objs[1] = ObjFromLong(dw1);
                result.value.objv.nobj = 2;
                result.value.objv.objPP = objs;
            }
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
            != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 401: // GetDocumentation
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_OBJV;
            hr = ifc.typelib->lpVtbl->GetDocumentation(
                ifc.typelib, dw1, &bstr1, &bstr2, &dw2, &bstr3);
            if (hr == S_OK) {
                objs[0] = ObjFromBSTR(bstr1);
                objs[1] = ObjFromBSTR(bstr2);
                objs[2] = ObjFromLong(dw2);







|







2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
            != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 401: // GetDocumentation
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_OBJV;
            hr = ifc.typelib->lpVtbl->GetDocumentation(
                ifc.typelib, dw1, &bstr1, &bstr2, &dw2, &bstr3);
            if (hr == S_OK) {
                objs[0] = ObjFromBSTR(bstr1);
                objs[1] = ObjFromBSTR(bstr2);
                objs[2] = ObjFromLong(dw2);
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
            result.type = TRT_DWORD;
            result.value.uval =
                ifc.typelib->lpVtbl->GetTypeInfoCount(ifc.typelib);
            break;
        case 403: // GetTypeInfoType
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_LONG;
            hr = ifc.typelib->lpVtbl->GetTypeInfoType(ifc.typelib, dw1, &tk);
            if (hr == S_OK)
                result.value.ival = tk;
            break;
        case 404: // GetTypeInfo
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "ITypeInfo";
            hr = ifc.typelib->lpVtbl->GetTypeInfo(
                ifc.typelib, dw1, (ITypeInfo **)&result.value.ifc.p);
            break;
        case 405: // GetTypeInfoOfGuid
            if (objc != 2)
                goto badargs;
            hr = CLSIDFromString(ObjToUnicode(objv[1]), &guid);
            if (hr == S_OK) {
                result.type = TRT_INTERFACE;
                result.value.ifc.name = "ITypeInfo";
                hr = ifc.typelib->lpVtbl->GetTypeInfoOfGuid(
                    ifc.typelib, &guid,
                    (ITypeInfo **)&result.value.ifc.p);
            }
            break;
        case 406: // GetLibAttr
            return Twapi_ITypeLib_GetLibAttr(interp, ifc.typelib);

        case 407: // RegisterTypeLib
            if (objc != 3)
                goto badargs;
            s = ObjToUnicode(objv[2]);
            NULLIFY_EMPTY(s);
            result.type = TRT_EMPTY;
            hr = RegisterTypeLib(ifc.typelib, ObjToUnicode(objv[1]), s);
            break;
        }
    } else if (func < 600) {
        /* IRecordInfo */
        /* TBD - for record data, we should create dummy type-safe pointers
           instead of passing around voids even though that is what
           the IRecordInfo interface does */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.recordinfo, "IRecordInfo")
            != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 501: // GetField
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETVOIDP(pv), GETOBJ(sObj),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            VariantInit(&result.value.var);
            result.type = TRT_VARIANT;
            hr = ifc.recordinfo->lpVtbl->GetField(
                ifc.recordinfo, pv, ObjToUnicode(sObj), &result.value.var);
            break;
        case 502: // GetGuid
            if (objc != 1)
                goto badargs;
            result.type = TRT_GUID;
            hr = ifc.recordinfo->lpVtbl->GetGuid(ifc.recordinfo, &result.value.guid);
            break;







|








|








|














|


|




















|







2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
            result.type = TRT_DWORD;
            result.value.uval =
                ifc.typelib->lpVtbl->GetTypeInfoCount(ifc.typelib);
            break;
        case 403: // GetTypeInfoType
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_LONG;
            hr = ifc.typelib->lpVtbl->GetTypeInfoType(ifc.typelib, dw1, &tk);
            if (hr == S_OK)
                result.value.ival = tk;
            break;
        case 404: // GetTypeInfo
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "ITypeInfo";
            hr = ifc.typelib->lpVtbl->GetTypeInfo(
                ifc.typelib, dw1, (ITypeInfo **)&result.value.ifc.p);
            break;
        case 405: // GetTypeInfoOfGuid
            if (objc != 2)
                goto badargs;
            hr = CLSIDFromString(ObjToWinChars(objv[1]), &guid);
            if (hr == S_OK) {
                result.type = TRT_INTERFACE;
                result.value.ifc.name = "ITypeInfo";
                hr = ifc.typelib->lpVtbl->GetTypeInfoOfGuid(
                    ifc.typelib, &guid,
                    (ITypeInfo **)&result.value.ifc.p);
            }
            break;
        case 406: // GetLibAttr
            return Twapi_ITypeLib_GetLibAttr(interp, ifc.typelib);

        case 407: // RegisterTypeLib
            if (objc != 3)
                goto badargs;
            s = ObjToWinChars(objv[2]);
            NULLIFY_EMPTY(s);
            result.type = TRT_EMPTY;
            hr = RegisterTypeLib(ifc.typelib, ObjToWinChars(objv[1]), s);
            break;
        }
    } else if (func < 600) {
        /* IRecordInfo */
        /* TBD - for record data, we should create dummy type-safe pointers
           instead of passing around voids even though that is what
           the IRecordInfo interface does */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.recordinfo, "IRecordInfo")
            != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 501: // GetField
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETVOIDP(pv), GETOBJ(sObj),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            VariantInit(&result.value.var);
            result.type = TRT_VARIANT;
            hr = ifc.recordinfo->lpVtbl->GetField(
                ifc.recordinfo, pv, ObjToWinChars(sObj), &result.value.var);
            break;
        case 502: // GetGuid
            if (objc != 1)
                goto badargs;
            result.type = TRT_GUID;
            hr = ifc.recordinfo->lpVtbl->GetGuid(ifc.recordinfo, &result.value.guid);
            break;
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.enumvariant->lpVtbl->Reset(ifc.enumvariant);
            break;
        case 703: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumvariant->lpVtbl->Skip(ifc.enumvariant, dw1);
            break;
        }        
    } else if (func < 900) {
        /* IConnectionPoint */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.connectionpoint,







|







2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.enumvariant->lpVtbl->Reset(ifc.enumvariant);
            break;
        case 703: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumvariant->lpVtbl->Skip(ifc.enumvariant, dw1);
            break;
        }        
    } else if (func < 900) {
        /* IConnectionPoint */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.connectionpoint,
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
            result.value.ifc.name = "IConnectionPointContainer";
            hr = ifc.connectionpoint->lpVtbl->GetConnectionPointContainer(ifc.connectionpoint, (IConnectionPointContainer **)&result.value.ifc.p);
            break;

        case 805: // Unadvise
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.connectionpoint->lpVtbl->Unadvise(ifc.connectionpoint, dw1);
            break;
        }
    } else if (func < 1000) {
        /* IConnectionPointContainer */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.connectionpointcontainer,







|







2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
            result.value.ifc.name = "IConnectionPointContainer";
            hr = ifc.connectionpoint->lpVtbl->GetConnectionPointContainer(ifc.connectionpoint, (IConnectionPointContainer **)&result.value.ifc.p);
            break;

        case 805: // Unadvise
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.connectionpoint->lpVtbl->Unadvise(ifc.connectionpoint, dw1);
            break;
        }
    } else if (func < 1000) {
        /* IConnectionPointContainer */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.connectionpointcontainer,
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
            hr = ifc.connectionpointcontainer->lpVtbl->EnumConnectionPoints(
                ifc.connectionpointcontainer,
                (IEnumConnectionPoints **)&result.value.ifc.p);
            break;
        case 902: // FindConnectionPoint
            if (objc != 2)
                goto badargs;
            hr = CLSIDFromString(ObjToUnicode(objv[1]), &guid);
            if (hr == S_OK) {
                result.type = TRT_INTERFACE;
                result.value.ifc.name = "IConnectionPoint";
                hr = ifc.connectionpointcontainer->lpVtbl->FindConnectionPoint(
                    ifc.connectionpointcontainer,
                    &guid,
                    (IConnectionPoint **)&result.value.ifc.p);







|







2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
            hr = ifc.connectionpointcontainer->lpVtbl->EnumConnectionPoints(
                ifc.connectionpointcontainer,
                (IEnumConnectionPoints **)&result.value.ifc.p);
            break;
        case 902: // FindConnectionPoint
            if (objc != 2)
                goto badargs;
            hr = CLSIDFromString(ObjToWinChars(objv[1]), &guid);
            if (hr == S_OK) {
                result.type = TRT_INTERFACE;
                result.value.ifc.name = "IConnectionPoint";
                hr = ifc.connectionpointcontainer->lpVtbl->FindConnectionPoint(
                    ifc.connectionpointcontainer,
                    &guid,
                    (IConnectionPoint **)&result.value.ifc.p);
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
            result.type = TRT_EMPTY;
            hr = ifc.enumconnectionpoints->lpVtbl->Reset(
                ifc.enumconnectionpoints);
            break;
        case 1003: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumconnectionpoints->lpVtbl->Skip(
                ifc.enumconnectionpoints,   dw1);
            break;
        }        
    } else if (func < 1200) {
        /* IEnumConnections */







|







2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
            result.type = TRT_EMPTY;
            hr = ifc.enumconnectionpoints->lpVtbl->Reset(
                ifc.enumconnectionpoints);
            break;
        case 1003: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumconnectionpoints->lpVtbl->Skip(
                ifc.enumconnectionpoints,   dw1);
            break;
        }        
    } else if (func < 1200) {
        /* IEnumConnections */
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.enumconnections->lpVtbl->Reset(ifc.enumconnections);
            break;
        case 1103: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumconnections->lpVtbl->Skip(ifc.enumconnections, dw1);
            break;
        }        
    } else if (func == 1201) {
        /* IProvideClassInfo */
        /* We accept both IProvideClassInfo and IProvideClassInfo2 interfaces */







|







2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.enumconnections->lpVtbl->Reset(ifc.enumconnections);
            break;
        case 1103: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumconnections->lpVtbl->Skip(ifc.enumconnections, dw1);
            break;
        }        
    } else if (func == 1201) {
        /* IProvideClassInfo */
        /* We accept both IProvideClassInfo and IProvideClassInfo2 interfaces */
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.provideclassinfo2,
                        "IProvideClassInfo2")
            != TCL_OK)
            return TCL_ERROR;

        if (objc != 2)
            goto badargs;
        CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
        result.type = TRT_GUID;
        hr = ifc.provideclassinfo2->lpVtbl->GetGUID(ifc.provideclassinfo2,
                                                    dw1, &result.value.guid);
    } else if (func < 1500) {
        /* ITypeComp */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.typecomp, "ITypeComp")
            != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 1401:
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETINT(dw1), GETWORD(w),
                             ARGEND) != TCL_OK)
                goto ret_error;
            return Twapi_ITypeComp_Bind(interp, ifc.typecomp,
                                        ObjToUnicode(sObj), dw1, w);
        }
    } else if (func < 5600) {
        /* IPersistFile */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.persistfile,
                        "IPersistFile") != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 5501: // GetCurFile
            if (objc != 1)
                goto badargs;
            hr = ifc.persistfile->lpVtbl->GetCurFile(
                ifc.persistfile, &result.value.lpolestr);
            if (hr != S_OK && hr != S_FALSE)
                break;
            /* Note S_FALSE also is a success return */
            result.type = TRT_OBJV;
            objs[0] = ObjFromLong(hr);
            objs[1] = ObjFromUnicode(result.value.lpolestr);
            result.value.objv.nobj = 2;
            result.value.objv.objPP = objs;
            break;
        case 5502: // IsDirty
            if (objc != 1)
                goto badargs;
            result.type = TRT_BOOL;
            result.value.bval = ifc.persistfile->lpVtbl->IsDirty(ifc.persistfile) == S_OK;
            break;
        case 5503: // Load
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETINT(dw1),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = ifc.persistfile->lpVtbl->Load(ifc.persistfile,
                                               ObjToUnicode(sObj), dw1);
            break;
        case 5504: // Save
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETINT(dw1),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = ifc.persistfile->lpVtbl->Save(ifc.persistfile, ObjToLPWSTR_NULL_IF_EMPTY(sObj), dw1);
            break;
        case 5505: // SaveCompleted
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.persistfile->lpVtbl->SaveCompleted(
                ifc.persistfile, ObjToUnicode(objv[1]));
            break;
        }
    } else if (func < 5700) {
        /* IVixHandle */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.vixh,
                        "IVixHandle") != TCL_OK)
            return TCL_ERROR;
        switch (func) {
        case 5601: // GetHandleType
            if (objc != 1)
                goto badargs;
            hr = ifc.vixh->lpVtbl->GetHandleType(ifc.vixh, &result.value.ival);
            if (hr != S_OK)
                break;
            result.type = TRT_DWORD;
            break;
        case 5602: // GetProperties
            if (objc != 2)
                goto badargs;







|
















|


















|
















|














|











|







2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.provideclassinfo2,
                        "IProvideClassInfo2")
            != TCL_OK)
            return TCL_ERROR;

        if (objc != 2)
            goto badargs;
        CHECK_DWORD_OBJ(interp, dw1, objv[1]);
        result.type = TRT_GUID;
        hr = ifc.provideclassinfo2->lpVtbl->GetGUID(ifc.provideclassinfo2,
                                                    dw1, &result.value.guid);
    } else if (func < 1500) {
        /* ITypeComp */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.typecomp, "ITypeComp")
            != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 1401:
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETINT(dw1), GETWORD(w),
                             ARGEND) != TCL_OK)
                goto ret_error;
            return Twapi_ITypeComp_Bind(interp, ifc.typecomp,
                                        ObjToWinChars(sObj), dw1, w);
        }
    } else if (func < 5600) {
        /* IPersistFile */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.persistfile,
                        "IPersistFile") != TCL_OK)
            return TCL_ERROR;

        switch (func) {
        case 5501: // GetCurFile
            if (objc != 1)
                goto badargs;
            hr = ifc.persistfile->lpVtbl->GetCurFile(
                ifc.persistfile, &result.value.lpolestr);
            if (hr != S_OK && hr != S_FALSE)
                break;
            /* Note S_FALSE also is a success return */
            result.type = TRT_OBJV;
            objs[0] = ObjFromLong(hr);
            objs[1] = ObjFromWinChars(result.value.lpolestr);
            result.value.objv.nobj = 2;
            result.value.objv.objPP = objs;
            break;
        case 5502: // IsDirty
            if (objc != 1)
                goto badargs;
            result.type = TRT_BOOL;
            result.value.bval = ifc.persistfile->lpVtbl->IsDirty(ifc.persistfile) == S_OK;
            break;
        case 5503: // Load
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETINT(dw1),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = ifc.persistfile->lpVtbl->Load(ifc.persistfile,
                                               ObjToWinChars(sObj), dw1);
            break;
        case 5504: // Save
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETINT(dw1),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = ifc.persistfile->lpVtbl->Save(ifc.persistfile, ObjToLPWSTR_NULL_IF_EMPTY(sObj), dw1);
            break;
        case 5505: // SaveCompleted
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.persistfile->lpVtbl->SaveCompleted(
                ifc.persistfile, ObjToWinChars(objv[1]));
            break;
        }
    } else if (func < 5700) {
        /* IVixHandle */
        if (ObjToOpaque(interp, objv[0], (void **)&ifc.vixh,
                        "IVixHandle") != TCL_OK)
            return TCL_ERROR;
        switch (func) {
        case 5601: // GetHandleType
            if (objc != 1)
                goto badargs;
            hr = ifc.vixh->lpVtbl->GetHandleType(ifc.vixh, &result.value.lval);
            if (hr != S_OK)
                break;
            result.type = TRT_DWORD;
            break;
        case 5602: // GetProperties
            if (objc != 2)
                goto badargs;
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
        /* Commands that are not method calls on interfaces. These
           are here and not in twapi_calls.c because they make use
           of COM typedefs (historical, not sure that's still true) */
        switch (func) {
        case 10001: // CreateFileMoniker
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IMoniker";
            hr = CreateFileMoniker(ObjToUnicode(objv[0]),
                                   (IMoniker **)&result.value.ifc.p);
            break;
        case 10002: // CreateBindCtx
            CHECK_INTEGER_OBJ(interp, dw1, objv[0]);
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IBindCtx";
            hr = CreateBindCtx(dw1, (IBindCtx **)&result.value.ifc.p);
            break;
        case 10003: // GetRecordInfoFromGuids
            if (TwapiGetArgs(interp, objc, objv,
                             GETGUID(guid), GETINT(dw1), GETINT(dw2),







|



|







2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
        /* Commands that are not method calls on interfaces. These
           are here and not in twapi_calls.c because they make use
           of COM typedefs (historical, not sure that's still true) */
        switch (func) {
        case 10001: // CreateFileMoniker
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IMoniker";
            hr = CreateFileMoniker(ObjToWinChars(objv[0]),
                                   (IMoniker **)&result.value.ifc.p);
            break;
        case 10002: // CreateBindCtx
            CHECK_DWORD_OBJ(interp, dw1, objv[0]);
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IBindCtx";
            hr = CreateBindCtx(dw1, (IBindCtx **)&result.value.ifc.p);
            break;
        case 10003: // GetRecordInfoFromGuids
            if (TwapiGetArgs(interp, objc, objv,
                             GETGUID(guid), GETINT(dw1), GETINT(dw2),
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
            result.value.ifc.name = "ITypeLib";
            hr = LoadRegTypeLib(&guid, w, w2, dw3,
                                (ITypeLib **) &result.value.ifc.p);
            break;
        case 10007: // LoadTypeLibEx
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "ITypeLib";
            hr = LoadTypeLibEx(ObjToUnicode(objv[0]), dw1,
                                              (ITypeLib **)&result.value.ifc.p);
            break;
        case 10008: // CoGetObject
            if (TwapiGetArgs(interp, objc, objv,
                             GETOBJ(sObj), ARGSKIP, GETGUID(guid), GETASTR(cP),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (ObjListLength(interp, objv[1], &dw1) == TCL_ERROR ||
                dw1 != 0) {
                ObjSetStaticResult(interp, "Bind options are not supported for CoGetOjbect and must be specified as empty."); //TBD
                goto ret_error;
            }
            result.type = TRT_INTERFACE;
            result.value.ifc.name = cP;
            hr = CoGetObject(ObjToUnicode(sObj),
                             NULL, &guid, &result.value.ifc.p);
            break;
        case 10009: // GetActiveObject
            if (objc != 1)
                goto badargs;
            if (ObjToGUID(interp, objv[0], &guid) != TCL_OK)
                goto ret_error;







|


|







|
<





|







2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820

2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
            result.value.ifc.name = "ITypeLib";
            hr = LoadRegTypeLib(&guid, w, w2, dw3,
                                (ITypeLib **) &result.value.ifc.p);
            break;
        case 10007: // LoadTypeLibEx
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "ITypeLib";
            hr = LoadTypeLibEx(ObjToWinChars(objv[0]), dw1,
                                              (ITypeLib **)&result.value.ifc.p);
            break;
        case 10008: // CoGetObject
            if (TwapiGetArgs(interp, objc, objv,
                             GETOBJ(sObj), ARGSKIP, GETGUID(guid), GETASTR(cP),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (ObjListLength(interp, objv[1], &i) == TCL_ERROR || i != 0) {

                ObjSetStaticResult(interp, "Bind options are not supported for CoGetOjbect and must be specified as empty."); //TBD
                goto ret_error;
            }
            result.type = TRT_INTERFACE;
            result.value.ifc.name = cP;
            hr = CoGetObject(ObjToWinChars(sObj),
                             NULL, &guid, &result.value.ifc.p);
            break;
        case 10009: // GetActiveObject
            if (objc != 1)
                goto badargs;
            if (ObjToGUID(interp, objv[0], &guid) != TCL_OK)
                goto ret_error;
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
            result.type = TRT_LPOLESTR;
            hr = ProgIDFromCLSID(&guid, &result.value.lpolestr);
            break;
        case 10011:  // CLSIDFromProgID
            if (objc != 1)
                goto badargs;
            result.type = TRT_GUID;
            hr = CLSIDFromProgID(ObjToUnicode(objv[0]), &result.value.guid);
            break;
        case 10012: // UNUSED
        case 10013: // MkParseDisplayName
            if (objc != 2)
                goto badargs;
            if (ObjToOpaque(interp, objv[0], &pv, "IBindCtx") != TCL_OK)
                goto ret_error;
            hr = MkParseDisplayName(pv, ObjToUnicode(objv[1]),
                                    &dw1, &ifc.moniker);
            if (hr == S_OK || hr == MK_E_SYNTAX) {
                if (hr == MK_E_SYNTAX) {
                    ifc.moniker = 0;
                    hr = S_OK;
                }
                result.type = TRT_OBJV;
                objs[0] = ObjFromDWORD(dw1);
                objs[1] = ObjFromOpaque(ifc.moniker, "IMoniker");
                result.value.objv.nobj = 2;
                result.value.objv.objPP = objs;
            }
            break;
        case 10014: // CoRegisterClassObject
            if (TwapiGetArgs(interp, objc, objv,
                             GETGUID(guid), GETVOIDP(pv),
                             GETINT(dw1), GETINT(dw2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_DWORD;
            hr = CoRegisterClassObject(&guid, pv, dw1, dw2, &result.value.ival);
            break;
        case 10015: // CoRevokeClassObject
            if (TwapiGetArgs(interp, objc, objv,
                             GETINT(dw1), ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = CoRevokeClassObject(dw1);







|







|




















|







2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
            result.type = TRT_LPOLESTR;
            hr = ProgIDFromCLSID(&guid, &result.value.lpolestr);
            break;
        case 10011:  // CLSIDFromProgID
            if (objc != 1)
                goto badargs;
            result.type = TRT_GUID;
            hr = CLSIDFromProgID(ObjToWinChars(objv[0]), &result.value.guid);
            break;
        case 10012: // UNUSED
        case 10013: // MkParseDisplayName
            if (objc != 2)
                goto badargs;
            if (ObjToOpaque(interp, objv[0], &pv, "IBindCtx") != TCL_OK)
                goto ret_error;
            hr = MkParseDisplayName(pv, ObjToWinChars(objv[1]),
                                    &dw1, &ifc.moniker);
            if (hr == S_OK || hr == MK_E_SYNTAX) {
                if (hr == MK_E_SYNTAX) {
                    ifc.moniker = 0;
                    hr = S_OK;
                }
                result.type = TRT_OBJV;
                objs[0] = ObjFromDWORD(dw1);
                objs[1] = ObjFromOpaque(ifc.moniker, "IMoniker");
                result.value.objv.nobj = 2;
                result.value.objv.objPP = objs;
            }
            break;
        case 10014: // CoRegisterClassObject
            if (TwapiGetArgs(interp, objc, objv,
                             GETGUID(guid), GETVOIDP(pv),
                             GETINT(dw1), GETINT(dw2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_DWORD;
            hr = CoRegisterClassObject(&guid, pv, dw1, dw2, &result.value.uval);
            break;
        case 10015: // CoRevokeClassObject
            if (TwapiGetArgs(interp, objc, objv,
                             GETINT(dw1), ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = CoRevokeClassObject(dw1);
2906
2907
2908
2909
2910
2911
2912
2913
2914

2915
2916
2917
2918
2919
2920
2921
ret_error:
    tcl_status = TCL_ERROR;
    goto vamoose;
}


/* Dispatcher for calling COM methods that require a TwapiInterpContext */
static TCL_RESULT Twapi_CallCOMTicObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    void *ifc;
    int func;
    HRESULT hr;
    TwapiResult result;
    DWORD dw1,dw2;

    hr = S_OK;







|

>







2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
ret_error:
    tcl_status = TCL_ERROR;
    goto vamoose;
}


/* Dispatcher for calling COM methods that require a TwapiInterpContext */
static TCL_RESULT Twapi_CallCOMTicObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    void *ifc;
    int func;
    HRESULT hr;
    TwapiResult result;
    DWORD dw1,dw2;

    hr = S_OK;
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
        /* We accept both IDispatch and IDispatchEx interfaces here */
        if (ObjToIDispatch(interp, objv[2], &ifc) != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc != 5)
            goto badargs;
        CHECK_INTEGER_OBJ(interp, dw1, objv[4]);
        return TwapiGetIDsOfNamesHelper(
            ticP, ifc, objv[3],
            dw1,              /* LCID */
            0);             /* 0->IDispatch interface */
    case 2: /* ITypeInfo.GetIDsOfNames */
        if (ObjToOpaque(interp, objv[2], &ifc, "ITypeInfo") != TCL_OK)
            return TCL_ERROR;







|







2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
        /* We accept both IDispatch and IDispatchEx interfaces here */
        if (ObjToIDispatch(interp, objv[2], &ifc) != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc != 5)
            goto badargs;
        CHECK_DWORD_OBJ(interp, dw1, objv[4]);
        return TwapiGetIDsOfNamesHelper(
            ticP, ifc, objv[3],
            dw1,              /* LCID */
            0);             /* 0->IDispatch interface */
    case 2: /* ITypeInfo.GetIDsOfNames */
        if (ObjToOpaque(interp, objv[2], &ifc, "ITypeInfo") != TCL_OK)
            return TCL_ERROR;
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
        if (ObjToOpaque(interp, objv[2], &ifc, "IEnumVARIANT")
            != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc < 4)
            goto badargs;
        CHECK_INTEGER_OBJ(interp, dw1, objv[3]);
        /* Let caller decide if he wants flat untagged variant list
           or a tagged variant value */
        dw2 = 0;            /* By default tagged value */
        if (objc > 4)
            CHECK_INTEGER_OBJ(interp, dw2, objv[4]);
        return TwapiIEnumNextHelper(ticP,ifc,dw1,1,dw2);

    case 4: /* IEnumConnectionPoints.Next */
        if (ObjToOpaque(interp, objv[2], &ifc, "IEnumConnectionPoints") != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc != 4)
            goto badargs;
        CHECK_INTEGER_OBJ(interp, dw1, objv[3]);
        return TwapiIEnumNextHelper(ticP,ifc,
                                    dw1, 2, 0);
    case 5: /* IEnumConnections.Next */
        if (ObjToOpaque(interp, objv[2], &ifc, "IEnumConnections") != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc != 4)
            goto badargs;
        CHECK_INTEGER_OBJ(interp, dw1, objv[3]);
        return TwapiIEnumNextHelper(ticP, ifc, dw1, 0, 0);

    }

    if (hr != S_OK) {
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = hr;







|




|









|









|







2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
        if (ObjToOpaque(interp, objv[2], &ifc, "IEnumVARIANT")
            != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc < 4)
            goto badargs;
        CHECK_DWORD_OBJ(interp, dw1, objv[3]);
        /* Let caller decide if he wants flat untagged variant list
           or a tagged variant value */
        dw2 = 0;            /* By default tagged value */
        if (objc > 4)
            CHECK_DWORD_OBJ(interp, dw2, objv[4]);
        return TwapiIEnumNextHelper(ticP,ifc,dw1,1,dw2);

    case 4: /* IEnumConnectionPoints.Next */
        if (ObjToOpaque(interp, objv[2], &ifc, "IEnumConnectionPoints") != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc != 4)
            goto badargs;
        CHECK_DWORD_OBJ(interp, dw1, objv[3]);
        return TwapiIEnumNextHelper(ticP,ifc,
                                    dw1, 2, 0);
    case 5: /* IEnumConnections.Next */
        if (ObjToOpaque(interp, objv[2], &ifc, "IEnumConnections") != TCL_OK)
            return TCL_ERROR;
        if (ifc == NULL)
            goto null_interface_error;
        if (objc != 4)
            goto badargs;
        CHECK_DWORD_OBJ(interp, dw1, objv[3]);
        return TwapiIEnumNextHelper(ticP, ifc, dw1, 0, 0);

    }

    if (hr != S_OK) {
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = hr;
Changes to undroid/twapi/twapi/com/comserver.c.
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

    if (ObjGetElements(NULL, me->memids, &nobjs, &objs) != TCL_OK ||
        (nobjs & 1) != 0)
        return E_NOTIMPL;            /* Should not happen */

    for (i = 1; i < nobjs; i += 2) {
        int memid;
        if (lstrcmpiW(name, ObjToUnicode(objs[i])) == 0) {
            if (ObjToInt(NULL, objs[i-1], &memid) != TCL_OK)
                return E_NOTIMPL;        /* Should not happen */
            *idP = memid;
            return S_OK;
        }
    }








|







166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

    if (ObjGetElements(NULL, me->memids, &nobjs, &objs) != TCL_OK ||
        (nobjs & 1) != 0)
        return E_NOTIMPL;            /* Should not happen */

    for (i = 1; i < nobjs; i += 2) {
        int memid;
        if (lstrcmpiW(name, ObjToWinChars(objs[i])) == 0) {
            if (ObjToInt(NULL, objs[i-1], &memid) != TCL_OK)
                return E_NOTIMPL;        /* Should not happen */
            *idP = memid;
            return S_OK;
        }
    }

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    if (me->ticP->thread != Tcl_GetCurrentThread())
        Tcl_Panic("Twapi_ComServer_Invoke called from non-interpreter thread");

    interp = me->ticP->interp;
    if (Tcl_InterpDeleted(interp))
        return E_POINTER;

    ObjToUnicodeCleanup();

    if (ObjGetElements(NULL, me->cmd, &cmdobjc, &cmdprefixv) != TCL_OK) {
        /* Internal error - should not happen. Should we log background error?*/
        return E_FAIL;
    }

    if (flags == DISPATCH_PROPERTYPUTREF) {
        /* TBD - better error code */







<
<







315
316
317
318
319
320
321


322
323
324
325
326
327
328
    if (me->ticP->thread != Tcl_GetCurrentThread())
        Tcl_Panic("Twapi_ComServer_Invoke called from non-interpreter thread");

    interp = me->ticP->interp;
    if (Tcl_InterpDeleted(interp))
        return E_POINTER;



    if (ObjGetElements(NULL, me->cmd, &cmdobjc, &cmdprefixv) != TCL_OK) {
        /* Internal error - should not happen. Should we log background error?*/
        return E_FAIL;
    }

    if (flags == DISPATCH_PROPERTYPUTREF) {
        /* TBD - better error code */
455
456
457
458
459
460
461
462
463
464
465
466

467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
}

/*
 * Called from a script create an automation object.
 * Returns the IDispatch interface.
 */
int Twapi_ComServerObjCmd(
    TwapiInterpContext *ticP,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{

    Twapi_ComServer *comserverP;
    IID iid;
    HRESULT hr;
    Tcl_Obj **memidObjs;
    int i, nmemids;

    TWAPI_ASSERT(ticP->interp == interp);

    ObjToUnicodeCleanup();

    if (objc != 4) {
        Tcl_WrongNumArgs(interp, 1, objv, "IID MEMIDMAP CMD");
        return TCL_ERROR;
    }

    hr = IIDFromString(ObjToUnicode(objv[1]), &iid);
    if (FAILED(hr))
        return Twapi_AppendSystemError(interp, hr);

    if (ObjGetElements(interp, objv[2], &nmemids, &memidObjs) != TCL_OK)
        return TCL_ERROR;
    if (nmemids & 1)
        goto invalid_memids;    /* Need even number of elements */







|




>








<
<




|
|







453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473


474
475
476
477
478
479
480
481
482
483
484
485
486
}

/*
 * Called from a script create an automation object.
 * Returns the IDispatch interface.
 */
int Twapi_ComServerObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Twapi_ComServer *comserverP;
    IID iid;
    HRESULT hr;
    Tcl_Obj **memidObjs;
    int i, nmemids;

    TWAPI_ASSERT(ticP->interp == interp);



    if (objc != 4) {
        Tcl_WrongNumArgs(interp, 1, objv, "IID MEMIDMAP CMD");
        return TCL_ERROR;
    }
    
    hr = IIDFromString(ObjToWinChars(objv[1]), &iid);
    if (FAILED(hr))
        return Twapi_AppendSystemError(interp, hr);

    if (ObjGetElements(interp, objv[2], &nmemids, &memidObjs) != TCL_OK)
        return TCL_ERROR;
    if (nmemids & 1)
        goto invalid_memids;    /* Need even number of elements */
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
    if (me->ticP->thread != Tcl_GetCurrentThread())
        Tcl_Panic("Twapi_ClassFactory_CreateInstance called from non-interpreter thread");

    interp = me->ticP->interp;
    if (Tcl_InterpDeleted(interp))
        return E_POINTER;

    ObjToUnicodeCleanup();

    if (ObjGetElements(NULL, me->cmd, &cmdobjc, &cmdprefixv) != TCL_OK) {
        /* Internal error - were invalid command. Should we log background error?*/
        return E_FAIL;
    }

    /*
     * Before eval'ing, addref ourselves so we don't get deleted in a







<
<







591
592
593
594
595
596
597


598
599
600
601
602
603
604
    if (me->ticP->thread != Tcl_GetCurrentThread())
        Tcl_Panic("Twapi_ClassFactory_CreateInstance called from non-interpreter thread");

    interp = me->ticP->interp;
    if (Tcl_InterpDeleted(interp))
        return E_POINTER;



    if (ObjGetElements(NULL, me->cmd, &cmdobjc, &cmdprefixv) != TCL_OK) {
        /* Internal error - were invalid command. Should we log background error?*/
        return E_FAIL;
    }

    /*
     * Before eval'ing, addref ourselves so we don't get deleted in a
686
687
688
689
690
691
692
693
694
695
696
697

698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
}

/*
 * Called from a script create a class factory
 * Returns the IClassFactory interface.
 */
int Twapi_ClassFactoryObjCmd(
    TwapiInterpContext *ticP,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{

    Twapi_ClassFactory *cfP;
    CLSID clsid;
    HRESULT hr;

    TWAPI_ASSERT(ticP->interp == interp);

    ObjToUnicodeCleanup();

    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 1, objv, "IID CMD");
        return TCL_ERROR;
    }

    hr = CLSIDFromString(ObjToUnicode(objv[1]), &clsid);
    if (FAILED(hr))
        return Twapi_AppendSystemError(interp, hr);

    /* Memory is freed when the object is released */
    cfP = TwapiAlloc(sizeof(*cfP));

    /* Fill in the cmdargs slots from the arguments */







|




>






<
<




|
|







681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699


700
701
702
703
704
705
706
707
708
709
710
711
712
}

/*
 * Called from a script create a class factory
 * Returns the IClassFactory interface.
 */
int Twapi_ClassFactoryObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Twapi_ClassFactory *cfP;
    CLSID clsid;
    HRESULT hr;

    TWAPI_ASSERT(ticP->interp == interp);



    if (objc != 3) {
        Tcl_WrongNumArgs(interp, 1, objv, "IID CMD");
        return TCL_ERROR;
    }
    
    hr = CLSIDFromString(ObjToWinChars(objv[1]), &clsid);
    if (FAILED(hr))
        return Twapi_AppendSystemError(interp, hr);

    /* Memory is freed when the object is released */
    cfP = TwapiAlloc(sizeof(*cfP));

    /* Fill in the cmdargs slots from the arguments */
Changes to undroid/twapi/twapi/com/twapi_com.h.
78
79
80
81
82
83
84
85
86
87
88
89

interface IVixHandle
{
    CONST_VTBL struct IVixHandleVtbl *lpVtbl;
};


int Twapi_ComServerObjCmd(TwapiInterpContext *, Tcl_Interp *, int, Tcl_Obj *CONST objv[]);
int Twapi_ClassFactoryObjCmd(TwapiInterpContext *, Tcl_Interp *, int, Tcl_Obj *CONST objv[]);


#endif







|
|



78
79
80
81
82
83
84
85
86
87
88
89

interface IVixHandle
{
    CONST_VTBL struct IVixHandleVtbl *lpVtbl;
};


TwapiTclObjCmd Twapi_ComServerObjCmd;
TwapiTclObjCmd Twapi_ClassFactoryObjCmd;


#endif
Changes to undroid/twapi/twapi/console/console.c.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    if (ObjGetElements(interp, obj, &objc, &objv) != TCL_OK ||
        objc != 2 ||
        ObjToInt(interp, objv[1], &i) != TCL_OK) {
        ObjSetStaticResult(interp, "Invalid CHAR_INFO structure.");
        return TCL_ERROR;
    }

    ciP->Char.UnicodeChar = * ObjToUnicode(objv[0]);
    ciP->Attributes = (WORD) i;
    return TCL_OK;
}

static int ObjToCOORD(Tcl_Interp *interp, Tcl_Obj *coordObj, COORD *coordP)
{
    int objc, x, y;







|







26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    if (ObjGetElements(interp, obj, &objc, &objv) != TCL_OK ||
        objc != 2 ||
        ObjToInt(interp, objv[1], &i) != TCL_OK) {
        ObjSetStaticResult(interp, "Invalid CHAR_INFO structure.");
        return TCL_ERROR;
    }

    ciP->Char.UnicodeChar = * ObjToWinChars(objv[0]);
    ciP->Attributes = (WORD) i;
    return TCL_OK;
}

static int ObjToCOORD(Tcl_Interp *interp, Tcl_Obj *coordObj, COORD *coordP)
{
    int objc, x, y;
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    switch (recP->EventType) {
    case KEY_EVENT:
        objs[0] = ObjFromBoolean(recP->Event.KeyEvent.bKeyDown);
        objs[1] = ObjFromInt(recP->Event.KeyEvent.wRepeatCount);
        objs[2] = ObjFromInt(recP->Event.KeyEvent.wVirtualKeyCode);
        objs[3] = ObjFromInt(recP->Event.KeyEvent.wVirtualScanCode);
        if (recP->Event.KeyEvent.uChar.UnicodeChar)
            objs[4] = ObjFromUnicodeN(&recP->Event.KeyEvent.uChar.UnicodeChar, 1);
        else
            objs[4] = ObjFromEmptyString();
        objs[5] = ObjFromDWORD(recP->Event.KeyEvent.dwControlKeyState);
        recObj = ObjNewList(6, objs);
        break;

    case MOUSE_EVENT:







|







134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    switch (recP->EventType) {
    case KEY_EVENT:
        objs[0] = ObjFromBoolean(recP->Event.KeyEvent.bKeyDown);
        objs[1] = ObjFromInt(recP->Event.KeyEvent.wRepeatCount);
        objs[2] = ObjFromInt(recP->Event.KeyEvent.wVirtualKeyCode);
        objs[3] = ObjFromInt(recP->Event.KeyEvent.wVirtualScanCode);
        if (recP->Event.KeyEvent.uChar.UnicodeChar)
            objs[4] = ObjFromWinCharsN(&recP->Event.KeyEvent.uChar.UnicodeChar, 1);
        else
            objs[4] = ObjFromEmptyString();
        objs[5] = ObjFromDWORD(recP->Event.KeyEvent.dwControlKeyState);
        recObj = ObjNewList(6, objs);
        break;

    case MOUSE_EVENT:
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        break;

    case FOCUS_EVENT:
        recObj = ObjFromBoolean(recP->Event.FocusEvent.bSetFocus);
        break;
        
    default:
        recObj = ObjFromByteArray((const char *)recP, sizeof(*recP));
        break;
    }

    objs[0] = ObjFromInt(recP->EventType);
    objs[1] = recObj;

    return ObjNewList(2, objs);







|







164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        break;

    case FOCUS_EVENT:
        recObj = ObjFromBoolean(recP->Event.FocusEvent.bSetFocus);
        break;
        
    default:
        recObj = ObjFromByteArray((BYTE *)recP, sizeof(*recP));
        break;
    }

    objs[0] = ObjFromInt(recP->EventType);
    objs[1] = recObj;

    return ObjNewList(2, objs);
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

    if (numchars > ARRAYSIZE(buf))
        bufP = SWSPushFrame(numchars * sizeof(WCHAR), NULL);
    else
        bufP = buf;

    if (ReadConsoleW(conh, bufP, numchars, &len, NULL)) {
        ObjSetResult(interp, ObjFromUnicodeN(bufP, len));
        status = TCL_OK;
    } else {
        TwapiReturnSystemError(interp);
        status = TCL_ERROR;
    }

    if (bufP != buf)







|







187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

    if (numchars > ARRAYSIZE(buf))
        bufP = SWSPushFrame(numchars * sizeof(WCHAR), NULL);
    else
        bufP = buf;

    if (ReadConsoleW(conh, bufP, numchars, &len, NULL)) {
        ObjSetResult(interp, ObjFromWinCharsN(bufP, len));
        status = TCL_OK;
    } else {
        TwapiReturnSystemError(interp);
        status = TCL_ERROR;
    }

    if (bufP != buf)
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    Tcl_Obj *objs[3];

    /*
     * Note - event if interp is gone, we let TwapiEvalAndUpdateCallback
     * deal with it.
     */

    ObjToUnicodeCleanup();

    switch (cbP->clientdata) {
    case CTRL_C_EVENT:
        event_str = "ctrl-c";
        break;
    case CTRL_BREAK_EVENT:
        event_str = "ctrl-break";
        break;







<
<







210
211
212
213
214
215
216


217
218
219
220
221
222
223
    Tcl_Obj *objs[3];

    /*
     * Note - event if interp is gone, we let TwapiEvalAndUpdateCallback
     * deal with it.
     */



    switch (cbP->clientdata) {
    case CTRL_C_EVENT:
        event_str = "ctrl-c";
        break;
    case CTRL_BREAK_EVENT:
        event_str = "ctrl-break";
        break;
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321

322
323
324
325
326
327
328
329
330
331
332
}

static int Twapi_StartConsoleEventNotifier(TwapiInterpContext *ticP)
{
    void *pv;

    ERROR_IF_UNTHREADED(ticP->interp);
    pv = InterlockedCompareExchangePointer(&console_control_ticP,
                                           ticP, NULL);

    ObjToUnicodeCleanup();

    if (pv) {
        ObjSetStaticResult(ticP->interp, "Console control handler is already set.");
        return TCL_ERROR;
    }

    if (SetConsoleCtrlHandler(TwapiConsoleCtrlHandler, TRUE)) {
        ticP->module.data.ival = 1; /* Indicates console is hooked in this interp */
        TwapiInterpContextRef(ticP, 1);
        return TCL_OK;
    }
    else {
        InterlockedExchangePointer(&console_control_ticP, NULL);
        return TwapiReturnSystemError(ticP->interp);
    }
}

    
static int Twapi_StopConsoleEventNotifier(TwapiInterpContext *ticP)
{
    void *pv;
    pv = InterlockedCompareExchangePointer(&console_control_ticP,
                                           NULL, ticP);
    if (pv != (void*) ticP) {
        ObjSetStaticResult(ticP->interp, "Console control handler not set by this interpreter.");
        return TCL_ERROR;
    }
    SetConsoleCtrlHandler(TwapiConsoleCtrlHandler, FALSE);
    ticP->module.data.ival = 0; /* Indicates console is not hooked in this interp */

    TwapiInterpContextUnref(ticP, 1);
    return TCL_OK;
}

static int Twapi_ConsoleEventNotifierObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    int func;

    ObjToUnicodeCleanup();

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);
    
    if (func)
        return Twapi_StartConsoleEventNotifier(ticP);
    else







|

<
<
<











|








|












|

>


<
<







273
274
275
276
277
278
279
280
281



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319


320
321
322
323
324
325
326
}

static int Twapi_StartConsoleEventNotifier(TwapiInterpContext *ticP)
{
    void *pv;

    ERROR_IF_UNTHREADED(ticP->interp);
    pv = InterlockedCompareExchangePointer((void * volatile *) &console_control_ticP,
                                           ticP, NULL);



    if (pv) {
        ObjSetStaticResult(ticP->interp, "Console control handler is already set.");
        return TCL_ERROR;
    }

    if (SetConsoleCtrlHandler(TwapiConsoleCtrlHandler, TRUE)) {
        ticP->module.data.ival = 1; /* Indicates console is hooked in this interp */
        TwapiInterpContextRef(ticP, 1);
        return TCL_OK;
    }
    else {
        InterlockedExchangePointer((void * volatile *)&console_control_ticP, NULL);
        return TwapiReturnSystemError(ticP->interp);
    }
}

    
static int Twapi_StopConsoleEventNotifier(TwapiInterpContext *ticP)
{
    void *pv;
    pv = InterlockedCompareExchangePointer((void * volatile *) &console_control_ticP,
                                           NULL, ticP);
    if (pv != (void*) ticP) {
        ObjSetStaticResult(ticP->interp, "Console control handler not set by this interpreter.");
        return TCL_ERROR;
    }
    SetConsoleCtrlHandler(TwapiConsoleCtrlHandler, FALSE);
    ticP->module.data.ival = 0; /* Indicates console is not hooked in this interp */

    TwapiInterpContextUnref(ticP, 1);
    return TCL_OK;
}

static int Twapi_ConsoleEventNotifierObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int func;



    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);
    
    if (func)
        return Twapi_StartConsoleEventNotifier(ticP);
    else
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    HANDLE h;
    WORD w;
    int func = PtrToInt(clientdata);
    TwapiResult result;
    Tcl_Obj *sObj;
    LPWSTR s;
    SWSMark mark = NULL;

    ObjToUnicodeCleanup();
    
    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {







|
<







348
349
350
351
352
353
354
355

356
357
358
359
360
361
362
    HANDLE h;
    WORD w;
    int func = PtrToInt(clientdata);
    TwapiResult result;
    Tcl_Obj *sObj;
    LPWSTR s;
    SWSMark mark = NULL;
    int i;

    
    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
            result.type = result.value.hwin ? TRT_HWND : TRT_GETLASTERROR;
            break;
        }
    } else if (func < 200) {
        /* First arg integer, maybe two more */
        if (objc == 0)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        switch (func) {
        case 100:
            result.value.ival = AttachConsole(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 101:
            result.value.ival = SetConsoleCP(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 102:
            result.value.ival = SetConsoleOutputCP(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 103:
            if (objc != 2)
                return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
            CHECK_INTEGER_OBJ(interp, dw2, objv[1]);
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = GenerateConsoleCtrlEvent(dw, dw2);
            break;
        }
    } else if (func < 300) {
        /* A single handle arguments */
        if (objc != 1)







|
















|







397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
            result.type = result.value.hwin ? TRT_HWND : TRT_GETLASTERROR;
            break;
        }
    } else if (func < 200) {
        /* First arg integer, maybe two more */
        if (objc == 0)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        switch (func) {
        case 100:
            result.value.ival = AttachConsole(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 101:
            result.value.ival = SetConsoleCP(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 102:
            result.value.ival = SetConsoleOutputCP(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 103:
            if (objc != 2)
                return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
            CHECK_DWORD_OBJ(interp, dw2, objv[1]);
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = GenerateConsoleCtrlEvent(dw, dw2);
            break;
        }
    } else if (func < 300) {
        /* A single handle arguments */
        if (objc != 1)
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
            break;
        case 1004:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETOBJ(sObj),
                             GETVAR(coord, ObjToCOORD),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            s = ObjToUnicodeN(sObj, &dw);
            if (WriteConsoleOutputCharacterW(h, s,
                                             dw, coord, &result.value.uval))
                result.type = TRT_DWORD;
            else
                result.type = TRT_GETLASTERROR;    
            break;
        case 1005: // SetConsoleCursorPosition
        case 1006: // SetConsoleScreenBufferSize
            if (TwapiGetArgs(interp, objc, objv,







|

|







503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
            break;
        case 1004:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETOBJ(sObj),
                             GETVAR(coord, ObjToCOORD),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            s = ObjToWinCharsN(sObj, &i);
            if (WriteConsoleOutputCharacterW(h, s,
                                             i, coord, &result.value.uval))
                result.type = TRT_DWORD;
            else
                result.type = TRT_GETLASTERROR;    
            break;
        case 1005: // SetConsoleCursorPosition
        case 1006: // SetConsoleScreenBufferSize
            if (TwapiGetArgs(interp, objc, objv,
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_HANDLE;
            result.value.hval = CreateConsoleScreenBuffer(dw, dw2, secattrP, dw3, NULL);
            break;
        case 1008:
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = SetConsoleTitleW(ObjToUnicode(objv[0]));
            break;
        case 1009:
        case 1010:
        case 1011:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETINT(dw), ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (func == 1011)
                return Twapi_ReadConsole(interp, h, dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival =
                func == 1009 ? SetConsoleMode(h, dw) : SetConsoleTextAttribute(h, (WORD) dw);
            break;
        case 1012:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETOBJ(sObj),
                             ARGUSEDEFAULT, GETINT(dw), ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (WriteConsoleW(h, ObjToUnicode(sObj),
                              dw, &result.value.uval, NULL))
                result.type = TRT_DWORD;
            else
                result.type = TRT_GETLASTERROR;
            break;
        case 1013:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETOBJ(sObj),
                             GETINT(dw), ARGSKIP, ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (ObjToCOORD(interp, objv[3], &coord) != TCL_OK)
                return TCL_ERROR;
            if (FillConsoleOutputCharacterW(h, *ObjToUnicode(sObj), dw, coord, &result.value.uval))
                result.type = TRT_DWORD;
            else
                result.type = TRT_GETLASTERROR;
            break;
        case 1014: 
        case 1015:
            if (TwapiGetArgs(interp, objc, objv,







|


















|












|







535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_HANDLE;
            result.value.hval = CreateConsoleScreenBuffer(dw, dw2, secattrP, dw3, NULL);
            break;
        case 1008:
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = SetConsoleTitleW(ObjToWinChars(objv[0]));
            break;
        case 1009:
        case 1010:
        case 1011:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETINT(dw), ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (func == 1011)
                return Twapi_ReadConsole(interp, h, dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival =
                func == 1009 ? SetConsoleMode(h, dw) : SetConsoleTextAttribute(h, (WORD) dw);
            break;
        case 1012:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETOBJ(sObj),
                             ARGUSEDEFAULT, GETINT(dw), ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (WriteConsoleW(h, ObjToWinChars(sObj),
                              dw, &result.value.uval, NULL))
                result.type = TRT_DWORD;
            else
                result.type = TRT_GETLASTERROR;
            break;
        case 1013:
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLE(h), GETOBJ(sObj),
                             GETINT(dw), ARGSKIP, ARGEND) != TCL_OK)
                return TCL_ERROR;
            if (ObjToCOORD(interp, objv[3], &coord) != TCL_OK)
                return TCL_ERROR;
            if (FillConsoleOutputCharacterW(h, *ObjToWinChars(sObj), dw, coord, &result.value.uval))
                result.type = TRT_DWORD;
            else
                result.type = TRT_GETLASTERROR;
            break;
        case 1014: 
        case 1015:
            if (TwapiGetArgs(interp, objc, objv,
Changes to undroid/twapi/twapi/crypto/crypto.c.
225
226
227
228
229
230
231
232
233
234
235
236
237

238
239
240
241
242
243
244

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    if (len == 0)
        return ObjFromEmptyString();
    if (len > ARRAYSIZE(buf))
        wP = SWSPushFrame(len*sizeof(WCHAR), NULL);
    else
        wP = buf;
    len = CertNameToStrW(X509_ASN_ENCODING, blobP, flags, wP, len) - 1;
    objP = ObjFromUnicodeN(wP, len);
    if (wP != buf)
        SWSPopFrame();
    return objP;
}


static Tcl_Obj *ObjFromCERT_NAME_VALUE(CERT_NAME_VALUE *valP)
{
    Tcl_Obj *objs[2];
    objs[0] = ObjFromDWORD(valP->dwValueType);
    objs[1] = ObjFromCRYPT_BLOB(&valP->Value);
    return ObjNewList(2, objs);
}


static Tcl_Obj *ObjFromCERT_NAME_VALUE_Unicode(CERT_NAME_VALUE *valP)
{
    Tcl_Obj *objs[2];
    objs[0] = ObjFromDWORD(valP->dwValueType);
    objs[1] = ObjFromUnicodeN((WCHAR *)valP->Value.pbData, valP->Value.cbData/sizeof(WCHAR));
    return ObjNewList(2, objs);
}

static Tcl_Obj *ObjFromCERT_ALT_NAME_ENTRY(CERT_ALT_NAME_ENTRY *caneP)
{
    Tcl_Obj *objs[2];
    int nobjs;

    nobjs = 2;
    switch (caneP->dwAltNameChoice) {
    case CERT_ALT_NAME_RFC822_NAME: /* FALLTHRU */
    case CERT_ALT_NAME_DNS_NAME:    /* FALLTHRU */
    case CERT_ALT_NAME_URL:
        objs[1] = ObjFromUnicode(caneP->pwszURL);
        break;
    case CERT_ALT_NAME_OTHER_NAME:
        objs[0] = ObjFromString(caneP->pOtherName->pszObjId);
        objs[1] = ObjFromByteArray(caneP->pOtherName->Value.pbData,
                                   caneP->pOtherName->Value.cbData);
        objs[1] = ObjNewList(2, objs);
        break;







|





>







>

|



|













|







225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    if (len == 0)
        return ObjFromEmptyString();
    if (len > ARRAYSIZE(buf))
        wP = SWSPushFrame(len*sizeof(WCHAR), NULL);
    else
        wP = buf;
    len = CertNameToStrW(X509_ASN_ENCODING, blobP, flags, wP, len) - 1;
    objP = ObjFromWinCharsN(wP, len);
    if (wP != buf)
        SWSPopFrame();
    return objP;
}

#ifdef NOTUSED
static Tcl_Obj *ObjFromCERT_NAME_VALUE(CERT_NAME_VALUE *valP)
{
    Tcl_Obj *objs[2];
    objs[0] = ObjFromDWORD(valP->dwValueType);
    objs[1] = ObjFromCRYPT_BLOB(&valP->Value);
    return ObjNewList(2, objs);
}
#endif

static Tcl_Obj *ObjFromCERT_NAME_VALUE_WinChars(CERT_NAME_VALUE *valP)
{
    Tcl_Obj *objs[2];
    objs[0] = ObjFromDWORD(valP->dwValueType);
    objs[1] = ObjFromWinCharsN((WCHAR *)valP->Value.pbData, valP->Value.cbData/sizeof(WCHAR));
    return ObjNewList(2, objs);
}

static Tcl_Obj *ObjFromCERT_ALT_NAME_ENTRY(CERT_ALT_NAME_ENTRY *caneP)
{
    Tcl_Obj *objs[2];
    int nobjs;

    nobjs = 2;
    switch (caneP->dwAltNameChoice) {
    case CERT_ALT_NAME_RFC822_NAME: /* FALLTHRU */
    case CERT_ALT_NAME_DNS_NAME:    /* FALLTHRU */
    case CERT_ALT_NAME_URL:
        objs[1] = ObjFromWinChars(caneP->pwszURL);
        break;
    case CERT_ALT_NAME_OTHER_NAME:
        objs[0] = ObjFromString(caneP->pOtherName->pszObjId);
        objs[1] = ObjFromByteArray(caneP->pOtherName->Value.pbData,
                                   caneP->pOtherName->Value.cbData);
        objs[1] = ObjNewList(2, objs);
        break;
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
}

static Tcl_Obj *ObjFromCRYPT_KEY_PROV_INFO(CRYPT_KEY_PROV_INFO *infP)
{
    Tcl_Obj *objs[6];
    DWORD i;
    
    objs[0] = ObjFromUnicode(infP->pwszContainerName);
    objs[1] = ObjFromUnicode(infP->pwszProvName);
    objs[2] = ObjFromDWORD(infP->dwProvType);
    objs[3] = ObjFromDWORD(infP->dwFlags);
    objs[4] = ObjNewList(infP->cProvParam, NULL);
    objs[5] = ObjFromDWORD(infP->dwKeySpec);
    
    if (infP->rgProvParam) {
        for (i=0; i < infP->cProvParam; ++i) {







|
|







301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
}

static Tcl_Obj *ObjFromCRYPT_KEY_PROV_INFO(CRYPT_KEY_PROV_INFO *infP)
{
    Tcl_Obj *objs[6];
    DWORD i;
    
    objs[0] = ObjFromWinChars(infP->pwszContainerName);
    objs[1] = ObjFromWinChars(infP->pwszProvName);
    objs[2] = ObjFromDWORD(infP->dwProvType);
    objs[3] = ObjFromDWORD(infP->dwFlags);
    objs[4] = ObjNewList(infP->cProvParam, NULL);
    objs[5] = ObjFromDWORD(infP->dwKeySpec);
    
    if (infP->rgProvParam) {
        for (i=0; i < infP->cProvParam; ++i) {
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
}

static Tcl_Obj *ObjFromCRYPT_OID_INFO(PCCRYPT_OID_INFO coiP)
{
    Tcl_Obj *objs[5];

    objs[0] = ObjFromString(coiP->pszOID);
    objs[1] = ObjFromUnicode(coiP->pwszName);
    objs[2] = ObjFromDWORD(coiP->dwGroupId);
    objs[3] = ObjFromDWORD(coiP->dwValue);
    objs[4] = ObjFromCRYPT_BLOB(&coiP->ExtraInfo);

    return ObjNewList(5, objs);
}








|







354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
}

static Tcl_Obj *ObjFromCRYPT_OID_INFO(PCCRYPT_OID_INFO coiP)
{
    Tcl_Obj *objs[5];

    objs[0] = ObjFromString(coiP->pszOID);
    objs[1] = ObjFromWinChars(coiP->pwszName);
    objs[2] = ObjFromDWORD(coiP->dwGroupId);
    objs[3] = ObjFromDWORD(coiP->dwValue);
    objs[4] = ObjFromCRYPT_BLOB(&coiP->ExtraInfo);

    return ObjNewList(5, objs);
}

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410

411
412
413
414
415
416
417
    objs[3] = ObjNewList(criP->cAttribute, NULL);
    for (i = 0; i < criP->cAttribute; ++i) {
        ObjAppendElement(NULL, objs[3], ObjFromCRYPT_ATTRIBUTE(&criP->rgAttribute[i]));
    }
    return ObjNewList(4, objs);
}


static Tcl_Obj *ObjFromCERT_TRUST_STATUS(const CERT_TRUST_STATUS *ctsP)
{
    Tcl_Obj *objs[2];
    objs[0] = ObjFromDWORD(ctsP->dwErrorStatus);
    objs[1] = ObjFromDWORD(ctsP->dwInfoStatus);
    return ObjNewList(2, objs);
}


static Tcl_Obj *ObjFromCERT_CHAIN_ELEMENT(Tcl_Interp *interp, CERT_CHAIN_ELEMENT *cceP)
{
    Tcl_Obj *objs[14];
    int nobjs;
    PCCERT_CONTEXT certP;








|







>







398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
    objs[3] = ObjNewList(criP->cAttribute, NULL);
    for (i = 0; i < criP->cAttribute; ++i) {
        ObjAppendElement(NULL, objs[3], ObjFromCRYPT_ATTRIBUTE(&criP->rgAttribute[i]));
    }
    return ObjNewList(4, objs);
}

#ifdef NOTUSED
static Tcl_Obj *ObjFromCERT_TRUST_STATUS(const CERT_TRUST_STATUS *ctsP)
{
    Tcl_Obj *objs[2];
    objs[0] = ObjFromDWORD(ctsP->dwErrorStatus);
    objs[1] = ObjFromDWORD(ctsP->dwInfoStatus);
    return ObjNewList(2, objs);
}
#endif

static Tcl_Obj *ObjFromCERT_CHAIN_ELEMENT(Tcl_Interp *interp, CERT_CHAIN_ELEMENT *cceP)
{
    Tcl_Obj *objs[14];
    int nobjs;
    PCCERT_CONTEXT certP;

434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    }
    if (cceP->pApplicationUsage) {
        objs[nobjs++] = STRING_LITERAL_OBJ("application_usage");
        objs[nobjs++] = ObjFromCERT_ENHKEY_USAGE(cceP->pApplicationUsage);
    }
    if (cceP->pwszExtendedErrorInfo) {
        objs[nobjs++] = STRING_LITERAL_OBJ("extended_error");
        objs[nobjs++] = ObjFromUnicode(cceP->pwszExtendedErrorInfo);
    }
    TWAPI_ASSERT(nobjs <= ARRAYSIZE(objs));
    return ObjNewList(nobjs, objs);
}

static Tcl_Obj *ObjFromCERT_SIMPLE_CHAIN(Tcl_Interp *interp,
                                         CERT_SIMPLE_CHAIN *cscP)







|







437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    }
    if (cceP->pApplicationUsage) {
        objs[nobjs++] = STRING_LITERAL_OBJ("application_usage");
        objs[nobjs++] = ObjFromCERT_ENHKEY_USAGE(cceP->pApplicationUsage);
    }
    if (cceP->pwszExtendedErrorInfo) {
        objs[nobjs++] = STRING_LITERAL_OBJ("extended_error");
        objs[nobjs++] = ObjFromWinChars(cceP->pwszExtendedErrorInfo);
    }
    TWAPI_ASSERT(nobjs <= ARRAYSIZE(objs));
    return ObjNewList(nobjs, objs);
}

static Tcl_Obj *ObjFromCERT_SIMPLE_CHAIN(Tcl_Interp *interp,
                                         CERT_SIMPLE_CHAIN *cscP)
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
    return ObjNewList(ARRAYSIZE(objs), objs);
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParsePCERT_CONTEXT_Array(
    TwapiInterpContext *ticP,
    Tcl_Obj *certsObj,
    int *countP,
    PCCERT_CONTEXT **arrP
    )
{
    Tcl_Obj **objs;
    int nobjs, i;
    PCERT_CONTEXT *certsPP;
    if (ObjGetElements(ticP->interp, certsObj, &nobjs, &objs) != TCL_OK)
        return TCL_ERROR;
    if (nobjs == 0)
        *arrP = NULL;
    else {
        certsPP = MemLifoAlloc(ticP->memlifoP, nobjs*sizeof(*certsPP), NULL);
        for (i = 0; i < nobjs; ++i) {
            if (ObjToVerifiedPointerTic(ticP, objs[i], &certsPP[i], "PCCERT_CONTEXT", CertFreeCertificateContext) != TCL_OK)
                return TCL_ERROR;
        }
        *arrP = certsPP;
    }
    *countP = nobjs;
    return TCL_OK;
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParsePCRL_CONTEXT_Array(
    TwapiInterpContext *ticP,
    Tcl_Obj *crlsObj,
    int *countP,
    PCCRL_CONTEXT **arrP
    )
{
    Tcl_Obj **objs;
    int nobjs, i;
    PCRL_CONTEXT *crlsPP;
    if (ObjGetElements(ticP->interp, crlsObj, &nobjs, &objs) != TCL_OK)
        return TCL_ERROR;
    if (nobjs == 0)
        *arrP = NULL;
    else {
        crlsPP = MemLifoAlloc(ticP->memlifoP, nobjs*sizeof(*crlsPP), NULL);
        for (i = 0; i < nobjs; ++i) {
            if (ObjToVerifiedPointerTic(ticP, objs[i], &crlsPP[i], "PCCRL_CONTEXT", CertFreeCRLContext) != TCL_OK)
                return TCL_ERROR;
        }
        *arrP = crlsPP;
    }
    *countP = nobjs;
    return TCL_OK;
}







|





|







|












|





|







|







477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
    return ObjNewList(ARRAYSIZE(objs), objs);
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParsePCERT_CONTEXT_Array(
    TwapiInterpContext *ticP,
    Tcl_Obj *certsObj,
    DWORD *countP,
    PCCERT_CONTEXT **arrP
    )
{
    Tcl_Obj **objs;
    int nobjs, i;
    PCCERT_CONTEXT *certsPP;
    if (ObjGetElements(ticP->interp, certsObj, &nobjs, &objs) != TCL_OK)
        return TCL_ERROR;
    if (nobjs == 0)
        *arrP = NULL;
    else {
        certsPP = MemLifoAlloc(ticP->memlifoP, nobjs*sizeof(*certsPP), NULL);
        for (i = 0; i < nobjs; ++i) {
            if (ObjToVerifiedPointerTic(ticP, objs[i], (void **) &certsPP[i], "PCCERT_CONTEXT", CertFreeCertificateContext) != TCL_OK)
                return TCL_ERROR;
        }
        *arrP = certsPP;
    }
    *countP = nobjs;
    return TCL_OK;
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParsePCRL_CONTEXT_Array(
    TwapiInterpContext *ticP,
    Tcl_Obj *crlsObj,
    DWORD *countP,
    PCCRL_CONTEXT **arrP
    )
{
    Tcl_Obj **objs;
    int nobjs, i;
    PCCRL_CONTEXT *crlsPP;
    if (ObjGetElements(ticP->interp, crlsObj, &nobjs, &objs) != TCL_OK)
        return TCL_ERROR;
    if (nobjs == 0)
        *arrP = NULL;
    else {
        crlsPP = MemLifoAlloc(ticP->memlifoP, nobjs*sizeof(*crlsPP), NULL);
        for (i = 0; i < nobjs; ++i) {
            if (ObjToVerifiedPointerTic(ticP, objs[i], (void **) &crlsPP[i], "PCCRL_CONTEXT", CertFreeCRLContext) != TCL_OK)
                return TCL_ERROR;
        }
        *arrP = crlsPP;
    }
    *countP = nobjs;
    return TCL_OK;
}
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
}


/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParseCRYPT_ATTRIBUTE_Array(
    TwapiInterpContext *ticP,
    Tcl_Obj *attrsObj,
    int *countP,
    CRYPT_ATTRIBUTE **arrP
    )
{
    Tcl_Obj **objs;
    int nobjs, i;
    CRYPT_ATTRIBUTE *attrsP;
    







|







610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
}


/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParseCRYPT_ATTRIBUTE_Array(
    TwapiInterpContext *ticP,
    Tcl_Obj *attrsObj,
    DWORD *countP,
    CRYPT_ATTRIBUTE **arrP
    )
{
    Tcl_Obj **objs;
    int nobjs, i;
    CRYPT_ATTRIBUTE *attrsP;
    
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
        goto format_error;
    }

    switch (name_type) {
    case CERT_ALT_NAME_RFC822_NAME: /* FALLTHROUGH */
    case CERT_ALT_NAME_DNS_NAME: /* FALLTHROUGH */
    case CERT_ALT_NAME_URL:
        pv = ObjToUnicodeN(objs[1], &n);
        caneP->pwszRfc822Name = MemLifoCopy(ticP->memlifoP, pv, sizeof(WCHAR) * (n+1));
        break;
    case CERT_ALT_NAME_REGISTERED_ID:
        pv = ObjToStringN(objs[1], &n);
        caneP->pszRegisteredID = MemLifoCopy(ticP->memlifoP, pv, n+1);
        break;
    case CERT_ALT_NAME_OTHER_NAME:







|







661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
        goto format_error;
    }

    switch (name_type) {
    case CERT_ALT_NAME_RFC822_NAME: /* FALLTHROUGH */
    case CERT_ALT_NAME_DNS_NAME: /* FALLTHROUGH */
    case CERT_ALT_NAME_URL:
        pv = ObjToWinCharsN(objs[1], &n);
        caneP->pwszRfc822Name = MemLifoCopy(ticP->memlifoP, pv, sizeof(WCHAR) * (n+1));
        break;
    case CERT_ALT_NAME_REGISTERED_ID:
        pv = ObjToStringN(objs[1], &n);
        caneP->pszRegisteredID = MemLifoCopy(ticP->memlifoP, pv, n+1);
        break;
    case CERT_ALT_NAME_OTHER_NAME:
696
697
698
699
700
701
702

703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719

720
721
722
723
724
725
726
727
728

format_error:
    ObjSetResult(ticP->interp,
                 Tcl_ObjPrintf("Invalid or unsupported name format \"%s\"", ObjToString(nameObj)));
    return TCL_ERROR;
}


static TCL_RESULT ParseCERT_NAME_VALUE(
    TwapiInterpContext *ticP,
    Tcl_Obj *namevalObj,
    CERT_NAME_VALUE *cnvP
    )
{
    Tcl_Obj **objs;
    int nobjs;

    if (ObjGetElements(NULL, namevalObj, &nobjs, &objs) == TCL_OK &&
        nobjs == 2 &&
        ObjToDWORD(NULL, objs[0], &cnvP->dwValueType) == TCL_OK &&
        ParseCRYPT_BLOB(ticP, objs[1], &cnvP->Value) == TCL_OK) {
        return TCL_OK;
    } else
        return TwapiReturnErrorMsg(ticP->interp, TWAPI_INVALID_ARGS, "Invalid CERT_NAME_VALUE");
}


static TCL_RESULT ParseCERT_NAME_VALUE_Unicode(
    TwapiInterpContext *ticP,
    Tcl_Obj *namevalObj,
    CERT_NAME_VALUE *cnvP
    )
{
    int nchars;








>

















>

|







699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733

format_error:
    ObjSetResult(ticP->interp,
                 Tcl_ObjPrintf("Invalid or unsupported name format \"%s\"", ObjToString(nameObj)));
    return TCL_ERROR;
}

#ifdef NOTUSED
static TCL_RESULT ParseCERT_NAME_VALUE(
    TwapiInterpContext *ticP,
    Tcl_Obj *namevalObj,
    CERT_NAME_VALUE *cnvP
    )
{
    Tcl_Obj **objs;
    int nobjs;

    if (ObjGetElements(NULL, namevalObj, &nobjs, &objs) == TCL_OK &&
        nobjs == 2 &&
        ObjToDWORD(NULL, objs[0], &cnvP->dwValueType) == TCL_OK &&
        ParseCRYPT_BLOB(ticP, objs[1], &cnvP->Value) == TCL_OK) {
        return TCL_OK;
    } else
        return TwapiReturnErrorMsg(ticP->interp, TWAPI_INVALID_ARGS, "Invalid CERT_NAME_VALUE");
}
#endif

static TCL_RESULT ParseCERT_NAME_VALUE_WinChars(
    TwapiInterpContext *ticP,
    Tcl_Obj *namevalObj,
    CERT_NAME_VALUE *cnvP
    )
{
    int nchars;

944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
    } else {
        p = ObjToStringN(objs[0], &n);
        algidP->pszObjId = MemLifoCopy(ticP->memlifoP, p, n+1);
        if (nobjs == 1) {
            algidP->Parameters.cbData = 0;
            algidP->Parameters.pbData = 0;
        } else {
            p = ObjToByteArray(objs[1], &n);
            algidP->Parameters.pbData = MemLifoCopy(ticP->memlifoP, p, n);
            algidP->Parameters.cbData = n;
        }
    }
    return TCL_OK;
}








|







949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
    } else {
        p = ObjToStringN(objs[0], &n);
        algidP->pszObjId = MemLifoCopy(ticP->memlifoP, p, n+1);
        if (nobjs == 1) {
            algidP->Parameters.cbData = 0;
            algidP->Parameters.pbData = 0;
        } else {
            p = (char *) ObjToByteArray(objs[1], &n);
            algidP->Parameters.pbData = MemLifoCopy(ticP->memlifoP, p, n);
            algidP->Parameters.cbData = n;
        }
    }
    return TCL_OK;
}

1087
1088
1089
1090
1091
1092
1093

1094
1095
1096
1097
1098
1099
1100

    csmP->cbSize = sizeof(*csmP);
    
    return TCL_OK;
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */

static TCL_RESULT ParseCRYPT_KEY_SIGN_MESSAGE_PARA(
    TwapiInterpContext *ticP,
    Tcl_Obj *objP,
    CRYPT_KEY_SIGN_MESSAGE_PARA *csmP
    )
{
    Tcl_Obj *hashalgObj, *pubalgObj;







>







1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106

    csmP->cbSize = sizeof(*csmP);
    
    return TCL_OK;
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
#ifdef NOTUSED
static TCL_RESULT ParseCRYPT_KEY_SIGN_MESSAGE_PARA(
    TwapiInterpContext *ticP,
    Tcl_Obj *objP,
    CRYPT_KEY_SIGN_MESSAGE_PARA *csmP
    )
{
    Tcl_Obj *hashalgObj, *pubalgObj;
1117
1118
1119
1120
1121
1122
1123

1124
1125
1126
1127
1128
1129
1130
        )
        return TCL_ERROR;

    csmP->cbSize = sizeof(*csmP);
    
    return TCL_OK;
}


/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParseCERT_PUBLIC_KEY_INFO(
    TwapiInterpContext *ticP,
    Tcl_Obj *pkObj,
    CERT_PUBLIC_KEY_INFO *pkP
    )







>







1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
        )
        return TCL_ERROR;

    csmP->cbSize = sizeof(*csmP);
    
    return TCL_OK;
}
#endif

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParseCERT_PUBLIC_KEY_INFO(
    TwapiInterpContext *ticP,
    Tcl_Obj *pkObj,
    CERT_PUBLIC_KEY_INFO *pkP
    )
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
        CERT_AUTHORITY_KEY_ID2_INFO *akeyidP;
        CERT_BASIC_CONSTRAINTS2_INFO *basicP;
        CERT_EXTENSIONS *cextsP;
    } u;
    DWORD n;
    LPCSTR oid;
    DWORD_PTR dwoid;
    Tcl_Obj * (*fnP)(void *);

    /* TBD - add other unimplemented types */

    /*
     * poid may be a Tcl_Obj or a dword corresponding to a Win32 #define
     * This is how the CryptDecodeObjEx API works
     */







|







1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
        CERT_AUTHORITY_KEY_ID2_INFO *akeyidP;
        CERT_BASIC_CONSTRAINTS2_INFO *basicP;
        CERT_EXTENSIONS *cextsP;
    } u;
    DWORD n;
    LPCSTR oid;
    DWORD_PTR dwoid;
    Tcl_Obj * (*fnP)() = NULL;

    /* TBD - add other unimplemented types */

    /*
     * poid may be a Tcl_Obj or a dword corresponding to a Win32 #define
     * This is how the CryptDecodeObjEx API works
     */
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
    } else if (dwoid == X509_EXTENSIONS) {
        objP = ObjFromCERT_EXTENSIONS(u.cextsP->cExtension, u.cextsP->rgExtension);
    } else if (dwoid == X509_CRL_DIST_POINTS) {
        fnP = ObjFromCRL_DIST_POINTS_INFO;
    } else if (dwoid == X509_AUTHORITY_INFO_ACCESS) {
        fnP = ObjFromCERT_AUTHORITY_INFO_ACCESS;
    } else if (dwoid == X509_UNICODE_ANY_STRING) {
        fnP = ObjFromCERT_NAME_VALUE_Unicode;
    } else if (dwoid == X509_PUBLIC_KEY_INFO) {
        fnP = ObjFromCERT_PUBLIC_KEY_INFO;
    } else if (dwoid == RSA_CSP_PUBLICKEYBLOB) {
        objP = ObjFromBLOBHEADER(u.pv, n);
    } else if (dwoid == (DWORD_PTR) (65535-1)) { // szOID_SUBJECT_KEY_IDENTIFIER
        fnP = ObjFromCRYPT_BLOB;
    } else {







|







1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
    } else if (dwoid == X509_EXTENSIONS) {
        objP = ObjFromCERT_EXTENSIONS(u.cextsP->cExtension, u.cextsP->rgExtension);
    } else if (dwoid == X509_CRL_DIST_POINTS) {
        fnP = ObjFromCRL_DIST_POINTS_INFO;
    } else if (dwoid == X509_AUTHORITY_INFO_ACCESS) {
        fnP = ObjFromCERT_AUTHORITY_INFO_ACCESS;
    } else if (dwoid == X509_UNICODE_ANY_STRING) {
        fnP = ObjFromCERT_NAME_VALUE_WinChars;
    } else if (dwoid == X509_PUBLIC_KEY_INFO) {
        fnP = ObjFromCERT_PUBLIC_KEY_INFO;
    } else if (dwoid == RSA_CSP_PUBLICKEYBLOB) {
        objP = ObjFromBLOBHEADER(u.pv, n);
    } else if (dwoid == (DWORD_PTR) (65535-1)) { // szOID_SUBJECT_KEY_IDENTIFIER
        fnP = ObjFromCRYPT_BLOB;
    } else {
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
    void *poid, /* Either a Tcl_Obj or a #define X509* int value */
    Tcl_Obj *valObj,
    CRYPT_OBJID_BLOB *blobP)
{
    DWORD     dw;
    TCL_RESULT res;
    void     *penc;
    int       nenc;
    union {
        CRYPT_DATA_BLOB blob;
        CERT_ALT_NAME_INFO cani;
        CERT_ENHKEY_USAGE  ceku;
        CRYPT_BIT_BLOB     bitblob;
        CERT_BASIC_CONSTRAINTS2_INFO basic;
        CERT_AUTHORITY_KEY_ID2_INFO auth_key_id;







|







1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
    void *poid, /* Either a Tcl_Obj or a #define X509* int value */
    Tcl_Obj *valObj,
    CRYPT_OBJID_BLOB *blobP)
{
    DWORD     dw;
    TCL_RESULT res;
    void     *penc;
    DWORD     nenc;
    union {
        CRYPT_DATA_BLOB blob;
        CERT_ALT_NAME_INFO cani;
        CERT_ENHKEY_USAGE  ceku;
        CRYPT_BIT_BLOB     bitblob;
        CERT_BASIC_CONSTRAINTS2_INFO basic;
        CERT_AUTHORITY_KEY_ID2_INFO auth_key_id;
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
    } else if (dwoid == X509_ALGORITHM_IDENTIFIER) {
        res = ParseCRYPT_ALGORITHM_IDENTIFIER(ticP, valObj, &u.algid);
        if (res != TCL_OK)
            return res;
    } else if (dwoid == X509_EXTENSIONS) {
        res = ParseCERT_EXTENSIONS(ticP, valObj, &u.cexts.cExtension, &u.cexts.rgExtension);
    } else if (dwoid == (DWORD_PTR) X509_UNICODE_ANY_STRING) {
        if ((res = ParseCERT_NAME_VALUE_Unicode(ticP, valObj, &u.cnv)) != TCL_OK)
            return res;
    } else if (dwoid == X509_PUBLIC_KEY_INFO) {
        if ((res = ParseCERT_PUBLIC_KEY_INFO(ticP, valObj, &u.cpki)) != TCL_OK)
            return res;
    } else if (dwoid == RSA_CSP_PUBLICKEYBLOB) {
        if (ObjGetElements(NULL, valObj, &nobjs, &objs) == TCL_OK &&
            nobjs == 5) {







|







1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
    } else if (dwoid == X509_ALGORITHM_IDENTIFIER) {
        res = ParseCRYPT_ALGORITHM_IDENTIFIER(ticP, valObj, &u.algid);
        if (res != TCL_OK)
            return res;
    } else if (dwoid == X509_EXTENSIONS) {
        res = ParseCERT_EXTENSIONS(ticP, valObj, &u.cexts.cExtension, &u.cexts.rgExtension);
    } else if (dwoid == (DWORD_PTR) X509_UNICODE_ANY_STRING) {
        if ((res = ParseCERT_NAME_VALUE_WinChars(ticP, valObj, &u.cnv)) != TCL_OK)
            return res;
    } else if (dwoid == X509_PUBLIC_KEY_INFO) {
        if ((res = ParseCERT_PUBLIC_KEY_INFO(ticP, valObj, &u.cpki)) != TCL_OK)
            return res;
    } else if (dwoid == RSA_CSP_PUBLICKEYBLOB) {
        if (ObjGetElements(NULL, valObj, &nobjs, &objs) == TCL_OK &&
            nobjs == 5) {
1823
1824
1825
1826
1827
1828
1829
1830
1831

1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
            return res;
        *timePP = timeP;
    }
    return TCL_OK;
}


static int Twapi_CertCreateSelfSignCertificate(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    void *pv;
    HCRYPTPROV hprov;
    DWORD flags;
    int status;
    CERT_NAME_BLOB name_blob;
    CRYPT_KEY_PROV_INFO *kiP;
    CRYPT_ALGORITHM_IDENTIFIER algid, *algidP;
    int       nobjs;
    SYSTEMTIME start, end, *startP, *endP;
    PCERT_CONTEXT certP;
    CERT_EXTENSIONS exts;
    Tcl_Obj *algidObj, *startObj, *endObj, *extsObj, *provinfoObj;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    if ((status = TwapiGetArgsEx(ticP, objc-1, objv+1,
                                 GETVERIFIEDPTR(pv, HCRYPTPROV, CryptReleaseContext),
                                 GETBA(name_blob.pbData, name_blob.cbData),
                                 GETINT(flags),
                                 GETOBJ(provinfoObj),







|

>














<
<







1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853


1854
1855
1856
1857
1858
1859
1860
            return res;
        *timePP = timeP;
    }
    return TCL_OK;
}


static int Twapi_CertCreateSelfSignCertificateObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    void *pv;
    HCRYPTPROV hprov;
    DWORD flags;
    int status;
    CERT_NAME_BLOB name_blob;
    CRYPT_KEY_PROV_INFO *kiP;
    CRYPT_ALGORITHM_IDENTIFIER algid, *algidP;
    int       nobjs;
    SYSTEMTIME start, end, *startP, *endP;
    PCERT_CONTEXT certP;
    CERT_EXTENSIONS exts;
    Tcl_Obj *algidObj, *startObj, *endObj, *extsObj, *provinfoObj;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);

    if ((status = TwapiGetArgsEx(ticP, objc-1, objv+1,
                                 GETVERIFIEDPTR(pv, HCRYPTPROV, CryptReleaseContext),
                                 GETBA(name_blob.pbData, name_blob.cbData),
                                 GETINT(flags),
                                 GETOBJ(provinfoObj),
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
        case CERT_FRIENDLY_NAME_PROP_ID:
        case CERT_PVK_FILE_PROP_ID:
        case CERT_DESCRIPTION_PROP_ID:
            if (! CertGetCertificateContextProperty(certP, prop_id, NULL, &n))
                return TwapiReturnSystemError(interp);
            pv = SWSPushFrame(n, NULL);
            if (CertGetCertificateContextProperty(certP, prop_id, pv, &n)) {
                result.value.obj = ObjFromUnicode(pv);
                result.type = TRT_OBJ;
            } else {
                result.value.ival = TwapiReturnSystemError(interp);
                result.type = TRT_TCL_RESULT;
            }
            SWSPopFrame();
            break;







|







2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
        case CERT_FRIENDLY_NAME_PROP_ID:
        case CERT_PVK_FILE_PROP_ID:
        case CERT_DESCRIPTION_PROP_ID:
            if (! CertGetCertificateContextProperty(certP, prop_id, NULL, &n))
                return TwapiReturnSystemError(interp);
            pv = SWSPushFrame(n, NULL);
            if (CertGetCertificateContextProperty(certP, prop_id, pv, &n)) {
                result.value.obj = ObjFromWinChars(pv);
                result.type = TRT_OBJ;
            } else {
                result.value.ival = TwapiReturnSystemError(interp);
                result.type = TRT_TCL_RESULT;
            }
            SWSPopFrame();
            break;
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052

        if (! CertGetCertificateContextProperty(certP, prop_id, NULL, &n))
            return TwapiReturnSystemError(interp);
        result.type = TRT_OBJ;
        result.value.obj = ObjFromByteArray(NULL, n);
        if (! CertGetCertificateContextProperty(
                certP, prop_id,
                ObjToByteArray(result.value.obj, &n),
                &n)) {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        Tcl_SetByteArrayLength(result.value.obj, n);
    }







|







2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058

        if (! CertGetCertificateContextProperty(certP, prop_id, NULL, &n))
            return TwapiReturnSystemError(interp);
        result.type = TRT_OBJ;
        result.value.obj = ObjFromByteArray(NULL, n);
        if (! CertGetCertificateContextProperty(
                certP, prop_id,
                ObjToByteArrayDW(result.value.obj, &n),
                &n)) {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        Tcl_SetByteArrayLength(result.value.obj, n);
    }
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
    case CERT_NAME_FRIENDLY_DISPLAY_TYPE: // 5
    case CERT_NAME_DNS_TYPE: // 6
    case CERT_NAME_URL_TYPE: // 7
    case CERT_NAME_UPN_TYPE: // 8
        pv = NULL;
        break;
    case CERT_NAME_RDN_TYPE: // 2
        if (ObjToInt(interp, owhat, &dw) != TCL_OK)
            return TCL_ERROR;
        pv = &dw;
        break;
    case CERT_NAME_ATTR_TYPE: // 3
        pv = ObjToString(owhat);
        break;
    default:
        ObjSetResult(interp, Tcl_ObjPrintf("CertGetNameString: unknown type %d", type));
        return TCL_ERROR;
    }

    // 1 -> CERT_NAME_ISSUER_FLAG 
    // 0x00010000 -> CERT_NAME_DISABLE_IE4_UTF8_FLAG 
    // are supported.
    // 2 -> CERT_NAME_SEARCH_ALL_NAMES_FLAG
    // 0x00200000 -> CERT_NAME_STR_ENABLE_PUNYCODE_FLAG 
    // are post Win8 AND they will change output encoding/format
    // Only support what we know
    if (flags & ~(0x00010001)) {
        ObjSetResult(interp, Tcl_ObjPrintf("CertGetNameString: unsupported flags %d", flags));
        return TCL_ERROR;
    }

    nchars = CertGetNameStringW(certP, type, flags, pv, buf, ARRAYSIZE(buf));
    /* Note nchars includes terminating NULL */
    if (nchars > 1) {
        if (nchars < ARRAYSIZE(buf)) {
            ObjSetResult(interp, ObjFromUnicodeN(buf, nchars-1));
        } else {
            /* Buffer might have been truncated. Explicitly get buffer size */
            WCHAR *bufP;
            nchars = CertGetNameStringW(certP, type, flags, pv, NULL, 0);
            bufP = SWSPushFrame(nchars*sizeof(WCHAR), NULL);
            nchars = CertGetNameStringW(certP, type, flags, pv, bufP, nchars);
            ObjSetResult(interp, ObjFromUnicodeN(bufP, nchars-1));
            SWSPopFrame();
        }
    }
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptSetProvParam(Tcl_Interp *interp,







|







|











|







|






|







2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
    case CERT_NAME_FRIENDLY_DISPLAY_TYPE: // 5
    case CERT_NAME_DNS_TYPE: // 6
    case CERT_NAME_URL_TYPE: // 7
    case CERT_NAME_UPN_TYPE: // 8
        pv = NULL;
        break;
    case CERT_NAME_RDN_TYPE: // 2
        if (ObjToDWORD(interp, owhat, &dw) != TCL_OK)
            return TCL_ERROR;
        pv = &dw;
        break;
    case CERT_NAME_ATTR_TYPE: // 3
        pv = ObjToString(owhat);
        break;
    default:
        ObjSetResult(interp, Tcl_ObjPrintf("CertGetNameString: unknown type %lu", type));
        return TCL_ERROR;
    }

    // 1 -> CERT_NAME_ISSUER_FLAG 
    // 0x00010000 -> CERT_NAME_DISABLE_IE4_UTF8_FLAG 
    // are supported.
    // 2 -> CERT_NAME_SEARCH_ALL_NAMES_FLAG
    // 0x00200000 -> CERT_NAME_STR_ENABLE_PUNYCODE_FLAG 
    // are post Win8 AND they will change output encoding/format
    // Only support what we know
    if (flags & ~(0x00010001)) {
        ObjSetResult(interp, Tcl_ObjPrintf("CertGetNameString: unsupported flags %lu", flags));
        return TCL_ERROR;
    }

    nchars = CertGetNameStringW(certP, type, flags, pv, buf, ARRAYSIZE(buf));
    /* Note nchars includes terminating NULL */
    if (nchars > 1) {
        if (nchars < ARRAYSIZE(buf)) {
            ObjSetResult(interp, ObjFromWinCharsN(buf, nchars-1));
        } else {
            /* Buffer might have been truncated. Explicitly get buffer size */
            WCHAR *bufP;
            nchars = CertGetNameStringW(certP, type, flags, pv, NULL, 0);
            bufP = SWSPushFrame(nchars*sizeof(WCHAR), NULL);
            nchars = CertGetNameStringW(certP, type, flags, pv, bufP, nchars);
            ObjSetResult(interp, ObjFromWinCharsN(bufP, nchars-1));
            SWSPopFrame();
        }
    }
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptSetProvParam(Tcl_Interp *interp,
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
#ifdef PP_PIN_PROMPT_STRING
    case PP_PIN_PROMPT_STRING:
#else
    case 44:
#endif
        /* FALLTHRU */
    case PP_UI_PROMPT:
        pv = ObjToUnicode(objP);
        break;
    default:
        return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS, Tcl_ObjPrintf("Provider parameter %d not implemented", param));
    }

    if (CryptSetProvParam(hprov, param, pv, flags)) {
        res = TCL_OK;
    } else {
        res = TwapiReturnSystemError(interp);
    }







|


|







2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
#ifdef PP_PIN_PROMPT_STRING
    case PP_PIN_PROMPT_STRING:
#else
    case 44:
#endif
        /* FALLTHRU */
    case PP_UI_PROMPT:
        pv = ObjToWinChars(objP);
        break;
    default:
        return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS, Tcl_ObjPrintf("Provider parameter %lu not implemented", param));
    }

    if (CryptSetProvParam(hprov, param, pv, flags)) {
        res = TCL_OK;
    } else {
        res = TwapiReturnSystemError(interp);
    }
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
    DWORD store_provider, enc_type, flags;
    void *pv = NULL;
    HCERTSTORE hstore;
    HANDLE h;
    TCL_RESULT res;
    CRYPT_DATA_BLOB blob;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc, objv,
                     GETINT(store_provider), GETINT(enc_type), ARGUNUSED,
                     GETINT(flags), ARGSKIP, ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    /* Using literals because the #defines are cast as LPCSTR */
    switch (store_provider) {







<
<







2345
2346
2347
2348
2349
2350
2351


2352
2353
2354
2355
2356
2357
2358
    DWORD store_provider, enc_type, flags;
    void *pv = NULL;
    HCERTSTORE hstore;
    HANDLE h;
    TCL_RESULT res;
    CRYPT_DATA_BLOB blob;



    if (TwapiGetArgs(interp, objc, objv,
                     GETINT(store_provider), GETINT(enc_type), ARGUNUSED,
                     GETINT(flags), ARGSKIP, ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    /* Using literals because the #defines are cast as LPCSTR */
    switch (store_provider) {
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409

2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467

2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
            return res;
        break;

    case 8: // CERT_STORE_PROV_FILENAME_W
    case 14: // CERT_STORE_PROV_PHYSICAL_W
    case 10: // CERT_STORE_PROV_SYSTEM_W
    case 13: // CERT_STORE_PROV_SYSTEM_REGISTRY_W
        pv = ObjToUnicode(objv[4]);
        break;

    case 5: // CERT_STORE_PROV_PKCS7
    case 6: // CERT_STORE_PROV_SERIALIZED
        blob.pbData = ObjToByteArray(objv[4], &blob.cbData);
        pv = &blob;
        break;

    case 15: // CERT_STORE_PROV_SMART_CARD
    case 16: // CERT_STORE_PROV_LDAP
    case 1: // CERT_STORE_PROV_MSG
    default:
        ObjSetResult(interp,
                         Tcl_ObjPrintf("Invalid or unsupported store provider \"%d\"", store_provider));
        return TCL_ERROR;
    }

    hstore = CertOpenStore(IntToPtr(store_provider), enc_type, 0, flags, pv);
    if (hstore) {
        /* CertCloseStore does not check pointer validity! So do ourselves*/
        TwapiRegisterHCERTSTORE(interp, hstore);
        return ObjSetResult(interp, ObjFromOpaque(hstore, "HCERTSTORE"));
    } else {
        if (flags & CERT_STORE_DELETE_FLAG) {
            /* Return value can mean success as well */
            if (GetLastError() == 0)
                return TCL_OK;
        }
        return TwapiReturnSystemError(interp);
    }
}

static TCL_RESULT Twapi_PFXExportCertStoreExObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    HCERTSTORE hstore;
    LPWSTR password = NULL;
    int password_len;
    Tcl_Obj *objP, *passObj;
    CRYPT_DATA_BLOB blob;
    BOOL status;
    int flags;
    TCL_RESULT res;
    SWSMark mark = NULL;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hstore, HCERTSTORE, CertCloseStore),
                     GETOBJ(passObj), ARGUNUSED,
                     GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    mark = SWSPushMark();
    password = ObjDecryptUnicodeSWS(interp, passObj, &password_len);
    if (password == NULL) {
        res = TCL_ERROR;
        goto vamoose;
    }

    res = TCL_OK;

    blob.cbData = 0;
    blob.pbData = NULL;

    status = PFXExportCertStoreEx(hstore, &blob, password, NULL, flags);
    if (!status) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }

    if (blob.cbData == 0)
        goto vamoose;

    objP = ObjAllocateByteArray(blob.cbData, &blob.pbData);
    status = PFXExportCertStoreEx(hstore, &blob, password, NULL, flags);
    if (! status) {
        res = TwapiReturnSystemError(interp);
        ObjDecrRefs(objP);
        goto vamoose;
    }
    ObjSetResult(interp, objP);

vamoose:
    if (password)
        SecureZeroMemory(password, sizeof(WCHAR) * password_len);
    if (mark)
        SWSPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_PFXImportCertStoreObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    HCERTSTORE hstore;
    LPWSTR password = NULL;
    int password_len;
    Tcl_Obj *passObj;
    CRYPT_DATA_BLOB blob;
    int flags;
    TCL_RESULT res;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETBA(blob.pbData, blob.cbData),
                         GETOBJ(passObj),
                         GETINT(flags), ARGEND);
    if (res != TCL_OK)
        goto vamoose;
    
    TWAPI_ASSERT(ticP->memlifoP == SWS());
    password = ObjDecryptUnicodeSWS(interp, passObj, &password_len);
    if (password == NULL) {
        res = TCL_ERROR;
        goto vamoose;
    }

    hstore = PFXImportCertStore(&blob, password, flags);
    if (hstore == NULL) {







|




|








|


















|

>








|
|
<
<






|
|



















|












|



|

>









<
<









|







2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424


2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480


2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
            return res;
        break;

    case 8: // CERT_STORE_PROV_FILENAME_W
    case 14: // CERT_STORE_PROV_PHYSICAL_W
    case 10: // CERT_STORE_PROV_SYSTEM_W
    case 13: // CERT_STORE_PROV_SYSTEM_REGISTRY_W
        pv = ObjToWinChars(objv[4]);
        break;

    case 5: // CERT_STORE_PROV_PKCS7
    case 6: // CERT_STORE_PROV_SERIALIZED
        blob.pbData = ObjToByteArrayDW(objv[4], &blob.cbData);
        pv = &blob;
        break;

    case 15: // CERT_STORE_PROV_SMART_CARD
    case 16: // CERT_STORE_PROV_LDAP
    case 1: // CERT_STORE_PROV_MSG
    default:
        ObjSetResult(interp,
                         Tcl_ObjPrintf("Invalid or unsupported store provider \"%lu\"", store_provider));
        return TCL_ERROR;
    }

    hstore = CertOpenStore(IntToPtr(store_provider), enc_type, 0, flags, pv);
    if (hstore) {
        /* CertCloseStore does not check pointer validity! So do ourselves*/
        TwapiRegisterHCERTSTORE(interp, hstore);
        return ObjSetResult(interp, ObjFromOpaque(hstore, "HCERTSTORE"));
    } else {
        if (flags & CERT_STORE_DELETE_FLAG) {
            /* Return value can mean success as well */
            if (GetLastError() == 0)
                return TCL_OK;
        }
        return TwapiReturnSystemError(interp);
    }
}

static TCL_RESULT Twapi_PFXExportCertStoreExObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HCERTSTORE hstore;
    LPWSTR password = NULL;
    int password_len;
    Tcl_Obj *objP, *passObj;
    CRYPT_DATA_BLOB blob;
    BOOL status;
    int flags;
    TCL_RESULT res;
    MemLifoMarkHandle mark = NULL;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hstore, HCERTSTORE, CertCloseStore),
                     GETOBJ(passObj), ARGUNUSED,
                     GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    mark = MemLifoPushMark(ticP->memlifoP);
    password = ObjDecryptWinCharsSWS(interp, passObj, &password_len);
    if (password == NULL) {
        res = TCL_ERROR;
        goto vamoose;
    }

    res = TCL_OK;

    blob.cbData = 0;
    blob.pbData = NULL;

    status = PFXExportCertStoreEx(hstore, &blob, password, NULL, flags);
    if (!status) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }

    if (blob.cbData == 0)
        goto vamoose;

    objP = ObjAllocateByteArray(blob.cbData, (void **) &blob.pbData);
    status = PFXExportCertStoreEx(hstore, &blob, password, NULL, flags);
    if (! status) {
        res = TwapiReturnSystemError(interp);
        ObjDecrRefs(objP);
        goto vamoose;
    }
    ObjSetResult(interp, objP);

vamoose:
    if (password)
        SecureZeroMemory(password, sizeof(WCHAR) * password_len);
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_PFXImportCertStoreObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HCERTSTORE hstore;
    LPWSTR password = NULL;
    int password_len;
    Tcl_Obj *passObj;
    CRYPT_DATA_BLOB blob;
    int flags;
    TCL_RESULT res;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETBA(blob.pbData, blob.cbData),
                         GETOBJ(passObj),
                         GETINT(flags), ARGEND);
    if (res != TCL_OK)
        goto vamoose;
    
    TWAPI_ASSERT(ticP->memlifoP == SWS());
    password = ObjDecryptWinCharsSWS(interp, passObj, &password_len);
    if (password == NULL) {
        res = TCL_ERROR;
        goto vamoose;
    }

    hstore = PFXImportCertStore(&blob, password, flags);
    if (hstore == NULL) {
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514

2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
        SecureZeroMemory(password, sizeof(WCHAR) * password_len);
    MemLifoPopMark(mark);
    return res;
}


static TCL_RESULT Twapi_CertFindCertificateInStoreObjCmd(
    TwapiInterpContext *ticP, Tcl_Interp *interp, int objc,
    Tcl_Obj *CONST objv[])
{

    HCERTSTORE hstore;
    PCCERT_CONTEXT certP, cert2P;
    DWORD         enctype, flags, findtype, dw;
    Tcl_Obj      *findObj;
    void         *pv;
    CERT_BLOB     blob;
    CERT_INFO     cinfo;
    TCL_RESULT    res;
    CERT_PUBLIC_KEY_INFO pki;
    MemLifoMarkHandle mark = NULL;

    ObjToUnicodeCleanup();

    certP = NULL;
    res = TwapiGetArgs(interp, objc-1, objv+1,
                       GETVERIFIEDPTR(hstore, HCERTSTORE, CertCloseStore),
                       GETINT(enctype), GETINT(flags), GETINT(findtype),
                       GETOBJ(findObj), GETVERIFIEDORNULL(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                       ARGEND);
    if (res != TCL_OK) {
        /* We have guaranteed caller certP will be freed even on error */
        if (certP && TwapiUnregisterPCCERT_CONTEXTTic(ticP, certP) == TCL_OK)
            CertFreeCertificateContext(certP);
        return res;
    }    

    switch (findtype) {
    case CERT_FIND_ANY:
        pv = NULL;
        break;
    case CERT_FIND_EXISTING:
        res = ObjToVerifiedPointerTic(ticP, findObj, (void **)&cert2P, "PCCERT_CONTEXT", CertFreeCertificateContext);
        if (res == TCL_OK)
            pv = (void *)cert2P;
        break;
    case CERT_FIND_SUBJECT_CERT:
        pv = &cinfo;
        mark = MemLifoPushMark(ticP->memlifoP);
        res = ParseCERT_INFO(ticP, findObj, &cinfo);
        break;
    case CERT_FIND_KEY_IDENTIFIER: /* FALLTHRU */
    case CERT_FIND_MD5_HASH:    /* FALLTHRU */
    case CERT_FIND_PUBKEY_MD5_HASH:    /* FALLTHRU */
    case CERT_FIND_SHA1_HASH:   /* FALLTHRU */
    case CERT_FIND_SIGNATURE_HASH: /* FALLTHRU */
    case CERT_FIND_ISSUER_NAME: /* FALLTHRU */
    case CERT_FIND_SUBJECT_NAME:
        blob.pbData = ObjToByteArray(findObj, &blob.cbData);
        pv = &blob;
        break;
    case CERT_FIND_ISSUER_STR_W: /* FALLTHRU */
    case CERT_FIND_SUBJECT_STR_W:
        pv = ObjToUnicode(findObj);
        break;
    case CERT_FIND_PROPERTY: /* FALLTHRU */
    case CERT_FIND_KEY_SPEC:
        res = ObjToDWORD(interp, findObj, &dw);
        pv = &dw;
        break;
    case CERT_FIND_PUBLIC_KEY:







|


>




|






<
<















<


















|




|







2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528


2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543

2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
        SecureZeroMemory(password, sizeof(WCHAR) * password_len);
    MemLifoPopMark(mark);
    return res;
}


static TCL_RESULT Twapi_CertFindCertificateInStoreObjCmd(
    ClientData clientdata, Tcl_Interp *interp, int objc,
    Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HCERTSTORE hstore;
    PCCERT_CONTEXT certP, cert2P;
    DWORD         enctype, flags, findtype, dw;
    Tcl_Obj      *findObj;
    void         *pv = NULL;
    CERT_BLOB     blob;
    CERT_INFO     cinfo;
    TCL_RESULT    res;
    CERT_PUBLIC_KEY_INFO pki;
    MemLifoMarkHandle mark = NULL;



    certP = NULL;
    res = TwapiGetArgs(interp, objc-1, objv+1,
                       GETVERIFIEDPTR(hstore, HCERTSTORE, CertCloseStore),
                       GETINT(enctype), GETINT(flags), GETINT(findtype),
                       GETOBJ(findObj), GETVERIFIEDORNULL(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                       ARGEND);
    if (res != TCL_OK) {
        /* We have guaranteed caller certP will be freed even on error */
        if (certP && TwapiUnregisterPCCERT_CONTEXTTic(ticP, certP) == TCL_OK)
            CertFreeCertificateContext(certP);
        return res;
    }    

    switch (findtype) {
    case CERT_FIND_ANY:

        break;
    case CERT_FIND_EXISTING:
        res = ObjToVerifiedPointerTic(ticP, findObj, (void **)&cert2P, "PCCERT_CONTEXT", CertFreeCertificateContext);
        if (res == TCL_OK)
            pv = (void *)cert2P;
        break;
    case CERT_FIND_SUBJECT_CERT:
        pv = &cinfo;
        mark = MemLifoPushMark(ticP->memlifoP);
        res = ParseCERT_INFO(ticP, findObj, &cinfo);
        break;
    case CERT_FIND_KEY_IDENTIFIER: /* FALLTHRU */
    case CERT_FIND_MD5_HASH:    /* FALLTHRU */
    case CERT_FIND_PUBKEY_MD5_HASH:    /* FALLTHRU */
    case CERT_FIND_SHA1_HASH:   /* FALLTHRU */
    case CERT_FIND_SIGNATURE_HASH: /* FALLTHRU */
    case CERT_FIND_ISSUER_NAME: /* FALLTHRU */
    case CERT_FIND_SUBJECT_NAME:
        blob.pbData = ObjToByteArrayDW(findObj, &blob.cbData);
        pv = &blob;
        break;
    case CERT_FIND_ISSUER_STR_W: /* FALLTHRU */
    case CERT_FIND_SUBJECT_STR_W:
        pv = ObjToWinChars(findObj);
        break;
    case CERT_FIND_PROPERTY: /* FALLTHRU */
    case CERT_FIND_KEY_SPEC:
        res = ObjToDWORD(interp, findObj, &dw);
        pv = &dw;
        break;
    case CERT_FIND_PUBLIC_KEY:
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624

2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
    if (mark)
        MemLifoPopMark(mark);

    return res;
}

static TCL_RESULT Twapi_CryptSignAndEncodeCertObjCmd(
    TwapiInterpContext *ticP, Tcl_Interp *interp, int objc,
    Tcl_Obj *CONST objv[])
{

    Tcl_Obj *algidObj, *certinfoObj, *encodedObj;
    TCL_RESULT res;
    CRYPT_ALGORITHM_IDENTIFIER algid;
    DWORD keyspec, enctype;
    union {
        CERT_INFO ci;
        CERT_REQUEST_INFO cri;
    } u;
    HCRYPTPROV hprov;
    DWORD nbytes;
    DWORD structtype;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETVERIFIEDPTR(hprov, HCRYPTPROV, CryptReleaseContext),
                         GETINT(keyspec), GETINT(enctype),
                         GETINT(structtype),
                         GETOBJ(certinfoObj), GETOBJ(algidObj),
                         ARGEND);







|


>













<
<







2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638


2639
2640
2641
2642
2643
2644
2645
    if (mark)
        MemLifoPopMark(mark);

    return res;
}

static TCL_RESULT Twapi_CryptSignAndEncodeCertObjCmd(
    ClientData clientdata, Tcl_Interp *interp, int objc,
    Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *algidObj, *certinfoObj, *encodedObj;
    TCL_RESULT res;
    CRYPT_ALGORITHM_IDENTIFIER algid;
    DWORD keyspec, enctype;
    union {
        CERT_INFO ci;
        CERT_REQUEST_INFO cri;
    } u;
    HCRYPTPROV hprov;
    DWORD nbytes;
    DWORD structtype;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETVERIFIEDPTR(hprov, HCRYPTPROV, CryptReleaseContext),
                         GETINT(keyspec), GETINT(enctype),
                         GETINT(structtype),
                         GETOBJ(certinfoObj), GETOBJ(algidObj),
                         ARGEND);
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697

2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715

2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735

2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766

2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
}

BOOL WINAPI TwapiCertEnumSystemStoreCallback(
    const void *storeP,
    DWORD flags,
    PCERT_SYSTEM_STORE_INFO storeinfoP,
    void *reserved,
    Tcl_Obj *listObj
)
{

    Tcl_Obj *objs[2];

    if (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG)
        return FALSE;     /* We do not know how to handle this currently */

    objs[0] = ObjFromUnicode(storeP);
    objs[1] = ObjFromDWORD(flags);
    ObjAppendElement(NULL, listObj, ObjNewList(2, objs));
    return TRUE;          /* Continue iteration */
}

BOOL WINAPI TwapiCertEnumSystemStoreLocationCallback(
    const void *locationP,
    DWORD flags,
    void *reserved,
    Tcl_Obj *listObj
)
{

    Tcl_Obj *objs[2];

    if (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG)
        return FALSE;     /* We do not know how to handle this currently */

    objs[0] = ObjFromUnicode(locationP);
    objs[1] = ObjFromDWORD(flags);
    ObjAppendElement(NULL, listObj, ObjNewList(2, objs));
    return TRUE;          /* Continue iteration */
}

BOOL WINAPI TwapiCertEnumPhysicalStoreCallback(
    const void *system_storeP,
    DWORD flags,
    LPCWSTR store_nameP,
    PCERT_PHYSICAL_STORE_INFO storeinfoP,
    void *reserved,
    Tcl_Obj *listObj
)
{

    Tcl_Obj *objs[4];
    Tcl_Obj *infoObjs[6];

    if (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG)
        return FALSE;     /* We do not know how to handle this currently */
    
    objs[0] = ObjFromUnicode(system_storeP);
    objs[1] = ObjFromDWORD(flags);
    objs[2] = ObjFromUnicode(store_nameP);

    infoObjs[0] = ObjFromString(storeinfoP->pszOpenStoreProvider);
    infoObjs[1] = ObjFromDWORD(storeinfoP->dwOpenEncodingType);
    infoObjs[2] = ObjFromDWORD(storeinfoP->dwOpenFlags);
    infoObjs[3] = ObjFromByteArray(storeinfoP->OpenParameters.pbData,
                                  storeinfoP->OpenParameters.cbData);
    infoObjs[4] = ObjFromDWORD(storeinfoP->dwFlags);
    infoObjs[5] = ObjFromDWORD(storeinfoP->dwPriority);
    objs[3] = ObjNewList(6, infoObjs);

    ObjAppendElement(NULL, listObj, ObjNewList(4, objs));
    return TRUE;          /* Continue iteration */
}

static BOOL WINAPI TwapiCryptEnumOIDInfoCB(PCCRYPT_OID_INFO coiP, void *pv)
{
    ObjAppendElement(NULL, (Tcl_Obj *)pv, ObjFromCRYPT_OID_INFO(coiP));
    return 1;
}

static TCL_RESULT Twapi_CertGetCertificateChainObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    HCERTCHAINENGINE hce;
    PCCERT_CONTEXT certP;
    Tcl_Obj *paramObj, *ftObj;
    FILETIME  ft, *ftP;
    HCERTSTORE hstore;
    DWORD flags;
    MemLifoMarkHandle mark;
    TCL_RESULT res;
    CERT_CHAIN_PARA chain_params;
    PCCERT_CHAIN_CONTEXT chainP;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLET(hce, HCERTCHAINENGINE),
                     GETVERIFIEDPTR(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                     GETOBJ(ftObj),
                     GETVERIFIEDORNULL(hstore, HCERTSTORE, CertCloseStore),
                     GETOBJ(paramObj), GETINT(flags),
                     ARGEND) != TCL_OK)







|


>





|






|


|


>





|











|
|

>






|

|




















|

>











<
<







2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780


2781
2782
2783
2784
2785
2786
2787
}

BOOL WINAPI TwapiCertEnumSystemStoreCallback(
    const void *storeP,
    DWORD flags,
    PCERT_SYSTEM_STORE_INFO storeinfoP,
    void *reserved,
    void *arg
)
{
    Tcl_Obj *listObj = arg;    
    Tcl_Obj *objs[2];

    if (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG)
        return FALSE;     /* We do not know how to handle this currently */

    objs[0] = ObjFromWinChars(storeP);
    objs[1] = ObjFromDWORD(flags);
    ObjAppendElement(NULL, listObj, ObjNewList(2, objs));
    return TRUE;          /* Continue iteration */
}

BOOL WINAPI TwapiCertEnumSystemStoreLocationCallback(
    LPCWSTR locationP,
    DWORD flags,
    void *reserved,
    void *arg
)
{
    Tcl_Obj *listObj = arg;
    Tcl_Obj *objs[2];

    if (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG)
        return FALSE;     /* We do not know how to handle this currently */

    objs[0] = ObjFromWinChars(locationP);
    objs[1] = ObjFromDWORD(flags);
    ObjAppendElement(NULL, listObj, ObjNewList(2, objs));
    return TRUE;          /* Continue iteration */
}

BOOL WINAPI TwapiCertEnumPhysicalStoreCallback(
    const void *system_storeP,
    DWORD flags,
    LPCWSTR store_nameP,
    PCERT_PHYSICAL_STORE_INFO storeinfoP,
    void *reserved,
    void *arg
    )
{
    Tcl_Obj *listObj = arg;
    Tcl_Obj *objs[4];
    Tcl_Obj *infoObjs[6];

    if (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG)
        return FALSE;     /* We do not know how to handle this currently */
    
    objs[0] = ObjFromWinChars(system_storeP);
    objs[1] = ObjFromDWORD(flags);
    objs[2] = ObjFromWinChars(store_nameP);

    infoObjs[0] = ObjFromString(storeinfoP->pszOpenStoreProvider);
    infoObjs[1] = ObjFromDWORD(storeinfoP->dwOpenEncodingType);
    infoObjs[2] = ObjFromDWORD(storeinfoP->dwOpenFlags);
    infoObjs[3] = ObjFromByteArray(storeinfoP->OpenParameters.pbData,
                                  storeinfoP->OpenParameters.cbData);
    infoObjs[4] = ObjFromDWORD(storeinfoP->dwFlags);
    infoObjs[5] = ObjFromDWORD(storeinfoP->dwPriority);
    objs[3] = ObjNewList(6, infoObjs);

    ObjAppendElement(NULL, listObj, ObjNewList(4, objs));
    return TRUE;          /* Continue iteration */
}

static BOOL WINAPI TwapiCryptEnumOIDInfoCB(PCCRYPT_OID_INFO coiP, void *pv)
{
    ObjAppendElement(NULL, (Tcl_Obj *)pv, ObjFromCRYPT_OID_INFO(coiP));
    return 1;
}

static TCL_RESULT Twapi_CertGetCertificateChainObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HCERTCHAINENGINE hce;
    PCCERT_CONTEXT certP;
    Tcl_Obj *paramObj, *ftObj;
    FILETIME  ft, *ftP;
    HCERTSTORE hstore;
    DWORD flags;
    MemLifoMarkHandle mark;
    TCL_RESULT res;
    CERT_CHAIN_PARA chain_params;
    PCCERT_CHAIN_CONTEXT chainP;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLET(hce, HCERTCHAINENGINE),
                     GETVERIFIEDPTR(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                     GETOBJ(ftObj),
                     GETVERIFIEDORNULL(hstore, HCERTSTORE, CertCloseStore),
                     GETOBJ(paramObj), GETINT(flags),
                     ARGEND) != TCL_OK)
2804
2805
2806
2807
2808
2809
2810
2811
2812

2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842

2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871

2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893

2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917

2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
            res = TwapiReturnSystemError(ticP->interp);
    }
    
    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT  Twapi_HashPublicKeyInfoObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TCL_RESULT res;
    CERT_PUBLIC_KEY_INFO ckpi;
    Tcl_Obj *objP;
    DWORD    len;
    MemLifoMarkHandle mark;

    CHECK_NARGS(interp, objc, 2);

    mark = MemLifoPushMark(ticP->memlifoP);
    if ((res = ParseCERT_PUBLIC_KEY_INFO(ticP, objv[1], &ckpi)) == TCL_OK) {
        objP = ObjFromByteArray(NULL, 20);
        if (CryptHashPublicKeyInfo(0, CALG_SHA1, 0,
                                   X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                                   &ckpi, 
                                   ObjToByteArray(objP, &len),
                                   &len)) {
            Tcl_SetByteArrayLength(objP, len);
            ObjSetResult(interp, objP);
            res = TCL_OK;
        } else {
            res = TwapiReturnSystemError(interp);
        }
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptFormatObjectObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    DWORD encoding, flags;
    void *encP, *bufP;
    int  enclen, buflen;
    TCL_RESULT res;
    MemLifoMarkHandle mark;
    char *oid;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETINT(encoding), ARGSKIP, GETINT(flags), ARGSKIP,
                         GETASTR(oid), GETBA(encP, enclen), ARGEND);
    if (res == TCL_OK) {
        /* First try a buffer size guess */
        bufP = MemLifoAlloc(ticP->memlifoP, enclen, &buflen);
        if (CryptFormatObject(encoding, 0, flags, NULL, oid, encP, enclen,
                              bufP, &buflen))
            ObjSetResult(interp, ObjFromUnicodeN(bufP, buflen/sizeof(WCHAR)));
        else
            res = TwapiReturnSystemError(interp);
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptEncodeObjectExObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *typeObj, *valObj;
    TCL_RESULT res;
    CRYPT_OBJID_BLOB blob;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(typeObj),
                         GETOBJ(valObj), ARGEND);
    if (res == TCL_OK) {
        res = TwapiCryptEncodeObject(ticP, typeObj, valObj, &blob);
        if (res == TCL_OK)
            ObjSetResult(interp, ObjFromCRYPT_BLOB(&blob));
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptDecodeObjectExObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *typeObj;
    void *encP;
    int  enc_len;
    Tcl_Obj *objP;
    TCL_RESULT res;
    MemLifoMarkHandle mark;
 
    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(typeObj),
                         GETBA(encP, enc_len), ARGEND);
    if (res == TCL_OK) {
        res = TwapiCryptDecodeObject(interp, typeObj, encP, enc_len, &objP);
        if (res == TCL_OK)
            ObjSetResult(interp, objP);
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CertVerifyChainPolicyObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    PCERT_CHAIN_POLICY_PARA policy_paramP;
    CERT_CHAIN_POLICY_STATUS policy_status;
    PCCERT_CHAIN_CONTEXT chainP;
    Tcl_Obj *paramObj;
    TCL_RESULT res;
    DWORD policy;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(policy),
                     GETVERIFIEDPTR(chainP, PCCERT_CHAIN_CONTEXT, CertFreeCertificateChain),
                     GETOBJ(paramObj), ARGEND) != TCL_OK)
        return TCL_ERROR;
    switch (policy) {
    case 1: // CERT_CHAIN_POLICY_BASE
    case 2: // CERT_CHAIN_POLICY_AUTHENTICODE







|

>



|











|












|

>
|

|




<
<









|








|

>





<
<













|

>






<
<














|

>
|







<
<







2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852


2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878


2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900


2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925


2926
2927
2928
2929
2930
2931
2932
            res = TwapiReturnSystemError(ticP->interp);
    }
    
    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT  Twapi_HashPublicKeyInfoObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    TCL_RESULT res;
    CERT_PUBLIC_KEY_INFO ckpi;
    Tcl_Obj *objP;
    int    len;
    MemLifoMarkHandle mark;

    CHECK_NARGS(interp, objc, 2);

    mark = MemLifoPushMark(ticP->memlifoP);
    if ((res = ParseCERT_PUBLIC_KEY_INFO(ticP, objv[1], &ckpi)) == TCL_OK) {
        objP = ObjFromByteArray(NULL, 20);
        if (CryptHashPublicKeyInfo(0, CALG_SHA1, 0,
                                   X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                                   &ckpi, 
                                   ObjToByteArray(objP, &len),
                                   (DWORD *) &len)) {
            Tcl_SetByteArrayLength(objP, len);
            ObjSetResult(interp, objP);
            res = TCL_OK;
        } else {
            res = TwapiReturnSystemError(interp);
        }
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptFormatObjectObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    DWORD encoding, flags, buflen;
    void *encP, *bufP;
    int  enclen;
    TCL_RESULT res;
    MemLifoMarkHandle mark;
    char *oid;



    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETINT(encoding), ARGSKIP, GETINT(flags), ARGSKIP,
                         GETASTR(oid), GETBA(encP, enclen), ARGEND);
    if (res == TCL_OK) {
        /* First try a buffer size guess */
        bufP = MemLifoAlloc(ticP->memlifoP, enclen, &buflen);
        if (CryptFormatObject(encoding, 0, flags, NULL, oid, encP, enclen,
                              bufP, &buflen))
            ObjSetResult(interp, ObjFromWinCharsN(bufP, buflen/sizeof(WCHAR)));
        else
            res = TwapiReturnSystemError(interp);
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptEncodeObjectExObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *typeObj, *valObj;
    TCL_RESULT res;
    CRYPT_OBJID_BLOB blob;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(typeObj),
                         GETOBJ(valObj), ARGEND);
    if (res == TCL_OK) {
        res = TwapiCryptEncodeObject(ticP, typeObj, valObj, &blob);
        if (res == TCL_OK)
            ObjSetResult(interp, ObjFromCRYPT_BLOB(&blob));
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptDecodeObjectExObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *typeObj;
    void *encP;
    int  enc_len;
    Tcl_Obj *objP;
    TCL_RESULT res;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(typeObj),
                         GETBA(encP, enc_len), ARGEND);
    if (res == TCL_OK) {
        res = TwapiCryptDecodeObject(interp, typeObj, encP, enc_len, &objP);
        if (res == TCL_OK)
            ObjSetResult(interp, objP);
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CertVerifyChainPolicyObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    PCERT_CHAIN_POLICY_PARA policy_paramP = NULL;
    CERT_CHAIN_POLICY_STATUS policy_status;
    PCCERT_CHAIN_CONTEXT chainP;
    Tcl_Obj *paramObj;
    TCL_RESULT res;
    DWORD policy;
    MemLifoMarkHandle mark;



    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(policy),
                     GETVERIFIEDPTR(chainP, PCCERT_CHAIN_CONTEXT, CertFreeCertificateChain),
                     GETOBJ(paramObj), ARGEND) != TCL_OK)
        return TCL_ERROR;
    switch (policy) {
    case 1: // CERT_CHAIN_POLICY_BASE
    case 2: // CERT_CHAIN_POLICY_AUTHENTICODE
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037

3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
            res = TwapiReturnSystemError(interp);
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CertChainSimpleChainObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    PCCERT_CHAIN_CONTEXT chainP;
    DWORD slot;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(chainP, PCCERT_CHAIN_CONTEXT, CertFreeCertificateChain),
                     GETINT(slot), ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (slot >= chainP->cChain) 
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Chain index out of range.");
    return ObjSetResult(interp, ObjFromCERT_SIMPLE_CHAIN(interp, chainP->rgpChain[slot]));
}

static int Twapi_CryptFindOIDInfoObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD keytype, group;
    Tcl_Obj *keyObj;
    void *pv;
    ALG_ID algids[2];
    Tcl_Obj **objs;
    int nobjs;
    PCCRYPT_OID_INFO coiP;
#if 0
#define CRYPT_OID_INFO_OID_KEY           1
#define CRYPT_OID_INFO_NAME_KEY          2
#define CRYPT_OID_INFO_ALGID_KEY         3
#define CRYPT_OID_INFO_SIGN_KEY          4

#endif

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(keytype), GETOBJ(keyObj),
                     GETINT(group), ARGEND) != TCL_OK)
        return TCL_ERROR;

    switch (keytype & ~CRYPT_OID_INFO_OID_KEY_FLAGS_MASK) {
    case CRYPT_OID_INFO_OID_KEY:
        pv = ObjToString(keyObj);
        break;
    case CRYPT_OID_INFO_NAME_KEY:
        pv = ObjToUnicode(keyObj);
        break;
    case CRYPT_OID_INFO_ALGID_KEY:
        if (ObjToDWORD(interp, keyObj, &algids[0]) != TCL_OK)
            return TCL_ERROR;
        pv = &algids[0];
        break;
    case CRYPT_OID_INFO_SIGN_KEY:
        if (ObjGetElements(NULL, keyObj, &nobjs, &objs) != TCL_OK ||
            nobjs != 2 ||
            ObjToDWORD(NULL, objs[0], &algids[0]) != TCL_OK ||
            ObjToDWORD(NULL, objs[1], &algids[1]) != TCL_OK) {
            TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid CRYPT_OID_INFO_SIGN_KEY format");
            return TCL_ERROR;
        }
        pv = algids;
        break;
    }

    /* NOTE: coiP must NOT be freed */
    coiP = CryptFindOIDInfo(keytype, pv, group);
    if (coiP)
        ObjSetResult(interp, ObjFromCRYPT_OID_INFO(coiP));
    /* Else empty result */

    return TCL_OK;
}

static int Twapi_CertSetCertificateContextPropertyObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    DWORD prop_id, flags;
    Tcl_Obj *valObj;
    void *pv;
    CRYPT_DATA_BLOB blob;
    TCL_RESULT res;
    MemLifoMarkHandle mark;
    CRYPT_KEY_PROV_INFO *kiP;
    PCCERT_CONTEXT certP;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETVERIFIEDPTR(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                         GETINT(prop_id), GETINT(flags), ARGUSEDEFAULT,
                         GETOBJ(valObj), ARGEND);
    if (res != TCL_OK)







|




<
<










|















|
<
<









|


|






|
|
















|

>









<
<







2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965


2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992


2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041


3042
3043
3044
3045
3046
3047
3048
            res = TwapiReturnSystemError(interp);
    }

    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CertChainSimpleChainObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    PCCERT_CHAIN_CONTEXT chainP;
    DWORD slot;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(chainP, PCCERT_CHAIN_CONTEXT, CertFreeCertificateChain),
                     GETINT(slot), ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (slot >= chainP->cChain) 
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Chain index out of range.");
    return ObjSetResult(interp, ObjFromCERT_SIMPLE_CHAIN(interp, chainP->rgpChain[slot]));
}

static int Twapi_CryptFindOIDInfoObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD keytype, group;
    Tcl_Obj *keyObj;
    void *pv;
    ALG_ID algids[2];
    Tcl_Obj **objs;
    int nobjs;
    PCCRYPT_OID_INFO coiP;
#if 0
#define CRYPT_OID_INFO_OID_KEY           1
#define CRYPT_OID_INFO_NAME_KEY          2
#define CRYPT_OID_INFO_ALGID_KEY         3
#define CRYPT_OID_INFO_SIGN_KEY          4

#endif
    


    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(keytype), GETOBJ(keyObj),
                     GETINT(group), ARGEND) != TCL_OK)
        return TCL_ERROR;

    switch (keytype & ~CRYPT_OID_INFO_OID_KEY_FLAGS_MASK) {
    case CRYPT_OID_INFO_OID_KEY:
        pv = ObjToString(keyObj);
        break;
    case CRYPT_OID_INFO_NAME_KEY:
        pv = ObjToWinChars(keyObj);
        break;
    case CRYPT_OID_INFO_ALGID_KEY:
        if (ObjToDWORD(interp, keyObj, (DWORD *)&algids[0]) != TCL_OK)
            return TCL_ERROR;
        pv = &algids[0];
        break;
    case CRYPT_OID_INFO_SIGN_KEY:
        if (ObjGetElements(NULL, keyObj, &nobjs, &objs) != TCL_OK ||
            nobjs != 2 ||
            ObjToDWORD(NULL, objs[0], (DWORD *) &algids[0]) != TCL_OK ||
            ObjToDWORD(NULL, objs[1], (DWORD *) &algids[1]) != TCL_OK) {
            TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid CRYPT_OID_INFO_SIGN_KEY format");
            return TCL_ERROR;
        }
        pv = algids;
        break;
    }

    /* NOTE: coiP must NOT be freed */
    coiP = CryptFindOIDInfo(keytype, pv, group);
    if (coiP)
        ObjSetResult(interp, ObjFromCRYPT_OID_INFO(coiP));
    /* Else empty result */

    return TCL_OK;
}

static int Twapi_CertSetCertificateContextPropertyObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    DWORD prop_id, flags;
    Tcl_Obj *valObj;
    void *pv;
    CRYPT_DATA_BLOB blob;
    TCL_RESULT res;
    MemLifoMarkHandle mark;
    CRYPT_KEY_PROV_INFO *kiP;
    PCCERT_CONTEXT certP;



    mark = MemLifoPushMark(ticP->memlifoP);
    
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETVERIFIEDPTR(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                         GETINT(prop_id), GETINT(flags), ARGUSEDEFAULT,
                         GETOBJ(valObj), ARGEND);
    if (res != TCL_OK)
3068
3069
3070
3071
3072
3073
3074

3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093

3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
        case CERT_DESCRIPTION_PROP_ID:
        case CERT_ARCHIVED_PROP_ID:
        case CERT_FRIENDLY_NAME_PROP_ID:
            pv = &blob;
            res = ParseCRYPT_BLOB(ticP, valObj, &blob);
            break;
        default:

            res = TwapiReturnError(interp, TWAPI_UNSUPPORTED_TYPE);
            break;
        }
    }
    if (res != TCL_OK)
        goto vamoose;

    if (CertSetCertificateContextProperty(certP, prop_id, flags, pv))
        res = TCL_OK;
    else
        res = TwapiReturnSystemError(interp);

vamoose:
    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptQueryObjectObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    DWORD operand_type, enc_type;
    Tcl_Obj *objP;
    void *operand;
    DWORD expected_content_type, expected_format_type, flags;
    int types_only;
    HCERTSTORE hstore = NULL, *hstoreP;
    HCRYPTMSG hmsg = NULL, *hmsgP;
    void *pv = NULL;
    void **pvP;
    CERT_BLOB blob;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    res = TwapiGetArgs(interp, objc-1, objv+1, GETINT(operand_type),
                       GETOBJ(objP), GETINT(expected_content_type),
                       GETINT(expected_format_type), GETINT(flags),
                       ARGUSEDEFAULT, GETBOOL(types_only),
                       ARGEND);
    if (res != TCL_OK)
        return res;
    if (types_only) {
        hstoreP = NULL;
        hmsgP   = NULL;
        pvP     = NULL;
    } else {
        hstoreP = &hstore;
        hmsgP   = &hmsg;
        pvP     = &pv;
    }
    res = TCL_OK;
    if (operand_type == CERT_QUERY_OBJECT_FILE) {
        operand = ObjToUnicode(objP);
    } else {
        mark = MemLifoPushMark(ticP->memlifoP);
        operand = &blob;
        res = ParseCRYPT_BLOB(ticP, objP, operand);
    }
    if (res == TCL_OK) {
        if (CryptQueryObject(operand_type, operand, 
                             expected_content_type, expected_format_type,
                             flags, &enc_type, &expected_content_type,
                             &expected_format_type, hstoreP, hmsgP,
                             pvP) == 0)
            res = TwapiReturnSystemError(interp);
        else {
            Tcl_Obj *objs[12];
            int nobjs;
            objs[0] = STRING_LITERAL_OBJ("encoding");
            objs[1] = ObjFromDWORD(enc_type);
            objs[2] = STRING_LITERAL_OBJ("formattype");







>

















|

>













<
<


















|










|







3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101


3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
        case CERT_DESCRIPTION_PROP_ID:
        case CERT_ARCHIVED_PROP_ID:
        case CERT_FRIENDLY_NAME_PROP_ID:
            pv = &blob;
            res = ParseCRYPT_BLOB(ticP, valObj, &blob);
            break;
        default:
            pv = NULL; /* Keep gcc happy */
            res = TwapiReturnError(interp, TWAPI_UNSUPPORTED_TYPE);
            break;
        }
    }
    if (res != TCL_OK)
        goto vamoose;

    if (CertSetCertificateContextProperty(certP, prop_id, flags, pv))
        res = TCL_OK;
    else
        res = TwapiReturnSystemError(interp);

vamoose:
    MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptQueryObjectObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    DWORD operand_type, enc_type;
    Tcl_Obj *objP;
    void *operand;
    DWORD expected_content_type, expected_format_type, flags;
    int types_only;
    HCERTSTORE hstore = NULL, *hstoreP;
    HCRYPTMSG hmsg = NULL, *hmsgP;
    void *pv = NULL;
    void **pvP;
    CERT_BLOB blob;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;



    res = TwapiGetArgs(interp, objc-1, objv+1, GETINT(operand_type),
                       GETOBJ(objP), GETINT(expected_content_type),
                       GETINT(expected_format_type), GETINT(flags),
                       ARGUSEDEFAULT, GETBOOL(types_only),
                       ARGEND);
    if (res != TCL_OK)
        return res;
    if (types_only) {
        hstoreP = NULL;
        hmsgP   = NULL;
        pvP     = NULL;
    } else {
        hstoreP = &hstore;
        hmsgP   = &hmsg;
        pvP     = &pv;
    }
    res = TCL_OK;
    if (operand_type == CERT_QUERY_OBJECT_FILE) {
        operand = ObjToWinChars(objP);
    } else {
        mark = MemLifoPushMark(ticP->memlifoP);
        operand = &blob;
        res = ParseCRYPT_BLOB(ticP, objP, operand);
    }
    if (res == TCL_OK) {
        if (CryptQueryObject(operand_type, operand, 
                             expected_content_type, expected_format_type,
                             flags, &enc_type, &expected_content_type,
                             &expected_format_type, hstoreP, hmsgP,
                             (const void **) pvP) == 0)
            res = TwapiReturnSystemError(interp);
        else {
            Tcl_Obj *objs[12];
            int nobjs;
            objs[0] = STRING_LITERAL_OBJ("encoding");
            objs[1] = ObjFromDWORD(enc_type);
            objs[2] = STRING_LITERAL_OBJ("formattype");
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
        }
    } 
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptGetKeyParamObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD param, flags;
    int nbytes;
    void *p;
    Tcl_Obj *objP = NULL;
    TCL_RESULT res;
    HCRYPTKEY hkey;
    DWORD dw;
    
    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hkey, HCRYPTKEY, CryptDestroyKey),
                     GETINT(param), ARGUSEDEFAULT,
                     GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;

    switch (param) {







|

|
<






<
<







3178
3179
3180
3181
3182
3183
3184
3185
3186
3187

3188
3189
3190
3191
3192
3193


3194
3195
3196
3197
3198
3199
3200
        }
    } 
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptGetKeyParamObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD param, flags, nbytes;

    void *p;
    Tcl_Obj *objP = NULL;
    TCL_RESULT res;
    HCRYPTKEY hkey;
    DWORD dw;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hkey, HCRYPTKEY, CryptDestroyKey),
                     GETINT(param), ARGUSEDEFAULT,
                     GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;

    switch (param) {
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315

3316

3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333

3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
            break;
        }
    }

    return res;
}

static TCL_RESULT Twapi_CryptSetKeyParamObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD param, flags;
    void *p;
    Tcl_Obj *paramObj = NULL;
    HCRYPTKEY hkey;
    DWORD dw, block_len;
    CRYPT_INTEGER_BLOB cblob;
    
    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hkey, HCRYPTKEY, CryptDestroyKey),
                     GETINT(param), GETOBJ(paramObj), ARGUSEDEFAULT,
                     GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;

    switch (param) {
    case KP_ALGID:  case KP_PERMISSIONS:
    case KP_EFFECTIVE_KEYLEN: case KP_HIGHEST_VERSION:
    case KP_PADDING: case KP_MODE:     case KP_MODE_BITS:
        if (ObjToDWORD(interp, paramObj, &dw) != TCL_OK)
            return TCL_ERROR;
        p = &dw;
        break;

    case KP_SALT_EX:
    case KP_P:       case KP_Q:        case KP_G:
    case KP_OAEP_PARAMS:
        cblob.pbData = ObjToByteArray(paramObj, &cblob.cbData);
        p = &cblob;
        break;
    case KP_X:
        p = NULL;
        break;

    case KP_IV:
        /* Need to verify the correct size of Initialization vector */
        dw = sizeof(block_len);
        if (!CryptGetKeyParam(hkey, KP_BLOCKLEN, (BYTE*)&block_len, &dw, 0))
            return TwapiReturnSystemError(interp);
        p = ObjToByteArray(paramObj, &dw);
        if (dw != block_len)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid IV size.");
        break;
        
    case KP_SALT:
    case KP_CERTIFICATE:
    default:
        /* Not supported because can't verify size of byte array is correct */
        return TwapiReturnError(interp, TWAPI_UNSUPPORTED_TYPE);
    }
    if (!CryptSetKeyParam(hkey, param, p, flags))
        return TwapiReturnSystemError(interp);
    else
        return TCL_OK;
}

static TCL_RESULT TwapiCloseContext(Tcl_Interp *interp, Tcl_Obj *objP,
                                    const char *typeptr,

                                    TCL_RESULT (*unregfn)(Tcl_Interp *, HANDLE),

                                    BOOL (WINAPI *freefn)(HANDLE))
{
    HANDLE h;
    if (ObjToOpaque(interp, objP, &h, typeptr) != TCL_OK ||
        (*unregfn)(interp, h) != TCL_OK)
        return TCL_ERROR;

    if ((*freefn)(h) == FALSE) {
        DWORD dw = GetLastError();
        if (dw != CRYPT_E_PENDING_CLOSE)
            return TwapiReturnSystemError(interp);
    }
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptSetHashParamObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    void *pv;
    DWORD param;
    Tcl_Obj *paramObj;
    HMAC_INFO hmaci;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;
    
    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                     GETINT(param), ARGUSEDEFAULT,
                     GETOBJ(paramObj), ARGEND) != TCL_OK)
        return TCL_ERROR;
    if (param != HP_HMAC_INFO)
        return TwapiReturnError(interp, TWAPI_INVALID_ARGS);







|








<
<


















|











|


















>
|
>
|














|

>







<
<







3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254


3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331


3332
3333
3334
3335
3336
3337
3338
            break;
        }
    }

    return res;
}

static TCL_RESULT Twapi_CryptSetKeyParamObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD param, flags;
    void *p;
    Tcl_Obj *paramObj = NULL;
    HCRYPTKEY hkey;
    DWORD dw, block_len;
    CRYPT_INTEGER_BLOB cblob;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hkey, HCRYPTKEY, CryptDestroyKey),
                     GETINT(param), GETOBJ(paramObj), ARGUSEDEFAULT,
                     GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;

    switch (param) {
    case KP_ALGID:  case KP_PERMISSIONS:
    case KP_EFFECTIVE_KEYLEN: case KP_HIGHEST_VERSION:
    case KP_PADDING: case KP_MODE:     case KP_MODE_BITS:
        if (ObjToDWORD(interp, paramObj, &dw) != TCL_OK)
            return TCL_ERROR;
        p = &dw;
        break;

    case KP_SALT_EX:
    case KP_P:       case KP_Q:        case KP_G:
    case KP_OAEP_PARAMS:
        cblob.pbData = ObjToByteArrayDW(paramObj, &cblob.cbData);
        p = &cblob;
        break;
    case KP_X:
        p = NULL;
        break;

    case KP_IV:
        /* Need to verify the correct size of Initialization vector */
        dw = sizeof(block_len);
        if (!CryptGetKeyParam(hkey, KP_BLOCKLEN, (BYTE*)&block_len, &dw, 0))
            return TwapiReturnSystemError(interp);
        p = ObjToByteArrayDW(paramObj, &dw);
        if (dw != block_len)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid IV size.");
        break;
        
    case KP_SALT:
    case KP_CERTIFICATE:
    default:
        /* Not supported because can't verify size of byte array is correct */
        return TwapiReturnError(interp, TWAPI_UNSUPPORTED_TYPE);
    }
    if (!CryptSetKeyParam(hkey, param, p, flags))
        return TwapiReturnSystemError(interp);
    else
        return TCL_OK;
}

static TCL_RESULT TwapiCloseContext(Tcl_Interp *interp, Tcl_Obj *objP,
                                    const char *typeptr,
//                                    TCL_RESULT (*unregfn)(Tcl_Interp *, HANDLE),
                                    TCL_RESULT (*unregfn)(),
//                                    BOOL (WINAPI *freefn)(HANDLE))
                                    BOOL (WINAPI *freefn)())
{
    HANDLE h;
    if (ObjToOpaque(interp, objP, &h, typeptr) != TCL_OK ||
        (*unregfn)(interp, h) != TCL_OK)
        return TCL_ERROR;

    if ((*freefn)(h) == FALSE) {
        DWORD dw = GetLastError();
        if (dw != CRYPT_E_PENDING_CLOSE)
            return TwapiReturnSystemError(interp);
    }
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptSetHashParamObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    void *pv;
    DWORD param;
    Tcl_Obj *paramObj;
    HMAC_INFO hmaci;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                     GETINT(param), ARGUSEDEFAULT,
                     GETOBJ(paramObj), ARGEND) != TCL_OK)
        return TCL_ERROR;
    if (param != HP_HMAC_INFO)
        return TwapiReturnError(interp, TWAPI_INVALID_ARGS);
3371
3372
3373
3374
3375
3376
3377
3378
3379

3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptCATAdminEnumCatalogFromHashObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TCL_RESULT res;
    HCATADMIN hca;
    HCATINFO  hci, prev_hci;
    BYTE *pb;
    DWORD cb, flags;
    MemLifoMarkHandle mark = NULL;
    
    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETVERIFIEDPTR(hca, HCATADMIN, CryptCATAdminReleaseContext),
                       GETBA(pb, cb), GETINT(flags),
                       ARGUSEDEFAULT,
                       GETVERIFIEDORNULL(prev_hci, HCATINFO, CryptCATAdminReleaseCatalogContext),
                       ARGEND);







|

>







<
<







3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376


3377
3378
3379
3380
3381
3382
3383

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptCATAdminEnumCatalogFromHashObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    TCL_RESULT res;
    HCATADMIN hca;
    HCATINFO  hci, prev_hci;
    BYTE *pb;
    DWORD cb, flags;
    MemLifoMarkHandle mark = NULL;
    


    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETVERIFIEDPTR(hca, HCATADMIN, CryptCATAdminReleaseContext),
                       GETBA(pb, cb), GETINT(flags),
                       ARGUSEDEFAULT,
                       GETVERIFIEDORNULL(prev_hci, HCATINFO, CryptCATAdminReleaseCatalogContext),
                       ARGEND);
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424

3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
    }
    
    if (mark)
        MemLifoPopMark(mark);
    return res;
}
        
static TCL_RESULT Twapi_CryptEncryptObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    void *pv, *pv2;
    HCRYPTKEY hkey;
    HCRYPTHASH hash;
    BOOL final, duped;
    DWORD block_len, len, buf_len, flags;

    ALG_ID alg_id;
    
    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(pv, HCRYPTKEY, CryptDestroyKey),
                     GETVERIFIEDORNULL(pv2, HCRYPTHASH, CryptDestroyHash),
                     GETBOOL(final), GETINT(flags), 
                     GETOBJ(objP), ARGEND) != TCL_OK)
        return TCL_ERROR;








|






|
>


<
<







3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415


3416
3417
3418
3419
3420
3421
3422
    }
    
    if (mark)
        MemLifoPopMark(mark);
    return res;
}
        
static TCL_RESULT Twapi_CryptEncryptObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    void *pv, *pv2;
    HCRYPTKEY hkey;
    HCRYPTHASH hash;
    BOOL final, duped;
    DWORD block_len, len, flags;
    int buf_len;
    ALG_ID alg_id;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(pv, HCRYPTKEY, CryptDestroyKey),
                     GETVERIFIEDORNULL(pv2, HCRYPTHASH, CryptDestroyHash),
                     GETBOOL(final), GETINT(flags), 
                     GETOBJ(objP), ARGEND) != TCL_OK)
        return TCL_ERROR;

3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
    
    /*
     * NOTE: The sample 5.26 in Secure Programming Cookbook does not
     * match the SDK and SDK samples. In particular, it seems to confuse
     * the buffer size and data length parameters and requirements.
     * Code below follows the SDK
     */
    pv = ObjToByteArray(objP, &len);
    if (block_len == 0)
        buf_len = len;
    else {
        buf_len = len + block_len; /* Might need block size more bytes */
        Tcl_SetByteArrayLength(objP, buf_len);
        pv = ObjToByteArray(objP, &buf_len); /* Might have been realloced */
    }
    if (!CryptEncrypt(hkey, hash, final, flags, pv, &len, buf_len)) {
        DWORD winerr = GetLastError();
        if (duped)
            ObjDecrRefs(objP);
        return Twapi_AppendSystemError(interp, winerr);
    }
    Tcl_SetByteArrayLength(objP, len); /* Set length to actual # ciphertext */
    ObjSetResult(interp, objP);
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptDecryptObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    void *pv, *pv2;
    HCRYPTKEY hkey;
    HCRYPTHASH hash;
    BOOL final, duped;
    DWORD len, flags;
    
    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(pv, HCRYPTKEY, CryptDestroyKey),
                     GETVERIFIEDORNULL(pv2, HCRYPTHASH, CryptDestroyHash),
                     GETBOOL(final), GETINT(flags), 
                     GETOBJ(objP), ARGEND) != TCL_OK)
        return TCL_ERROR;








|


















|








<
<







3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480


3481
3482
3483
3484
3485
3486
3487
    
    /*
     * NOTE: The sample 5.26 in Secure Programming Cookbook does not
     * match the SDK and SDK samples. In particular, it seems to confuse
     * the buffer size and data length parameters and requirements.
     * Code below follows the SDK
     */
    pv = ObjToByteArrayDW(objP, &len);
    if (block_len == 0)
        buf_len = len;
    else {
        buf_len = len + block_len; /* Might need block size more bytes */
        Tcl_SetByteArrayLength(objP, buf_len);
        pv = ObjToByteArray(objP, &buf_len); /* Might have been realloced */
    }
    if (!CryptEncrypt(hkey, hash, final, flags, pv, &len, buf_len)) {
        DWORD winerr = GetLastError();
        if (duped)
            ObjDecrRefs(objP);
        return Twapi_AppendSystemError(interp, winerr);
    }
    Tcl_SetByteArrayLength(objP, len); /* Set length to actual # ciphertext */
    ObjSetResult(interp, objP);
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptDecryptObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    void *pv, *pv2;
    HCRYPTKEY hkey;
    HCRYPTHASH hash;
    BOOL final, duped;
    DWORD len, flags;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(pv, HCRYPTKEY, CryptDestroyKey),
                     GETVERIFIEDORNULL(pv2, HCRYPTHASH, CryptDestroyHash),
                     GETBOOL(final), GETINT(flags), 
                     GETOBJ(objP), ARGEND) != TCL_OK)
        return TCL_ERROR;

3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534

3535
3536

3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577

3578
3579
3580

3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624

3625
3626
3627

3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
    
    /*
     * NOTE: The sample 5.26 in Secure Programming Cookbook does not
     * match the SDK and SDK samples. In particular, it seems to confuse
     * the buffer size and data length parameters and requirements.
     * Code below follows the SDK
     */
    pv = ObjToByteArray(objP, &len);
    if (!CryptDecrypt(hkey, hash, final, flags, pv, &len)) {
        DWORD winerr = GetLastError();
        if (duped)
            ObjDecrRefs(objP);
        return Twapi_AppendSystemError(interp, winerr);
    }
    Tcl_SetByteArrayLength(objP, len); /* Set length to actual # ciphertext */
    ObjSetResult(interp, objP);
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptEncryptMessageObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *paramObj, *certsObj, *dataObj, *objP;
    TCL_RESULT res;

    int ncerts, nin, nout;
    PCERT_CONTEXT *certsPP;
    BYTE *in, *out;
    CRYPT_ENCRYPT_MESSAGE_PARA param;
    MemLifoMarkHandle mark = NULL;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETOBJ(paramObj), GETOBJ(certsObj),
                       GETOBJ(dataObj), ARGEND) != TCL_OK
        || ParseCRYPT_ENCRYPT_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK
        || ParsePCERT_CONTEXT_Array(ticP, certsObj, &ncerts, &certsPP) != TCL_OK) {
        res = TCL_ERROR;
    } else {
        in = ObjToByteArray(dataObj, &nin);
        nout = 0;
        if (! CryptEncryptMessage(&param, ncerts, certsPP, in, nin, NULL, &nout)) {
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        objP = ObjAllocateByteArray(nout, &out);
        if (! CryptEncryptMessage(&param, ncerts, certsPP, in, nin, out, &nout)) {
            res = TwapiReturnSystemError(interp);
            ObjDecrRefs(objP);
            goto vamoose;
        }
        Tcl_SetByteArrayLength(objP, nout);
        ObjSetResult(interp, objP);
        res = TCL_OK;
    }

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptSignAndEncryptMessageObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *signparamObj, *encparamObj, *certsObj, *dataObj, *objP;
    TCL_RESULT res;
    int ncerts, nin, nout;

    PCERT_CONTEXT *certsPP;
    BYTE *in, *out;
    CRYPT_SIGN_MESSAGE_PARA sign_param;
    CRYPT_ENCRYPT_MESSAGE_PARA enc_param;
    MemLifoMarkHandle mark = NULL;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(signparamObj),
                       GETOBJ(encparamObj), GETOBJ(certsObj),
                       GETOBJ(dataObj), ARGEND) != TCL_OK
        || ParseCRYPT_SIGN_MESSAGE_PARA(ticP, signparamObj, &sign_param) != TCL_OK
        || ParseCRYPT_ENCRYPT_MESSAGE_PARA(ticP, encparamObj, &enc_param) != TCL_OK
        || ParsePCERT_CONTEXT_Array(ticP, certsObj, &ncerts, &certsPP) != TCL_OK) {
        res = TCL_ERROR;
    } else {
        in = ObjToByteArray(dataObj, &nin);
        nout = 0;
        if (! CryptSignAndEncryptMessage(&sign_param, &enc_param, ncerts,
                                         certsPP, in, nin, NULL, &nout)) {
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        objP = ObjAllocateByteArray(nout, &out);
        if (! CryptSignAndEncryptMessage(&sign_param, &enc_param, ncerts,
                                  certsPP, in, nin, out, &nout)) {
            res = TwapiReturnSystemError(interp);
            ObjDecrRefs(objP);
            goto vamoose;
        }
        Tcl_SetByteArrayLength(objP, nout);
        ObjSetResult(interp, objP);
        res = TCL_OK;
    }

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptDecryptMessageObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    MemLifoMarkHandle mark = NULL;
    Tcl_Obj *paramObj, *dataObj, *objP, *certVar;
    TCL_RESULT res;

    int  n, nin, nout;
    BYTE *in, *out;
    CRYPT_DECRYPT_MESSAGE_PARA param;
    PCCERT_CONTEXT certP, *certPP;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETOBJ(paramObj), GETOBJ(dataObj), ARGUSEDEFAULT,
                       GETOBJ(certVar), ARGEND) != TCL_OK
        || ParseCRYPT_DECRYPT_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK)
        res = TCL_ERROR;
    else {
        if (certVar && Tcl_GetStringFromObj(certVar, &n) && n != 0)
            certPP = &certP;
        else
            certPP = NULL;

        in = ObjToByteArray(dataObj, &nin);
        nout = 0;
        if (! CryptDecryptMessage(&param, in, nin, NULL, &nout, certPP)) {
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        objP = ObjAllocateByteArray(nout, &out);
        if (! CryptDecryptMessage(&param, in, nin, out, &nout, certPP)) {
                res = TwapiReturnSystemError(interp);
                ObjDecrRefs(objP);
                goto vamoose;
            }
        Tcl_SetByteArrayLength(objP, nout);
        if (certPP) {







|











|

>


>
|
|




<
<














|
















|

>


|
>
|





<
<
















|

















|

>



>
|




<
<


















|







3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529


3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573


3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619


3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
    
    /*
     * NOTE: The sample 5.26 in Secure Programming Cookbook does not
     * match the SDK and SDK samples. In particular, it seems to confuse
     * the buffer size and data length parameters and requirements.
     * Code below follows the SDK
     */
    pv = ObjToByteArrayDW(objP, &len);
    if (!CryptDecrypt(hkey, hash, final, flags, pv, &len)) {
        DWORD winerr = GetLastError();
        if (duped)
            ObjDecrRefs(objP);
        return Twapi_AppendSystemError(interp, winerr);
    }
    Tcl_SetByteArrayLength(objP, len); /* Set length to actual # ciphertext */
    ObjSetResult(interp, objP);
    return TCL_OK;
}

static TCL_RESULT Twapi_CryptEncryptMessageObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *paramObj, *certsObj, *dataObj, *objP;
    TCL_RESULT res;
    int nin;
    DWORD ncerts, nout;
    PCCERT_CONTEXT *certsPP;
    BYTE *in, *out;
    CRYPT_ENCRYPT_MESSAGE_PARA param;
    MemLifoMarkHandle mark = NULL;



    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETOBJ(paramObj), GETOBJ(certsObj),
                       GETOBJ(dataObj), ARGEND) != TCL_OK
        || ParseCRYPT_ENCRYPT_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK
        || ParsePCERT_CONTEXT_Array(ticP, certsObj, &ncerts, &certsPP) != TCL_OK) {
        res = TCL_ERROR;
    } else {
        in = ObjToByteArray(dataObj, &nin);
        nout = 0;
        if (! CryptEncryptMessage(&param, ncerts, certsPP, in, nin, NULL, &nout)) {
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        objP = ObjAllocateByteArray(nout, (void **) &out);
        if (! CryptEncryptMessage(&param, ncerts, certsPP, in, nin, out, &nout)) {
            res = TwapiReturnSystemError(interp);
            ObjDecrRefs(objP);
            goto vamoose;
        }
        Tcl_SetByteArrayLength(objP, nout);
        ObjSetResult(interp, objP);
        res = TCL_OK;
    }

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptSignAndEncryptMessageObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *signparamObj, *encparamObj, *certsObj, *dataObj, *objP;
    TCL_RESULT res;
    DWORD ncerts, nout;
    int nin;
    PCCERT_CONTEXT *certsPP;
    BYTE *in, *out;
    CRYPT_SIGN_MESSAGE_PARA sign_param;
    CRYPT_ENCRYPT_MESSAGE_PARA enc_param;
    MemLifoMarkHandle mark = NULL;



    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(signparamObj),
                       GETOBJ(encparamObj), GETOBJ(certsObj),
                       GETOBJ(dataObj), ARGEND) != TCL_OK
        || ParseCRYPT_SIGN_MESSAGE_PARA(ticP, signparamObj, &sign_param) != TCL_OK
        || ParseCRYPT_ENCRYPT_MESSAGE_PARA(ticP, encparamObj, &enc_param) != TCL_OK
        || ParsePCERT_CONTEXT_Array(ticP, certsObj, &ncerts, &certsPP) != TCL_OK) {
        res = TCL_ERROR;
    } else {
        in = ObjToByteArray(dataObj, &nin);
        nout = 0;
        if (! CryptSignAndEncryptMessage(&sign_param, &enc_param, ncerts,
                                         certsPP, in, nin, NULL, &nout)) {
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        objP = ObjAllocateByteArray(nout, (void **) &out);
        if (! CryptSignAndEncryptMessage(&sign_param, &enc_param, ncerts,
                                  certsPP, in, nin, out, &nout)) {
            res = TwapiReturnSystemError(interp);
            ObjDecrRefs(objP);
            goto vamoose;
        }
        Tcl_SetByteArrayLength(objP, nout);
        ObjSetResult(interp, objP);
        res = TCL_OK;
    }

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptDecryptMessageObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    MemLifoMarkHandle mark = NULL;
    Tcl_Obj *paramObj, *dataObj, *objP, *certVar;
    TCL_RESULT res;
    DWORD nout;
    int  n, nin;
    BYTE *in, *out;
    CRYPT_DECRYPT_MESSAGE_PARA param;
    PCCERT_CONTEXT certP, *certPP;



    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETOBJ(paramObj), GETOBJ(dataObj), ARGUSEDEFAULT,
                       GETOBJ(certVar), ARGEND) != TCL_OK
        || ParseCRYPT_DECRYPT_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK)
        res = TCL_ERROR;
    else {
        if (certVar && Tcl_GetStringFromObj(certVar, &n) && n != 0)
            certPP = &certP;
        else
            certPP = NULL;

        in = ObjToByteArray(dataObj, &nin);
        nout = 0;
        if (! CryptDecryptMessage(&param, in, nin, NULL, &nout, certPP)) {
            res = TwapiReturnSystemError(interp);
            goto vamoose;
        }
        objP = ObjAllocateByteArray(nout, (void **) &out);
        if (! CryptDecryptMessage(&param, in, nin, out, &nout, certPP)) {
                res = TwapiReturnSystemError(interp);
                ObjDecrRefs(objP);
                goto vamoose;
            }
        Tcl_SetByteArrayLength(objP, nout);
        if (certPP) {
3677
3678
3679
3680
3681
3682
3683
3684
3685

3686
3687

3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptVerifyMessageSignatureObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *dataObj, *paramObj, *contentVar, *certVar, *contentObj;
    TCL_RESULT res;

    int  n, nin, nout;
    BYTE *in, *out;
    CRYPT_VERIFY_MESSAGE_PARA param;
    DWORD signer_index;
    PCCERT_CONTEXT certP = NULL, *certPP;
    MemLifoMarkHandle mark = NULL;
    DWORD winerr;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETINT(signer_index), GETOBJ(dataObj),
                     ARGUSEDEFAULT, GETOBJ(contentVar), GETOBJ(certVar),
                     ARGEND) != TCL_OK
        || ParseCRYPT_VERIFY_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK) {







|

>


>
|







<
<







3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682


3683
3684
3685
3686
3687
3688
3689

vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptVerifyMessageSignatureObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *dataObj, *paramObj, *contentVar, *certVar, *contentObj;
    TCL_RESULT res;
    DWORD nout;
    int  n, nin;
    BYTE *in, *out;
    CRYPT_VERIFY_MESSAGE_PARA param;
    DWORD signer_index;
    PCCERT_CONTEXT certP = NULL, *certPP;
    MemLifoMarkHandle mark = NULL;
    DWORD winerr;



    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETINT(signer_index), GETOBJ(dataObj),
                     ARGUSEDEFAULT, GETOBJ(contentVar), GETOBJ(certVar),
                     ARGEND) != TCL_OK
        || ParseCRYPT_VERIFY_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK) {
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
           treat as detached message and raise an error 
        */
        ObjSetStaticResult(interp, "No data found associated with signature. Use the detached message verification command instead.");
        goto error_return;
    }
    /* Verified. If we need the content, need to call it again with a buffer */
    if (contentVar && Tcl_GetStringFromObj(contentVar, &n) && n != 0) {
        contentObj = ObjAllocateByteArray(nout, &out);
        if (! CryptVerifyMessageSignature(&param, signer_index, in, nin, out, &nout, certPP))
            goto system_error;
        Tcl_SetByteArrayLength(contentObj, nout);
        if (Tcl_ObjSetVar2(interp, contentVar, NULL, contentObj, TCL_LEAVE_ERR_MSG) == NULL)
            goto error_return;
    }
    if (certPP) {







|







3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
           treat as detached message and raise an error 
        */
        ObjSetStaticResult(interp, "No data found associated with signature. Use the detached message verification command instead.");
        goto error_return;
    }
    /* Verified. If we need the content, need to call it again with a buffer */
    if (contentVar && Tcl_GetStringFromObj(contentVar, &n) && n != 0) {
        contentObj = ObjAllocateByteArray(nout, (void **) &out);
        if (! CryptVerifyMessageSignature(&param, signer_index, in, nin, out, &nout, certPP))
            goto system_error;
        Tcl_SetByteArrayLength(contentObj, nout);
        if (Tcl_ObjSetVar2(interp, contentVar, NULL, contentObj, TCL_LEAVE_ERR_MSG) == NULL)
            goto error_return;
    }
    if (certPP) {
3772
3773
3774
3775
3776
3777
3778
3779
3780

3781
3782

3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
    if (certPP && *certPP)
        CertFreeCertificateContext(*certPP);
    if (contentObj)
        ObjDecrRefs(contentObj);
    goto vamoose; 
}

static TCL_RESULT Twapi_CryptVerifyMessageSignatureWithKeyObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *dataObj, *pkinfoObj, *contentVar, *contentObj;
    TCL_RESULT res;

    int  nin, nout;
    BYTE *in, *out;
    MemLifoMarkHandle mark = NULL;
    CRYPT_KEY_VERIFY_MESSAGE_PARA param;
    CERT_PUBLIC_KEY_INFO pkinfo;

    contentObj = NULL;
    
    param.cbSize = sizeof(param);
    param.dwMsgEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
    param.hCryptProv = 0;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETOBJ(pkinfoObj),
                     GETOBJ(dataObj),
                     ARGUSEDEFAULT, GETOBJ(contentVar),
                     ARGEND) != TCL_OK







|

>


>
|











<
<







3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781


3782
3783
3784
3785
3786
3787
3788
    if (certPP && *certPP)
        CertFreeCertificateContext(*certPP);
    if (contentObj)
        ObjDecrRefs(contentObj);
    goto vamoose; 
}

static TCL_RESULT Twapi_CryptVerifyMessageSignatureWithKeyObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *dataObj, *pkinfoObj, *contentVar, *contentObj;
    TCL_RESULT res;
    DWORD nout;
    int  nin;
    BYTE *in, *out;
    MemLifoMarkHandle mark = NULL;
    CRYPT_KEY_VERIFY_MESSAGE_PARA param;
    CERT_PUBLIC_KEY_INFO pkinfo;

    contentObj = NULL;
    
    param.cbSize = sizeof(param);
    param.dwMsgEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
    param.hCryptProv = 0;



    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETOBJ(pkinfoObj),
                     GETOBJ(dataObj),
                     ARGUSEDEFAULT, GETOBJ(contentVar),
                     ARGEND) != TCL_OK
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
     * generate a unicode rep
     */
    if (contentVar) {
        /* content will never be more than number of input bytes */
        contentObj = ObjFromByteArray(NULL, nin);
        /* Incr ref in case of errors setting variable */
        ObjIncrRefs(contentObj);
        out = ObjToByteArray(contentObj, &nout);
    } else {
        contentObj = NULL;
        out = NULL;
        nout = 0;
    }
    
    if (! CryptVerifyMessageSignatureWithKey(&param, &pkinfo, in, nin, out, &nout)) {







|







3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
     * generate a unicode rep
     */
    if (contentVar) {
        /* content will never be more than number of input bytes */
        contentObj = ObjFromByteArray(NULL, nin);
        /* Incr ref in case of errors setting variable */
        ObjIncrRefs(contentObj);
        out = ObjToByteArrayDW(contentObj, &nout);
    } else {
        contentObj = NULL;
        out = NULL;
        nout = 0;
    }
    
    if (! CryptVerifyMessageSignatureWithKey(&param, &pkinfo, in, nin, out, &nout)) {
3843
3844
3845
3846
3847
3848
3849
3850
3851

3852
3853
3854
3855
3856

3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
    if (contentObj)
        ObjDecrRefs(contentObj);
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptVerifyDetachedMessageSignatureObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *sigObj, *contentObj, *paramObj, *certVar;
    TCL_RESULT res;
    int  i, n, nin, ndata;
    Tcl_Obj **dataObjs;
    BYTE *in, **dataPP;

    DWORD *datalenP;
    CRYPT_VERIFY_MESSAGE_PARA param;
    DWORD signer_index;
    PCCERT_CONTEXT certP, *certPP;
    MemLifoMarkHandle mark = NULL;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETINT(signer_index), GETOBJ(sigObj),
                     GETOBJ(contentObj), ARGUSEDEFAULT,
                     GETOBJ(certVar), ARGEND) != TCL_OK
        || ParseCRYPT_VERIFY_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK







|

>




|
>






<
<







3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849


3850
3851
3852
3853
3854
3855
3856
    if (contentObj)
        ObjDecrRefs(contentObj);
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptVerifyDetachedMessageSignatureObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *sigObj, *contentObj, *paramObj, *certVar;
    TCL_RESULT res;
    int  i, n, nin, ndata;
    Tcl_Obj **dataObjs;
    BYTE *in;
    const BYTE **dataPP;
    DWORD *datalenP;
    CRYPT_VERIFY_MESSAGE_PARA param;
    DWORD signer_index;
    PCCERT_CONTEXT certP, *certPP;
    MemLifoMarkHandle mark = NULL;



    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETINT(signer_index), GETOBJ(sigObj),
                     GETOBJ(contentObj), ARGUSEDEFAULT,
                     GETOBJ(certVar), ARGEND) != TCL_OK
        || ParseCRYPT_VERIFY_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
    else
        certPP = NULL;

    /* To avoid shimmering issues, extract byte arrays after other objects */
    dataPP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*dataPP), NULL);
    datalenP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*datalenP), NULL);
    for (i = 0; i < ndata; ++i)
        dataPP[i] = ObjToByteArray(dataObjs[i], &datalenP[i]);
    
    in = ObjToByteArray(sigObj, &nin);
    if (CryptVerifyDetachedMessageSignature(&param, signer_index, in, nin, 
                                            ndata, dataPP, datalenP, certPP)) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }







|







3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
    else
        certPP = NULL;

    /* To avoid shimmering issues, extract byte arrays after other objects */
    dataPP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*dataPP), NULL);
    datalenP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*datalenP), NULL);
    for (i = 0; i < ndata; ++i)
        dataPP[i] = ObjToByteArrayDW(dataObjs[i], &datalenP[i]);
    
    in = ObjToByteArray(sigObj, &nin);
    if (CryptVerifyDetachedMessageSignature(&param, signer_index, in, nin, 
                                            ndata, dataPP, datalenP, certPP)) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }
3912
3913
3914
3915
3916
3917
3918
3919
3920

3921
3922
3923

3924
3925

3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976

3977
3978
3979

3980
3981

3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032

4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
    res = TCL_OK;
vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptSignMessageObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *sigObj, *contentObj, *paramObj;
    TCL_RESULT res;
    int  i, nsig, ndata;

    Tcl_Obj **dataObjs;
    BYTE *sig, **dataPP;

    DWORD *datalenP;
    int detached;
    CRYPT_SIGN_MESSAGE_PARA param;
    MemLifoMarkHandle mark = NULL;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETBOOL(detached), GETOBJ(contentObj), ARGEND) != TCL_OK
        || ParseCRYPT_SIGN_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK
        || ObjGetElements(interp, contentObj, &ndata, &dataObjs) != TCL_OK) {
         res = TCL_ERROR;
         goto vamoose;
    }

    if (ndata == 0) {
        res = TwapiReturnError(interp, TWAPI_INVALID_DATA);
        goto vamoose;
    }

    /* To avoid shimmering issues, extract byte arrays after other objects */
    dataPP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*dataPP), NULL);
    datalenP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*datalenP), NULL);
    for (i = 0; i < ndata; ++i)
        dataPP[i] = ObjToByteArray(dataObjs[i], &datalenP[i]);

    nsig = 0;
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          NULL, &nsig)) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }
    sigObj = ObjAllocateByteArray(nsig, &sig);
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          sig, &nsig)) {
        res = TwapiReturnSystemError(interp);
        ObjDecrRefs(sigObj);
        goto vamoose;
    }
    Tcl_SetByteArrayLength(sigObj, nsig);
    res = ObjSetResult(interp, sigObj);
vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptSignMessageWithKeyObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    Tcl_Obj *sigObj, *contentObj, *paramObj;
    TCL_RESULT res;
    int  i, nsig, ndata;

    Tcl_Obj **dataObjs;
    BYTE *sig, **dataPP;

    DWORD *datalenP;
    int detached;
    CRYPT_SIGN_MESSAGE_PARA param;
    MemLifoMarkHandle mark = NULL;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETBOOL(detached), GETOBJ(sigObj),
                     GETOBJ(contentObj), ARGEND) != TCL_OK
        || ParseCRYPT_SIGN_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK
        || ObjGetElements(interp, contentObj, &ndata, &dataObjs) != TCL_OK) {
         res = TCL_ERROR;
         goto vamoose;
    }

    if (ndata == 0) {
        res = TwapiReturnError(interp, TWAPI_INVALID_DATA);
        goto vamoose;
    }

    /* To avoid shimmering issues, extract byte arrays after other objects */
    dataPP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*dataPP), NULL);
    datalenP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*datalenP), NULL);
    for (i = 0; i < ndata; ++i)
        dataPP[i] = ObjToByteArray(dataObjs[i], &datalenP[i]);

    nsig = 0;
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          NULL, &nsig)) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }
    sigObj = ObjAllocateByteArray(nsig, &sig);
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          sig, &nsig)) {
        res = TwapiReturnSystemError(interp);
        ObjDecrRefs(sigObj);
        goto vamoose;
    }
    Tcl_SetByteArrayLength(sigObj, nsig);
    res = ObjSetResult(interp, sigObj);
vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}
static TCL_RESULT Twapi_CryptExportKeyObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    void *hkey, *hwrapper;
    DWORD blob_type, flags, nbytes;
    BLOBHEADER *blobP;
    TCL_RESULT res;
    
    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hkey, HCRYPTKEY, CryptDestroyKey),
                     GETVERIFIEDORNULL(hwrapper, HCRYPTKEY, CryptDestroyKey),
                     GETINT(blob_type), GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (blob_type == PUBLICKEYBLOB)







|

>


|
>

|
>





<
<



















|







|














|

>


|
>

|
>





<
<




















|







|













|

>





<
<







3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918


3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975


3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025


4026
4027
4028
4029
4030
4031
4032
    res = TCL_OK;
vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptSignMessageObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *sigObj, *contentObj, *paramObj;
    TCL_RESULT res;
    int  i, ndata;
    DWORD nsig;
    Tcl_Obj **dataObjs;
    BYTE *sig;
    const BYTE **dataPP;
    DWORD *datalenP;
    int detached;
    CRYPT_SIGN_MESSAGE_PARA param;
    MemLifoMarkHandle mark = NULL;



    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETBOOL(detached), GETOBJ(contentObj), ARGEND) != TCL_OK
        || ParseCRYPT_SIGN_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK
        || ObjGetElements(interp, contentObj, &ndata, &dataObjs) != TCL_OK) {
         res = TCL_ERROR;
         goto vamoose;
    }

    if (ndata == 0) {
        res = TwapiReturnError(interp, TWAPI_INVALID_DATA);
        goto vamoose;
    }

    /* To avoid shimmering issues, extract byte arrays after other objects */
    dataPP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*dataPP), NULL);
    datalenP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*datalenP), NULL);
    for (i = 0; i < ndata; ++i)
        dataPP[i] = ObjToByteArrayDW(dataObjs[i], &datalenP[i]);

    nsig = 0;
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          NULL, &nsig)) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }
    sigObj = ObjAllocateByteArray(nsig, (void **) &sig);
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          sig, &nsig)) {
        res = TwapiReturnSystemError(interp);
        ObjDecrRefs(sigObj);
        goto vamoose;
    }
    Tcl_SetByteArrayLength(sigObj, nsig);
    res = ObjSetResult(interp, sigObj);
vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}

static TCL_RESULT Twapi_CryptSignMessageWithKeyObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    Tcl_Obj *sigObj, *contentObj, *paramObj;
    TCL_RESULT res;
    int  i, ndata;
    DWORD nsig;
    Tcl_Obj **dataObjs;
    BYTE *sig;
    const BYTE **dataPP;
    DWORD *datalenP;
    int detached;
    CRYPT_SIGN_MESSAGE_PARA param;
    MemLifoMarkHandle mark = NULL;



    mark = MemLifoPushMark(ticP->memlifoP);

    if (TwapiGetArgs(interp, objc-1, objv+1, GETOBJ(paramObj),
                     GETBOOL(detached), GETOBJ(sigObj),
                     GETOBJ(contentObj), ARGEND) != TCL_OK
        || ParseCRYPT_SIGN_MESSAGE_PARA(ticP, paramObj, &param) != TCL_OK
        || ObjGetElements(interp, contentObj, &ndata, &dataObjs) != TCL_OK) {
         res = TCL_ERROR;
         goto vamoose;
    }

    if (ndata == 0) {
        res = TwapiReturnError(interp, TWAPI_INVALID_DATA);
        goto vamoose;
    }

    /* To avoid shimmering issues, extract byte arrays after other objects */
    dataPP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*dataPP), NULL);
    datalenP = MemLifoAlloc(ticP->memlifoP, ndata*sizeof(*datalenP), NULL);
    for (i = 0; i < ndata; ++i)
        dataPP[i] = ObjToByteArrayDW(dataObjs[i], &datalenP[i]);

    nsig = 0;
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          NULL, &nsig)) {
        res = TwapiReturnSystemError(interp);
        goto vamoose;
    }
    sigObj = ObjAllocateByteArray(nsig, (void **)&sig);
    if (!CryptSignMessage(&param, detached, ndata, dataPP, datalenP,
                          sig, &nsig)) {
        res = TwapiReturnSystemError(interp);
        ObjDecrRefs(sigObj);
        goto vamoose;
    }
    Tcl_SetByteArrayLength(sigObj, nsig);
    res = ObjSetResult(interp, sigObj);
vamoose:
    if (mark)
        MemLifoPopMark(mark);
    return res;
}
static TCL_RESULT Twapi_CryptExportKeyObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    void *hkey, *hwrapper;
    DWORD blob_type, flags, nbytes;
    BLOBHEADER *blobP;
    TCL_RESULT res;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(hkey, HCRYPTKEY, CryptDestroyKey),
                     GETVERIFIEDORNULL(hwrapper, HCRYPTKEY, CryptDestroyKey),
                     GETINT(blob_type), GETINT(flags), ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (blob_type == PUBLICKEYBLOB)
4057
4058
4059
4060
4061
4062
4063
4064
4065

4066
4067
4068
4069

4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097

4098
4099
4100

4101
4102
4103
4104
4105
4106
4107
4108
4109
    } else
        res = TwapiReturnSystemError(interp);

    MemLifoPopFrame(ticP->memlifoP);
    return res;
}

static TCL_RESULT Twapi_CryptImportKeyObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    int btype, bver, breserved;
    ALG_ID balg_id;
    void *cryptH, *keyH;
    DWORD nbytes, flags;

    Tcl_Obj *blobObj, *keyObj;
    BLOBHEADER *blobP;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;
    HCRYPTKEY importH;
    int nclear = 0;
    
    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(cryptH, HCRYPTPROV, CryptReleaseContext),
                     GETOBJ(keyObj),
                     GETVERIFIEDORNULL(keyH, HCRYPTKEY, CryptDestroyKey),
                     GETINT(flags), ARGEND) != TCL_OK
        ||
        TwapiGetArgsObj(interp, keyObj,
                        GETINT(btype), GETINT(bver), GETINT(breserved), 
                        GETINT(balg_id), GETOBJ(blobObj), ARGEND) != TCL_OK)
        return TCL_ERROR;


    if (btype == 0) {
        /* 0 is not a valid CryptoAPI blob type so we use it to indicate
         * the key blob is plaintext sealed with twapi. We have to build
         * a PLAINTEXTBLOB header in front of it.
         */
        TWAPI_PLAINTEXTKEYBLOB *p;
        int keysize;

        mark = SWSPushMark();
        p = ObjDecryptBytesExSWS(interp, blobObj, offsetof(TWAPI_PLAINTEXTKEYBLOB, rgbKeyData), &keysize);
        if (p == NULL)

            goto vamoose;
        
        p->dwKeySize = keysize;
        nbytes = TWAPI_PLAINTEXTKEYBLOB_SIZE(p->dwKeySize);
        nclear = nbytes; /* Number of bytes to clear out */
        btype = PLAINTEXTKEYBLOB;
        blobP = &p->hdr;
        blobP->bType = btype;
        blobP->bVersion = bver;







|

>



|
>







<
<














|




>
|

|
>

|







4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064


4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
    } else
        res = TwapiReturnSystemError(interp);

    MemLifoPopFrame(ticP->memlifoP);
    return res;
}

static TCL_RESULT Twapi_CryptImportKeyObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int btype, bver, breserved;
    ALG_ID balg_id;
    void *cryptH, *keyH;
    int nbytes;
    DWORD flags;
    Tcl_Obj *blobObj, *keyObj;
    BLOBHEADER *blobP;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;
    HCRYPTKEY importH;
    int nclear = 0;
    


    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(cryptH, HCRYPTPROV, CryptReleaseContext),
                     GETOBJ(keyObj),
                     GETVERIFIEDORNULL(keyH, HCRYPTKEY, CryptDestroyKey),
                     GETINT(flags), ARGEND) != TCL_OK
        ||
        TwapiGetArgsObj(interp, keyObj,
                        GETINT(btype), GETINT(bver), GETINT(breserved), 
                        GETINT(balg_id), GETOBJ(blobObj), ARGEND) != TCL_OK)
        return TCL_ERROR;


    if (btype == 0) {
        /* 0 is not a valid CryptoAPI blob type so we use it to indicate
        * the key blob is plaintext sealed with twapi. We have to build
         * a PLAINTEXTBLOB header in front of it.
         */
        TWAPI_PLAINTEXTKEYBLOB *p;
        int keysize;
        TWAPI_ASSERT(SWS() == ticP->memlifoP);
        mark = MemLifoPushMark(ticP->memlifoP);
        p = ObjDecryptBytesExSWS(interp, blobObj, offsetof(TWAPI_PLAINTEXTKEYBLOB, rgbKeyData), &keysize);
        if (p == NULL) {
            res = TCL_ERROR;
            goto vamoose;
        }
        p->dwKeySize = keysize;
        nbytes = TWAPI_PLAINTEXTKEYBLOB_SIZE(p->dwKeySize);
        nclear = nbytes; /* Number of bytes to clear out */
        btype = PLAINTEXTKEYBLOB;
        blobP = &p->hdr;
        blobP->bType = btype;
        blobP->bVersion = bver;
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142

4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
            res = TwapiReturnSystemError(interp);
    }

vamoose:
    if (nclear)
        SecureZeroMemory(blobP, nclear); /* Clear out plaintext key */
    if (mark)
        SWSPopMark(mark);

    return res;
}

static TCL_RESULT Twapi_CryptImportPublicKeyInfoExObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    ALG_ID alg_id;
    void *cryptH;
    DWORD cert_encoding;
    Tcl_Obj *keyObj;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;
    HCRYPTKEY importH;
    CERT_PUBLIC_KEY_INFO cpki;
    int nclear = 0;
    
    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP); /* For ParseCERT* below */
    if ((res = TwapiGetArgs(interp, objc-1, objv+1,
                            GETVERIFIEDPTR(cryptH, HCRYPTPROV, CryptReleaseContext),
                            GETINT(cert_encoding),
                            GETOBJ(keyObj),
                            GETINT(alg_id), ARGEND)) != TCL_OK ||
        (res = ParseCERT_PUBLIC_KEY_INFO(ticP, keyObj, &cpki)) != TCL_OK) {







|




|

>








<

<
<







4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139

4140


4141
4142
4143
4144
4145
4146
4147
            res = TwapiReturnSystemError(interp);
    }

vamoose:
    if (nclear)
        SecureZeroMemory(blobP, nclear); /* Clear out plaintext key */
    if (mark)
        MemLifoPopMark(mark);

    return res;
}

static TCL_RESULT Twapi_CryptImportPublicKeyInfoExObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    ALG_ID alg_id;
    void *cryptH;
    DWORD cert_encoding;
    Tcl_Obj *keyObj;
    MemLifoMarkHandle mark = NULL;
    TCL_RESULT res;
    HCRYPTKEY importH;
    CERT_PUBLIC_KEY_INFO cpki;

    


    mark = MemLifoPushMark(ticP->memlifoP); /* For ParseCERT* below */
    if ((res = TwapiGetArgs(interp, objc-1, objv+1,
                            GETVERIFIEDPTR(cryptH, HCRYPTPROV, CryptReleaseContext),
                            GETINT(cert_encoding),
                            GETOBJ(keyObj),
                            GETINT(alg_id), ARGEND)) != TCL_OK ||
        (res = ParseCERT_PUBLIC_KEY_INFO(ticP, keyObj, &cpki)) != TCL_OK) {
4180
4181
4182
4183
4184
4185
4186

4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203

4204
4205

4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
static TCL_RESULT Twapi_CryptoCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;
    DWORD dw, dw2, dw3;
    DWORD_PTR dwp;
    LPVOID pv,pv2;
    LPWSTR s1;

    LPSTR  cP;
    struct _CRYPTOAPI_BLOB blob, blob2;
    PCCERT_CONTEXT certP, cert2P;
    void *bufP;
    DWORD buf_sz;
    Tcl_Obj *s1Obj, *s2Obj;
    BOOL bval;
    int func = PtrToInt(clientdata);
    Tcl_Obj *objs[11];
    TCL_RESULT res;
    CERT_INFO *ciP;
    HCERTSTORE hstore;
    HANDLE h, h2;
    union {
        GUID guid;
        WCHAR uni[MAX_PATH+1];
        char ansi[MAX_PATH+1];

        CATALOG_INFO catinfo;
    } buf;

    SWSMark mark = NULL;
    
    ObjToUnicodeCleanup();

    --objc;
    ++objv;

    TWAPI_ASSERT(sizeof(HCRYPTPROV) <= sizeof(pv));
    TWAPI_ASSERT(sizeof(HCRYPTKEY) <= sizeof(pv));
    TWAPI_ASSERT(sizeof(HCRYPTHASH) <= sizeof(pv));
    TWAPI_ASSERT(sizeof(dwp) <= sizeof(void*));







>
|
















>


>


<
<







4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196


4197
4198
4199
4200
4201
4202
4203
static TCL_RESULT Twapi_CryptoCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;
    DWORD dw, dw2, dw3;
    DWORD_PTR dwp;
    LPVOID pv,pv2;
    LPWSTR s1;
    BYTE  *bytesP;
    char  *cP;
    struct _CRYPTOAPI_BLOB blob, blob2;
    PCCERT_CONTEXT certP, cert2P;
    void *bufP;
    DWORD buf_sz;
    Tcl_Obj *s1Obj, *s2Obj;
    BOOL bval;
    int func = PtrToInt(clientdata);
    Tcl_Obj *objs[11];
    TCL_RESULT res;
    CERT_INFO *ciP;
    HCERTSTORE hstore;
    HANDLE h, h2;
    union {
        GUID guid;
        WCHAR uni[MAX_PATH+1];
        char ansi[MAX_PATH+1];
        BYTE bytes[MAX_PATH+1];
        CATALOG_INFO catinfo;
    } buf;
    int ival;
    SWSMark mark = NULL;
    


    --objc;
    ++objv;

    TWAPI_ASSERT(sizeof(HCRYPTPROV) <= sizeof(pv));
    TWAPI_ASSERT(sizeof(HCRYPTKEY) <= sizeof(pv));
    TWAPI_ASSERT(sizeof(HCRYPTHASH) <= sizeof(pv));
    TWAPI_ASSERT(sizeof(dwp) <= sizeof(void*));
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
                         GETINT(dw), GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        return Twapi_CryptGetProvParam(interp, (HCRYPTPROV) pv, dw, dw2);

    case 10003: // CertOpenSystemStore
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        pv = CertOpenSystemStoreW(0, ObjToUnicode(objv[0]));
        if (pv) {
            /* CertCloseStore does not check ponter validity! So do ourselves*/
            TwapiRegisterHCERTSTORE(interp, pv);
            TwapiResult_SET_NONNULL_PTR(result, HCERTSTORE, pv);
        } else {
            return TwapiReturnSystemError(interp);
        }







|







4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
                         GETINT(dw), GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        return Twapi_CryptGetProvParam(interp, (HCRYPTPROV) pv, dw, dw2);

    case 10003: // CertOpenSystemStore
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        pv = CertOpenSystemStoreW(0, ObjToWinChars(objv[0]));
        if (pv) {
            /* CertCloseStore does not check ponter validity! So do ourselves*/
            TwapiRegisterHCERTSTORE(interp, pv);
            TwapiResult_SET_NONNULL_PTR(result, HCERTSTORE, pv);
        } else {
            return TwapiReturnSystemError(interp);
        }
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
        }
        break;

    case 10005: // CertCreateCertificateContext
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
        cP = ObjToByteArray(objv[1], &dw2);
        certP = CertCreateCertificateContext(dw, cP, dw2);
        if (certP) {
            TwapiRegisterPCCERT_CONTEXT(interp, certP);
            TwapiResult_SET_NONNULL_PTR(result, PCCERT_CONTEXT, (void*)certP);
        } else
            result.type = TRT_GETLASTERROR;
        break;








|
|







4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
        }
        break;

    case 10005: // CertCreateCertificateContext
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
        bytesP = ObjToByteArrayDW(objv[1], &dw2);
        certP = CertCreateCertificateContext(dw, bytesP, dw2);
        if (certP) {
            TwapiRegisterPCCERT_CONTEXT(interp, certP);
            TwapiResult_SET_NONNULL_PTR(result, PCCERT_CONTEXT, (void*)certP);
        } else
            result.type = TRT_GETLASTERROR;
        break;

4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468

    case 10011: // CertStrToName
        if (TwapiGetArgs(interp, objc, objv, GETOBJ(s1Obj), ARGUSEDEFAULT,
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_GETLASTERROR;
        dw2 = 0;
        s1 = ObjToUnicode(s1Obj); /* Do AFTER extracting other args above */
        if (CertStrToNameW(X509_ASN_ENCODING, s1,
                           dw, NULL, NULL, &dw2, NULL)) {
            result.value.obj = ObjFromByteArray(NULL, dw2);
            if (CertStrToNameW(X509_ASN_ENCODING, s1, dw, NULL,
                               ObjToByteArray(result.value.obj, &dw2),
                               &dw2, NULL)) {
                Tcl_SetByteArrayLength(result.value.obj, dw2);
                result.type = TRT_OBJ;
            } else {
                ObjDecrRefs(result.value.obj);
            }
        }
        break;

    case 10012: // CertNameToStr
        if (TwapiGetArgs(interp, objc, objv, ARGSKIP, GETINT(dw), ARGEND)
            != TCL_OK)
            return TCL_ERROR;
        blob.pbData = ObjToByteArray(objv[0], &blob.cbData);
        result.type = TRT_OBJ;
        result.value.obj = ObjFromCERT_NAME_BLOB(&blob, dw);
        break;

    case 10013: // CertGetNameString
        if (TwapiGetArgs(interp, objc, objv,
                         GETVERIFIEDPTR(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                         GETINT(dw), GETINT(dw2), ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
            
        return TwapiCertGetNameString(interp, certP, dw, dw2, objv[3]);

            
    case 10016: // CertUnregisterSystemStore
        /* This command is there to primarily clean up mistakes in testing */
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s1Obj), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = CertUnregisterSystemStore(ObjToUnicode(s1Obj), dw);
        break;
    case 10017: // CertCloseStore
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLET(pv, HCERTSTORE), ARGUSEDEFAULT,
                         GETINT(dw), ARGEND) != TCL_OK ||
            TwapiUnregisterHCERTSTORE(interp, pv) != TCL_OK)
            return TCL_ERROR;







|




|













|



















|







4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455

    case 10011: // CertStrToName
        if (TwapiGetArgs(interp, objc, objv, GETOBJ(s1Obj), ARGUSEDEFAULT,
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_GETLASTERROR;
        dw2 = 0;
        s1 = ObjToWinChars(s1Obj); /* Do AFTER extracting other args above */
        if (CertStrToNameW(X509_ASN_ENCODING, s1,
                           dw, NULL, NULL, &dw2, NULL)) {
            result.value.obj = ObjFromByteArray(NULL, dw2);
            if (CertStrToNameW(X509_ASN_ENCODING, s1, dw, NULL,
                               ObjToByteArrayDW(result.value.obj, &dw2),
                               &dw2, NULL)) {
                Tcl_SetByteArrayLength(result.value.obj, dw2);
                result.type = TRT_OBJ;
            } else {
                ObjDecrRefs(result.value.obj);
            }
        }
        break;

    case 10012: // CertNameToStr
        if (TwapiGetArgs(interp, objc, objv, ARGSKIP, GETINT(dw), ARGEND)
            != TCL_OK)
            return TCL_ERROR;
        blob.pbData = ObjToByteArrayDW(objv[0], &blob.cbData);
        result.type = TRT_OBJ;
        result.value.obj = ObjFromCERT_NAME_BLOB(&blob, dw);
        break;

    case 10013: // CertGetNameString
        if (TwapiGetArgs(interp, objc, objv,
                         GETVERIFIEDPTR(certP, PCCERT_CONTEXT, CertFreeCertificateContext),
                         GETINT(dw), GETINT(dw2), ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
            
        return TwapiCertGetNameString(interp, certP, dw, dw2, objv[3]);

            
    case 10016: // CertUnregisterSystemStore
        /* This command is there to primarily clean up mistakes in testing */
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(s1Obj), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = CertUnregisterSystemStore(ObjToWinChars(s1Obj), dw);
        break;
    case 10017: // CertCloseStore
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLET(pv, HCERTSTORE), ARGUSEDEFAULT,
                         GETINT(dw), ARGEND) != TCL_OK ||
            TwapiUnregisterHCERTSTORE(interp, pv) != TCL_OK)
            return TCL_ERROR;
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
        return Twapi_CryptSetProvParam(interp, (HCRYPTPROV) pv, dw, dw2, objv[3]);

    case 10020: // CertOpenStore
        return Twapi_CertOpenStore(interp, objc, objv);

    case 10021: // CryptEnumOIDInfo
        CHECK_NARGS(interp, objc, 1);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        result.value.obj = ObjNewList(0, NULL);
        CryptEnumOIDInfo(dw, 0, result.value.obj, TwapiCryptEnumOIDInfoCB);
        result.type = TRT_OBJ;
        break;

    case 10022: // CertAddCertificateContextToStore
        /* TBD - add option to not require added certificate context







|







4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
        return Twapi_CryptSetProvParam(interp, (HCRYPTPROV) pv, dw, dw2, objv[3]);

    case 10020: // CertOpenStore
        return Twapi_CertOpenStore(interp, objc, objv);

    case 10021: // CryptEnumOIDInfo
        CHECK_NARGS(interp, objc, 1);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        result.value.obj = ObjNewList(0, NULL);
        CryptEnumOIDInfo(dw, 0, result.value.obj, TwapiCryptEnumOIDInfoCB);
        result.type = TRT_OBJ;
        break;

    case 10022: // CertAddCertificateContextToStore
        /* TBD - add option to not require added certificate context
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
            result.value.ival = TwapiReturnSystemError(interp);
        }
        SWSPopFrame();
        break;

    case 10024:
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        if (dw & CERT_SYSTEM_STORE_RELOCATE_FLAG)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "RELOCATE flag not supported.");
        result.value.obj = ObjNewList(0, NULL);
        if (CertEnumSystemStore(dw, ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
                                result.value.obj,
                                TwapiCertEnumSystemStoreCallback)) {
            result.type = TRT_OBJ;
        } else {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        break;

    case 10025:
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);
        if (dw & CERT_SYSTEM_STORE_RELOCATE_FLAG)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "RELOCATE flag not supported.");
        result.value.obj = ObjNewList(0, NULL);
        if (CertEnumPhysicalStore(ObjToUnicode(objv[0]), dw,
                                result.value.obj,
                                TwapiCertEnumPhysicalStoreCallback)) {
            result.type = TRT_OBJ;
        } else {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        break;

    case 10026:
        CHECK_NARGS(interp, objc, 1);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        if (dw & CERT_SYSTEM_STORE_RELOCATE_FLAG)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "RELOCATE flag not supported.");
        result.value.obj = ObjNewList(0, NULL);
        if (CertEnumSystemStoreLocation(dw, result.value.obj,
                                        TwapiCertEnumSystemStoreLocationCallback)) {
            result.type = TRT_OBJ;
        } else {







|
















|



|












|







4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
            result.value.ival = TwapiReturnSystemError(interp);
        }
        SWSPopFrame();
        break;

    case 10024:
        CHECK_NARGS(interp, objc, 2);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        if (dw & CERT_SYSTEM_STORE_RELOCATE_FLAG)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "RELOCATE flag not supported.");
        result.value.obj = ObjNewList(0, NULL);
        if (CertEnumSystemStore(dw, ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
                                result.value.obj,
                                TwapiCertEnumSystemStoreCallback)) {
            result.type = TRT_OBJ;
        } else {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        break;

    case 10025:
        CHECK_NARGS(interp, objc, 2);
        CHECK_DWORD_OBJ(interp, dw, objv[1]);
        if (dw & CERT_SYSTEM_STORE_RELOCATE_FLAG)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "RELOCATE flag not supported.");
        result.value.obj = ObjNewList(0, NULL);
        if (CertEnumPhysicalStore(ObjToWinChars(objv[0]), dw,
                                result.value.obj,
                                TwapiCertEnumPhysicalStoreCallback)) {
            result.type = TRT_OBJ;
        } else {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        break;

    case 10026:
        CHECK_NARGS(interp, objc, 1);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        if (dw & CERT_SYSTEM_STORE_RELOCATE_FLAG)
            return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "RELOCATE flag not supported.");
        result.value.obj = ObjNewList(0, NULL);
        if (CertEnumSystemStoreLocation(dw, result.value.obj,
                                        TwapiCertEnumSystemStoreLocationCallback)) {
            result.type = TRT_OBJ;
        } else {
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
           decode a cert without needing a temp store */
        /* TBD - add option to not require added certificate context
           to be returned */
        if (TwapiGetArgs(interp, objc, objv,
                         GETVERIFIEDPTR(pv, HCERTSTORE, CertCloseStore),
                         GETINT(dw), ARGSKIP, GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        cP = ObjToByteArray(objv[2], &dw3);
        if (CertAddEncodedCertificateToStore(pv, dw, cP, dw3, dw2, &certP)) {
            TwapiRegisterPCCERT_CONTEXT(interp, certP);
            TwapiResult_SET_NONNULL_PTR(result, PCCERT_CONTEXT, (void*)certP);
        } else
            result.type = TRT_GETLASTERROR;
        break;
    case 10039: // CertOIDToAlgId
        CHECK_NARGS(interp, objc, 1);
        dw = CertOIDToAlgId(ObjToString(objv[0]));
        /* For ease of reading, return as a hex formatted */
        result.value.obj = ObjFromULONGHex(dw);
        result.type = TRT_OBJ;
        break;
    case 10040: // CertAlgIdToOID
        CHECK_NARGS(interp, objc, 1);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        result.type = TRT_CHARS;
        result.value.chars.str = (char *) CertAlgIdToOID(dw);
        result.value.chars.len = -1;
        break;

        // case 10041 is above








|
|














|







4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
           decode a cert without needing a temp store */
        /* TBD - add option to not require added certificate context
           to be returned */
        if (TwapiGetArgs(interp, objc, objv,
                         GETVERIFIEDPTR(pv, HCERTSTORE, CertCloseStore),
                         GETINT(dw), ARGSKIP, GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        bytesP = ObjToByteArrayDW(objv[2], &dw3);
        if (CertAddEncodedCertificateToStore(pv, dw, bytesP, dw3, dw2, &certP)) {
            TwapiRegisterPCCERT_CONTEXT(interp, certP);
            TwapiResult_SET_NONNULL_PTR(result, PCCERT_CONTEXT, (void*)certP);
        } else
            result.type = TRT_GETLASTERROR;
        break;
    case 10039: // CertOIDToAlgId
        CHECK_NARGS(interp, objc, 1);
        dw = CertOIDToAlgId(ObjToString(objv[0]));
        /* For ease of reading, return as a hex formatted */
        result.value.obj = ObjFromULONGHex(dw);
        result.type = TRT_OBJ;
        break;
    case 10040: // CertAlgIdToOID
        CHECK_NARGS(interp, objc, 1);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        result.type = TRT_CHARS;
        result.value.chars.str = (char *) CertAlgIdToOID(dw);
        result.value.chars.len = -1;
        break;

        // case 10041 is above

4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
        result.value.obj = ObjFromOpaque(pv, "HCERTSTORE");
        result.type = TRT_OBJ;
        break;

    case 10043: // PFXIsPFXBlob
        CHECK_NARGS(interp, objc, 1);
        result.type = TRT_BOOL;
        blob.pbData = ObjToByteArray(objv[0], &blob.cbData);
        result.value.bval = PFXIsPFXBlob(&blob);
        break;

    case 10044: // PFXVerifyPassword
        CHECK_NARGS(interp, objc, 2);
        mark = SWSPushMark();
        pv = ObjDecryptUnicodeSWS(interp, objv[1], &dw);
        if (pv == NULL) {
            /* Can't just return because have to clean up SWS at bottom */
            result.type = TRT_TCL_RESULT;
            result.value.ival = TCL_ERROR;
            break;
        }
        result.type = TRT_BOOL;
        blob.pbData = ObjToByteArray(objv[0], &blob.cbData);
        result.value.bval = PFXVerifyPassword(&blob, pv, 0);
        SecureZeroMemory(pv, sizeof(WCHAR) * dw);
        break;

    case 10045: // Twapi_CertStoreSerialize
        if (TwapiGetArgs(interp, objc, objv,
                         GETVERIFIEDPTR(hstore, HCERTSTORE, CertCloseStore),
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        blob.pbData = NULL;
        blob.cbData = 0;
        if (! CertSaveStore(hstore, PKCS_7_ASN_ENCODING|X509_ASN_ENCODING,
                            dw, CERT_STORE_SAVE_TO_MEMORY, &blob, 0))
            return TwapiReturnSystemError(interp);
        result.value.obj = ObjAllocateByteArray(blob.cbData, &blob.pbData);
        if (! CertSaveStore(hstore, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
                            dw, CERT_STORE_SAVE_TO_MEMORY, &blob, 0)) {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        Tcl_SetByteArrayLength(result.value.obj, blob.cbData);
        result.type = TRT_OBJ;
        break;

    case 10046: // CryptStringToBinary
        if (TwapiGetArgs(interp, objc, objv, GETOBJ(s1Obj),
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToUnicodeN(s1Obj, &dw2);
        if (!CryptStringToBinaryW(s1, dw2, dw, NULL, &dw3, NULL, NULL))
            return TwapiReturnSystemError(interp);
        result.value.obj = ObjAllocateByteArray(dw3, &pv);
        if (!CryptStringToBinaryW(s1, dw2, dw, pv, &dw3, NULL, NULL)) {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
        }
        Tcl_SetByteArrayLength(result.value.obj, dw3);
        result.type = TRT_OBJ;
        break;
    case 10047: // CryptBinaryToString
        if (TwapiGetArgs(interp, objc, objv, GETOBJ(s1Obj),
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        pv = ObjToByteArray(s1Obj, &dw2);
        if (!CryptBinaryToStringW(pv, dw2, dw, NULL, &dw3))
            return TwapiReturnSystemError(interp);
        /* dw3 includes space for terminating \0 since we passed NULL above */
        pv2 = SWSPushFrame(sizeof(WCHAR)*dw3, NULL);
        if (CryptBinaryToStringW(pv, dw2, dw, pv2, &dw3)) {
            /* dw3 does NOT include terminating \0 */
            result.value.obj = ObjFromUnicodeN(pv2, dw3);
            result.type = TRT_OBJ;
        } else {
            result.value.ival = TwapiReturnSystemError(interp);
            result.type = TRT_TCL_RESULT;
        }        
        SWSPopFrame();
        break;
    case 10048: // CryptFindLocalizedName
        CHECK_NARGS(interp, objc, 1);
        result.value.unicode.str = (WCHAR *)CryptFindLocalizedName(ObjToUnicode(objv[0]));
        /* Note returned string is STATIC RESOURCE and must NOT be dealloced*/
        if (result.value.unicode.str) {
            result.value.unicode.len = -1;
            result.type = TRT_UNICODE;
        } else {
            result.value.obj = objv[0];
            result.type = TRT_OBJ;
        }
        break;
    case 10049: // CertCompareCertificateName
        // TBD - is this any different than doing a string compare in script?
        CHECK_NARGS(interp, objc, 3);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        blob.pbData = ObjToByteArray(objv[1], &blob.cbData);
        blob2.pbData = ObjToByteArray(objv[2], &blob2.cbData);
        result.type = TRT_BOOL;
        result.value.bval = CertCompareCertificateName(dw, &blob, &blob2);
        break;
    case 10050: // CryptEnumProviderTypes
    case 10051: // CryptEnumProvider
        CHECK_NARGS(interp, objc, 1);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);

        /* XP SP3 has a bug where the Unicode version of the
           CryptEnumProviderTypes always returns ERROR_MORE_DATA - see
           http://support.microsoft.com/kb/959160
           We special case this to use the ANSI version.
        */
        if (func == 10050 && ! TwapiMinOSVersion(6, 0)) {
            dw2 = sizeof(buf.ansi);   /* sizeof, NOT ARRAYSIZE in all cases */
            if (CryptEnumProviderTypesA(dw, NULL, 0, &dw3, buf.ansi, &dw2)) {
                objs[0] = ObjFromDWORD(dw3);
                objs[1] = ObjFromStringLimited(buf.ansi, dw2, NULL);
                result.type= TRT_OBJV;
                result.value.objv.objPP = objs;
                result.value.objv.nobj = 2;
                break;
            }
        } else {
            dw2 = sizeof(buf.uni);   /* sizeof, NOT ARRAYSIZE in all cases */
            if ((func == 10050 ? CryptEnumProviderTypesW : CryptEnumProvidersW)(dw, NULL, 0, &dw3, buf.uni, &dw2)) {
                objs[0] = ObjFromDWORD(dw3);
                objs[1] = ObjFromUnicodeLimited(buf.uni, dw2/sizeof(WCHAR), NULL);
                result.type= TRT_OBJV;
                result.value.objv.objPP = objs;
                result.value.objv.nobj = 2;
                break;
            }
        }
        /* Error handling */







|






|







|

|












|














|














|






|









|












|
|
|






|

|


















|







4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
        result.value.obj = ObjFromOpaque(pv, "HCERTSTORE");
        result.type = TRT_OBJ;
        break;

    case 10043: // PFXIsPFXBlob
        CHECK_NARGS(interp, objc, 1);
        result.type = TRT_BOOL;
        blob.pbData = ObjToByteArrayDW(objv[0], &blob.cbData);
        result.value.bval = PFXIsPFXBlob(&blob);
        break;

    case 10044: // PFXVerifyPassword
        CHECK_NARGS(interp, objc, 2);
        mark = SWSPushMark();
        pv = ObjDecryptWinCharsSWS(interp, objv[1], &ival);
        if (pv == NULL) {
            /* Can't just return because have to clean up SWS at bottom */
            result.type = TRT_TCL_RESULT;
            result.value.ival = TCL_ERROR;
            break;
        }
        result.type = TRT_BOOL;
        blob.pbData = ObjToByteArrayDW(objv[0], &blob.cbData);
        result.value.bval = PFXVerifyPassword(&blob, pv, 0);
        SecureZeroMemory(pv, sizeof(WCHAR) * ival);
        break;

    case 10045: // Twapi_CertStoreSerialize
        if (TwapiGetArgs(interp, objc, objv,
                         GETVERIFIEDPTR(hstore, HCERTSTORE, CertCloseStore),
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        blob.pbData = NULL;
        blob.cbData = 0;
        if (! CertSaveStore(hstore, PKCS_7_ASN_ENCODING|X509_ASN_ENCODING,
                            dw, CERT_STORE_SAVE_TO_MEMORY, &blob, 0))
            return TwapiReturnSystemError(interp);
        result.value.obj = ObjAllocateByteArray(blob.cbData, (void **) &blob.pbData);
        if (! CertSaveStore(hstore, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
                            dw, CERT_STORE_SAVE_TO_MEMORY, &blob, 0)) {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
            return TCL_ERROR;
        }
        Tcl_SetByteArrayLength(result.value.obj, blob.cbData);
        result.type = TRT_OBJ;
        break;

    case 10046: // CryptStringToBinary
        if (TwapiGetArgs(interp, objc, objv, GETOBJ(s1Obj),
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s1 = ObjToWinCharsNDW(s1Obj, &dw2);
        if (!CryptStringToBinaryW(s1, dw2, dw, NULL, &dw3, NULL, NULL))
            return TwapiReturnSystemError(interp);
        result.value.obj = ObjAllocateByteArray(dw3, &pv);
        if (!CryptStringToBinaryW(s1, dw2, dw, pv, &dw3, NULL, NULL)) {
            TwapiReturnSystemError(interp);
            ObjDecrRefs(result.value.obj);
        }
        Tcl_SetByteArrayLength(result.value.obj, dw3);
        result.type = TRT_OBJ;
        break;
    case 10047: // CryptBinaryToString
        if (TwapiGetArgs(interp, objc, objv, GETOBJ(s1Obj),
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        pv = ObjToByteArrayDW(s1Obj, &dw2);
        if (!CryptBinaryToStringW(pv, dw2, dw, NULL, &dw3))
            return TwapiReturnSystemError(interp);
        /* dw3 includes space for terminating \0 since we passed NULL above */
        pv2 = SWSPushFrame(sizeof(WCHAR)*dw3, NULL);
        if (CryptBinaryToStringW(pv, dw2, dw, pv2, &dw3)) {
            /* dw3 does NOT include terminating \0 */
            result.value.obj = ObjFromWinCharsN(pv2, dw3);
            result.type = TRT_OBJ;
        } else {
            result.value.ival = TwapiReturnSystemError(interp);
            result.type = TRT_TCL_RESULT;
        }        
        SWSPopFrame();
        break;
    case 10048: // CryptFindLocalizedName
        CHECK_NARGS(interp, objc, 1);
        result.value.unicode.str = (WCHAR *)CryptFindLocalizedName(ObjToWinChars(objv[0]));
        /* Note returned string is STATIC RESOURCE and must NOT be dealloced*/
        if (result.value.unicode.str) {
            result.value.unicode.len = -1;
            result.type = TRT_UNICODE;
        } else {
            result.value.obj = objv[0];
            result.type = TRT_OBJ;
        }
        break;
    case 10049: // CertCompareCertificateName
        // TBD - is this any different than doing a string compare in script?
        CHECK_NARGS(interp, objc, 3);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);
        blob.pbData = ObjToByteArrayDW(objv[1], &blob.cbData);
        blob2.pbData = ObjToByteArrayDW(objv[2], &blob2.cbData);
        result.type = TRT_BOOL;
        result.value.bval = CertCompareCertificateName(dw, &blob, &blob2);
        break;
    case 10050: // CryptEnumProviderTypes
    case 10051: // CryptEnumProvider
        CHECK_NARGS(interp, objc, 1);
        CHECK_DWORD_OBJ(interp, dw, objv[0]);

        /* XP SP3 has a bug where the WCHAR version of the
           CryptEnumProviderTypes always returns ERROR_MORE_DATA - see
           http://support.microsoft.com/kb/959160
           We special case this to use the ANSI version.
        */
        if (func == 10050 && ! TwapiMinOSVersion(6, 0)) {
            dw2 = sizeof(buf.ansi);   /* sizeof, NOT ARRAYSIZE in all cases */
            if (CryptEnumProviderTypesA(dw, NULL, 0, &dw3, buf.ansi, &dw2)) {
                objs[0] = ObjFromDWORD(dw3);
                objs[1] = ObjFromStringLimited(buf.ansi, dw2, NULL);
                result.type= TRT_OBJV;
                result.value.objv.objPP = objs;
                result.value.objv.nobj = 2;
                break;
            }
        } else {
            dw2 = sizeof(buf.uni);   /* sizeof, NOT ARRAYSIZE in all cases */
            if ((func == 10050 ? CryptEnumProviderTypesW : CryptEnumProvidersW)(dw, NULL, 0, &dw3, buf.uni, &dw2)) {
                objs[0] = ObjFromDWORD(dw3);
                objs[1] = ObjFromWinCharsLimited(buf.uni, dw2/sizeof(WCHAR), NULL);
                result.type= TRT_OBJV;
                result.value.objv.objPP = objs;
                result.value.objv.nobj = 2;
                break;
            }
        }
        /* Error handling */
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
        return TwapiCloseContext(interp, objv[0], "PCCTL_CONTEXT",
                                 TwapiUnregisterPCCTL_CONTEXT, CertFreeCTLContext);
        
    case 10055: // CryptCATAdminCalcHashFromFileHandle
        CHECK_NARGS(interp, objc, 1);
        if (ObjToHANDLE(interp, objv[0], &h) != TCL_OK)
            return TCL_ERROR;
        dw = sizeof(buf.ansi);
        if (CryptCATAdminCalcHashFromFileHandle(h, &dw, buf.ansi, 0) == FALSE)
            result.type = TRT_GETLASTERROR;
        else 
            return ObjSetResult(interp, ObjFromByteArray(buf.ansi, dw));
         break;
    case 10056: // CryptCATAdminAcquireContext 
        CHECK_NARGS(interp, objc, 1);
        if (ObjToGUID(interp, objv[0], &buf.guid) != TCL_OK)
            return TCL_ERROR;
        if (CryptCATAdminAcquireContext(&h, &buf.guid, 0) == FALSE)
            result.type = TRT_GETLASTERROR;







|
|


|







4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
        return TwapiCloseContext(interp, objv[0], "PCCTL_CONTEXT",
                                 TwapiUnregisterPCCTL_CONTEXT, CertFreeCTLContext);
        
    case 10055: // CryptCATAdminCalcHashFromFileHandle
        CHECK_NARGS(interp, objc, 1);
        if (ObjToHANDLE(interp, objv[0], &h) != TCL_OK)
            return TCL_ERROR;
        dw = sizeof(buf.bytes);
        if (CryptCATAdminCalcHashFromFileHandle(h, &dw, buf.bytes, 0) == FALSE)
            result.type = TRT_GETLASTERROR;
        else 
            return ObjSetResult(interp, ObjFromByteArray(buf.bytes, dw));
         break;
    case 10056: // CryptCATAdminAcquireContext 
        CHECK_NARGS(interp, objc, 1);
        if (ObjToGUID(interp, objv[0], &buf.guid) != TCL_OK)
            return TCL_ERROR;
        if (CryptCATAdminAcquireContext(&h, &buf.guid, 0) == FALSE)
            result.type = TRT_GETLASTERROR;
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
        if (TwapiGetArgs(interp, objc, objv, 
                         GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                         GETOBJ(s1Obj), ARGUSEDEFAULT, GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        /* Note: we did not use GETBA(pv, dw2) in the above call because
           of potential shimmering with the GETINT that would invalidate pv */
        pv2 = ObjToByteArray(s1Obj, &dw2);
        if (CryptHashData((HCRYPTHASH) pv, pv2, dw2, dw))
            result.type = TRT_EMPTY;
        else
            result.type = TRT_GETLASTERROR;
        break;
        
    case 10063: // CryptHashSessionKey







|







5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
        if (TwapiGetArgs(interp, objc, objv, 
                         GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                         GETOBJ(s1Obj), ARGUSEDEFAULT, GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        /* Note: we did not use GETBA(pv, dw2) in the above call because
           of potential shimmering with the GETINT that would invalidate pv */
        pv2 = ObjToByteArrayDW(s1Obj, &dw2);
        if (CryptHashData((HCRYPTHASH) pv, pv2, dw2, dw))
            result.type = TRT_EMPTY;
        else
            result.type = TRT_GETLASTERROR;
        break;
        
    case 10063: // CryptHashSessionKey
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
        break;
        
    case 10068: // capi_hash_password
        if (TwapiGetArgs(interp, objc, objv, 
                         GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                         GETOBJ(s1Obj), ARGEND) != TCL_OK)
            return TCL_ERROR;
        pv2 = ObjDecryptUtf8SWS(interp, s1Obj, &dw2);
        if (pv2 == NULL) {
            result.type = TRT_TCL_RESULT;
            result.value.ival = TCL_ERROR;
            break;
        }
        if (CryptHashData((HCRYPTHASH) pv, pv2, dw2, 0))
            result.type = TRT_EMPTY;
        else
            result.type = TRT_GETLASTERROR;
        SecureZeroMemory(pv2, dw2);
        break;

    case 10069: // CryptVerifySignature
        if (TwapiGetArgs(interp, objc, objv, 
                         GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                         GETOBJ(s1Obj),
                         GETVERIFIEDPTR(pv2, HCRYPTKEY, CryptDestroyKey),
                         ARGSKIP, GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        cP = ObjToByteArray(s1Obj, &dw2);
        if (CryptVerifySignature((HCRYPTHASH) pv, cP, dw2, (HCRYPTKEY)pv2, NULL, dw)) {
            result.value.bval = 1;
            result.type = TRT_BOOL;
        } else {
            result.value.ival = GetLastError();
            if (result.value.ival == NTE_BAD_SIGNATURE) {
                result.type = TRT_BOOL;
                result.value.bval = 0;







|





|



|










|
|







5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
        break;
        
    case 10068: // capi_hash_password
        if (TwapiGetArgs(interp, objc, objv, 
                         GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                         GETOBJ(s1Obj), ARGEND) != TCL_OK)
            return TCL_ERROR;
        pv2 = ObjDecryptUtf8SWS(interp, s1Obj, &ival);
        if (pv2 == NULL) {
            result.type = TRT_TCL_RESULT;
            result.value.ival = TCL_ERROR;
            break;
        }
        if (CryptHashData((HCRYPTHASH) pv, pv2, ival, 0))
            result.type = TRT_EMPTY;
        else
            result.type = TRT_GETLASTERROR;
        SecureZeroMemory(pv2, ival);
        break;

    case 10069: // CryptVerifySignature
        if (TwapiGetArgs(interp, objc, objv, 
                         GETVERIFIEDPTR(pv, HCRYPTHASH, CryptDestroyHash),
                         GETOBJ(s1Obj),
                         GETVERIFIEDPTR(pv2, HCRYPTKEY, CryptDestroyKey),
                         ARGSKIP, GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        bytesP = ObjToByteArrayDW(s1Obj, &dw2);
        if (CryptVerifySignature((HCRYPTHASH) pv, bytesP, dw2, (HCRYPTKEY)pv2, NULL, dw)) {
            result.value.bval = 1;
            result.type = TRT_BOOL;
        } else {
            result.value.ival = GetLastError();
            if (result.value.ival == NTE_BAD_SIGNATURE) {
                result.type = TRT_BOOL;
                result.value.bval = 0;
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETOBJ(s1Obj),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        if (dw != CERT_STORE_CERTIFICATE_CONTEXT) {
            return TwapiReturnError(interp, TWAPI_UNSUPPORTED_TYPE);
        }
        pv = ObjToByteArray(s1Obj, &dw3);
        certP = CertCreateContext(dw, dw2, pv, dw3, 0, NULL);
        if (certP == NULL)
            return TwapiReturnSystemError(interp);
        TwapiRegisterPCCERT_CONTEXT(interp, certP);
        TwapiResult_SET_NONNULL_PTR(result, PCCERT_CONTEXT, (void*)certP);
        break;
#endif







|







5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETOBJ(s1Obj),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        if (dw != CERT_STORE_CERTIFICATE_CONTEXT) {
            return TwapiReturnError(interp, TWAPI_UNSUPPORTED_TYPE);
        }
        pv = ObjToByteArrayDW(s1Obj, &dw3);
        certP = CertCreateContext(dw, dw2, pv, dw3, 0, NULL);
        if (certP == NULL)
            return TwapiReturnSystemError(interp);
        TwapiRegisterPCCERT_CONTEXT(interp, certP);
        TwapiResult_SET_NONNULL_PTR(result, PCCERT_CONTEXT, (void*)certP);
        break;
#endif
5271
5272
5273
5274
5275
5276
5277
5278
5279

5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
                                 GETHWND(promptP->hwndApp),
                                 GETWSTR(promptP->szPrompt), ARGEND);
            }
    }
    return res;
}

static int Twapi_CryptProtectObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    DWORD flags;
    CRYPT_DATA_BLOB inblob, outblob;
    TCL_RESULT res;
    Tcl_Obj *inObj, *promptObj;
    LPCWSTR description;
    CRYPTPROTECT_PROMPTSTRUCT prompt;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();
    
    mark = MemLifoPushMark(ticP->memlifoP);
    
    /* We do not want to make a copy of the input data for performance
       reasons so we do not extract it directly using TwapiGetArgsEx. Other
       parameters are extracted using that function so we are safe
       in directly accessing the input data blob without fear of
       the Tcl_Obj shimmering underneath us
    */
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(inObj),
                         GETEMPTYASNULL(description), ARGSKIP,
                         ARGSKIP, GETOBJ(promptObj),
                         GETINT(flags), ARGEND);
    if (res != TCL_OK)
        goto vamoose;

    res = ParseCRYPTPROTECT_PROMPTSTRUCT(ticP, promptObj, &prompt);
    if (res != TCL_OK)
        goto vamoose;

    inblob.pbData = ObjToByteArray(inObj, &inblob.cbData);
    outblob.pbData = NULL;
    outblob.cbData = 0;
    if (CryptProtectData(
            &inblob,
            description,        /* May be NULL */
            NULL,               /* Entropy, not supported */
            NULL,               /* Reserved - should be NULL */







|

>







<
<




















|







5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274


5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
                                 GETHWND(promptP->hwndApp),
                                 GETWSTR(promptP->szPrompt), ARGEND);
            }
    }
    return res;
}

static int Twapi_CryptProtectObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    DWORD flags;
    CRYPT_DATA_BLOB inblob, outblob;
    TCL_RESULT res;
    Tcl_Obj *inObj, *promptObj;
    LPCWSTR description;
    CRYPTPROTECT_PROMPTSTRUCT prompt;
    MemLifoMarkHandle mark;


    
    mark = MemLifoPushMark(ticP->memlifoP);
    
    /* We do not want to make a copy of the input data for performance
       reasons so we do not extract it directly using TwapiGetArgsEx. Other
       parameters are extracted using that function so we are safe
       in directly accessing the input data blob without fear of
       the Tcl_Obj shimmering underneath us
    */
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(inObj),
                         GETEMPTYASNULL(description), ARGSKIP,
                         ARGSKIP, GETOBJ(promptObj),
                         GETINT(flags), ARGEND);
    if (res != TCL_OK)
        goto vamoose;

    res = ParseCRYPTPROTECT_PROMPTSTRUCT(ticP, promptObj, &prompt);
    if (res != TCL_OK)
        goto vamoose;

    inblob.pbData = ObjToByteArrayDW(inObj, &inblob.cbData);
    outblob.pbData = NULL;
    outblob.cbData = 0;
    if (CryptProtectData(
            &inblob,
            description,        /* May be NULL */
            NULL,               /* Entropy, not supported */
            NULL,               /* Reserved - should be NULL */
5327
5328
5329
5330
5331
5332
5333
5334
5335

5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410

vamoose:
    MemLifoPopMark(mark);
    return res;
}


static int Twapi_CryptUnprotectObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    DWORD flags;
    CRYPT_DATA_BLOB inblob, outblob;
    Tcl_Obj *inObj, *promptObj;
    LPWSTR description;
    CRYPTPROTECT_PROMPTSTRUCT prompt;
    MemLifoMarkHandle mark;
    TCL_RESULT res;
    
    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    
    /* We do not want to make a copy of the input data for performance
       reasons so we do not extract it directly using TwapiGetArgsEx. Other
       parameters are extracted using that function so we are safe
       in directly accessing the input data blob without fear of
       the Tcl_Obj shimmering underneath us
    */
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(inObj),
                         ARGSKIP, ARGSKIP, GETOBJ(promptObj),
                         GETINT(flags), ARGEND);
    if (res != TCL_OK)
        goto vamoose;

    res = ParseCRYPTPROTECT_PROMPTSTRUCT(ticP, promptObj, &prompt);
    if (res != TCL_OK)
        goto vamoose;

    inblob.pbData = ObjToByteArray(inObj, &inblob.cbData);
    outblob.pbData = NULL;
    outblob.cbData = 0;
    description = NULL;
    if (CryptUnprotectData(
            &inblob,
            &description,
            NULL,
            NULL,
            prompt.szPrompt ? &prompt : NULL,
            flags,
            &outblob)) {
        Tcl_Obj *objs[2];
        objs[0] = ObjFromByteArray(outblob.pbData, outblob.cbData);
        objs[1] = description ? ObjFromUnicode(description) : ObjFromEmptyString();
        ObjSetResult(interp, ObjNewList(2, objs));
        if (description)
            LocalFree(description);
        if (outblob.pbData)
            LocalFree(outblob.pbData);
    }
    else
        res = TwapiReturnSystemError(interp);

vamoose:
    MemLifoPopMark(mark);
    return res;
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParseWINTRUST_DATA(TwapiInterpContext *ticP, Tcl_Obj *objP, TWAPI_WINTRUST_DATA *wtdP)
{
    Tcl_Interp *interp = ticP->interp;
    TCL_RESULT ret;
    Tcl_Obj *trustObj;
    WINTRUST_FILE_INFO *wfiP;
    WINTRUST_CATALOG_INFO *wciP;

    ObjToUnicodeCleanup();

    ZeroMemory(wtdP, sizeof(*wtdP));
    wtdP->cbStruct = sizeof(*wtdP);
    ret = TwapiGetArgsExObj(ticP, objP,
                            ARGSKIP, // pPolicyCallbackData
                            ARGSKIP, // pSIPClientData
                            GETINT(wtdP->dwUIChoice),
                            GETINT(wtdP->fdwRevocationChecks),







|

>








<
<


















|













|

















<





<
<







5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330


5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380

5381
5382
5383
5384
5385


5386
5387
5388
5389
5390
5391
5392

vamoose:
    MemLifoPopMark(mark);
    return res;
}


static int Twapi_CryptUnprotectObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    DWORD flags;
    CRYPT_DATA_BLOB inblob, outblob;
    Tcl_Obj *inObj, *promptObj;
    LPWSTR description;
    CRYPTPROTECT_PROMPTSTRUCT prompt;
    MemLifoMarkHandle mark;
    TCL_RESULT res;
    


    mark = MemLifoPushMark(ticP->memlifoP);
    
    /* We do not want to make a copy of the input data for performance
       reasons so we do not extract it directly using TwapiGetArgsEx. Other
       parameters are extracted using that function so we are safe
       in directly accessing the input data blob without fear of
       the Tcl_Obj shimmering underneath us
    */
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, GETOBJ(inObj),
                         ARGSKIP, ARGSKIP, GETOBJ(promptObj),
                         GETINT(flags), ARGEND);
    if (res != TCL_OK)
        goto vamoose;

    res = ParseCRYPTPROTECT_PROMPTSTRUCT(ticP, promptObj, &prompt);
    if (res != TCL_OK)
        goto vamoose;

    inblob.pbData = ObjToByteArrayDW(inObj, &inblob.cbData);
    outblob.pbData = NULL;
    outblob.cbData = 0;
    description = NULL;
    if (CryptUnprotectData(
            &inblob,
            &description,
            NULL,
            NULL,
            prompt.szPrompt ? &prompt : NULL,
            flags,
            &outblob)) {
        Tcl_Obj *objs[2];
        objs[0] = ObjFromByteArray(outblob.pbData, outblob.cbData);
        objs[1] = description ? ObjFromWinChars(description) : ObjFromEmptyString();
        ObjSetResult(interp, ObjNewList(2, objs));
        if (description)
            LocalFree(description);
        if (outblob.pbData)
            LocalFree(outblob.pbData);
    }
    else
        res = TwapiReturnSystemError(interp);

vamoose:
    MemLifoPopMark(mark);
    return res;
}

/* Note caller has to clean up ticP->memlifo irrespective of success/error */
static TCL_RESULT ParseWINTRUST_DATA(TwapiInterpContext *ticP, Tcl_Obj *objP, TWAPI_WINTRUST_DATA *wtdP)
{

    TCL_RESULT ret;
    Tcl_Obj *trustObj;
    WINTRUST_FILE_INFO *wfiP;
    WINTRUST_CATALOG_INFO *wciP;



    ZeroMemory(wtdP, sizeof(*wtdP));
    wtdP->cbStruct = sizeof(*wtdP);
    ret = TwapiGetArgsExObj(ticP, objP,
                            ARGSKIP, // pPolicyCallbackData
                            ARGSKIP, // pSIPClientData
                            GETINT(wtdP->dwUIChoice),
                            GETINT(wtdP->fdwRevocationChecks),
5452
5453
5454
5455
5456
5457
5458
5459
5460

5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490

5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
        ret = TwapiReturnErrorMsg(ticP->interp, TWAPI_UNSUPPORTED_TYPE, "Unsupported Wintrust type");
        break;
    }

    return ret;
}

static int Twapi_WinVerifyTrustObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TWAPI_WINTRUST_DATA wtd;
    Tcl_Obj *wtdObj;
    HWND hwnd;
    GUID guid;
    TCL_RESULT ret;
    LONG status;
    MemLifoMarkHandle mark;
    
    ObjToUnicodeCleanup();

    ret = TwapiGetArgs(interp, objc-1, objv+1, GETHWND(hwnd), GETGUID(guid),
                       GETOBJ(wtdObj), ARGEND);
    if (ret != TCL_OK)
        return ret;
    mark = MemLifoPushMark(ticP->memlifoP);
    ret = ParseWINTRUST_DATA(ticP, wtdObj, &wtd);
    if (ret == TCL_OK) {
        status = WinVerifyTrust(hwnd, &guid, (WINTRUST_DATA *)&wtd);

        wtd.dwStateAction = WTD_STATEACTION_CLOSE;
        wtd.dwUIChoice = WTD_UI_NONE;
        WinVerifyTrust((HWND) INVALID_HANDLE_VALUE, &guid, (WINTRUST_DATA *)&wtd);
        ObjSetResult(interp, ObjFromInt(status));
    }
    MemLifoPopMark(mark);
    return ret;
}

static int Twapi_PBKDF2ObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    unsigned char *utfpassP, *saltP, *keyP;
    int nutf, nsalt, niterations, nkeybytes, nkeybits;
    TCL_RESULT res;
    Tcl_Obj *passObj;
    BOOL pbkdf2_status;
    MemLifoMarkHandle mark;
    TWAPI_PLAINTEXTKEYBLOB *blobP;
    PRF *prf;
    ALG_ID alg_id;
    
    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, 
                         GETOBJ(passObj),
                         GETINT(nkeybits), 
                         GETINT(alg_id),
                         GETBA(saltP, nsalt), 
                         GETINT(niterations),







|

>








<
<


















|

>










<
<







5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451


5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482


5483
5484
5485
5486
5487
5488
5489
        ret = TwapiReturnErrorMsg(ticP->interp, TWAPI_UNSUPPORTED_TYPE, "Unsupported Wintrust type");
        break;
    }

    return ret;
}

static int Twapi_WinVerifyTrustObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    TWAPI_WINTRUST_DATA wtd;
    Tcl_Obj *wtdObj;
    HWND hwnd;
    GUID guid;
    TCL_RESULT ret;
    LONG status;
    MemLifoMarkHandle mark;
    


    ret = TwapiGetArgs(interp, objc-1, objv+1, GETHWND(hwnd), GETGUID(guid),
                       GETOBJ(wtdObj), ARGEND);
    if (ret != TCL_OK)
        return ret;
    mark = MemLifoPushMark(ticP->memlifoP);
    ret = ParseWINTRUST_DATA(ticP, wtdObj, &wtd);
    if (ret == TCL_OK) {
        status = WinVerifyTrust(hwnd, &guid, (WINTRUST_DATA *)&wtd);

        wtd.dwStateAction = WTD_STATEACTION_CLOSE;
        wtd.dwUIChoice = WTD_UI_NONE;
        WinVerifyTrust((HWND) INVALID_HANDLE_VALUE, &guid, (WINTRUST_DATA *)&wtd);
        ObjSetResult(interp, ObjFromInt(status));
    }
    MemLifoPopMark(mark);
    return ret;
}

static int Twapi_PBKDF2ObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    unsigned char *utfpassP, *saltP, *keyP;
    int nutf, nsalt, niterations, nkeybytes, nkeybits;
    TCL_RESULT res;
    Tcl_Obj *passObj;
    BOOL pbkdf2_status;
    MemLifoMarkHandle mark;
    TWAPI_PLAINTEXTKEYBLOB *blobP;
    PRF *prf;
    ALG_ID alg_id;
    


    mark = MemLifoPushMark(ticP->memlifoP);
    res = TwapiGetArgsEx(ticP, objc-1, objv+1, 
                         GETOBJ(passObj),
                         GETINT(nkeybits), 
                         GETINT(alg_id),
                         GETBA(saltP, nsalt), 
                         GETINT(niterations),
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537

    /* We will bundle the plaintext key in sealed form as a PLAINTEXTKEYBLOB */
    blobP = MemLifoAlloc(ticP->memlifoP, 
                         TWAPI_PLAINTEXTKEYBLOB_SIZE(nkeybytes), NULL);
    keyP = &blobP->rgbKeyData[0];
    
    TWAPI_ASSERT(ticP->memlifoP == SWS());
    utfpassP = ObjDecryptUtf8SWS(interp, passObj, &nutf);
    if (utfpassP == NULL) {
        res = TCL_ERROR;
        goto vamoose;                    /* Error already filled in */ 
    }
    
    switch (alg_id) {
    case CALG_SHA1: prf = &sha1Prf; break;







|







5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517

    /* We will bundle the plaintext key in sealed form as a PLAINTEXTKEYBLOB */
    blobP = MemLifoAlloc(ticP->memlifoP, 
                         TWAPI_PLAINTEXTKEYBLOB_SIZE(nkeybytes), NULL);
    keyP = &blobP->rgbKeyData[0];
    
    TWAPI_ASSERT(ticP->memlifoP == SWS());
    utfpassP = (unsigned char *) ObjDecryptUtf8SWS(interp, passObj, &nutf);
    if (utfpassP == NULL) {
        res = TCL_ERROR;
        goto vamoose;                    /* Error already filled in */ 
    }
    
    switch (alg_id) {
    case CALG_SHA1: prf = &sha1Prf; break;
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
        DEFINE_FNCODE_CMD(CryptVerifySignature, 10069), // TBD - Tcl
        DEFINE_FNCODE_CMD(Twapi_CertChainError, 10070),
        DEFINE_FNCODE_CMD(Twapi_CertChainInfo, 10071),
        DEFINE_FNCODE_CMD(cert_chain_simple_chain_count, 10072), // TBD - doc
    };

    static struct tcl_dispatch_s TclDispatch[] = {
        DEFINE_TCL_CMD(CertCreateSelfSignCertificate, Twapi_CertCreateSelfSignCertificate),
        DEFINE_TCL_CMD(CryptSignAndEncodeCertificate, Twapi_CryptSignAndEncodeCertObjCmd),
        DEFINE_TCL_CMD(CertFindCertificateInStore, Twapi_CertFindCertificateInStoreObjCmd),
        DEFINE_TCL_CMD(CertGetCertificateChain, Twapi_CertGetCertificateChainObjCmd),
        DEFINE_TCL_CMD(Twapi_CertVerifyChainPolicy, Twapi_CertVerifyChainPolicyObjCmd),
        DEFINE_TCL_CMD(Twapi_HashPublicKeyInfo, Twapi_HashPublicKeyInfoObjCmd),
        DEFINE_TCL_CMD(CryptFindOIDInfo, Twapi_CryptFindOIDInfoObjCmd),
        DEFINE_TCL_CMD(CryptDecodeObjectEx, Twapi_CryptDecodeObjectExObjCmd), // Tcl







|







5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
        DEFINE_FNCODE_CMD(CryptVerifySignature, 10069), // TBD - Tcl
        DEFINE_FNCODE_CMD(Twapi_CertChainError, 10070),
        DEFINE_FNCODE_CMD(Twapi_CertChainInfo, 10071),
        DEFINE_FNCODE_CMD(cert_chain_simple_chain_count, 10072), // TBD - doc
    };

    static struct tcl_dispatch_s TclDispatch[] = {
        DEFINE_TCL_CMD(CertCreateSelfSignCertificate, Twapi_CertCreateSelfSignCertificateObjCmd),
        DEFINE_TCL_CMD(CryptSignAndEncodeCertificate, Twapi_CryptSignAndEncodeCertObjCmd),
        DEFINE_TCL_CMD(CertFindCertificateInStore, Twapi_CertFindCertificateInStoreObjCmd),
        DEFINE_TCL_CMD(CertGetCertificateChain, Twapi_CertGetCertificateChainObjCmd),
        DEFINE_TCL_CMD(Twapi_CertVerifyChainPolicy, Twapi_CertVerifyChainPolicyObjCmd),
        DEFINE_TCL_CMD(Twapi_HashPublicKeyInfo, Twapi_HashPublicKeyInfoObjCmd),
        DEFINE_TCL_CMD(CryptFindOIDInfo, Twapi_CryptFindOIDInfoObjCmd),
        DEFINE_TCL_CMD(CryptDecodeObjectEx, Twapi_CryptDecodeObjectExObjCmd), // Tcl
Changes to undroid/twapi/twapi/crypto/sspi.c.
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
            /* MSDN docs say "pvBuffer" does not contain a copy of the
               data. What they probably mean is that it points into
               the original data, not to a copy of it. But the sample
               code in MSDN and curl etc. does not make use of this field
               so neither do we, just to be safe. */
            if (sbP->BufferType == SECBUFFER_EXTRA && sbP->cbBuffer) {
                TWAPI_ASSERT(sb0P->cbBuffer > sbP->cbBuffer);
                return ObjFromByteArray(((char*) sb0P->pvBuffer) + (sb0P->cbBuffer - sbP->cbBuffer),
                                        sbP->cbBuffer);
            }
        }
    }
    return ObjFromEmptyString();
}








|







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
            /* MSDN docs say "pvBuffer" does not contain a copy of the
               data. What they probably mean is that it points into
               the original data, not to a copy of it. But the sample
               code in MSDN and curl etc. does not make use of this field
               so neither do we, just to be safe. */
            if (sbP->BufferType == SECBUFFER_EXTRA && sbP->cbBuffer) {
                TWAPI_ASSERT(sb0P->cbBuffer > sbP->cbBuffer);
                return ObjFromByteArray(((BYTE*) sb0P->pvBuffer) + (sb0P->cbBuffer - sbP->cbBuffer),
                                        sbP->cbBuffer);
            }
        }
    }
    return ObjFromEmptyString();
}

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
     * integer type and optionally the data itself
     */
    for (i=0; i < objc; ++i) {
        Tcl_Obj **bufobjv;
        int       bufobjc;
        int       buftype;
        int       datalen;
        char     *dataP;
        if (ObjGetElements(interp, objv[i], &bufobjc, &bufobjv) != TCL_OK)
            return TCL_ERROR;
        if ((bufobjc != 1 && bufobjc != 2) ||
            Tcl_GetIntFromObj(interp, bufobjv[0], &buftype) != TCL_OK) {
            ObjSetStaticResult(interp, "Invalid SecBuffer format");
            goto handle_error;
        }







|







183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
     * integer type and optionally the data itself
     */
    for (i=0; i < objc; ++i) {
        Tcl_Obj **bufobjv;
        int       bufobjc;
        int       buftype;
        int       datalen;
        BYTE     *dataP;
        if (ObjGetElements(interp, objv[i], &bufobjc, &bufobjv) != TCL_OK)
            return TCL_ERROR;
        if ((bufobjc != 1 && bufobjc != 2) ||
            Tcl_GetIntFromObj(interp, bufobjv[0], &buftype) != TCL_OK) {
            ObjSetStaticResult(interp, "Invalid SecBuffer format");
            goto handle_error;
        }
269
270
271
272
273
274
275
276
277
278
279

280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    FreeContextBuffer(spiP);

    ObjSetResult(interp, obj);
    return TCL_OK;
}

static TCL_RESULT Twapi_InitializeSecurityContextObjCmd(
    TwapiInterpContext *ticP,
    Tcl_Interp *interp,
    int objc, Tcl_Obj *CONST objv[])
{

    SecHandle credential, context, *contextP;
    LPWSTR     targetP;
    ULONG      contextreq, reserved1, targetdatarep, reserved2;
    SecBufferDesc sbd_in, *sbd_inP;
    SecBuffer     sb_out;
    SecBufferDesc sbd_out;
    SECURITY_STATUS status, auth_status;
    CtxtHandle    new_context = {0, 0};
    ULONG         new_context_attr;
    Tcl_Obj      *objs[6];
    TimeStamp     expiration;

    ObjToUnicodeCleanup();

    /* NOTE - on XP for schannel at least, the input buffer must not 
       be read-only. Discovered in testing so made sbd_in read-write
       Later Win versions do not seem to mind */
    contextP = &context;
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETVAR(credential, ObjToSecHandle),
                       GETVAR(contextP, ObjToSecHandle_NULL),







|



>












<
<







269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292


293
294
295
296
297
298
299
    FreeContextBuffer(spiP);

    ObjSetResult(interp, obj);
    return TCL_OK;
}

static TCL_RESULT Twapi_InitializeSecurityContextObjCmd(
    ClientData clientdata,
    Tcl_Interp *interp,
    int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    SecHandle credential, context, *contextP;
    LPWSTR     targetP;
    ULONG      contextreq, reserved1, targetdatarep, reserved2;
    SecBufferDesc sbd_in, *sbd_inP;
    SecBuffer     sb_out;
    SecBufferDesc sbd_out;
    SECURITY_STATUS status, auth_status;
    CtxtHandle    new_context = {0, 0};
    ULONG         new_context_attr;
    Tcl_Obj      *objs[6];
    TimeStamp     expiration;



    /* NOTE - on XP for schannel at least, the input buffer must not 
       be read-only. Discovered in testing so made sbd_in read-write
       Later Win versions do not seem to mind */
    contextP = &context;
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETVAR(credential, ObjToSecHandle),
                       GETVAR(contextP, ObjToSecHandle_NULL),
415
416
417
418
419
420
421
422
423

424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    if (sb_out.pvBuffer)
        FreeContextBuffer(sb_out.pvBuffer);

    TwapiFreeSecBufferDesc(sbd_inP);
    return TCL_OK;
}

static int Twapi_AcceptSecurityContextObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    SecHandle credential, context, *contextP;
    SecBufferDesc sbd_in, *sbd_inP;
    ULONG      contextreq, targetdatarep;
    SecBuffer     sb_out;
    SecBufferDesc sbd_out;
    SECURITY_STATUS status, auth_status;
    CtxtHandle    new_context = {0, 0};
    ULONG         new_context_attr;
    Tcl_Obj      *objs[6];
    TimeStamp     expiration;

    ObjToUnicodeCleanup();

    /* NOTE - on XP for schannel at least, the input buffer must not 
       be read-only. Discovered in testing so made sbd_in read-write
       Later Win versions do not seem to mind */
    contextP = &context;
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETVAR(credential, ObjToSecHandle),
                       GETVAR(contextP, ObjToSecHandle_NULL),







|

>











<
<







414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434


435
436
437
438
439
440
441
    if (sb_out.pvBuffer)
        FreeContextBuffer(sb_out.pvBuffer);

    TwapiFreeSecBufferDesc(sbd_inP);
    return TCL_OK;
}

static int Twapi_AcceptSecurityContextObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    SecHandle credential, context, *contextP;
    SecBufferDesc sbd_in, *sbd_inP;
    ULONG      contextreq, targetdatarep;
    SecBuffer     sb_out;
    SecBufferDesc sbd_out;
    SECURITY_STATUS status, auth_status;
    CtxtHandle    new_context = {0, 0};
    ULONG         new_context_attr;
    Tcl_Obj      *objs[6];
    TimeStamp     expiration;



    /* NOTE - on XP for schannel at least, the input buffer must not 
       be read-only. Discovered in testing so made sbd_in read-write
       Later Win versions do not seem to mind */
    contextP = &context;
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETVAR(credential, ObjToSecHandle),
                       GETVAR(contextP, ObjToSecHandle_NULL),
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
    case SECPKG_ATTR_ISSUER_LIST_EX:
        ss = QueryContextAttributesW(ctxP, attr, &param);
        if (ss == SEC_E_OK) {
            switch (attr) {
            case SECPKG_ATTR_AUTHORITY:
                buf = param.authority.sAuthorityName; /* Freed later */
                if (buf)
                    obj = ObjFromUnicode(buf);
                break;
            case SECPKG_ATTR_FLAGS:
                obj = ObjFromLong(param.flags.Flags);
                break;
            case SECPKG_ATTR_SIZES:
                objs[0] = ObjFromLong(param.sizes.cbMaxToken);
                objs[1] = ObjFromLong(param.sizes.cbMaxSignature);







|







664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
    case SECPKG_ATTR_ISSUER_LIST_EX:
        ss = QueryContextAttributesW(ctxP, attr, &param);
        if (ss == SEC_E_OK) {
            switch (attr) {
            case SECPKG_ATTR_AUTHORITY:
                buf = param.authority.sAuthorityName; /* Freed later */
                if (buf)
                    obj = ObjFromWinChars(buf);
                break;
            case SECPKG_ATTR_FLAGS:
                obj = ObjFromLong(param.flags.Flags);
                break;
            case SECPKG_ATTR_SIZES:
                objs[0] = ObjFromLong(param.sizes.cbMaxToken);
                objs[1] = ObjFromLong(param.sizes.cbMaxSignature);
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
                objs[0] = ObjFromWideInt(param.lifespan.tsStart.QuadPart);
                objs[1] = ObjFromWideInt(param.lifespan.tsExpiry.QuadPart);
                obj = ObjNewList(2, objs);
                break;
            case SECPKG_ATTR_NAMES:
                buf = param.names.sUserName; /* Freed later */
                if (buf)
                    obj = ObjFromUnicode(buf);
                break;
            case SECPKG_ATTR_NATIVE_NAMES:
                objs[0] = ObjFromUnicode(param.nativenames.sClientName ? param.nativenames.sClientName : L"");
                objs[1] = ObjFromUnicode(param.nativenames.sServerName ? param.nativenames.sServerName : L"");
                obj = ObjNewList(2, objs);
                if (param.nativenames.sClientName)
                    FreeContextBuffer(param.nativenames.sClientName);
                if (param.nativenames.sServerName)
                    FreeContextBuffer(param.nativenames.sServerName);
                break;
            case SECPKG_ATTR_PASSWORD_EXPIRY:
                obj = ObjFromWideInt(param.passwordexpiry.tsPasswordExpires.QuadPart);
                break;
            case SECPKG_ATTR_PACKAGE_INFO:
                buf = param.pkginfo.PackageInfo; /* So it can be freed */
                if (param.pkginfo.PackageInfo) {
                    objs[0] = ObjFromULONG(param.pkginfo.PackageInfo->fCapabilities);
                    objs[1] = ObjFromInt(param.pkginfo.PackageInfo->wVersion);
                    objs[2] = ObjFromInt(param.pkginfo.PackageInfo->wRPCID);
                    objs[3] = ObjFromULONG(param.pkginfo.PackageInfo->cbMaxToken);
                    objs[4] = ObjFromUnicode(param.pkginfo.PackageInfo->Name);
                    objs[5] = ObjFromUnicode(param.pkginfo.PackageInfo->Comment);
                    obj = ObjNewList(6, objs);
                }
                break;
            case SECPKG_ATTR_LOCAL_CERT_CONTEXT: /* FALLTHRU */
            case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
                TwapiRegisterPCCERT_CONTEXT(interp, param.certP);
                obj = ObjFromOpaque(param.certP, "PCCERT_CONTEXT");







|


|
|
















|
|







692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
                objs[0] = ObjFromWideInt(param.lifespan.tsStart.QuadPart);
                objs[1] = ObjFromWideInt(param.lifespan.tsExpiry.QuadPart);
                obj = ObjNewList(2, objs);
                break;
            case SECPKG_ATTR_NAMES:
                buf = param.names.sUserName; /* Freed later */
                if (buf)
                    obj = ObjFromWinChars(buf);
                break;
            case SECPKG_ATTR_NATIVE_NAMES:
                objs[0] = ObjFromWinChars(param.nativenames.sClientName ? param.nativenames.sClientName : L"");
                objs[1] = ObjFromWinChars(param.nativenames.sServerName ? param.nativenames.sServerName : L"");
                obj = ObjNewList(2, objs);
                if (param.nativenames.sClientName)
                    FreeContextBuffer(param.nativenames.sClientName);
                if (param.nativenames.sServerName)
                    FreeContextBuffer(param.nativenames.sServerName);
                break;
            case SECPKG_ATTR_PASSWORD_EXPIRY:
                obj = ObjFromWideInt(param.passwordexpiry.tsPasswordExpires.QuadPart);
                break;
            case SECPKG_ATTR_PACKAGE_INFO:
                buf = param.pkginfo.PackageInfo; /* So it can be freed */
                if (param.pkginfo.PackageInfo) {
                    objs[0] = ObjFromULONG(param.pkginfo.PackageInfo->fCapabilities);
                    objs[1] = ObjFromInt(param.pkginfo.PackageInfo->wVersion);
                    objs[2] = ObjFromInt(param.pkginfo.PackageInfo->wRPCID);
                    objs[3] = ObjFromULONG(param.pkginfo.PackageInfo->cbMaxToken);
                    objs[4] = ObjFromWinChars(param.pkginfo.PackageInfo->Name);
                    objs[5] = ObjFromWinChars(param.pkginfo.PackageInfo->Comment);
                    obj = ObjNewList(6, objs);
                }
                break;
            case SECPKG_ATTR_LOCAL_CERT_CONTEXT: /* FALLTHRU */
            case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
                TwapiRegisterPCCERT_CONTEXT(interp, param.certP);
                obj = ObjFromOpaque(param.certP, "PCCERT_CONTEXT");
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802

    if (obj)
        ObjSetResult(interp, obj);

    return TCL_OK;
}

static TCL_RESULT Twapi_MakeSignatureObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    SecHandle sech;
    ULONG qop;
    ULONG seqnum;

    SECURITY_STATUS ss;
    SecPkgContext_Sizes spc_sizes;
    SecBuffer sbufs[2];
    SecBufferDesc sbd;
    Tcl_Obj *objs[ARRAYSIZE(sbufs)];
    Tcl_Obj *dataObj;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVAR(sech, ObjToSecHandle),
                     GETINT(qop),
                     GETOBJ(dataObj),
                     GETINT(seqnum),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;


    ss = QueryContextAttributesW(&sech, SECPKG_ATTR_SIZES, &spc_sizes);
    if (ss != SEC_E_OK)
        return Twapi_AppendSystemError(interp, ss);

    objs[0] = ObjFromByteArray(NULL, spc_sizes.cbMaxSignature);
    sbufs[0].BufferType = SECBUFFER_TOKEN;
    sbufs[0].pvBuffer   = ObjToByteArray(objs[0], &sbufs[0].cbBuffer);

    objs[1] = ObjDuplicate(dataObj);
    TWAPI_ASSERT(! Tcl_IsShared(objs[1]));
    sbufs[1].BufferType = SECBUFFER_DATA | SECBUFFER_READONLY;
    sbufs[1].pvBuffer   = ObjToByteArray(objs[1], &sbufs[1].cbBuffer);
    
    sbd.cBuffers = 2;
    sbd.pBuffers = sbufs;
    sbd.ulVersion = SECBUFFER_VERSION;

    ss = MakeSignature(&sech, qop, &sbd, seqnum);
    if (ss != SEC_E_OK) {







|












<
<















|




|







751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770


771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798

    if (obj)
        ObjSetResult(interp, obj);

    return TCL_OK;
}

static TCL_RESULT Twapi_MakeSignatureObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    SecHandle sech;
    ULONG qop;
    ULONG seqnum;

    SECURITY_STATUS ss;
    SecPkgContext_Sizes spc_sizes;
    SecBuffer sbufs[2];
    SecBufferDesc sbd;
    Tcl_Obj *objs[ARRAYSIZE(sbufs)];
    Tcl_Obj *dataObj;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVAR(sech, ObjToSecHandle),
                     GETINT(qop),
                     GETOBJ(dataObj),
                     GETINT(seqnum),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;


    ss = QueryContextAttributesW(&sech, SECPKG_ATTR_SIZES, &spc_sizes);
    if (ss != SEC_E_OK)
        return Twapi_AppendSystemError(interp, ss);

    objs[0] = ObjFromByteArray(NULL, spc_sizes.cbMaxSignature);
    sbufs[0].BufferType = SECBUFFER_TOKEN;
    sbufs[0].pvBuffer   = (BYTE*) ObjToByteArray(objs[0], (int *) &sbufs[0].cbBuffer);

    objs[1] = ObjDuplicate(dataObj);
    TWAPI_ASSERT(! Tcl_IsShared(objs[1]));
    sbufs[1].BufferType = SECBUFFER_DATA | SECBUFFER_READONLY;
    sbufs[1].pvBuffer   = (BYTE*) ObjToByteArray(objs[1], (int *) &sbufs[1].cbBuffer);
    
    sbd.cBuffers = 2;
    sbd.pBuffers = sbufs;
    sbd.ulVersion = SECBUFFER_VERSION;

    ss = MakeSignature(&sech, qop, &sbd, seqnum);
    if (ss != SEC_E_OK) {
811
812
813
814
815
816
817
818
819

820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
        ObjSetResult(interp, ObjNewList(ARRAYSIZE(objs), objs));
    }

    return ss == SEC_E_OK ? TCL_OK : TCL_ERROR;
}


static TCL_RESULT Twapi_EncryptMessageObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    SecHandle sech;
    ULONG qop;
    ULONG seqnum;
    SECURITY_STATUS ss;
    SecPkgContext_Sizes spc_sizes;
    SecBuffer sbufs[3];
    SecBufferDesc sbd;
    Tcl_Obj *dataObj;
    Tcl_Obj *objs[ARRAYSIZE(sbufs)];

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVAR(sech, ObjToSecHandle),
                     GETINT(qop),
                     GETOBJ(dataObj),
                     GETINT(seqnum),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    ss = QueryContextAttributesW(&sech, SECPKG_ATTR_SIZES, &spc_sizes);
    if (ss != SEC_E_OK)
        return Twapi_AppendSystemError(ticP->interp, ss);

    objs[0] = ObjFromByteArray(NULL, spc_sizes.cbSecurityTrailer);
    sbufs[0].BufferType = SECBUFFER_TOKEN;
    sbufs[0].pvBuffer   = ObjToByteArray(objs[0], &sbufs[0].cbBuffer);

    objs[1] = ObjDuplicate(dataObj);
    TWAPI_ASSERT(! Tcl_IsShared(objs[1]));
    sbufs[1].BufferType = SECBUFFER_DATA;
    sbufs[1].pvBuffer   = ObjToByteArray(objs[1], &sbufs[1].cbBuffer);
    
    objs[2] = ObjFromByteArray(NULL, spc_sizes.cbBlockSize);
    sbufs[2].BufferType = SECBUFFER_PADDING;
    sbufs[2].pvBuffer   = ObjToByteArray(objs[2], &sbufs[2].cbBuffer);

    sbd.cBuffers = 3;
    sbd.pBuffers = sbufs;
    sbd.ulVersion = SECBUFFER_VERSION;

    ss = EncryptMessage(&sech, qop, &sbd, seqnum);
    if (ss != SEC_E_OK) {







|

>










<
<














|




|



|







807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826


827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
        ObjSetResult(interp, ObjNewList(ARRAYSIZE(objs), objs));
    }

    return ss == SEC_E_OK ? TCL_OK : TCL_ERROR;
}


static TCL_RESULT Twapi_EncryptMessageObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    SecHandle sech;
    ULONG qop;
    ULONG seqnum;
    SECURITY_STATUS ss;
    SecPkgContext_Sizes spc_sizes;
    SecBuffer sbufs[3];
    SecBufferDesc sbd;
    Tcl_Obj *dataObj;
    Tcl_Obj *objs[ARRAYSIZE(sbufs)];



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVAR(sech, ObjToSecHandle),
                     GETINT(qop),
                     GETOBJ(dataObj),
                     GETINT(seqnum),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    ss = QueryContextAttributesW(&sech, SECPKG_ATTR_SIZES, &spc_sizes);
    if (ss != SEC_E_OK)
        return Twapi_AppendSystemError(ticP->interp, ss);

    objs[0] = ObjFromByteArray(NULL, spc_sizes.cbSecurityTrailer);
    sbufs[0].BufferType = SECBUFFER_TOKEN;
    sbufs[0].pvBuffer   = (BYTE *) ObjToByteArray(objs[0], (int *) &sbufs[0].cbBuffer);

    objs[1] = ObjDuplicate(dataObj);
    TWAPI_ASSERT(! Tcl_IsShared(objs[1]));
    sbufs[1].BufferType = SECBUFFER_DATA;
    sbufs[1].pvBuffer   = (BYTE *) ObjToByteArray(objs[1], (int *) &sbufs[1].cbBuffer);
    
    objs[2] = ObjFromByteArray(NULL, spc_sizes.cbBlockSize);
    sbufs[2].BufferType = SECBUFFER_PADDING;
    sbufs[2].pvBuffer   = (BYTE *) ObjToByteArray(objs[2], (int *) &sbufs[2].cbBuffer);

    sbd.cBuffers = 3;
    sbd.pBuffers = sbufs;
    sbd.ulVersion = SECBUFFER_VERSION;

    ss = EncryptMessage(&sech, qop, &sbd, seqnum);
    if (ss != SEC_E_OK) {
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
        ObjSetResult(ticP->interp, ObjNewList(ARRAYSIZE(objs), objs));
    }

    return ss == SEC_E_OK ? TCL_OK : TCL_ERROR;
}


static TCL_RESULT Twapi_EncryptStreamObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    SecHandle sech;
    ULONG qop;
    SECURITY_STATUS ss;
    SecPkgContext_StreamSizes sizes;
    SecBuffer sbufs[4];
    SecBufferDesc sbd;
    Tcl_Obj *dataObj;
    Tcl_Obj *objs[2];           /* 0 encrypted data, 1 leftover data */
    char *dataP, *encP;
    DWORD   datalen;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVAR(sech, ObjToSecHandle),
                     GETINT(qop),
                     GETOBJ(dataObj),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    ss = QueryContextAttributesW(&sech, SECPKG_ATTR_STREAM_SIZES, &sizes);
    if (ss != SEC_E_OK)
        return Twapi_AppendSystemError(interp, ss);

    dataP = ObjToByteArray(dataObj, &datalen);
    if (datalen > sizes.cbMaximumMessage) {
        objs[1] = ObjFromByteArray(dataP+sizes.cbMaximumMessage,
                                       datalen-sizes.cbMaximumMessage);
        datalen = sizes.cbMaximumMessage;
    } else
        objs[1] = ObjFromEmptyString();








|









|


<
<











|







866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885


886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
        ObjSetResult(ticP->interp, ObjNewList(ARRAYSIZE(objs), objs));
    }

    return ss == SEC_E_OK ? TCL_OK : TCL_ERROR;
}


static TCL_RESULT Twapi_EncryptStreamObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    SecHandle sech;
    ULONG qop;
    SECURITY_STATUS ss;
    SecPkgContext_StreamSizes sizes;
    SecBuffer sbufs[4];
    SecBufferDesc sbd;
    Tcl_Obj *dataObj;
    Tcl_Obj *objs[2];           /* 0 encrypted data, 1 leftover data */
    BYTE  *dataP, *encP;
    DWORD   datalen;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVAR(sech, ObjToSecHandle),
                     GETINT(qop),
                     GETOBJ(dataObj),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    ss = QueryContextAttributesW(&sech, SECPKG_ATTR_STREAM_SIZES, &sizes);
    if (ss != SEC_E_OK)
        return Twapi_AppendSystemError(interp, ss);

    dataP = ObjToByteArray(dataObj, (int *) &datalen);
    if (datalen > sizes.cbMaximumMessage) {
        objs[1] = ObjFromByteArray(dataP+sizes.cbMaximumMessage,
                                       datalen-sizes.cbMaximumMessage);
        datalen = sizes.cbMaximumMessage;
    } else
        objs[1] = ObjFromEmptyString();

946
947
948
949
950
951
952
953
954

955
956
957
958
959
960
961
962
963
964
965
966
967
        ObjSetResult(interp, ObjNewList(ARRAYSIZE(objs), objs));
    }

    return ss == SEC_E_OK ? TCL_OK : TCL_ERROR;
}


static TCL_RESULT Twapi_DecryptStreamObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    SecHandle sech;
    SECURITY_STATUS ss;
    SecBuffer sbufs[4];
    SecBufferDesc sbd;
    Tcl_Obj *objs[3];           /* 0 status, 1 decrypted data, 2 extra data */
    char *encP, *p;
    int  i, enclen;
    TCL_RESULT res;

    CHECK_NARGS_RANGE(interp, objc, 3, INT_MAX);
    if (ObjToSecHandle(interp, objv[1], &sech) != TCL_OK)
        return TCL_ERROR;








|

>





|







939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
        ObjSetResult(interp, ObjNewList(ARRAYSIZE(objs), objs));
    }

    return ss == SEC_E_OK ? TCL_OK : TCL_ERROR;
}


static TCL_RESULT Twapi_DecryptStreamObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    SecHandle sech;
    SECURITY_STATUS ss;
    SecBuffer sbufs[4];
    SecBufferDesc sbd;
    Tcl_Obj *objs[3];           /* 0 status, 1 decrypted data, 2 extra data */
    BYTE *encP, *p;
    int  i, enclen;
    TCL_RESULT res;

    CHECK_NARGS_RANGE(interp, objc, 3, INT_MAX);
    if (ObjToSecHandle(interp, objv[1], &sech) != TCL_OK)
        return TCL_ERROR;

1057
1058
1059
1060
1061
1062
1063
1064
1065

1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
        break;
    }

    MemLifoPopFrame(ticP->memlifoP);
    return res;
}

static int Twapi_AcquireCredentialsHandleObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    LUID luid, *luidP;
    LPWSTR principalP;
    LPWSTR packageP;
    DWORD cred_use;
    Tcl_Obj *authObj;
    SECURITY_STATUS status;
    LARGE_INTEGER timestamp;
    SecHandle credH; 
    Tcl_Obj *objs[2];
    MemLifoMarkHandle mark;
    TCL_RESULT res = TCL_ERROR;
    int is_unisp, n;
    void *pv;

    ObjToUnicodeCleanup();

    pv = NULL;

    mark = MemLifoPushMark(ticP->memlifoP);
    luidP = &luid;
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETEMPTYASNULL(principalP), GETWSTR(packageP),
                       GETINT(cred_use), GETVAR(luidP, ObjToLUID_NULL),
                       GETOBJ(authObj), ARGEND) != TCL_OK)
        goto vamoose;

    if (ObjListLength(interp, authObj, &n) != TCL_OK)
        goto vamoose;

    if (n == 0)
        pv = NULL;
    else {
        if (WSTREQ(packageP, UNISP_NAME_W) ||
            WSTREQ(packageP, SCHANNEL_NAME_W)) {
            if (ParseSCHANNEL_CRED(ticP, authObj, (SCHANNEL_CRED *)&pv) != TCL_OK)
                goto vamoose;
            is_unisp = 1;
#ifdef WDIGEST_SP_NAME_W
        } else if (WSTREQ(packageP, WDIGEST_SP_NAME_W) ||
                   WSTREQ(packageP, NTLMSP_NAME) ||
                   WSTREQ(packageP, NEGOSSP_NAME_W) ||
                   WSTREQ(packageP, MICROSOFT_KERBEROS_NAME_W)) {
            /* TBD - SDK has the comment that for RPC this memory
               must be valid for the lifetime of the binding handle. Is
               that true for SSPI also. Test */
            if (ParsePSEC_WINNT_AUTH_IDENTITY(ticP, authObj, &(SEC_WINNT_AUTH_IDENTITY_W *)pv) != TCL_OK)
                goto vamoose;
            is_unisp = 0;
#endif
        } else {
            TwapiReturnErrorEx(interp, TWAPI_UNSUPPORTED_TYPE,
                               Tcl_ObjPrintf("Non-default authentication is not supported for SSPI package %s.", ObjToString(objv[2])));
            goto vamoose;







|

>














<
<

>











|
<
<


|










|







1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074


1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088


1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
        break;
    }

    MemLifoPopFrame(ticP->memlifoP);
    return res;
}

static int Twapi_AcquireCredentialsHandleObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    LUID luid, *luidP;
    LPWSTR principalP;
    LPWSTR packageP;
    DWORD cred_use;
    Tcl_Obj *authObj;
    SECURITY_STATUS status;
    LARGE_INTEGER timestamp;
    SecHandle credH; 
    Tcl_Obj *objs[2];
    MemLifoMarkHandle mark;
    TCL_RESULT res = TCL_ERROR;
    int is_unisp, n;
    void *pv;



    pv = NULL;
    is_unisp = 1;
    mark = MemLifoPushMark(ticP->memlifoP);
    luidP = &luid;
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETEMPTYASNULL(principalP), GETWSTR(packageP),
                       GETINT(cred_use), GETVAR(luidP, ObjToLUID_NULL),
                       GETOBJ(authObj), ARGEND) != TCL_OK)
        goto vamoose;

    if (ObjListLength(interp, authObj, &n) != TCL_OK)
        goto vamoose;

    if (n != 0) {


        if (WSTREQ(packageP, UNISP_NAME_W) ||
            WSTREQ(packageP, SCHANNEL_NAME_W)) {
            if (ParseSCHANNEL_CRED(ticP, authObj, (SCHANNEL_CRED **)&pv) != TCL_OK)
                goto vamoose;
            is_unisp = 1;
#ifdef WDIGEST_SP_NAME_W
        } else if (WSTREQ(packageP, WDIGEST_SP_NAME_W) ||
                   WSTREQ(packageP, NTLMSP_NAME) ||
                   WSTREQ(packageP, NEGOSSP_NAME_W) ||
                   WSTREQ(packageP, MICROSOFT_KERBEROS_NAME_W)) {
            /* TBD - SDK has the comment that for RPC this memory
               must be valid for the lifetime of the binding handle. Is
               that true for SSPI also. Test */
            if (ParsePSEC_WINNT_AUTH_IDENTITY(ticP, authObj, (SEC_WINNT_AUTH_IDENTITY_W **)&pv) != TCL_OK)
                goto vamoose;
            is_unisp = 0;
#endif
        } else {
            TwapiReturnErrorEx(interp, TWAPI_UNSUPPORTED_TYPE,
                               Tcl_ObjPrintf("Non-default authentication is not supported for SSPI package %s.", ObjToString(objv[2])));
            goto vamoose;
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
        case 10025: // DecryptMessage
            if (TwapiGetArgs(interp, objc, objv,
                             GETVAR(sech, ObjToSecHandle),
                             GETVAR(sbd, ObjToSecBufferDescRW),
                             GETINT(dw),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            dw2 = DecryptMessage(&sech, &sbd, dw, &result.value.ival);
            if (dw2 == 0) {
                result.type = TRT_OBJ;
                result.value.obj = ObjFromSecBufferDesc(&sbd);
            } else {
                result.type = TRT_EXCEPTION_ON_ERROR;
                result.value.ival = dw2;
            }







|







1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
        case 10025: // DecryptMessage
            if (TwapiGetArgs(interp, objc, objv,
                             GETVAR(sech, ObjToSecHandle),
                             GETVAR(sbd, ObjToSecBufferDescRW),
                             GETINT(dw),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            dw2 = DecryptMessage(&sech, &sbd, dw, &result.value.uval);
            if (dw2 == 0) {
                result.type = TRT_OBJ;
                result.value.obj = ObjFromSecBufferDesc(&sbd);
            } else {
                result.type = TRT_EXCEPTION_ON_ERROR;
                result.value.ival = dw2;
            }
Changes to undroid/twapi/twapi/device/device.c.
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
            DEV_BROADCAST_HDR dev_bcast_hdr; /* VARIABLE SIZED. MUST BE LAST */
        } device;
        char msg[1];            /* Actually variable size */
    } data;
} TwapiDeviceNotificationCallback;

static TwapiOneTimeInitState TwapiDeviceModuleInitialized;
static DWORD TwapiDeviceNotificationTid;

int ObjToSP_DEVINFO_DATA(Tcl_Interp *, Tcl_Obj *objP, SP_DEVINFO_DATA *sddP);
int ObjToSP_DEVINFO_DATA_NULL(Tcl_Interp *interp, Tcl_Obj *objP,
                              SP_DEVINFO_DATA **sddPP);
Tcl_Obj *ObjFromSP_DEVINFO_DATA(SP_DEVINFO_DATA *sddP);
int ObjToSP_DEVICE_INTERFACE_DATA(Tcl_Interp *interp, Tcl_Obj *objP,
                                  SP_DEVICE_INTERFACE_DATA *sdidP);







|







76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
            DEV_BROADCAST_HDR dev_bcast_hdr; /* VARIABLE SIZED. MUST BE LAST */
        } device;
        char msg[1];            /* Actually variable size */
    } data;
} TwapiDeviceNotificationCallback;

static TwapiOneTimeInitState TwapiDeviceModuleInitialized;
static UINT TwapiDeviceNotificationTid;

int ObjToSP_DEVINFO_DATA(Tcl_Interp *, Tcl_Obj *objP, SP_DEVINFO_DATA *sddP);
int ObjToSP_DEVINFO_DATA_NULL(Tcl_Interp *interp, Tcl_Obj *objP,
                              SP_DEVINFO_DATA **sddPP);
Tcl_Obj *ObjFromSP_DEVINFO_DATA(SP_DEVINFO_DATA *sddP);
int ObjToSP_DEVICE_INTERFACE_DATA(Tcl_Interp *interp, Tcl_Obj *objP,
                                  SP_DEVICE_INTERFACE_DATA *sdidP);
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        if (success || (winerr = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
            break;
        /* Retry with larger buffer size as returned in call */
        sdiddP = MemLifoAlloc(ticP->memlifoP, buf_sz, NULL);
    }

    if (success) {
        objs[0] = ObjFromUnicode(sdiddP->DevicePath);
        objs[1] = ObjFromSP_DEVINFO_DATA(&sdd);
        ObjSetResult(ticP->interp, ObjNewList(2, objs));
    } else
        Twapi_AppendSystemError(ticP->interp, HRESULT_FROM_SETUPAPI(winerr));

    MemLifoPopFrame(ticP->memlifoP);








|







265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        if (success || (winerr = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
            break;
        /* Retry with larger buffer size as returned in call */
        sdiddP = MemLifoAlloc(ticP->memlifoP, buf_sz, NULL);
    }

    if (success) {
        objs[0] = ObjFromWinChars(sdiddP->DevicePath);
        objs[1] = ObjFromSP_DEVINFO_DATA(&sdd);
        ObjSetResult(ticP->interp, ObjNewList(2, objs));
    } else
        Twapi_AppendSystemError(ticP->interp, HRESULT_FROM_SETUPAPI(winerr));

    MemLifoPopFrame(ticP->memlifoP);

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    DWORD needed;
    int success;
    void  *reserved;
    DWORD  i;
    DWORD buf_sz;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    success = 0;
    if (TwapiGetArgsEx(ticP, objc, objv,
                       GETWSTR(class_name),
                       ARGUSEDEFAULT,
                       GETEMPTYASNULL(system_name),







<
<







289
290
291
292
293
294
295


296
297
298
299
300
301
302
    DWORD needed;
    int success;
    void  *reserved;
    DWORD  i;
    DWORD buf_sz;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);

    success = 0;
    if (TwapiGetArgsEx(ticP, objc, objv,
                       GETWSTR(class_name),
                       ARGUSEDEFAULT,
                       GETEMPTYASNULL(system_name),
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
       }

        objs[nobjs++] = ObjFromDevtype(dbhP->dbch_devicetype);
        switch( dbhP->dbch_devicetype ) {
        case DBT_DEVTYP_DEVICEINTERFACE:
            /* First tack on the GUID, then the name */
            objs[nobjs++] = ObjFromGUID(&((PDEV_BROADCAST_DEVICEINTERFACE_W)dbhP)->dbcc_classguid);
            objs[nobjs++] = ObjFromUnicode(((PDEV_BROADCAST_DEVICEINTERFACE_W)dbhP)->dbcc_name);
            break;

        case DBT_DEVTYP_HANDLE:
            objs[nobjs++] = ObjFromHANDLE(((PDEV_BROADCAST_HANDLE)dbhP)->dbch_handle);
            objs[nobjs++] = ObjFromOpaque(((PDEV_BROADCAST_HANDLE)dbhP)->dbch_hdevnotify, "HDEVNOTIFY");

            /*
             * No additional arguments are passed since there is no other
             * useful information in the structure unless the event is
             * DBT_CUSTOMEVENT which is not handled here.
             */
            break;

        case DBT_DEVTYP_OEM:
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_OEM)dbhP)->dbco_identifier);
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_OEM)dbhP)->dbco_suppfunc);
            break;

        case DBT_DEVTYP_PORT:
            objs[nobjs++] = ObjFromUnicode(((PDEV_BROADCAST_PORT_W)dbhP)->dbcp_name);
            break;

        case DBT_DEVTYP_VOLUME:
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_VOLUME)dbhP)->dbcv_unitmask);
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_VOLUME)dbhP)->dbcv_flags);
            break;
        }







|



















|







413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
       }

        objs[nobjs++] = ObjFromDevtype(dbhP->dbch_devicetype);
        switch( dbhP->dbch_devicetype ) {
        case DBT_DEVTYP_DEVICEINTERFACE:
            /* First tack on the GUID, then the name */
            objs[nobjs++] = ObjFromGUID(&((PDEV_BROADCAST_DEVICEINTERFACE_W)dbhP)->dbcc_classguid);
            objs[nobjs++] = ObjFromWinChars(((PDEV_BROADCAST_DEVICEINTERFACE_W)dbhP)->dbcc_name);
            break;

        case DBT_DEVTYP_HANDLE:
            objs[nobjs++] = ObjFromHANDLE(((PDEV_BROADCAST_HANDLE)dbhP)->dbch_handle);
            objs[nobjs++] = ObjFromOpaque(((PDEV_BROADCAST_HANDLE)dbhP)->dbch_hdevnotify, "HDEVNOTIFY");

            /*
             * No additional arguments are passed since there is no other
             * useful information in the structure unless the event is
             * DBT_CUSTOMEVENT which is not handled here.
             */
            break;

        case DBT_DEVTYP_OEM:
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_OEM)dbhP)->dbco_identifier);
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_OEM)dbhP)->dbco_suppfunc);
            break;

        case DBT_DEVTYP_PORT:
            objs[nobjs++] = ObjFromWinChars(((PDEV_BROADCAST_PORT_W)dbhP)->dbcp_name);
            break;

        case DBT_DEVTYP_VOLUME:
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_VOLUME)dbhP)->dbcv_unitmask);
            objs[nobjs++] = ObjFromLong(((PDEV_BROADCAST_VOLUME)dbhP)->dbcv_flags);
            break;
        }
798
799
800
801
802
803
804
805
806
807
808
809
810
811

812
813
814
815
816
817
818
819
820
821
822
    } // End of PeekMessage while loop.


    return 0;
}


static int TwapiDeviceModuleInit(Tcl_Interp *interp)
{
    /*
     * We have to create the device notification thread. Moreover, we
     * will have to wait for it to run and start processing the message loop 
     * else our first request might be lost.
     */

    HANDLE threadH;
    HANDLE sig;
    int status = TCL_ERROR;
    DWORD winerr;

    
    sig = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (sig) {
        /* TBD - when does the thread get asked to exit? */
#if defined(TWAPI_REPLACE_CRT) || defined(TWAPI_MINIMIZE_CRT)
        threadH = CreateThread(NULL, 0, TwapiDeviceNotificationThread, sig, 0,







|






>



|







796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
    } // End of PeekMessage while loop.


    return 0;
}


static int TwapiDeviceModuleInit(void *arg)
{
    /*
     * We have to create the device notification thread. Moreover, we
     * will have to wait for it to run and start processing the message loop 
     * else our first request might be lost.
     */
    Tcl_Interp *interp = arg;
    HANDLE threadH;
    HANDLE sig;
    int status = TCL_ERROR;
    DWORD winerr = 0;

    
    sig = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (sig) {
        /* TBD - when does the thread get asked to exit? */
#if defined(TWAPI_REPLACE_CRT) || defined(TWAPI_MINIMIZE_CRT)
        threadH = CreateThread(NULL, 0, TwapiDeviceNotificationThread, sig, 0,
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076

1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
        objs[2] = ObjFromEmptyString();
    
    return ObjNewList(3, objs);
}


/* Find the window handle corresponding to a device notification id */
static TwapiDeviceNotificationContext *TwapiFindDeviceNotificationById(DWORD_PTR id)
{
    TwapiDeviceNotificationContext *dncP;

    /* No need for locking, only accessed from a single thread */
    ZLIST_LOCATE(dncP, &gTwapiDeviceNotificationRegistry, id, id);
    return dncP;
}

/* Find the window handle corresponding to a device notification id */
static TwapiDeviceNotificationContext *TwapiFindDeviceNotificationByHwnd(HWND hwnd)
{
    TwapiDeviceNotificationContext *dncP;

    /* No need for locking, only accessed from a single thread */
    ZLIST_LOCATE(dncP, &gTwapiDeviceNotificationRegistry, hwnd, hwnd);
    return dncP;
}

static int Twapi_DeviceIoControlObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    HANDLE   hdev;
    Tcl_Obj *inputObj;
    DWORD    ctrl;
    void    *inP, *outP;
    DWORD    nin, nout;
    MemLifo *memlifoP = ticP->memlifoP;
    MemLifoMarkHandle mark;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLE(hdev), GETINT(ctrl),
                     ARGUSEDEFAULT, GETOBJ(inputObj),
                     GETINT(nout),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;








|


















|

>









<
<







1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085


1086
1087
1088
1089
1090
1091
1092
        objs[2] = ObjFromEmptyString();
    
    return ObjNewList(3, objs);
}


/* Find the window handle corresponding to a device notification id */
static TwapiDeviceNotificationContext *TwapiFindDeviceNotificationById(TwapiId id)
{
    TwapiDeviceNotificationContext *dncP;

    /* No need for locking, only accessed from a single thread */
    ZLIST_LOCATE(dncP, &gTwapiDeviceNotificationRegistry, id, id);
    return dncP;
}

/* Find the window handle corresponding to a device notification id */
static TwapiDeviceNotificationContext *TwapiFindDeviceNotificationByHwnd(HWND hwnd)
{
    TwapiDeviceNotificationContext *dncP;

    /* No need for locking, only accessed from a single thread */
    ZLIST_LOCATE(dncP, &gTwapiDeviceNotificationRegistry, hwnd, hwnd);
    return dncP;
}

static int Twapi_DeviceIoControlObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HANDLE   hdev;
    Tcl_Obj *inputObj;
    DWORD    ctrl;
    void    *inP, *outP;
    DWORD    nin, nout;
    MemLifo *memlifoP = ticP->memlifoP;
    MemLifoMarkHandle mark;
    TCL_RESULT res;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLE(hdev), GETINT(ctrl),
                     ARGUSEDEFAULT, GETOBJ(inputObj),
                     GETINT(nout),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

1121
1122
1123
1124
1125
1126
1127
1128
1129

1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
            res = TwapiReturnSystemError(interp);
    }

    MemLifoPopMark(mark);
    return res;
}

static int Twapi_DeviceCallObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    int func;
    GUID guid;
    GUID *guidP;
    HWND   hwnd;
    LPVOID pv;
    Tcl_Obj *sObj, *s2Obj;
    DWORD dw, dw2;
    CONFIGRET cret;
    union {
        WCHAR buf[MAX_PATH+1];
        struct {
            SP_DEVINFO_DATA sp_devinfo_data;
            SP_DEVINFO_DATA *sp_devinfo_dataP;
            SP_DEVICE_INTERFACE_DATA sp_device_interface_data;
        } dev;
    } u;
    HANDLE h;
    TwapiResult result;

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 56: // CM_Reenumerate_DevNode_Ex







|

>



















<
<







1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147


1148
1149
1150
1151
1152
1153
1154
            res = TwapiReturnSystemError(interp);
    }

    MemLifoPopMark(mark);
    return res;
}

static int Twapi_DeviceCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int func;
    GUID guid;
    GUID *guidP;
    HWND   hwnd;
    LPVOID pv;
    Tcl_Obj *sObj, *s2Obj;
    DWORD dw, dw2;
    CONFIGRET cret;
    union {
        WCHAR buf[MAX_PATH+1];
        struct {
            SP_DEVINFO_DATA sp_devinfo_data;
            SP_DEVINFO_DATA *sp_devinfo_dataP;
            SP_DEVICE_INTERFACE_DATA sp_device_interface_data;
        } dev;
    } u;
    HANDLE h;
    TwapiResult result;



    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 56: // CM_Reenumerate_DevNode_Ex
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
        
    case 57: // CM_Locate_DevNode_Ex
        if (TwapiGetArgs(interp, objc-2, objv+2, ARGSKIP, GETINT(dw),
                         ARGUSEDEFAULT,
                         GETHANDLET(h, HMACHINE),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        cret = CM_Locate_DevNode_ExW(&result.value.ival,
                                        ObjToUnicode(objv[2]), dw, h);
        if (cret == CR_SUCCESS)
            result.type = TRT_DWORD;
        else {
            result.type = TRT_CONFIGRET;
            result.value.ival = cret;
        }
        break;







|
|







1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
        
    case 57: // CM_Locate_DevNode_Ex
        if (TwapiGetArgs(interp, objc-2, objv+2, ARGSKIP, GETINT(dw),
                         ARGUSEDEFAULT,
                         GETHANDLET(h, HMACHINE),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        cret = CM_Locate_DevNode_ExW(&result.value.uval,
                                        ObjToWinChars(objv[2]), dw, h);
        if (cret == CR_SUCCESS)
            result.type = TRT_DWORD;
        else {
            result.type = TRT_CONFIGRET;
            result.value.ival = cret;
        }
        break;
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
        return Twapi_SetupDiClassGuidsFromNameEx(ticP, objc-2, objv+2);
    case 69: // SetupDiOpenDeviceInfo
        if (TwapiGetArgs(interp, objc-2, objv+2,
                         GETHANDLET(h, HDEVINFO), GETOBJ(sObj),
                         GETHWND(hwnd), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        u.dev.sp_devinfo_data.cbSize = sizeof(u.dev.sp_devinfo_data);
        if (SetupDiOpenDeviceInfoW(h, ObjToUnicode(sObj), hwnd, dw,
                                   &u.dev.sp_devinfo_data)) {
            result.type = TRT_OBJ;
            result.value.obj = ObjFromSP_DEVINFO_DATA(&u.dev.sp_devinfo_data);
        } else
            result.type = TRT_GETLASTERROR_SETUPAPI;
        break;
    case 70:
        if (objc != 3)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        if (ObjToHANDLE(interp, objv[2], &h) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SetupDiDestroyDeviceInfoList(h);
        break;
    case 71:
        return Twapi_RegisterDeviceNotification(ticP, objc-2, objv+2);
    case 72:
        if (objc != 3)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_INTEGER_OBJ(interp, dw, objv[2]);
        return Twapi_UnregisterDeviceNotification(ticP, dw);
    }

    return TwapiSetResult(interp, &result);
}









|



















|







1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
        return Twapi_SetupDiClassGuidsFromNameEx(ticP, objc-2, objv+2);
    case 69: // SetupDiOpenDeviceInfo
        if (TwapiGetArgs(interp, objc-2, objv+2,
                         GETHANDLET(h, HDEVINFO), GETOBJ(sObj),
                         GETHWND(hwnd), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        u.dev.sp_devinfo_data.cbSize = sizeof(u.dev.sp_devinfo_data);
        if (SetupDiOpenDeviceInfoW(h, ObjToWinChars(sObj), hwnd, dw,
                                   &u.dev.sp_devinfo_data)) {
            result.type = TRT_OBJ;
            result.value.obj = ObjFromSP_DEVINFO_DATA(&u.dev.sp_devinfo_data);
        } else
            result.type = TRT_GETLASTERROR_SETUPAPI;
        break;
    case 70:
        if (objc != 3)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        if (ObjToHANDLE(interp, objv[2], &h) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SetupDiDestroyDeviceInfoList(h);
        break;
    case 71:
        return Twapi_RegisterDeviceNotification(ticP, objc-2, objv+2);
    case 72:
        if (objc != 3)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        CHECK_DWORD_OBJ(interp, dw, objv[2]);
        return Twapi_UnregisterDeviceNotification(ticP, dw);
    }

    return TwapiSetResult(interp, &result);
}


Changes to undroid/twapi/twapi/doc/certs.man.
90
91
92
93
94
95
96

97
98
99
100
101
102
103
by calling [uri #cert_store_commit [cmd cert_store_commit]].

[para]
Commands
[uri #cert_store_export_pfx [cmd cert_store_export_pfx]],
[uri #cert_store_export_pkcs12 [cmd cert_store_export_pkcs12]],
[uri #cert_store_export_pkcs7 [cmd cert_store_export_pkcs7]],

and
[uri #cert_store_serialize [cmd cert_store_serialize]] can be used
to export certificate stores in various formats. 

[para]
Existing certificate stores can be deleted using the commands
[uri #cert_system_store_delete [cmd cert_system_store_delete]],







>







90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
by calling [uri #cert_store_commit [cmd cert_store_commit]].

[para]
Commands
[uri #cert_store_export_pfx [cmd cert_store_export_pfx]],
[uri #cert_store_export_pkcs12 [cmd cert_store_export_pkcs12]],
[uri #cert_store_export_pkcs7 [cmd cert_store_export_pkcs7]],
[uri #cert_store_export_pem [cmd cert_store_export_pem]],
and
[uri #cert_store_serialize [cmd cert_store_serialize]] can be used
to export certificate stores in various formats. 

[para]
Existing certificate stores can be deleted using the commands
[uri #cert_system_store_delete [cmd cert_system_store_delete]],
865
866
867
868
869
870
871


872
873
874
875
876
877
878

[call [cmd cert_import] [arg ENCODEDCERT] [opt "[cmd -encoding] [arg encoding]"]]
Creates and returns a certificate context from encoded data in
[arg ENCODEDCERT]. 
[arg ENCODING] may be [const der] or [const pem]
depending on whether [arg ENCODEDCERT] uses DER- or PEM-encoding.
If unspecified, the command attempts to determine the encoding itself.



[call [cmd cert_info] [arg HCERT]]
Returns the following fields from a certificate context as a dictionary.
[list_begin opt]
[opt_def [const -end]] The end of the certificate's validity period
in the format [arg "Year-Month-Day Hour:Minutes:Seconds"]
[opt_def [const -extensions]] A list of extensions in the certificate.







>
>







866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881

[call [cmd cert_import] [arg ENCODEDCERT] [opt "[cmd -encoding] [arg encoding]"]]
Creates and returns a certificate context from encoded data in
[arg ENCODEDCERT]. 
[arg ENCODING] may be [const der] or [const pem]
depending on whether [arg ENCODEDCERT] uses DER- or PEM-encoding.
If unspecified, the command attempts to determine the encoding itself.
For performance reasons, the encoding should be explicitly specified
when possible.

[call [cmd cert_info] [arg HCERT]]
Returns the following fields from a certificate context as a dictionary.
[list_begin opt]
[opt_def [const -end]] The end of the certificate's validity period
in the format [arg "Year-Month-Day Hour:Minutes:Seconds"]
[opt_def [const -extensions]] A list of extensions in the certificate.
1232
1233
1234
1235
1236
1237
1238




1239
1240
1241
1242
1243
1244
1245
The command returns an
empty string when there are no more certificates in the store.
[nl]
The command 
[uri #cert_store_find_certificate [cmd cert_store_find_certificate]]
offers another means for retrieving certificates from a store.





[call [cmd cert_store_export_pfx] [arg HSTORE] [arg PASSWORD] [opt [arg options]]]
Returns a binary containing all the certificates in a certificate store
in PFX (PKCS #12) format.
[arg HSTORE] is a handle to the store and [arg PASSWORD] is the password
to be used for encrypting the returned content. [arg PASSWORD] itself
must be an empty string (if the returned data is not to be encrypted),
or the encryption password in 







>
>
>
>







1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
The command returns an
empty string when there are no more certificates in the store.
[nl]
The command 
[uri #cert_store_find_certificate [cmd cert_store_find_certificate]]
offers another means for retrieving certificates from a store.

[call [cmd cert_store_export_pem] [arg HSTORE]]
Returns all certificates in a store in PEM encoded format. This format is
commonly used with the [cmd openssl] program's [cmd -CAfile] option.

[call [cmd cert_store_export_pfx] [arg HSTORE] [arg PASSWORD] [opt [arg options]]]
Returns a binary containing all the certificates in a certificate store
in PFX (PKCS #12) format.
[arg HSTORE] is a handle to the store and [arg PASSWORD] is the password
to be used for encrypting the returned content. [arg PASSWORD] itself
must be an empty string (if the returned data is not to be encrypted),
or the encryption password in 
Changes to undroid/twapi/twapi/doc/crypto.man.
1154
1155
1156
1157
1158
1159
1160
1161













































































































1162
1163
1164
1165
1166
1167
1168
[nl]
[arg PRF] specifies the pseudo random function and must be
either [const sha1] or [const sha_256].
[arg SALT] and [arg NITERATIONS] are used as defined
in the RFC.
[nl]
The returned key is in a [uri base.html#protectingdatainmemory concealed] form.
                    













































































































[call [cmd protect_data] [arg BINDATA] [opt [arg options]]]
Encrypts and signs the binary data [arg BINDATA] so that it can only
be recovered by a process running under the same user credentials
on the same system through [uri #unprotect_data [cmd unprotect_data]].
[nl]
The following options may be specified:
[list_begin opt]







|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
[nl]
[arg PRF] specifies the pseudo random function and must be
either [const sha1] or [const sha_256].
[arg SALT] and [arg NITERATIONS] are used as defined
in the RFC.
[nl]
The returned key is in a [uri base.html#protectingdatainmemory concealed] form.


[call [cmd pkcs7_decrypt] [arg PKCS7MSG] [arg STORES] [opt [arg options]]]
Decrypts the PKCS7 message [arg PKCS7MSG] and returns the corresponding
plaintext. [arg STORES] should be a list of one or more certificate store
handles one of which must contain a certificate matching one of
the recipients listed in the message and which has an associated private key.
[nl]
The following options may be specified.
[list_begin opt]
[opt_def [cmd -certvar] [arg CERTVAR]]
If specified and [arg CERTVAR] is not the empty string, a handle
to a certificate context for the certificate used for decryption is stored
in the variable [arg CERTVAR] in the caller's context. This must
be released later by calling [uri certs.html#cert_release [cmd cert_release]].
[opt_def [cmd -encoding] [arg ENCODING]]
If unspecified or the empty string,
the command attempts to determine the encoding itself.
Otherwise, [arg ENCODING] must be [const der] or [const pem]
depending on whether [arg PKCS7MSG] uses DER- or PEM-encoding.
For performance reasons, the encoding should be explicitly specified
when possible.
[opt_def [cmd -silent] [arg BOOL]]
If the decryption key is user protected, the user is notified when
the key is used. If [arg -silent] is [const true],
the user is not notified for such keys and the command returns an
error instead. Default is [const false].
[list_end]

[call [cmd pkcs7_encrypt] [arg BINDATA] [arg RECIPIENTS] [arg ENCALGOID] [opt [arg options]]]
Encrypts the binary string [arg BINDATA] using a generated session
key for the symmetric encryption algorithm specified by the OID
[arg ENCALGOID]. The session key is itself encrypted using each
of the public keys corresponding to the list of certificate contexts
[arg RECIPIENTS]. The return value is formatted as an enveloped PKCS7
message as defined in [uri https://tools.ietf.org/html/rfc2315 "RFC 2315"].
[nl]
The following option may be specified with the command.
[list_begin opt]
[opt_def [cmd -encoding] [arg ENCODING]]
Specifies the encoding in which the encoded message is returned.
[arg ENCODING] may be [const der] or [const pem] (default)
for DER- and PEM-encoding respectively.
[list_end]
                    
[call [cmd pkcs7_sign] [arg BINDATA] [arg HCERT] [arg HASHALGOID] [opt [arg options]]]
Computes the hash of the binary string [arg BINDATA], signs it
with the private key corresponding
to the certificate [arg HCERT] and returns it as a PKCS7 formatted
message as defined in [uri https://tools.ietf.org/html/rfc2315 "RFC 2315"].
[arg HASHALGOID] is the OID of the hashing algorithm to be used.
The following options may be specified.
[list_begin opt]
[opt_def [cmd -detached] [arg BOOL]]
If [const false] (default), the content [arg BINDATA] is included in
the message. If [const true], the PKCS7 packet is constructed as a
detached packet without the content.
[opt_def [cmd -encoding] [arg ENCODING]]
Specifies the encoding in which the encoded message is returned.
[arg ENCODING] may be [const der] or [const pem] (default)
for DER- and PEM-encoding respectively.
[opt_def [cmd -includecerts] [const none|leaf|all]]
If unspecified or [const all], the signing certificate [arg HCERT]
along with all certificates in its certificate chain are included
in the PKCS7 message. If [const leaf], only the signing certificate is
included and if [const none], no certificates are included in the message.
[opt_def [cmd -silent] [arg BOOL]]
If the signing key is user protected, the user is notified when
the key is used for signing. If [arg -silent] is [const true],
the user is not notified for such keys and the command returns an
error instead. Default is [const false].
[opt_def [cmd -usersignerkeyid] [arg BOOL]]
By default or if [const false],
the certificate issuer and serial number is used to identify
the signer. If this option is [const true], the key identifier is
used for this purpose instead.
[list_end]

[call [cmd pkcs7_verify] [arg PKCS7MSG] [opt [arg options]]]
Verifies the signature of a PKCS7 signed message [arg PKCS7MSG]. If
the signature verifies successfully, the command returns [const ok].
Otherwise, it returns one of the error status values specified
for [uri certs.html#cert_verify [cmd cert_verify]].
[nl]
In addition to verifying the signature on the message, the command
also verifies that the signing certificate is valid by calling
[uri certs.html#cert_verify [cmd cert_verify]]. All options for
that command are therefore accepted by [cmd pkcs7_verify] as well.
[nl]
In addition to those options, the command accepts the following options:
[list_begin opt]
[opt_def [cmd -certvar] [arg CERTVAR]]
If specified and [arg CERTVAR] is not the empty string, a handle
to a certificate context for the signing certificate is stored
in the variable [arg CERTVAR] in the caller's context. This must
be released later by calling [uri certs.html#cert_release [cmd cert_release]].
[opt_def [cmd -contentvar] [arg CONTENTVAR]]
If specified and [arg CONTENTVAR] is not the empty string, the
content of the message is stored in the variable [arg CONTENTVAR] in
the caller's context.
[opt_def [cmd -encoding] [arg ENCODING]]
If unspecified or the empty string,
the command attempts to determine the encoding itself.
Otherwise, [arg ENCODING] must be [const der] or [const pem]
depending on whether [arg PKCS7MSG] uses DER- or PEM-encoding.
For performance reasons, the encoding should be explicitly specified
when possible.

[list_end]

[call [cmd protect_data] [arg BINDATA] [opt [arg options]]]
Encrypts and signs the binary data [arg BINDATA] so that it can only
be recovered by a process running under the same user credentials
on the same system through [uri #unprotect_data [cmd unprotect_data]].
[nl]
The following options may be specified:
[list_begin opt]
Changes to undroid/twapi/twapi/doc/versionhistory.man.
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
[uri certs.html#cert_chain_build [cmd cert_chain_build]],
[uri certs.html#cert_chain_simple_chain [cmd cert_chain_simple_chain]],
[uri certs.html#cert_chain_trust_errors [cmd cert_chain_trust_errors]],
[uri certs.html#cert_chain_trust_info [cmd cert_chain_trust_info]]
for certificate validation.

[bullet]







Added [uri certs.html#cert_fetch [cmd cert_fetch]] for retrieving a
certificate from a SSL/TLS server.



[bullet]
Added [uri comserver.html#com_query_client_blanket [cmd com_query_client_blanket]].

[bullet]
Added [cmd -requestclientcert] option to
[uri tls.html#tls_socket [cmd tls_socket]].

[bullet]
Added [const bstr] type to [uri base.html#tclcast [cmd tclcast]]
for casting COM parameters as strings.

[bullet]
Added
[uri crypto.html#capi_hash_sign [cmd capi_hash_sign]],
[uri crypto.html#capi_hash_verify [cmd capi_hash_verify]],
[uri crypto.html#capi_encrypt_bytes [cmd capi_encrypt_bytes]],
[uri crypto.html#capi_encrypt_string [cmd capi_encrypt_string]],







>
>
>
>
>
>
>
|
|
>
>









|
<







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
[uri certs.html#cert_chain_build [cmd cert_chain_build]],
[uri certs.html#cert_chain_simple_chain [cmd cert_chain_simple_chain]],
[uri certs.html#cert_chain_trust_errors [cmd cert_chain_trust_errors]],
[uri certs.html#cert_chain_trust_info [cmd cert_chain_trust_info]]
for certificate validation.

[bullet]
Addec PKCS7 handling commands
[uri crypto.html#pkcs7_decrypt [cmd pkcs7_decrypt]],
[uri crypto.html#pkcs7_encrypt [cmd pkcs7_encrypt]],
[uri crypto.html#pkcs7_sign [cmd pkcs7_sign]],
[uri crypto.html#pkcs7_verify [cmd pkcs7_verify]].

[bullet]
Added [uri certs.html#cert_fetch [cmd cert_fetch]].

[bullet]
Added [uri certs.html#cert_store_export_pem [cmd cert_store_export_pem]].

[bullet]
Added [uri comserver.html#com_query_client_blanket [cmd com_query_client_blanket]].

[bullet]
Added [cmd -requestclientcert] option to
[uri tls.html#tls_socket [cmd tls_socket]].

[bullet]
Added [const bstr] type to [uri base.html#tclcast [cmd tclcast]].


[bullet]
Added
[uri crypto.html#capi_hash_sign [cmd capi_hash_sign]],
[uri crypto.html#capi_hash_verify [cmd capi_hash_verify]],
[uri crypto.html#capi_encrypt_bytes [cmd capi_encrypt_bytes]],
[uri crypto.html#capi_encrypt_string [cmd capi_encrypt_string]],
Changes to undroid/twapi/twapi/etw/etw.c.
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416

/* Windows allows max 64 sessions */
#define MAX_SESSIONS 64

/* Max length of file and session name fields in a trace (documented in SDK) */
#define MAX_TRACE_NAME_CHARS (1024+1)

#define ObjFromTRACEHANDLE(val_) ObjFromWideInt(val_)
#define ObjToTRACEHANDLE ObjToWideInt

static TRACEHANDLE gInvalidTraceHandle;
#define INVALID_SESSIONTRACE_HANDLE(ht_) ((ht_) == gInvalidTraceHandle)

/* For efficiency reasons, when constructing many "records" each of which is
 * a keyed list or dictionary, we do not want to recreate the
 * key Tcl_Obj for every record. So we create them once and reuse them.







<
<







401
402
403
404
405
406
407


408
409
410
411
412
413
414

/* Windows allows max 64 sessions */
#define MAX_SESSIONS 64

/* Max length of file and session name fields in a trace (documented in SDK) */
#define MAX_TRACE_NAME_CHARS (1024+1)




static TRACEHANDLE gInvalidTraceHandle;
#define INVALID_SESSIONTRACE_HANDLE(ht_) ((ht_) == gInvalidTraceHandle)

/* For efficiency reasons, when constructing many "records" each of which is
 * a keyed list or dictionary, we do not want to recreate the
 * key Tcl_Obj for every record. So we create them once and reuse them.
504
505
506
507
508
509
510









511
512
513
514
515
516
517
TCL_RESULT Twapi_StartTrace(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
TCL_RESULT Twapi_ProcessTrace(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
TCL_RESULT Twapi_ParseEventMofData(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);

/*
 * Functions
 */










static int TwapiCalcPointerSize(EVENT_RECORD *evrP)
{
    if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_32_BIT_HEADER)
        return 4;
    else if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_64_BIT_HEADER)
        return 8;







>
>
>
>
>
>
>
>
>







502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
TCL_RESULT Twapi_StartTrace(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
TCL_RESULT Twapi_ProcessTrace(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);
TCL_RESULT Twapi_ParseEventMofData(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]);

/*
 * Functions
 */
static Tcl_Obj *ObjFromTRACEHANDLE(TRACEHANDLE htrace)
{
    return ObjFromWideInt((Tcl_WideInt) htrace);
}
static TCL_RESULT ObjToTRACEHANDLE(Tcl_Interp *interp, Tcl_Obj *objP, TRACEHANDLE *traceP)
{
    TWAPI_ASSERT(sizeof(TRACEHANDLE) == sizeof(Tcl_WideInt));
    return ObjToWideInt(interp, objP, (Tcl_WideInt *)traceP);
}

static int TwapiCalcPointerSize(EVENT_RECORD *evrP)
{
    if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_32_BIT_HEADER)
        return 4;
    else if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_64_BIT_HEADER)
        return 8;
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
        case 1: // -sessionname
            session_name_i = i;
            break;
        }
    }
    
    if (session_name_i >= 0) {
        session_name = ObjToUnicodeN(objv[session_name_i+1], &session_name_i);
    } else {
        session_name_i = 0;
    }

    if (logfile_name_i >= 0) {
        logfile_name = ObjToUnicodeN(objv[logfile_name_i+1], &logfile_name_i);
    } else {
        logfile_name_i = 0;
    }

    /* Note: session_name_i/logfile_name_i now contain lengths of names */

    buf_sz = sizeof(*etP);







|





|







639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
        case 1: // -sessionname
            session_name_i = i;
            break;
        }
    }
    
    if (session_name_i >= 0) {
        session_name = ObjToWinCharsN(objv[session_name_i+1], &session_name_i);
    } else {
        session_name_i = 0;
    }

    if (logfile_name_i >= 0) {
        logfile_name = ObjToWinCharsN(objv[logfile_name_i+1], &logfile_name_i);
    } else {
        logfile_name_i = 0;
    }

    /* Note: session_name_i/logfile_name_i now contain lengths of names */

    buf_sz = sizeof(*etP);
738
739
740
741
742
743
744
745

746
747
748
749
750
751
752
        case 9: // -enableflags
            ulP = &etP->EnableFlags;
            break;
        case 10: // -clockresolution
            ulP = &etP->Wnode.ClientContext;
            break;
        case 11: // -agelimit
            ulP = &etP->AgeLimit;

            break;
        case 12: // -numbuffers
            ulP = &etP->NumberOfBuffers;
            break;
        case 13: // -freebuffers
            ulP = &etP->FreeBuffers;
            break;







|
>







745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
        case 9: // -enableflags
            ulP = &etP->EnableFlags;
            break;
        case 10: // -clockresolution
            ulP = &etP->Wnode.ClientContext;
            break;
        case 11: // -agelimit
            if (ObjToLong(interp, objv[i+1], &etP->AgeLimit) != TCL_OK)
                goto error_handler;
            break;
        case 12: // -numbuffers
            ulP = &etP->NumberOfBuffers;
            break;
        case 13: // -freebuffers
            ulP = &etP->FreeBuffers;
            break;
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
            ObjSetStaticResult(interp, "Internal error: Unexpected field index.");
            goto error_handler;
        }
        
        if (ulP == NULL) {
            /* Nothing to do, value already set in the switch */
        } else {
            if (ObjToLong(interp, objv[i+1], ulP) != TCL_OK)
                goto error_handler;
        }
    }
    
    *etPP = etP;
    return TCL_OK;

error_handler: /* interp must already contain error msg */
    if (etP)
        TwapiFree(etP);
    return TCL_ERROR;
}

static Tcl_Obj *ObjFromEVENT_TRACE_PROPERTIES(EVENT_TRACE_PROPERTIES *etP)
{
    Tcl_Obj *objs[19];

    if (etP->LogFileNameOffset)
        objs[0] = ObjFromUnicode((WCHAR *)(etP->LogFileNameOffset + (char *) etP));
    else
        objs[0] = ObjFromEmptyString();

    if (etP->LoggerNameOffset)
        objs[1] = ObjFromUnicode((WCHAR *)(etP->LoggerNameOffset + (char *) etP));
    else
        objs[1] = ObjFromEmptyString();

    objs[2] = ObjFromGUID(&etP->Wnode.Guid);
    objs[3] = ObjFromLong(etP->BufferSize);
    objs[4] = ObjFromLong(etP->MinimumBuffers);
    objs[5] = ObjFromLong(etP->MaximumBuffers);







|


















|




|







779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
            ObjSetStaticResult(interp, "Internal error: Unexpected field index.");
            goto error_handler;
        }
        
        if (ulP == NULL) {
            /* Nothing to do, value already set in the switch */
        } else {
            if (ObjToDWORD(interp, objv[i+1], ulP) != TCL_OK)
                goto error_handler;
        }
    }
    
    *etPP = etP;
    return TCL_OK;

error_handler: /* interp must already contain error msg */
    if (etP)
        TwapiFree(etP);
    return TCL_ERROR;
}

static Tcl_Obj *ObjFromEVENT_TRACE_PROPERTIES(EVENT_TRACE_PROPERTIES *etP)
{
    Tcl_Obj *objs[19];

    if (etP->LogFileNameOffset)
        objs[0] = ObjFromWinChars((WCHAR *)(etP->LogFileNameOffset + (char *) etP));
    else
        objs[0] = ObjFromEmptyString();

    if (etP->LoggerNameOffset)
        objs[1] = ObjFromWinChars((WCHAR *)(etP->LoggerNameOffset + (char *) etP));
    else
        objs[1] = ObjFromEmptyString();

    objs[2] = ObjFromGUID(&etP->Wnode.Guid);
    objs[3] = ObjFromLong(etP->BufferSize);
    objs[4] = ObjFromLong(etP->MinimumBuffers);
    objs[5] = ObjFromLong(etP->MaximumBuffers);
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
    event.eth.Flags = WNODE_FLAG_TRACED_GUID |
        WNODE_FLAG_USE_GUID_PTR | WNODE_FLAG_USE_MOF_PTR;
    event.eth.GuidPtr = (ULONGLONG) &gETWProviderEventClassGuid;
    event.eth.Class.Type = type;
    event.eth.Class.Level = level;

    for (i = 0; i < objc; ++i) {
        event.mof[i].DataPtr = (ULONG64) ObjToByteArray(objv[i], &event.mof[i].Length);
    }

    rc = TraceEvent(gETWProviderSessionHandle, &event.eth);
    return rc == ERROR_SUCCESS ?
        TCL_OK : Twapi_AppendSystemError(interp, rc);
}


TCL_RESULT Twapi_StartTrace(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    EVENT_TRACE_PROPERTIES *etP;
    TRACEHANDLE htrace;
    TCL_RESULT res;
    
    if (objc != 3)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    ObjToUnicodeCleanup();

    if (ObjToPEVENT_TRACE_PROPERTIES(interp, objv[2], &etP) != TCL_OK)
        return TCL_ERROR;

    /* Note etP has to be freed */

    /* If no log file specified, set logfilenameoffset to 0 
       since ObjToPEVENT_TRACE_PROPERTIES does not do that as it
       is also used by ControlTrace */
    if (*(WCHAR *) (etP->LogFileNameOffset + (char *)etP) == 0)
        etP->LogFileNameOffset = 0;

    if (StartTraceW(&htrace,
                    ObjToUnicode(objv[1]),
                    etP) == ERROR_SUCCESS) {
        ObjSetResult(interp, ObjFromTRACEHANDLE(htrace));
        res = TCL_OK;
    } else
        res = Twapi_AppendSystemError(interp, GetLastError());

    TwapiFree(etP);







|

















<
<












|







1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048


1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
    event.eth.Flags = WNODE_FLAG_TRACED_GUID |
        WNODE_FLAG_USE_GUID_PTR | WNODE_FLAG_USE_MOF_PTR;
    event.eth.GuidPtr = (ULONGLONG) &gETWProviderEventClassGuid;
    event.eth.Class.Type = type;
    event.eth.Class.Level = level;

    for (i = 0; i < objc; ++i) {
        event.mof[i].DataPtr = (ULONG64) ObjToByteArrayDW(objv[i], &event.mof[i].Length);
    }

    rc = TraceEvent(gETWProviderSessionHandle, &event.eth);
    return rc == ERROR_SUCCESS ?
        TCL_OK : Twapi_AppendSystemError(interp, rc);
}


TCL_RESULT Twapi_StartTrace(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    EVENT_TRACE_PROPERTIES *etP;
    TRACEHANDLE htrace;
    TCL_RESULT res;
    
    if (objc != 3)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);



    if (ObjToPEVENT_TRACE_PROPERTIES(interp, objv[2], &etP) != TCL_OK)
        return TCL_ERROR;

    /* Note etP has to be freed */

    /* If no log file specified, set logfilenameoffset to 0 
       since ObjToPEVENT_TRACE_PROPERTIES does not do that as it
       is also used by ControlTrace */
    if (*(WCHAR *) (etP->LogFileNameOffset + (char *)etP) == 0)
        etP->LogFileNameOffset = 0;

    if (StartTraceW(&htrace,
                    ObjToWinChars(objv[1]),
                    etP) == ERROR_SUCCESS) {
        ObjSetResult(interp, ObjFromTRACEHANDLE(htrace));
        res = TCL_OK;
    } else
        res = Twapi_AppendSystemError(interp, GetLastError());

    TwapiFree(etP);
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
    ULONG code;

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(code), GETWIDE(htrace), ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    ObjToUnicodeCleanup();

    if (ObjToPEVENT_TRACE_PROPERTIES(interp, objv[3], &etP) != TCL_OK)
        return TCL_ERROR;

    if (etP->LoggerNameOffset &&
        (*(WCHAR *) (etP->LoggerNameOffset + (char *)etP) != 0))
        session_name = (WCHAR *)(etP->LoggerNameOffset + (char *)etP);
    else







<
<







1077
1078
1079
1080
1081
1082
1083


1084
1085
1086
1087
1088
1089
1090
    ULONG code;

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(code), GETWIDE(htrace), ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;



    if (ObjToPEVENT_TRACE_PROPERTIES(interp, objv[3], &etP) != TCL_OK)
        return TCL_ERROR;

    if (etP->LoggerNameOffset &&
        (*(WCHAR *) (etP->LoggerNameOffset + (char *)etP) != 0))
        session_name = (WCHAR *)(etP->LoggerNameOffset + (char *)etP);
    else
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(enable), GETINT(flags), GETINT(level),
                     GETUUID(guid), GETWIDE(htrace),
                     ARGEND) != TCL_OK) {
        return TCL_ERROR;
    }

    ObjToUnicodeCleanup();

    if (EnableTrace(enable, flags, level, &guid, htrace) != ERROR_SUCCESS)
        return TwapiReturnSystemError(interp);

    return TCL_OK;
}









<
<







1112
1113
1114
1115
1116
1117
1118


1119
1120
1121
1122
1123
1124
1125
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(enable), GETINT(flags), GETINT(level),
                     GETUUID(guid), GETWIDE(htrace),
                     ARGEND) != TCL_OK) {
        return TCL_ERROR;
    }



    if (EnableTrace(enable, flags, level, &guid, htrace) != ERROR_SUCCESS)
        return TwapiReturnSystemError(interp);

    return TCL_OK;
}


1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
        objs[4] = ObjFromEmptyString();
    
    ObjAppendElement(NULL, gETWContext.eventsObj, ObjNewList(ARRAYSIZE(objs), objs));
}

/* Used in constructing a Tcl_Obj for TRACE_EVENT_INFO when a name is 
   missing */
static Tcl_Obj *TwapiTEIUnicodeObj(TRACE_EVENT_INFO *teiP, int offset, ULONG numeric_val)
{
    if (offset == 0)
        return ObjFromULONG(numeric_val); /* Name missing, return the numeric */
    else
        return ObjFromUnicodeNoTrailingSpace((WCHAR*) (offset + (char*)teiP));
}

static Tcl_Obj *ObjFromEVENT_DESCRIPTOR(EVENT_DESCRIPTOR *evdP)
{
    Tcl_Obj *objs[7];

    objs[0] = ObjFromLong(evdP->Id);







|




|







1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
        objs[4] = ObjFromEmptyString();
    
    ObjAppendElement(NULL, gETWContext.eventsObj, ObjNewList(ARRAYSIZE(objs), objs));
}

/* Used in constructing a Tcl_Obj for TRACE_EVENT_INFO when a name is 
   missing */
static Tcl_Obj *TwapiTEIWinCharsObj(TRACE_EVENT_INFO *teiP, int offset, ULONG numeric_val)
{
    if (offset == 0)
        return ObjFromULONG(numeric_val); /* Name missing, return the numeric */
    else
        return ObjFromWinCharsNoTrailingSpace((WCHAR*) (offset + (char*)teiP));
}

static Tcl_Obj *ObjFromEVENT_DESCRIPTOR(EVENT_DESCRIPTOR *evdP)
{
    Tcl_Obj *objs[7];

    objs[0] = ObjFromLong(evdP->Id);
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
        return Twapi_AppendSystemError(ticP->interp, winerr);

    if (ref_value_size == 2)
        *countP = ref_value.ushort_val;
    else {
        if (ref_value.ulong_val > teiP->PropertyCount)
            return TwapiReturnErrorEx(ticP->interp, TWAPI_INVALID_DATA,
                                      Tcl_ObjPrintf("Property index %d out of bounds.", ref_value.ulong_val));

        *countP = (USHORT) ref_value.ulong_val;
    }

    return TCL_OK;
}








|







1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
        return Twapi_AppendSystemError(ticP->interp, winerr);

    if (ref_value_size == 2)
        *countP = ref_value.ushort_val;
    else {
        if (ref_value.ulong_val > teiP->PropertyCount)
            return TwapiReturnErrorEx(ticP->interp, TWAPI_INVALID_DATA,
                                      Tcl_ObjPrintf("Property index %lu out of bounds.", ref_value.ulong_val));

        *countP = (USHORT) ref_value.ulong_val;
    }

    return TCL_OK;
}

1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388


1389

1390
1391
1392
1393
1394
1395
1396
1397
     *   - bit map to list of strings using a mapping array (manifest based)
     * EVENTMAP_INFO_FLAG_WBEM_BITMAP
     *   - bit map to list of strings using a mapping array (MOF based)
     * EVENTMAP_INFO_FLAG_WBEM_BITMAP | EVENTMAP_INFO_FLAG_WBEM_NO_MAP
     *   - maps 0-based bit positions to list of string values (MOF based)
     */
     
    switch (emiP->Flag) {
    case EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP:
    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP:
        for (i = 0; i < emiP->EntryCount; ++i) {
            if (emiP->MapEntryArray[i].Value == val)
                return ObjFromUnicode((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP));
        }
        break;
    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP | EVENTMAP_INFO_FLAG_WBEM_NO_MAP:
        if (val < emiP->EntryCount)
            return ObjFromUnicode((WCHAR *) (emiP->MapEntryArray[val].OutputOffset + (char*)emiP));
        break;
    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP | EVENTMAP_INFO_FLAG_WBEM_FLAG:
        objP = ObjNewList(0, NULL);
        /* We ignore bits in val that are set but don't have a matching entry */
        for (i = 0; i < emiP->EntryCount; ++i) {
            if ((emiP->MapEntryArray[i].Value & val) == emiP->MapEntryArray[i].Value)
                ObjAppendElement(NULL, objP, ObjFromUnicode((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
        }
        return objP;


    case EVENTMAP_INFO_FLAG_MANIFEST_BITMAP:
        objP = ObjNewList(0, NULL);
        for (i = 0; val != 0 && i < emiP->EntryCount; ++i) {
            /* Value field is the bit mask. Match with any bit means match */
            bitmask = emiP->MapEntryArray[i].Value;
            if (bitmask & val) {
                ObjAppendElement(NULL, objP, ObjFromUnicode((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
                val &= ~ bitmask;
            }
        }
        return objP;

    case EVENTMAP_INFO_FLAG_WBEM_BITMAP:
        objP = ObjNewList(0, NULL);
        for (i = 0; val != 0 && i < emiP->EntryCount; ++i) {
            if (emiP->MapEntryArray[i].Value > 31)
                continue;
            /* Value field is the bit position to check */
            bitmask = (1 << emiP->MapEntryArray[i].Value);
            if (bitmask & val) {
                ObjAppendElement(NULL, objP, ObjFromUnicode((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
                /* Reset the bit both for efficiency as well as so we only
                   include one element even in the MapEntryArray[] contains
                   duplicate values */
                val &= ~bitmask;
            }
        }
        return objP;

    case EVENTMAP_INFO_FLAG_WBEM_BITMAP | EVENTMAP_INFO_FLAG_WBEM_NO_MAP:
        objP = ObjNewList(0, NULL);
        for (i = 0; val != 0 && i < emiP->EntryCount && i < 32; ++i) {
            bitmask = (1 << i);
            if (val & bitmask) {
                ObjAppendElement(NULL, objP, ObjFromUnicode((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
                val &= ~bitmask;
            }
        }
        return objP;

    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP | EVENTMAP_INFO_FLAG_WBEM_FLAG | EVENTMAP_INFO_FLAG_WBEM_NO_MAP:
        break;                  /* TBD */
    }




    /* No map value, return as integer */
    return ObjFromDWORD(val);
}


/* Given the raw bytes for a TDH property, return the Tcl_Obj */
static TCL_RESULT TwapiTdhPropertyValue(
    TwapiInterpContext *ticP,







|




|




|






|










|













|













|






|
|
>
>
|
>
|







1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
     *   - bit map to list of strings using a mapping array (manifest based)
     * EVENTMAP_INFO_FLAG_WBEM_BITMAP
     *   - bit map to list of strings using a mapping array (MOF based)
     * EVENTMAP_INFO_FLAG_WBEM_BITMAP | EVENTMAP_INFO_FLAG_WBEM_NO_MAP
     *   - maps 0-based bit positions to list of string values (MOF based)
     */
     
    switch ((int) emiP->Flag) {
    case EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP:
    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP:
        for (i = 0; i < emiP->EntryCount; ++i) {
            if (emiP->MapEntryArray[i].Value == val)
                return ObjFromWinChars((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP));
        }
        break;
    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP | EVENTMAP_INFO_FLAG_WBEM_NO_MAP:
        if (val < emiP->EntryCount)
            return ObjFromWinChars((WCHAR *) (emiP->MapEntryArray[val].OutputOffset + (char*)emiP));
        break;
    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP | EVENTMAP_INFO_FLAG_WBEM_FLAG:
        objP = ObjNewList(0, NULL);
        /* We ignore bits in val that are set but don't have a matching entry */
        for (i = 0; i < emiP->EntryCount; ++i) {
            if ((emiP->MapEntryArray[i].Value & val) == emiP->MapEntryArray[i].Value)
                ObjAppendElement(NULL, objP, ObjFromWinChars((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
        }
        return objP;


    case EVENTMAP_INFO_FLAG_MANIFEST_BITMAP:
        objP = ObjNewList(0, NULL);
        for (i = 0; val != 0 && i < emiP->EntryCount; ++i) {
            /* Value field is the bit mask. Match with any bit means match */
            bitmask = emiP->MapEntryArray[i].Value;
            if (bitmask & val) {
                ObjAppendElement(NULL, objP, ObjFromWinChars((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
                val &= ~ bitmask;
            }
        }
        return objP;

    case EVENTMAP_INFO_FLAG_WBEM_BITMAP:
        objP = ObjNewList(0, NULL);
        for (i = 0; val != 0 && i < emiP->EntryCount; ++i) {
            if (emiP->MapEntryArray[i].Value > 31)
                continue;
            /* Value field is the bit position to check */
            bitmask = (1 << emiP->MapEntryArray[i].Value);
            if (bitmask & val) {
                ObjAppendElement(NULL, objP, ObjFromWinChars((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
                /* Reset the bit both for efficiency as well as so we only
                   include one element even in the MapEntryArray[] contains
                   duplicate values */
                val &= ~bitmask;
            }
        }
        return objP;

    case EVENTMAP_INFO_FLAG_WBEM_BITMAP | EVENTMAP_INFO_FLAG_WBEM_NO_MAP:
        objP = ObjNewList(0, NULL);
        for (i = 0; val != 0 && i < emiP->EntryCount && i < 32; ++i) {
            bitmask = (1 << i);
            if (val & bitmask) {
                ObjAppendElement(NULL, objP, ObjFromWinChars((WCHAR *) (emiP->MapEntryArray[i].OutputOffset + (char*)emiP)));
                val &= ~bitmask;
            }
        }
        return objP;

    case EVENTMAP_INFO_FLAG_WBEM_VALUEMAP | EVENTMAP_INFO_FLAG_WBEM_FLAG | EVENTMAP_INFO_FLAG_WBEM_NO_MAP:
        break;

    default:
        break;
    }

    /* No map value for whatever reason, return as integer */
    return ObjFromDWORD(val);
}


/* Given the raw bytes for a TDH property, return the Tcl_Obj */
static TCL_RESULT TwapiTdhPropertyValue(
    TwapiInterpContext *ticP,
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
        double dbl;
        struct {
            void *s;
            ULONG   len;
        } string;
        GUID guid;
        SYSTEMTIME stime;
        char *bin;
    } u;
    FILETIME ftime;
    ULONG remain = prop_size;
    DWORD dw;
    Tcl_Interp *interp = ticP->interp;









|







1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
        double dbl;
        struct {
            void *s;
            ULONG   len;
        } string;
        GUID guid;
        SYSTEMTIME stime;
        BYTE *bin;
    } u;
    FILETIME ftime;
    ULONG remain = prop_size;
    DWORD dw;
    Tcl_Interp *interp = ticP->interp;


1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
        else
            goto size_error;
        return TCL_OK;

    case TDH_INTYPE_HEXDUMP:
        EXTRACT(dw, DWORD);
        remain -= sizeof(DWORD);
        *valueObjP = ObjFromByteArray(sizeof(DWORD)+(char*)bytesP,
                                      remain < dw ? remain : dw);
        return TCL_OK;

    case TDH_INTYPE_WBEMSID:
        /* TOKEN_USER structure followed by SID. Sizeof TOKEN_USER
           depends on 32/64 bittedness of event stream. */
        if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_32_BIT_HEADER)







|







1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
        else
            goto size_error;
        return TCL_OK;

    case TDH_INTYPE_HEXDUMP:
        EXTRACT(dw, DWORD);
        remain -= sizeof(DWORD);
        *valueObjP = ObjFromByteArray(sizeof(DWORD)+(BYTE*)bytesP,
                                      remain < dw ? remain : dw);
        return TCL_OK;

    case TDH_INTYPE_WBEMSID:
        /* TOKEN_USER structure followed by SID. Sizeof TOKEN_USER
           depends on 32/64 bittedness of event stream. */
        if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_32_BIT_HEADER)
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592

    case TDH_INTYPE_UNICODESTRING:
    case TDH_INTYPE_COUNTEDSTRING:
    case TDH_INTYPE_REVERSEDCOUNTEDSTRING:
    case TDH_INTYPE_NONNULLTERMINATEDSTRING:
    case TDH_INTYPE_UNICODECHAR:
        if (u.string.len == -1) {
            *valueObjP = ObjFromUnicodeLimited((WCHAR*)u.string.s,
                                               remain/sizeof(WCHAR), NULL);
        } else {
            remain /= sizeof(WCHAR);
            if (remain < u.string.len)
                u.string.len = remain;
            *valueObjP = ObjFromUnicodeN((WCHAR*)u.string.s, u.string.len);
        }
        break;

    case TDH_INTYPE_ANSISTRING:
    case TDH_INTYPE_COUNTEDANSISTRING:
    case TDH_INTYPE_REVERSEDCOUNTEDANSISTRING:
    case TDH_INTYPE_ANSICHAR:







|





|







1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597

    case TDH_INTYPE_UNICODESTRING:
    case TDH_INTYPE_COUNTEDSTRING:
    case TDH_INTYPE_REVERSEDCOUNTEDSTRING:
    case TDH_INTYPE_NONNULLTERMINATEDSTRING:
    case TDH_INTYPE_UNICODECHAR:
        if (u.string.len == -1) {
            *valueObjP = ObjFromWinCharsLimited((WCHAR*)u.string.s,
                                               remain/sizeof(WCHAR), NULL);
        } else {
            remain /= sizeof(WCHAR);
            if (remain < u.string.len)
                u.string.len = remain;
            *valueObjP = ObjFromWinCharsN((WCHAR*)u.string.s, u.string.len);
        }
        break;

    case TDH_INTYPE_ANSISTRING:
    case TDH_INTYPE_COUNTEDANSISTRING:
    case TDH_INTYPE_REVERSEDCOUNTEDANSISTRING:
    case TDH_INTYPE_ANSICHAR:
1708
1709
1710
1711
1712
1713
1714

1715
1716
1717
1718
1719
1720
1721
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_DATA, "NameOffset field is 0 for property in event record.");
    }

    tdhctx.ParameterValue = TwapiCalcPointerSize(evrP);
    tdhctx.ParameterType = TDH_CONTEXT_POINTERSIZE;
    tdhctx.ParameterSize = 0;   /* Reserved value */


    res = TwapiTdhPropertyArraySize(ticP, evrP, teiP, prop_index, &nvalues);
    if (res != TCL_OK)
        return res;
    
    prop_name = (ULONGLONG)(epiP->NameOffset + (char*) teiP);

    /* Special case arrays of UNICHAR and ANSICHAR. These are actually strings*/







>







1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_DATA, "NameOffset field is 0 for property in event record.");
    }

    tdhctx.ParameterValue = TwapiCalcPointerSize(evrP);
    tdhctx.ParameterType = TDH_CONTEXT_POINTERSIZE;
    tdhctx.ParameterSize = 0;   /* Reserved value */

    nvalues = 0;
    res = TwapiTdhPropertyArraySize(ticP, evrP, teiP, prop_index, &nvalues);
    if (res != TCL_OK)
        return res;
    
    prop_name = (ULONGLONG)(epiP->NameOffset + (char*) teiP);

    /* Special case arrays of UNICHAR and ANSICHAR. These are actually strings*/
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
        winerr = TdhGetPropertySize(evrP, 1, &tdhctx, 1, pdd, &prop_size);
        if (winerr == ERROR_SUCCESS) {
            /* Do we need to check for presence of map info here ? */
            pv = MemLifoPushFrame(memlifoP, prop_size, NULL);
            winerr = TdhGetProperty(evrP, 1, &tdhctx, 1, pdd, prop_size, pv);
            if (winerr == ERROR_SUCCESS) {
                *propvalObjP  = ObjNewList(1, NULL);
                *propnameObjP = ObjFromUnicode((WCHAR *)(epiP->NameOffset + (char*)teiP));
                if (epiP->nonStructType.InType == TDH_INTYPE_UNICODECHAR)
                    ObjAppendElement(NULL, *propvalObjP,
                                     ObjFromUnicodeLimited(pv, prop_size/sizeof(WCHAR), NULL));
                else
                    ObjAppendElement(NULL, *propvalObjP,
                                     ObjFromStringLimited(pv, prop_size, NULL));
            }
            MemLifoPopFrame(memlifoP);
        }
        return winerr == ERROR_SUCCESS ? TCL_OK : Twapi_AppendSystemError(interp, winerr);







|


|







1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
        winerr = TdhGetPropertySize(evrP, 1, &tdhctx, 1, pdd, &prop_size);
        if (winerr == ERROR_SUCCESS) {
            /* Do we need to check for presence of map info here ? */
            pv = MemLifoPushFrame(memlifoP, prop_size, NULL);
            winerr = TdhGetProperty(evrP, 1, &tdhctx, 1, pdd, prop_size, pv);
            if (winerr == ERROR_SUCCESS) {
                *propvalObjP  = ObjNewList(1, NULL);
                *propnameObjP = ObjFromWinChars((WCHAR *)(epiP->NameOffset + (char*)teiP));
                if (epiP->nonStructType.InType == TDH_INTYPE_UNICODECHAR)
                    ObjAppendElement(NULL, *propvalObjP,
                                     ObjFromWinCharsLimited(pv, prop_size/sizeof(WCHAR), NULL));
                else
                    ObjAppendElement(NULL, *propvalObjP,
                                     ObjFromStringLimited(pv, prop_size, NULL));
            }
            MemLifoPopFrame(memlifoP);
        }
        return winerr == ERROR_SUCCESS ? TCL_OK : Twapi_AppendSystemError(interp, winerr);
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
            /* Property is a struct */
            USHORT member_index     = epiP->structType.StructStartIndex;
            ULONG member_index_bound = member_index + epiP->structType.NumOfStructMembers;
            valueObj = ObjNewList(2 * epiP->structType.NumOfStructMembers, NULL);
            if (member_index_bound > teiP->TopLevelPropertyCount) {
                res = TwapiReturnErrorEx(interp,
                                         TWAPI_INVALID_DATA,
                                         Tcl_ObjPrintf("Property index %d out of bounds.", member_index_bound));
            } else {
                while (member_index < member_index_bound) {
                    Tcl_Obj *membernameObj, *membervalObj;
                    res = TwapiDecodeEVENT_PROPERTY_INFO(ticP, evrP, teiP, member_index, (LPWSTR)(epiP->NameOffset + (char *) teiP), array_index, &membernameObj, &membervalObj);
                    if (res != TCL_OK)
                        break;
                    ObjAppendElement(NULL, valueObj, membernameObj);







|







1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
            /* Property is a struct */
            USHORT member_index     = epiP->structType.StructStartIndex;
            ULONG member_index_bound = member_index + epiP->structType.NumOfStructMembers;
            valueObj = ObjNewList(2 * epiP->structType.NumOfStructMembers, NULL);
            if (member_index_bound > teiP->TopLevelPropertyCount) {
                res = TwapiReturnErrorEx(interp,
                                         TWAPI_INVALID_DATA,
                                         Tcl_ObjPrintf("Property index %lu out of bounds.", member_index_bound));
            } else {
                while (member_index < member_index_bound) {
                    Tcl_Obj *membernameObj, *membervalObj;
                    res = TwapiDecodeEVENT_PROPERTY_INFO(ticP, evrP, teiP, member_index, (LPWSTR)(epiP->NameOffset + (char *) teiP), array_index, &membernameObj, &membervalObj);
                    if (res != TCL_OK)
                        break;
                    ObjAppendElement(NULL, valueObj, membernameObj);
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
            /* TBD - see GetPropertyLength in SDK doc article
               "Using TdhFormatProperty to Consume Event Data". More involved
               than just calling TdhGetPropertySize. Do we need to copy
               that code ? */
            winerr = TdhGetPropertySize(evrP, 1, &tdhctx, pdd_count, pdd, &prop_size);
            if (winerr == ERROR_SUCCESS) {
                ULONG map_size;
                EVENT_MAP_INFO *mapP;

                /* Since we might be looping, alloc and release memory in 
                   every iteration.
                   Not necessary for correctness since caller will pop memlifo
                   frame anyway so in error case, we don't bother to pop
                   the frame */
                pv = MemLifoPushFrame(memlifoP, prop_size, NULL);







|







1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
            /* TBD - see GetPropertyLength in SDK doc article
               "Using TdhFormatProperty to Consume Event Data". More involved
               than just calling TdhGetPropertySize. Do we need to copy
               that code ? */
            winerr = TdhGetPropertySize(evrP, 1, &tdhctx, pdd_count, pdd, &prop_size);
            if (winerr == ERROR_SUCCESS) {
                ULONG map_size;
                EVENT_MAP_INFO *mapP = NULL;

                /* Since we might be looping, alloc and release memory in 
                   every iteration.
                   Not necessary for correctness since caller will pop memlifo
                   frame anyway so in error case, we don't bother to pop
                   the frame */
                pv = MemLifoPushFrame(memlifoP, prop_size, NULL);
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
            ObjDecrArrayRefs(array_index, valueObjs);
            return res;
        }
        valueObjs[array_index] = valueObj;
    }

    *propvalObjP  = ObjNewList(nvalues, valueObjs);
    *propnameObjP = ObjFromUnicode((WCHAR *)(epiP->NameOffset + (char*)teiP));
    return TCL_OK;
}


/* Uses memlifo frame. Caller responsible for cleanup */
static TCL_RESULT TwapiTdhGetEventInformation(TwapiInterpContext *ticP, EVENT_RECORD *evrP, Tcl_Obj **teiObjP)
{







|







1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
            ObjDecrArrayRefs(array_index, valueObjs);
            return res;
        }
        valueObjs[array_index] = valueObj;
    }

    *propvalObjP  = ObjNewList(nvalues, valueObjs);
    *propnameObjP = ObjFromWinChars((WCHAR *)(epiP->NameOffset + (char*)teiP));
    return TCL_OK;
}


/* Uses memlifo frame. Caller responsible for cleanup */
static TCL_RESULT TwapiTdhGetEventInformation(TwapiInterpContext *ticP, EVENT_RECORD *evrP, Tcl_Obj **teiObjP)
{
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
    case DecodingSourceWbem:    classic = 1; break;
    default:
        return TwapiReturnErrorEx(ticP->interp, TWAPI_UNSUPPORTED_TYPE,
                                  Tcl_ObjPrintf("Unsupported ETW decoding source (%d)", teiP->DecodingSource));
    }


#define OFFSET_TO_OBJ(field_) (teiP->field_ ? ObjFromUnicodeNoTrailingSpace((LPWSTR)(teiP->field_ + (char*)teiP)) : emptyObj)

    /* Provider GUID and EventDescriptor are already returned as part
       of EVENT_HEADER. We prefer to do it there so that we can return
       partial info even when the TdhGetEventInformation call fails
       due to the MOF not having been registered
    */

    //objs[] = ObjFromGUID(&teiP->ProviderGuid);
    objs[0] = classic ? ObjFromGUID(&teiP->EventGuid) : emptyObj;
    //objs[] = ObjFromEVENT_DESCRIPTOR(&teiP->EventDescriptor);
    objs[1] = ObjFromLong(teiP->DecodingSource);
    objs[2] = OFFSET_TO_OBJ(ProviderNameOffset);
    objs[3] = TwapiTEIUnicodeObj(teiP, teiP->LevelNameOffset, edP->Level);
    objs[4] = TwapiTEIUnicodeObj(teiP, teiP->ChannelNameOffset, edP->Channel);
    if (teiP->KeywordsNameOffset)
        objs[5] = ObjFromMultiSz((LPWSTR) (teiP->KeywordsNameOffset + (char*)teiP), -1);
    else
        objs[5] = emptyObj;
    objs[6] = TwapiTEIUnicodeObj(teiP, teiP->TaskNameOffset, edP->Task);
    objs[7] = TwapiTEIUnicodeObj(teiP, teiP->OpcodeNameOffset, edP->Opcode);
    objs[8] = OFFSET_TO_OBJ(EventMessageOffset);
    objs[9] = OFFSET_TO_OBJ(ProviderMessageOffset);
    if (classic) {
        objs[10] = OFFSET_TO_OBJ(ActivityIDNameOffset);
        objs[11] = OFFSET_TO_OBJ(RelatedActivityIDNameOffset);
    } else {
        objs[10] = emptyObj;
        objs[11] = emptyObj;
    }

    objs[12] = ObjNewList(2 * teiP->TopLevelPropertyCount, NULL);
    if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_STRING_ONLY) {
        ObjAppendElement(NULL, objs[12], STRING_LITERAL_OBJ("_stringdata"));
        ObjAppendElement(NULL, objs[12],
                         ObjFromUnicodeLimited(evrP->UserData,
                                               evrP->UserDataLength/sizeof(WCHAR), NULL));
    } else {
        USHORT i;

        for (i = 0; i < teiP->TopLevelPropertyCount; ++i) {
            Tcl_Obj *propnameObj, *propvalObj;
            status = TwapiDecodeEVENT_PROPERTY_INFO(ticP, evrP, teiP, i, NULL, 0, &propnameObj, &propvalObj);







|












|
|




|
|














|







1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
    case DecodingSourceWbem:    classic = 1; break;
    default:
        return TwapiReturnErrorEx(ticP->interp, TWAPI_UNSUPPORTED_TYPE,
                                  Tcl_ObjPrintf("Unsupported ETW decoding source (%d)", teiP->DecodingSource));
    }


#define OFFSET_TO_OBJ(field_) (teiP->field_ ? ObjFromWinCharsNoTrailingSpace((LPWSTR)(teiP->field_ + (char*)teiP)) : emptyObj)

    /* Provider GUID and EventDescriptor are already returned as part
       of EVENT_HEADER. We prefer to do it there so that we can return
       partial info even when the TdhGetEventInformation call fails
       due to the MOF not having been registered
    */

    //objs[] = ObjFromGUID(&teiP->ProviderGuid);
    objs[0] = classic ? ObjFromGUID(&teiP->EventGuid) : emptyObj;
    //objs[] = ObjFromEVENT_DESCRIPTOR(&teiP->EventDescriptor);
    objs[1] = ObjFromLong(teiP->DecodingSource);
    objs[2] = OFFSET_TO_OBJ(ProviderNameOffset);
    objs[3] = TwapiTEIWinCharsObj(teiP, teiP->LevelNameOffset, edP->Level);
    objs[4] = TwapiTEIWinCharsObj(teiP, teiP->ChannelNameOffset, edP->Channel);
    if (teiP->KeywordsNameOffset)
        objs[5] = ObjFromMultiSz((LPWSTR) (teiP->KeywordsNameOffset + (char*)teiP), -1);
    else
        objs[5] = emptyObj;
    objs[6] = TwapiTEIWinCharsObj(teiP, teiP->TaskNameOffset, edP->Task);
    objs[7] = TwapiTEIWinCharsObj(teiP, teiP->OpcodeNameOffset, edP->Opcode);
    objs[8] = OFFSET_TO_OBJ(EventMessageOffset);
    objs[9] = OFFSET_TO_OBJ(ProviderMessageOffset);
    if (classic) {
        objs[10] = OFFSET_TO_OBJ(ActivityIDNameOffset);
        objs[11] = OFFSET_TO_OBJ(RelatedActivityIDNameOffset);
    } else {
        objs[10] = emptyObj;
        objs[11] = emptyObj;
    }

    objs[12] = ObjNewList(2 * teiP->TopLevelPropertyCount, NULL);
    if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_STRING_ONLY) {
        ObjAppendElement(NULL, objs[12], STRING_LITERAL_OBJ("_stringdata"));
        ObjAppendElement(NULL, objs[12],
                         ObjFromWinCharsLimited(evrP->UserData,
                                               evrP->UserDataLength/sizeof(WCHAR), NULL));
    } else {
        USHORT i;

        for (i = 0; i < teiP->TopLevelPropertyCount; ++i) {
            Tcl_Obj *propnameObj, *propvalObj;
            status = TwapiDecodeEVENT_PROPERTY_INFO(ticP, evrP, teiP, i, NULL, 0, &propnameObj, &propvalObj);
1996
1997
1998
1999
2000
2001
2002



2003
2004
2005
2006
2007
2008
2009
2010
    mark = MemLifoPushMark(ticP->memlifoP);

    recObjs[0] = ObjFromEVENT_HEADER(&evrP->EventHeader);

    /* Buffer Context */
    if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_PROCESSOR_INDEX) {
        /* Win 8 defines as a USHORT (field ProcessorIndex in new sdk) */



        objs[0] = ObjFromLong(*(USHORT *)&evrP->BufferContext.ProcessorNumber);
    } else {
        objs[0] = ObjFromLong(evrP->BufferContext.ProcessorNumber);
    }
    objs[1] = ObjFromLong(evrP->BufferContext.LoggerId);
    recObjs[1] = ObjNewList(2, objs);
    
    /* Extended Data */







>
>
>
|







2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
    mark = MemLifoPushMark(ticP->memlifoP);

    recObjs[0] = ObjFromEVENT_HEADER(&evrP->EventHeader);

    /* Buffer Context */
    if (evrP->EventHeader.Flags & EVENT_HEADER_FLAG_PROCESSOR_INDEX) {
        /* Win 8 defines as a USHORT (field ProcessorIndex in new sdk) */
        USHORT u16;
        u16 = evrP->BufferContext.ProcessorNumber +
            (evrP->BufferContext.Alignment << 8);
        objs[0] = ObjFromLong(u16);
    } else {
        objs[0] = ObjFromLong(evrP->BufferContext.ProcessorNumber);
    }
    objs[1] = ObjFromLong(evrP->BufferContext.LoggerId);
    recObjs[1] = ObjNewList(2, objs);
    
    /* Extended Data */
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
}


ULONG WINAPI TwapiETWBufferCallback(
  PEVENT_TRACE_LOGFILEW etlP
)
{
    Tcl_Obj *evalObj;
    Tcl_Obj *bufObj;
    Tcl_Obj *args[2];
    Tcl_Interp *interp;
    int code;
    Tcl_Obj *objs[8];

    /* Called back from Win32 ProcessTrace call. Assumed that gETWContext is locked */
    TWAPI_ASSERT(gETWContext.ticP != NULL);
    TWAPI_ASSERT(gETWContext.ticP->interp != NULL);
    interp = gETWContext.ticP->interp;

    if (Tcl_InterpDeleted(interp))
        return FALSE;

    if (gETWContext.status != TCL_OK) /* If some previous error occurred, return */
        return FALSE;

    ObjToUnicodeCleanup();

    TWAPI_ASSERT(gETWContext.eventsObj);

    if (gETWContext.buffer_cmdlen == 0) {
        /* We are simply collecting events without invoking callback */
        TWAPI_ASSERT(gETWContext.buffer.listObj != NULL);
    } else {
        /*
         * Construct a command to call with the event. 
         * gETWContext.buffer_cmdObj could be a shared object, either
         * initially itself or result in a shared object in the callback.
         * So we need to check for that and Dup it if necessary
         */

        if (Tcl_IsShared(gETWContext.buffer.cmdObj)) {
            evalObj = ObjDuplicate(gETWContext.buffer.cmdObj);
            ObjIncrRefs(evalObj);
        } else
            evalObj = gETWContext.buffer.cmdObj;
    }

    objs[0] = etlP->LogFileName ? ObjFromUnicode(etlP->LogFileName) : ObjFromEmptyString();
    objs[1] = etlP->LoggerName ? ObjFromUnicode(etlP->LoggerName) : ObjFromEmptyString();
    objs[2] = ObjFromULONGLONG(etlP->CurrentTime);
    objs[3] = ObjFromLong(etlP->BuffersRead);
    //  ObjFromLong(etlP->LogFileMode) - docs say do not use
    objs[4] = ObjFromTRACE_LOGFILE_HEADER(&etlP->LogfileHeader);
    objs[5] = ObjFromLong(etlP->BufferSize);
    objs[6] = ObjFromLong(etlP->Filled);
    // Docs say unused -  ObjFromLong(etlP->EventsLost));







|

















<
<




















|
|







2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086


2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
}


ULONG WINAPI TwapiETWBufferCallback(
  PEVENT_TRACE_LOGFILEW etlP
)
{
    Tcl_Obj *evalObj = NULL;
    Tcl_Obj *bufObj;
    Tcl_Obj *args[2];
    Tcl_Interp *interp;
    int code;
    Tcl_Obj *objs[8];

    /* Called back from Win32 ProcessTrace call. Assumed that gETWContext is locked */
    TWAPI_ASSERT(gETWContext.ticP != NULL);
    TWAPI_ASSERT(gETWContext.ticP->interp != NULL);
    interp = gETWContext.ticP->interp;

    if (Tcl_InterpDeleted(interp))
        return FALSE;

    if (gETWContext.status != TCL_OK) /* If some previous error occurred, return */
        return FALSE;



    TWAPI_ASSERT(gETWContext.eventsObj);

    if (gETWContext.buffer_cmdlen == 0) {
        /* We are simply collecting events without invoking callback */
        TWAPI_ASSERT(gETWContext.buffer.listObj != NULL);
    } else {
        /*
         * Construct a command to call with the event. 
         * gETWContext.buffer_cmdObj could be a shared object, either
         * initially itself or result in a shared object in the callback.
         * So we need to check for that and Dup it if necessary
         */

        if (Tcl_IsShared(gETWContext.buffer.cmdObj)) {
            evalObj = ObjDuplicate(gETWContext.buffer.cmdObj);
            ObjIncrRefs(evalObj);
        } else
            evalObj = gETWContext.buffer.cmdObj;
    }

    objs[0] = etlP->LogFileName ? ObjFromWinChars(etlP->LogFileName) : ObjFromEmptyString();
    objs[1] = etlP->LoggerName ? ObjFromWinChars(etlP->LoggerName) : ObjFromEmptyString();
    objs[2] = ObjFromULONGLONG(etlP->CurrentTime);
    objs[3] = ObjFromLong(etlP->BuffersRead);
    //  ObjFromLong(etlP->LogFileMode) - docs say do not use
    objs[4] = ObjFromTRACE_LOGFILE_HEADER(&etlP->LogfileHeader);
    objs[5] = ObjFromLong(etlP->BufferSize);
    objs[6] = ObjFromLong(etlP->Filled);
    // Docs say unused -  ObjFromLong(etlP->EventsLost));
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
    MemLifo *memlifoP = ticP->memlifoP;
    PROVIDER_ENUMERATION_INFO *peiP;
    DWORD buf_sz;
    DWORD status;
    TCL_RESULT res;
    DWORD i;

    ObjToUnicodeCleanup();

    CHECK_NARGS_RANGE(interp, objc, 1, 2);

    if (gTdhStatus <= 0)
        return Twapi_AppendSystemError(interp, ERROR_PROC_NOT_FOUND);

    /* Windows 7/8 have a LOT of providers */
    buf_sz =  TwapiMinOSVersion(6, 2) ? 100000 : 30000;







<
<







2160
2161
2162
2163
2164
2165
2166


2167
2168
2169
2170
2171
2172
2173
    MemLifo *memlifoP = ticP->memlifoP;
    PROVIDER_ENUMERATION_INFO *peiP;
    DWORD buf_sz;
    DWORD status;
    TCL_RESULT res;
    DWORD i;



    CHECK_NARGS_RANGE(interp, objc, 1, 2);

    if (gTdhStatus <= 0)
        return Twapi_AppendSystemError(interp, ERROR_PROC_NOT_FOUND);

    /* Windows 7/8 have a LOT of providers */
    buf_sz =  TwapiMinOSVersion(6, 2) ? 100000 : 30000;
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
        if (objc == 1) {
            /* Return all */
            Tcl_Obj **objPP = MemLifoAlloc(memlifoP, peiP->NumberOfProviders * sizeof(*objPP), NULL);
            while (i--) {
                TRACE_PROVIDER_INFO *tpiP = &peiP->TraceProviderInfoArray[i];
                objs[0] = ObjFromGUID(&tpiP->ProviderGuid);
                objs[1] = ObjFromLong(tpiP->SchemaSource);
                objs[2] = ObjFromUnicode(ADDPTR(peiP, tpiP->ProviderNameOffset, WCHAR *));
                objPP[i] = ObjNewList(3, objs);
            }
            ObjSetResult(interp, ObjNewList(peiP->NumberOfProviders, objPP));
        } else {
            /* Return matching one. Empty string if not found */
            WCHAR *s = ObjToUnicode(objv[1]);
            while (i--) {
                TRACE_PROVIDER_INFO *tpiP = &peiP->TraceProviderInfoArray[i];
                WCHAR *s2 = ADDPTR(peiP, tpiP->ProviderNameOffset, WCHAR *);
                if (lstrcmpiW(s, s2) == 0) {
                    objs[0] = ObjFromGUID(&tpiP->ProviderGuid);
                    objs[1] = ObjFromLong(tpiP->SchemaSource);
                    objs[2] = ObjFromUnicode(s2);
                    ObjSetResult(interp, ObjNewList(3, objs));
                    break;
                }
            }            
        }
        res = TCL_OK;
    } else







|





|






|







2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
        if (objc == 1) {
            /* Return all */
            Tcl_Obj **objPP = MemLifoAlloc(memlifoP, peiP->NumberOfProviders * sizeof(*objPP), NULL);
            while (i--) {
                TRACE_PROVIDER_INFO *tpiP = &peiP->TraceProviderInfoArray[i];
                objs[0] = ObjFromGUID(&tpiP->ProviderGuid);
                objs[1] = ObjFromLong(tpiP->SchemaSource);
                objs[2] = ObjFromWinChars(ADDPTR(peiP, tpiP->ProviderNameOffset, WCHAR *));
                objPP[i] = ObjNewList(3, objs);
            }
            ObjSetResult(interp, ObjNewList(peiP->NumberOfProviders, objPP));
        } else {
            /* Return matching one. Empty string if not found */
            WCHAR *s = ObjToWinChars(objv[1]);
            while (i--) {
                TRACE_PROVIDER_INFO *tpiP = &peiP->TraceProviderInfoArray[i];
                WCHAR *s2 = ADDPTR(peiP, tpiP->ProviderNameOffset, WCHAR *);
                if (lstrcmpiW(s, s2) == 0) {
                    objs[0] = ObjFromGUID(&tpiP->ProviderGuid);
                    objs[1] = ObjFromLong(tpiP->SchemaSource);
                    objs[2] = ObjFromWinChars(s2);
                    ObjSetResult(interp, ObjNewList(3, objs));
                    break;
                }
            }            
        }
        res = TCL_OK;
    } else
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
    WCHAR *s;

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     ARGSKIP, GETINT(real_time),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    ObjToUnicodeCleanup();

    s = ObjToUnicode(objv[1]);
    ZeroMemory(&etl, sizeof(etl));
    etl.BufferCallback = TwapiETWBufferCallback;
    /*
     * To support older compilers/SDK's, we use
     *   EventCallback instead of EventRecordCallback
     *   LogFileMode instead of ProcessTraceMode
     *   EVENT_TRACE_REAL_TIME_MODE instead of PROCESS_TRACE_MODE_REAL_TIME







<
<
|







2227
2228
2229
2230
2231
2232
2233


2234
2235
2236
2237
2238
2239
2240
2241
    WCHAR *s;

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     ARGSKIP, GETINT(real_time),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;



    s = ObjToWinChars(objv[1]);
    ZeroMemory(&etl, sizeof(etl));
    etl.BufferCallback = TwapiETWBufferCallback;
    /*
     * To support older compilers/SDK's, we use
     *   EventCallback instead of EventRecordCallback
     *   LogFileMode instead of ProcessTraceMode
     *   EVENT_TRACE_REAL_TIME_MODE instead of PROCESS_TRACE_MODE_REAL_TIME
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
    EVENT_TRACE_PROPERTIES **sessPP;
    EVENT_TRACE_PROPERTIES *bufP;
    DWORD i, count, struct_size, buf_size, status;
    Tcl_Obj **objPP;
    MemLifo *memlifoP = ticP->memlifoP;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    CHECK_NARGS(interp, objc, 1);

    sessPP = MemLifoPushFrame(memlifoP, MAX_SESSIONS * sizeof(*sessPP), NULL);
    struct_size = sizeof(EVENT_TRACE_PROPERTIES)  +
        (MAX_TRACE_NAME_CHARS*sizeof(WCHAR)) + /* Space for session name */
        (MAX_TRACE_NAME_CHARS*sizeof(WCHAR));  /* Space for file name */
    buf_size = MAX_SESSIONS * struct_size;







<
<







2269
2270
2271
2272
2273
2274
2275


2276
2277
2278
2279
2280
2281
2282
    EVENT_TRACE_PROPERTIES **sessPP;
    EVENT_TRACE_PROPERTIES *bufP;
    DWORD i, count, struct_size, buf_size, status;
    Tcl_Obj **objPP;
    MemLifo *memlifoP = ticP->memlifoP;
    TCL_RESULT res;



    CHECK_NARGS(interp, objc, 1);

    sessPP = MemLifoPushFrame(memlifoP, MAX_SESSIONS * sizeof(*sessPP), NULL);
    struct_size = sizeof(EVENT_TRACE_PROPERTIES)  +
        (MAX_TRACE_NAME_CHARS*sizeof(WCHAR)) + /* Space for session name */
        (MAX_TRACE_NAME_CHARS*sizeof(WCHAR));  /* Space for file name */
    buf_size = MAX_SESSIONS * struct_size;
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (ObjToTRACEHANDLE(interp, objv[1], &htrace) != TCL_OK)
        return TCL_ERROR;

    ObjToUnicodeCleanup();

    err = CloseTrace(htrace);
    if (err == ERROR_SUCCESS)
        return TCL_OK;
    else
        return Twapi_AppendSystemError(interp, err);
}


TCL_RESULT Twapi_ProcessTrace(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext *) clientData;
    int i;
    FILETIME start, end, *startP, *endP;
    struct TwapiETWContext etwc;
    int buffer_cmdlen;
    DWORD winerr;
    Tcl_Obj **htraceObjs;
    TRACEHANDLE htraces[8];
    int       ntraces;

    if (objc != 5)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (ObjGetElements(interp, objv[1], &ntraces, &htraceObjs) != TCL_OK)
        return TCL_ERROR;

    ObjToUnicodeCleanup();

    for (i = 0; i < ntraces; ++i) {
        if (ObjToTRACEHANDLE(interp, htraceObjs[i], &htraces[i]) != TCL_OK)
            return TCL_ERROR;
    }

    /* Verify callback command prefix is a list. If empty, data
     * is returned instead.







<
<








|

|















<
<







2313
2314
2315
2316
2317
2318
2319


2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345


2346
2347
2348
2349
2350
2351
2352

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (ObjToTRACEHANDLE(interp, objv[1], &htrace) != TCL_OK)
        return TCL_ERROR;



    err = CloseTrace(htrace);
    if (err == ERROR_SUCCESS)
        return TCL_OK;
    else
        return Twapi_AppendSystemError(interp, err);
}


TCL_RESULT Twapi_ProcessTrace(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int i;
    FILETIME start, end, *startP, *endP;
    struct TwapiETWContext etwc;
    int buffer_cmdlen;
    DWORD winerr;
    Tcl_Obj **htraceObjs;
    TRACEHANDLE htraces[8];
    int       ntraces;

    if (objc != 5)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (ObjGetElements(interp, objv[1], &ntraces, &htraceObjs) != TCL_OK)
        return TCL_ERROR;



    for (i = 0; i < ntraces; ++i) {
        if (ObjToTRACEHANDLE(interp, htraceObjs[i], &htraces[i]) != TCL_OK)
            return TCL_ERROR;
    }

    /* Verify callback command prefix is a list. If empty, data
     * is returned instead.
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
        Tcl_ResetResult(interp); /* For any holdover from callbacks */

    return TCL_OK;
}

TCL_RESULT Twapi_ParseEventMofData(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    int       i;
    ULONG eaten;
    Tcl_Obj **types;            /* Field types */
    int       ntypes;           /* Number of fields/types */
    char     *bytesP;
    int       nbytes;
    ULONG     remain;
    Tcl_Obj  *resultObj = NULL;
    WCHAR     wc;
    GUID      guid;
    int       pointer_size;     /* Of target system, NOT us */
    long      lpointer_size;
    union {
        SID sid;                /* For alignment */
        char buf[SECURITY_MAX_SID_SIZE];
    } u;
    short     port;

    /* TBD - objv[1] and other objv[] may be samve and shimmer.
       Fix by using TwapiGetArgsEx
    */
    if (objc != 4)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    
    ObjToUnicodeCleanup();

    bytesP = ObjToByteArray(objv[1], &nbytes);

    /* The field descriptor is a list of alternating field types and names */
    if (ObjGetElements(interp, objv[2], &ntypes, &types) != TCL_OK ||
        ObjToLong(interp, objv[3], &lpointer_size) != TCL_OK)
        return TCL_ERROR;
    pointer_size = lpointer_size;
    if (ntypes & 1) {
        return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                           Tcl_ObjPrintf("Field descriptor argument has odd number of elements (%d).", ntypes));
    }

    if (pointer_size != 4 && pointer_size != 8) {
        return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,







|
<


|






<












<
<




|

|







2423
2424
2425
2426
2427
2428
2429
2430

2431
2432
2433
2434
2435
2436
2437
2438
2439

2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451


2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
        Tcl_ResetResult(interp); /* For any holdover from callbacks */

    return TCL_OK;
}

TCL_RESULT Twapi_ParseEventMofData(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    int       i, eaten;

    Tcl_Obj **types;            /* Field types */
    int       ntypes;           /* Number of fields/types */
    BYTE     *bytesP;
    int       nbytes;
    ULONG     remain;
    Tcl_Obj  *resultObj = NULL;
    WCHAR     wc;
    GUID      guid;
    int       pointer_size;     /* Of target system, NOT us */

    union {
        SID sid;                /* For alignment */
        char buf[SECURITY_MAX_SID_SIZE];
    } u;
    short     port;

    /* TBD - objv[1] and other objv[] may be samve and shimmer.
       Fix by using TwapiGetArgsEx
    */
    if (objc != 4)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    


    bytesP = ObjToByteArray(objv[1], &nbytes);

    /* The field descriptor is a list of alternating field types and names */
    if (ObjGetElements(interp, objv[2], &ntypes, &types) != TCL_OK ||
        ObjToInt(interp, objv[3], &pointer_size) != TCL_OK)
        return TCL_ERROR;
        
    if (ntypes & 1) {
        return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
                           Tcl_ObjPrintf("Field descriptor argument has odd number of elements (%d).", ntypes));
    }

    if (pointer_size != 4 && pointer_size != 8) {
        return TwapiReturnErrorEx(interp, TWAPI_INVALID_ARGS,
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
        }

        /* IMPORTANT: switch values based on _etw_decipher_mof_event_field_type proc */
        switch (typeenum) {
        case 1: // string / stringnullterminated
            /* We cannot rely on event being formatted correctly with a \0
               do not directly call Tcl_NewStringObj */
            objP = ObjFromStringLimited(bytesP, remain, &eaten);
            /* eaten is num remaining. Prime for loop iteration to
               be num used */
            eaten = remain - eaten;
            break;

        case 2: // wstring / wstringnullterminated
            /* Data may not be aligned ! Copy to align if necessary? TBD */
            /* We cannot rely on event being formatted correctly with a \0
               do not directly call Tcl_NewStringObj */
            objP = ObjFromUnicodeLimited((WCHAR *)bytesP, remain/sizeof(WCHAR), &eaten);
            /* eaten is num WCHARS remaining. Prime for loop iteration to
               be num used */
            eaten = remain - (sizeof(WCHAR)*eaten);
            break;

        case 3: // stringcounted
        case 4: // stringreversecounted
            if (remain < 2)
                goto done;      /* Data truncation */
            eaten = *(unsigned short UNALIGNED *)bytesP;
            if (typeenum == 4)  /* Need to swap bytes */
                eaten = ((eaten & 0xff) << 8) | (eaten >> 8);
            if (remain < (2+eaten)) {
                /* truncated */
                eaten = remain-2;
            }
            objP = ObjFromStringN(bytesP+2, eaten);
            eaten += 2;         /* include the length field */
            break;

        case 5: // wstringcounted
        case 6: // wstringreversecounted
            if (remain < 2)
                goto done;      /* Data truncation */







|









|
















|







2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
        }

        /* IMPORTANT: switch values based on _etw_decipher_mof_event_field_type proc */
        switch (typeenum) {
        case 1: // string / stringnullterminated
            /* We cannot rely on event being formatted correctly with a \0
               do not directly call Tcl_NewStringObj */
            objP = ObjFromStringLimited((char *)bytesP, remain, &eaten);
            /* eaten is num remaining. Prime for loop iteration to
               be num used */
            eaten = remain - eaten;
            break;

        case 2: // wstring / wstringnullterminated
            /* Data may not be aligned ! Copy to align if necessary? TBD */
            /* We cannot rely on event being formatted correctly with a \0
               do not directly call Tcl_NewStringObj */
            objP = ObjFromWinCharsLimited((WCHAR *)bytesP, remain/sizeof(WCHAR), &eaten);
            /* eaten is num WCHARS remaining. Prime for loop iteration to
               be num used */
            eaten = remain - (sizeof(WCHAR)*eaten);
            break;

        case 3: // stringcounted
        case 4: // stringreversecounted
            if (remain < 2)
                goto done;      /* Data truncation */
            eaten = *(unsigned short UNALIGNED *)bytesP;
            if (typeenum == 4)  /* Need to swap bytes */
                eaten = ((eaten & 0xff) << 8) | (eaten >> 8);
            if (remain < (2+eaten)) {
                /* truncated */
                eaten = remain-2;
            }
            objP = ObjFromStringN((char *)(bytesP+2), eaten);
            eaten += 2;         /* include the length field */
            break;

        case 5: // wstringcounted
        case 6: // wstringreversecounted
            if (remain < 2)
                goto done;      /* Data truncation */
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
               well know LogParser utility. On XP there does not seem
               to be a MoF that actually uses this so maybe it is moot.
               For now leave as is 
            */

            if ((remain-2) < (sizeof(WCHAR)*eaten)) {
                /* truncated */
                objP = ObjFromUnicodeN((WCHAR *)(bytesP+2), (remain-2)/sizeof(WCHAR));
                eaten = remain; /* We used up all */
            } else {
                objP = ObjFromUnicodeN((WCHAR *)(bytesP+2), eaten);
                eaten = (sizeof(WCHAR)*eaten) + 2; /* include length field */
            }
            break;

        case 7: // boolean
            if (remain < sizeof(int))
                goto done;      /* Data truncation */
            objP = ObjFromBoolean((*(int UNALIGNED *)bytesP) ? 1 : 0);
            eaten = sizeof(int);
            break;

        case 8: // sint8
        case 9: // uint8
            objP = ObjFromInt(typeenum == 8 ? *(signed char *)bytesP : *(unsigned char *)bytesP);
            eaten = sizeof(char);
            break;
            
        case 10: // csint8
        case 11: // cuint8
            /* Return as an ascii char */
            objP = ObjFromStringN(bytesP, 1);
            eaten = sizeof(char);
            break;

        case 12: // sint16
        case 13: // uint16
            if (remain < sizeof(short))
                goto done;      /* Data truncation */







|


|




















|







2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
               well know LogParser utility. On XP there does not seem
               to be a MoF that actually uses this so maybe it is moot.
               For now leave as is 
            */

            if ((remain-2) < (sizeof(WCHAR)*eaten)) {
                /* truncated */
                objP = ObjFromWinCharsN((WCHAR *)(bytesP+2), (remain-2)/sizeof(WCHAR));
                eaten = remain; /* We used up all */
            } else {
                objP = ObjFromWinCharsN((WCHAR *)(bytesP+2), eaten);
                eaten = (sizeof(WCHAR)*eaten) + 2; /* include length field */
            }
            break;

        case 7: // boolean
            if (remain < sizeof(int))
                goto done;      /* Data truncation */
            objP = ObjFromBoolean((*(int UNALIGNED *)bytesP) ? 1 : 0);
            eaten = sizeof(int);
            break;

        case 8: // sint8
        case 9: // uint8
            objP = ObjFromInt(typeenum == 8 ? *(signed char *)bytesP : *(unsigned char *)bytesP);
            eaten = sizeof(char);
            break;
            
        case 10: // csint8
        case 11: // cuint8
            /* Return as an ascii char */
            objP = ObjFromStringN((char *)bytesP, 1);
            eaten = sizeof(char);
            break;

        case 12: // sint16
        case 13: // uint16
            if (remain < sizeof(short))
                goto done;      /* Data truncation */
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
             */
            goto done;

        case 27: // char16
            if (remain < sizeof(WCHAR))
                goto done;      /* Data truncation */
            wc = *(WCHAR UNALIGNED *) bytesP;
            objP = ObjFromUnicodeN(&wc, 1);
            eaten = sizeof(WCHAR);
            break;

        case 28: // uint8guid
        case 29: // objectguid
            if (remain < sizeof(GUID))
                goto done;      /* Data truncation */







|







2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
             */
            goto done;

        case 27: // char16
            if (remain < sizeof(WCHAR))
                goto done;      /* Data truncation */
            wc = *(WCHAR UNALIGNED *) bytesP;
            objP = ObjFromWinCharsN(&wc, 1);
            eaten = sizeof(WCHAR);
            break;

        case 28: // uint8guid
        case 29: // objectguid
            if (remain < sizeof(GUID))
                goto done;      /* Data truncation */
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
            break;

        case 40: // datetime - TBD
            goto done;          /* TBD */
            break;
            
        case 41: // stringnotcounted
            objP = ObjFromStringN(bytesP, remain);
            eaten = remain;
            break;

        case 42: // wstringnotcounted
            objP = ObjFromUnicodeN((WCHAR *)bytesP, remain/sizeof(WCHAR));
            eaten = remain;
            break;

        case 43: // pointer
            if (pointer_size == 8)
                objP = ObjFromULONGLONGHex(*(ULONGLONG UNALIGNED *)bytesP);
            else







|




|







2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
            break;

        case 40: // datetime - TBD
            goto done;          /* TBD */
            break;
            
        case 41: // stringnotcounted
            objP = ObjFromStringN((char *) bytesP, remain);
            eaten = remain;
            break;

        case 42: // wstringnotcounted
            objP = ObjFromWinCharsN((WCHAR *)bytesP, remain/sizeof(WCHAR));
            eaten = remain;
            break;

        case 43: // pointer
            if (pointer_size == 8)
                objP = ObjFromULONGLONGHex(*(ULONGLONG UNALIGNED *)bytesP);
            else
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826


static int Twapi_ETWCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    objP = NULL;
    switch (func) {
    case 1: // etw_provider_enable_flags
        objP = ObjFromLong(gETWProviderTraceEnableFlags);
        break;
    case 2: // etw_provider_enable_level
        objP = ObjFromLong(gETWProviderTraceEnableLevel);







<
<







2804
2805
2806
2807
2808
2809
2810


2811
2812
2813
2814
2815
2816
2817


static int Twapi_ETWCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    Tcl_Obj *objP;
    int func = PtrToInt(clientdata);



    objP = NULL;
    switch (func) {
    case 1: // etw_provider_enable_flags
        objP = ObjFromLong(gETWProviderTraceEnableFlags);
        break;
    case 2: // etw_provider_enable_level
        objP = ObjFromLong(gETWProviderTraceEnableLevel);
2919
2920
2921
2922
2923
2924
2925
2926
2927

2928
2929
2930
2931
2932
2933
2934
    INIT_TDH_STUB(TdhEnumerateProviders);

#endif

    gTdhStatus = 1;
}

static int ETWModuleOneTimeInit(Tcl_Interp *interp)
{

    TwapiInitTdhStubs(interp);

    /* Depends on OS - see documentation of OpenTrace in SDK */
    if (sizeof(void*) == 8) {
        gInvalidTraceHandle = 0xFFFFFFFFFFFFFFFF;
    } else {
        /* 32-bit */







|

>







2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
    INIT_TDH_STUB(TdhEnumerateProviders);

#endif

    gTdhStatus = 1;
}

static int ETWModuleOneTimeInit(void *arg)
{
    Tcl_Interp *interp = arg;
    TwapiInitTdhStubs(interp);

    /* Depends on OS - see documentation of OpenTrace in SDK */
    if (sizeof(void*) == 8) {
        gInvalidTraceHandle = 0xFFFFFFFFFFFFFFFF;
    } else {
        /* 32-bit */
Changes to undroid/twapi/twapi/eventlog/eventlog.c.
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
                               sizeof(evlinfo), &bytesneeded)) {
        *fullP = evlinfo.dwFull;
        return TRUE;
    }
    return FALSE;
}

static int Twapi_ReadEventLogObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    HANDLE evlH;
    DWORD  flags;
    DWORD  offset;
    DWORD  buf_sz;
    char  *bufP;
    DWORD  num_read;
    int    i;
    EVENTLOGRECORD *evlP;
    Tcl_Obj *resultObj;
    DWORD winerr = ERROR_SUCCESS;
    static const char *fieldnames[] = {
        "-source", "-system", "-reserved", "-recordnum", "-timegenerated",
        "-timewritten", "-eventid", "-level", "-category", "-reservedflags",
        "-closingrecnum", "-params", "-sid", "-data" };

    Tcl_Obj *fields[ARRAYSIZE(fieldnames)];

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETHANDLE(evlH),
                     GETINT(flags), GETINT(offset), ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* Ask for 1000 bytes alloc, will get more if available. TBD - instrument */
    bufP = MemLifoPushFrame(ticP->memlifoP, 1000, &buf_sz);








|

>








|








<
<







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
                               sizeof(evlinfo), &bytesneeded)) {
        *fullP = evlinfo.dwFull;
        return TRUE;
    }
    return FALSE;
}

static int Twapi_ReadEventLogObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HANDLE evlH;
    DWORD  flags;
    DWORD  offset;
    DWORD  buf_sz;
    char  *bufP;
    DWORD  num_read;
    int    i;
    EVENTLOGRECORD *evlP;
    Tcl_Obj *resultObj = NULL;
    DWORD winerr = ERROR_SUCCESS;
    static const char *fieldnames[] = {
        "-source", "-system", "-reserved", "-recordnum", "-timegenerated",
        "-timewritten", "-eventid", "-level", "-category", "-reservedflags",
        "-closingrecnum", "-params", "-sid", "-data" };

    Tcl_Obj *fields[ARRAYSIZE(fieldnames)];



    if (TwapiGetArgs(interp, objc-1, objv+1, GETHANDLE(evlH),
                     GETINT(flags), GETINT(offset), ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* Ask for 1000 bytes alloc, will get more if available. TBD - instrument */
    bufP = MemLifoPushFrame(ticP->memlifoP, 1000, &buf_sz);

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
        PSID     sidP;
        int      strindex;
        WCHAR   *strP;
        int      len;

        strP = (WCHAR *) (1 + &(evlP->DataOffset));
        len = lstrlenW(strP);
        objv[0] = ObjFromUnicodeN(strP, len); /* Source name */
        strP += len + 1;
        objv[1] = ObjFromUnicode(strP); /* Computer name */
        objv[2] = ObjFromDWORD(evlP->Reserved);
        objv[3] = ObjFromDWORD(evlP->RecordNumber);
        objv[4] = ObjFromDWORD(evlP->TimeGenerated);
        objv[5] = ObjFromDWORD(evlP->TimeWritten);
        objv[6] = ObjFromDWORD(evlP->EventID);
        objv[7] = ObjFromInt(evlP->EventType);
        objv[8] = ObjFromInt(evlP->EventCategory);
        objv[9] = ObjFromInt(evlP->ReservedFlags);
        objv[10] = ObjFromDWORD(evlP->ClosingRecordNumber);

        /* Collect all the strings together into a list */
        objv[11] = ObjNewList(0, NULL);
        for (strP = (WCHAR *)(evlP->StringOffset + (char *)evlP), strindex = 0;
             strindex < evlP->NumStrings;
             ++strindex) {
            len = lstrlenW(strP);
            ObjAppendElement(interp, objv[11],
                                     ObjFromUnicodeN(strP, len));
            strP += len + 1;
        }

        /* Get the SID */
        sidP = (PSID) (evlP->UserSidOffset + (char *)evlP);
        if ((evlP->UserSidLength == 0) ||
            (ObjFromSID(interp, sidP, &objv[12]) != TCL_OK)) {







|

|

















|







96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        PSID     sidP;
        int      strindex;
        WCHAR   *strP;
        int      len;

        strP = (WCHAR *) (1 + &(evlP->DataOffset));
        len = lstrlenW(strP);
        objv[0] = ObjFromWinCharsN(strP, len); /* Source name */
        strP += len + 1;
        objv[1] = ObjFromWinChars(strP); /* Computer name */
        objv[2] = ObjFromDWORD(evlP->Reserved);
        objv[3] = ObjFromDWORD(evlP->RecordNumber);
        objv[4] = ObjFromDWORD(evlP->TimeGenerated);
        objv[5] = ObjFromDWORD(evlP->TimeWritten);
        objv[6] = ObjFromDWORD(evlP->EventID);
        objv[7] = ObjFromInt(evlP->EventType);
        objv[8] = ObjFromInt(evlP->EventCategory);
        objv[9] = ObjFromInt(evlP->ReservedFlags);
        objv[10] = ObjFromDWORD(evlP->ClosingRecordNumber);

        /* Collect all the strings together into a list */
        objv[11] = ObjNewList(0, NULL);
        for (strP = (WCHAR *)(evlP->StringOffset + (char *)evlP), strindex = 0;
             strindex < evlP->NumStrings;
             ++strindex) {
            len = lstrlenW(strP);
            ObjAppendElement(interp, objv[11],
                                     ObjFromWinCharsN(strP, len));
            strP += len + 1;
        }

        /* Get the SID */
        sidP = (PSID) (evlP->UserSidOffset + (char *)evlP);
        if ((evlP->UserSidLength == 0) ||
            (ObjFromSID(interp, sidP, &objv[12]) != TCL_OK)) {
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

static int Twapi_EventlogCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;
    int func = PtrToInt(clientdata);
    HANDLE h, h2;

    ObjToUnicodeCleanup();

    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    if (func < 100) {
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), ARGUSEDEFAULT, GETHANDLE(h2),
                         ARGEND) != TCL_OK)







<
<







159
160
161
162
163
164
165


166
167
168
169
170
171
172

static int Twapi_EventlogCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;
    int func = PtrToInt(clientdata);
    HANDLE h, h2;



    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    if (func < 100) {
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), ARGUSEDEFAULT, GETHANDLE(h2),
                         ARGEND) != TCL_OK)
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        /* Exactly 2 args */
        CHECK_NARGS(interp, objc, 2);
        switch (func) {
        case 1002:
            if (ObjToLPVOID(interp, objv[0], &h) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = BackupEventLogW(h, ObjToUnicode(objv[1]));
            break;
        case 1003:
            if (ObjToLPVOID(interp, objv[0], &h) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = ClearEventLogW(h, ObjToLPWSTR_NULL_IF_EMPTY(objv[1]));
            break;
        case 1004:
            result.type = TRT_HANDLE;
            result.value.hval = OpenBackupEventLogW(
                ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
                ObjToUnicode(objv[1]));
            break;
        }
    }

    return TwapiSetResult(interp, &result);
}








|











|







203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
        /* Exactly 2 args */
        CHECK_NARGS(interp, objc, 2);
        switch (func) {
        case 1002:
            if (ObjToLPVOID(interp, objv[0], &h) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = BackupEventLogW(h, ObjToWinChars(objv[1]));
            break;
        case 1003:
            if (ObjToLPVOID(interp, objv[0], &h) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = ClearEventLogW(h, ObjToLPWSTR_NULL_IF_EMPTY(objv[1]));
            break;
        case 1004:
            result.type = TRT_HANDLE;
            result.value.hval = OpenBackupEventLogW(
                ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
                ObjToWinChars(objv[1]));
            break;
        }
    }

    return TwapiSetResult(interp, &result);
}

Changes to undroid/twapi/twapi/eventlog/evt.c.
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    objP = NULL;
    switch (varP->Type) {
    case EvtVarTypeNull:
        break;
    case EvtVarTypeString:
    case EvtVarTypeEvtXml:
        if (varP->StringVal)
            objP = ObjFromUnicode(varP->StringVal);
        break;
    case EvtVarTypeAnsiString:
        if (varP->AnsiStringVal)
            objP = ObjFromString(varP->AnsiStringVal);
        break;
    case EvtVarTypeSByte:
        objP = ObjFromInt(varP->SByteVal);







|







293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    objP = NULL;
    switch (varP->Type) {
    case EvtVarTypeNull:
        break;
    case EvtVarTypeString:
    case EvtVarTypeEvtXml:
        if (varP->StringVal)
            objP = ObjFromWinChars(varP->StringVal);
        break;
    case EvtVarTypeAnsiString:
        if (varP->AnsiStringVal)
            objP = ObjFromString(varP->AnsiStringVal);
        break;
    case EvtVarTypeSByte:
        objP = ObjFromInt(varP->SByteVal);
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
                                 count * sizeof(objPP[0]), NULL);

        switch (varP->Type & EVT_VARIANT_TYPE_MASK) {
        case EvtVarTypeString:
        case EvtVarTypeEvtXml:
            for (i = 0; i < count; ++i) {
                objPP[i] = varP->StringArr[i] ?
                    ObjFromUnicode(varP->StringArr[i])
                    : ObjFromEmptyString();
            }
            break;
        case EvtVarTypeAnsiString:
            for (i = 0; i < count; ++i) {
                objPP[i] = varP->AnsiStringArr[i] ?
                    ObjFromString(varP->AnsiStringArr[i])







|







375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
                                 count * sizeof(objPP[0]), NULL);

        switch (varP->Type & EVT_VARIANT_TYPE_MASK) {
        case EvtVarTypeString:
        case EvtVarTypeEvtXml:
            for (i = 0; i < count; ++i) {
                objPP[i] = varP->StringArr[i] ?
                    ObjFromWinChars(varP->StringArr[i])
                    : ObjFromEmptyString();
            }
            break;
        case EvtVarTypeAnsiString:
            for (i = 0; i < count; ++i) {
                objPP[i] = varP->AnsiStringArr[i] ?
                    ObjFromString(varP->AnsiStringArr[i])
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
}

/* IMPORTANT:
 * If a valid buffer is passed in (as the 4th arg) caller must not
 * access it again irrespective of successful or error return unless
 * in the former case the same buffer is returned explicitly
 */
static TCL_RESULT Twapi_EvtRenderValuesObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE hevt, hevt2;
    DWORD status;
    void *bufP;
    TwapiEVT_RENDER_VALUES_HEADER *ervhP;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETEVTH(hevt),
                     GETHANDLET(hevt2, EVT_HANDLE),
                     GETVERIFIEDORNULL(ervhP, TwapiEVT_RENDER_VALUES_HEADER*, Twapi_EvtRenderValuesObjCmd),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* 4th arg is supposed to describe a previously returned buffer







|






<
<







605
606
607
608
609
610
611
612
613
614
615
616
617
618


619
620
621
622
623
624
625
}

/* IMPORTANT:
 * If a valid buffer is passed in (as the 4th arg) caller must not
 * access it again irrespective of successful or error return unless
 * in the former case the same buffer is returned explicitly
 */
static TCL_RESULT Twapi_EvtRenderValuesObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE hevt, hevt2;
    DWORD status;
    void *bufP;
    TwapiEVT_RENDER_VALUES_HEADER *ervhP;



    if (TwapiGetArgs(interp, objc-1, objv+1, GETEVTH(hevt),
                     GETHANDLET(hevt2, EVT_HANDLE),
                     GETVERIFIEDORNULL(ervhP, TwapiEVT_RENDER_VALUES_HEADER*, Twapi_EvtRenderValuesObjCmd),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* 4th arg is supposed to describe a previously returned buffer
671
672
673
674
675
676
677
678
679

680
681
682
683
684
685
686
687
688
689
690
691
692
693


    ObjSetResult(interp, ObjFromOpaque(ervhP, "TwapiEVT_RENDER_VALUES_HEADER*"));
    return TCL_OK;
}

/* EvtRender for Unicode return types */
static TCL_RESULT Twapi_EvtRenderUnicodeObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp,  int objc, Tcl_Obj *CONST objv[])
{

    HANDLE hevt, hevt2;
    DWORD flags, sz, count, status;
    void *bufP;
    Tcl_Obj *objP;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETEVTH(hevt),
                     GETHANDLET(hevt2, EVT_HANDLE), GETINT(flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* 1 -> EvtRenderEventXml */
    /* 2 -> EvtRenderBookmark */







|

>





<
<







669
670
671
672
673
674
675
676
677
678
679
680
681
682
683


684
685
686
687
688
689
690


    ObjSetResult(interp, ObjFromOpaque(ervhP, "TwapiEVT_RENDER_VALUES_HEADER*"));
    return TCL_OK;
}

/* EvtRender for Unicode return types */
static TCL_RESULT Twapi_EvtRenderUnicodeObjCmd(ClientData clientdata, Tcl_Interp *interp,  int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    HANDLE hevt, hevt2;
    DWORD flags, sz, count, status;
    void *bufP;
    Tcl_Obj *objP;



    if (TwapiGetArgs(interp, objc-1, objv+1, GETEVTH(hevt),
                     GETHANDLET(hevt2, EVT_HANDLE), GETINT(flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* 1 -> EvtRenderEventXml */
    /* 2 -> EvtRenderBookmark */
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726

727
728
729
730
731
732
733
734
735
736
737
738
739
740
741

742
743
744
745
746
747
748
749
750
751
752
753
754
755
756

757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772

    if (status != ERROR_SUCCESS) {
        MemLifoPopFrame(ticP->memlifoP);
        return Twapi_AppendSystemError(interp, status);
    }

    /* Unicode string. Should we use sz/2 instead of -1 ? TBD */
    objP = ObjFromUnicode(bufP);
    MemLifoPopFrame(ticP->memlifoP);
    ObjSetResult(ticP->interp, objP);
    return TCL_OK;
}

static TCL_RESULT Twapi_ExtractEVT_VARIANT_ARRAYObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    EVT_VARIANT *varP;
    int dw;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETHANDLE(varP), GETINT(dw),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
        
    ObjSetResult(interp, ObjFromEVT_VARIANT_ARRAY(ticP, varP, dw));
    return TCL_OK;
}

static TCL_RESULT Twapi_ExtractEVT_RENDER_VALUESObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    TwapiEVT_RENDER_VALUES_HEADER *ervhP;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(ervhP, TwapiEVT_RENDER_VALUES_HEADER*, Twapi_EvtRenderValuesObjCmd),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    ObjSetResult(interp, ObjFromEVT_VARIANT_ARRAY(ticP, ERVHP_BUFFER(ervhP), ervhP->header.count));
    return TCL_OK;
}

static TCL_RESULT Twapi_EvtNextObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    EVT_HANDLE hevt;
    EVT_HANDLE *hevtP;
    DWORD i, count, timeout, dw;
    Tcl_Obj *objP;
    Tcl_Obj **objPP;
    int result;

    ObjToUnicodeCleanup();

    /* ARGSKIP is status. Only filled on error */
    if (TwapiGetArgs(interp, objc-1, objv+1, GETEVTH(hevt), GETINT(count),
                     GETINT(timeout), GETINT(dw), ARGUSEDEFAULT, ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (count > 1024) // TBD - why ?







|





|

>



<
<








|

>


<
<









|

>







<
<







709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727


728
729
730
731
732
733
734
735
736
737
738
739
740


741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759


760
761
762
763
764
765
766

    if (status != ERROR_SUCCESS) {
        MemLifoPopFrame(ticP->memlifoP);
        return Twapi_AppendSystemError(interp, status);
    }

    /* Unicode string. Should we use sz/2 instead of -1 ? TBD */
    objP = ObjFromWinChars(bufP);
    MemLifoPopFrame(ticP->memlifoP);
    ObjSetResult(ticP->interp, objP);
    return TCL_OK;
}

static TCL_RESULT Twapi_ExtractEVT_VARIANT_ARRAYObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    EVT_VARIANT *varP;
    int dw;



    if (TwapiGetArgs(interp, objc-1, objv+1, GETHANDLE(varP), GETINT(dw),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
        
    ObjSetResult(interp, ObjFromEVT_VARIANT_ARRAY(ticP, varP, dw));
    return TCL_OK;
}

static TCL_RESULT Twapi_ExtractEVT_RENDER_VALUESObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    TwapiEVT_RENDER_VALUES_HEADER *ervhP;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETVERIFIEDPTR(ervhP, TwapiEVT_RENDER_VALUES_HEADER*, Twapi_EvtRenderValuesObjCmd),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    ObjSetResult(interp, ObjFromEVT_VARIANT_ARRAY(ticP, ERVHP_BUFFER(ervhP), ervhP->header.count));
    return TCL_OK;
}

static TCL_RESULT Twapi_EvtNextObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    EVT_HANDLE hevt;
    EVT_HANDLE *hevtP;
    DWORD i, count, timeout, dw;
    Tcl_Obj *objP;
    Tcl_Obj **objPP;
    int result;



    /* ARGSKIP is status. Only filled on error */
    if (TwapiGetArgs(interp, objc-1, objv+1, GETEVTH(hevt), GETINT(count),
                     GETINT(timeout), GETINT(dw), ARGUSEDEFAULT, ARGSKIP,
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (count > 1024) // TBD - why ?
813
814
815
816
817
818
819
820
821

822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
    }


    MemLifoPopFrame(ticP->memlifoP);
    return result;
}

static TCL_RESULT Twapi_EvtCreateRenderContextObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    EVT_HANDLE hevt;
    int count;
    LPCWSTR *xpathsP = NULL;
    int flags;
    DWORD ret = TCL_ERROR;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, ARGSKIP, GETINT(flags), ARGEND) != TCL_OK ||
        ObjListLength(interp, objv[1], &count) != TCL_OK)
        return TCL_ERROR;

    if (count == 0) {
        xpathsP = NULL;
    } else {







|

>






<
<







807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822


823
824
825
826
827
828
829
    }


    MemLifoPopFrame(ticP->memlifoP);
    return result;
}

static TCL_RESULT Twapi_EvtCreateRenderContextObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    EVT_HANDLE hevt;
    int count;
    LPCWSTR *xpathsP = NULL;
    int flags;
    DWORD ret = TCL_ERROR;



    if (TwapiGetArgs(interp, objc-1, objv+1, ARGSKIP, GETINT(flags), ARGEND) != TCL_OK ||
        ObjListLength(interp, objv[1], &count) != TCL_OK)
        return TCL_ERROR;

    if (count == 0) {
        xpathsP = NULL;
    } else {
852
853
854
855
856
857
858
859
860

861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
vamoose:
    if (xpathsP)
        MemLifoPopFrame(ticP->memlifoP);
    return ret;
}


static TCL_RESULT Twapi_EvtFormatMessageObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    EVT_HANDLE hpub, hev;
    DWORD msgid, flags;
    EVT_VARIANT *valuesP;
    int nvalues;
    WCHAR buf[500];             /* TBD - instrument */
    int buf_sz, used;
    WCHAR *bufP;
    DWORD winerr;
    TwapiEVT_RENDER_VALUES_HEADER *ervhP;
    Tcl_Obj *objP;
    TCL_RESULT status;

    ObjToUnicodeCleanup();

    /* objv[6], if specified, is the name of the variable to store
       message. If unspecified, message is returned in interp result. */
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLET(hpub, EVT_HANDLE),
                     GETHANDLET(hev, EVT_HANDLE),
                     GETINT(msgid),
                     GETVERIFIEDORNULL(ervhP, TwapiEVT_RENDER_VALUES_HEADER*, Twapi_EvtRenderValuesObjCmd),







|

>

|



<






<
<







845
846
847
848
849
850
851
852
853
854
855
856
857
858
859

860
861
862
863
864
865


866
867
868
869
870
871
872
vamoose:
    if (xpathsP)
        MemLifoPopFrame(ticP->memlifoP);
    return ret;
}


static TCL_RESULT Twapi_EvtFormatMessageObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    EVT_HANDLE hpub, hev;
    DWORD msgid, flags, used, buf_sz;
    EVT_VARIANT *valuesP;
    int nvalues;
    WCHAR buf[500];             /* TBD - instrument */

    WCHAR *bufP;
    DWORD winerr;
    TwapiEVT_RENDER_VALUES_HEADER *ervhP;
    Tcl_Obj *objP;
    TCL_RESULT status;



    /* objv[6], if specified, is the name of the variable to store
       message. If unspecified, message is returned in interp result. */
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHANDLET(hpub, EVT_HANDLE),
                     GETHANDLET(hev, EVT_HANDLE),
                     GETINT(msgid),
                     GETVERIFIEDORNULL(ervhP, TwapiEVT_RENDER_VALUES_HEADER*, Twapi_EvtRenderValuesObjCmd),
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
            objP = ObjFromMultiSz(bufP, used);
        } else {
            /* For other cases, like xml, used may be more than last char
               so depend on null termination, not used count.
               TBD - for performance reasons, verify this and may be
               make exception for xml only
            */
            objP = ObjFromUnicode(bufP);
        }
    } else {
        if (objc == 7) {
            objP = Twapi_MapWindowsErrorToString(winerr);
            status = TCL_OK;
        } else {
            Twapi_AppendSystemError(interp, winerr);







|







925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
            objP = ObjFromMultiSz(bufP, used);
        } else {
            /* For other cases, like xml, used may be more than last char
               so depend on null termination, not used count.
               TBD - for performance reasons, verify this and may be
               make exception for xml only
            */
            objP = ObjFromWinChars(bufP);
        }
    } else {
        if (objc == 7) {
            objP = Twapi_MapWindowsErrorToString(winerr);
            status = TCL_OK;
        } else {
            Twapi_AppendSystemError(interp, winerr);
968
969
970
971
972
973
974
975
976

977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
    if (bufP != buf)
        MemLifoPopFrame(ticP->memlifoP);

    return status;
}


static TCL_RESULT Twapi_EvtGetEVT_VARIANTObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    EVT_HANDLE hevt;
    int sz;
    EVT_VARIANT *varP;
    int func;
    DWORD dw, dw2, dw3;
    DWORD status;
    BOOL (WINAPI *fn3args)(HANDLE,int,DWORD,DWORD,EVT_VARIANT *, PDWORD);
    BOOL (WINAPI *fn2args)(HANDLE,int,DWORD,EVT_VARIANT *, PDWORD);

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(func), GETEVTH(hevt),
                     GETINT(dw), ARGUSEDEFAULT, GETINT(dw2),
                     GETINT(dw3), ARGEND) != TCL_OK)
        return TCL_ERROR;

    varP = MemLifoPushFrame(ticP->memlifoP, sizeof(EVT_VARIANT), &sz);
    while (1) {







|

>

<


|




<
<







959
960
961
962
963
964
965
966
967
968
969

970
971
972
973
974
975
976


977
978
979
980
981
982
983
    if (bufP != buf)
        MemLifoPopFrame(ticP->memlifoP);

    return status;
}


static TCL_RESULT Twapi_EvtGetEVT_VARIANTObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    EVT_HANDLE hevt;

    EVT_VARIANT *varP;
    int func;
    DWORD sz, dw, dw2, dw3;
    DWORD status;
    BOOL (WINAPI *fn3args)(HANDLE,int,DWORD,DWORD,EVT_VARIANT *, PDWORD);
    BOOL (WINAPI *fn2args)(HANDLE,int,DWORD,EVT_VARIANT *, PDWORD);



    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(func), GETEVTH(hevt),
                     GETINT(dw), ARGUSEDEFAULT, GETINT(dw2),
                     GETINT(dw3), ARGEND) != TCL_OK)
        return TCL_ERROR;

    varP = MemLifoPushFrame(ticP->memlifoP, sizeof(EVT_VARIANT), &sz);
    while (1) {
1035
1036
1037
1038
1039
1040
1041
1042
1043

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
    }
    MemLifoPopFrame(ticP->memlifoP);

    return status == FALSE ? TCL_ERROR : TCL_OK;
}


static TCL_RESULT Twapi_EvtOpenSessionObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    int login_class;
    DWORD timeout, flags;
    Tcl_Obj **loginObjs;
    int nobjs;
    EVT_RPC_LOGIN erl;
    TCL_RESULT res;
    WCHAR *passwordP;
    int password_len;
    SWSMark mark = NULL;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(login_class),
                     ARGSKIP, ARGUSEDEFAULT, GETINT(timeout), GETINT(flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (login_class != 1) {
        /* Only EvtRpcLogin (1) supported */
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid login class");
    }
    if (ObjGetElements(interp, objv[2], &nobjs, &loginObjs) != TCL_OK)
        return TCL_ERROR;

    if (nobjs != 5 ||
        ObjToInt(interp, loginObjs[4], &erl.Flags) != TCL_OK) {
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid EVT_RPC_LOGIN structure");

    }
    erl.Server = ObjToUnicode(loginObjs[0]);
    erl.User = ObjToLPWSTR_NULL_IF_EMPTY(loginObjs[1]);
    erl.Domain = ObjToLPWSTR_NULL_IF_EMPTY(loginObjs[2]);
    mark = SWSPushMark();
    passwordP = ObjDecryptPasswordSWS(loginObjs[3], &password_len);
    erl.Password = passwordP;
    NULLIFY_EMPTY(erl.Password);
    res = TwapiReturnNonnullHandle(interp,
                                   EvtOpenSession(login_class, &erl,
                                                  timeout, flags),
                                   "EVT_HANDLE");
    SecureZeroMemory(passwordP, sizeof(WCHAR) * password_len);
    SWSPopMark(mark);
    return res;
}

int Twapi_EvtCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;
    DWORD dw, dw2;







|

>








|
<
<





|








|



|


|








|







1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042


1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
    }
    MemLifoPopFrame(ticP->memlifoP);

    return status == FALSE ? TCL_ERROR : TCL_OK;
}


static TCL_RESULT Twapi_EvtOpenSessionObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int login_class;
    DWORD timeout, flags;
    Tcl_Obj **loginObjs;
    int nobjs;
    EVT_RPC_LOGIN erl;
    TCL_RESULT res;
    WCHAR *passwordP;
    int password_len;
    MemLifoMarkHandle mark = NULL;



    if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(login_class),
                     ARGSKIP, ARGUSEDEFAULT, GETINT(timeout), GETINT(flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    if (login_class != 1) {
        /* Only EvtRpcLogin (1) supported */
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid login class");
    }
    if (ObjGetElements(interp, objv[2], &nobjs, &loginObjs) != TCL_OK)
        return TCL_ERROR;

    if (nobjs != 5 ||
        ObjToDWORD(interp, loginObjs[4], &erl.Flags) != TCL_OK) {
        return TwapiReturnErrorMsg(interp, TWAPI_INVALID_ARGS, "Invalid EVT_RPC_LOGIN structure");

    }
    erl.Server = ObjToWinChars(loginObjs[0]);
    erl.User = ObjToLPWSTR_NULL_IF_EMPTY(loginObjs[1]);
    erl.Domain = ObjToLPWSTR_NULL_IF_EMPTY(loginObjs[2]);
    mark = MemLifoPushMark(ticP->memlifoP);
    passwordP = ObjDecryptPasswordSWS(loginObjs[3], &password_len);
    erl.Password = passwordP;
    NULLIFY_EMPTY(erl.Password);
    res = TwapiReturnNonnullHandle(interp,
                                   EvtOpenSession(login_class, &erl,
                                                  timeout, flags),
                                   "EVT_HANDLE");
    SecureZeroMemory(passwordP, sizeof(WCHAR) * password_len);
    MemLifoPopMark(mark);
    return res;
}

int Twapi_EvtCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiResult result;
    DWORD dw, dw2;
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
        WCHAR buf[MAX_PATH+1];
        EVT_HANDLE hevts[100];
    } u;
    EVT_VARIANT var;
    GUID guid;
    int i;

    ObjToUnicodeCleanup();

    if (gEvtStatus != 1)
        return Twapi_AppendSystemError(interp, ERROR_CALL_NOT_IMPLEMENTED);

    --objc;
    ++objv;

    /* NOTE AS ALWAYS, TO AVOID SHIMMERING ISSUES, WSTR ARGS ARE ALWAYS
       EXTRACTED AFTER SCALAR ARGS */

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
    case 2:
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt), GETOBJ(sObj), GETOBJ(s2Obj), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToUnicode(sObj);
        s2 = ObjToLPWSTR_NULL_IF_EMPTY(s2Obj);
        if (func == 1) {
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = EvtClearLog(hevt, s, s2, dw);
        } else
            TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtQuery(hevt, s, s2, dw));
        break;
    case 3: // EvtSeek
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETWIDE(wide), GETHANDLET(hevt2, EVT_HANDLE),
                         GETINT(dw), GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = EvtSeek(hevt, wide, hevt2, dw, dw2);
        break;
    case 4: // EvtOpenLog
    case 5: // EvtOpenChannelConfig
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        hevt2 = (func == 4 ? EvtOpenLog : EvtOpenChannelConfig) (hevt, ObjToUnicode(sObj), dw);
        TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, hevt2);
        break;
    case 6: // EvtArchiveExportedLog
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETINT(dw), GETINT(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = EvtArchiveExportedLog(hevt, ObjToUnicode(sObj), dw, dw2);
        break;
    case 7: // EvtSubscribe
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETHANDLE(h), GETOBJ(sObj), GETOBJ(s2Obj),
                         GETEVTH(hevt2), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtSubscribe(hevt, h, ObjToUnicode(sObj), ObjToUnicode(s2Obj), hevt2, NULL, NULL, dw));
        break;
    case 8: // EvtExportLog
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETOBJ(s2Obj), GETOBJ(s3Obj), GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = EvtExportLog(hevt, ObjToUnicode(sObj), ObjToUnicode(s2Obj), ObjToUnicode(s3Obj), dw);
        break;

    case 9: // EvtSetChannelConfigProperty
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETINT(dw), GETINT(dw2), ARGSKIP,
                         ARGEND) != TCL_OK)
            return TCL_ERROR;







<
<















|




















|








|






|







|







1088
1089
1090
1091
1092
1093
1094


1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
        WCHAR buf[MAX_PATH+1];
        EVT_HANDLE hevts[100];
    } u;
    EVT_VARIANT var;
    GUID guid;
    int i;



    if (gEvtStatus != 1)
        return Twapi_AppendSystemError(interp, ERROR_CALL_NOT_IMPLEMENTED);

    --objc;
    ++objv;

    /* NOTE AS ALWAYS, TO AVOID SHIMMERING ISSUES, WSTR ARGS ARE ALWAYS
       EXTRACTED AFTER SCALAR ARGS */

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
    case 2:
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt), GETOBJ(sObj), GETOBJ(s2Obj), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToWinChars(sObj);
        s2 = ObjToLPWSTR_NULL_IF_EMPTY(s2Obj);
        if (func == 1) {
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = EvtClearLog(hevt, s, s2, dw);
        } else
            TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtQuery(hevt, s, s2, dw));
        break;
    case 3: // EvtSeek
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETWIDE(wide), GETHANDLET(hevt2, EVT_HANDLE),
                         GETINT(dw), GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = EvtSeek(hevt, wide, hevt2, dw, dw2);
        break;
    case 4: // EvtOpenLog
    case 5: // EvtOpenChannelConfig
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        hevt2 = (func == 4 ? EvtOpenLog : EvtOpenChannelConfig) (hevt, ObjToWinChars(sObj), dw);
        TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, hevt2);
        break;
    case 6: // EvtArchiveExportedLog
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETINT(dw), GETINT(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = EvtArchiveExportedLog(hevt, ObjToWinChars(sObj), dw, dw2);
        break;
    case 7: // EvtSubscribe
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETHANDLE(h), GETOBJ(sObj), GETOBJ(s2Obj),
                         GETEVTH(hevt2), GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtSubscribe(hevt, h, ObjToWinChars(sObj), ObjToWinChars(s2Obj), hevt2, NULL, NULL, dw));
        break;
    case 8: // EvtExportLog
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETOBJ(s2Obj), GETOBJ(s3Obj), GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = EvtExportLog(hevt, ObjToWinChars(sObj), ObjToWinChars(s2Obj), ObjToWinChars(s3Obj), dw);
        break;

    case 9: // EvtSetChannelConfigProperty
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETINT(dw), GETINT(dw2), ARGSKIP,
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207

1208
1209
1210
1211
1212
1213
1214
1215
            var.Type = EvtVarTypeBoolean;
            break;
        case EvtChannelConfigIsolation:
        case EvtChannelConfigType:
        case EvtChannelPublishingConfigLevel:
        case EvtChannelPublishingConfigClockType:
        case EvtChannelPublishingConfigFileMax:
            if (ObjToLong(interp, objv[3], &var.UInt32Val) != TCL_OK)
                return TCL_ERROR;
            var.Type = EvtVarTypeUInt32;
            break;
        case EvtChannelConfigOwningPublisher:
        case EvtChannelConfigAccess:
        case EvtChannelLoggingConfigLogFilePath:
        case EvtChannelPublisherList:
            var.StringVal = ObjToUnicode(objv[3]);
            var.Type = EvtVarTypeString;
            break;

        case EvtChannelLoggingConfigMaxSize:
        case EvtChannelPublishingConfigKeywords:

            if (ObjToWideInt(interp, objv[3], &var.UInt64Val) != TCL_OK)
                return TCL_ERROR;
            var.Type = EvtVarTypeUInt64;
            break;
        case EvtChannelPublishingConfigControlGuid:
            if (ObjToGUID(interp, objv[3], &guid) != TCL_OK)
                return TCL_ERROR;
            var.Type = EvtVarTypeGuid;







|







|





>
|







1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
            var.Type = EvtVarTypeBoolean;
            break;
        case EvtChannelConfigIsolation:
        case EvtChannelConfigType:
        case EvtChannelPublishingConfigLevel:
        case EvtChannelPublishingConfigClockType:
        case EvtChannelPublishingConfigFileMax:
            if (ObjToDWORD(interp, objv[3], &var.UInt32Val) != TCL_OK)
                return TCL_ERROR;
            var.Type = EvtVarTypeUInt32;
            break;
        case EvtChannelConfigOwningPublisher:
        case EvtChannelConfigAccess:
        case EvtChannelLoggingConfigLogFilePath:
        case EvtChannelPublisherList:
            var.StringVal = ObjToWinChars(objv[3]);
            var.Type = EvtVarTypeString;
            break;

        case EvtChannelLoggingConfigMaxSize:
        case EvtChannelPublishingConfigKeywords:
            TWAPI_ASSERT(sizeof(Tcl_WideInt) == sizeof(UINT64));
            if (ObjToWideInt(interp, objv[3], (Tcl_WideInt *)&var.UInt64Val) != TCL_OK)
                return TCL_ERROR;
            var.Type = EvtVarTypeUInt64;
            break;
        case EvtChannelPublishingConfigControlGuid:
            if (ObjToGUID(interp, objv[3], &guid) != TCL_OK)
                return TCL_ERROR;
            var.Type = EvtVarTypeGuid;
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
        break;

    case 10: // EvtOpenPublisherMetadata
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETOBJ(s2Obj), GETINT(dw),
                         GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s2 = ObjToUnicode(s2Obj);
        NULLIFY_EMPTY(s2);
        TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtOpenPublisherMetadata(hevt, ObjToUnicode(sObj), s2, dw, dw2));
        break;

    case 11: // evt_create_bookmark
        if (TwapiGetArgs(interp, objc, objv, ARGUSEDEFAULT,
                         GETOBJ(sObj), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToLPWSTR_NULL_IF_EMPTY(sObj);







|

|







1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
        break;

    case 10: // EvtOpenPublisherMetadata
        if (TwapiGetArgs(interp, objc, objv, GETEVTH(hevt),
                         GETOBJ(sObj), GETOBJ(s2Obj), GETINT(dw),
                         GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s2 = ObjToWinChars(s2Obj);
        NULLIFY_EMPTY(s2);
        TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtOpenPublisherMetadata(hevt, ObjToWinChars(sObj), s2, dw, dw2));
        break;

    case 11: // evt_create_bookmark
        if (TwapiGetArgs(interp, objc, objv, ARGUSEDEFAULT,
                         GETOBJ(sObj), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToLPWSTR_NULL_IF_EMPTY(sObj);
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
            TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtOpenChannelEnum(hevt, dw));
            break;
        case 104: // EvtNextChannelPath
        case 109: // EvtNextPublisherId
            /* Note channel/publisher is max 255 chars so no need to check
               for ERROR_INSUFFICIENT_BUFFER */
            if ((func == 104 ? EvtNextChannelPath : EvtNextPublisherId)(hevt, ARRAYSIZE(u.buf), u.buf, &dw) != FALSE) {
                ObjSetResult(interp, ObjFromUnicodeN(u.buf, dw-1));
                return TCL_OK;
            }
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = GetLastError();
            if (result.value.ival == ERROR_NO_MORE_ITEMS)
                return TCL_OK;
            break;







|







1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
            TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtOpenChannelEnum(hevt, dw));
            break;
        case 104: // EvtNextChannelPath
        case 109: // EvtNextPublisherId
            /* Note channel/publisher is max 255 chars so no need to check
               for ERROR_INSUFFICIENT_BUFFER */
            if ((func == 104 ? EvtNextChannelPath : EvtNextPublisherId)(hevt, ARRAYSIZE(u.buf), u.buf, &dw) != FALSE) {
                ObjSetResult(interp, ObjFromWinCharsN(u.buf, dw-1));
                return TCL_OK;
            }
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = GetLastError();
            if (result.value.ival == ERROR_NO_MORE_ITEMS)
                return TCL_OK;
            break;
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
            TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtNextEventMetadata(hevt, dw));
            if (result.value.ptr.p == NULL &&
                GetLastError() == ERROR_NO_MORE_ITEMS)
                return TCL_OK;
            break;
        case 110:
            result.type =
                EvtGetObjectArraySize(hevt, &result.value.ival) ?
                TRT_DWORD : TRT_GETLASTERROR;
            break;
        }            
    }

    dw = TwapiSetResult(interp, &result);
    if (dw == TCL_OK)







|







1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
            TwapiResult_SET_NONNULL_PTR(result, EVT_HANDLE, EvtNextEventMetadata(hevt, dw));
            if (result.value.ptr.p == NULL &&
                GetLastError() == ERROR_NO_MORE_ITEMS)
                return TCL_OK;
            break;
        case 110:
            result.type =
                EvtGetObjectArraySize(hevt, &result.value.uval) ?
                TRT_DWORD : TRT_GETLASTERROR;
            break;
        }            
    }

    dw = TwapiSetResult(interp, &result);
    if (dw == TCL_OK)
Changes to undroid/twapi/twapi/include/rules.inc.
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#           files into one and passing to the linker.
#       [d] The resource compiler is run only for the twapi_base module
#           and its output is linked to the DLL (more on this below
#           in the embedding section).
#       [e] Since Tcl does not explicitly call module initialization
#           functions (except for the twapi_base DLL which is explicitly
#           loaded), each module needs to provide a way for its
#           initialization function to be called. To accomplish this,
#           a *.initfn file is generated in the twapi_base build directory
#           when a module is built. Each file contains a C code fragment
#           to register the module as a static Tcl package. These files 
#           are combined when the twapi_base is built and included via
#           a C #include statement in the twapi_base initialization code.
#           A similar mechanism is used to generate the prototypes for
#           the module initialization functions and include them as well.
#
# Embedding of scripts:
#
#  [4] If scripts are not to be embedded in the DLL, the resource
#      TWAPI_SCRIPT_RESOURCE_PATH is not defined and the DLL resource
#      definition file is compiled as is as described above in the building
#      of the DLL. THIS CASE IS NOT CURRENTLY USED - EVEN IF THE TCL







|
|
<
<
|
|
<
|







30
31
32
33
34
35
36
37
38


39
40

41
42
43
44
45
46
47
48
#           files into one and passing to the linker.
#       [d] The resource compiler is run only for the twapi_base module
#           and its output is linked to the DLL (more on this below
#           in the embedding section).
#       [e] Since Tcl does not explicitly call module initialization
#           functions (except for the twapi_base DLL which is explicitly
#           loaded), each module needs to provide a way for its
#           initialization function to be called. These initialization
#           fragments and associated prototypes are contained in the


#           files twapi_module_static_{init,proto}.h. These files
#           used to be automatically generated but that is no longer

#           true, partly to support MinGW builds.
#
# Embedding of scripts:
#
#  [4] If scripts are not to be embedded in the DLL, the resource
#      TWAPI_SCRIPT_RESOURCE_PATH is not defined and the DLL resource
#      definition file is compiled as is as described above in the building
#      of the DLL. THIS CASE IS NOT CURRENTLY USED - EVEN IF THE TCL
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"$(OBJDIR)" "$(PACKAGEDIR)":
	@if not exist $@ mkdir $@

!if defined(TWAPI_SINGLE_MODULE)
#  See [3] - Single combined DLL or static lib build
!  if  "$(MODULENAME)" == "twapi_base"
#    See [3a,c,e] - build twapi_base DLL with included other modules
"$(OBJDIR)\$(MODULE)": "$(OBJDIR)\$(MODULENAME).res" $(OBJS) "$(OBJDIR)\*.link" "$(OBJDIR)\*.initfn"
	$(COPY) "$(OBJDIR)\*.link" "$(OBJDIR)\linkmodules"
!    if defined(TWAPI_STATIC_BUILD)
        $(LIBTOOL) -nologo -out:$@ "@$(OBJDIR)\linkmodules" $(OBJS)
!    else
        $(LINK) $(LOPT) -out:$@ $(LIBS) "@$(OBJDIR)\linkmodules" "$(OBJDIR)\$(MODULENAME).res" $(OBJS)
#      See http://kb.froglogic.com/display/KB/Manifests. VC 9 *requires*
#      manifests for DLL's as well. Newer compilers do not seem to care
!      if $(VCVER) == 9
	cd $(OBJDIR) && $(MT) -manifest $(MODULE).manifest -outputresource:$(MODULE);2
!      endif $(VCVER) == 9
!    endif  TWAPI_STATIC_BUILD
!  else
#    See [3b] - building a module other than twapi_base in single DLL mode
"$(OBJDIR)\$(MODULE)": "$(OBJDIR)\..\twapi_base\$(MODULENAME).link" "$(OBJDIR)\..\twapi_base\$(MODULENAME).initfn" $(TWAPI_SCRIPT_RESOURCE_PATH) $(RCFRAG)

#    See [3e] - write module initialization fragments
"$(OBJDIR)\..\twapi_base\$(MODULENAME).initfn": $(OBJS)
	-@if not exist $(@D) mkdir $(@D)
	echo puts "Tcl_PackageInitProc [string totitle $(MODULENAME)]_Init;" | $(TCLSH) > $@.proto
	echo puts "TWAPI_INIT_STATIC_PACKAGE([string totitle $(MODULENAME)], [string totitle $(MODULENAME)]_Init, NULL);" | $(TCLSH) > $@

#    See [3b] - create link inputs for modules other than twapi_base
"$(OBJDIR)\..\twapi_base\$(MODULENAME).link" : $(OBJS)
	-@if not exist $(@D) mkdir $(@D)
!    if defined(TWAPI_STATIC_BUILD)
	echo $(OBJS) > $@
!    else







|













|
<
<
<
<
<
<







144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165






166
167
168
169
170
171
172
"$(OBJDIR)" "$(PACKAGEDIR)":
	@if not exist $@ mkdir $@

!if defined(TWAPI_SINGLE_MODULE)
#  See [3] - Single combined DLL or static lib build
!  if  "$(MODULENAME)" == "twapi_base"
#    See [3a,c,e] - build twapi_base DLL with included other modules
"$(OBJDIR)\$(MODULE)": "$(OBJDIR)\$(MODULENAME).res" $(OBJS) "$(OBJDIR)\*.link"
	$(COPY) "$(OBJDIR)\*.link" "$(OBJDIR)\linkmodules"
!    if defined(TWAPI_STATIC_BUILD)
        $(LIBTOOL) -nologo -out:$@ "@$(OBJDIR)\linkmodules" $(OBJS)
!    else
        $(LINK) $(LOPT) -out:$@ $(LIBS) "@$(OBJDIR)\linkmodules" "$(OBJDIR)\$(MODULENAME).res" $(OBJS)
#      See http://kb.froglogic.com/display/KB/Manifests. VC 9 *requires*
#      manifests for DLL's as well. Newer compilers do not seem to care
!      if $(VCVER) == 9
	cd $(OBJDIR) && $(MT) -manifest $(MODULE).manifest -outputresource:$(MODULE);2
!      endif $(VCVER) == 9
!    endif  TWAPI_STATIC_BUILD
!  else
#    See [3b] - building a module other than twapi_base in single DLL mode
"$(OBJDIR)\$(MODULE)": "$(OBJDIR)\..\twapi_base\$(MODULENAME).link" $(TWAPI_SCRIPT_RESOURCE_PATH) $(RCFRAG)







#    See [3b] - create link inputs for modules other than twapi_base
"$(OBJDIR)\..\twapi_base\$(MODULENAME).link" : $(OBJS)
	-@if not exist $(@D) mkdir $(@D)
!    if defined(TWAPI_STATIC_BUILD)
	echo $(OBJS) > $@
!    else
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
!endif defined(EMBED_SCRIPT)

$(OBJDIR)\$(MODULELIB): $(OBJDIR) $(OBJS) $(TWAPI_SCRIPT_RESOURCE_PATH) $(RCFRAG)
!if "$(MODULENAME)" == "twapi_base"
	$(COPY) "$(OBJDIR)\*.link" "$(OBJDIR)\linkmodules"
        $(LIBTOOL) -nologo -out:$@ "@$(OBJDIR)\linkmodules" $(OBJS)
!else
$(OBJDIR)\$(MODULELIB): "$(OBJDIR)\..\twapi_base\$(MODULENAME).initfn" "$(OBJDIR)\..\twapi_base\$(MODULENAME).link"
!endif




makefile: $(SRCROOT)\include\common.inc $(SRCROOT)\include\rules.inc

$(SRCROOT)\include\common.inc: $(SRCROOT)\include\version.inc

clean:
        -$(RMDIR) "$(OBJDIR)"

# Inference rules
# Compile a file
.c{$(OBJDIR)}.obj::
!if defined(TWAPI_SINGLE_MODULE) && "$(MODULENAME)" == "twapi_base"
	$(COPY) "$(OBJDIR)\*.initfn.proto" "$(OBJDIR)\twapi_module_static_proto.h"
	$(COPY) "$(OBJDIR)\*.initfn" "$(OBJDIR)\twapi_module_static_init.h"
!endif
	$(CC) $(CFLAGS) -Fo$(OBJDIR)\ $<







|

<
<












<
<
<
<

237
238
239
240
241
242
243
244
245


246
247
248
249
250
251
252
253
254
255
256
257




258
!endif defined(EMBED_SCRIPT)

$(OBJDIR)\$(MODULELIB): $(OBJDIR) $(OBJS) $(TWAPI_SCRIPT_RESOURCE_PATH) $(RCFRAG)
!if "$(MODULENAME)" == "twapi_base"
	$(COPY) "$(OBJDIR)\*.link" "$(OBJDIR)\linkmodules"
        $(LIBTOOL) -nologo -out:$@ "@$(OBJDIR)\linkmodules" $(OBJS)
!else
$(OBJDIR)\$(MODULELIB): "$(OBJDIR)\..\twapi_base\$(MODULENAME).link"
!endif




makefile: $(SRCROOT)\include\common.inc $(SRCROOT)\include\rules.inc

$(SRCROOT)\include\common.inc: $(SRCROOT)\include\version.inc

clean:
        -$(RMDIR) "$(OBJDIR)"

# Inference rules
# Compile a file
.c{$(OBJDIR)}.obj::




	$(CC) $(CFLAGS) -Fo$(OBJDIR)\ $<
Changes to undroid/twapi/twapi/include/twapi.h.
403
404
405
406
407
408
409
410
411

412

413

414

415
416
417

418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433

434
435
436
437
438
439
440
441
#define TWAPI_WIN32_ERROR_TO_CODE(winerr) ((winerr) & 0x0000ffff)

/**********************
 * Misc utility macros
 **********************/

/* Verify a Tcl_Obj is an integer/long and return error if not */
#define CHECK_INTEGER_OBJ(interp_, intvar_, objp_)                      \
    do {                                                                \

        long longvar_;                                                  \

        if (ObjToLong((interp_), (objp_), &(longvar_)) != TCL_OK)       \

            return TCL_ERROR;                                           \

        intvar_ = (int) longvar_;                                       \
    } while (0)


/* Check number of arguments */
#define CHECK_NARGS(interp_, n_, m_)                                    \
    do {                                                                \
        if ((n_) != (m_))                                               \
            return TwapiReturnError((interp_), TWAPI_BAD_ARG_COUNT);    \
    } while (0)

#define CHECK_NARGS_RANGE(interp_, nargs_, min_, max_)                  \
    do {                                                                \
        if ((nargs_) < (min_) || (nargs_) > (max_))                     \
            return TwapiReturnError((interp_), TWAPI_BAD_ARG_COUNT);    \
    } while (0)


/* String equality test - check first char before calling strcmp */
#define STREQ(x, y) ((((x)[0]) == ((y)[0])) && ! lstrcmpA((x), (y)))

#define STREQUN(x, y, n) (((x)[0] == (y)[0]) && (strncmp(x, y, n) == 0))
#define WSTREQ(x, y) ( (((x)[0]) == ((y)[0])) && ! lstrcmpW((x), (y)) )

/* Make a pointer null if it points to empty element (generally used
   when we want to treat empty strings as null pointers */
#define NULLIFY_EMPTY(s_) if ((s_) && ((s_)[0] == 0)) (s_) = NULL
/* And the converse */
#define EMPTIFY_NULL(s_) if ((s_) == NULL) (s_) = L"";







|

>
|
>
|
>
|
>
|


>

|













|
>
|







403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#define TWAPI_WIN32_ERROR_TO_CODE(winerr) ((winerr) & 0x0000ffff)

/**********************
 * Misc utility macros
 **********************/

/* Verify a Tcl_Obj is an integer/long and return error if not */
#define CHECK_INTEGER_OBJ(interp_, intvar_, objp_)       \
    do {                                                                \
        if (ObjToInt((interp_), (objp_), &(intvar_)) != TCL_OK) \
            return TCL_ERROR;                                           \
    } while (0)

#define CHECK_DWORD_OBJ(interp_, dwvar_, objp_)       \
    do {                                                                \
        if (ObjToDWORD((interp_), (objp_), &(dwvar_)) != TCL_OK) \
            return TCL_ERROR;                                           \
    } while (0)


/* Check number of arguments */
#define CHECK_NARGS(interp_, n_, m_)                        \
    do {                                                                \
        if ((n_) != (m_))                                               \
            return TwapiReturnError((interp_), TWAPI_BAD_ARG_COUNT);    \
    } while (0)

#define CHECK_NARGS_RANGE(interp_, nargs_, min_, max_)                  \
    do {                                                                \
        if ((nargs_) < (min_) || (nargs_) > (max_))                     \
            return TwapiReturnError((interp_), TWAPI_BAD_ARG_COUNT);    \
    } while (0)


/* String equality test - check first char before calling strcmp */
#define STREQ(x, y) ( (((x)[0]) == ((y)[0])) && ! lstrcmpA((x), (y)) )
#define STREQUN(x, y, n) \
    (((x)[0] == (y)[0]) && (strncmp(x, y, n) == 0))
#define WSTREQ(x, y) ( (((x)[0]) == ((y)[0])) && ! lstrcmpW((x), (y)) )

/* Make a pointer null if it points to empty element (generally used
   when we want to treat empty strings as null pointers */
#define NULLIFY_EMPTY(s_) if ((s_) && ((s_)[0] == 0)) (s_) = NULL
/* And the converse */
#define EMPTIFY_NULL(s_) if ((s_) == NULL) (s_) = L"";
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    ObjAppendElement((interp_), (listp_), ObjFromWideInt((structp_)->field_.QuadPart)); \
  } while (0)

/* Appends a struct Unicode field name and string pair to a Tcl list object */
#define Twapi_APPEND_LPCWSTR_FIELD_TO_LIST(interp_, listp_, structp_, field_) \
  do { \
    ObjAppendElement((interp_), (listp_), STRING_LITERAL_OBJ( # field_)); \
    ObjAppendElement((interp_),(listp_), ObjFromUnicodeN(((structp_)->field_ ? (structp_)->field_ : L""), -1)); \
  } while (0)

/* Appends a struct char string field name and string pair to a Tcl list object */
#define Twapi_APPEND_LPCSTR_FIELD_TO_LIST(interp_, listp_, structp_, field_) \
  do { \
    ObjAppendElement((interp_), (listp_), STRING_LITERAL_OBJ( # field_)); \
    ObjAppendElement((interp_),(listp_), ObjFromString(((structp_)->field_ ? (structp_)->field_ : ""))); \







|







517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
    ObjAppendElement((interp_), (listp_), ObjFromWideInt((structp_)->field_.QuadPart)); \
  } while (0)

/* Appends a struct Unicode field name and string pair to a Tcl list object */
#define Twapi_APPEND_LPCWSTR_FIELD_TO_LIST(interp_, listp_, structp_, field_) \
  do { \
    ObjAppendElement((interp_), (listp_), STRING_LITERAL_OBJ( # field_)); \
    ObjAppendElement((interp_),(listp_), ObjFromWinCharsN(((structp_)->field_ ? (structp_)->field_ : L""), -1)); \
  } while (0)

/* Appends a struct char string field name and string pair to a Tcl list object */
#define Twapi_APPEND_LPCSTR_FIELD_TO_LIST(interp_, listp_, structp_, field_) \
  do { \
    ObjAppendElement((interp_), (listp_), STRING_LITERAL_OBJ( # field_)); \
    ObjAppendElement((interp_),(listp_), ObjFromString(((structp_)->field_ ? (structp_)->field_ : ""))); \
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
 *******************/

/*
 * Type for generating ids. Because they are passed around in windows
 * messages, make them the same size as DWORD_PTR though we would have
 * liked them to be 64 bit even on 32-bit platforms.
 */
typedef DWORD_PTR TwapiId;
#define ObjFromTwapiId ObjFromDWORD_PTR
#define ObjToTwapiId ObjToDWORD_PTR
#define INVALID_TwapiId    0
#define TWAPI_NEWID Twapi_NewId

/* Used to maintain context for common NetEnum* interfaces */
typedef struct _TwapiEnumCtx {
    Tcl_Interp *interp;
    Tcl_Obj    *objP;







|
|
|







606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
 *******************/

/*
 * Type for generating ids. Because they are passed around in windows
 * messages, make them the same size as DWORD_PTR though we would have
 * liked them to be 64 bit even on 32-bit platforms.
 */
typedef LONG_PTR TwapiId;
#define ObjFromTwapiId ObjFromLONG_PTR
#define ObjToTwapiId ObjToLONG_PTR
#define INVALID_TwapiId    0
#define TWAPI_NEWID Twapi_NewId

/* Used to maintain context for common NetEnum* interfaces */
typedef struct _TwapiEnumCtx {
    Tcl_Interp *interp;
    Tcl_Obj    *objP;
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698

699
700
701
702
703
704

705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
    TRT_GUID = 39,  /* Also use for IID, CLSID; string rep differs from TRT_UUID
 */
    TRT_HKEY = 40,
    TRT_TCL_RESULT = 41,             /* Interp result already set. Return ival
                                        field as status */
    TRT_NTSTATUS = 42,
    TRT_LSA_HANDLE = 43,
    TRT_LONG = 44,              /* Signed long */
    TRT_HDEVINFO = 45,
    TRT_PIDL = 46,              /* Freed using CoTaskMemFree */
    TRT_WIDE = 47,              /* Tcl_WideInt */
    TRT_UNICODE_DYNAMIC = 48,     /* Unicode to be freed through TwapiFree */
    TRT_TWAPI_ERROR = 49,          /* TWAPI error code in ival*/
    TRT_HRGN = 50,
    TRT_HMODULE = 51,
    TRT_HMACHINE = 52,
    TRT_CONFIGRET = 53,         /* PnP Manager status (CM_* calls) */
    TRT_GETLASTERROR_SETUPAPI = 54 /* Setup* calls */

} TwapiResultType;

typedef struct {
    TwapiResultType type;
    union {
        long ival;

        unsigned long uval;
        double dval;
        BOOL bval;
        DWORD_PTR dwp;
        Tcl_WideInt wide;
        LPVOID pv;
        HANDLE hval;
        HMODULE hmodule;
        HWND hwin;
        HKEY hkey;
        struct {
            WCHAR *str;
            int    len;         /* len == -1 if str is null terminated */
        } unicode;
        struct {
            char *str;
            int    len;         /* len == -1 if str is null terminated */
        } chars;
        struct {
            char  *p;
            int    len;
        } binary;
        Tcl_Obj *obj;
        struct {
            int nobj;
            Tcl_Obj **objPP;
        } objv;







|









|
>





|
>
|


















|







687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
    TRT_GUID = 39,  /* Also use for IID, CLSID; string rep differs from TRT_UUID
 */
    TRT_HKEY = 40,
    TRT_TCL_RESULT = 41,             /* Interp result already set. Return ival
                                        field as status */
    TRT_NTSTATUS = 42,
    TRT_LSA_HANDLE = 43,
    TRT_INT = 44,
    TRT_HDEVINFO = 45,
    TRT_PIDL = 46,              /* Freed using CoTaskMemFree */
    TRT_WIDE = 47,              /* Tcl_WideInt */
    TRT_UNICODE_DYNAMIC = 48,     /* Unicode to be freed through TwapiFree */
    TRT_TWAPI_ERROR = 49,          /* TWAPI error code in ival*/
    TRT_HRGN = 50,
    TRT_HMODULE = 51,
    TRT_HMACHINE = 52,
    TRT_CONFIGRET = 53,         /* PnP Manager status (CM_* calls) */
    TRT_GETLASTERROR_SETUPAPI = 54, /* Setup* calls */
    TRT_LONG = 55, 
} TwapiResultType;

typedef struct {
    TwapiResultType type;
    union {
        int ival;
        LONG lval;
        DWORD uval;
        double dval;
        BOOL bval;
        DWORD_PTR dwp;
        Tcl_WideInt wide;
        LPVOID pv;
        HANDLE hval;
        HMODULE hmodule;
        HWND hwin;
        HKEY hkey;
        struct {
            WCHAR *str;
            int    len;         /* len == -1 if str is null terminated */
        } unicode;
        struct {
            char *str;
            int    len;         /* len == -1 if str is null terminated */
        } chars;
        struct {
            unsigned char  *p;
            int    len;
        } binary;
        Tcl_Obj *obj;
        struct {
            int nobj;
            Tcl_Obj **objPP;
        } objv;
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
            POINTS message_pos;
            DWORD  ticks;
        } wm_state;             /* Used for Window message notifications
                                   (where there is no response) */
    } ;
} TwapiCallback;

typedef struct _TwapiDS {
    struct _TwapiDS *next;
    Tcl_DString ds;
} TwapiDS;

/*
 * Thread local storage area. This is initialized when the extension
 * is loaded in the thread by an interpreter if no other interpreter
 * in that thread has already done so. It is deallocated when all
 * interps AND TwapiInterpContexts in that thread are deleted. This is
 * tracked through reference counts which are incr/decr'ed whenever







<
<
<
<







961
962
963
964
965
966
967




968
969
970
971
972
973
974
            POINTS message_pos;
            DWORD  ticks;
        } wm_state;             /* Used for Window message notifications
                                   (where there is no response) */
    } ;
} TwapiCallback;






/*
 * Thread local storage area. This is initialized when the extension
 * is loaded in the thread by an interpreter if no other interpreter
 * in that thread has already done so. It is deallocated when all
 * interps AND TwapiInterpContexts in that thread are deleted. This is
 * tracked through reference counts which are incr/decr'ed whenever
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
     * ffiObj points to a Tcl_DictObj that maps the DLL and function
     * to its address. The key is the DLL name/path and function name.
     * The value being the address of the function
     * if found and 0 otherwise.
     */
    Tcl_Obj *ffiObj;

#if (TCL_UTF_MAX > 4)
    /*
     * Encoding and buffer for Tcl_Obj to/from WCHAR translation.
     */
    Tcl_Encoding enc;
    TwapiDS *dsFree, *dsList;
#endif

    int nrefs;                  /* Reference count */

#define TWAPI_TLS_SLOTS 8
    DWORD_PTR slots[TWAPI_TLS_SLOTS];
/* Unsafe access to a slot */
#define TWAPI_TLS_SLOT_UNSAFE(slot_) (Twapi_GetTls()->slots[slot_])
} TwapiTls;







<
<
<
<
<
<
<
<







991
992
993
994
995
996
997








998
999
1000
1001
1002
1003
1004
     * ffiObj points to a Tcl_DictObj that maps the DLL and function
     * to its address. The key is the DLL name/path and function name.
     * The value being the address of the function
     * if found and 0 otherwise.
     */
    Tcl_Obj *ffiObj;









    int nrefs;                  /* Reference count */

#define TWAPI_TLS_SLOTS 8
    DWORD_PTR slots[TWAPI_TLS_SLOTS];
/* Unsafe access to a slot */
#define TWAPI_TLS_SLOT_UNSAFE(slot_) (Twapi_GetTls()->slots[slot_])
} TwapiTls;
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
/* Async handling related */

TWAPI_EXTERN void TwapiEnqueueTclEvent(TwapiInterpContext *ticP, Tcl_Event *evP);
#define TwapiCallbackRef(pcb_, incr_) InterlockedExchangeAdd(&(pcb_)->nrefs, (incr_))
TWAPI_EXTERN void TwapiCallbackUnref(TwapiCallback *pcbP, int);
TWAPI_EXTERN void TwapiCallbackDelete(TwapiCallback *pcbP);
TWAPI_EXTERN TwapiCallback *TwapiCallbackNew(
    TwapiInterpContext *ticP, TwapiCallbackFn *callback, size_t sz);
TWAPI_EXTERN int TwapiEnqueueCallback(
    TwapiInterpContext *ticP, TwapiCallback *pcbP,
    int enqueue_method,
    int timeout,
    TwapiCallback **responseP
    );
#define TWAPI_ENQUEUE_DIRECT 0







|







1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
/* Async handling related */

TWAPI_EXTERN void TwapiEnqueueTclEvent(TwapiInterpContext *ticP, Tcl_Event *evP);
#define TwapiCallbackRef(pcb_, incr_) InterlockedExchangeAdd(&(pcb_)->nrefs, (incr_))
TWAPI_EXTERN void TwapiCallbackUnref(TwapiCallback *pcbP, int);
TWAPI_EXTERN void TwapiCallbackDelete(TwapiCallback *pcbP);
TWAPI_EXTERN TwapiCallback *TwapiCallbackNew(
    TwapiInterpContext *ticP, TwapiCallbackFn *callback, int sz);
TWAPI_EXTERN int TwapiEnqueueCallback(
    TwapiInterpContext *ticP, TwapiCallback *pcbP,
    int enqueue_method,
    int timeout,
    TwapiCallback **responseP
    );
#define TWAPI_ENQUEUE_DIRECT 0
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405

1406

1407


1408
1409

1410

1411
1412
1413
1414
1415
1416

1417
1418
1419
1420
1421
1422
1423










1424
1425
1426
1427
1428
1429





1430


1431
1432
1433
1434





1435


1436
1437
1438
1439
1440
1441
1442
#define VARIANT_REP_VALUE(objP_) ((objP_)->internalRep.ptrAndLongRep.ptr)
#define VARIANT_REP_VT(objP_)  ((objP_)->internalRep.ptrAndLongRep.value)
/* TWAPI-specific hack to indicate contents to be treated as a variable name. */
#define VT_TWAPI_VARNAME (VT_EMPTY|VT_BYREF)

/* The following macros assume objP_ typePtr points to Twapi's gOpaqueType */
#define OPAQUE_REP_VALUE(objP_) ((objP_)->internalRep.twoPtrValue.ptr1)
#define OPAQUE_REP_VALUE_ASSIGN(objP_) (objP_)->internalRep.twoPtrValue.ptr1
#define OPAQUE_REP_CTYPE(objP_)  ((Tcl_Obj *) (objP_)->internalRep.twoPtrValue.ptr2)
#define OPAQUE_REP_CTYPE_ASSIGN(objP_)  ((Tcl_Obj *) (objP_))->internalRep.twoPtrValue.ptr2

TCL_RESULT SetOpaqueFromAny(Tcl_Interp *interp, Tcl_Obj *objP);
TWAPI_EXTERN TCL_RESULT ObjToOpaque(Tcl_Interp *interp, Tcl_Obj *obj, void **pvP, const char *name);
TWAPI_EXTERN TCL_RESULT ObjToOpaqueMulti(Tcl_Interp *interp, Tcl_Obj *obj, void **pvP, int ntypes, char **types);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointer(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerOrNull(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerTic(TwapiInterpContext *, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerOrNullTic(TwapiInterpContext *, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);

TWAPI_EXTERN TCL_RESULT ObjToLPVOID(Tcl_Interp *interp, Tcl_Obj *objP, HANDLE *pvP);
#define ObjToHANDLE ObjToLPVOID
#define ObjToHWND(ip_, obj_, p_) ObjToOpaque((ip_), (obj_), (p_), "HWND")

#define ObjToHMODULE(ip_, obj_, p_) ObjToOpaque((ip_), (obj_), (p_), "HMODULE")

#define ObjToFARPROC(ip_, obj_, p_) ObjToOpaque((ip_), (obj_), (void **)(p_), "FARPROC")



#define ObjFromULONG      ObjFromDWORD

#define ObjToDWORD        ObjToLong


TWAPI_EXTERN Tcl_Obj *ObjFromBoolean(int bval);
TWAPI_EXTERN TCL_RESULT ObjToBoolean(Tcl_Interp *, Tcl_Obj *, int *);
TWAPI_EXTERN Tcl_Obj *ObjFromLong(long val);
#define ObjFromInt ObjFromLong
TWAPI_EXTERN TCL_RESULT ObjToLong(Tcl_Interp *interp, Tcl_Obj *objP, long *lvalP);

#define ObjToInt ObjToLong

TWAPI_EXTERN Tcl_Obj *ObjFromWideInt(Tcl_WideInt val);
/* Unsigneds need to be promoted to wide ints when converting to Tcl_Obj*/
TWAPI_INLINE Tcl_Obj *ObjFromDWORD(DWORD dw) {
    return ObjFromWideInt(dw);
}











TWAPI_EXTERN TCL_RESULT ObjToWideInt(Tcl_Interp *interp, Tcl_Obj *objP, Tcl_WideInt *wideP);
TWAPI_EXTERN Tcl_Obj *ObjFromDouble(double val);
TWAPI_EXTERN TCL_RESULT ObjToDouble(Tcl_Interp *interp, Tcl_Obj *objP, double *);

#ifdef _WIN64





#define ObjToDWORD_PTR        ObjToWideInt


#define ObjFromDWORD_PTR(p_)  ObjFromULONGLONG((ULONGLONG)(p_))
#define ObjToLONG_PTR         ObjToWideInt
#define ObjFromLONG_PTR       ObjFromWideInt
#else  // ! _WIN64





#define ObjToDWORD_PTR        ObjToLong


#define ObjFromDWORD_PTR(p_)  ObjFromDWORD((DWORD_PTR)(p_))
#define ObjToLONG_PTR         ObjToLong
#define ObjFromLONG_PTR       ObjFromLong
#endif // _WIN64
#define ObjToULONG_PTR    ObjToDWORD_PTR
#define ObjFromULONG_PTR  ObjFromDWORD_PTR
#define ObjFromSIZE_T     ObjFromDWORD_PTR







|

|











|
>
|
>
|
>
>
|
|
>
|
>




<
|
>
|






>
>
>
>
>
>
>
>
>
>






>
>
>
>
>
|
>
>




>
>
>
>
>
|
>
>







1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416

1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
#define VARIANT_REP_VALUE(objP_) ((objP_)->internalRep.ptrAndLongRep.ptr)
#define VARIANT_REP_VT(objP_)  ((objP_)->internalRep.ptrAndLongRep.value)
/* TWAPI-specific hack to indicate contents to be treated as a variable name. */
#define VT_TWAPI_VARNAME (VT_EMPTY|VT_BYREF)

/* The following macros assume objP_ typePtr points to Twapi's gOpaqueType */
#define OPAQUE_REP_VALUE(objP_) ((objP_)->internalRep.twoPtrValue.ptr1)
#define OPAQUE_REP_VALUE_SET(objP_) (objP_)->internalRep.twoPtrValue.ptr1
#define OPAQUE_REP_CTYPE(objP_)  ((Tcl_Obj *) (objP_)->internalRep.twoPtrValue.ptr2)
#define OPAQUE_REP_CTYPE_SET(objP_)  ((Tcl_Obj *) (objP_))->internalRep.twoPtrValue.ptr2

TCL_RESULT SetOpaqueFromAny(Tcl_Interp *interp, Tcl_Obj *objP);
TWAPI_EXTERN TCL_RESULT ObjToOpaque(Tcl_Interp *interp, Tcl_Obj *obj, void **pvP, const char *name);
TWAPI_EXTERN TCL_RESULT ObjToOpaqueMulti(Tcl_Interp *interp, Tcl_Obj *obj, void **pvP, int ntypes, char **types);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointer(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerOrNull(Tcl_Interp *interp, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerTic(TwapiInterpContext *, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);
TWAPI_EXTERN TCL_RESULT ObjToVerifiedPointerOrNullTic(TwapiInterpContext *, Tcl_Obj *objP, void **pvP, const char *name, void *verifier);

TWAPI_EXTERN TCL_RESULT ObjToLPVOID(Tcl_Interp *interp, Tcl_Obj *objP, HANDLE *pvP);
#define ObjToHANDLE ObjToLPVOID

TWAPI_INLINE TCL_RESULT ObjToHWND(Tcl_Interp *ip, Tcl_Obj *objP, HWND *pvP) {
    return ObjToOpaque(ip, objP, (void **)pvP, "HWND");
}        

TWAPI_INLINE TCL_RESULT ObjToHMODULE(Tcl_Interp *ip, Tcl_Obj *objP, HMODULE *pvP) {
    return ObjToOpaque(ip, objP, (void **)pvP, "HMODULE");
}        

TWAPI_INLINE TCL_RESULT ObjToFARPROC(Tcl_Interp *ip, Tcl_Obj *objP, FARPROC *pvP) {
    return ObjToOpaque(ip, objP, (void **)pvP, "FARPROC");
}        

TWAPI_EXTERN Tcl_Obj *ObjFromBoolean(int bval);
TWAPI_EXTERN TCL_RESULT ObjToBoolean(Tcl_Interp *, Tcl_Obj *, int *);
TWAPI_EXTERN Tcl_Obj *ObjFromLong(long val);

TWAPI_EXTERN TCL_RESULT ObjToLong(Tcl_Interp *interp, Tcl_Obj *objP, long *);
TWAPI_EXTERN Tcl_Obj *ObjFromInt(int val);
TWAPI_EXTERN TCL_RESULT ObjToInt(Tcl_Interp *interp, Tcl_Obj *objP, int *);

TWAPI_EXTERN Tcl_Obj *ObjFromWideInt(Tcl_WideInt val);
/* Unsigneds need to be promoted to wide ints when converting to Tcl_Obj*/
TWAPI_INLINE Tcl_Obj *ObjFromDWORD(DWORD dw) {
    return ObjFromWideInt(dw);
}
TWAPI_INLINE TCL_RESULT ObjToDWORD(Tcl_Interp *interp, Tcl_Obj *objP, DWORD *dwP) {
    long l;
    /* TBD - should we convert to Tcl_WideInt and check the range?
       How much code depends on silent long<->unsigned long conversions? */
    TCL_RESULT res = ObjToLong(interp, objP, &l);
    if (res == TCL_OK)
        *dwP = (DWORD) l;
    return res;
}
#define ObjFromULONG      ObjFromDWORD

TWAPI_EXTERN TCL_RESULT ObjToWideInt(Tcl_Interp *interp, Tcl_Obj *objP, Tcl_WideInt *wideP);
TWAPI_EXTERN Tcl_Obj *ObjFromDouble(double val);
TWAPI_EXTERN TCL_RESULT ObjToDouble(Tcl_Interp *interp, Tcl_Obj *objP, double *);

#ifdef _WIN64
/* Define as a function to avoid gcc squawking about signed pointers */
TWAPI_INLINE TCL_RESULT ObjToDWORD_PTR(Tcl_Interp *interp, Tcl_Obj *objP, DWORD_PTR *dwP) {
    Tcl_WideInt wide;
    TCL_RESULT res = ObjToWideInt(interp, objP, &wide);
    if (res == TCL_OK)
        *dwP = (DWORD_PTR) wide;
    return res;
}
#define ObjFromDWORD_PTR(p_)  ObjFromULONGLONG((ULONGLONG)(p_))
#define ObjToLONG_PTR         ObjToWideInt
#define ObjFromLONG_PTR       ObjFromWideInt
#else  // ! _WIN64
/* Define as a function to avoid gcc squawking about signed pointers */
TWAPI_INLINE TCL_RESULT ObjToDWORD_PTR(Tcl_Interp *interp, Tcl_Obj *objP, DWORD_PTR *dwP) {
    DWORD dw;
    TCL_RESULT res = ObjToDWORD(interp, objP, &dw);
    if (res == TCL_OK)
        *dwP = (DWORD_PTR) dw;
    return res;
}
#define ObjFromDWORD_PTR(p_)  ObjFromDWORD((DWORD_PTR)(p_))
#define ObjToLONG_PTR         ObjToLong
#define ObjFromLONG_PTR       ObjFromLong
#endif // _WIN64
#define ObjToULONG_PTR    ObjToDWORD_PTR
#define ObjFromULONG_PTR  ObjFromDWORD_PTR
#define ObjFromSIZE_T     ObjFromDWORD_PTR
1450
1451
1452
1453
1454
1455
1456






1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482

1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
#define ObjFromLARGE_INTEGER(val_) ObjFromWideInt((val_).QuadPart)
TWAPI_EXTERN Tcl_Obj *ObjFromULONGLONG(ULONGLONG ull);

TWAPI_EXTERN Tcl_Obj *ObjFromUCHARHex(UCHAR);
TWAPI_EXTERN Tcl_Obj *ObjFromUSHORTHex(USHORT);
TWAPI_EXTERN Tcl_Obj *ObjFromULONGHex(ULONG ull);
TWAPI_EXTERN Tcl_Obj *ObjFromULONGLONGHex(ULONGLONG ull);







TWAPI_EXTERN char *ObjToString(Tcl_Obj *objP);
TWAPI_EXTERN char *ObjToStringN(Tcl_Obj *objP, int *lenP);
#if (TCL_UTF_MAX > 4)
TWAPI_EXTERN void ObjToUnicodeCleanup(void);
#else
#define ObjToUnicodeCleanup()
#endif
TWAPI_EXTERN WCHAR *ObjToUnicode(Tcl_Obj *objP);
TWAPI_EXTERN WCHAR *ObjToUnicodeN(Tcl_Obj *objP, int *lenP);
TWAPI_EXTERN int TwapiWCHARToUtf8(CONST WCHAR *wsP, int nchars, char *buf, int buf_sz);
TWAPI_EXTERN Tcl_Obj *TwapiUtf8ObjFromUnicode(CONST WCHAR *p, int len);
TWAPI_EXTERN Tcl_Obj *ObjFromEmptyString();
TWAPI_EXTERN Tcl_Obj *ObjFromUnicodeN(const WCHAR *ws, int len);
TWAPI_EXTERN Tcl_Obj *ObjFromUnicode(const WCHAR *ws);
TWAPI_EXTERN Tcl_Obj *ObjFromStringN(const char *s, int len);
TWAPI_EXTERN Tcl_Obj *ObjFromString(const char *s);
TWAPI_EXTERN int ObjCharLength(Tcl_Obj *);
TWAPI_EXTERN Tcl_Obj *ObjFromStringLimited(const char *strP, int max, int *remain);
TWAPI_EXTERN Tcl_Obj *ObjFromUnicodeLimited(const WCHAR *wstrP, int max, int *remain);
TWAPI_EXTERN Tcl_Obj *ObjFromUnicodeNoTrailingSpace(const WCHAR *strP);

TWAPI_EXTERN Tcl_Obj *ObjFromByteArray(const unsigned char *bytes, int len);
TWAPI_EXTERN Tcl_Obj *ObjAllocateByteArray(int len, void **);
TWAPI_EXTERN Tcl_Obj *ObjFromByteArrayHex(const unsigned char *bytes, int len);
TWAPI_EXTERN unsigned char *ObjToByteArray(Tcl_Obj *objP, int *lenP);


TWAPI_EXTERN TCL_RESULT TwapiEncryptData(Tcl_Interp *, BYTE *, int, BYTE *, int *);
TWAPI_EXTERN TCL_RESULT TwapiDecryptData(Tcl_Interp *, BYTE *, int , BYTE *, int *);
TWAPI_EXTERN BYTE *TwapiDecryptDataSWS(Tcl_Interp *, BYTE *, int , int *);
TWAPI_EXTERN Tcl_Obj *ObjEncryptBytes(Tcl_Interp *, void *, int);
TWAPI_EXTERN void *ObjDecryptBytesExSWS(Tcl_Interp *, Tcl_Obj *, int, int *);
TWAPI_EXTERN Tcl_Obj *ObjEncryptUnicode(Tcl_Interp *, WCHAR *, int);
TWAPI_EXTERN WCHAR * ObjDecryptUnicodeSWS(Tcl_Interp *, Tcl_Obj *, int *);
TWAPI_EXTERN char * ObjDecryptUtf8SWS(Tcl_Interp *, Tcl_Obj *, int *);
TWAPI_EXTERN WCHAR * ObjDecryptPasswordSWS(Tcl_Obj *objP, int *ncharsP);

TWAPI_EXTERN Tcl_Obj *ObjFromLSA_UNICODE_STRING(const LSA_UNICODE_STRING *lsauniP);
TWAPI_EXTERN void ObjToLSA_UNICODE_STRING(Tcl_Obj *objP, LSA_UNICODE_STRING *lsauniP);
TWAPI_EXTERN int ObjToLSASTRINGARRAYSWS(Tcl_Interp *interp, Tcl_Obj *obj,
                        LSA_UNICODE_STRING **arrayP, ULONG *countP);







>
>
>
>
>
>



|
|
|
|
<
|
|
<
|
|
|
|
<
|
<
<
<
<





>






|
|







1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495

1496
1497

1498
1499
1500
1501

1502




1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
#define ObjFromLARGE_INTEGER(val_) ObjFromWideInt((val_).QuadPart)
TWAPI_EXTERN Tcl_Obj *ObjFromULONGLONG(ULONGLONG ull);

TWAPI_EXTERN Tcl_Obj *ObjFromUCHARHex(UCHAR);
TWAPI_EXTERN Tcl_Obj *ObjFromUSHORTHex(USHORT);
TWAPI_EXTERN Tcl_Obj *ObjFromULONGHex(ULONG ull);
TWAPI_EXTERN Tcl_Obj *ObjFromULONGLONGHex(ULONGLONG ull);

TWAPI_EXTERN int TwapiWinCharsToUtf8(CONST WCHAR *wsP, int nchars, char *buf, int buf_sz);
TWAPI_EXTERN Tcl_Obj *TwapiUtf8ObjFromWinChars(CONST WCHAR *p, int len);

TWAPI_EXTERN Tcl_Obj *ObjFromEmptyString();
TWAPI_EXTERN int ObjCharLength(Tcl_Obj *);

TWAPI_EXTERN char *ObjToString(Tcl_Obj *objP);
TWAPI_EXTERN char *ObjToStringN(Tcl_Obj *objP, int *lenP);
TWAPI_EXTERN Tcl_Obj *ObjFromStringN(const char *s, int len);
TWAPI_EXTERN Tcl_Obj *ObjFromString(const char *s);
TWAPI_EXTERN Tcl_Obj *ObjFromStringLimited(const char *strP, int max, int *remain);


TWAPI_EXTERN WCHAR *ObjToWinChars(Tcl_Obj *objP);
TWAPI_EXTERN WCHAR *ObjToWinCharsN(Tcl_Obj *objP, int *lenP);

TWAPI_EXTERN WCHAR *ObjToWinCharsNDW(Tcl_Obj *objP, DWORD *lenP);
TWAPI_EXTERN Tcl_Obj *ObjFromWinCharsN(const WCHAR *ws, int len);
TWAPI_EXTERN Tcl_Obj *ObjFromWinChars(const WCHAR *ws);
TWAPI_EXTERN Tcl_Obj *ObjFromWinCharsLimited(const WCHAR *wstrP, int max, int *remain);

TWAPI_EXTERN Tcl_Obj *ObjFromWinCharsNoTrailingSpace(const WCHAR *strP);





TWAPI_EXTERN Tcl_Obj *ObjFromByteArray(const unsigned char *bytes, int len);
TWAPI_EXTERN Tcl_Obj *ObjAllocateByteArray(int len, void **);
TWAPI_EXTERN Tcl_Obj *ObjFromByteArrayHex(const unsigned char *bytes, int len);
TWAPI_EXTERN unsigned char *ObjToByteArray(Tcl_Obj *objP, int *lenP);
TWAPI_EXTERN unsigned char *ObjToByteArrayDW(Tcl_Obj *objP, DWORD *lenP);

TWAPI_EXTERN TCL_RESULT TwapiEncryptData(Tcl_Interp *, BYTE *, int, BYTE *, int *);
TWAPI_EXTERN TCL_RESULT TwapiDecryptData(Tcl_Interp *, BYTE *, int , BYTE *, int *);
TWAPI_EXTERN BYTE *TwapiDecryptDataSWS(Tcl_Interp *, BYTE *, int , int *);
TWAPI_EXTERN Tcl_Obj *ObjEncryptBytes(Tcl_Interp *, void *, int);
TWAPI_EXTERN void *ObjDecryptBytesExSWS(Tcl_Interp *, Tcl_Obj *, int, int *);
TWAPI_EXTERN Tcl_Obj *ObjEncryptWinChars(Tcl_Interp *, WCHAR *, int);
TWAPI_EXTERN WCHAR * ObjDecryptWinCharsSWS(Tcl_Interp *, Tcl_Obj *, int *);
TWAPI_EXTERN char * ObjDecryptUtf8SWS(Tcl_Interp *, Tcl_Obj *, int *);
TWAPI_EXTERN WCHAR * ObjDecryptPasswordSWS(Tcl_Obj *objP, int *ncharsP);

TWAPI_EXTERN Tcl_Obj *ObjFromLSA_UNICODE_STRING(const LSA_UNICODE_STRING *lsauniP);
TWAPI_EXTERN void ObjToLSA_UNICODE_STRING(Tcl_Obj *objP, LSA_UNICODE_STRING *lsauniP);
TWAPI_EXTERN int ObjToLSASTRINGARRAYSWS(Tcl_Interp *interp, Tcl_Obj *obj,
                        LSA_UNICODE_STRING **arrayP, ULONG *countP);
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
TWAPI_EXTERN Tcl_Obj *ObjFromLUID (const LUID *luidP);
TWAPI_EXTERN int ObjToLUID(Tcl_Interp *interp, Tcl_Obj *objP, LUID *luidP);
TWAPI_EXTERN int ObjToLUID_NULL(Tcl_Interp *interp, Tcl_Obj *objP, LUID **luidPP);

/* Network stuff */
TWAPI_EXTERN Tcl_Obj *IPAddrObjFromDWORD(DWORD addr);
TWAPI_EXTERN int IPAddrObjToDWORD(Tcl_Interp *interp, Tcl_Obj *objP, DWORD *addrP);
TWAPI_EXTERN Tcl_Obj *ObjFromIPv6Addr(const char *addrP, DWORD scope_id);
TWAPI_EXTERN Tcl_Obj *ObjFromIP_ADDR_STRING (Tcl_Interp *, const IP_ADDR_STRING *ipaddrstrP);
TWAPI_EXTERN Tcl_Obj *ObjFromSOCKADDR_address(SOCKADDR *saP);
TWAPI_EXTERN Tcl_Obj *ObjFromSOCKADDR(SOCKADDR *saP);


/* Security stuff */
#define TWAPI_SID_LENGTH(sid_) GetSidLengthRequired((sid_)->SubAuthorityCount)







|







1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
TWAPI_EXTERN Tcl_Obj *ObjFromLUID (const LUID *luidP);
TWAPI_EXTERN int ObjToLUID(Tcl_Interp *interp, Tcl_Obj *objP, LUID *luidP);
TWAPI_EXTERN int ObjToLUID_NULL(Tcl_Interp *interp, Tcl_Obj *objP, LUID **luidPP);

/* Network stuff */
TWAPI_EXTERN Tcl_Obj *IPAddrObjFromDWORD(DWORD addr);
TWAPI_EXTERN int IPAddrObjToDWORD(Tcl_Interp *interp, Tcl_Obj *objP, DWORD *addrP);
TWAPI_EXTERN Tcl_Obj *ObjFromIPv6Addr(const BYTE *addrP, DWORD scope_id);
TWAPI_EXTERN Tcl_Obj *ObjFromIP_ADDR_STRING (Tcl_Interp *, const IP_ADDR_STRING *ipaddrstrP);
TWAPI_EXTERN Tcl_Obj *ObjFromSOCKADDR_address(SOCKADDR *saP);
TWAPI_EXTERN Tcl_Obj *ObjFromSOCKADDR(SOCKADDR *saP);


/* Security stuff */
#define TWAPI_SID_LENGTH(sid_) GetSidLengthRequired((sid_)->SubAuthorityCount)
Changes to undroid/twapi/twapi/input/input.c.
214
215
216
217
218
219
220

221




222
223
224
225
226
227
228

    /* NUmber of events is twice number of chars (keydown + keyup) */
    max_input_records = 2 * num_chars;
    input = MemLifoAlloc(ticP->memlifoP, max_input_records * sizeof(*input), NULL);
    for (i = 0, j = 0; i < num_chars; ++i) {
        WCHAR wch;
            

        wch = Tcl_GetUniChar(input_obj, i);




#ifndef KEYEVENTF_UNICODE
#define KEYEVENTF_UNICODE     0x0004
#endif
        init_keyboard_input(&input[j], 0, KEYEVENTF_UNICODE);
        input[j].ki.wScan = wch;
        ++j;
        init_keyboard_input(&input[j], 0, KEYEVENTF_UNICODE|KEYEVENTF_KEYUP);







>

>
>
>
>







214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

    /* NUmber of events is twice number of chars (keydown + keyup) */
    max_input_records = 2 * num_chars;
    input = MemLifoAlloc(ticP->memlifoP, max_input_records * sizeof(*input), NULL);
    for (i = 0, j = 0; i < num_chars; ++i) {
        WCHAR wch;
            
#if TCL_UTF_MAX <= 4
        wch = Tcl_GetUniChar(input_obj, i);
#else
        wch = (WCHAR) Tcl_GetUniChar(input_obj, i);
#endif

#ifndef KEYEVENTF_UNICODE
#define KEYEVENTF_UNICODE     0x0004
#endif
        init_keyboard_input(&input[j], 0, KEYEVENTF_UNICODE);
        input[j].ki.wScan = wch;
        ++j;
        init_keyboard_input(&input[j], 0, KEYEVENTF_UNICODE|KEYEVENTF_KEYUP);
262
263
264
265
266
267
268
269
270

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
    pin->ki.wVk     = vkey;
    pin->ki.wScan   = 0;
    pin->ki.dwFlags = flags;
    pin->ki.time    = 0;
    pin->ki.dwExtraInfo = 0;
}

static int Twapi_InputCallObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{

    int func;
    DWORD dw, dw2, dw3;
    LASTINPUTINFO lastin;
    TwapiResult result;
    WCHAR kl[KL_NAMELENGTH+1];

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:







|

>






<
<







267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282


283
284
285
286
287
288
289
    pin->ki.wVk     = vkey;
    pin->ki.wScan   = 0;
    pin->ki.dwFlags = flags;
    pin->ki.time    = 0;
    pin->ki.dwExtraInfo = 0;
}

static int Twapi_InputCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    TwapiInterpContext *ticP = (TwapiInterpContext*) clientdata;
    int func;
    DWORD dw, dw2, dw3;
    LASTINPUTINFO lastin;
    TwapiResult result;
    WCHAR kl[KL_NAMELENGTH+1];



    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
Changes to undroid/twapi/twapi/mstask/mstask.c.
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wEndDay);
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wStartHour);
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wStartMinute);
    Twapi_APPEND_DWORD_FIELD_TO_LIST(NULL, resultObj, triggerP, MinutesDuration);
    Twapi_APPEND_DWORD_FIELD_TO_LIST(NULL, resultObj, triggerP, MinutesInterval);
    Twapi_APPEND_DWORD_FIELD_TO_LIST(NULL, resultObj, triggerP, rgFlags);

    ntype = 1;
    typeObj[0] = ObjFromInt(triggerP->TriggerType);

    switch (triggerP->TriggerType) {
    case 1:
        typeObj[1] = ObjFromInt(triggerP->Type.Daily.DaysInterval);
        ntype = 2;
        break;







<







51
52
53
54
55
56
57

58
59
60
61
62
63
64
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wEndDay);
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wStartHour);
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wStartMinute);
    Twapi_APPEND_DWORD_FIELD_TO_LIST(NULL, resultObj, triggerP, MinutesDuration);
    Twapi_APPEND_DWORD_FIELD_TO_LIST(NULL, resultObj, triggerP, MinutesInterval);
    Twapi_APPEND_DWORD_FIELD_TO_LIST(NULL, resultObj, triggerP, rgFlags);


    typeObj[0] = ObjFromInt(triggerP->TriggerType);

    switch (triggerP->TriggerType) {
    case 1:
        typeObj[1] = ObjFromInt(triggerP->Type.Daily.DaysInterval);
        ntype = 2;
        break;
74
75
76
77
78
79
80



81
82
83
84
85
86
87
        ntype = 3;
        break;
    case 4:
        typeObj[1] = ObjFromInt(triggerP->Type.MonthlyDOW.wWhichWeek);
        typeObj[2] = ObjFromInt(triggerP->Type.MonthlyDOW.rgfDaysOfTheWeek);
        typeObj[3] = ObjFromInt(triggerP->Type.MonthlyDOW.rgfMonths);
        ntype = 4;



        break;
    }
    ObjAppendElement(NULL, resultObj, STRING_LITERAL_OBJ("type"));
    ObjAppendElement(NULL, resultObj, ObjNewList(ntype, typeObj));

    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, Reserved2);
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wRandomMinutesInterval);







>
>
>







73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        ntype = 3;
        break;
    case 4:
        typeObj[1] = ObjFromInt(triggerP->Type.MonthlyDOW.wWhichWeek);
        typeObj[2] = ObjFromInt(triggerP->Type.MonthlyDOW.rgfDaysOfTheWeek);
        typeObj[3] = ObjFromInt(triggerP->Type.MonthlyDOW.rgfMonths);
        ntype = 4;
        break;
    default: /* TBD - TASK_EVENT_TRIGGER_ON_IDLE,AT_SYSTEMSTART,AT_LOGON etc. */
        ntype = 1;
        break;
    }
    ObjAppendElement(NULL, resultObj, STRING_LITERAL_OBJ("type"));
    ObjAppendElement(NULL, resultObj, ObjNewList(ntype, typeObj));

    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, Reserved2);
    Twapi_APPEND_LONG_FIELD_TO_LIST(NULL, resultObj, triggerP, wRandomMinutesInterval);
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
                return TCL_ERROR;
        }
        else if (STREQ(name, "wStartMinute")) {
            if (ObjToWord(interp, objv[i+1], &triggerP->wStartMinute) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "MinutesDuration")) {
            if (ObjToLong(interp, objv[i+1], &triggerP->MinutesDuration) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "MinutesInterval")) {
            if (ObjToLong(interp, objv[i+1], &triggerP->MinutesInterval) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "rgFlags")) {
            if (ObjToLong(interp, objv[i+1], &triggerP->rgFlags) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "Reserved2")) {
            if (ObjToWord(interp, objv[i+1], &triggerP->Reserved2) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "wRandomMinutesInterval")) {







|



|



|







145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
                return TCL_ERROR;
        }
        else if (STREQ(name, "wStartMinute")) {
            if (ObjToWord(interp, objv[i+1], &triggerP->wStartMinute) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "MinutesDuration")) {
            if (ObjToDWORD(interp, objv[i+1], &triggerP->MinutesDuration) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "MinutesInterval")) {
            if (ObjToDWORD(interp, objv[i+1], &triggerP->MinutesInterval) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "rgFlags")) {
            if (ObjToDWORD(interp, objv[i+1], &triggerP->rgFlags) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "Reserved2")) {
            if (ObjToWord(interp, objv[i+1], &triggerP->Reserved2) != TCL_OK)
                return TCL_ERROR;
        }
        else if (STREQ(name, "wRandomMinutesInterval")) {
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223



224
225
226
227
228
229
230
                if (ObjToWord(interp, typeObj[2], &triggerP->Type.Weekly.rgfDaysOfTheWeek) != TCL_OK)
                    goto trigger_type_count_error;
                break;

            case 3:
                if (ntype != 3)
                    goto trigger_type_count_error;
                if (ObjToLong(interp, typeObj[1], &triggerP->Type.MonthlyDate.rgfDays) != TCL_OK)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[2], &triggerP->Type.MonthlyDate.rgfMonths) != TCL_OK)
                    goto trigger_type_count_error;
                break;

            case 4:
                if (ntype != 4)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[1], &triggerP->Type.MonthlyDOW.wWhichWeek) != TCL_OK)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[2], &triggerP->Type.MonthlyDOW.rgfDaysOfTheWeek) != TCL_OK)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[3], &triggerP->Type.MonthlyDOW.rgfMonths) != TCL_OK)
                    goto trigger_type_count_error;
                break;



            }
        }
        else {
            Tcl_AppendResult(interp, "Unknown TASK_TRIGGER field '", name, "'", NULL);
            return TCL_ERROR;
        }
    }







|















>
>
>







203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
                if (ObjToWord(interp, typeObj[2], &triggerP->Type.Weekly.rgfDaysOfTheWeek) != TCL_OK)
                    goto trigger_type_count_error;
                break;

            case 3:
                if (ntype != 3)
                    goto trigger_type_count_error;
                if (ObjToDWORD(interp, typeObj[1], &triggerP->Type.MonthlyDate.rgfDays) != TCL_OK)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[2], &triggerP->Type.MonthlyDate.rgfMonths) != TCL_OK)
                    goto trigger_type_count_error;
                break;

            case 4:
                if (ntype != 4)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[1], &triggerP->Type.MonthlyDOW.wWhichWeek) != TCL_OK)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[2], &triggerP->Type.MonthlyDOW.rgfDaysOfTheWeek) != TCL_OK)
                    goto trigger_type_count_error;
                if (ObjToWord(interp, typeObj[3], &triggerP->Type.MonthlyDOW.rgfMonths) != TCL_OK)
                    goto trigger_type_count_error;
                break;
            default: /* TBD - additional types TASK_TIME_TRIFFER_ONCE,ON_IDLE,AT_SYSTEMSTART etc.*/
                ObjSetStaticResult(interp, "Unknown or unsupported trigger type.");
                return TCL_ERROR;
            }
        }
        else {
            Tcl_AppendResult(interp, "Unknown TASK_TRIGGER field '", name, "'", NULL);
            return TCL_ERROR;
        }
    }
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    }

    objv[0] = ObjFromBoolean(hr == S_OK); // More to come?
    objv[1] = ObjNewList(0, NULL);
    if (jobsP) {
        for (i = 0; i < ret_count; ++i) {
            ObjAppendElement(interp, objv[1],
                                     ObjFromUnicode(jobsP[i]));
            /* Free the string */
            CoTaskMemFree(jobsP[i]);
        }
        /* Free the array itself */
        CoTaskMemFree(jobsP);
    }    








|







267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    }

    objv[0] = ObjFromBoolean(hr == S_OK); // More to come?
    objv[1] = ObjNewList(0, NULL);
    if (jobsP) {
        for (i = 0; i < ret_count; ++i) {
            ObjAppendElement(interp, objv[1],
                                     ObjFromWinChars(jobsP[i]));
            /* Free the string */
            CoTaskMemFree(jobsP[i]);
        }
        /* Free the array itself */
        CoTaskMemFree(jobsP);
    }    

373
374
375
376
377
378
379

380
381
382
383
384
385
386
387
388
389
390
    Tcl_Obj *sObj;
    WORD w, w2;
    Tcl_Obj *objs[4];
    SYSTEMTIME systime, systime2;
    TASK_TRIGGER tasktrigger;
    int func = PtrToInt(clientdata);
    WCHAR *s, *passwordP;

    SWSMark mark = NULL;

    ObjToUnicodeCleanup();

    hr = S_OK;
    result.type = TRT_BADFUNCTIONCODE;

    if (TwapiGetArgs(interp, objc-1, objv+1, GETVOIDP(pv), ARGTERM) != TCL_OK)
        return TCL_ERROR;

    if (pv == NULL) {







>


<
<







378
379
380
381
382
383
384
385
386
387


388
389
390
391
392
393
394
    Tcl_Obj *sObj;
    WORD w, w2;
    Tcl_Obj *objs[4];
    SYSTEMTIME systime, systime2;
    TASK_TRIGGER tasktrigger;
    int func = PtrToInt(clientdata);
    WCHAR *s, *passwordP;
    int i;
    SWSMark mark = NULL;



    hr = S_OK;
    result.type = TRT_BADFUNCTIONCODE;

    if (TwapiGetArgs(interp, objc-1, objv+1, GETVOIDP(pv), ARGTERM) != TCL_OK)
        return TCL_ERROR;

    if (pv == NULL) {
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETVAR(guid, ObjToGUID),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IUnknown";
            hr = ifc.taskscheduler->lpVtbl->Activate(
                ifc.taskscheduler,   ObjToUnicode(sObj),   &guid,
                (IUnknown **) &result.value.ifc.p);
            break;
        case 5002: // AddWorkItem
            if (objc != 3)
                goto badargs;
            if (ObjToOpaque(interp, objv[2], &pv, "IScheduledWorkItem") != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = ifc.taskscheduler->lpVtbl->AddWorkItem(
                ifc.taskscheduler,
                ObjToUnicode(objv[1]),
                (IScheduledWorkItem *) pv );
            break;
        case 5003: // Delete
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.taskscheduler->lpVtbl->Delete(ifc.taskscheduler,
                                                   ObjToUnicode(objv[1]));
            break;
        case 5004: // Enum
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IEnumWorkItems";
            hr = ifc.taskscheduler->lpVtbl->Enum(
                ifc.taskscheduler,
                (IEnumWorkItems **) &result.value.ifc.p);
            break;
        case 5005: // IsOfType
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETVAR(guid, ObjToGUID),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_BOOL;
            result.value.bval = ifc.taskscheduler->lpVtbl->IsOfType(
                ifc.taskscheduler, ObjToUnicode(sObj), &guid) == S_OK;
            break;
        case 5006: // NewWorkItem
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj),
                             GETGUID(guid), GETGUID(guid2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IUnknown";
            hr = ifc.taskscheduler->lpVtbl->NewWorkItem(
                ifc.taskscheduler, ObjToUnicode(sObj), &guid, &guid2,
                (IUnknown **) &result.value.ifc.p);
            break;
        case 5007: // SetTargetComputer
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.taskscheduler->lpVtbl->SetTargetComputer(







|










|







|















|










|







413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETVAR(guid, ObjToGUID),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IUnknown";
            hr = ifc.taskscheduler->lpVtbl->Activate(
                ifc.taskscheduler,   ObjToWinChars(sObj),   &guid,
                (IUnknown **) &result.value.ifc.p);
            break;
        case 5002: // AddWorkItem
            if (objc != 3)
                goto badargs;
            if (ObjToOpaque(interp, objv[2], &pv, "IScheduledWorkItem") != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
            hr = ifc.taskscheduler->lpVtbl->AddWorkItem(
                ifc.taskscheduler,
                ObjToWinChars(objv[1]),
                (IScheduledWorkItem *) pv );
            break;
        case 5003: // Delete
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.taskscheduler->lpVtbl->Delete(ifc.taskscheduler,
                                                   ObjToWinChars(objv[1]));
            break;
        case 5004: // Enum
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IEnumWorkItems";
            hr = ifc.taskscheduler->lpVtbl->Enum(
                ifc.taskscheduler,
                (IEnumWorkItems **) &result.value.ifc.p);
            break;
        case 5005: // IsOfType
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj), GETVAR(guid, ObjToGUID),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_BOOL;
            result.value.bval = ifc.taskscheduler->lpVtbl->IsOfType(
                ifc.taskscheduler, ObjToWinChars(sObj), &guid) == S_OK;
            break;
        case 5006: // NewWorkItem
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETOBJ(sObj),
                             GETGUID(guid), GETGUID(guid2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_INTERFACE;
            result.value.ifc.name = "IUnknown";
            hr = ifc.taskscheduler->lpVtbl->NewWorkItem(
                ifc.taskscheduler, ObjToWinChars(sObj), &guid, &guid2,
                (IUnknown **) &result.value.ifc.p);
            break;
        case 5007: // SetTargetComputer
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.taskscheduler->lpVtbl->SetTargetComputer(
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.enumworkitems->lpVtbl->Reset(ifc.enumworkitems);
            break;
        case 5103: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumworkitems->lpVtbl->Skip(ifc.enumworkitems, dw1);
            break;
        case 5104: // Next
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            return Twapi_IEnumWorkItems_Next(interp,ifc.enumworkitems,dw1);
        }
    } else if (func < 5300) {
        /* IScheduledWorkItem - ITask inherits from this and is also allowed */
        char *allowed_types[] = {"ITask", "IScheduledWorkItem"};

        if (ObjToOpaqueMulti(interp, objv[0], (void **)&ifc.scheduledworkitem,







|






|







501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.enumworkitems->lpVtbl->Reset(ifc.enumworkitems);
            break;
        case 5103: // Skip
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.enumworkitems->lpVtbl->Skip(ifc.enumworkitems, dw1);
            break;
        case 5104: // Next
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            return Twapi_IEnumWorkItems_Next(interp,ifc.enumworkitems,dw1);
        }
    } else if (func < 5300) {
        /* IScheduledWorkItem - ITask inherits from this and is also allowed */
        char *allowed_types[] = {"ITask", "IScheduledWorkItem"};

        if (ObjToOpaqueMulti(interp, objv[0], (void **)&ifc.scheduledworkitem,
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
                ifc.scheduledworkitem, &result.value.systime);
            break;
        case 5214: // GetStatus
            if (objc != 1)
                goto badargs;
            result.type = TRT_LONG;
            hr = ifc.scheduledworkitem->lpVtbl->GetStatus(
                ifc.scheduledworkitem, &result.value.ival);
            break;
        case 5215: // GetTrigger
            if (objc != 2)
                goto badargs;
            if (ObjToWord(interp, objv[1], &w) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_INTERFACE;







|







635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
                ifc.scheduledworkitem, &result.value.systime);
            break;
        case 5214: // GetStatus
            if (objc != 1)
                goto badargs;
            result.type = TRT_LONG;
            hr = ifc.scheduledworkitem->lpVtbl->GetStatus(
                ifc.scheduledworkitem, &result.value.uval);
            break;
        case 5215: // GetTrigger
            if (objc != 2)
                goto badargs;
            if (ObjToWord(interp, objv[1], &w) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_INTERFACE;
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
            if (objc != 1)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->Run(ifc.scheduledworkitem);
            break;
        case 5219: // SetAccountInformation
            CHECK_NARGS_RANGE(interp, objc, 2, 3);
            s = ObjToUnicode(objv[1]);
            if (objc == 2 || s[0] == 0)
                passwordP = NULL;
            else {
                mark = SWSPushMark();
                passwordP = ObjDecryptPasswordSWS(objv[2], &dw1);
            }
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetAccountInformation(
                ifc.scheduledworkitem, s, passwordP);
            if (mark) {
                SecureZeroMemory(passwordP, dw1);
                SWSPopMark(mark);
            }
            break;
        case 5220: // SetComment
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetComment(
                ifc.scheduledworkitem, ObjToUnicode(objv[1]));
            break;
        case 5221: // SetCreator
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetCreator(
                ifc.scheduledworkitem, ObjToUnicode(objv[1]));
            break;
        case 5222: // SetErrorRetryCount
            if (objc != 2)
                goto badargs;
            if (ObjToWord(interp, objv[1], &w) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;







|




|





|








|






|







672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
            if (objc != 1)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->Run(ifc.scheduledworkitem);
            break;
        case 5219: // SetAccountInformation
            CHECK_NARGS_RANGE(interp, objc, 2, 3);
            s = ObjToWinChars(objv[1]);
            if (objc == 2 || s[0] == 0)
                passwordP = NULL;
            else {
                mark = SWSPushMark();
                passwordP = ObjDecryptPasswordSWS(objv[2], &i);
            }
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetAccountInformation(
                ifc.scheduledworkitem, s, passwordP);
            if (mark) {
                SecureZeroMemory(passwordP, i);
                SWSPopMark(mark);
            }
            break;
        case 5220: // SetComment
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetComment(
                ifc.scheduledworkitem, ObjToWinChars(objv[1]));
            break;
        case 5221: // SetCreator
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetCreator(
                ifc.scheduledworkitem, ObjToWinChars(objv[1]));
            break;
        case 5222: // SetErrorRetryCount
            if (objc != 2)
                goto badargs;
            if (ObjToWord(interp, objv[1], &w) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EMPTY;
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetErrorRetryInterval(
                ifc.scheduledworkitem, w);
            break;
        case 5224: // SetFlags
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetFlags(
                ifc.scheduledworkitem, dw1);
            break;
        case 5225: // SetIdleWait
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETWORD(w), GETWORD(w2),







|







722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetErrorRetryInterval(
                ifc.scheduledworkitem, w);
            break;
        case 5224: // SetFlags
            if (objc != 2)
                goto badargs;
            CHECK_DWORD_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.scheduledworkitem->lpVtbl->SetFlags(
                ifc.scheduledworkitem, dw1);
            break;
        case 5225: // SetIdleWait
            if (TwapiGetArgs(interp, objc-1, objv+1,
                             GETWORD(w), GETWORD(w2),
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
                ifc.task, &result.value.lpolestr);
            break;
        case 5307: // SetApplicationName
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetApplicationName(
                ifc.task, ObjToUnicode(objv[1]));
            break;
        case 5308: // SetParameters
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetParameters(
                ifc.task, ObjToUnicode(objv[1]));
            break;
        case 5309: // SetWorkingDirectory
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetWorkingDirectory(
                ifc.task, ObjToUnicode(objv[1]));
            break;
        case 5310: // SetMaxRunTime
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetMaxRunTime(ifc.task, dw1);







|






|






|







817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
                ifc.task, &result.value.lpolestr);
            break;
        case 5307: // SetApplicationName
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetApplicationName(
                ifc.task, ObjToWinChars(objv[1]));
            break;
        case 5308: // SetParameters
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetParameters(
                ifc.task, ObjToWinChars(objv[1]));
            break;
        case 5309: // SetWorkingDirectory
            if (objc != 2)
                goto badargs;
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetWorkingDirectory(
                ifc.task, ObjToWinChars(objv[1]));
            break;
        case 5310: // SetMaxRunTime
            if (objc != 2)
                goto badargs;
            CHECK_INTEGER_OBJ(interp, dw1, objv[1]);
            result.type = TRT_EMPTY;
            hr = ifc.task->lpVtbl->SetMaxRunTime(ifc.task, dw1);
Changes to undroid/twapi/twapi/namedpipe/namedpipe.c.
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    NPipeTls *tlsP;
    int event_mask = 0;

    if (!(flags & TCL_FILE_EVENTS)) {
	return 0;               /* 0 -> Event will stay on queue */
    }

    ObjToUnicodeCleanup();

    /*
     * Note: can use GET_NPIPE_TLS here because, this routine would not
     * be called without NPipeSetupProc being called first which guarantees
     * the TLS is set up.
     */
    tlsP = GET_NPIPE_TLS();








<
<







456
457
458
459
460
461
462


463
464
465
466
467
468
469
    NPipeTls *tlsP;
    int event_mask = 0;

    if (!(flags & TCL_FILE_EVENTS)) {
	return 0;               /* 0 -> Event will stay on queue */
    }



    /*
     * Note: can use GET_NPIPE_TLS here because, this routine would not
     * be called without NPipeSetupProc being called first which guarantees
     * the TLS is set up.
     */
    tlsP = GET_NPIPE_TLS();

1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
    NPipeChannel *pcP;
    DWORD winerr = ERROR_SUCCESS;
    NPipeTls *tlsP;
    Tcl_Obj *nameObj, *secattrObj;
    SWSMark mark = NULL;
    TCL_RESULT res;
    
    ObjToUnicodeCleanup();

    res = TwapiGetArgs(interp, objc-1, objv+1,
                       GETOBJ(nameObj), GETINT(open_mode), GETINT(pipe_mode),
                       GETINT(max_instances), GETINT(outbuf_sz),
                       GETINT(inbuf_sz), GETINT(timeout),
                       GETOBJ(secattrObj), ARGEND);
    if (res != TCL_OK)
        return res;







<
<







1227
1228
1229
1230
1231
1232
1233


1234
1235
1236
1237
1238
1239
1240
    NPipeChannel *pcP;
    DWORD winerr = ERROR_SUCCESS;
    NPipeTls *tlsP;
    Tcl_Obj *nameObj, *secattrObj;
    SWSMark mark = NULL;
    TCL_RESULT res;
    


    res = TwapiGetArgs(interp, objc-1, objv+1,
                       GETOBJ(nameObj), GETINT(open_mode), GETINT(pipe_mode),
                       GETINT(max_instances), GETINT(outbuf_sz),
                       GETINT(inbuf_sz), GETINT(timeout),
                       GETOBJ(secattrObj), ARGEND);
    if (res != TCL_OK)
        return res;
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
    mark = SWSPushMark();
    res = ObjToPSECURITY_ATTRIBUTESSWS(interp, secattrObj, &secattrP);
    if (res != TCL_OK) {
        SWSPopMark(mark);
        return res;
    }

    pcP->hpipe = CreateNamedPipeW(ObjToUnicode(nameObj), open_mode,
                                  pipe_mode, max_instances,
                                  outbuf_sz, inbuf_sz, timeout, secattrP);
    SWSPopMark(mark);

    if (pcP->hpipe != INVALID_HANDLE_VALUE) {
        /* Create event used for sync i/o. Note this is manual reset event */
        pcP->hsync = CreateEvent(NULL, TRUE, FALSE, NULL);







|







1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
    mark = SWSPushMark();
    res = ObjToPSECURITY_ATTRIBUTESSWS(interp, secattrObj, &secattrP);
    if (res != TCL_OK) {
        SWSPopMark(mark);
        return res;
    }

    pcP->hpipe = CreateNamedPipeW(ObjToWinChars(nameObj), open_mode,
                                  pipe_mode, max_instances,
                                  outbuf_sz, inbuf_sz, timeout, secattrP);
    SWSPopMark(mark);

    if (pcP->hpipe != INVALID_HANDLE_VALUE) {
        /* Create event used for sync i/o. Note this is manual reset event */
        pcP->hsync = CreateEvent(NULL, TRUE, FALSE, NULL);
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
    NPipeChannel *pcP;
    DWORD winerr;
    NPipeTls *tlsP;
    HANDLE hpipe;
    Tcl_Obj *nameObj, *secattrObj;
    SWSMark mark = NULL;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETOBJ(nameObj),
                     GETINT(desired_access),
                     GETINT(share_mode),
                     GETOBJ(secattrObj),
                     GETINT(creation_disposition),
                     GETINT(flags_attr),







<
<







1353
1354
1355
1356
1357
1358
1359


1360
1361
1362
1363
1364
1365
1366
    NPipeChannel *pcP;
    DWORD winerr;
    NPipeTls *tlsP;
    HANDLE hpipe;
    Tcl_Obj *nameObj, *secattrObj;
    SWSMark mark = NULL;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETOBJ(nameObj),
                     GETINT(desired_access),
                     GETINT(share_mode),
                     GETOBJ(secattrObj),
                     GETINT(creation_disposition),
                     GETINT(flags_attr),
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
    flags_attr |= FILE_FLAG_OVERLAPPED;
    
    mark = SWSPushMark();
    if (ObjToPSECURITY_ATTRIBUTESSWS(interp, secattrObj, &secattrP) != TCL_OK) {
        SWSPopMark(mark);
        return TCL_ERROR;
    }
    hpipe = CreateFileW(ObjToUnicode(nameObj), desired_access,
                        share_mode, secattrP,
                        creation_disposition,
                        flags_attr, NULL);
    SWSPopMark(mark);
    if (hpipe == INVALID_HANDLE_VALUE)
        return TwapiReturnSystemError(interp);








|







1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
    flags_attr |= FILE_FLAG_OVERLAPPED;
    
    mark = SWSPushMark();
    if (ObjToPSECURITY_ATTRIBUTESSWS(interp, secattrObj, &secattrP) != TCL_OK) {
        SWSPopMark(mark);
        return TCL_ERROR;
    }
    hpipe = CreateFileW(ObjToWinChars(nameObj), desired_access,
                        share_mode, secattrP,
                        creation_disposition,
                        flags_attr, NULL);
    SWSPopMark(mark);
    if (hpipe == INVALID_HANDLE_VALUE)
        return TwapiReturnSystemError(interp);

1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
}


int Twapi_NPipeImpersonateObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE h;

    ObjToUnicodeCleanup();

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (ObjToHANDLE(interp, objv[1], &h) != TCL_OK)
        return TCL_ERROR;

    if (ImpersonateNamedPipeClient(h) == 0)







<
<







1453
1454
1455
1456
1457
1458
1459


1460
1461
1462
1463
1464
1465
1466
}


int Twapi_NPipeImpersonateObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE h;



    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (ObjToHANDLE(interp, objv[1], &h) != TCL_OK)
        return TCL_ERROR;

    if (ImpersonateNamedPipeClient(h) == 0)
Changes to undroid/twapi/twapi/network/network.c.
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
    objv[5] = ObjEmptyList();
    dnsserverP = iaaP->FirstDnsServerAddress;
    while (dnsserverP) {
        ObjAppendElement(NULL, objv[5], ObjFromIP_ADAPTER_DNS_SERVER_ADDRESS(dnsserverP));
        dnsserverP = dnsserverP->Next;
    }

    objv[6] = ObjFromUnicode(iaaP->DnsSuffix);
    objv[7] = ObjFromUnicode(iaaP->Description);
    objv[8] = ObjFromUnicode(iaaP->FriendlyName);
    objv[9] = ObjFromByteArray(iaaP->PhysicalAddress, iaaP->PhysicalAddressLength);
    objv[10] = ObjFromDWORD(iaaP->Flags);
    objv[11] = ObjFromDWORD(iaaP->Mtu);
    objv[12] = ObjFromDWORD(iaaP->IfType);
    objv[13] = ObjFromDWORD(iaaP->OperStatus);

    /*







|
|
|







479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
    objv[5] = ObjEmptyList();
    dnsserverP = iaaP->FirstDnsServerAddress;
    while (dnsserverP) {
        ObjAppendElement(NULL, objv[5], ObjFromIP_ADAPTER_DNS_SERVER_ADDRESS(dnsserverP));
        dnsserverP = dnsserverP->Next;
    }

    objv[6] = ObjFromWinChars(iaaP->DnsSuffix);
    objv[7] = ObjFromWinChars(iaaP->Description);
    objv[8] = ObjFromWinChars(iaaP->FriendlyName);
    objv[9] = ObjFromByteArray(iaaP->PhysicalAddress, iaaP->PhysicalAddressLength);
    objv[10] = ObjFromDWORD(iaaP->Flags);
    objv[11] = ObjFromDWORD(iaaP->Mtu);
    objv[12] = ObjFromDWORD(iaaP->IfType);
    objv[13] = ObjFromDWORD(iaaP->OperStatus);

    /*
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
    if (objv[29] == NULL)
        objv[29] = ObjEmptyList();
    objv[30] = ObjFromByteArray(ilhP->Dhcpv6ClientDuid, ilhP->Dhcpv6ClientDuidLength);
    objv[31] = ObjFromULONG(ilhP->Dhcpv6Iaid);
    objv[32] = ObjEmptyList();
    dnssuffixP = ilhP->FirstDnsSuffix;
    while (dnssuffixP) {
        ObjAppendElement(NULL, objv[32], ObjFromUnicodeLimited(dnssuffixP->String, MAX_DNS_SUFFIX_STRING_LENGTH, NULL));
        dnssuffixP = dnssuffixP->Next;
    }

    return ObjNewList(33, objv);
}


#ifdef NOTUSED
Tcl_Obj *ObjFromMIB_IFROW(Tcl_Interp *interp, const MIB_IFROW *ifrP)
{
    Tcl_Obj *objv[22];
    int len;
#if 0
    This field does not seem to contain a consistent format
    objv[0] = ObjFromUnicode(ifrP->wszName);
#else
    objv[0] = ObjFromEmptyString();
#endif
    objv[1] = ObjFromDWORD(ifrP->dwIndex);
    objv[2] = ObjFromDWORD(ifrP->dwType);
    objv[3] = ObjFromDWORD(ifrP->dwMtu);
    objv[4] = ObjFromDWORD(ifrP->dwSpeed);







|














|







554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
    if (objv[29] == NULL)
        objv[29] = ObjEmptyList();
    objv[30] = ObjFromByteArray(ilhP->Dhcpv6ClientDuid, ilhP->Dhcpv6ClientDuidLength);
    objv[31] = ObjFromULONG(ilhP->Dhcpv6Iaid);
    objv[32] = ObjEmptyList();
    dnssuffixP = ilhP->FirstDnsSuffix;
    while (dnssuffixP) {
        ObjAppendElement(NULL, objv[32], ObjFromWinCharsLimited(dnssuffixP->String, MAX_DNS_SUFFIX_STRING_LENGTH, NULL));
        dnssuffixP = dnssuffixP->Next;
    }

    return ObjNewList(33, objv);
}


#ifdef NOTUSED
Tcl_Obj *ObjFromMIB_IFROW(Tcl_Interp *interp, const MIB_IFROW *ifrP)
{
    Tcl_Obj *objv[22];
    int len;
#if 0
    This field does not seem to contain a consistent format
    objv[0] = ObjFromWinChars(ifrP->wszName);
#else
    objv[0] = ObjFromEmptyString();
#endif
    objv[1] = ObjFromDWORD(ifrP->dwIndex);
    objv[2] = ObjFromDWORD(ifrP->dwType);
    objv[3] = ObjFromDWORD(ifrP->dwMtu);
    objv[4] = ObjFromDWORD(ifrP->dwSpeed);
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
    fn = Twapi_GetProc_GetOwnerModuleFromTcpEntry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_TCPROW_OWNER_MODULE *)row,
                    0, // TCPIP_OWNER_MODULE_BASIC_INFO
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[7] = ObjFromUnicode(modP->pModuleName);
        obj[8] = ObjFromUnicode(modP->pModulePath);
    } else {
        obj[7] = ObjFromEmptyString();
        obj[8] = ObjFromEmptyString();
    }

    return ObjNewList(9, obj);
}







|
|







710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
    fn = Twapi_GetProc_GetOwnerModuleFromTcpEntry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_TCPROW_OWNER_MODULE *)row,
                    0, // TCPIP_OWNER_MODULE_BASIC_INFO
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[7] = ObjFromWinChars(modP->pModuleName);
        obj[8] = ObjFromWinChars(modP->pModulePath);
    } else {
        obj[7] = ObjFromEmptyString();
        obj[8] = ObjFromEmptyString();
    }

    return ObjNewList(9, obj);
}
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
    fn = Twapi_GetProc_GetOwnerModuleFromTcp6Entry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_TCP6ROW_OWNER_MODULE *)row,
                    0, //TCPIP_OWNER_MODULE_BASIC_INFO
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[7] = ObjFromUnicode(modP->pModuleName);
        obj[8] = ObjFromUnicode(modP->pModulePath);
    } else {
        obj[7] = ObjFromEmptyString();
        obj[8] = ObjFromEmptyString();
    }

    return ObjNewList(9, obj);
}







|
|







779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
    fn = Twapi_GetProc_GetOwnerModuleFromTcp6Entry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_TCP6ROW_OWNER_MODULE *)row,
                    0, //TCPIP_OWNER_MODULE_BASIC_INFO
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[7] = ObjFromWinChars(modP->pModuleName);
        obj[8] = ObjFromWinChars(modP->pModulePath);
    } else {
        obj[7] = ObjFromEmptyString();
        obj[8] = ObjFromEmptyString();
    }

    return ObjNewList(9, obj);
}
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
    fn = Twapi_GetProc_GetOwnerModuleFromUdpEntry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_UDPROW_OWNER_MODULE *)row,
                    0, // TCPIP_OWNER_MODULE_BASIC_INFO enum
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[4] = ObjFromUnicode(modP->pModuleName);
        obj[5] = ObjFromUnicode(modP->pModulePath);
    } else {
        obj[4] = ObjFromEmptyString();
        obj[5] = ObjFromEmptyString();
    }

    return ObjNewList(6, obj);
}







|
|







817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
    fn = Twapi_GetProc_GetOwnerModuleFromUdpEntry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_UDPROW_OWNER_MODULE *)row,
                    0, // TCPIP_OWNER_MODULE_BASIC_INFO enum
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[4] = ObjFromWinChars(modP->pModuleName);
        obj[5] = ObjFromWinChars(modP->pModulePath);
    } else {
        obj[4] = ObjFromEmptyString();
        obj[5] = ObjFromEmptyString();
    }

    return ObjNewList(6, obj);
}
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
    fn = Twapi_GetProc_GetOwnerModuleFromUdp6Entry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_UDP6ROW_OWNER_MODULE *)row,
                    0, // TCPIP_OWNER_MODULE_BASIC_INFO enum
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[4] = ObjFromUnicode(modP->pModuleName);
        obj[5] = ObjFromUnicode(modP->pModulePath);
    } else {
        obj[4] = ObjFromEmptyString();
        obj[5] = ObjFromEmptyString();
    }

    return ObjNewList(6, obj);
}







|
|







850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
    fn = Twapi_GetProc_GetOwnerModuleFromUdp6Entry();
    buf_sz = sizeof(buf);
    if (fn && (*fn)((MIB_UDP6ROW_OWNER_MODULE *)row,
                    0, // TCPIP_OWNER_MODULE_BASIC_INFO enum
                    buf, &buf_sz) == NO_ERROR) {
        TCPIP_OWNER_MODULE_BASIC_INFO *modP;
        modP = (TCPIP_OWNER_MODULE_BASIC_INFO *) buf;
        obj[4] = ObjFromWinChars(modP->pModuleName);
        obj[5] = ObjFromWinChars(modP->pModulePath);
    } else {
        obj[4] = ObjFromEmptyString();
        obj[5] = ObjFromEmptyString();
    }

    return ObjNewList(6, obj);
}
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
    int status;
    SOCKADDR_STORAGE ss;
    char hostname[NI_MAXHOST];
    char portname[NI_MAXSERV];
    Tcl_Obj *objs[2];
    int flags;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     ARGSKIP, GETINT(flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (ObjToSOCKADDR_STORAGE(interp, objv[1], &ss) != TCL_OK)
        return TCL_ERROR;







<
<







1578
1579
1580
1581
1582
1583
1584


1585
1586
1587
1588
1589
1590
1591
    int status;
    SOCKADDR_STORAGE ss;
    char hostname[NI_MAXHOST];
    char portname[NI_MAXSERV];
    Tcl_Obj *objs[2];
    int flags;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     ARGSKIP, GETINT(flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    if (ObjToSOCKADDR_STORAGE(interp, objv[1], &ss) != TCL_OK)
        return TCL_ERROR;
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
{
    const char *hostname;
    const char *svcname;
    int status;
    struct addrinfo hints;
    struct addrinfo *addrP;

    ObjToUnicodeCleanup();

    TwapiZeroMemory(&hints, sizeof(hints));
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETASTR(hostname), GETASTR(svcname),
                     ARGUSEDEFAULT,
                     GETINT(hints.ai_family),
                     GETINT(hints.ai_protocol),
                     GETINT(hints.ai_socktype),







<
<







1637
1638
1639
1640
1641
1642
1643


1644
1645
1646
1647
1648
1649
1650
{
    const char *hostname;
    const char *svcname;
    int status;
    struct addrinfo hints;
    struct addrinfo *addrP;



    TwapiZeroMemory(&hints, sizeof(hints));
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETASTR(hostname), GETASTR(svcname),
                     ARGUSEDEFAULT,
                     GETINT(hints.ai_family),
                     GETINT(hints.ai_protocol),
                     GETINT(hints.ai_socktype),
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685

static int Twapi_GetBestRouteObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    MIB_IPFORWARDROW route;
    int error;
    DWORD dest, src;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(ticP->interp, objc-1, objv+1,
                     GETVAR(dest, IPAddrObjToDWORD),
                     GETVAR(src, IPAddrObjToDWORD),
                     ARGEND) != TCL_OK) {
        return TCL_ERROR;
    }








<
<







1666
1667
1668
1669
1670
1671
1672


1673
1674
1675
1676
1677
1678
1679

static int Twapi_GetBestRouteObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    MIB_IPFORWARDROW route;
    int error;
    DWORD dest, src;



    if (TwapiGetArgs(ticP->interp, objc-1, objv+1,
                     GETVAR(dest, IPAddrObjToDWORD),
                     GETVAR(src, IPAddrObjToDWORD),
                     ARGEND) != TCL_OK) {
        return TCL_ERROR;
    }

1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
{
    GetBestInterfaceEx_t fn;
    int result;
    DWORD ifindex;
    DWORD ipaddr;
    Tcl_Obj *objP;

    ObjToUnicodeCleanup();

    if (objc != 2)
        return TwapiReturnError(ticP->interp, TWAPI_BAD_ARG_COUNT);

    fn = Twapi_GetProc_GetBestInterfaceEx();
    if (fn) {
        SOCKADDR_STORAGE ss;








<
<







1690
1691
1692
1693
1694
1695
1696


1697
1698
1699
1700
1701
1702
1703
{
    GetBestInterfaceEx_t fn;
    int result;
    DWORD ifindex;
    DWORD ipaddr;
    Tcl_Obj *objP;



    if (objc != 2)
        return TwapiReturnError(ticP->interp, TWAPI_BAD_ARG_COUNT);

    fn = Twapi_GetProc_GetBestInterfaceEx();
    if (fn) {
        SOCKADDR_STORAGE ss;

1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
    char *name;
    int   len;
    TwapiHostnameEvent *theP;
    DWORD winerr;
    int family;
    int hint_flags;

    ObjToUnicodeCleanup();

    ERROR_IF_UNTHREADED(ticP->interp);

    if (TwapiGetArgs(ticP->interp, objc-1, objv+1,
                     GETASTRN(name, len), ARGUSEDEFAULT, GETINT(family),
                     ARGUSEDEFAULT, GETINT(hint_flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;







<
<







1791
1792
1793
1794
1795
1796
1797


1798
1799
1800
1801
1802
1803
1804
    char *name;
    int   len;
    TwapiHostnameEvent *theP;
    DWORD winerr;
    int family;
    int hint_flags;



    ERROR_IF_UNTHREADED(ticP->interp);

    if (TwapiGetArgs(ticP->interp, objc-1, objv+1,
                     GETASTRN(name, len), ARGUSEDEFAULT, GETINT(family),
                     ARGUSEDEFAULT, GETINT(hint_flags),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
{
    TwapiHostnameEvent *theP = (TwapiHostnameEvent *) tclevP;

    if (theP->ticP->interp != NULL &&
        ! Tcl_InterpDeleted(theP->ticP->interp)) {
        /* Invoke the script */
        Tcl_Interp *interp = theP->ticP->interp;
        Tcl_Obj *objP;

        ObjToUnicodeCleanup();

        objP = ObjEmptyList();
        ObjAppendElement(
            interp, objP, STRING_LITERAL_OBJ(TWAPI_TCL_NAMESPACE "::_address_resolve_handler"));
        ObjAppendElement(interp, objP, ObjFromTwapiId(theP->id));
        if (theP->status == ERROR_SUCCESS) {
            /* Success. Note theP->hostname may still be NULL */
            ObjAppendElement(interp, objP, STRING_LITERAL_OBJ("success"));
            ObjAppendElement(







|

<
<
<







1837
1838
1839
1840
1841
1842
1843
1844
1845



1846
1847
1848
1849
1850
1851
1852
{
    TwapiHostnameEvent *theP = (TwapiHostnameEvent *) tclevP;

    if (theP->ticP->interp != NULL &&
        ! Tcl_InterpDeleted(theP->ticP->interp)) {
        /* Invoke the script */
        Tcl_Interp *interp = theP->ticP->interp;
        Tcl_Obj *objP = ObjEmptyList();




        ObjAppendElement(
            interp, objP, STRING_LITERAL_OBJ(TWAPI_TCL_NAMESPACE "::_address_resolve_handler"));
        ObjAppendElement(interp, objP, ObjFromTwapiId(theP->id));
        if (theP->status == ERROR_SUCCESS) {
            /* Success. Note theP->hostname may still be NULL */
            ObjAppendElement(interp, objP, STRING_LITERAL_OBJ("success"));
            ObjAppendElement(
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
    TwapiId id;
    char *addrstr;
    int   len;
    TwapiHostnameEvent *theP;
    DWORD winerr;
    int family;

    ObjToUnicodeCleanup();

    ERROR_IF_UNTHREADED(ticP->interp);

    if (TwapiGetArgs(ticP->interp, objc-1, objv+1,
                     GETASTRN(addrstr, len), ARGUSEDEFAULT, GETINT(family),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;








<
<







1914
1915
1916
1917
1918
1919
1920


1921
1922
1923
1924
1925
1926
1927
    TwapiId id;
    char *addrstr;
    int   len;
    TwapiHostnameEvent *theP;
    DWORD winerr;
    int family;



    ERROR_IF_UNTHREADED(ticP->interp);

    if (TwapiGetArgs(ticP->interp, objc-1, objv+1,
                     GETASTRN(addrstr, len), ARGUSEDEFAULT, GETINT(family),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
        MIB_TCPROW tcprow;
        SOCKADDR_STORAGE ss;
    } u;
    DWORD dw, dw2, dw3, dw4;
    LPWSTR s;
    LPVOID pv;

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {







<
<







1965
1966
1967
1968
1969
1970
1971


1972
1973
1974
1975
1976
1977
1978
        MIB_TCPROW tcprow;
        SOCKADDR_STORAGE ss;
    } u;
    DWORD dw, dw2, dw3, dw4;
    LPWSTR s;
    LPVOID pv;



    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
                return Twapi_GetIpForwardTable(ticP, dw);
            case 207:
                result.value.ival = FlushIpNetTable(dw);
                result.type = TRT_EXCEPTION_ON_ERROR;
                break;
            }
        } else {
            s = ObjToUnicode(objv[2]);
            switch (func) {
            case 251:
                result.type = GetAdapterIndex((LPWSTR)s, &result.value.uval)
                    ? TRT_GETLASTERROR
                    : TRT_DWORD;
                break;
            case 252: // Twapi_IPAddressFamily - TBD - optimizable?







|







2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
                return Twapi_GetIpForwardTable(ticP, dw);
            case 207:
                result.value.ival = FlushIpNetTable(dw);
                result.type = TRT_EXCEPTION_ON_ERROR;
                break;
            }
        } else {
            s = ObjToWinChars(objv[2]);
            switch (func) {
            case 251:
                result.type = GetAdapterIndex((LPWSTR)s, &result.value.uval)
                    ? TRT_GETLASTERROR
                    : TRT_DWORD;
                break;
            case 252: // Twapi_IPAddressFamily - TBD - optimizable?
Changes to undroid/twapi/twapi/nls/nls.c.
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
                     GETOBJ(number_stringObj), GETINT(ndigits),
                     GETINT(leading_zero),
                     GETINT(grouping), GETOBJ(decimal_sepObj),
                     GETOBJ(thousand_sepObj), GETINT(negative_order),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    number_string = ObjToUnicode(number_stringObj);

#define TWAPI_GETNUMBERFORMAT_USELOCALE 1 // Defined in newer SDK's

    if (opts & TWAPI_GETNUMBERFORMAT_USELOCALE) {
        fmtP = NULL;
    } else {
        numfmt.NumDigits = ndigits;
        numfmt.LeadingZero = leading_zero;
        numfmt.Grouping = grouping;
        numfmt.lpDecimalSep = ObjToUnicode(decimal_sepObj);
        numfmt.lpThousandSep = ObjToUnicode(thousand_sepObj);
        numfmt.NegativeOrder = negative_order;
        fmtP = &numfmt;
    }

    numchars = GetNumberFormatW(loc, flags, number_string, fmtP, NULL, 0);
    if (numchars == 0) {
        return TwapiReturnSystemError(ticP->interp);
    }

    buf = MemLifoPushFrame(ticP->memlifoP, sizeof(WCHAR)*(numchars+1), NULL);

    numchars = GetNumberFormatW(loc, flags, number_string, fmtP, buf, numchars);
    if (numchars == 0)
        TwapiReturnSystemError(ticP->interp);
    else
        ObjSetResult(ticP->interp, ObjFromUnicodeN(buf, numchars-1));

    MemLifoPopFrame(ticP->memlifoP);

    return numchars ? TCL_OK : TCL_ERROR;
}









|









|
|















|







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
                     GETOBJ(number_stringObj), GETINT(ndigits),
                     GETINT(leading_zero),
                     GETINT(grouping), GETOBJ(decimal_sepObj),
                     GETOBJ(thousand_sepObj), GETINT(negative_order),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    number_string = ObjToWinChars(number_stringObj);

#define TWAPI_GETNUMBERFORMAT_USELOCALE 1 // Defined in newer SDK's

    if (opts & TWAPI_GETNUMBERFORMAT_USELOCALE) {
        fmtP = NULL;
    } else {
        numfmt.NumDigits = ndigits;
        numfmt.LeadingZero = leading_zero;
        numfmt.Grouping = grouping;
        numfmt.lpDecimalSep = ObjToWinChars(decimal_sepObj);
        numfmt.lpThousandSep = ObjToWinChars(thousand_sepObj);
        numfmt.NegativeOrder = negative_order;
        fmtP = &numfmt;
    }

    numchars = GetNumberFormatW(loc, flags, number_string, fmtP, NULL, 0);
    if (numchars == 0) {
        return TwapiReturnSystemError(ticP->interp);
    }

    buf = MemLifoPushFrame(ticP->memlifoP, sizeof(WCHAR)*(numchars+1), NULL);

    numchars = GetNumberFormatW(loc, flags, number_string, fmtP, buf, numchars);
    if (numchars == 0)
        TwapiReturnSystemError(ticP->interp);
    else
        ObjSetResult(ticP->interp, ObjFromWinCharsN(buf, numchars-1));

    MemLifoPopFrame(ticP->memlifoP);

    return numchars ? TCL_OK : TCL_ERROR;
}


101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
                     GETINT(leading_zero),
                     GETINT(grouping), GETOBJ(decimal_sepObj),
                     GETOBJ(thousand_sepObj), GETINT(negative_order),
                     GETINT(positive_order), GETOBJ(currency_symObj),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    number_string = ObjToUnicode(number_stringObj);

#define TWAPI_GETCURRENCYFORMAT_USELOCALE 1

    if (opts & TWAPI_GETCURRENCYFORMAT_USELOCALE) {
        fmtP = NULL;
    } else {
        fmt.NumDigits = ndigits;
        fmt.LeadingZero = leading_zero;
        fmt.Grouping = grouping;
        fmt.lpDecimalSep = ObjToUnicode(decimal_sepObj);
        fmt.lpThousandSep = ObjToUnicode(thousand_sepObj);
        fmt.NegativeOrder = negative_order;
        fmt.PositiveOrder = positive_order;
        fmt.lpCurrencySymbol = ObjToUnicode(currency_symObj);
        fmtP = &fmt;
    }

    numchars = GetCurrencyFormatW(loc, flags, number_string, fmtP, NULL, 0);
    if (numchars == 0) {
        return TwapiReturnSystemError(ticP->interp);
    }
    buf = MemLifoPushFrame(ticP->memlifoP, sizeof(WCHAR)*(numchars+1), NULL);

    numchars = GetCurrencyFormatW(loc, flags, number_string, fmtP, buf, numchars);
    if (numchars == 0)
        TwapiReturnSystemError(ticP->interp);
    else
        ObjSetResult(ticP->interp, ObjFromUnicodeN(buf, numchars-1));

    MemLifoPopFrame(ticP->memlifoP);

    return numchars ? TCL_OK : TCL_ERROR;
}

static int Twapi_NlsCallObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    int func;
    DWORD dw, dw2;
    TwapiResult result;
    WCHAR buf[MAX_PATH+1];

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 23:







|









|
|


|













|













<
<







101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149


150
151
152
153
154
155
156
                     GETINT(leading_zero),
                     GETINT(grouping), GETOBJ(decimal_sepObj),
                     GETOBJ(thousand_sepObj), GETINT(negative_order),
                     GETINT(positive_order), GETOBJ(currency_symObj),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    number_string = ObjToWinChars(number_stringObj);

#define TWAPI_GETCURRENCYFORMAT_USELOCALE 1

    if (opts & TWAPI_GETCURRENCYFORMAT_USELOCALE) {
        fmtP = NULL;
    } else {
        fmt.NumDigits = ndigits;
        fmt.LeadingZero = leading_zero;
        fmt.Grouping = grouping;
        fmt.lpDecimalSep = ObjToWinChars(decimal_sepObj);
        fmt.lpThousandSep = ObjToWinChars(thousand_sepObj);
        fmt.NegativeOrder = negative_order;
        fmt.PositiveOrder = positive_order;
        fmt.lpCurrencySymbol = ObjToWinChars(currency_symObj);
        fmtP = &fmt;
    }

    numchars = GetCurrencyFormatW(loc, flags, number_string, fmtP, NULL, 0);
    if (numchars == 0) {
        return TwapiReturnSystemError(ticP->interp);
    }
    buf = MemLifoPushFrame(ticP->memlifoP, sizeof(WCHAR)*(numchars+1), NULL);

    numchars = GetCurrencyFormatW(loc, flags, number_string, fmtP, buf, numchars);
    if (numchars == 0)
        TwapiReturnSystemError(ticP->interp);
    else
        ObjSetResult(ticP->interp, ObjFromWinCharsN(buf, numchars-1));

    MemLifoPopFrame(ticP->memlifoP);

    return numchars ? TCL_OK : TCL_ERROR;
}

static int Twapi_NlsCallObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    int func;
    DWORD dw, dw2;
    TwapiResult result;
    WCHAR buf[MAX_PATH+1];



    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 23:
Changes to undroid/twapi/twapi/os/os.c.
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
    int    bufsz;
    ULONG  dummy;
    NTSTATUS status;
    DWORD    i;
    NtQuerySystemInformation_t NtQuerySystemInformationPtr = Twapi_GetProc_NtQuerySystemInformation();
    Tcl_Obj *resultObj;

    ObjToUnicodeCleanup();

    if (NtQuerySystemInformationPtr == NULL) {
        return Twapi_AppendSystemError(interp, ERROR_PROC_NOT_FOUND);
    }

    /* Need to know number of elements returned */
    GetSystemInfo(&sysinfo);








<
<







416
417
418
419
420
421
422


423
424
425
426
427
428
429
    int    bufsz;
    ULONG  dummy;
    NTSTATUS status;
    DWORD    i;
    NtQuerySystemInformation_t NtQuerySystemInformationPtr = Twapi_GetProc_NtQuerySystemInformation();
    Tcl_Obj *resultObj;



    if (NtQuerySystemInformationPtr == NULL) {
        return Twapi_AppendSystemError(interp, ERROR_PROC_NOT_FOUND);
    }

    /* Need to know number of elements returned */
    GetSystemInfo(&sysinfo);

476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    )
{
    Tcl_Obj *objs[4];

    objs[0] = ObjFromSIZE_T(pfiP->TotalSize);
    objs[1] = ObjFromSIZE_T(pfiP->TotalInUse);
    objs[2] = ObjFromSIZE_T(pfiP->PeakUsage);
    objs[3] = ObjFromUnicode(fnP);
    ObjAppendElement(NULL, objP, ObjNewList(4, objs));

    return TRUE;
}


/*







|







474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    )
{
    Tcl_Obj *objs[4];

    objs[0] = ObjFromSIZE_T(pfiP->TotalSize);
    objs[1] = ObjFromSIZE_T(pfiP->TotalInUse);
    objs[2] = ObjFromSIZE_T(pfiP->PeakUsage);
    objs[3] = ObjFromWinChars(fnP);
    ObjAppendElement(NULL, objP, ObjNewList(4, objs));

    return TRUE;
}


/*
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
    if (len == 0) {
        return TwapiReturnSystemError(interp);
    }
    if (len >= (sizeof(path)/sizeof(path[0]))) {
        return Twapi_AppendSystemError(interp, ERROR_INSUFFICIENT_BUFFER);
    }

    ObjSetResult(interp, ObjFromUnicodeN(path, len));
    return TCL_OK;
}

static int Twapi_OsCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD dw, dw2, dw3;
    TwapiResult result;







|







526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
    if (len == 0) {
        return TwapiReturnSystemError(interp);
    }
    if (len >= (sizeof(path)/sizeof(path[0]))) {
        return Twapi_AppendSystemError(interp, ERROR_INSUFFICIENT_BUFFER);
    }

    ObjSetResult(interp, ObjFromWinCharsN(path, len));
    return TCL_OK;
}

static int Twapi_OsCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    DWORD dw, dw2, dw3;
    TwapiResult result;
Changes to undroid/twapi/twapi/pdh/pdh.c.
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    WCHAR buf[1024]; /* PDH_MAX_COUNTER_NAME on newer SDK's */
    DWORD bufsz;
    PDH_STATUS status;

    bufsz=ARRAYSIZE(buf);
    status = PdhLookupPerfNameByIndexW(szMachineName, ctr_index, buf, &bufsz);
    if (status == ERROR_SUCCESS) {
        ObjSetResult(interp, ObjFromUnicode(buf));
        return TCL_OK;
    }
    else {
        return Twapi_AppendSystemError(interp, status);
    }
}








|







63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    WCHAR buf[1024]; /* PDH_MAX_COUNTER_NAME on newer SDK's */
    DWORD bufsz;
    PDH_STATUS status;

    bufsz=ARRAYSIZE(buf);
    status = PdhLookupPerfNameByIndexW(szMachineName, ctr_index, buf, &bufsz);
    if (status == ERROR_SUCCESS) {
        ObjSetResult(interp, ObjFromWinChars(buf));
        return TCL_OK;
    }
    else {
        return Twapi_AppendSystemError(interp, status);
    }
}

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
            break;
        case 2:
            /* Note there is a difference between an object has no *current*
               instances versus one that CANNOT have instances (e.g. Memory) */
            if (instance_buf_size)
                objP = ObjFromMultiSz(instance_buf, instance_buf_size);
            else {
                objP = ObjFromUnicode(szObjectName);
                Tcl_AppendPrintfToObj(objP, " performance object does not support instances");
                res = TCL_ERROR;
            }                
            break;
        default:
            objs[0] = ObjFromMultiSz(counter_buf, counter_buf_size);
            /* Note there is a difference between an object has no *current*







|







182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
            break;
        case 2:
            /* Note there is a difference between an object has no *current*
               instances versus one that CANNOT have instances (e.g. Memory) */
            if (instance_buf_size)
                objP = ObjFromMultiSz(instance_buf, instance_buf_size);
            else {
                objP = ObjFromWinChars(szObjectName);
                Tcl_AppendPrintfToObj(objP, " performance object does not support instances");
                res = TCL_ERROR;
            }                
            break;
        default:
            objs[0] = ObjFromMultiSz(counter_buf, counter_buf_size);
            /* Note there is a difference between an object has no *current*
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
            path_buf = MemLifoAlloc(ticP->memlifoP,
                                    path_buf_size*sizeof(*path_buf), NULL);
            pdh_status = PdhMakeCounterPathW(&pdh_elements, path_buf,
                                             &path_buf_size, dwFlags);
            if (pdh_status != ERROR_SUCCESS)
                result = Twapi_AppendSystemError(ticP->interp, pdh_status);
            else
                ObjSetResult(ticP->interp, ObjFromUnicode(path_buf));
        }
    }

    MemLifoPopMark(mark);
    return result;
}








|







243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
            path_buf = MemLifoAlloc(ticP->memlifoP,
                                    path_buf_size*sizeof(*path_buf), NULL);
            pdh_status = PdhMakeCounterPathW(&pdh_elements, path_buf,
                                             &path_buf_size, dwFlags);
            if (pdh_status != ERROR_SUCCESS)
                result = Twapi_AppendSystemError(ticP->interp, pdh_status);
            else
                ObjSetResult(ticP->interp, ObjFromWinChars(path_buf));
        }
    }

    MemLifoPopMark(mark);
    return result;
}

280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
                                          &buf_size, dwFlags);
    
        if (pdh_status != ERROR_SUCCESS) {
            Twapi_AppendSystemError(ticP->interp, pdh_status);
            result = TCL_ERROR;
        } else {
            Tcl_Obj *objs[6];
            objs[0] = ObjFromUnicode(pdh_elems->szMachineName);
            objs[1] = ObjFromUnicode(pdh_elems->szObjectName);
            objs[2] = ObjFromUnicode(pdh_elems->szInstanceName);
            objs[3] = ObjFromUnicode(pdh_elems->szParentInstance);
            objs[4] = ObjFromLong(pdh_elems->dwInstanceIndex);
            objs[5] = ObjFromUnicode(pdh_elems->szCounterName);
            ObjSetResult(ticP->interp, ObjNewList(ARRAYSIZE(objs), objs));
            result = TCL_OK;
        }
        MemLifoPopFrame(ticP->memlifoP);
    }

    return result;







|
|
|
|

|







280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
                                          &buf_size, dwFlags);
    
        if (pdh_status != ERROR_SUCCESS) {
            Twapi_AppendSystemError(ticP->interp, pdh_status);
            result = TCL_ERROR;
        } else {
            Tcl_Obj *objs[6];
            objs[0] = ObjFromWinChars(pdh_elems->szMachineName);
            objs[1] = ObjFromWinChars(pdh_elems->szObjectName);
            objs[2] = ObjFromWinChars(pdh_elems->szInstanceName);
            objs[3] = ObjFromWinChars(pdh_elems->szParentInstance);
            objs[4] = ObjFromLong(pdh_elems->dwInstanceIndex);
            objs[5] = ObjFromWinChars(pdh_elems->szCounterName);
            ObjSetResult(ticP->interp, ObjNewList(ARRAYSIZE(objs), objs));
            result = TCL_OK;
        }
        MemLifoPopFrame(ticP->memlifoP);
    }

    return result;
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
{
    Tcl_Obj *valObj;

    valObj = ObjFromPDH_FMT_COUNTERVALUE(interp, &itemP->FmtValue, dwFormat);
    if (valObj == NULL)
        return TCL_ERROR;            /* interp already holds error */
        
    *nameObjP = ObjFromUnicode(itemP->szName);
    *valObjP = valObj;
    return TCL_OK;
}

TCL_RESULT Twapi_PdhGetFormattedCounterArray(
    Tcl_Interp *interp,
    HANDLE hCounter,







|







321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
{
    Tcl_Obj *valObj;

    valObj = ObjFromPDH_FMT_COUNTERVALUE(interp, &itemP->FmtValue, dwFormat);
    if (valObj == NULL)
        return TCL_ERROR;            /* interp already holds error */
        
    *nameObjP = ObjFromWinChars(itemP->szName);
    *valObjP = valObj;
    return TCL_OK;
}

TCL_RESULT Twapi_PdhGetFormattedCounterArray(
    Tcl_Interp *interp,
    HANDLE hCounter,
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
{
    int func;
    LPWSTR s;
    DWORD   dw, dw2;
    HANDLE h;
    TwapiResult result;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(func),
                     ARGTERM) != TCL_OK)
        return TCL_ERROR;

    result.type = TRT_BADFUNCTIONCODE;
    if (func < 100) {







<
<







526
527
528
529
530
531
532


533
534
535
536
537
538
539
{
    int func;
    LPWSTR s;
    DWORD   dw, dw2;
    HANDLE h;
    TwapiResult result;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(func),
                     ARGTERM) != TCL_OK)
        return TCL_ERROR;

    result.type = TRT_BADFUNCTIONCODE;
    if (func < 100) {
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
            break;
        case 102:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = PdhConnectMachineW(ObjToLPWSTR_NULL_IF_EMPTY(objv[2]));
            break;
        case 103:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = PdhValidatePathW(ObjToUnicode(objv[2]));
            break;
        }
    } else if (func < 300) {
        /* Single string with integer arg. */
        CHECK_NARGS(interp, objc, 4);
        /* To prevent shimmering issues, get int arg first */
        CHECK_INTEGER_OBJ(interp, dw, objv[3]);
        s = ObjToUnicode(objv[2]);
        switch (func) {
        case 201: 
            return Twapi_PdhParseCounterPath(ticP, s, dw);
        case 202: 
            NULLIFY_EMPTY(s);
            return Twapi_PdhLookupPerfNameByIndex(interp, s, dw);
        case 203:







|







|







566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
            break;
        case 102:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = PdhConnectMachineW(ObjToLPWSTR_NULL_IF_EMPTY(objv[2]));
            break;
        case 103:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = PdhValidatePathW(ObjToWinChars(objv[2]));
            break;
        }
    } else if (func < 300) {
        /* Single string with integer arg. */
        CHECK_NARGS(interp, objc, 4);
        /* To prevent shimmering issues, get int arg first */
        CHECK_INTEGER_OBJ(interp, dw, objv[3]);
        s = ObjToWinChars(objv[2]);
        switch (func) {
        case 201: 
            return Twapi_PdhParseCounterPath(ticP, s, dw);
        case 202: 
            NULLIFY_EMPTY(s);
            return Twapi_PdhLookupPerfNameByIndex(interp, s, dw);
        case 203:
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
                return TCL_ERROR;
            return (func == 1001 ? Twapi_PdhGetFormattedCounterValue : Twapi_PdhGetFormattedCounterArray)(interp, h, dw);
        case 1002:
            if (TwapiGetArgs(interp, objc-2, objv+2,
                             GETHANDLE(h), ARGSKIP, GETINT(dw),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            dw = PdhAddCounterW(h, ObjToUnicode(objv[3]), dw, &result.value.hval);
            if (dw == 0)
                result.type = TRT_HANDLE;
            else {
                result.type = TRT_EXCEPTION_ON_ERROR;
                result.value.ival = dw;
            }
            break;
        case 1003:
            return Twapi_PdhMakeCounterPath(ticP, objc-2, objv+2);
        case 1004:
            if (TwapiGetArgs(interp, objc-2, objv+2,
                             ARGSKIP, ARGSKIP, ARGSKIP,
                             GETINT(dw), GETINT(dw2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            return Twapi_PdhEnumObjectItems(
                ticP,
                ObjToLPWSTR_NULL_IF_EMPTY(objv[2]),
                ObjToLPWSTR_NULL_IF_EMPTY(objv[3]),
                ObjToUnicode(objv[4]),
                dw, dw2);
        case 1005:
            if (TwapiGetArgs(interp, objc-2, objv+2,
                             ARGSKIP, ARGSKIP,
                             GETINT(dw), GETBOOL(dw2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;







|



















|







627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
                return TCL_ERROR;
            return (func == 1001 ? Twapi_PdhGetFormattedCounterValue : Twapi_PdhGetFormattedCounterArray)(interp, h, dw);
        case 1002:
            if (TwapiGetArgs(interp, objc-2, objv+2,
                             GETHANDLE(h), ARGSKIP, GETINT(dw),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            dw = PdhAddCounterW(h, ObjToWinChars(objv[3]), dw, &result.value.hval);
            if (dw == 0)
                result.type = TRT_HANDLE;
            else {
                result.type = TRT_EXCEPTION_ON_ERROR;
                result.value.ival = dw;
            }
            break;
        case 1003:
            return Twapi_PdhMakeCounterPath(ticP, objc-2, objv+2);
        case 1004:
            if (TwapiGetArgs(interp, objc-2, objv+2,
                             ARGSKIP, ARGSKIP, ARGSKIP,
                             GETINT(dw), GETINT(dw2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            return Twapi_PdhEnumObjectItems(
                ticP,
                ObjToLPWSTR_NULL_IF_EMPTY(objv[2]),
                ObjToLPWSTR_NULL_IF_EMPTY(objv[3]),
                ObjToWinChars(objv[4]),
                dw, dw2);
        case 1005:
            if (TwapiGetArgs(interp, objc-2, objv+2,
                             ARGSKIP, ARGSKIP,
                             GETINT(dw), GETBOOL(dw2),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
Changes to undroid/twapi/twapi/process/process.c.
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    DWORD  buf_filled;
    DWORD  buf_size;
    int    result;
    BOOL   status;
    int type;
    HANDLE phandle;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(type), ARGUSEDEFAULT, GETHANDLE(phandle),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    /*
     * EnumProcesses/EnumProcessModules do not return error if the 







<
<







323
324
325
326
327
328
329


330
331
332
333
334
335
336
    DWORD  buf_filled;
    DWORD  buf_size;
    int    result;
    BOOL   status;
    int type;
    HANDLE phandle;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETINT(type), ARGUSEDEFAULT, GETHANDLE(phandle),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;
    
    /*
     * EnumProcesses/EnumProcessModules do not return error if the 
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
    BOOL status = 0;
    PROCESS_INFORMATION pi;
    LPWSTR appname, cmdline, curdir;
    Tcl_Interp *interp = ticP->interp;
    MemLifoMarkHandle mark;
    Tcl_Obj *startinfoObj, *envObj;

    ObjToUnicodeCleanup();

    asuser = (asuser != 0);     /* Make 0 or 1 */

    if (objc != (1+asuser+9))
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (asuser) {
        if (ObjToHANDLE(interp, objv[1], &tokH) != TCL_OK)







<
<







695
696
697
698
699
700
701


702
703
704
705
706
707
708
    BOOL status = 0;
    PROCESS_INFORMATION pi;
    LPWSTR appname, cmdline, curdir;
    Tcl_Interp *interp = ticP->interp;
    MemLifoMarkHandle mark;
    Tcl_Obj *startinfoObj, *envObj;



    asuser = (asuser != 0);     /* Make 0 or 1 */

    if (objc != (1+asuser+9))
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    if (asuser) {
        if (ObjToHANDLE(interp, objv[1], &tokH) != TCL_OK)
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    PROCESS_INFORMATION pi;
    LPWSTR appname, cmdline, curdir;
    Tcl_Interp *interp = ticP->interp;
    MemLifoMarkHandle mark;
    Tcl_Obj *startinfoObj, *envObj, *authObj;
    SEC_WINNT_AUTH_IDENTITY_W *swaiP = NULL;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETOBJ(authObj), GETINT(logon_flags),
                       GETEMPTYASNULL(appname),   GETEMPTYASNULL(cmdline),
                       GETINT(create_flags),
                       GETOBJ(envObj),   GETEMPTYASNULL(curdir),
                       GETOBJ(startinfoObj), ARGEND) != TCL_OK)







<
<







789
790
791
792
793
794
795


796
797
798
799
800
801
802
    PROCESS_INFORMATION pi;
    LPWSTR appname, cmdline, curdir;
    Tcl_Interp *interp = ticP->interp;
    MemLifoMarkHandle mark;
    Tcl_Obj *startinfoObj, *envObj, *authObj;
    SEC_WINNT_AUTH_IDENTITY_W *swaiP = NULL;



    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                       GETOBJ(authObj), GETINT(logon_flags),
                       GETEMPTYASNULL(appname),   GETEMPTYASNULL(cmdline),
                       GETINT(create_flags),
                       GETOBJ(envObj),   GETEMPTYASNULL(curdir),
                       GETOBJ(startinfoObj), ARGEND) != TCL_OK)
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
    Tcl_Obj *CONST objv[])
{
    HANDLE  hToken;
    PROFILEINFOW profileinfo;
    int nobjs;
    Tcl_Obj **objs;

    ObjToUnicodeCleanup();

    CHECK_NARGS(interp, objc, 2);
    if (ObjGetElements(interp, objv[1], &nobjs, &objs) != TCL_OK)
        return TCL_ERROR;

    TwapiZeroMemory(&profileinfo, sizeof(profileinfo));
    profileinfo.dwSize        = sizeof(profileinfo);
    if (TwapiGetArgsEx(ticP, nobjs, objs, GETHANDLE(hToken),







<
<







910
911
912
913
914
915
916


917
918
919
920
921
922
923
    Tcl_Obj *CONST objv[])
{
    HANDLE  hToken;
    PROFILEINFOW profileinfo;
    int nobjs;
    Tcl_Obj **objs;



    CHECK_NARGS(interp, objc, 2);
    if (ObjGetElements(interp, objv[1], &nobjs, &objs) != TCL_OK)
        return TCL_ERROR;

    TwapiZeroMemory(&profileinfo, sizeof(profileinfo));
    profileinfo.dwSize        = sizeof(profileinfo);
    if (TwapiGetArgsEx(ticP, nobjs, objs, GETHANDLE(hToken),
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    LPWSTR s, bufP;
    LPVOID pv;
    TwapiResult result;
    int func = PtrToInt(clientdata);
    Tcl_Obj *objs[10];
    SIZE_T sz, sz2;

    ObjToUnicodeCleanup();

    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 2:
        result.type =
            GetProfileType(&result.value.uval) ? TRT_DWORD : TRT_GETLASTERROR;







<
<







950
951
952
953
954
955
956


957
958
959
960
961
962
963
    LPWSTR s, bufP;
    LPVOID pv;
    TwapiResult result;
    int func = PtrToInt(clientdata);
    Tcl_Obj *objs[10];
    SIZE_T sz, sz2;



    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 2:
        result.type =
            GetProfileType(&result.value.uval) ? TRT_DWORD : TRT_GETLASTERROR;
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
            result.type = TRT_GETLASTERROR;
        break;
    case 5: // ExpandEnvironmentStringsForUser
        if (TwapiGetArgs(interp, objc, objv, GETHANDLE(h), ARGSKIP, ARGEND)
            != TCL_OK)
            return TCL_ERROR;
        dw = 2048;
        s =  ObjToUnicode(objv[1]);
        while (1) {
            bufP = SWSPushFrame(dw, &dw);
            if (ExpandEnvironmentStringsForUserW(h, s, bufP, dw/sizeof(WCHAR))) {
                result.value.obj = ObjFromUnicode(bufP);
                result.type = TRT_OBJ;
                SWSPopFrame();
                break;
            } else {
                result.type = TRT_EXCEPTION_ON_ERROR;
                result.value.ival = GetLastError(); /* Save error BEFORE any
                                                       other calls */







|



|







981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
            result.type = TRT_GETLASTERROR;
        break;
    case 5: // ExpandEnvironmentStringsForUser
        if (TwapiGetArgs(interp, objc, objv, GETHANDLE(h), ARGSKIP, ARGEND)
            != TCL_OK)
            return TCL_ERROR;
        dw = 2048;
        s =  ObjToWinChars(objv[1]);
        while (1) {
            bufP = SWSPushFrame(dw, &dw);
            if (ExpandEnvironmentStringsForUserW(h, s, bufP, dw/sizeof(WCHAR))) {
                result.value.obj = ObjFromWinChars(bufP);
                result.type = TRT_OBJ;
                SWSPopFrame();
                break;
            } else {
                result.type = TRT_EXCEPTION_ON_ERROR;
                result.value.ival = GetLastError(); /* Save error BEFORE any
                                                       other calls */
Changes to undroid/twapi/twapi/rds/rds.c.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    if (! (BOOL) (WTSEnumerateSessionsW)(wtsH, 0, 1, &sessP, &count)) {
        return TwapiReturnSystemError(interp);
    }

    records = SWSPushFrame(count * sizeof(Tcl_Obj*), NULL);
    for (i = 0; i < count; ++i) {
        objv[0] = ObjFromLong(sessP[i].SessionId);
        objv[1] = ObjFromUnicode(sessP[i].pWinStationName);
        objv[2] = ObjFromLong(sessP[i].State);

        records[i] = ObjNewList(3, objv);
    }

    Twapi_WTSFreeMemory(sessP);








|







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    if (! (BOOL) (WTSEnumerateSessionsW)(wtsH, 0, 1, &sessP, &count)) {
        return TwapiReturnSystemError(interp);
    }

    records = SWSPushFrame(count * sizeof(Tcl_Obj*), NULL);
    for (i = 0; i < count; ++i) {
        objv[0] = ObjFromLong(sessP[i].SessionId);
        objv[1] = ObjFromWinChars(sessP[i].pWinStationName);
        objv[2] = ObjFromLong(sessP[i].State);

        records[i] = ObjNewList(3, objv);
    }

    Twapi_WTSFreeMemory(sessP);

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        if (! (BOOL) WTSQuerySessionInformationW(wtsH, sess_id, info_class, &bufP, &bytes )) {
            winerr = GetLastError();
            goto handle_error;

        }
        /* Note bufP can be NULL even on success! */
        if (bufP)
            ObjSetResult(interp, ObjFromUnicode(bufP));
        break;

    case WTSClientBuildNumber:
    case WTSClientHardwareId:
    case WTSConnectState:
    case WTSSessionId:
        if (! (BOOL) WTSQuerySessionInformationW(wtsH, sess_id, info_class, &bufP, &bytes )) {







|







77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        if (! (BOOL) WTSQuerySessionInformationW(wtsH, sess_id, info_class, &bufP, &bytes )) {
            winerr = GetLastError();
            goto handle_error;

        }
        /* Note bufP can be NULL even on success! */
        if (bufP)
            ObjSetResult(interp, ObjFromWinChars(bufP));
        break;

    case WTSClientBuildNumber:
    case WTSClientHardwareId:
    case WTSConnectState:
    case WTSSessionId:
        if (! (BOOL) WTSQuerySessionInformationW(wtsH, sess_id, info_class, &bufP, &bytes )) {
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
    LPWSTR s, s2;
    DWORD dw, dw2, dw3, dw4;
    HANDLE h;
    int i, i2;
    TwapiResult result;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    /* At least one arg for every command */
    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        result.type = TRT_HANDLE;
        result.value.hval = WTSOpenServerW(ObjToUnicode(objv[0]));
        break;
    case 2:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), GETINT(dw),
                         ARGSKIP, ARGSKIP,
                         GETINT(dw2), GETINT(dw3), GETBOOL(dw4),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToUnicodeN(objv[2], &i);
        s2 = ObjToUnicodeN(objv[3], &i2);
        if (WTSSendMessageW(h, dw, s, sizeof(WCHAR)*i,
                            s2, sizeof(WCHAR)*i2, dw2,
                            dw3, &result.value.uval, dw4))
            result.type = TRT_DWORD;
        else
            result.type = TRT_GETLASTERROR;    
        break;







<
<











|








|
|







134
135
136
137
138
139
140


141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    LPWSTR s, s2;
    DWORD dw, dw2, dw3, dw4;
    HANDLE h;
    int i, i2;
    TwapiResult result;
    int func = PtrToInt(clientdata);



    /* At least one arg for every command */
    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        result.type = TRT_HANDLE;
        result.value.hval = WTSOpenServerW(ObjToWinChars(objv[0]));
        break;
    case 2:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), GETINT(dw),
                         ARGSKIP, ARGSKIP,
                         GETINT(dw2), GETINT(dw3), GETBOOL(dw4),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToWinCharsN(objv[2], &i);
        s2 = ObjToWinCharsN(objv[3], &i2);
        if (WTSSendMessageW(h, dw, s, sizeof(WCHAR)*i,
                            s2, sizeof(WCHAR)*i2, dw2,
                            dw3, &result.value.uval, dw4))
            result.type = TRT_DWORD;
        else
            result.type = TRT_GETLASTERROR;    
        break;
Changes to undroid/twapi/twapi/resource/resource.c.
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
     * Resource type and name can be integers or strings. If integer,
     * they must pass the IS_INTRESOURCE test as not all integers are valid.
     */
    if (ObjToLong(NULL, objP, &i) == TCL_OK &&
        IS_INTRESOURCE(i))
        *wsP = MAKEINTRESOURCEW(i);
    else
        *wsP = ObjToUnicode(objP);

    return TCL_OK;
}

Tcl_Obj *ObjFromResourceIntOrString(LPCWSTR s)
{
    if (IS_INTRESOURCE(s))
        return Tcl_NewLongObj((long) (LONG_PTR) s); /* Double cast to avoid warning */
    else
        return ObjFromUnicode(s);
}


TWAPI_FILEVERINFO* Twapi_GetFileVersionInfo(LPWSTR path)
{
    DWORD  sz;
    DWORD  unused;







|









|







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
     * Resource type and name can be integers or strings. If integer,
     * they must pass the IS_INTRESOURCE test as not all integers are valid.
     */
    if (ObjToLong(NULL, objP, &i) == TCL_OK &&
        IS_INTRESOURCE(i))
        *wsP = MAKEINTRESOURCEW(i);
    else
        *wsP = ObjToWinChars(objP);

    return TCL_OK;
}

Tcl_Obj *ObjFromResourceIntOrString(LPCWSTR s)
{
    if (IS_INTRESOURCE(s))
        return Tcl_NewLongObj((long) (LONG_PTR) s); /* Double cast to avoid warning */
    else
        return ObjFromWinChars(s);
}


TWAPI_FILEVERINFO* Twapi_GetFileVersionInfo(LPWSTR path)
{
    DWORD  sz;
    DWORD  unused;
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

    if (TwapiGetArgs(interp, objc, objv,
                     GETVERIFIEDPTR(verP, TWAPI_FILEVERINFO, Twapi_FreeFileVersionInfo),
                     GETASTR(lang_and_cp), GETASTR(name), ARGEND) != TCL_OK)
        return TCL_ERROR;

    objP = Tcl_ObjPrintf("\\StringFileInfo\\%s\\%s", lang_and_cp, name);
    if ((! VerQueryValueW(verP, ObjToUnicode(objP), (LPVOID) &valueP, &len)) ||
        len == 0) {
        /* Return empty string, not error */
        ObjDecrRefs(objP);
        return TCL_OK;
    }
    ObjDecrRefs(objP);

    /* Note valueP does not have to be freed, points into verP */
    ObjSetResult(interp, ObjFromUnicode(valueP));
    return TCL_OK;
}

int Twapi_VerQueryValue_TRANSLATIONS(
    Tcl_Interp *interp,
    TWAPI_FILEVERINFO* verP
    )







|








|







132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

    if (TwapiGetArgs(interp, objc, objv,
                     GETVERIFIEDPTR(verP, TWAPI_FILEVERINFO, Twapi_FreeFileVersionInfo),
                     GETASTR(lang_and_cp), GETASTR(name), ARGEND) != TCL_OK)
        return TCL_ERROR;

    objP = Tcl_ObjPrintf("\\StringFileInfo\\%s\\%s", lang_and_cp, name);
    if ((! VerQueryValueW(verP, ObjToWinChars(objP), (LPVOID) &valueP, &len)) ||
        len == 0) {
        /* Return empty string, not error */
        ObjDecrRefs(objP);
        return TCL_OK;
    }
    ObjDecrRefs(objP);

    /* Note valueP does not have to be freed, points into verP */
    ObjSetResult(interp, ObjFromWinChars(valueP));
    return TCL_OK;
}

int Twapi_VerQueryValue_TRANSLATIONS(
    Tcl_Interp *interp,
    TWAPI_FILEVERINFO* verP
    )
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
    while (len >= 2) {
        WORD slen = *wP++;
        if (slen > (sizeof(WCHAR)*len)) {
            /* Should not happen */
            break;
        }
        ObjAppendElement(interp, objP,
                                 ObjFromUnicodeN(wP, slen));
        wP += slen;
        len -= sizeof(WCHAR)*(1+slen);
    }

    ObjSetResult(interp, objP);
    return TCL_OK;
}







|







446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
    while (len >= 2) {
        WORD slen = *wP++;
        if (slen > (sizeof(WCHAR)*len)) {
            /* Should not happen */
            break;
        }
        ObjAppendElement(interp, objP,
                                 ObjFromWinCharsN(wP, slen));
        wP += slen;
        len -= sizeof(WCHAR)*(1+slen);
    }

    ObjSetResult(interp, objP);
    return TCL_OK;
}
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
    LPWSTR s;
    DWORD dw;
    HANDLE h;
    TwapiResult result;
    void *pv;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    /* Every command has at least one argument */
    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;








<
<







495
496
497
498
499
500
501


502
503
504
505
506
507
508
    LPWSTR s;
    DWORD dw;
    HANDLE h;
    TwapiResult result;
    void *pv;
    int func = PtrToInt(clientdata);



    /* Every command has at least one argument */
    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    case 11:
        return Twapi_EnumResourceLanguages(interp, objc, objv);
    case 12:
        return Twapi_SplitStringResource(interp, objc, objv);
    case 13: // LoadImage
        return Twapi_LoadImage(interp, objc, objv);
    case 14:
        pv = Twapi_GetFileVersionInfo(ObjToUnicode(objv[0]));
        if (pv) {
            if (TwapiRegisterPointer(interp, pv, Twapi_FreeFileVersionInfo) != TCL_OK)
                return TCL_ERROR;
            TwapiResult_SET_NONNULL_PTR(result, TWAPI_FILEVERINFO, pv);
        } else
            result.type = TRT_GETLASTERROR;
        break;
    case 15: // AddFontResourceEx
    case 16: // BeginUpdateResource
        if (TwapiGetArgs(interp, objc, objv, ARGSKIP, GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToUnicode(objv[0]);
        if (func == 15) {
            result.type = TRT_LONG;
            result.value.ival = AddFontResourceExW(s, dw, NULL);
        } else {
            result.type = TRT_HANDLE;
            result.value.hval = BeginUpdateResourceW(s, dw);
        }







|











|







549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
    case 11:
        return Twapi_EnumResourceLanguages(interp, objc, objv);
    case 12:
        return Twapi_SplitStringResource(interp, objc, objv);
    case 13: // LoadImage
        return Twapi_LoadImage(interp, objc, objv);
    case 14:
        pv = Twapi_GetFileVersionInfo(ObjToWinChars(objv[0]));
        if (pv) {
            if (TwapiRegisterPointer(interp, pv, Twapi_FreeFileVersionInfo) != TCL_OK)
                return TCL_ERROR;
            TwapiResult_SET_NONNULL_PTR(result, TWAPI_FILEVERINFO, pv);
        } else
            result.type = TRT_GETLASTERROR;
        break;
    case 15: // AddFontResourceEx
    case 16: // BeginUpdateResource
        if (TwapiGetArgs(interp, objc, objv, ARGSKIP, GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToWinChars(objv[0]);
        if (func == 15) {
            result.type = TRT_LONG;
            result.value.ival = AddFontResourceExW(s, dw, NULL);
        } else {
            result.type = TRT_HANDLE;
            result.value.hval = BeginUpdateResourceW(s, dw);
        }
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
        break;
    case 19:
        CHECK_NARGS(interp, objc, 4);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival =
            CreateScalableFontResourceW(dw,
                                        ObjToUnicode(objv[1]),
                                        ObjToUnicode(objv[2]),
                                        ObjToUnicode(objv[3]));
        break;
    case 20:
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);
        result.type = TRT_BOOL;
        result.value.bval = RemoveFontResourceExW(ObjToUnicode(objv[0]), dw, NULL);
        break;
    }

    return TwapiSetResult(interp, &result);
}









|
|
|





|







586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        break;
    case 19:
        CHECK_NARGS(interp, objc, 4);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival =
            CreateScalableFontResourceW(dw,
                                        ObjToWinChars(objv[1]),
                                        ObjToWinChars(objv[2]),
                                        ObjToWinChars(objv[3]));
        break;
    case 20:
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);
        result.type = TRT_BOOL;
        result.value.bval = RemoveFontResourceExW(ObjToWinChars(objv[0]), dw, NULL);
        break;
    }

    return TwapiSetResult(interp, &result);
}


Changes to undroid/twapi/twapi/security/security.c.
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
    return TCL_OK;
}

static TCL_RESULT Twapi_SecCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    LPWSTR s, s2;
    DWORD dw, dw2, dw3;
    long ldw;
    SECURITY_ATTRIBUTES *secattrP;
    HANDLE h, h2;
    SECURITY_DESCRIPTOR *secdP;
    LUID luid;
    ACL *daclP, *saclP;
    PSID osidP, gsidP;
    union {







<







800
801
802
803
804
805
806

807
808
809
810
811
812
813
    return TCL_OK;
}

static TCL_RESULT Twapi_SecCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    LPWSTR s, s2;
    DWORD dw, dw2, dw3;

    SECURITY_ATTRIBUTES *secattrP;
    HANDLE h, h2;
    SECURITY_DESCRIPTOR *secdP;
    LUID luid;
    ACL *daclP, *saclP;
    PSID osidP, gsidP;
    union {
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
    Tcl_Obj **objPP;
    DWORD nobjs;
    int *iP;
    Tcl_Obj *objP;
    SWSMark mark = NULL;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    daclP = saclP = NULL;
    osidP = gsidP = NULL;
    secdP = NULL;

    result.type = TRT_BADFUNCTIONCODE;

    --objc;







<
<







831
832
833
834
835
836
837


838
839
840
841
842
843
844
    Tcl_Obj **objPP;
    DWORD nobjs;
    int *iP;
    Tcl_Obj *objP;
    SWSMark mark = NULL;
    TCL_RESULT res;



    daclP = saclP = NULL;
    osidP = gsidP = NULL;
    secdP = NULL;

    result.type = TRT_BADFUNCTIONCODE;

    --objc;
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
            if (res != TCL_OK)
                goto vamoose;
            // Note aclP may me NULL even on TCL_OK
            result.type = TRT_BOOL;
            result.value.bval = daclP ? IsValidAcl(daclP) : 0;
            break;
        case 103:
            res = ObjToLong(interp, objv[0], &ldw);
            if (res != TCL_OK)
                goto vamoose;
            dw = (DWORD) ldw;
            result.value.ival = ImpersonateSelf(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 104:
            res = ObjToHANDLE(interp, objv[0], &h);
            if (res != TCL_OK)
                goto vamoose;







|


<







885
886
887
888
889
890
891
892
893
894

895
896
897
898
899
900
901
            if (res != TCL_OK)
                goto vamoose;
            // Note aclP may me NULL even on TCL_OK
            result.type = TRT_BOOL;
            result.value.bval = daclP ? IsValidAcl(daclP) : 0;
            break;
        case 103:
            res = ObjToInt(interp, objv[0], &dw);
            if (res != TCL_OK)
                goto vamoose;

            result.value.ival = ImpersonateSelf(dw);
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 104:
            res = ObjToHANDLE(interp, objv[0], &h);
            if (res != TCL_OK)
                goto vamoose;
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
        }
    } else if (func < 500) {
        /* Two string args */
        if (objc != 2) {
            res = TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
            goto vamoose;
        }
        s = ObjToUnicode(objv[0]);
        s2 = ObjToUnicode(objv[1]);
        switch (func) {
        case 401:
            result.value.unicode.len = ARRAYSIZE(u.buf);
            if (LookupPrivilegeDisplayNameW(s,s2,u.buf,&result.value.unicode.len,&dw)) {
                result.value.unicode.str = u.buf;
                result.type = TRT_UNICODE;
            } else







|
|







920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
        }
    } else if (func < 500) {
        /* Two string args */
        if (objc != 2) {
            res = TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
            goto vamoose;
        }
        s = ObjToWinChars(objv[0]);
        s2 = ObjToWinChars(objv[1]);
        switch (func) {
        case 401:
            result.value.unicode.len = ARRAYSIZE(u.buf);
            if (LookupPrivilegeDisplayNameW(s,s2,u.buf,&result.value.unicode.len,&dw)) {
                result.value.unicode.str = u.buf;
                result.type = TRT_UNICODE;
            } else
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
    } else if (func < 1000) {
        /* Args - string, dw, optional dw2 */
        res = TwapiGetArgs(interp, objc, objv,
                           ARGSKIP, GETINT(dw), ARGUSEDEFAULT,
                           GETINT(dw2), ARGEND);
        if (res != TCL_OK)
            goto vamoose;
        s = ObjToUnicode(objv[0]);
        switch (func) {
        case 501:
            if (ConvertStringSecurityDescriptorToSecurityDescriptorW(
                    s, dw, &secdP, NULL)) {
                result.value.obj = ObjFromSECURITY_DESCRIPTOR(interp, secdP);
                if (secdP)
                    LocalFree(secdP);







|







945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
    } else if (func < 1000) {
        /* Args - string, dw, optional dw2 */
        res = TwapiGetArgs(interp, objc, objv,
                           ARGSKIP, GETINT(dw), ARGUSEDEFAULT,
                           GETINT(dw2), ARGEND);
        if (res != TCL_OK)
            goto vamoose;
        s = ObjToWinChars(objv[0]);
        switch (func) {
        case 501:
            if (ConvertStringSecurityDescriptorToSecurityDescriptorW(
                    s, dw, &secdP, NULL)) {
                result.value.obj = ObjFromSECURITY_DESCRIPTOR(interp, secdP);
                if (secdP)
                    LocalFree(secdP);
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
            NULLIFY_EMPTY(s);
            if (CredEnumerateW(s, 0, &dw2, &u.credsPP)) {
                result.value.obj = ObjEmptyList();
                for (dw = 0; dw < dw2; ++dw) {
                    Tcl_Obj *objs[10];
                    objs[0] = ObjFromDWORD(u.credsPP[dw]->Flags);
                    objs[1] = ObjFromDWORD(u.credsPP[dw]->Type);
                    objs[2] = ObjFromUnicode(u.credsPP[dw]->TargetName);
                    objs[3] = ObjFromUnicode(u.credsPP[dw]->Comment);
                    objs[4] = ObjFromFILETIME(&u.credsPP[dw]->LastWritten);
                    objs[5] = ObjFromByteArray(u.credsPP[dw]->CredentialBlob,
                                               u.credsPP[dw]->CredentialBlobSize);
                    objs[6] = ObjFromDWORD(u.credsPP[dw]->Persist);
                    objs[7] = ObjEmptyList(); /* Place holder for attributes */
                    objs[8] = ObjFromUnicode(u.credsPP[dw]->TargetAlias);
                    objs[9] = ObjFromUnicode(u.credsPP[dw]->UserName);
                    ObjAppendElement(interp, result.value.obj, ObjNewList(ARRAYSIZE(objs), objs));
                }
                CredFree(u.credsPP);
                result.type = TRT_OBJ;
            } else
                result.type = TRT_GETLASTERROR;
            break;







|
|





|
|







975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
            NULLIFY_EMPTY(s);
            if (CredEnumerateW(s, 0, &dw2, &u.credsPP)) {
                result.value.obj = ObjEmptyList();
                for (dw = 0; dw < dw2; ++dw) {
                    Tcl_Obj *objs[10];
                    objs[0] = ObjFromDWORD(u.credsPP[dw]->Flags);
                    objs[1] = ObjFromDWORD(u.credsPP[dw]->Type);
                    objs[2] = ObjFromWinChars(u.credsPP[dw]->TargetName);
                    objs[3] = ObjFromWinChars(u.credsPP[dw]->Comment);
                    objs[4] = ObjFromFILETIME(&u.credsPP[dw]->LastWritten);
                    objs[5] = ObjFromByteArray(u.credsPP[dw]->CredentialBlob,
                                               u.credsPP[dw]->CredentialBlobSize);
                    objs[6] = ObjFromDWORD(u.credsPP[dw]->Persist);
                    objs[7] = ObjEmptyList(); /* Place holder for attributes */
                    objs[8] = ObjFromWinChars(u.credsPP[dw]->TargetAlias);
                    objs[9] = ObjFromWinChars(u.credsPP[dw]->UserName);
                    ObjAppendElement(interp, result.value.obj, ObjNewList(ARRAYSIZE(objs), objs));
                }
                CredFree(u.credsPP);
                result.type = TRT_OBJ;
            } else
                result.type = TRT_GETLASTERROR;
            break;
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
                ObjToBoolean(interp, objv[1], &dw2) != TCL_OK ||
                ObjGetElements(interp, objv[2], &nobjs, &objPP) != TCL_OK) {
                res = TCL_ERROR;
                goto vamoose;
            }
            iP = SWSAlloc(sizeof(int) * nobjs, NULL);
            for (dw = 0; dw < nobjs; ++dw) {
                if (ObjToLong(interp, objPP[dw], &ldw) != TCL_OK)
                    break;
                iP[dw] = (int) ldw;
            }
            if (dw < nobjs) {
                /* Failed to convert to int */
                res = TCL_ERROR;
                goto vamoose;
            } else {
                POLICY_AUDIT_EVENTS_INFO paei;







|

<







1169
1170
1171
1172
1173
1174
1175
1176
1177

1178
1179
1180
1181
1182
1183
1184
                ObjToBoolean(interp, objv[1], &dw2) != TCL_OK ||
                ObjGetElements(interp, objv[2], &nobjs, &objPP) != TCL_OK) {
                res = TCL_ERROR;
                goto vamoose;
            }
            iP = SWSAlloc(sizeof(int) * nobjs, NULL);
            for (dw = 0; dw < nobjs; ++dw) {
                if (ObjToInt(interp, objPP[dw], &iP[dw]) != TCL_OK)
                    break;

            }
            if (dw < nobjs) {
                /* Failed to convert to int */
                res = TCL_ERROR;
                goto vamoose;
            } else {
                POLICY_AUDIT_EVENTS_INFO paei;
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
            res = TwapiGetArgs(interp, objc, objv,
                               ARGSKIP, ARGSKIP, ARGSKIP,
                               GETINT(dw), GETINT(dw2), ARGEND);
            if (res != TCL_OK)
                goto vamoose;
            passwordP = ObjDecryptPasswordSWS(objv[2], &dw3);
            if (LogonUserW(
                    ObjToUnicode(objv[0]),
                    ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
                    passwordP, dw, dw2, &result.value.hval))
                result.type = TRT_HANDLE;
            else
                result.type = TRT_GETLASTERROR;
            SecureZeroMemory(passwordP, dw3);
            break;







|







1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
            res = TwapiGetArgs(interp, objc, objv,
                               ARGSKIP, ARGSKIP, ARGSKIP,
                               GETINT(dw), GETINT(dw2), ARGEND);
            if (res != TCL_OK)
                goto vamoose;
            passwordP = ObjDecryptPasswordSWS(objv[2], &dw3);
            if (LogonUserW(
                    ObjToWinChars(objv[0]),
                    ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
                    passwordP, dw, dw2, &result.value.hval))
                result.type = TRT_HANDLE;
            else
                result.type = TRT_GETLASTERROR;
            SecureZeroMemory(passwordP, dw3);
            break;
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
                goto vamoose;
            if (ConvertSecurityDescriptorToStringSecurityDescriptorW(
                    secdP, dw, dw2, &s, &dw3)) {
                /* Cannot use TRT_UNICODE since buffer has to be LocalFree'd */
                result.type = TRT_OBJ;
                /* Do not use dw3 as length because it seems to be size
                   of buffer, not string length as it includes padded nulls */
                result.value.obj = ObjFromUnicode(s);
                LocalFree(s);
            } else
                result.type = TRT_GETLASTERROR;
            break;
        case 10018: // UNUSED
            break;
        case 10019:







|







1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
                goto vamoose;
            if (ConvertSecurityDescriptorToStringSecurityDescriptorW(
                    secdP, dw, dw2, &s, &dw3)) {
                /* Cannot use TRT_UNICODE since buffer has to be LocalFree'd */
                result.type = TRT_OBJ;
                /* Do not use dw3 as length because it seems to be size
                   of buffer, not string length as it includes padded nulls */
                result.value.obj = ObjFromWinChars(s);
                LocalFree(s);
            } else
                result.type = TRT_GETLASTERROR;
            break;
        case 10018: // UNUSED
            break;
        case 10019:
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
                               GETVAR(saclP, ObjToPACLSWS),
                               ARGEND);
            if (res != TCL_OK)
                goto vamoose;

            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = SetNamedSecurityInfoW(
                ObjToUnicode(objv[0]),
                dw, dw2, osidP, gsidP, daclP, saclP);
            break;
        case 10021: // LookupPrivilegeName
            res = TwapiGetArgs(interp, objc, objv,
                               ARGSKIP, GETVAR(luid, ObjToLUID),
                               ARGEND);
            if (res != TCL_OK)
                goto vamoose;
            result.value.unicode.len = sizeof(u.buf)/sizeof(u.buf[0]);
            if (LookupPrivilegeNameW(ObjToUnicode(objv[0]), &luid,
                                     u.buf, &result.value.unicode.len)) {
                result.type = TRT_UNICODE;
                result.value.unicode.str = u.buf;
                result.value.unicode.len = -1;
            } else
                result.type = TRT_GETLASTERROR;
            break;







|









|







1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
                               GETVAR(saclP, ObjToPACLSWS),
                               ARGEND);
            if (res != TCL_OK)
                goto vamoose;

            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = SetNamedSecurityInfoW(
                ObjToWinChars(objv[0]),
                dw, dw2, osidP, gsidP, daclP, saclP);
            break;
        case 10021: // LookupPrivilegeName
            res = TwapiGetArgs(interp, objc, objv,
                               ARGSKIP, GETVAR(luid, ObjToLUID),
                               ARGEND);
            if (res != TCL_OK)
                goto vamoose;
            result.value.unicode.len = sizeof(u.buf)/sizeof(u.buf[0]);
            if (LookupPrivilegeNameW(ObjToWinChars(objv[0]), &luid,
                                     u.buf, &result.value.unicode.len)) {
                result.type = TRT_UNICODE;
                result.value.unicode.str = u.buf;
                result.value.unicode.len = -1;
            } else
                result.type = TRT_GETLASTERROR;
            break;
Changes to undroid/twapi/twapi/service/scm.c.
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    objv[4] = STRING_LITERAL_OBJ("-starttype");
    objv[5] = ObjFromDWORD(qbuf->dwStartType);
    objv[6] = STRING_LITERAL_OBJ("-errorcontrol");
    objv[7] = ObjFromDWORD(qbuf->dwErrorControl);
    objv[8] = STRING_LITERAL_OBJ("-tagid");
    objv[9] = ObjFromDWORD(qbuf->dwTagId);
    objv[10] = STRING_LITERAL_OBJ("-command");
    objv[11] = ObjFromUnicode(qbuf->lpBinaryPathName);
    objv[12] = STRING_LITERAL_OBJ("-loadordergroup");
    objv[13] = ObjFromUnicode(qbuf->lpLoadOrderGroup);
    objv[14] = STRING_LITERAL_OBJ("-account");
    objv[15] = ObjFromUnicode(qbuf->lpServiceStartName);
    objv[16] = STRING_LITERAL_OBJ("-displayname");
    objv[17] = ObjFromUnicode(qbuf->lpDisplayName);
    objv[18] = STRING_LITERAL_OBJ("-interactive");
    objv[19] = ObjFromBoolean(qbuf->dwServiceType & SERVICE_INTERACTIVE_PROCESS);
    ObjSetResult(ticP->interp, ObjNewList(20,objv));
    tcl_result = TCL_OK;

vamoose:
    MemLifoPopFrame(ticP->memlifoP);
    if (tcl_result != TCL_OK)
        Twapi_AppendSystemError(ticP->interp, winerr);

    return tcl_result;
}


Tcl_Obj *ObjFromSERVICE_FAILURE_ACTIONS(SERVICE_FAILURE_ACTIONSW *sfaP)
{
    Tcl_Obj *objs[4];
    DWORD i;

    objs[0] = ObjFromLong(sfaP->dwResetPeriod);
    objs[1] = ObjFromUnicode(sfaP->lpRebootMsg);
    objs[2] = ObjFromUnicode(sfaP->lpCommand);
    objs[3] = ObjNewList(sfaP->cActions, NULL);
    if (sfaP->lpsaActions) {
        for (i = 0; i < sfaP->cActions; ++i) {
            Tcl_Obj *fields[2];
            fields[0] = ObjFromInt(sfaP->lpsaActions[i].Type);
            fields[1] = ObjFromDWORD(sfaP->lpsaActions[i].Delay);
            ObjAppendElement(NULL, objs[3], ObjNewList(2, fields));







|

|

|

|




















|
|







139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    objv[4] = STRING_LITERAL_OBJ("-starttype");
    objv[5] = ObjFromDWORD(qbuf->dwStartType);
    objv[6] = STRING_LITERAL_OBJ("-errorcontrol");
    objv[7] = ObjFromDWORD(qbuf->dwErrorControl);
    objv[8] = STRING_LITERAL_OBJ("-tagid");
    objv[9] = ObjFromDWORD(qbuf->dwTagId);
    objv[10] = STRING_LITERAL_OBJ("-command");
    objv[11] = ObjFromWinChars(qbuf->lpBinaryPathName);
    objv[12] = STRING_LITERAL_OBJ("-loadordergroup");
    objv[13] = ObjFromWinChars(qbuf->lpLoadOrderGroup);
    objv[14] = STRING_LITERAL_OBJ("-account");
    objv[15] = ObjFromWinChars(qbuf->lpServiceStartName);
    objv[16] = STRING_LITERAL_OBJ("-displayname");
    objv[17] = ObjFromWinChars(qbuf->lpDisplayName);
    objv[18] = STRING_LITERAL_OBJ("-interactive");
    objv[19] = ObjFromBoolean(qbuf->dwServiceType & SERVICE_INTERACTIVE_PROCESS);
    ObjSetResult(ticP->interp, ObjNewList(20,objv));
    tcl_result = TCL_OK;

vamoose:
    MemLifoPopFrame(ticP->memlifoP);
    if (tcl_result != TCL_OK)
        Twapi_AppendSystemError(ticP->interp, winerr);

    return tcl_result;
}


Tcl_Obj *ObjFromSERVICE_FAILURE_ACTIONS(SERVICE_FAILURE_ACTIONSW *sfaP)
{
    Tcl_Obj *objs[4];
    DWORD i;

    objs[0] = ObjFromLong(sfaP->dwResetPeriod);
    objs[1] = ObjFromWinChars(sfaP->lpRebootMsg);
    objs[2] = ObjFromWinChars(sfaP->lpCommand);
    objs[3] = ObjNewList(sfaP->cActions, NULL);
    if (sfaP->lpsaActions) {
        for (i = 0; i < sfaP->cActions; ++i) {
            Tcl_Obj *fields[2];
            fields[0] = ObjFromInt(sfaP->lpsaActions[i].Type);
            fields[1] = ObjFromDWORD(sfaP->lpsaActions[i].Delay);
            ObjAppendElement(NULL, objs[3], ObjNewList(2, fields));
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    bufP = MemLifoPushFrame(ticP->memlifoP, buf_sz, &buf_sz);
    if (QueryServiceConfig2W(hService, level, (LPBYTE) bufP, buf_sz, &buf_sz)) {
        switch (level) {
        case SERVICE_CONFIG_DESCRIPTION:
            /* If NULL, we keep result as empty string. Not an error */
            res = TCL_OK;
            if (((SERVICE_DESCRIPTIONW *)bufP)->lpDescription)
                ObjSetResult(ticP->interp, ObjFromUnicode(((SERVICE_DESCRIPTIONW *)bufP)->lpDescription));
            break;

        case SERVICE_CONFIG_FAILURE_ACTIONS:
            ObjSetResult(ticP->interp, ObjFromSERVICE_FAILURE_ACTIONS(bufP));
            res = TCL_OK;
            break;








|







198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    bufP = MemLifoPushFrame(ticP->memlifoP, buf_sz, &buf_sz);
    if (QueryServiceConfig2W(hService, level, (LPBYTE) bufP, buf_sz, &buf_sz)) {
        switch (level) {
        case SERVICE_CONFIG_DESCRIPTION:
            /* If NULL, we keep result as empty string. Not an error */
            res = TCL_OK;
            if (((SERVICE_DESCRIPTIONW *)bufP)->lpDescription)
                ObjSetResult(ticP->interp, ObjFromWinChars(((SERVICE_DESCRIPTIONW *)bufP)->lpDescription));
            break;

        case SERVICE_CONFIG_FAILURE_ACTIONS:
            ObjSetResult(ticP->interp, ObjFromSERVICE_FAILURE_ACTIONS(bufP));
            res = TCL_OK;
            break;

372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
            rec[2] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwControlsAccepted);
            rec[3] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwWin32ExitCode);
            rec[4] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwServiceSpecificExitCode);
            rec[5] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwCheckPoint);
            rec[6] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwWaitHint);
            rec[7] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwProcessId);
            rec[8] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwServiceFlags);
            rec[9] = ObjFromUnicode(sbuf[i].lpServiceName); /* KEY for record array */
            rec[10] = ObjFromUnicode(sbuf[i].lpDisplayName);
            rec[11] = Tcl_NewBooleanObj(sbuf[i].ServiceStatusProcess.dwServiceType & SERVICE_INTERACTIVE_PROCESS);

            ObjAppendElement(NULL, resultObj, ObjNewList(ARRAYSIZE(rec), rec));
        }
        /* If !success -> ERROR_MORE_DATA so keep looping */
    } while (! success);








|
|







372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
            rec[2] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwControlsAccepted);
            rec[3] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwWin32ExitCode);
            rec[4] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwServiceSpecificExitCode);
            rec[5] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwCheckPoint);
            rec[6] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwWaitHint);
            rec[7] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwProcessId);
            rec[8] = ObjFromDWORD(sbuf[i].ServiceStatusProcess.dwServiceFlags);
            rec[9] = ObjFromWinChars(sbuf[i].lpServiceName); /* KEY for record array */
            rec[10] = ObjFromWinChars(sbuf[i].lpDisplayName);
            rec[11] = Tcl_NewBooleanObj(sbuf[i].ServiceStatusProcess.dwServiceType & SERVICE_INTERACTIVE_PROCESS);

            ObjAppendElement(NULL, resultObj, ObjNewList(ARRAYSIZE(rec), rec));
        }
        /* If !success -> ERROR_MORE_DATA so keep looping */
    } while (! success);

473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
        else
            rec[1] = ObjFromDWORD(dw);
        rec[2] = ObjFromDWORD(sbuf[i].ServiceStatus.dwControlsAccepted);
        rec[3] = ObjFromDWORD(sbuf[i].ServiceStatus.dwWin32ExitCode);
        rec[4] = ObjFromDWORD(sbuf[i].ServiceStatus.dwServiceSpecificExitCode);
        rec[5] = ObjFromDWORD(sbuf[i].ServiceStatus.dwCheckPoint);
        rec[6] = ObjFromDWORD(sbuf[i].ServiceStatus.dwWaitHint);
        rec[7] = ObjFromUnicode(sbuf[i].lpServiceName); /* KEY for record array */
        rec[8] = ObjFromUnicode(sbuf[i].lpDisplayName);
        rec[9] = ObjFromDWORD(sbuf[i].ServiceStatus.dwServiceType & SERVICE_INTERACTIVE_PROCESS);

        ObjAppendElement(NULL, resultObj, ObjNewList(ARRAYSIZE(rec), rec));
    }

    ObjSetResult(interp, resultObj);
    status = TCL_OK;







|
|







473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
        else
            rec[1] = ObjFromDWORD(dw);
        rec[2] = ObjFromDWORD(sbuf[i].ServiceStatus.dwControlsAccepted);
        rec[3] = ObjFromDWORD(sbuf[i].ServiceStatus.dwWin32ExitCode);
        rec[4] = ObjFromDWORD(sbuf[i].ServiceStatus.dwServiceSpecificExitCode);
        rec[5] = ObjFromDWORD(sbuf[i].ServiceStatus.dwCheckPoint);
        rec[6] = ObjFromDWORD(sbuf[i].ServiceStatus.dwWaitHint);
        rec[7] = ObjFromWinChars(sbuf[i].lpServiceName); /* KEY for record array */
        rec[8] = ObjFromWinChars(sbuf[i].lpDisplayName);
        rec[9] = ObjFromDWORD(sbuf[i].ServiceStatus.dwServiceType & SERVICE_INTERACTIVE_PROCESS);

        ObjAppendElement(NULL, resultObj, ObjNewList(ARRAYSIZE(rec), rec));
    }

    ObjSetResult(interp, resultObj);
    status = TCL_OK;
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
    */
    if (nobjs == 0)
        return TCL_OK;

    for (i = 0; i < nobjs; ++i) {
        Tcl_Obj **fields;
        int nfields;
        long lsc_type, ldelay;

        res = ObjGetElements(interp, objs[i], &nfields, &fields);
        if (res != TCL_OK)
            return res;
        if (nfields != 2)
            return TwapiReturnError(interp, TWAPI_INVALID_DATA);
        if (ObjToLong(interp, fields[0], &lsc_type) != TCL_OK ||
            ObjToLong(interp, fields[1], &ldelay) != TCL_OK)
            return TCL_ERROR;
	
        sfaP->lpsaActions[i].Type = (SC_ACTION_TYPE) lsc_type;
        sfaP->lpsaActions[i].Delay = ldelay;
    }        

    return TCL_OK;
}


static TCL_RESULT Twapi_ChangeServiceConfig2(TwapiInterpContext *ticP, int objc, Tcl_Obj *CONST objv[])







|






|
|

<
|
<







542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558

559

560
561
562
563
564
565
566
    */
    if (nobjs == 0)
        return TCL_OK;

    for (i = 0; i < nobjs; ++i) {
        Tcl_Obj **fields;
        int nfields;
        int sc_type;

        res = ObjGetElements(interp, objs[i], &nfields, &fields);
        if (res != TCL_OK)
            return res;
        if (nfields != 2)
            return TwapiReturnError(interp, TWAPI_INVALID_DATA);
        if (ObjToInt(interp, fields[0], &sc_type) != TCL_OK ||
            ObjToInt(interp, fields[1], &sfaP->lpsaActions[i].Delay) != TCL_OK)
            return TCL_ERROR;

        sfaP->lpsaActions[i].Type = (SC_ACTION_TYPE) sc_type;

    }        

    return TCL_OK;
}


static TCL_RESULT Twapi_ChangeServiceConfig2(TwapiInterpContext *ticP, int objc, Tcl_Obj *CONST objv[])
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
                         GETOBJ(infoObj), ARGEND);
    if (res != TCL_OK)
        goto vamoose;

    switch (info_level) {
    case SERVICE_CONFIG_DESCRIPTION:
        pv = &u.desc;
        u.desc.lpDescription = ObjToUnicode(infoObj);
        break;
    case SERVICE_CONFIG_FAILURE_ACTIONS:
        pv = &u.failure_actions;
        res = ParseSERVICE_FAILURE_ACTIONS(ticP, infoObj, &u.failure_actions);
        break;
    default:
        res = TwapiReturnError(ticP->interp, TWAPI_INVALID_OPTION);







|







582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
                         GETOBJ(infoObj), ARGEND);
    if (res != TCL_OK)
        goto vamoose;

    switch (info_level) {
    case SERVICE_CONFIG_DESCRIPTION:
        pv = &u.desc;
        u.desc.lpDescription = ObjToWinChars(infoObj);
        break;
    case SERVICE_CONFIG_FAILURE_ACTIONS:
        pv = &u.failure_actions;
        res = ParseSERVICE_FAILURE_ACTIONS(ticP, infoObj, &u.failure_actions);
        break;
    default:
        res = TwapiReturnError(ticP->interp, TWAPI_INVALID_OPTION);
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
            res = TCL_ERROR;
            goto vamoose;   /* interp already holds error fom ObjToLong */
        }
        Tcl_ResetResult(interp);
        tag_idP = NULL;         /* Tag is not to be changed */
    }

    dependencies = ObjToUnicode(depObj);
    if (lstrcmpW(dependencies, NULL_TOKEN_L) == 0) {
        dependencies = NULL;
    } else {
        res = ObjToMultiSzEx(interp, depObj, (LPCWSTR*) &dependencies, ticP->memlifoP);
        if (res != TCL_OK)
            goto vamoose;
    }







|







644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
            res = TCL_ERROR;
            goto vamoose;   /* interp already holds error fom ObjToLong */
        }
        Tcl_ResetResult(interp);
        tag_idP = NULL;         /* Tag is not to be changed */
    }

    dependencies = ObjToWinChars(depObj);
    if (lstrcmpW(dependencies, NULL_TOKEN_L) == 0) {
        dependencies = NULL;
    } else {
        res = ObjToMultiSzEx(interp, depObj, (LPCWSTR*) &dependencies, ticP->memlifoP);
        if (res != TCL_OK)
            goto vamoose;
    }
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
    else {
        /* An empty string means value is not to be changed. Else error */
        if (Tcl_GetCharLength(tagObj) != 0)
            return TCL_ERROR;   /* interp already holds error */
        tag_idP = NULL;         /* Tag is not to be changed */
    }

    dependencies = ObjToUnicode(depObj);
    if (lstrcmpW(dependencies, NULL_TOKEN_L) == 0) {
        dependencies = NULL;
    } else {
        res = ObjToMultiSzEx(interp, depObj, (LPCWSTR*) &dependencies, ticP->memlifoP);
        if (res == TCL_ERROR)
            goto vamoose;
    }







|







719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    else {
        /* An empty string means value is not to be changed. Else error */
        if (Tcl_GetCharLength(tagObj) != 0)
            return TCL_ERROR;   /* interp already holds error */
        tag_idP = NULL;         /* Tag is not to be changed */
    }

    dependencies = ObjToWinChars(depObj);
    if (lstrcmpW(dependencies, NULL_TOKEN_L) == 0) {
        dependencies = NULL;
    } else {
        res = ObjToMultiSzEx(interp, depObj, (LPCWSTR*) &dependencies, ticP->memlifoP);
        if (res == TCL_ERROR)
            goto vamoose;
    }
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790

    if (nargs > ARRAYSIZE(args)) {
        ObjSetStaticResult(interp, "Exceeded limit on number of service arguments.");
        return TCL_ERROR;
    }

    for (i = 0; i < nargs; i++) {
        args[i] = ObjToUnicode(argObjs[i]);
    }
    if (StartServiceW(svcH, nargs, args))
        return TCL_OK;
    else
        return TwapiReturnSystemError(interp);
}








|







774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

    if (nargs > ARRAYSIZE(args)) {
        ObjSetStaticResult(interp, "Exceeded limit on number of service arguments.");
        return TCL_ERROR;
    }

    for (i = 0; i < nargs; i++) {
        args[i] = ObjToWinChars(argObjs[i]);
    }
    if (StartServiceW(svcH, nargs, args))
        return TCL_OK;
    else
        return TwapiReturnSystemError(interp);
}

825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
        WCHAR buf[MAX_PATH+1];
    } u;
    DWORD dw;
    LPWSTR s;
    HANDLE h;
    Tcl_Obj *sObj;

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {







<
<







823
824
825
826
827
828
829


830
831
832
833
834
835
836
        WCHAR buf[MAX_PATH+1];
    } u;
    DWORD dw;
    LPWSTR s;
    HANDLE h;
    Tcl_Obj *sObj;



    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
    CHECK_INTEGER_OBJ(interp, func, objv[1]);

    result.type = TRT_BADFUNCTIONCODE;

    if (func < 100) {
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
        }
    } else if (func < 300) {
        /* Handle, string, int */
        if (TwapiGetArgs(interp, objc-2, objv+2,
                         GETHANDLE(h), GETOBJ(sObj), ARGUSEDEFAULT,
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToUnicode(sObj);
        switch (func) {
        case 201:
            result.value.unicode.len = sizeof(u.buf)/sizeof(u.buf[0]);
            if (GetServiceKeyNameW(h, s, u.buf, &result.value.unicode.len)) {
                result.value.unicode.str = u.buf;
                result.type = TRT_UNICODE;
            } else







|







872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
        }
    } else if (func < 300) {
        /* Handle, string, int */
        if (TwapiGetArgs(interp, objc-2, objv+2,
                         GETHANDLE(h), GETOBJ(sObj), ARGUSEDEFAULT,
                         GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToWinChars(sObj);
        switch (func) {
        case 201:
            result.value.unicode.len = sizeof(u.buf)/sizeof(u.buf[0]);
            if (GetServiceKeyNameW(h, s, u.buf, &result.value.unicode.len)) {
                result.value.unicode.str = u.buf;
                result.type = TRT_UNICODE;
            } else
Changes to undroid/twapi/twapi/service/service.c.
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
                     GETINT(ss.dwCheckPoint),
                     GETINT(ss.dwWaitHint), GETINT(ss.dwControlsAccepted),
                     ARGEND
            )
        != TCL_OK)
        return TCL_ERROR;

    service_index = TwapiFindServiceIndex(ObjToUnicode(objv[0]));
    if (service_index < 0)
        return Twapi_AppendSystemError(ticP->interp, ERROR_INVALID_NAME);

    ss.dwServiceType  = gServiceType;

    if (SetServiceStatus(gServiceContexts[service_index]->service_status_handle, &ss))
        return TCL_OK;







|







82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
                     GETINT(ss.dwCheckPoint),
                     GETINT(ss.dwWaitHint), GETINT(ss.dwControlsAccepted),
                     ARGEND
            )
        != TCL_OK)
        return TCL_ERROR;

    service_index = TwapiFindServiceIndex(ObjToWinChars(objv[0]));
    if (service_index < 0)
        return Twapi_AppendSystemError(ticP->interp, ERROR_INVALID_NAME);

    ss.dwServiceType  = gServiceType;

    if (SetServiceStatus(gServiceContexts[service_index]->service_status_handle, &ss))
        return TCL_OK;
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        if (ObjGetElements(interp, objv[i+1], &n, &objs) != TCL_OK ||
            n != 2 ||
            ObjToLong(interp, objs[1], &ctrls) != TCL_OK) {
            ObjSetStaticResult(interp, "Invalid service specification.");
            goto error_handler;
        }
        /* Allocate a single block for the context and name */
        nameP = ObjToUnicodeN(objs[0], &n);
        gServiceContexts[i] = TwapiAlloc(SIZE_TwapiServiceContext(n));
        CopyMemory(gServiceContexts[i]->name, nameP, sizeof(WCHAR)*(n+1));
        gServiceContexts[i]->controls_accepted = ctrls;
        gServiceContexts[i]->service_status_handle = NULL;
    }

    /*







|







134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        if (ObjGetElements(interp, objv[i+1], &n, &objs) != TCL_OK ||
            n != 2 ||
            ObjToLong(interp, objs[1], &ctrls) != TCL_OK) {
            ObjSetStaticResult(interp, "Invalid service specification.");
            goto error_handler;
        }
        /* Allocate a single block for the context and name */
        nameP = ObjToWinCharsN(objs[0], &n);
        gServiceContexts[i] = TwapiAlloc(SIZE_TwapiServiceContext(n));
        CopyMemory(gServiceContexts[i]->name, nameP, sizeof(WCHAR)*(n+1));
        gServiceContexts[i]->controls_accepted = ctrls;
        gServiceContexts[i]->service_status_handle = NULL;
    }

    /*
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
        }
    }

    if (ctrl_str) {
        Tcl_Obj *objs[6];
        int nobjs = 0;
        objs[0] = STRING_LITERAL_OBJ(TWAPI_TCL_NAMESPACE "::_service_handler");
        objs[1] = ObjFromUnicode(gServiceContexts[cbP->service_index]->name);
        objs[2] = ObjFromOpaque(gServiceContexts[cbP->service_index]->service_status_handle, "SERVICE_STATUS_HANDLE");
        objs[3] = Tcl_NewStringObj(ctrl_str, -1);
        objs[4] = Tcl_NewLongObj(cbP->ctrl);
        nobjs = 5;
        if (event_str) {
            objs[nobjs++] = Tcl_NewStringObj(event_str, -1);
            if (cbP->ctrl == SERVICE_CONTROL_SESSIONCHANGE)







|







338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
        }
    }

    if (ctrl_str) {
        Tcl_Obj *objs[6];
        int nobjs = 0;
        objs[0] = STRING_LITERAL_OBJ(TWAPI_TCL_NAMESPACE "::_service_handler");
        objs[1] = ObjFromWinChars(gServiceContexts[cbP->service_index]->name);
        objs[2] = ObjFromOpaque(gServiceContexts[cbP->service_index]->service_status_handle, "SERVICE_STATUS_HANDLE");
        objs[3] = Tcl_NewStringObj(ctrl_str, -1);
        objs[4] = Tcl_NewLongObj(cbP->ctrl);
        nobjs = 5;
        if (event_str) {
            objs[nobjs++] = Tcl_NewStringObj(event_str, -1);
            if (cbP->ctrl == SERVICE_CONTROL_SESSIONCHANGE)
Changes to undroid/twapi/twapi/share/share.c.
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

    ciP = (CONNECTION_INFO_1 *) infoP; /* May actually be CONNECTION_INFO_0 */

    objc = 1;
    switch (level) {
    case 1:
        objc += 6;
        objv[6] = ObjFromUnicode(ciP->coni1_netname);
        objv[5] = ObjFromUnicode(ciP->coni1_username);
        objv[4] = ObjFromLong(ciP->coni1_time);
        objv[3] = ObjFromLong(ciP->coni1_num_users);
        objv[2] = ObjFromLong(ciP->coni1_num_opens);
        objv[1] = ObjFromLong(ciP->coni1_type);
        /* FALLTHRU */
    case 0:
        objv[0] = ObjFromLong(ciP->coni1_id);







|
|







89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

    ciP = (CONNECTION_INFO_1 *) infoP; /* May actually be CONNECTION_INFO_0 */

    objc = 1;
    switch (level) {
    case 1:
        objc += 6;
        objv[6] = ObjFromWinChars(ciP->coni1_netname);
        objv[5] = ObjFromWinChars(ciP->coni1_username);
        objv[4] = ObjFromLong(ciP->coni1_time);
        objv[3] = ObjFromLong(ciP->coni1_num_users);
        objv[2] = ObjFromLong(ciP->coni1_num_opens);
        objv[1] = ObjFromLong(ciP->coni1_type);
        /* FALLTHRU */
    case 0:
        objv[0] = ObjFromLong(ciP->coni1_id);
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    uiP = (USE_INFO_2 *) infoP; /* May acutally be any USE_INFO_* */

    objc = 2;
    switch (level) {
    case 2:
        objc += 2;
        objv[8] = ObjFromUnicode(uiP->ui2_domainname);
        objv[7] = ObjFromUnicode(uiP->ui2_username);
        // FALLTHRU
    case 1:
        objc += 5;
        /* Does this contain a valid value and need to be encrypted ? - TBD */
        objv[6] = ObjFromDWORD(uiP->ui2_usecount);
        objv[5] = ObjFromDWORD(uiP->ui2_refcount);
        objv[4] = ObjFromDWORD(uiP->ui2_asg_type);
        objv[3] = ObjFromDWORD(uiP->ui2_status);
        objv[2] = ObjFromUnicode(uiP->ui2_password);
        //FALLTHRU
    case 0:
        objv[1] = ObjFromUnicode(uiP->ui2_remote);
        objv[0] = ObjFromUnicode(uiP->ui2_local);
        break;

    default:
        Twapi_WrongLevelError(interp, level);
        return NULL;
    }








|
|








|


|
|







124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    uiP = (USE_INFO_2 *) infoP; /* May acutally be any USE_INFO_* */

    objc = 2;
    switch (level) {
    case 2:
        objc += 2;
        objv[8] = ObjFromWinChars(uiP->ui2_domainname);
        objv[7] = ObjFromWinChars(uiP->ui2_username);
        // FALLTHRU
    case 1:
        objc += 5;
        /* Does this contain a valid value and need to be encrypted ? - TBD */
        objv[6] = ObjFromDWORD(uiP->ui2_usecount);
        objv[5] = ObjFromDWORD(uiP->ui2_refcount);
        objv[4] = ObjFromDWORD(uiP->ui2_asg_type);
        objv[3] = ObjFromDWORD(uiP->ui2_status);
        objv[2] = ObjFromWinChars(uiP->ui2_password);
        //FALLTHRU
    case 0:
        objv[1] = ObjFromWinChars(uiP->ui2_remote);
        objv[0] = ObjFromWinChars(uiP->ui2_local);
        break;

    default:
        Twapi_WrongLevelError(interp, level);
        return NULL;
    }

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        objc += 2;
        objv[9] = ObjFromSECURITY_DESCRIPTOR(interp,
                                            siP->shi502_security_descriptor);
        objv[8] = ObjFromDWORD(siP->shi502_reserved);
        // FALLTHRU
    case 2:
        objc += 5;
        objv[7] = ObjFromUnicode(siP->shi502_passwd ? siP->shi502_passwd : L"");
        objv[6] = ObjFromUnicode(siP->shi502_path);
        objv[5] = ObjFromLong(siP->shi502_current_uses);
        objv[4] = ObjFromLong(siP->shi502_max_uses);
        objv[3] = ObjFromDWORD(siP->shi502_permissions);
        // FALLTHRU
    case 1:
        objc += 2;
        objv[2] = ObjFromUnicode(siP->shi502_remark);
        objv[1] = ObjFromDWORD(siP->shi502_type);
        // FALLTHRU
    case 0:
        objv[0] = ObjFromUnicode(siP->shi502_netname);
        break;

    default:
        Twapi_WrongLevelError(interp, level);
        return NULL;
    }








|
|






|



|







171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        objc += 2;
        objv[9] = ObjFromSECURITY_DESCRIPTOR(interp,
                                            siP->shi502_security_descriptor);
        objv[8] = ObjFromDWORD(siP->shi502_reserved);
        // FALLTHRU
    case 2:
        objc += 5;
        objv[7] = ObjFromWinChars(siP->shi502_passwd ? siP->shi502_passwd : L"");
        objv[6] = ObjFromWinChars(siP->shi502_path);
        objv[5] = ObjFromLong(siP->shi502_current_uses);
        objv[4] = ObjFromLong(siP->shi502_max_uses);
        objv[3] = ObjFromDWORD(siP->shi502_permissions);
        // FALLTHRU
    case 1:
        objc += 2;
        objv[2] = ObjFromWinChars(siP->shi502_remark);
        objv[1] = ObjFromDWORD(siP->shi502_type);
        // FALLTHRU
    case 0:
        objv[0] = ObjFromWinChars(siP->shi502_netname);
        break;

    default:
        Twapi_WrongLevelError(interp, level);
        return NULL;
    }

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

    fiP = (FILE_INFO_3 *) infoP; /* May acutally be FILE_INFO_* */

    objc = 1;
    switch (level) {
    case 3:
        objc += 4;
        objv[4] = ObjFromUnicode(fiP->fi3_username);
        objv[3] = ObjFromUnicode(fiP->fi3_pathname);
        objv[2] = ObjFromLong(fiP->fi3_num_locks);
        objv[1] = ObjFromLong(fiP->fi3_permissions);
        /* FALLTHRU */
    case 2:
        objv[0] = ObjFromLong(fiP->fi3_id);
        break;
    default:







|
|







211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

    fiP = (FILE_INFO_3 *) infoP; /* May acutally be FILE_INFO_* */

    objc = 1;
    switch (level) {
    case 3:
        objc += 4;
        objv[4] = ObjFromWinChars(fiP->fi3_username);
        objv[3] = ObjFromWinChars(fiP->fi3_pathname);
        objv[2] = ObjFromLong(fiP->fi3_num_locks);
        objv[1] = ObjFromLong(fiP->fi3_permissions);
        /* FALLTHRU */
    case 2:
        objv[0] = ObjFromLong(fiP->fi3_id);
        break;
    default:
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
       another except level 10
    */

    objc = 0;
    switch (level) {
    case 502:
        objc += 1;
        objv[7] = ObjFromUnicode(((SESSION_INFO_502 *)infoP)->sesi502_transport);
        /* FALLTHRU */
    case 2:
        objc += 1;
        objv[6] = ObjFromUnicode(((SESSION_INFO_2 *)infoP)->sesi2_cltype_name);
        /* FALLTHRU */
    case 1:
        objc += 5;
        objv[5] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_user_flags);
        objv[4] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_idle_time);
        objv[3] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_time);
        objv[2] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_num_opens);
        objv[1] = ObjFromUnicode(((SESSION_INFO_1 *)infoP)->sesi1_username);
        /* FALLTHRU */
    case 0:
        objc += 1;
        objv[0] = ObjFromUnicode(((SESSION_INFO_0 *)infoP)->sesi0_cname);
        break;

    case 10:
        objc = 4;
        objv[0] = ObjFromUnicode(((SESSION_INFO_10 *)infoP)->sesi10_cname);
        objv[1] = ObjFromUnicode(((SESSION_INFO_10 *)infoP)->sesi10_username);
        objv[2] = ObjFromLong(((SESSION_INFO_10 *)infoP)->sesi10_time);
        objv[3] = ObjFromLong(((SESSION_INFO_10 *)infoP)->sesi10_idle_time);
        break;

    default:
        Twapi_WrongLevelError(interp, level);
        return NULL;







|



|







|



|




|
|







245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
       another except level 10
    */

    objc = 0;
    switch (level) {
    case 502:
        objc += 1;
        objv[7] = ObjFromWinChars(((SESSION_INFO_502 *)infoP)->sesi502_transport);
        /* FALLTHRU */
    case 2:
        objc += 1;
        objv[6] = ObjFromWinChars(((SESSION_INFO_2 *)infoP)->sesi2_cltype_name);
        /* FALLTHRU */
    case 1:
        objc += 5;
        objv[5] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_user_flags);
        objv[4] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_idle_time);
        objv[3] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_time);
        objv[2] = ObjFromLong(((SESSION_INFO_1 *)infoP)->sesi1_num_opens);
        objv[1] = ObjFromWinChars(((SESSION_INFO_1 *)infoP)->sesi1_username);
        /* FALLTHRU */
    case 0:
        objc += 1;
        objv[0] = ObjFromWinChars(((SESSION_INFO_0 *)infoP)->sesi0_cname);
        break;

    case 10:
        objc = 4;
        objv[0] = ObjFromWinChars(((SESSION_INFO_10 *)infoP)->sesi10_cname);
        objv[1] = ObjFromWinChars(((SESSION_INFO_10 *)infoP)->sesi10_username);
        objv[2] = ObjFromLong(((SESSION_INFO_10 *)infoP)->sesi10_time);
        objv[3] = ObjFromLong(((SESSION_INFO_10 *)infoP)->sesi10_idle_time);
        break;

    default:
        Twapi_WrongLevelError(interp, level);
        return NULL;
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
{
    Tcl_Obj *objs[8];

    objs[0] = ObjFromDWORD(nrP->dwScope);
    objs[1] = ObjFromDWORD(nrP->dwType);
    objs[2] = ObjFromDWORD(nrP->dwDisplayType);
    objs[3] = ObjFromDWORD(nrP->dwUsage);
    objs[4] = ObjFromUnicode(nrP->lpLocalName);
    objs[5] = ObjFromUnicode(nrP->lpRemoteName);
    objs[6] = ObjFromUnicode(nrP->lpComment);
    objs[7] = ObjFromUnicode(nrP->lpProvider);

    return ObjNewList(8, objs);
}    

/*
 * Convert REMOTE_NAME_INFOW structure to Tcl list. Returns TCL_OK/TCL_ERROR
 * interp may be NULL
 */
static Tcl_Obj *ListObjFromREMOTE_NAME_INFOW(
    Tcl_Interp         *interp,
    REMOTE_NAME_INFOW *rniP
    ) 
{
    Tcl_Obj *objv[3];

    objv[0] = ObjFromUnicode(rniP->lpUniversalName);
    objv[1] = ObjFromUnicode(rniP->lpConnectionName);
    objv[2] = ObjFromUnicode(rniP->lpRemainingPath);

    return ObjNewList(3, objv);
}

int Twapi_NetShareAdd(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    LPWSTR server_name;







|
|
|
|















|
|
|







296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
{
    Tcl_Obj *objs[8];

    objs[0] = ObjFromDWORD(nrP->dwScope);
    objs[1] = ObjFromDWORD(nrP->dwType);
    objs[2] = ObjFromDWORD(nrP->dwDisplayType);
    objs[3] = ObjFromDWORD(nrP->dwUsage);
    objs[4] = ObjFromWinChars(nrP->lpLocalName);
    objs[5] = ObjFromWinChars(nrP->lpRemoteName);
    objs[6] = ObjFromWinChars(nrP->lpComment);
    objs[7] = ObjFromWinChars(nrP->lpProvider);

    return ObjNewList(8, objs);
}    

/*
 * Convert REMOTE_NAME_INFOW structure to Tcl list. Returns TCL_OK/TCL_ERROR
 * interp may be NULL
 */
static Tcl_Obj *ListObjFromREMOTE_NAME_INFOW(
    Tcl_Interp         *interp,
    REMOTE_NAME_INFOW *rniP
    ) 
{
    Tcl_Obj *objv[3];

    objv[0] = ObjFromWinChars(rniP->lpUniversalName);
    objv[1] = ObjFromWinChars(rniP->lpConnectionName);
    objv[2] = ObjFromWinChars(rniP->lpRemainingPath);

    return ObjNewList(3, objv);
}

int Twapi_NetShareAdd(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    LPWSTR server_name;
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359

    mark = SWSPushMark();
    if (ObjToPSECURITY_DESCRIPTORSWS(interp, objv[6], &secdP) != TCL_OK) {
        SWSPopMark(mark);
        return TCL_ERROR;
    }
    server_name = ObjToLPWSTR_NULL_IF_EMPTY(objv[0]);
    share_info.shi502_netname = ObjToUnicode(objv[1]);
    share_info.shi502_remark  = ObjToUnicode(objv[3]);
    share_info.shi502_path    = ObjToUnicode(objv[5]);
    share_info.shi502_permissions = 0;
    share_info.shi502_current_uses = 0;
    share_info.shi502_passwd       = NULL;
    share_info.shi502_reserved     = 0;
    share_info.shi502_security_descriptor = secdP;
    
    status = NetShareAdd(server_name, 502, (unsigned char *)&share_info, &parm_err);







|
|
|







343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359

    mark = SWSPushMark();
    if (ObjToPSECURITY_DESCRIPTORSWS(interp, objv[6], &secdP) != TCL_OK) {
        SWSPopMark(mark);
        return TCL_ERROR;
    }
    server_name = ObjToLPWSTR_NULL_IF_EMPTY(objv[0]);
    share_info.shi502_netname = ObjToWinChars(objv[1]);
    share_info.shi502_remark  = ObjToWinChars(objv[3]);
    share_info.shi502_path    = ObjToWinChars(objv[5]);
    share_info.shi502_permissions = 0;
    share_info.shi502_current_uses = 0;
    share_info.shi502_passwd       = NULL;
    share_info.shi502_reserved     = 0;
    share_info.shi502_security_descriptor = secdP;
    
    status = NetShareAdd(server_name, 502, (unsigned char *)&share_info, &parm_err);
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
    /* TBD - what is the type of HWD ? SHould it not use ObjToHWND ? */
    if (ObjToHWND(interp, objv[0], &winH) != TCL_OK)
        return TCL_ERROR;
    CHECK_INTEGER_OBJ(interp, netresource.dwType, objv[1]);
    CHECK_INTEGER_OBJ(interp, ignore_password, objv[6]);
    CHECK_INTEGER_OBJ(interp, flags, objv[8]);
    netresource.lpLocalName = ObjToLPWSTR_NULL_IF_EMPTY(objv[2]);
    netresource.lpRemoteName = ObjToUnicode(objv[3]);
    netresource.lpProvider = ObjToLPWSTR_NULL_IF_EMPTY(objv[4]);
    usernameP = ObjToLPWSTR_NULL_IF_EMPTY(objv[5]);

    mark = SWSPushMark();
    decrypted_password = ObjDecryptPasswordSWS(objv[7], &password_len);

    if (ignore_password) {







|







493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
    /* TBD - what is the type of HWD ? SHould it not use ObjToHWND ? */
    if (ObjToHWND(interp, objv[0], &winH) != TCL_OK)
        return TCL_ERROR;
    CHECK_INTEGER_OBJ(interp, netresource.dwType, objv[1]);
    CHECK_INTEGER_OBJ(interp, ignore_password, objv[6]);
    CHECK_INTEGER_OBJ(interp, flags, objv[8]);
    netresource.lpLocalName = ObjToLPWSTR_NULL_IF_EMPTY(objv[2]);
    netresource.lpRemoteName = ObjToWinChars(objv[3]);
    netresource.lpProvider = ObjToLPWSTR_NULL_IF_EMPTY(objv[4]);
    usernameP = ObjToLPWSTR_NULL_IF_EMPTY(objv[5]);

    mark = SWSPushMark();
    decrypted_password = ObjDecryptPasswordSWS(objv[7], &password_len);

    if (ignore_password) {
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
    error = WNetUseConnectionW(winH, &netresource, passwordP, usernameP, flags,
                               accessname, &accessname_size, &outflags);

    SecureZeroMemory(decrypted_password, password_len);
    SWSPopMark(mark);

    if (error == NO_ERROR) {
        ObjSetResult(interp, ObjFromUnicode(accessname));
        return TCL_OK;
    }
    else {
        return Twapi_AppendWNetError(interp, error);
    }
}

static TCL_RESULT Twapi_WNetGetUniversalNameObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    int result;
    DWORD error;
    DWORD buf_sz;
    void *buf;
    LPCWSTR      localpathP;

    ObjToUnicodeCleanup();

    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    localpathP = ObjToUnicode(objv[1]);

    buf = MemLifoPushFrame(ticP->memlifoP, MAX_PATH+1, &buf_sz);
    error = WNetGetUniversalNameW(localpathP, REMOTE_NAME_INFO_LEVEL,
                                  buf, &buf_sz);
    if (error = ERROR_MORE_DATA) {
        /* Retry with larger buffer */
        buf = MemLifoAlloc(ticP->memlifoP, buf_sz, NULL);







|















<
<



|







515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537


538
539
540
541
542
543
544
545
546
547
548
    error = WNetUseConnectionW(winH, &netresource, passwordP, usernameP, flags,
                               accessname, &accessname_size, &outflags);

    SecureZeroMemory(decrypted_password, password_len);
    SWSPopMark(mark);

    if (error == NO_ERROR) {
        ObjSetResult(interp, ObjFromWinChars(accessname));
        return TCL_OK;
    }
    else {
        return Twapi_AppendWNetError(interp, error);
    }
}

static TCL_RESULT Twapi_WNetGetUniversalNameObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    int result;
    DWORD error;
    DWORD buf_sz;
    void *buf;
    LPCWSTR      localpathP;



    if (objc != 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    localpathP = ObjToWinChars(objv[1]);

    buf = MemLifoPushFrame(ticP->memlifoP, MAX_PATH+1, &buf_sz);
    error = WNetGetUniversalNameW(localpathP, REMOTE_NAME_INFO_LEVEL,
                                  buf, &buf_sz);
    if (error = ERROR_MORE_DATA) {
        /* Retry with larger buffer */
        buf = MemLifoAlloc(ticP->memlifoP, buf_sz, NULL);
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
    DWORD       outsz;
    int         error;
    LPWSTR      systempart;
    Tcl_Obj    *objs[2];
    MemLifoMarkHandle mark;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    /* TBD - check if GETNULLIFEMPTY is ok */
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETEMPTYASNULL(in.lpRemoteName),
                         GETEMPTYASNULL(in.lpProvider),
                         GETINT(in.dwType),
                         ARGEND);
    if (res == TCL_OK) {
        outP = MemLifoAlloc(ticP->memlifoP, 4000, &outsz);
        error = WNetGetResourceInformationW(&in, outP, &outsz, &systempart);
        if (error == ERROR_MORE_DATA) {
            /* Retry with larger buffer */
            outP = MemLifoAlloc(ticP->memlifoP, outsz, NULL);
            error = WNetGetResourceInformationW(&in, outP, &outsz, &systempart);
        }
        if (error == ERROR_SUCCESS) {
            /* TBD - replace with ObjFromCStruct */
            objs[0] = ListObjFromNETRESOURCEW(ticP->interp, outP);
            objs[1] = ObjFromUnicode(systempart);
            ObjSetResult(ticP->interp, ObjNewList(2, objs));
            res = TCL_OK;
        } else
            res = Twapi_AppendWNetError(ticP->interp, error);
    }

    MemLifoPopMark(mark);







<
<



















|







572
573
574
575
576
577
578


579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
    DWORD       outsz;
    int         error;
    LPWSTR      systempart;
    Tcl_Obj    *objs[2];
    MemLifoMarkHandle mark;
    TCL_RESULT res;



    mark = MemLifoPushMark(ticP->memlifoP);

    /* TBD - check if GETNULLIFEMPTY is ok */
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETEMPTYASNULL(in.lpRemoteName),
                         GETEMPTYASNULL(in.lpProvider),
                         GETINT(in.dwType),
                         ARGEND);
    if (res == TCL_OK) {
        outP = MemLifoAlloc(ticP->memlifoP, 4000, &outsz);
        error = WNetGetResourceInformationW(&in, outP, &outsz, &systempart);
        if (error == ERROR_MORE_DATA) {
            /* Retry with larger buffer */
            outP = MemLifoAlloc(ticP->memlifoP, outsz, NULL);
            error = WNetGetResourceInformationW(&in, outP, &outsz, &systempart);
        }
        if (error == ERROR_SUCCESS) {
            /* TBD - replace with ObjFromCStruct */
            objs[0] = ListObjFromNETRESOURCEW(ticP->interp, outP);
            objs[1] = ObjFromWinChars(systempart);
            ObjSetResult(ticP->interp, ObjNewList(2, objs));
            res = TCL_OK;
        } else
            res = Twapi_AppendWNetError(ticP->interp, error);
    }

    MemLifoPopMark(mark);
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
    MemLifoMarkHandle mark;
    LPCWSTR     username;
    HWND hwnd;
    WCHAR         *decryptedP;
    int            decrypted_len;
    NETRESOURCEW *netresP;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);

    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETHWND(hwnd),
                         ARGSKIP,
                         ARGSKIP,
                         GETWSTR(username),







<
<







614
615
616
617
618
619
620


621
622
623
624
625
626
627
    MemLifoMarkHandle mark;
    LPCWSTR     username;
    HWND hwnd;
    WCHAR         *decryptedP;
    int            decrypted_len;
    NETRESOURCEW *netresP;



    mark = MemLifoPushMark(ticP->memlifoP);

    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
                         GETHWND(hwnd),
                         ARGSKIP,
                         ARGSKIP,
                         GETWSTR(username),
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
    DWORD bufsz = ARRAYSIZE(buf);
    DWORD error;

    error = WNetGetUserW(lpName, buf, &bufsz);
    if (error != NO_ERROR)
        return Twapi_AppendWNetError(interp, error);

    ObjSetResult(interp, ObjFromUnicode(buf));
    return TCL_OK;
}

int Twapi_NetSessionGetInfo(
    Tcl_Interp    *interp,
    LPWSTR server,
    LPWSTR client,







|







684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
    DWORD bufsz = ARRAYSIZE(buf);
    DWORD error;

    error = WNetGetUserW(lpName, buf, &bufsz);
    if (error != NO_ERROR)
        return Twapi_AppendWNetError(interp, error);

    ObjSetResult(interp, ObjFromWinChars(buf));
    return TCL_OK;
}

int Twapi_NetSessionGetInfo(
    Tcl_Interp    *interp,
    LPWSTR server,
    LPWSTR client,
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
    int struct_size;
    Tcl_Obj *(*objfn)(Tcl_Interp *, LPBYTE, DWORD);
    Tcl_Obj *objs[4];
    Tcl_Obj *enumObj = NULL;
    Tcl_Obj *sObj;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    sObj = objv[1];
    objc -= 2;
    objv += 2;








<
<







754
755
756
757
758
759
760


761
762
763
764
765
766
767
    int struct_size;
    Tcl_Obj *(*objfn)(Tcl_Interp *, LPBYTE, DWORD);
    Tcl_Obj *objs[4];
    Tcl_Obj *enumObj = NULL;
    Tcl_Obj *sObj;
    int func = PtrToInt(clientdata);



    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    sObj = objv[1];
    objc -= 2;
    objv += 2;

793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
        case 0: struct_size = sizeof(USE_INFO_0); break;
        case 1: struct_size = sizeof(USE_INFO_1); break;
        case 2: struct_size = sizeof(USE_INFO_2); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromUSE_INFO;
        netenum.status = NetUseEnum (
            ObjToUnicode(sObj), netenum.level,
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,
            &dwresume);
        netenum.hresume = (DWORD_PTR) dwresume;
        break;







|







785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
        case 0: struct_size = sizeof(USE_INFO_0); break;
        case 1: struct_size = sizeof(USE_INFO_1); break;
        case 2: struct_size = sizeof(USE_INFO_2); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromUSE_INFO;
        netenum.status = NetUseEnum (
            ObjToWinChars(sObj), netenum.level,
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,
            &dwresume);
        netenum.hresume = (DWORD_PTR) dwresume;
        break;
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
        case 0: struct_size = sizeof(SHARE_INFO_0); break;
        case 1: struct_size = sizeof(SHARE_INFO_1); break;
        case 2: struct_size = sizeof(SHARE_INFO_2); break;
        case 502: struct_size = sizeof(SHARE_INFO_502); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromSHARE_INFO;
        netenum.status = NetShareEnum(ObjToUnicode(sObj), netenum.level,
                                      &netenum.netbufP,
                                      MAX_PREFERRED_LENGTH,
                                      &netenum.entriesread,
                                      &netenum.totalentries,
                                      &dwresume);
        netenum.hresume = (DWORD_PTR) dwresume;
        break;







|







810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
        case 0: struct_size = sizeof(SHARE_INFO_0); break;
        case 1: struct_size = sizeof(SHARE_INFO_1); break;
        case 2: struct_size = sizeof(SHARE_INFO_2); break;
        case 502: struct_size = sizeof(SHARE_INFO_502); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromSHARE_INFO;
        netenum.status = NetShareEnum(ObjToWinChars(sObj), netenum.level,
                                      &netenum.netbufP,
                                      MAX_PREFERRED_LENGTH,
                                      &netenum.entriesread,
                                      &netenum.totalentries,
                                      &dwresume);
        netenum.hresume = (DWORD_PTR) dwresume;
        break;
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
        switch (netenum.level) {
        case 0: struct_size = sizeof(CONNECTION_INFO_0); break;
        case 1: struct_size = sizeof(CONNECTION_INFO_1); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromCONNECTION_INFO;
        netenum.status = NetConnectionEnum (
            ObjToUnicode(sObj),
            ObjToUnicode(objv[0]),
            netenum.level,
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,
            &dwresume);
        netenum.hresume = (DWORD_PTR)dwresume;







|
|







834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
        switch (netenum.level) {
        case 0: struct_size = sizeof(CONNECTION_INFO_0); break;
        case 1: struct_size = sizeof(CONNECTION_INFO_1); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromCONNECTION_INFO;
        netenum.status = NetConnectionEnum (
            ObjToWinChars(sObj),
            ObjToWinChars(objv[0]),
            netenum.level,
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,
            &dwresume);
        netenum.hresume = (DWORD_PTR)dwresume;
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
        switch (netenum.level) {
        case 2: struct_size = sizeof(FILE_INFO_2); break;
        case 3: struct_size = sizeof(FILE_INFO_3); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromFILE_INFO;
        netenum.status = NetFileEnum (
            ObjToUnicode(sObj),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
            netenum.level, 
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,







|







857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
        switch (netenum.level) {
        case 2: struct_size = sizeof(FILE_INFO_2); break;
        case 3: struct_size = sizeof(FILE_INFO_3); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromFILE_INFO;
        netenum.status = NetFileEnum (
            ObjToWinChars(sObj),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
            netenum.level, 
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
        case 2: struct_size = sizeof(SESSION_INFO_2); break;
        case 10: struct_size = sizeof(SESSION_INFO_10); break;
        case 502: struct_size = sizeof(SESSION_INFO_502); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromSESSION_INFO;
        netenum.status = NetSessionEnum (
            ObjToUnicode(sObj),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
            netenum.level, 
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,







|







884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
        case 2: struct_size = sizeof(SESSION_INFO_2); break;
        case 10: struct_size = sizeof(SESSION_INFO_10); break;
        case 502: struct_size = sizeof(SESSION_INFO_502); break;
        default: goto invalid_level_error;
        }
        objfn = ObjFromSESSION_INFO;
        netenum.status = NetSessionEnum (
            ObjToWinChars(sObj),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
            ObjToLPWSTR_NULL_IF_EMPTY(objv[1]),
            netenum.level, 
            &netenum.netbufP,
            MAX_PREFERRED_LENGTH,
            &netenum.entriesread,
            &netenum.totalentries,
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
    SWSMark mark = NULL;
    NETRESOURCEW *netresP;
    HANDLE h;
    TCL_RESULT res;
    Tcl_Obj *objP;
    NETINFOSTRUCT netinfo;

    ObjToUnicodeCleanup();

    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        return Twapi_WNetUseConnection(interp, objc, objv);
    case 2:
        return Twapi_NetShareAdd(interp, objc, objv);
    case 3:
        CHECK_NARGS(interp, objc, 1);
        return Twapi_WNetGetUser(interp, ObjToUnicode(objv[0]));
    case 4: // NetFileClose
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = NetFileClose(ObjToLPWSTR_NULL_IF_EMPTY(objv[0]), dw);
        break;
    case 5:
    case 6:
        if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(dw), GETINT(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToUnicode(objv[0]);
        if (func == 5) {
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;
            result.value.ival = WNetCancelConnection2W(s, dw, dw2);
        } else {
            NULLIFY_EMPTY(s);
            return Twapi_NetFileGetInfo(interp, s, dw, dw2);
        }
        break;
    case 7: // NetShareSetInfo
        CHECK_NARGS(interp, objc, 5);
        CHECK_INTEGER_OBJ(interp, dw, objv[3]);
        mark = SWSPushMark();
        res = ObjToPSECURITY_DESCRIPTORSWS(interp, objv[4], &secdP);
        /* Note secdP may be NULL even on success */
        if (res == TCL_OK) {
            res = Twapi_NetShareSetInfo(interp,
                                        ObjToUnicode(objv[0]),
                                        ObjToUnicode(objv[1]),
                                        ObjToUnicode(objv[2]),
                                        dw, secdP);
        }
        SWSPopMark(mark);
        return res;

    case 8:
    case 9:
    case 10:
    case 11:
        CHECK_NARGS_RANGE(interp, objc, 2, 3);
        if (objc == 2)
            dw = 0;
        else {
            CHECK_INTEGER_OBJ(interp, dw, objv[2]);
        }
        s = ObjToLPWSTR_NULL_IF_EMPTY(objv[0]);
        s2 = ObjToUnicode(objv[1]);
        switch (func) {
        case 8:
            return Twapi_NetUseGetInfo(interp, s, s2, dw);
        case 9:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetShareDel(s,s2,dw);
            break;







<
<














|











|
















|
|
|
















|







950
951
952
953
954
955
956


957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
    SWSMark mark = NULL;
    NETRESOURCEW *netresP;
    HANDLE h;
    TCL_RESULT res;
    Tcl_Obj *objP;
    NETINFOSTRUCT netinfo;



    if (objc < 2)
        return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        return Twapi_WNetUseConnection(interp, objc, objv);
    case 2:
        return Twapi_NetShareAdd(interp, objc, objv);
    case 3:
        CHECK_NARGS(interp, objc, 1);
        return Twapi_WNetGetUser(interp, ObjToWinChars(objv[0]));
    case 4: // NetFileClose
        CHECK_NARGS(interp, objc, 2);
        CHECK_INTEGER_OBJ(interp, dw, objv[1]);
        result.type = TRT_EXCEPTION_ON_ERROR;
        result.value.ival = NetFileClose(ObjToLPWSTR_NULL_IF_EMPTY(objv[0]), dw);
        break;
    case 5:
    case 6:
        if (TwapiGetArgs(interp, objc-1, objv+1, GETINT(dw), GETINT(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        s = ObjToWinChars(objv[0]);
        if (func == 5) {
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;
            result.value.ival = WNetCancelConnection2W(s, dw, dw2);
        } else {
            NULLIFY_EMPTY(s);
            return Twapi_NetFileGetInfo(interp, s, dw, dw2);
        }
        break;
    case 7: // NetShareSetInfo
        CHECK_NARGS(interp, objc, 5);
        CHECK_INTEGER_OBJ(interp, dw, objv[3]);
        mark = SWSPushMark();
        res = ObjToPSECURITY_DESCRIPTORSWS(interp, objv[4], &secdP);
        /* Note secdP may be NULL even on success */
        if (res == TCL_OK) {
            res = Twapi_NetShareSetInfo(interp,
                                        ObjToWinChars(objv[0]),
                                        ObjToWinChars(objv[1]),
                                        ObjToWinChars(objv[2]),
                                        dw, secdP);
        }
        SWSPopMark(mark);
        return res;

    case 8:
    case 9:
    case 10:
    case 11:
        CHECK_NARGS_RANGE(interp, objc, 2, 3);
        if (objc == 2)
            dw = 0;
        else {
            CHECK_INTEGER_OBJ(interp, dw, objv[2]);
        }
        s = ObjToLPWSTR_NULL_IF_EMPTY(objv[0]);
        s2 = ObjToWinChars(objv[1]);
        switch (func) {
        case 8:
            return Twapi_NetUseGetInfo(interp, s, s2, dw);
        case 9:
            result.type = TRT_EXCEPTION_ON_ERROR;
            result.value.ival = NetShareDel(s,s2,dw);
            break;
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
            ObjToLPWSTR_NULL_IF_EMPTY(objv[2]));
        break;
    case 13:
        CHECK_NARGS(interp, objc, 4);
        CHECK_INTEGER_OBJ(interp, dw, objv[3]);
        return Twapi_NetSessionGetInfo(interp,
                                       ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
                                       ObjToUnicode(objv[1]),
                                       ObjToUnicode(objv[2]),
                                       dw);
    case 14: // WNetOpenEnum
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETINT(dw3),
                         ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
        mark = SWSPushMark();







|
|







1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
            ObjToLPWSTR_NULL_IF_EMPTY(objv[2]));
        break;
    case 13:
        CHECK_NARGS(interp, objc, 4);
        CHECK_INTEGER_OBJ(interp, dw, objv[3]);
        return Twapi_NetSessionGetInfo(interp,
                                       ObjToLPWSTR_NULL_IF_EMPTY(objv[0]),
                                       ObjToWinChars(objv[1]),
                                       ObjToWinChars(objv[2]),
                                       dw);
    case 14: // WNetOpenEnum
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETINT(dw3),
                         ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
        mark = SWSPushMark();
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
        break;

    case 17: // WNetGetConnection
        CHECK_NARGS(interp, objc, 1);
        mark = SWSPushMark();
        s = SWSAlloc(sizeof(WCHAR)*MAX_PATH, &dw2);
        dw2 /= sizeof(WCHAR);
        result.value.ival = WNetGetConnectionW(ObjToUnicode(objv[0]), s, &dw2);
        if (result.value.ival == NO_ERROR) {
            result.type = TRT_OBJ;
            result.value.obj = ObjFromUnicode(s);
        } else
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;

        break;

    case 18: // WNetGetProviderName
        CHECK_NARGS(interp, objc, 1);







|


|







1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
        break;

    case 17: // WNetGetConnection
        CHECK_NARGS(interp, objc, 1);
        mark = SWSPushMark();
        s = SWSAlloc(sizeof(WCHAR)*MAX_PATH, &dw2);
        dw2 /= sizeof(WCHAR);
        result.value.ival = WNetGetConnectionW(ObjToWinChars(objv[0]), s, &dw2);
        if (result.value.ival == NO_ERROR) {
            result.type = TRT_OBJ;
            result.value.obj = ObjFromWinChars(s);
        } else
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;

        break;

    case 18: // WNetGetProviderName
        CHECK_NARGS(interp, objc, 1);
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
        } else
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;
        break;

    case 19: // WnetGetNetworkInformation
        CHECK_NARGS(interp, objc, 2);
        netinfo.cbStructure = sizeof(netinfo);
        result.value.ival = WNetGetNetworkInformationW(ObjToUnicode(objv[0]),
                                                       &netinfo);
        if (result.value.ival != NO_ERROR)
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;
        else {
            result.value.ival = ObjFromCStruct(interp, &netinfo, sizeof(netinfo),
                                 objv[1], 0, &objP);
            if (result.value.ival != TCL_OK)







|







1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
        } else
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;
        break;

    case 19: // WnetGetNetworkInformation
        CHECK_NARGS(interp, objc, 2);
        netinfo.cbStructure = sizeof(netinfo);
        result.value.ival = WNetGetNetworkInformationW(ObjToWinChars(objv[0]),
                                                       &netinfo);
        if (result.value.ival != NO_ERROR)
            result.type = TRT_EXCEPTION_ON_WNET_ERROR;
        else {
            result.value.ival = ObjFromCStruct(interp, &netinfo, sizeof(netinfo),
                                 objv[1], 0, &objP);
            if (result.value.ival != TCL_OK)
Changes to undroid/twapi/twapi/shell/shell.c.
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    HRESULT hres; 
    IShellLinkW* psl; 
    IPersistFile* ppf;
    IShellLinkDataList* psldl;
    MemLifoMarkHandle mark;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    psl = NULL;
    psldl = NULL;
    itemIds = NULL;
    ppf = NULL;
    mark = MemLifoPushMark(ticP->memlifoP);
 
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,







<
<







141
142
143
144
145
146
147


148
149
150
151
152
153
154
    HRESULT hres; 
    IShellLinkW* psl; 
    IPersistFile* ppf;
    IShellLinkDataList* psldl;
    MemLifoMarkHandle mark;
    TCL_RESULT res;



    psl = NULL;
    psldl = NULL;
    itemIds = NULL;
    ppf = NULL;
    mark = MemLifoPushMark(ticP->memlifoP);
 
    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
        goto fail;

    /* Load the resource through the IPersist interface */
    hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (LPVOID*)&ppf); 
    if (FAILED(hres))
        goto fail;
    
    hres = ppf->lpVtbl->Load(ppf, ObjToUnicode(linkObj), STGM_READ);
    if (FAILED(hres))
        goto fail;

    /* Resolve the link */
    hres = psl->lpVtbl->Resolve(psl, hwnd, resolve_flags);
#if 0    /* Ignore resolve errors */
    if (FAILED(hres))
        goto fail;
#endif

    resultObj = ObjEmptyList();

    /*
     * Get each field. Note that inability to get a field is not treated
     * as an error. We just go on and try to get the next one
     */
    hres = psl->lpVtbl->GetArguments(psl, buf, sizeof(buf)/sizeof(buf[0]));
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-args"));
        ObjAppendElement(interp, resultObj, ObjFromUnicode(buf));
    }

    hres = psl->lpVtbl->GetDescription(psl, buf, sizeof(buf)/sizeof(buf[0]));
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-desc"));
        ObjAppendElement(interp, resultObj, ObjFromUnicode(buf));
    }

    hres = psl->lpVtbl->GetHotkey(psl, &wordval);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-hotkey"));
        ObjAppendElement(interp, resultObj, 
                                 ObjFromLong(wordval));
    }

    hres = psl->lpVtbl->GetIconLocation(psl,
                                        buf, sizeof(buf)/sizeof(buf[0]),
                                        &intval);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-iconindex"));
        ObjAppendElement(interp, resultObj, 
                                 ObjFromLong(intval));
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-iconpath"));
        ObjAppendElement(interp, resultObj, ObjFromUnicode(buf));
    }

    hres = psl->lpVtbl->GetIDList(psl, &pidl);
    if (hres == NOERROR) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-idl"));
        ObjAppendElement(interp, resultObj, ObjFromPIDL(pidl));
        CoTaskMemFree(pidl);
    }

    hres = psl->lpVtbl->GetPath(psl, buf, sizeof(buf)/sizeof(buf[0]),
                                NULL, pathFlags);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-path"));
        ObjAppendElement(interp, resultObj, ObjFromUnicode(buf));
    }

    hres = psl->lpVtbl->GetShowCmd(psl, &intval);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-showcmd"));
        ObjAppendElement(interp, resultObj, 
                                 ObjFromLong(intval));
    }

    hres = psl->lpVtbl->GetWorkingDirectory(psl, buf, sizeof(buf)/sizeof(buf[0]));
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-workdir"));
        ObjAppendElement(interp, resultObj, ObjFromUnicode(buf));
    }
    
    hres = psl->lpVtbl->QueryInterface(psl, &IID_IShellLinkDataList,
                                       (LPVOID*)&psldl); 
    if (SUCCEEDED(hres)) {
        hres = psldl->lpVtbl->GetFlags(psldl, &runas);
        if (SUCCEEDED(hres)) {







|




















|






|




















|















|














|







294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
        goto fail;

    /* Load the resource through the IPersist interface */
    hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (LPVOID*)&ppf); 
    if (FAILED(hres))
        goto fail;
    
    hres = ppf->lpVtbl->Load(ppf, ObjToWinChars(linkObj), STGM_READ);
    if (FAILED(hres))
        goto fail;

    /* Resolve the link */
    hres = psl->lpVtbl->Resolve(psl, hwnd, resolve_flags);
#if 0    /* Ignore resolve errors */
    if (FAILED(hres))
        goto fail;
#endif

    resultObj = ObjEmptyList();

    /*
     * Get each field. Note that inability to get a field is not treated
     * as an error. We just go on and try to get the next one
     */
    hres = psl->lpVtbl->GetArguments(psl, buf, sizeof(buf)/sizeof(buf[0]));
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-args"));
        ObjAppendElement(interp, resultObj, ObjFromWinChars(buf));
    }

    hres = psl->lpVtbl->GetDescription(psl, buf, sizeof(buf)/sizeof(buf[0]));
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-desc"));
        ObjAppendElement(interp, resultObj, ObjFromWinChars(buf));
    }

    hres = psl->lpVtbl->GetHotkey(psl, &wordval);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-hotkey"));
        ObjAppendElement(interp, resultObj, 
                                 ObjFromLong(wordval));
    }

    hres = psl->lpVtbl->GetIconLocation(psl,
                                        buf, sizeof(buf)/sizeof(buf[0]),
                                        &intval);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-iconindex"));
        ObjAppendElement(interp, resultObj, 
                                 ObjFromLong(intval));
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-iconpath"));
        ObjAppendElement(interp, resultObj, ObjFromWinChars(buf));
    }

    hres = psl->lpVtbl->GetIDList(psl, &pidl);
    if (hres == NOERROR) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-idl"));
        ObjAppendElement(interp, resultObj, ObjFromPIDL(pidl));
        CoTaskMemFree(pidl);
    }

    hres = psl->lpVtbl->GetPath(psl, buf, sizeof(buf)/sizeof(buf[0]),
                                NULL, pathFlags);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-path"));
        ObjAppendElement(interp, resultObj, ObjFromWinChars(buf));
    }

    hres = psl->lpVtbl->GetShowCmd(psl, &intval);
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-showcmd"));
        ObjAppendElement(interp, resultObj, 
                                 ObjFromLong(intval));
    }

    hres = psl->lpVtbl->GetWorkingDirectory(psl, buf, sizeof(buf)/sizeof(buf[0]));
    if (SUCCEEDED(hres)) {
        ObjAppendElement(interp, resultObj,
                                 STRING_LITERAL_OBJ("-workdir"));
        ObjAppendElement(interp, resultObj, ObjFromWinChars(buf));
    }
    
    hres = psl->lpVtbl->QueryInterface(psl, &IID_IShellLinkDataList,
                                       (LPVOID*)&psldl); 
    if (SUCCEEDED(hres)) {
        hres = psldl->lpVtbl->GetFlags(psldl, &runas);
        if (SUCCEEDED(hres)) {
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        goto fail;

    hres = psl->lpVtbl->GetURL(psl, &url);

    if (FAILED(hres))
        goto fail;

    ObjSetResult(interp, ObjFromUnicode(url));
    CoTaskMemFree(url);

    retval = TCL_OK;

 vamoose:
    if (psl)
        psl->lpVtbl->Release(psl); 







|







485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
        goto fail;

    hres = psl->lpVtbl->GetURL(psl, &url);

    if (FAILED(hres))
        goto fail;

    ObjSetResult(interp, ObjFromWinChars(url));
    CoTaskMemFree(url);

    retval = TCL_OK;

 vamoose:
    if (psl)
        psl->lpVtbl->Release(psl); 
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
        hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (LPVOID*)&ppf); 
    }
    if (FAILED(hres)) {
        /* This CoCreateInstance or QueryInterface error so we do not get
           use TWAPI_STORE_COM_ERROR */
        Twapi_AppendSystemError(interp, hres);
    } else {
        hres = ppf->lpVtbl->Load(ppf, ObjToUnicode(linkObj), STGM_READ);
        if (FAILED(hres)) {
            TWAPI_STORE_COM_ERROR(interp, hres, ppf, &IID_IPersistFile);
        } else {
            urlcmd.dwcbSize = sizeof(urlcmd);
            urlcmd.dwFlags = flags;
            urlcmd.hwndParent = hwnd;
            urlcmd.pcszVerb = ObjToUnicode(verbObj);

            hres = psl->lpVtbl->InvokeCommand(psl, &urlcmd);
            if (FAILED(hres)) {
                TWAPI_STORE_COM_ERROR(interp, hres, psl, &IID_IUniformResourceLocatorW);
            }
        }
    }







|






|







534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
        hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (LPVOID*)&ppf); 
    }
    if (FAILED(hres)) {
        /* This CoCreateInstance or QueryInterface error so we do not get
           use TWAPI_STORE_COM_ERROR */
        Twapi_AppendSystemError(interp, hres);
    } else {
        hres = ppf->lpVtbl->Load(ppf, ObjToWinChars(linkObj), STGM_READ);
        if (FAILED(hres)) {
            TWAPI_STORE_COM_ERROR(interp, hres, ppf, &IID_IPersistFile);
        } else {
            urlcmd.dwcbSize = sizeof(urlcmd);
            urlcmd.dwFlags = flags;
            urlcmd.hwndParent = hwnd;
            urlcmd.pcszVerb = ObjToWinChars(verbObj);

            hres = psl->lpVtbl->InvokeCommand(psl, &urlcmd);
            if (FAILED(hres)) {
                TWAPI_STORE_COM_ERROR(interp, hres, psl, &IID_IUniformResourceLocatorW);
            }
        }
    }
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
        ||
        ObjToMultiSzEx(interp, fromObj, &sfop.pFrom, sws) != TCL_OK
        ||
        ObjToMultiSzEx(interp, toObj, &sfop.pTo, sws) != TCL_OK
        )
        goto vamoose;
     
    sfop.lpszProgressTitle = ObjToUnicode(titleObj);
    sfop.hNameMappings = NULL;

    if (SHFileOperationW(&sfop) != 0) {
        // Note GetLastError() is not set by the call
        ObjSetStaticResult(interp, "SHFileOperation failed");
        goto vamoose;
    }

    objs[0] = ObjFromBoolean(sfop.fAnyOperationsAborted);
    objs[1] = ObjEmptyList();

    if (sfop.hNameMappings) {
        int i;
        SHNAMEMAPPINGW *mapP = *(SHNAMEMAPPINGW **)(((char *)sfop.hNameMappings) + 4);
        for (i = 0; i < *(int *) (sfop.hNameMappings); ++i) {
            ObjAppendElement(interp, objs[1],
                                     ObjFromUnicodeN(
                                         mapP[i].pszOldPath,
                                         mapP[i].cchOldPath));
            ObjAppendElement(interp, objs[1],
                                     ObjFromUnicodeN(
                                         mapP[i].pszNewPath,
                                         mapP[i].cchNewPath));
        }

        SHFreeNameMappings(sfop.hNameMappings);
    }








|
















|



|







584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
        ||
        ObjToMultiSzEx(interp, fromObj, &sfop.pFrom, sws) != TCL_OK
        ||
        ObjToMultiSzEx(interp, toObj, &sfop.pTo, sws) != TCL_OK
        )
        goto vamoose;
     
    sfop.lpszProgressTitle = ObjToWinChars(titleObj);
    sfop.hNameMappings = NULL;

    if (SHFileOperationW(&sfop) != 0) {
        // Note GetLastError() is not set by the call
        ObjSetStaticResult(interp, "SHFileOperation failed");
        goto vamoose;
    }

    objs[0] = ObjFromBoolean(sfop.fAnyOperationsAborted);
    objs[1] = ObjEmptyList();

    if (sfop.hNameMappings) {
        int i;
        SHNAMEMAPPINGW *mapP = *(SHNAMEMAPPINGW **)(((char *)sfop.hNameMappings) + 4);
        for (i = 0; i < *(int *) (sfop.hNameMappings); ++i) {
            ObjAppendElement(interp, objs[1],
                                     ObjFromWinCharsN(
                                         mapP[i].pszOldPath,
                                         mapP[i].cchOldPath));
            ObjAppendElement(interp, objs[1],
                                     ObjFromWinCharsN(
                                         mapP[i].pszNewPath,
                                         mapP[i].cchNewPath));
        }

        SHFreeNameMappings(sfop.hNameMappings);
    }

635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    HKEY hkeyClass;
    DWORD dwHotKey;
    HANDLE hIconOrMonitor;
    TCL_RESULT res;
    SHELLEXECUTEINFOW sei;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    mark = MemLifoPushMark(ticP->memlifoP);
    
    TwapiZeroMemory(&sei, sizeof(sei)); /* Also sets sei.lpIDList = NULL -
                                     Need to track if it needs freeing */
    sei.cbSize = sizeof(sei);

    res = TwapiGetArgsEx(ticP, objc-1, objv+1,







<
<







633
634
635
636
637
638
639


640
641
642
643
644
645
646
    HKEY hkeyClass;
    DWORD dwHotKey;
    HANDLE hIconOrMonitor;
    TCL_RESULT res;
    SHELLEXECUTEINFOW sei;
    MemLifoMarkHandle mark;



    mark = MemLifoPushMark(ticP->memlifoP);
    
    TwapiZeroMemory(&sei, sizeof(sei)); /* Also sets sei.lpIDList = NULL -
                                     Need to track if it needs freeing */
    sei.cbSize = sizeof(sei);

    res = TwapiGetArgsEx(ticP, objc-1, objv+1,
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
    case SHCNF_DWORD:
    case SHCNF_PATHW:
    case SHCNF_PRINTERW:
    case SHCNF_IDLIST:
        /* Valid but no special treatment */
        break;
    case SHCNF_PATHA:
        /* Always pass as Unicode */
        flags = (flags & ~SHCNF_TYPE) | SHCNF_PATHW;
        break;
    case SHCNF_PRINTERA:
        /* Always pass as Unicode */
        flags = (flags & ~SHCNF_TYPE) | SHCNF_PRINTERW;
        break;
        
    default:
        goto invalid_flags_error;
    }








|



|







710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
    case SHCNF_DWORD:
    case SHCNF_PATHW:
    case SHCNF_PRINTERW:
    case SHCNF_IDLIST:
        /* Valid but no special treatment */
        break;
    case SHCNF_PATHA:
        /* Always pass as WCHAR */
        flags = (flags & ~SHCNF_TYPE) | SHCNF_PATHW;
        break;
    case SHCNF_PRINTERA:
        /* Always pass as WCHAR */
        flags = (flags & ~SHCNF_TYPE) | SHCNF_PRINTERW;
        break;
        
    default:
        goto invalid_flags_error;
    }

764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
        switch (flags & SHCNF_TYPE) {
        case SHCNF_IDLIST:
            if (ObjToPIDL(interp, objv[2], &idl1P) != TCL_OK)
                goto vamoose;
            dwItem1 = idl1P;
            break;
        case SHCNF_PATHW:
            dwItem1 = ObjToUnicode(objv[2]);
            break;
        default:
            goto invalid_flags_error;
        }

        break;








|







760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
        switch (flags & SHCNF_TYPE) {
        case SHCNF_IDLIST:
            if (ObjToPIDL(interp, objv[2], &idl1P) != TCL_OK)
                goto vamoose;
            dwItem1 = idl1P;
            break;
        case SHCNF_PATHW:
            dwItem1 = ObjToWinChars(objv[2]);
            break;
        default:
            goto invalid_flags_error;
        }

        break;

787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
            if (ObjToPIDL(interp, objv[2], &idl1P) != TCL_OK ||
                ObjToPIDL(interp, objv[3], &idl2P) != TCL_OK)
                goto vamoose;
            dwItem1 = idl1P;
            dwItem2 = idl2P;
            break;
        case SHCNF_PATHW:
            dwItem1 = ObjToUnicode(objv[2]);
            dwItem2 = ObjToUnicode(objv[3]);
            break;
        default:
            goto invalid_flags_error;
        }

        break;








|
|







783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
            if (ObjToPIDL(interp, objv[2], &idl1P) != TCL_OK ||
                ObjToPIDL(interp, objv[3], &idl2P) != TCL_OK)
                goto vamoose;
            dwItem1 = idl1P;
            dwItem2 = idl2P;
            break;
        case SHCNF_PATHW:
            dwItem1 = ObjToWinChars(objv[2]);
            dwItem2 = ObjToWinChars(objv[3]);
            break;
        default:
            goto invalid_flags_error;
        }

        break;

836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
                if (objc > 3) {
                    if (ObjToPIDL(interp, objv[3], &idl2P) != TCL_OK)
                        goto vamoose;
                    dwItem2 = idl2P;
                }
                break;
            case SHCNF_PATHW:
                dwItem1 = ObjToUnicode(objv[2]);
                if (objc > 3)
                    dwItem2 = ObjToUnicode(objv[3]);
                break;
            default:
                goto invalid_flags_error;
            }
        }

        break;







|

|







832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
                if (objc > 3) {
                    if (ObjToPIDL(interp, objv[3], &idl2P) != TCL_OK)
                        goto vamoose;
                    dwItem2 = idl2P;
                }
                break;
            case SHCNF_PATHW:
                dwItem1 = ObjToWinChars(objv[2]);
                if (objc > 3)
                    dwItem2 = ObjToWinChars(objv[3]);
                break;
            default:
                goto invalid_flags_error;
            }
        }

        break;
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
    } u;
    HANDLE h;
    TwapiResult result;
    LPITEMIDLIST idlP;
    Tcl_Obj *sObj, *s2Obj;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 2:
        return Twapi_ReadShortcut(interp, objc, objv);
    case 3:
        return Twapi_InvokeUrlShortcut(interp, objc, objv);
    case 4: // SHInvokePrinterCommand
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(hwnd), GETINT(dw),
                         GETOBJ(sObj), GETOBJ(s2Obj), GETBOOL(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SHInvokePrinterCommandW(
            hwnd, dw, ObjToUnicode(sObj), ObjToUnicode(s2Obj), dw2);
        break;
    case 5:
        return Twapi_GetShellVersion(interp);
    case 6: // SHGetFolderPath - TBD Tcl wrapper
        if (TwapiGetArgs(interp, objc, objv,
                         GETHWND(hwnd), GETINT(dw),
                         GETHANDLE(h), GETINT(dw2),







<
<
















|







884
885
886
887
888
889
890


891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
    } u;
    HANDLE h;
    TwapiResult result;
    LPITEMIDLIST idlP;
    Tcl_Obj *sObj, *s2Obj;
    int func = PtrToInt(clientdata);



    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 2:
        return Twapi_ReadShortcut(interp, objc, objv);
    case 3:
        return Twapi_InvokeUrlShortcut(interp, objc, objv);
    case 4: // SHInvokePrinterCommand
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(hwnd), GETINT(dw),
                         GETOBJ(sObj), GETOBJ(s2Obj), GETBOOL(dw2),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival = SHInvokePrinterCommandW(
            hwnd, dw, ObjToWinChars(sObj), ObjToWinChars(s2Obj), dw2);
        break;
    case 5:
        return Twapi_GetShellVersion(interp);
    case 6: // SHGetFolderPath - TBD Tcl wrapper
        if (TwapiGetArgs(interp, objc, objv,
                         GETHWND(hwnd), GETINT(dw),
                         GETHANDLE(h), GETINT(dw2),
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
        if (Shell_NotifyIconW(dw, u.niP) == FALSE) {
            result.type = TRT_GETLASTERROR;
        }
        break;
    case 11:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        return Twapi_ReadUrlShortcut(interp, ObjToUnicode(objv[0]));
    case 12:
        return Twapi_SHFileOperation(interp, objc, objv);
    case 13:
        return Twapi_SHChangeNotify(interp, objc, objv);
    case 14:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLET(hwnd, HWND), GETINT(dw),
                         GETOBJ(sObj), GETOBJ(s2Obj),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival =
            Twapi_SHObjectProperties(hwnd, dw,
                                     ObjToUnicode(sObj),
                                     ObjToLPWSTR_NULL_IF_EMPTY(s2Obj));
        break;
    case 15:
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(sObj), GETOBJ(s2Obj), GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        return Twapi_WriteUrlShortcut(interp,
                                      ObjToUnicode(sObj),
                                      ObjToUnicode(s2Obj), dw);
    }

    return TwapiSetResult(interp, &result);
}

static int TwapiShellInitCalls(Tcl_Interp *interp, TwapiInterpContext *ticP)
{







|













|








|
|







978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
        if (Shell_NotifyIconW(dw, u.niP) == FALSE) {
            result.type = TRT_GETLASTERROR;
        }
        break;
    case 11:
        if (objc != 1)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);
        return Twapi_ReadUrlShortcut(interp, ObjToWinChars(objv[0]));
    case 12:
        return Twapi_SHFileOperation(interp, objc, objv);
    case 13:
        return Twapi_SHChangeNotify(interp, objc, objv);
    case 14:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLET(hwnd, HWND), GETINT(dw),
                         GETOBJ(sObj), GETOBJ(s2Obj),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival =
            Twapi_SHObjectProperties(hwnd, dw,
                                     ObjToWinChars(sObj),
                                     ObjToLPWSTR_NULL_IF_EMPTY(s2Obj));
        break;
    case 15:
        if (TwapiGetArgs(interp, objc, objv,
                         GETOBJ(sObj), GETOBJ(s2Obj), GETINT(dw),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        return Twapi_WriteUrlShortcut(interp,
                                      ObjToWinChars(sObj),
                                      ObjToWinChars(s2Obj), dw);
    }

    return TwapiSetResult(interp, &result);
}

static int TwapiShellInitCalls(Tcl_Interp *interp, TwapiInterpContext *ticP)
{
Changes to undroid/twapi/twapi/storage/dirmonitor.c.
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    int    include_subtree;
    int    npatterns;
    WCHAR  **patterns;
    DWORD  winerr;
    DWORD filter;
    MemLifoMarkHandle mark;

    ObjToUnicodeCleanup();

    ERROR_IF_UNTHREADED(interp);

    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                     GETWSTRN(pathP, path_len), GETBOOL(include_subtree),
                     GETINT(filter),
                     GETARGVW(patterns, npatterns),







<
<







38
39
40
41
42
43
44


45
46
47
48
49
50
51
    int    include_subtree;
    int    npatterns;
    WCHAR  **patterns;
    DWORD  winerr;
    DWORD filter;
    MemLifoMarkHandle mark;



    ERROR_IF_UNTHREADED(interp);

    mark = MemLifoPushMark(ticP->memlifoP);
    if (TwapiGetArgsEx(ticP, objc-1, objv+1,
                     GETWSTRN(pathP, path_len), GETBOOL(include_subtree),
                     GETINT(filter),
                     GETARGVW(patterns, npatterns),
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159


TCL_RESULT Twapi_UnregisterDirectoryMonitorObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE dirhandle;
    TwapiDirectoryMonitorContext *dmcP;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1, GETHANDLE(dirhandle),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* 
     * Look up the handle in list of directory monitors. No locking
     * required as list access always done in thread of interpreter







<
<







142
143
144
145
146
147
148


149
150
151
152
153
154
155


TCL_RESULT Twapi_UnregisterDirectoryMonitorObjCmd(TwapiInterpContext *ticP, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HANDLE dirhandle;
    TwapiDirectoryMonitorContext *dmcP;



    if (TwapiGetArgs(interp, objc-1, objv+1, GETHANDLE(dirhandle),
                     ARGEND) != TCL_OK)
        return TCL_ERROR;

    /* 
     * Look up the handle in list of directory monitors. No locking
     * required as list access always done in thread of interpreter
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
             * Skip if pattern specified and do not match. We first create
             * a Tcl_Obj and then do the match because unfortunately, the
             * the filenames in iobP are not null terminated so we would have
             * to copy them somewhere anyways to compare. We could temporarily
             * overwrite the next char with \0 but that would not work for
             * the last filename.
             */
            if (fnObj[1]) {
                ObjDecrRefs(fnObj[1]);
            }
            fnObj[1] = ObjFromUnicodeN(fniP->FileName, fniP->FileNameLength / sizeof (WCHAR));
            if (dmcP->npatterns == 0)
                pattern_matched = 1; /* No pattern so match everything */
            else {
                /* Need to match on pattern */
                int i;
                for (i = 0; i < dmcP->npatterns; ++i) {
                    int matched = TwapiDirectoryMonitorPatternMatch(
                        ObjToUnicode(fnObj[1]),
                        dmcP->patterns[i]);
                    if (matched) {
                        /* Matches can be inclusive or exclusive */
                        pattern_matched = (matched > 0);
                        break;
                    }
                }







|

<
|







|







502
503
504
505
506
507
508
509
510

511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
             * Skip if pattern specified and do not match. We first create
             * a Tcl_Obj and then do the match because unfortunately, the
             * the filenames in iobP are not null terminated so we would have
             * to copy them somewhere anyways to compare. We could temporarily
             * overwrite the next char with \0 but that would not work for
             * the last filename.
             */
            if (fnObj[1])
                ObjDecrRefs(fnObj[1]);

            fnObj[1] = ObjFromWinCharsN(fniP->FileName, fniP->FileNameLength/2);
            if (dmcP->npatterns == 0)
                pattern_matched = 1; /* No pattern so match everything */
            else {
                /* Need to match on pattern */
                int i;
                for (i = 0; i < dmcP->npatterns; ++i) {
                    int matched = TwapiDirectoryMonitorPatternMatch(
                        ObjToWinChars(fnObj[1]),
                        dmcP->patterns[i]);
                    if (matched) {
                        /* Matches can be inclusive or exclusive */
                        pattern_matched = (matched > 0);
                        break;
                    }
                }
720
721
722
723
724
725
726

727













728


        ++pattern;
    } else if (pattern[0] == L'+') {
        include = 1;
        ++pattern;
    } else
        include = 1;            /* Default is inclusive pattern */


    return Tcl_UniCharCaseMatch(path, pattern, 1) ? include : 0;













}









>

>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
        ++pattern;
    } else if (pattern[0] == L'+') {
        include = 1;
        ++pattern;
    } else
        include = 1;            /* Default is inclusive pattern */

#if TCL_UTF_MAX <= 4
    return Tcl_UniCharCaseMatch(path, pattern, 1) ? include : 0;
#else
    {
        Tcl_Obj *patObj, *pathObj;
        Tcl_UniChar *pathuni, *patuni;
        int match_result;
        patObj = ObjFromWinChars(pattern);
        patuni = Tcl_GetUnicode(patObj);
        pathObj = ObjFromWinChars(path);
        pathuni = Tcl_GetUnicode(pathObj);
        match_result = Tcl_UniCharCaseMatch(pathuni, patuni, 1) ? include : 0;
        ObjDecrRefs(patObj);
        ObjDecrRefs(pathObj);
        return match_result;
    }
#endif
}
Changes to undroid/twapi/twapi/storage/storage.c.
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
    else
        h = FindFirstVolumeW(buf, sizeof(buf)/sizeof(buf[0]));

    if (h == INVALID_HANDLE_VALUE)
        return TwapiReturnSystemError(interp);

    objv[0] = ObjFromHANDLE(h);
    objv[1] = ObjFromUnicode(buf);

    ObjSetResult(interp, ObjNewList(2, objv));
    return TCL_OK;
}

int TwapiNextVolume(Tcl_Interp *interp, int treat_as_mountpoint, HANDLE hFindVolume)
{
    BOOL    found;
    WCHAR   buf[MAX_PATH+1];

    found = (treat_as_mountpoint ?
             FindNextVolumeMountPointW : FindNextVolumeW)
        (hFindVolume, buf, sizeof(buf)/sizeof(buf[0]));

    if (found) {
        Tcl_Obj *objv[2];
        objv[0] = ObjFromLong(1);
        objv[1] = ObjFromUnicode(buf);
        ObjSetResult(interp, ObjNewList(2, objv));
        return TCL_OK;
    } else {
        DWORD lasterr = GetLastError();
        buf[0] = 0;
        if (lasterr == ERROR_NO_MORE_FILES) {
            /* Not an error, signal no more volumes */







|

















|







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
    else
        h = FindFirstVolumeW(buf, sizeof(buf)/sizeof(buf[0]));

    if (h == INVALID_HANDLE_VALUE)
        return TwapiReturnSystemError(interp);

    objv[0] = ObjFromHANDLE(h);
    objv[1] = ObjFromWinChars(buf);

    ObjSetResult(interp, ObjNewList(2, objv));
    return TCL_OK;
}

int TwapiNextVolume(Tcl_Interp *interp, int treat_as_mountpoint, HANDLE hFindVolume)
{
    BOOL    found;
    WCHAR   buf[MAX_PATH+1];

    found = (treat_as_mountpoint ?
             FindNextVolumeMountPointW : FindNextVolumeW)
        (hFindVolume, buf, sizeof(buf)/sizeof(buf[0]));

    if (found) {
        Tcl_Obj *objv[2];
        objv[0] = ObjFromLong(1);
        objv[1] = ObjFromWinChars(buf);
        ObjSetResult(interp, ObjNewList(2, objv));
        return TCL_OK;
    } else {
        DWORD lasterr = GetLastError();
        buf[0] = 0;
        if (lasterr == ERROR_NO_MORE_FILES) {
            /* Not an error, signal no more volumes */
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
            &serial_no,
            &max_component_len,
            &sysflags,
            fsname, sizeof(fsname)/sizeof(fsname[0])) == 0) {
        return TwapiReturnSystemError(interp);
    }

    objv[0] = ObjFromUnicode(volname);
    objv[1] = ObjFromLong(serial_no);
    objv[2] = ObjFromLong(max_component_len);
    objv[3] = ObjFromLong(sysflags);
    objv[4] = ObjFromUnicode(fsname);
    ObjSetResult(interp, ObjNewList(5, objv));

    return TCL_OK;
}


int Twapi_QueryDosDevice(Tcl_Interp *interp, LPCWSTR lpDeviceName)







|



|







97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
            &serial_no,
            &max_component_len,
            &sysflags,
            fsname, sizeof(fsname)/sizeof(fsname[0])) == 0) {
        return TwapiReturnSystemError(interp);
    }

    objv[0] = ObjFromWinChars(volname);
    objv[1] = ObjFromLong(serial_no);
    objv[2] = ObjFromLong(max_component_len);
    objv[3] = ObjFromLong(sysflags);
    objv[4] = ObjFromWinChars(fsname);
    ObjSetResult(interp, ObjNewList(5, objv));

    return TCL_OK;
}


int Twapi_QueryDosDevice(Tcl_Interp *interp, LPCWSTR lpDeviceName)
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    LARGE_INTEGER largeint;
    FILETIME ft[3];
    FILETIME *ftP[3];
    Tcl_Obj *objs[3];
    int i;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        result.value.uval = GetLogicalDrives();







<
<







187
188
189
190
191
192
193


194
195
196
197
198
199
200
    LARGE_INTEGER largeint;
    FILETIME ft[3];
    FILETIME *ftP[3];
    Tcl_Obj *objs[3];
    int i;
    int func = PtrToInt(clientdata);



    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        result.value.uval = GetLogicalDrives();
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
        CHECK_NARGS(interp, objc, 1);
        s = ObjToUnicode(objv[0]);
        switch (func) {
        case 3:
            return Twapi_QueryDosDevice(interp, s);
        case 4:
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = DeleteVolumeMountPointW(s);
            break;







|







208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
        CHECK_NARGS(interp, objc, 1);
        s = ObjToWinChars(objv[0]);
        switch (func) {
        case 3:
            return Twapi_QueryDosDevice(interp, s);
        case 4:
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = DeleteVolumeMountPointW(s);
            break;
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    case 21:
        CHECK_NARGS_RANGE(interp, objc, 2, 3);
        if (objc == 2)
            dw = 0;
        else {
            CHECK_INTEGER_OBJ(interp, dw, objv[2]);
        }
        s = ObjToUnicode(objv[0]);
        s2 = ObjToUnicode(objv[1]);
        switch (func) {
        case 19:
            NULLIFY_EMPTY(s2);
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = MoveFileExW(s,s2,dw);
            break;
        case 20:







|
|







308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    case 21:
        CHECK_NARGS_RANGE(interp, objc, 2, 3);
        if (objc == 2)
            dw = 0;
        else {
            CHECK_INTEGER_OBJ(interp, dw, objv[2]);
        }
        s = ObjToWinChars(objv[0]);
        s2 = ObjToWinChars(objv[1]);
        switch (func) {
        case 19:
            NULLIFY_EMPTY(s2);
            result.type = TRT_EXCEPTION_ON_FALSE;
            result.value.ival = MoveFileExW(s,s2,dw);
            break;
        case 20:
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        CHECK_NARGS(interp, objc, 3);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), ARGSKIP, ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival =
            DefineDosDeviceW(dw, ObjToUnicode(objv[1]),
                             ObjToLPWSTR_NULL_IF_EMPTY(objv[2]));
        break;

    }

    return TwapiSetResult(interp, &result);
}







|







352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
        CHECK_NARGS(interp, objc, 3);
        CHECK_INTEGER_OBJ(interp, dw, objv[0]);
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), ARGSKIP, ARGSKIP, ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_EXCEPTION_ON_FALSE;
        result.value.ival =
            DefineDosDeviceW(dw, ObjToWinChars(objv[1]),
                             ObjToLPWSTR_NULL_IF_EMPTY(objv[2]));
        break;

    }

    return TwapiSetResult(interp, &result);
}
Changes to undroid/twapi/twapi/tcl/accounts.tcl.
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
        # Tried it separately with a simple C program. So this code
        # is commented out and we use group membership to achieve
        # the desired result
        # Note: - latest MSDN confirms above
        if {![info exists twapi::priv_level_map($priv_level)]} {
            error "Invalid privilege level value '$priv_level' specified. Must be one of [join [array names twapi::priv_level_map] ,]"
        }
        set priv $::twapi::priv_level_map($priv_level)

        Twapi_NetUserSetInfo_priv $opts(system) $username $priv
    } else {
        # Don't hardcode group names - reverse map SID's instead for 
        # non-English systems. Also note that since
        # we might be lowering privilege level, we have to also
        # remove from higher privileged groups







|







937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
        # Tried it separately with a simple C program. So this code
        # is commented out and we use group membership to achieve
        # the desired result
        # Note: - latest MSDN confirms above
        if {![info exists twapi::priv_level_map($priv_level)]} {
            error "Invalid privilege level value '$priv_level' specified. Must be one of [join [array names twapi::priv_level_map] ,]"
        }
        set priv $twapi::priv_level_map($priv_level)

        Twapi_NetUserSetInfo_priv $opts(system) $username $priv
    } else {
        # Don't hardcode group names - reverse map SID's instead for 
        # non-English systems. Also note that since
        # we might be lowering privilege level, we have to also
        # remove from higher privileged groups
Changes to undroid/twapi/twapi/tcl/apputil.tcl.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Delete an ini file string
proc twapi::delete_inifile_key {section key args} {
    array set opts [parseargs args {
        inifile.arg
    } -maxleftover 0]

    if {[info exists opts(inifile)]} {
        WritePrivateProfileString $section $key $::twapi::nullptr $opts(inifile)
    } else {
        WriteProfileString $section $key $::twapi::nullptr
    }
}

# Get names of the sections in an inifile
proc twapi::read_inifile_section_names {args} {
    array set opts [parseargs args {
        inifile.arg







|

|







59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Delete an ini file string
proc twapi::delete_inifile_key {section key args} {
    array set opts [parseargs args {
        inifile.arg
    } -maxleftover 0]

    if {[info exists opts(inifile)]} {
        WritePrivateProfileString $section $key $twapi::nullptr $opts(inifile)
    } else {
        WriteProfileString $section $key $twapi::nullptr
    }
}

# Get names of the sections in an inifile
proc twapi::read_inifile_section_names {args} {
    array set opts [parseargs args {
        inifile.arg
Changes to undroid/twapi/twapi/tcl/base.tcl.
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808

    set result [list ]
    if {$opts(all) || $opts(domain)} {
        lappend result -domain $domain
    }
    if {$opts(all) || $opts(type)} {
        if {[info exists twapi::sid_type_names($type)]} {
            lappend result -type $::twapi::sid_type_names($type)
        } else {
            # Could be the "logonid" dummy type we added above
            lappend result -type $type
        }
    }

    if {$opts(all) || $opts(sid)} {







|







794
795
796
797
798
799
800
801
802
803
804
805
806
807
808

    set result [list ]
    if {$opts(all) || $opts(domain)} {
        lappend result -domain $domain
    }
    if {$opts(all) || $opts(type)} {
        if {[info exists twapi::sid_type_names($type)]} {
            lappend result -type $twapi::sid_type_names($type)
        } else {
            # Could be the "logonid" dummy type we added above
            lappend result -type $type
        }
    }

    if {$opts(all) || $opts(sid)} {
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871

    set result [list ]
    if {$opts(all) || $opts(domain)} {
        lappend result -domain $domain
    }
    if {$opts(all) || $opts(type)} {
        if {[info exists twapi::sid_type_names($type)]} {
            lappend result -type $::twapi::sid_type_names($type)
        } else {
            # Could be the "logonid" dummy type we added above
            lappend result -type $type
        }
    }

    if {$opts(all) || $opts(name)} {







|







857
858
859
860
861
862
863
864
865
866
867
868
869
870
871

    set result [list ]
    if {$opts(all) || $opts(domain)} {
        lappend result -domain $domain
    }
    if {$opts(all) || $opts(type)} {
        if {[info exists twapi::sid_type_names($type)]} {
            lappend result -type $twapi::sid_type_names($type)
        } else {
            # Could be the "logonid" dummy type we added above
            lappend result -type $type
        }
    }

    if {$opts(all) || $opts(name)} {
Changes to undroid/twapi/twapi/tcl/crypto.tcl.
373
374
375
376
377
378
379






380
381
382
383
384
385
386
proc twapi::cert_store_add_encoded_certificate {hstore enccert args} {
    parseargs args {
        {encoding.arg {} {der pem {}}}
    } -ignoreunknown -setvars
    array set opts [_cert_add_parseargs args]
    return [CertAddEncodedCertificateToStore $hstore 0x10001 [_pem_decode $enccert $encoding] $opts(disposition)]
}







proc twapi::cert_store_export_pfx {hstore password args} {
    parseargs args {
        {exportprivatekeys.bool 0 0x4}
        {failonmissingkey.bool 0 0x1}
        {failonunexportablekey.bool 0 0x2}
    } -maxleftover 0 -setvars







>
>
>
>
>
>







373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
proc twapi::cert_store_add_encoded_certificate {hstore enccert args} {
    parseargs args {
        {encoding.arg {} {der pem {}}}
    } -ignoreunknown -setvars
    array set opts [_cert_add_parseargs args]
    return [CertAddEncodedCertificateToStore $hstore 0x10001 [_pem_decode $enccert $encoding] $opts(disposition)]
}

proc twapi::cert_store_export_pem {hstore} {
    set pem {}
    cert_store_iterate $hstore c {append pem [cert_export $c]\n}
    return $pem
}

proc twapi::cert_store_export_pfx {hstore password args} {
    parseargs args {
        {exportprivatekeys.bool 0 0x4}
        {failonmissingkey.bool 0 0x1}
        {failonunexportablekey.bool 0 0x2}
    } -maxleftover 0 -setvars
1611
1612
1613
1614
1615
1616
1617

1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636

1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653

1654
1655

1656
1657
1658
1659
1660
1661
1662
}

###
# PKCS7 commands

proc twapi::pkcs7_encrypt {bytes recipients encalg args} {
    parseargs args {

        {innertype.arg 0}
    } -setvars -maxleftover 0

    # TBD - add support for the following
    set flags 0
    set encauxinfo {}

    set params [list \
                    0x10001 \
                    NULL \
                    [_make_algorithm_identifier $encalg] \
                    $encauxinfo \
                    $flags \
                    $innertype]
    return [CryptEncryptMessage $params $recipients $bytes]
}

proc twapi::pkcs7_decrypt {bytes stores args} {
    parseargs args {

        {silent.bool 0 0x40}
        {certvar.arg ""}
    } -maxleftover 0 -setvars

    set params [list \
                    0x10001 \
                    $stores \
                    $silent]
    if {$certvar ne ""} {
        upvar 1 $certvar hcert
        set certvar hcert
    }
    
    return [CryptDecryptMessage $params $bytes $certvar]
}
 
proc twapi::pkcs7_sign {bytes hcert hashalg args} {

    parseargs args {
        {detached.bool 0}

        {includecerts.arg all {none leaf all}}
        {silent.bool 0 0x40}
        {usesignerkeyid.bool 0 0x4}
        {crls.arg {}}
        {innercontenttype.arg 0}
    } -setvars -maxleftover 0








>














|




>













|



>


>







1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
}

###
# PKCS7 commands

proc twapi::pkcs7_encrypt {bytes recipients encalg args} {
    parseargs args {
        {encoding.arg pem {pem der}}
        {innertype.arg 0}
    } -setvars -maxleftover 0

    # TBD - add support for the following
    set flags 0
    set encauxinfo {}

    set params [list \
                    0x10001 \
                    NULL \
                    [_make_algorithm_identifier $encalg] \
                    $encauxinfo \
                    $flags \
                    $innertype]
    return [_as_pem_or_der [CryptEncryptMessage $params $recipients $bytes] PKCS7 $encoding]
}

proc twapi::pkcs7_decrypt {bytes stores args} {
    parseargs args {
        {encoding.arg {} {der pem {}}}
        {silent.bool 0 0x40}
        {certvar.arg ""}
    } -maxleftover 0 -setvars

    set params [list \
                    0x10001 \
                    $stores \
                    $silent]
    if {$certvar ne ""} {
        upvar 1 $certvar hcert
        set certvar hcert
    }
    
    return [CryptDecryptMessage $params [_pem_decode $bytes $encoding] $certvar]
}
 
proc twapi::pkcs7_sign {bytes hcert hashalg args} {
    # TBD - document crls?
    parseargs args {
        {detached.bool 0}
        {encoding.arg pem {pem der}}
        {includecerts.arg all {none leaf all}}
        {silent.bool 0 0x40}
        {usesignerkeyid.bool 0 0x4}
        {crls.arg {}}
        {innercontenttype.arg 0}
    } -setvars -maxleftover 0

1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700

1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
                    $authattrs \
                    $unauthattrs \
                    $flags \
                    $innercontenttype \
                    $encalg \
                    $hashencaux]
    trap {
        return [CryptSignMessage $params $detached [list $bytes]]
    } finally {
        foreach c $certs {
            cert_release $c
        }
    }
}

proc twapi::pkcs7_verify {bytes args} {
    parseargs args {

        {contentvar.arg ""}
        {certvar.arg ""}
    } -maxleftover 0 -setvars -ignoreunknown

    if {$contentvar ne ""} {
        upvar 1 $contentvar content
        set contentvar content
    }
    set status [CryptVerifyMessageSignature [list 0x10001 NULL] 0 $bytes $contentvar hcert]
    if {$status == 0} {
        trap {
            set status [cert_verify $hcert base {*}$args]
            if {$status eq "ok"} {
                if {$certvar ne ""} {
                    upvar 1 $certvar cert
                    set cert $hcert







|









>








|







1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
                    $authattrs \
                    $unauthattrs \
                    $flags \
                    $innercontenttype \
                    $encalg \
                    $hashencaux]
    trap {
        return [_as_pem_or_der [CryptSignMessage $params $detached [list $bytes]] PKCS7 $encoding]
    } finally {
        foreach c $certs {
            cert_release $c
        }
    }
}

proc twapi::pkcs7_verify {bytes args} {
    parseargs args {
        {encoding.arg {} {der pem {}}}
        {contentvar.arg ""}
        {certvar.arg ""}
    } -maxleftover 0 -setvars -ignoreunknown

    if {$contentvar ne ""} {
        upvar 1 $contentvar content
        set contentvar content
    }
    set status [CryptVerifyMessageSignature [list 0x10001 NULL] 0 [_pem_decode $bytes $encoding] $contentvar hcert]
    if {$status == 0} {
        trap {
            set status [cert_verify $hcert base {*}$args]
            if {$status eq "ok"} {
                if {$certvar ne ""} {
                    upvar 1 $certvar cert
                    set cert $hcert
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
# Helper for converting input parameters if they are in PEM format
# pem_or_der is the data
# enc specifies the type of pem_or_der. If empty, we guess.
# pemtype should generally be
# 0 -> CRYPT_STRING_BASE64HEADER for certificates
# 1 -> CRYPT_STRING_BASE64 (no header)
# 3 -> CRYPT_STRING_BASE64REQUESTHEADER
# 6 -> CRYPT_STIRNG_BASE64_ANY (actually same as 0 or 1)
proc twapi::_pem_decode {pem_or_der enc {pemtype 6}} {
    if {$enc eq "der"} {
        return $pem_or_der
    }
    if {$enc eq "pem" || 
        [regexp -nocase {^\s*-----\s*BEGIN\s+} $pem_or_der]} {
        return [CryptStringToBinary $pem_or_der $pemtype]







|







3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
# Helper for converting input parameters if they are in PEM format
# pem_or_der is the data
# enc specifies the type of pem_or_der. If empty, we guess.
# pemtype should generally be
# 0 -> CRYPT_STRING_BASE64HEADER for certificates
# 1 -> CRYPT_STRING_BASE64 (no header)
# 3 -> CRYPT_STRING_BASE64REQUESTHEADER
# 6 -> CRYPT_STRING_BASE64_ANY (actually same as 0 or 1)
proc twapi::_pem_decode {pem_or_der enc {pemtype 6}} {
    if {$enc eq "der"} {
        return $pem_or_der
    }
    if {$enc eq "pem" || 
        [regexp -nocase {^\s*-----\s*BEGIN\s+} $pem_or_der]} {
        return [CryptStringToBinary $pem_or_der $pemtype]
Changes to undroid/twapi/twapi/tcl/services.tcl.
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
    # -servicetype and -interactive go in same field
    if {![info exists opts(servicetype)] && ![info exists opts(interactive)]} {
        set winparams(servicetype) 0xffffffff; # SERVICE_NO_CHANGE
    }

    foreach opt {command loadordergroup dependencies account password displayname} {
        if {![info exists opts($opt)]} {
            set winparams($opt) $::twapi::nullptr
        }
    }

    set opts(scm_priv) 0x00020000; # 0x00020000 -> STANDARD_RIGHTS_READ
    set opts(svc_priv) 2;    # 2 -> SERVICE_CHANGE_CONFIG

    set opts(proc)     twapi::ChangeServiceConfig







|







518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
    # -servicetype and -interactive go in same field
    if {![info exists opts(servicetype)] && ![info exists opts(interactive)]} {
        set winparams(servicetype) 0xffffffff; # SERVICE_NO_CHANGE
    }

    foreach opt {command loadordergroup dependencies account password displayname} {
        if {![info exists opts($opt)]} {
            set winparams($opt) $twapi::nullptr
        }
    }

    set opts(scm_priv) 0x00020000; # 0x00020000 -> STANDARD_RIGHTS_READ
    set opts(svc_priv) 2;    # 2 -> SERVICE_CHANGE_CONFIG

    set opts(proc)     twapi::ChangeServiceConfig
Changes to undroid/twapi/twapi/tcl/ui.tcl.
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
    }
}


# if $hwin corresponds to a null window handle, returns an empty string
proc twapi::_return_window {hwin} {
    if {[pointer_null? $hwin HWND]} {
        return $::twapi::null_hwin
    }
    return $hwin
}

# Return 1 if same window
proc twapi::_same_window {hwin1 hwin2} {
    # If either is a empty/null handle, no match, even if both empty/null







|







1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
    }
}


# if $hwin corresponds to a null window handle, returns an empty string
proc twapi::_return_window {hwin} {
    if {[pointer_null? $hwin HWND]} {
        return $twapi::null_hwin
    }
    return $hwin
}

# Return 1 if same window
proc twapi::_same_window {hwin1 hwin2} {
    # If either is a empty/null handle, no match, even if both empty/null
Changes to undroid/twapi/twapi/tests/base.test.
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        twapi::get_version
    } -result 4.2

    test get_version-1.1 {
        Get TWAPI version patchlevel
    } -body {
        twapi::get_version -patchlevel
    } -result 4.2a4

    ################################################################

    test get_build_config-1.0 {
        Get the build configuration
    } -body {
        verify_kl_fields [twapi::get_build_config] {







|







41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        twapi::get_version
    } -result 4.2

    test get_version-1.1 {
        Get TWAPI version patchlevel
    } -body {
        twapi::get_version -patchlevel
    } -result 4.2a5

    ################################################################

    test get_build_config-1.0 {
        Get the build configuration
    } -body {
        verify_kl_fields [twapi::get_build_config] {
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563

    test tclcast-6.0 {
        Test for wide integer type
    } -body {
        # Note casting a 32 bit int to a wide int will not result
        # in a wide int - Tcl optimizes it back to an int
        twapi::tcltype [twapi::tclcast wideInt "0x123456789abcd"]
    } -result {Bad cast to "wideInt". Must be one of: "" empty null int boolean double string list dict} -returnCodes error

    test tclcast-6.1 {
        Test for wide integer type from integer
    } -body {
        twapi::tcltype [twapi::tclcast wideInt 1]
    } -result {Bad cast to "wideInt". Must be one of: "" empty null int boolean double string list dict} -returnCodes error

    test tclcast-7.0 {
        Test for double type
    } -body {
        twapi::tcltype [twapi::tclcast double 2.5]
    } -result double








|





|







1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563

    test tclcast-6.0 {
        Test for wide integer type
    } -body {
        # Note casting a 32 bit int to a wide int will not result
        # in a wide int - Tcl optimizes it back to an int
        twapi::tcltype [twapi::tclcast wideInt "0x123456789abcd"]
    } -result {Bad cast to "wideInt". Must be one of: "" empty null bstr int boolean double string list dict} -returnCodes error

    test tclcast-6.1 {
        Test for wide integer type from integer
    } -body {
        twapi::tcltype [twapi::tclcast wideInt 1]
    } -result {Bad cast to "wideInt". Must be one of: "" empty null bstr int boolean double string list dict} -returnCodes error

    test tclcast-7.0 {
        Test for double type
    } -body {
        twapi::tcltype [twapi::tclcast double 2.5]
    } -result double

3797
3798
3799
3800
3801
3802
3803












3804
3805
3806
3807
3808
3809
3810
        proc badproc args {twapi::badargs! Message}
    } -body {
        list [catch {badproc a b c} msg] [regexp {while executing\s+"badproc a b c"} $::errorInfo] $::errorCode
    } -result {1 1 {TWAPI BADARGS Message}}

    ################################################################













    test conceal-1.0 {
        Conceal text
    } -body {
        set c [twapi::conceal abc]
        list [string length $c] [string first a $c] [twapi::reveal $c]
    } -result {8 -1 abc}








>
>
>
>
>
>
>
>
>
>
>
>







3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
        proc badproc args {twapi::badargs! Message}
    } -body {
        list [catch {badproc a b c} msg] [regexp {while executing\s+"badproc a b c"} $::errorInfo] $::errorCode
    } -result {1 1 {TWAPI BADARGS Message}}

    ################################################################

    proc conceal_check {a b} {
        set m [stringSimilarity $a $b]
        # stringSimilarity considers ab and ba to be completely different
        # so check for reversed sequences
        set n [stringSimilarity $a [string reverse $b]]
        if {[tcl::mathfunc::max $m $n] == 0} {
            return 1
        } else {
            return 0
        }
    }
    # Following similarity code is from the wiki http://wiki.tcl.tk/3070
    test conceal-1.0 {
        Conceal text
    } -body {
        set c [twapi::conceal abc]
        list [string length $c] [string first a $c] [twapi::reveal $c]
    } -result {8 -1 abc}

3820
3821
3822
3823
3824
3825
3826


3827
3828
3829
3830
3831
3832
3833


3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
    } -body {
        set c [twapi::conceal ""]
        list [string length $c] [string equal "" $c] [twapi::reveal $c]
    } -result [list 8 0 {}]

    test conceal-1.3 {
        Conceal string


    } -body {
        set c [twapi::conceal "\x00\xff\x80"]
        list [string length $c] [string first \x00 $c] [twapi::reveal $c]
    } -result [list 8 -1 "\x00\xff\x80"]

    test conceal-1.4 {
        Conceal string, block size (8)


    } -body {
        set c [twapi::conceal "\x00\x01\x02\x03\xff\xfe\xfd\xfc"]
        list [string length $c] [string first \x00 $c] [twapi::reveal $c]
    } -result [list 24 -1 "\x00\x01\x02\x03\xff\xfe\xfd\xfc"]

    test conceal-1.5 {
        Conceal binary
    } -setup {
        set l {}
        for {set i 0} {$i < 256} {incr i} {
            lappend l $i
        }
        set binstr [binary format c* $l]
    } -body {
        set c [twapi::conceal $binstr]
        # binary will be encoded as unicode (256*2) plus 8 byte pad = 520
        list [string length $c] [string equal $binstr [twapi::reveal $c]]
    } -result [list 520 1]

    ################################################################

    test concealed?-1.0 {
        Unconcealed text
    } -body {
        twapi::concealed? abc







>
>

|
|
|



>
>

|
|
|












|
|







3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
    } -body {
        set c [twapi::conceal ""]
        list [string length $c] [string equal "" $c] [twapi::reveal $c]
    } -result [list 8 0 {}]

    test conceal-1.3 {
        Conceal string
    } -setup {
        set s "\x00\xff\x80"
    } -body {
        set c [twapi::conceal $s]
        list [string length $c] [conceal_check $s $c]  [twapi::reveal $c]
    } -result [list 8 1 "\x00\xff\x80"]

    test conceal-1.4 {
        Conceal string, block size (8)
    } -setup {
        set s "\x00\x01\x02\x03\xff\xfe\xfd\xfc"
    } -body {
        set c [twapi::conceal $s]
        list [string length $c] [conceal_check $s $c] [twapi::reveal $c]
    } -result [list 24 1 "\x00\x01\x02\x03\xff\xfe\xfd\xfc"]

    test conceal-1.5 {
        Conceal binary
    } -setup {
        set l {}
        for {set i 0} {$i < 256} {incr i} {
            lappend l $i
        }
        set binstr [binary format c* $l]
    } -body {
        set c [twapi::conceal $binstr]
        # binary will be encoded as unicode (256*2) plus 8 byte pad = 520
        list [string length $c] [conceal_check $binstr $c] [string equal $binstr [twapi::reveal $c]]
    } -result [list 520 1 1]

    ################################################################

    test concealed?-1.0 {
        Unconcealed text
    } -body {
        twapi::concealed? abc
Changes to undroid/twapi/twapi/tests/testutil.tcl.
1392
1393
1394
1395
1396
1397
1398























1399
1400
1401
1402
1403
1404
1405

proc inrange {range value} {
    foreach {low high} $range break
    expr {$value >= $low && $value <= $high}
}
tcltest::customMatch inrange inrange

























# Log a test debug message
proc testlog {msg} {
    if {![info exists ::testlog_fd]} {
        set ::testlog_fd [open testlog-[pid].log w+]
        set ::testlog_time [clock clicks]
    }







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428

proc inrange {range value} {
    foreach {low high} $range break
    expr {$value >= $low && $value <= $high}
}
tcltest::customMatch inrange inrange

# Following similarity code is from the wiki http://wiki.tcl.tk/3070
proc stringDistance {a b} {
    set n [string length $a]
    set m [string length $b]
    for {set i 0} {$i<=$n} {incr i} {set c($i,0) $i}
    for {set j 0} {$j<=$m} {incr j} {set c(0,$j) $j}
    for {set i 1} {$i<=$n} {incr i} {
        for {set j 1} {$j<=$m} {incr j} {
            set x [expr {$c([tcl::mathop::- $i 1],$j)+1}]
            set y [expr {$c($i,[tcl::mathop::- $j 1])+1}]
            set z $c([tcl::mathop::- $i 1],[tcl::mathop::- $j 1])
            if {[string index $a [tcl::mathop::- $i 1]]!=[string index $b [tcl::mathop::- $j 1]]} {
                incr z
            }
            set c($i,$j) [tcl::mathfunc::min $x $y $z]
        }
    }
    set c($n,$m)
}
proc stringSimilarity {a b} {
    set totalLength [string length $a$b]
    tcl::mathfunc::max [expr {double($totalLength-2*[stringDistance $a $b])/$totalLength}] 0.0
 }

# Log a test debug message
proc testlog {msg} {
    if {![info exists ::testlog_fd]} {
        set ::testlog_fd [open testlog-[pid].log w+]
        set ::testlog_time [clock clicks]
    }
Changes to undroid/twapi/twapi/ui/gdi.c.
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
/* 
 * Copyright (c) 2006-2012, Ashok P. Nadkarni
 * All rights reserved.
 *
 * See the file LICENSE for license
 */

#include "twapi.h"
#include "twapi_ui.h"
Tcl_Obj *ObjFromDISPLAY_DEVICE(DISPLAY_DEVICEW *ddP)
{
    Tcl_Obj *objv[5];

    objv[0] = ObjFromUnicode(ddP->DeviceName);
    objv[1] = ObjFromUnicode(ddP->DeviceString);
    objv[2] = ObjFromDWORD(ddP->StateFlags);
    objv[3] = ObjFromUnicode(ddP->DeviceID);
    objv[4] = ObjFromUnicode(ddP->DeviceKey);

    return Tcl_NewListObj(5, objv);
}

Tcl_Obj *ObjFromMONITORINFOEX(MONITORINFO *miP)
{
    Tcl_Obj *objv[4];
    int      objc;

    objc = 3;
    objv[0] = ObjFromRECT(&miP->rcMonitor);
    objv[1] = ObjFromRECT(&miP->rcWork);
    objv[2] = Tcl_NewLongObj(miP->dwFlags);
    /* miP could be either a MONITORINFO or MONITORINFOEX or MONITORINFOEXW */
    if (miP->cbSize == sizeof(MONITORINFOEX)) {
        objv[3] = Tcl_NewStringObj(((MONITORINFOEX *)miP)->szDevice, -1);
        objc = 4;
    }
    else if (miP->cbSize == sizeof(MONITORINFOEXW)) {
        objv[3] = ObjFromUnicode(((MONITORINFOEXW *)miP)->szDevice);
        objc = 4;
    }

    return Tcl_NewListObj(objc, objv);
}

/* Window enumeration callback */













|
|

|
|



















|







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
/* 
 * Copyright (c) 2006-2012, Ashok P. Nadkarni
 * All rights reserved.
 *
 * See the file LICENSE for license
 */

#include "twapi.h"
#include "twapi_ui.h"
Tcl_Obj *ObjFromDISPLAY_DEVICE(DISPLAY_DEVICEW *ddP)
{
    Tcl_Obj *objv[5];

    objv[0] = ObjFromWinChars(ddP->DeviceName);
    objv[1] = ObjFromWinChars(ddP->DeviceString);
    objv[2] = ObjFromDWORD(ddP->StateFlags);
    objv[3] = ObjFromWinChars(ddP->DeviceID);
    objv[4] = ObjFromWinChars(ddP->DeviceKey);

    return Tcl_NewListObj(5, objv);
}

Tcl_Obj *ObjFromMONITORINFOEX(MONITORINFO *miP)
{
    Tcl_Obj *objv[4];
    int      objc;

    objc = 3;
    objv[0] = ObjFromRECT(&miP->rcMonitor);
    objv[1] = ObjFromRECT(&miP->rcWork);
    objv[2] = Tcl_NewLongObj(miP->dwFlags);
    /* miP could be either a MONITORINFO or MONITORINFOEX or MONITORINFOEXW */
    if (miP->cbSize == sizeof(MONITORINFOEX)) {
        objv[3] = Tcl_NewStringObj(((MONITORINFOEX *)miP)->szDevice, -1);
        objc = 4;
    }
    else if (miP->cbSize == sizeof(MONITORINFOEXW)) {
        objv[3] = ObjFromWinChars(((MONITORINFOEXW *)miP)->szDevice);
        objc = 4;
    }

    return Tcl_NewListObj(objc, objv);
}

/* Window enumeration callback */
Changes to undroid/twapi/twapi/ui/ui.c.
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    objv[20] = STRING_LITERAL_OBJ("lfClipPrecision");
    objv[21] = ObjFromLong(lfP->lfClipPrecision);
    objv[22] = STRING_LITERAL_OBJ("lfQuality");
    objv[23] = ObjFromLong(lfP->lfQuality);
    objv[24] = STRING_LITERAL_OBJ("lfPitchAndFamily");
    objv[25] = ObjFromLong(lfP->lfPitchAndFamily);
    objv[26] = STRING_LITERAL_OBJ("lfFaceName");
    objv[27] = ObjFromUnicode(lfP->lfFaceName);

    return ObjNewList(28, objv);
}


int ObjToFLASHWINFO (Tcl_Interp *interp, Tcl_Obj *obj, FLASHWINFO *fwP)
{







|







64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    objv[20] = STRING_LITERAL_OBJ("lfClipPrecision");
    objv[21] = ObjFromLong(lfP->lfClipPrecision);
    objv[22] = STRING_LITERAL_OBJ("lfQuality");
    objv[23] = ObjFromLong(lfP->lfQuality);
    objv[24] = STRING_LITERAL_OBJ("lfPitchAndFamily");
    objv[25] = ObjFromLong(lfP->lfPitchAndFamily);
    objv[26] = STRING_LITERAL_OBJ("lfFaceName");
    objv[27] = ObjFromWinChars(lfP->lfFaceName);

    return ObjNewList(28, objv);
}


int ObjToFLASHWINFO (Tcl_Interp *interp, Tcl_Obj *obj, FLASHWINFO *fwP)
{
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
                   color, ARRAYSIZE(color),
                   size, ARRAYSIZE(size));

    if (status != S_OK) {
        return Twapi_AppendSystemError(interp, status);
    }

    objv[0] = ObjFromUnicode(filename);
    objv[1] = ObjFromUnicode(color);
    objv[2] = ObjFromUnicode(size);
    ObjSetResult(interp, ObjNewList(3, objv));
    return TCL_OK;
}

int Twapi_GetThemeColor(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HTHEME hTheme;







|
|
|







240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
                   color, ARRAYSIZE(color),
                   size, ARRAYSIZE(size));

    if (status != S_OK) {
        return Twapi_AppendSystemError(interp, status);
    }

    objv[0] = ObjFromWinChars(filename);
    objv[1] = ObjFromWinChars(color);
    objv[2] = ObjFromWinChars(size);
    ObjSetResult(interp, ObjNewList(3, objv));
    return TCL_OK;
}

int Twapi_GetThemeColor(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    HTHEME hTheme;
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
        DISPLAY_DEVICEW display_device;
        LOGFONTW lf;
    } u;
    RECT *rectP;
    LPVOID pv;
    int func = PtrToInt(clientdata);

    ObjToUnicodeCleanup();

    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    if (func < 1000) {
        /* Functions taking no arguments */








<
<







325
326
327
328
329
330
331


332
333
334
335
336
337
338
        DISPLAY_DEVICEW display_device;
        LOGFONTW lf;
    } u;
    RECT *rectP;
    LPVOID pv;
    int func = PtrToInt(clientdata);



    --objc;
    ++objv;

    result.type = TRT_BADFUNCTIONCODE;
    if (func < 1000) {
        /* Functions taking no arguments */

537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
            break;
        case 10008: // AddFontResourceExW
        case 10009: // RemoveFontResourceExW
            if (TwapiGetArgs(interp, objc, objv, ARGSKIP,
                             ARGUSEDEFAULT, GETINT(dw), ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.value.ival =
                (func == 10008 ? AddFontResourceExW : RemoveFontResourceExW) (ObjToUnicode(objv[0]), dw, NULL);
            result.type = TRT_LONG;
            break;
        }
    }
    return TwapiSetResult(interp, &result);
}








|







535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
            break;
        case 10008: // AddFontResourceExW
        case 10009: // RemoveFontResourceExW
            if (TwapiGetArgs(interp, objc, objv, ARGSKIP,
                             ARGUSEDEFAULT, GETINT(dw), ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.value.ival =
                (func == 10008 ? AddFontResourceExW : RemoveFontResourceExW) (ObjToWinChars(objv[0]), dw, NULL);
            result.type = TRT_LONG;
            break;
        }
    }
    return TwapiSetResult(interp, &result);
}

561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
        WCHAR buf[MAX_PATH+1];
        RECT   rect;
        HRGN   hrgn;
    } u;
    RECT *rectP;
    HANDLE h;

    ObjToUnicodeCleanup();

    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHWND(hwnd),
                     ARGTERM) != TCL_OK)
        return TCL_ERROR;

    objc -= 2;
    objv += 2;







<
<







559
560
561
562
563
564
565


566
567
568
569
570
571
572
        WCHAR buf[MAX_PATH+1];
        RECT   rect;
        HRGN   hrgn;
    } u;
    RECT *rectP;
    HANDLE h;



    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHWND(hwnd),
                     ARGTERM) != TCL_OK)
        return TCL_ERROR;

    objc -= 2;
    objv += 2;
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
    } else {
        /* At least one additional arg */
        if (objc == 0)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

        switch (func) {
        case 1001: // SetWindowText
            result.value.ival = SetWindowTextW(hwnd, ObjToUnicode(objv[0]));
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 1002: // IsChild
            if (ObjToHWND(interp, objv[0], &hwnd2) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_BOOL;
            result.value.bval = IsChild(hwnd, hwnd2);







|







709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
    } else {
        /* At least one additional arg */
        if (objc == 0)
            return TwapiReturnError(interp, TWAPI_BAD_ARG_COUNT);

        switch (func) {
        case 1001: // SetWindowText
            result.value.ival = SetWindowTextW(hwnd, ObjToWinChars(objv[0]));
            result.type = TRT_EXCEPTION_ON_FALSE;
            break;
        case 1002: // IsChild
            if (ObjToHWND(interp, objv[0], &hwnd2) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_BOOL;
            result.value.bval = IsChild(hwnd, hwnd2);
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_LONG;
            result.value.ival = ReleaseDC(hwnd, h);
            break;
        case 1008:
            result.type = TRT_HANDLE;
            result.value.hval = OpenThemeData(hwnd, ObjToUnicode(objv[0]));
            break;
        case 1009: // SetWindowRgn
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLET(u.hrgn, HRGN), GETBOOL(dw),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EXCEPTION_ON_FALSE;







|







764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_LONG;
            result.value.ival = ReleaseDC(hwnd, h);
            break;
        case 1008:
            result.type = TRT_HANDLE;
            result.value.hval = OpenThemeData(hwnd, ObjToWinChars(objv[0]));
            break;
        case 1009: // SetWindowRgn
            if (TwapiGetArgs(interp, objc, objv,
                             GETHANDLET(u.hrgn, HRGN), GETBOOL(dw),
                             ARGEND) != TCL_OK)
                return TCL_ERROR;
            result.type = TRT_EXCEPTION_ON_FALSE;
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
        WINDOWPLACEMENT winplace;
        WINDOWINFO wininfo;
        WCHAR buf[MAX_PATH+1];
        RECT   rect;
        HRGN   hrgn;
    } u;

    ObjToUnicodeCleanup();

    /* At least two args - window and another arg */
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHWND(hwnd), GETOBJ(objP),
                     ARGTERM) != TCL_OK)
        return TCL_ERROR;

    mark = SWSPushMark();







<
<







814
815
816
817
818
819
820


821
822
823
824
825
826
827
        WINDOWPLACEMENT winplace;
        WINDOWINFO wininfo;
        WCHAR buf[MAX_PATH+1];
        RECT   rect;
        HRGN   hrgn;
    } u;



    /* At least two args - window and another arg */
    if (TwapiGetArgs(interp, objc-1, objv+1,
                     GETHWND(hwnd), GETOBJ(objP),
                     ARGTERM) != TCL_OK)
        return TCL_ERROR;

    mark = SWSPushMark();
Changes to undroid/twapi/twapi/winsta/winsta.c.
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* Window station enumeration callback */
BOOL CALLBACK Twapi_EnumWindowStationsOrDesktopsCallback(LPCWSTR p_winsta, LPARAM p_ctx) {
    TwapiEnumCtx *p_enum_ctx =
        (TwapiEnumCtx *) p_ctx;

    ObjAppendElement(p_enum_ctx->interp,
                             p_enum_ctx->objP,
                             ObjFromUnicode(p_winsta));
    return 1;
}

/* Window station enumeration */
int Twapi_EnumWindowStations(Tcl_Interp *interp)
{
    TwapiEnumCtx enum_ctx;







|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* Window station enumeration callback */
BOOL CALLBACK Twapi_EnumWindowStationsOrDesktopsCallback(LPCWSTR p_winsta, LPARAM p_ctx) {
    TwapiEnumCtx *p_enum_ctx =
        (TwapiEnumCtx *) p_ctx;

    ObjAppendElement(p_enum_ctx->interp,
                             p_enum_ctx->objP,
                             ObjFromWinChars(p_winsta));
    return 1;
}

/* Window station enumeration */
int Twapi_EnumWindowStations(Tcl_Interp *interp)
{
    TwapiEnumCtx enum_ctx;
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
            break;
        case 5: // UOI_HEAPSIZE: not defined in win2003 SDK (only supported on Vista on)
        case 6: // == ditto ==
            objP = ObjFromDWORD(* (DWORD*)pv);
            break;
        case UOI_NAME:
        case UOI_TYPE:
            objP = ObjFromUnicode(pv);
            break;
        case UOI_USER_SID:
            /* If len is 0, no SID is associated and we just return empty result */
            if (len == 0)
                objP = NULL;
            else
                objP = ObjFromSIDNoFail(pv);







|







106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
            break;
        case 5: // UOI_HEAPSIZE: not defined in win2003 SDK (only supported on Vista on)
        case 6: // == ditto ==
            objP = ObjFromDWORD(* (DWORD*)pv);
            break;
        case UOI_NAME:
        case UOI_TYPE:
            objP = ObjFromWinChars(pv);
            break;
        case UOI_USER_SID:
            /* If len is 0, no SID is associated and we just return empty result */
            if (len == 0)
                objP = NULL;
            else
                objP = ObjFromSIDNoFail(pv);
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    DWORD dw, dw2, dw3;
    SECURITY_ATTRIBUTES *secattrP;
    HANDLE h;
    int func = PtrToInt(clientdata);
    TwapiResult result;
    SWSMark mark = NULL;
    TCL_RESULT res;

    ObjToUnicodeCleanup();

    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        return Twapi_EnumWindowStations(interp);
    case 2:
        result.type = TRT_HWINSTA;
        result.value.hval = GetProcessWindowStation();
        break;
    case 3:
        mark = SWSPushMark();
        res = TwapiGetArgs(interp, objc, objv, ARGSKIP,
                           GETINT(dw), GETINT(dw2),
                           GETVAR(secattrP, ObjToPSECURITY_ATTRIBUTESSWS),
                           ARGEND);
        if (res != TCL_OK)
            goto vamoose;
        result.type = TRT_HWINSTA;
        result.value.hval = CreateWindowStationW(ObjToUnicode(objv[0]), dw, dw2, secattrP);
        break;
    case 4:
        if (TwapiGetArgs(interp, objc, objv,
                         ARGSKIP, GETINT(dw), GETINT(dw2), GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HDESK;
        result.value.hval = OpenDesktopW(ObjToUnicode(objv[0]), dw, dw2, dw3);
        break;
    case 5:
        if (TwapiGetArgs(interp, objc, objv, GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.value.hval = GetThreadDesktop(dw);
        result.type = TRT_HDESK;
        break;
    case 6:
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HDESK;
        result.value.hval = OpenInputDesktop(dw, dw2, dw3);
        break;
    case 7:
        if (TwapiGetArgs(interp, objc, objv,
                         ARGSKIP, GETINT(dw), GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HWINSTA;
        result.value.hval = OpenWindowStationW(ObjToUnicode(objv[0]), dw, dw2);
        break;
    case 8: // CreateDesktopW
        /* Note second, third args are ignored and are reserved as NULL */
        mark = SWSPushMark();
        res = TwapiGetArgs(interp, objc, objv,
                           ARGSKIP, ARGUNUSED, ARGUNUSED, GETINT(dw),
                           GETINT(dw2),
                           GETVAR(secattrP, ObjToPSECURITY_ATTRIBUTESSWS),
                           ARGEND);
        if (res != TCL_OK)
            goto vamoose;
        result.type = TRT_HDESK;
        result.value.hval = CreateDesktopW(ObjToUnicode(objv[0]), NULL, NULL, dw, dw2, secattrP);
        break;
    default:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), ARGEND) != TCL_OK)
            return TCL_ERROR;
        switch (func) {
        case 31:







|
<
<



















|







|




















|












|







135
136
137
138
139
140
141
142


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    DWORD dw, dw2, dw3;
    SECURITY_ATTRIBUTES *secattrP;
    HANDLE h;
    int func = PtrToInt(clientdata);
    TwapiResult result;
    SWSMark mark = NULL;
    TCL_RESULT res;
    


    --objc;
    ++objv;
    result.type = TRT_BADFUNCTIONCODE;
    switch (func) {
    case 1:
        return Twapi_EnumWindowStations(interp);
    case 2:
        result.type = TRT_HWINSTA;
        result.value.hval = GetProcessWindowStation();
        break;
    case 3:
        mark = SWSPushMark();
        res = TwapiGetArgs(interp, objc, objv, ARGSKIP,
                           GETINT(dw), GETINT(dw2),
                           GETVAR(secattrP, ObjToPSECURITY_ATTRIBUTESSWS),
                           ARGEND);
        if (res != TCL_OK)
            goto vamoose;
        result.type = TRT_HWINSTA;
        result.value.hval = CreateWindowStationW(ObjToWinChars(objv[0]), dw, dw2, secattrP);
        break;
    case 4:
        if (TwapiGetArgs(interp, objc, objv,
                         ARGSKIP, GETINT(dw), GETINT(dw2), GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HDESK;
        result.value.hval = OpenDesktopW(ObjToWinChars(objv[0]), dw, dw2, dw3);
        break;
    case 5:
        if (TwapiGetArgs(interp, objc, objv, GETINT(dw), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.value.hval = GetThreadDesktop(dw);
        result.type = TRT_HDESK;
        break;
    case 6:
        if (TwapiGetArgs(interp, objc, objv,
                         GETINT(dw), GETINT(dw2), GETINT(dw3),
                         ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HDESK;
        result.value.hval = OpenInputDesktop(dw, dw2, dw3);
        break;
    case 7:
        if (TwapiGetArgs(interp, objc, objv,
                         ARGSKIP, GETINT(dw), GETINT(dw2), ARGEND) != TCL_OK)
            return TCL_ERROR;
        result.type = TRT_HWINSTA;
        result.value.hval = OpenWindowStationW(ObjToWinChars(objv[0]), dw, dw2);
        break;
    case 8: // CreateDesktopW
        /* Note second, third args are ignored and are reserved as NULL */
        mark = SWSPushMark();
        res = TwapiGetArgs(interp, objc, objv,
                           ARGSKIP, ARGUNUSED, ARGUNUSED, GETINT(dw),
                           GETINT(dw2),
                           GETVAR(secattrP, ObjToPSECURITY_ATTRIBUTESSWS),
                           ARGEND);
        if (res != TCL_OK)
            goto vamoose;
        result.type = TRT_HDESK;
        result.value.hval = CreateDesktopW(ObjToWinChars(objv[0]), NULL, NULL, dw, dw2, secattrP);
        break;
    default:
        if (TwapiGetArgs(interp, objc, objv,
                         GETHANDLE(h), ARGEND) != TCL_OK)
            return TCL_ERROR;
        switch (func) {
        case 31:
Changes to undroid/twapi/twapi/wmi/wmi.c.
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
        buf = ObjToStringN(objv[1], &buflen);
        hr = ifc->lpVtbl->CompileBuffer(ifc, buflen, buf, server_namespace,
                                         user, authority, password,
                                         optflags, classflags, instflags,
                                         &wcsi);
        break;
    case 1:
        hr = ifc->lpVtbl->CompileFile(ifc, ObjToUnicode(objv[1]),
                                       server_namespace,
                                       user, authority, password,
                                       optflags, classflags, instflags,
                                       &wcsi);
        break;

    case 2:
        hr = ifc->lpVtbl->CreateBMOF(ifc, ObjToUnicode(objv[1]),
                                     ObjToUnicode(objv[2]),
                                     server_namespace,
                                     optflags, classflags, instflags,
                                     &wcsi);
        break;

    default:
        return TwapiReturnErrorEx(interp,







|







|
|







62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
        buf = ObjToStringN(objv[1], &buflen);
        hr = ifc->lpVtbl->CompileBuffer(ifc, buflen, buf, server_namespace,
                                         user, authority, password,
                                         optflags, classflags, instflags,
                                         &wcsi);
        break;
    case 1:
        hr = ifc->lpVtbl->CompileFile(ifc, ObjToWinChars(objv[1]),
                                       server_namespace,
                                       user, authority, password,
                                       optflags, classflags, instflags,
                                       &wcsi);
        break;

    case 2:
        hr = ifc->lpVtbl->CreateBMOF(ifc, ObjToWinChars(objv[1]),
                                     ObjToWinChars(objv[2]),
                                     server_namespace,
                                     optflags, classflags, instflags,
                                     &wcsi);
        break;

    default:
        return TwapiReturnErrorEx(interp,
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
                                       wcsi.LastLine));
        return Twapi_AppendSystemError(interp, wcsi.hRes ? wcsi.hRes : hr);
    }
}                     

static int Twapi_WmiCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    ObjToUnicodeCleanup();

    --objc;
    ++objv;
    switch (PtrToInt(clientdata)) {
    case 1: // IMofCompiler_CompileBuffer
        return Twapi_IMofCompiler_CompileFileOrBuffer(interp, 0, objc, objv);
    case 2: // IMofCompiler_CompileFile
        return Twapi_IMofCompiler_CompileFileOrBuffer(interp, 1, objc, objv);







<
<







102
103
104
105
106
107
108


109
110
111
112
113
114
115
                                       wcsi.LastLine));
        return Twapi_AppendSystemError(interp, wcsi.hRes ? wcsi.hRes : hr);
    }
}                     

static int Twapi_WmiCallObjCmd(ClientData clientdata, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{


    --objc;
    ++objv;
    switch (PtrToInt(clientdata)) {
    case 1: // IMofCompiler_CompileBuffer
        return Twapi_IMofCompiler_CompileFileOrBuffer(interp, 0, objc, objv);
    case 2: // IMofCompiler_CompileFile
        return Twapi_IMofCompiler_CompileFileOrBuffer(interp, 1, objc, objv);