forked from microsoft/windows-drivers-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1440 lines (1297 loc) · 52.6 KB
/
lib.rs
File metadata and controls
1440 lines (1297 loc) · 52.6 KB
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
221
222
223
224
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
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
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
391
392
393
394
395
396
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
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
513
514
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
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
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
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
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
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
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
// Copyright (c) Microsoft Corporation
// License: MIT OR Apache-2.0
//! A collection of macros that help make it easier to interact with
//! [`wdk-sys`]'s direct bindings to the Windows Driver Kit (WDK).
use std::{collections::HashMap, path::PathBuf, str::FromStr};
use fs4::fs_std::FileExt;
use itertools::Itertools;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{format_ident, quote, ToTokens};
use serde::{Deserialize, Serialize};
use syn::{
parse::{Parse, ParseStream, Parser},
parse2,
parse_file,
parse_quote,
punctuated::Punctuated,
AngleBracketedGenericArguments,
Attribute,
BareFnArg,
Error,
Expr,
ExprCall,
File,
GenericArgument,
Ident,
Item,
ItemType,
LitStr,
Path,
PathArguments,
PathSegment,
Result,
ReturnType,
Signature,
Stmt,
Token,
Type,
TypeBareFn,
TypePath,
};
/// A procedural macro that allows WDF functions to be called by name.
///
/// This macro is only intended to be used in the `wdk-sys` crate. Users wanting
/// to call WDF functions should use the macro in `wdk-sys`. This macro differs
/// from the one in [`wdk-sys`] in that it must pass in the generated types from
/// `wdk-sys` as an argument to the macro.
#[proc_macro]
pub fn call_unsafe_wdf_function_binding(input_tokens: TokenStream) -> TokenStream {
call_unsafe_wdf_function_binding_impl(TokenStream2::from(input_tokens)).into()
}
/// A trait to provide additional functionality to the [`String`] type
trait StringExt {
/// Convert a string to `snake_case`
fn to_snake_case(&self) -> String;
}
/// Struct storing the input tokens directly parsed from calls to
/// `call_unsafe_wdf_function_binding` macro
#[derive(Debug, PartialEq)]
struct Inputs {
/// Path to file where generated type information resides.
types_path: LitStr,
/// The name of the WDF function to call. This matches the name of the
/// function in C/C++.
wdf_function_identifier: Ident,
/// The arguments to pass to the WDF function. These should match the
/// function signature of the WDF function.
wdf_function_arguments: Punctuated<Expr, Token![,]>,
}
/// Struct storing all the AST fragments derived from [`Inputs`]. This
/// represents all the ASTs derived from [`Inputs`]. These ultimately get used
/// in the final generated code.
#[derive(Debug, PartialEq)]
struct DerivedASTFragments {
function_pointer_type: Ident,
function_table_index: Ident,
parameters: Punctuated<BareFnArg, Token![,]>,
parameter_identifiers: Punctuated<Ident, Token![,]>,
return_type: ReturnType,
arguments: Punctuated<Expr, Token![,]>,
inline_wdf_fn_name: Ident,
}
/// Struct storing the AST fragments that form distinct sections of the final
/// generated code. Each field is derived from [`DerivedASTFragments`].
struct IntermediateOutputASTFragments {
must_use_attribute: Option<Attribute>,
inline_wdf_fn_signature: Signature,
inline_wdf_fn_body_statments: Vec<Stmt>,
inline_wdf_fn_invocation: ExprCall,
}
/// Struct storing string representations of the information we want to cache
/// from `types.rs`.
#[derive(Serialize, Deserialize)]
struct SavedFunctionInfo {
parameters: String,
return_type: String,
}
impl StringExt for String {
fn to_snake_case(&self) -> String {
// There will be, at max, 2 characters unhandled by the 3-char windows. It is
// only less than 2 when the string has length less than 2
const MAX_PADDING_NEEDED: usize = 2;
let mut snake_case_string = Self::with_capacity(self.len());
for (current_char, next_char, next_next_char) in self
.chars()
.map(Some)
.chain([None; MAX_PADDING_NEEDED])
.tuple_windows()
.filter_map(|(c1, c2, c3)| Some((c1?, c2, c3)))
{
// Handle camelCase or PascalCase word boundary (e.g. lC in camelCase)
if current_char.is_lowercase() && next_char.is_some_and(|c| c.is_ascii_uppercase()) {
snake_case_string.push(current_char);
snake_case_string.push('_');
}
// Handle UPPERCASE acronym word boundary (e.g. ISt in ASCIIString)
else if current_char.is_uppercase()
&& next_char.is_some_and(|c| c.is_ascii_uppercase())
&& next_next_char.is_some_and(|c| c.is_ascii_lowercase())
{
snake_case_string.push(current_char.to_ascii_lowercase());
snake_case_string.push('_');
} else {
snake_case_string.push(current_char.to_ascii_lowercase());
}
}
snake_case_string
}
}
impl Parse for Inputs {
fn parse(input: ParseStream) -> Result<Self> {
let types_path = input.parse::<LitStr>()?;
input.parse::<Token![,]>()?;
let c_wdf_function_identifier = input.parse::<Ident>()?;
// Support WDF apis with no arguments
if input.is_empty() {
return Ok(Self {
types_path,
wdf_function_identifier: c_wdf_function_identifier,
wdf_function_arguments: Punctuated::new(),
});
}
input.parse::<Token![,]>()?;
let wdf_function_arguments = input.parse_terminated(Expr::parse, Token![,])?;
Ok(Self {
types_path,
wdf_function_identifier: c_wdf_function_identifier,
wdf_function_arguments,
})
}
}
impl Inputs {
fn generate_derived_ast_fragments(self) -> Result<DerivedASTFragments> {
let function_pointer_type = format_ident!(
"PFN_{uppercase_c_function_name}",
uppercase_c_function_name = self.wdf_function_identifier.to_string().to_uppercase(),
span = self.wdf_function_identifier.span()
);
let function_table_index = format_ident!(
"{wdf_function_identifier}TableIndex",
wdf_function_identifier = self.wdf_function_identifier,
span = self.wdf_function_identifier.span()
);
let function_name_to_info_map: HashMap<String, SavedFunctionInfo> =
self.get_fragment_info_map()?;
let function_info = function_name_to_info_map
.get(&self.wdf_function_identifier.to_string())
.ok_or_else(|| {
Error::new(
self.wdf_function_identifier.span(),
format!(
"Failed to find function info for {}",
self.wdf_function_identifier
),
)
})?;
let parameters_tokens = TokenStream2::from_str(&function_info.parameters)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
let return_type_tokens = TokenStream2::from_str(&function_info.return_type)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
let parameters =
Punctuated::<BareFnArg, Token![,]>::parse_terminated.parse2(parameters_tokens)?;
let return_type = ReturnType::parse.parse2(return_type_tokens)?;
let parameter_identifiers = parameters
.iter()
.cloned()
.map(|bare_fn_arg| {
if let Some((identifier, _)) = bare_fn_arg.name {
return Ok(identifier);
}
Err(Error::new(
function_pointer_type.span(),
format!("Expected fn parameter to have a name: {bare_fn_arg:#?}"),
))
})
.collect::<Result<_>>()?;
let inline_wdf_fn_name = format_ident!(
"{c_function_name_snake_case}_impl",
c_function_name_snake_case = self.wdf_function_identifier.to_string().to_snake_case()
);
Ok(DerivedASTFragments {
function_pointer_type,
function_table_index,
parameters,
parameter_identifiers,
return_type,
arguments: self.wdf_function_arguments,
inline_wdf_fn_name,
})
}
// Motivation for this function is to reduce build time. Rather than parse
// types.rs for relevant information to construct function table call on each
// macro invocation, we store all possible function table information for each
// function on first invocation. We cache this using the `scratch` crate, and
// read from this cache for each subsequent invocation.
fn get_fragment_info_map(&self) -> Result<HashMap<String, SavedFunctionInfo>> {
let scratch_dir = scratch::path("ast_fragments");
let flock = std::fs::File::create(scratch_dir.join(".lock"))
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
let fragment_info_map_path = scratch_dir.join("fragment_info_map.json");
if !fragment_info_map_path.exists() {
FileExt::lock_exclusive(&flock)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
if !fragment_info_map_path.exists() {
let generated_map = self.generate_fragment_info_map_from_types()?;
let generated_map_string = serde_json::to_string(&generated_map)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
std::fs::write(&fragment_info_map_path, generated_map_string)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
}
FileExt::unlock(&flock)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
}
let generated_map_string = std::fs::read_to_string(&fragment_info_map_path)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
let map: HashMap<String, SavedFunctionInfo> =
serde_json::from_str(&generated_map_string)
.map_err(|e| map_to_syn_error(self.wdf_function_identifier.span(), e))?;
Ok(map)
}
// To generate the cache we parse the types.rs file for `mod _WDFFUNCENUM`. This
// stores each function table name with the suffix "TableIndex", which we parse
// and trim. We then use this function name to parse for the function pointer
// type alias, which we then parse for the function parameters and return type.
fn generate_fragment_info_map_from_types(&self) -> Result<HashMap<String, SavedFunctionInfo>> {
let types_ast = parse_types_ast(&self.types_path)?;
let func_enum_mod: Option<&syn::ItemMod> = types_ast.items.iter().find_map(|item| {
if let Item::Mod(mod_alias) = item {
if mod_alias.ident == "_WDFFUNCENUM" {
return Some(mod_alias);
}
}
None
});
let func_enum_mod = func_enum_mod.ok_or_else(|| {
Error::new(
self.wdf_function_identifier.span(),
"Failed to find _WDFFUNCENUM module in types file",
)
})?;
let func_enum_mod_contents = &func_enum_mod
.content
.as_ref()
.ok_or_else(|| {
Error::new(
self.wdf_function_identifier.span(),
"Failed to find _WDFFUNCENUM module contents in types file",
)
})?
.1;
let mut const_func_enum_types: Vec<String> = vec![];
for func_enum_mod_item in func_enum_mod_contents {
if let Item::Const(const_alias) = func_enum_mod_item {
const_func_enum_types.push(const_alias.ident.to_string());
}
}
let mut function_name_to_info_map: HashMap<String, SavedFunctionInfo> = HashMap::new();
for const_func_enum_type in const_func_enum_types {
let Some(wdf_function_name) = const_func_enum_type.strip_suffix("TableIndex") else {
continue;
};
let function_pointer_type = format_ident!(
"PFN_{uppercase_c_function_name}",
uppercase_c_function_name = wdf_function_name.to_uppercase(),
span = self.wdf_function_identifier.span()
);
let (parameters, return_type) =
match generate_parameters_and_return_type(&types_ast, &function_pointer_type) {
Ok((parameters, return_type)) => (parameters, return_type),
Err(err) => {
if err
.to_string()
.contains("Failed to find type alias definition for")
{
continue;
}
return Err(err);
}
};
function_name_to_info_map.insert(
wdf_function_name.into(),
SavedFunctionInfo {
parameters: parameters.to_token_stream().to_string(),
return_type: return_type.to_token_stream().to_string(),
},
);
}
Ok(function_name_to_info_map)
}
}
impl DerivedASTFragments {
fn generate_intermediate_output_ast_fragments(self) -> IntermediateOutputASTFragments {
let Self {
function_pointer_type,
function_table_index,
parameters,
parameter_identifiers,
return_type,
arguments,
inline_wdf_fn_name,
} = self;
let must_use_attribute = generate_must_use_attribute(&return_type);
let inline_wdf_fn_signature = parse_quote! {
unsafe fn #inline_wdf_fn_name(#parameters) #return_type
};
let inline_wdf_fn_body_statments = parse_quote! {
// Get handle to WDF function from the function table
let wdf_function: wdk_sys::#function_pointer_type = Some(
// SAFETY: This `transmute` from a no-argument function pointer to a function pointer with the correct
// arguments for the WDF function is safe befause WDF maintains the strict mapping between the
// function table index and the correct function pointer type.
unsafe {
let wdf_function_table = wdk_sys::WdfFunctions;
let wdf_function_count = wdk_sys::wdf::__private::get_wdf_function_count();
// SAFETY: This is safe because:
// 1. `WdfFunctions` is valid for reads for `{NUM_WDF_FUNCTIONS_PLACEHOLDER}` * `core::mem::size_of::<WDFFUNC>()`
// bytes, and is guaranteed to be aligned and it must be properly aligned.
// 2. `WdfFunctions` points to `{NUM_WDF_FUNCTIONS_PLACEHOLDER}` consecutive properly initialized values of
// type `WDFFUNC`.
// 3. WDF does not mutate the memory referenced by the returned slice for for its entire `'static' lifetime.
// 4. The total size, `{NUM_WDF_FUNCTIONS_PLACEHOLDER}` * `core::mem::size_of::<WDFFUNC>()`, of the slice must be no
// larger than `isize::MAX`. This is proven by the below `const_assert!`.
debug_assert!(isize::try_from(wdf_function_count * core::mem::size_of::<wdk_sys::WDFFUNC>()).is_ok());
let wdf_function_table = core::slice::from_raw_parts(wdf_function_table, wdf_function_count);
core::mem::transmute(
// FIXME: investigate why _WDFFUNCENUM does not have a generated type alias without the underscore prefix
wdf_function_table[wdk_sys::_WDFFUNCENUM::#function_table_index as usize],
)
}
);
// Call the WDF function with the supplied args. This mirrors what happens in the inlined WDF function in
// the various wdf headers(ex. wdfdriver.h)
if let Some(wdf_function) = wdf_function {
// SAFETY: The WDF function pointer is always valid because its an entry in
// `wdk_sys::WDF_FUNCTION_TABLE` indexed by `table_index` and guarded by the type-safety of
// `pointer_type`. The passed arguments are also guaranteed to be of a compatible type due to
// `pointer_type`.
unsafe {
(wdf_function)(
wdk_sys::WdfDriverGlobals,
#parameter_identifiers
)
}
} else {
unreachable!("Option should never be None");
}
};
let inline_wdf_fn_invocation = parse_quote! {
#inline_wdf_fn_name(#arguments)
};
IntermediateOutputASTFragments {
must_use_attribute,
inline_wdf_fn_signature,
inline_wdf_fn_body_statments,
inline_wdf_fn_invocation,
}
}
}
impl IntermediateOutputASTFragments {
fn assemble_final_output(self) -> TokenStream2 {
let Self {
must_use_attribute,
inline_wdf_fn_signature,
inline_wdf_fn_body_statments,
inline_wdf_fn_invocation,
} = self;
let conditional_must_use_attribute =
must_use_attribute.map_or_else(TokenStream2::new, quote::ToTokens::into_token_stream);
quote! {
{
// Use a private module to prevent leaking of glob import into inline_wdf_fn_invocation's parameters
mod private__ {
// Glob import types from wdk_sys. glob importing is done instead of blindly prepending the
// paramters types with wdk_sys:: because bindgen generates some paramters as native rust types
use wdk_sys::*;
// If the function returns a value, add a `#[must_use]` attribute to the function
#conditional_must_use_attribute
// Encapsulate the code in an inline functions to allow for condition must_use attribute.
// core::hint::must_use is not stable yet: https://github.com/rust-lang/rust/issues/94745
#[inline(always)]
pub #inline_wdf_fn_signature {
#(#inline_wdf_fn_body_statments)*
}
}
private__::#inline_wdf_fn_invocation
}
}
}
}
fn map_to_syn_error<E: std::fmt::Display>(span: Span, error: E) -> Error {
Error::new(span, error.to_string())
}
fn call_unsafe_wdf_function_binding_impl(input_tokens: TokenStream2) -> TokenStream2 {
let inputs = match parse2::<Inputs>(input_tokens) {
Ok(syntax_tree) => syntax_tree,
Err(err) => return err.to_compile_error(),
};
let derived_ast_fragments = match inputs.generate_derived_ast_fragments() {
Ok(derived_ast_fragments) => derived_ast_fragments,
Err(err) => return err.to_compile_error(),
};
derived_ast_fragments
.generate_intermediate_output_ast_fragments()
.assemble_final_output()
}
fn parse_types_ast(path: &LitStr) -> Result<File> {
let types_path = PathBuf::from(path.value());
let types_path = match types_path.canonicalize() {
Ok(types_path) => types_path,
Err(err) => {
return Err(Error::new(
path.span(),
format!(
"Failed to canonicalize types_path ({}): {err}",
types_path.display()
),
));
}
};
let types_file_contents = match std::fs::read_to_string(&types_path) {
Ok(contents) => contents,
Err(err) => {
return Err(Error::new(
path.span(),
format!(
"Failed to read wdk-sys types information from {}: {err}",
types_path.display(),
),
));
}
};
match parse_file(&types_file_contents) {
Ok(wdk_sys_types_rs_abstract_syntax_tree) => Ok(wdk_sys_types_rs_abstract_syntax_tree),
Err(err) => Err(Error::new(
path.span(),
format!(
"Failed to parse wdk-sys types information from {} into AST: {err}",
types_path.display(),
),
)),
}
}
/// Generate the function parameters and return type corresponding to the
/// function signature of the `function_pointer_type` type alias found in
/// bindgen-generated types information
///
/// # Examples
///
/// Passing the `PFN_WDFDRIVERCREATE` [`Ident`] as `function_pointer_type` would
/// return a [`Punctuated`] representation of
///
/// ```rust, compile_fail
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: WDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER
/// ```
///
/// and return type as the [`ReturnType`] representation of `wdk_sys::NTSTATUS`
fn generate_parameters_and_return_type(
types_ast: &File,
function_pointer_type: &Ident,
) -> Result<(Punctuated<BareFnArg, Token![,]>, ReturnType)> {
let type_alias_definition = find_type_alias_definition(types_ast, function_pointer_type)?;
let fn_pointer_definition =
extract_fn_pointer_definition(type_alias_definition, function_pointer_type.span())?;
parse_fn_pointer_definition(fn_pointer_definition, function_pointer_type.span())
}
/// Find type alias declaration and definition that matches the Ident of
/// `function_pointer_type` in `syn::File` AST
///
/// # Examples
///
/// Passing the `PFN_WDFDRIVERCREATE` [`Ident`] as `function_pointer_type` would
/// return a [`ItemType`] representation of:
///
/// ```rust, compile_fail
/// pub type PFN_WDFDRIVERCREATE = ::core::option::Option<
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// >;
/// ```
fn find_type_alias_definition<'a>(
types_ast: &'a File,
function_pointer_type: &Ident,
) -> Result<&'a ItemType> {
types_ast
.items
.iter()
.find_map(|item| {
if let Item::Type(type_alias) = item {
if type_alias.ident == *function_pointer_type {
return Some(type_alias);
}
}
None
})
.ok_or_else(|| {
Error::new(
function_pointer_type.span(),
format!("Failed to find type alias definition for {function_pointer_type}"),
)
})
}
/// Extract the [`TypePath`] representing the function pointer definition from
/// the [`ItemType`]
///
/// # Examples
///
/// The [`ItemType`] representation of
///
/// ```rust, compile_fail
/// pub type PFN_WDFDRIVERCREATE = ::core::option::Option<
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// >;
/// ```
///
/// would return the [`TypePath`] representation of
///
/// ```rust, compile_fail
/// ::core::option::Option<
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// >
/// ```
fn extract_fn_pointer_definition(type_alias: &ItemType, error_span: Span) -> Result<&TypePath> {
if let Type::Path(fn_pointer) = type_alias.ty.as_ref() {
Ok(fn_pointer)
} else {
Err(Error::new(
error_span,
format!("Expected Type::Path when parsing ItemType.ty:\n{type_alias:#?}"),
))
}
}
/// Parse the parameter list (both names and types) and the return type from the
/// [`TypePath`] representing the function pointer definition
///
/// # Examples
///
/// The [`TypePath`] representation of
///
/// ```rust, compile_fail
/// ::core::option::Option<
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// >
/// ```
///
/// would return the parsed parameter list as the [`Punctuated`] representation
/// of
///
/// ```rust, compile_fail
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: WDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER
/// ```
///
/// and return type as the [`ReturnType`] representation of `wdk_sys::NTSTATUS`
fn parse_fn_pointer_definition(
fn_pointer_typepath: &TypePath,
error_span: Span,
) -> Result<(Punctuated<BareFnArg, Token![,]>, ReturnType)> {
let bare_fn_type = extract_bare_fn_type(fn_pointer_typepath, error_span)?;
let fn_parameters = compute_fn_parameters(bare_fn_type, error_span)?;
let return_type = compute_return_type(bare_fn_type);
Ok((fn_parameters, return_type))
}
/// Extract the [`TypeBareFn`] (i.e. function definition) from the [`TypePath`]
/// (i.e. the function pointer option) representing the function
///
/// # Examples
///
/// The [`TypePath`] representation of
///
/// ```rust, compile_fail
/// ::core::option::Option<
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// >
/// ```
///
/// would return the [`TypeBareFn`] representation of
///
/// ```rust, compile_fail
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// ```
fn extract_bare_fn_type(fn_pointer_typepath: &TypePath, error_span: Span) -> Result<&TypeBareFn> {
let option_path_segment: &PathSegment =
fn_pointer_typepath.path.segments.last().ok_or_else(|| {
Error::new(
error_span,
format!("Expected at least one PathSegment in TypePath:\n{fn_pointer_typepath:#?}"),
)
})?;
if option_path_segment.ident != "Option" {
return Err(Error::new(
error_span,
format!("Expected Option as last PathSegment in TypePath:\n{fn_pointer_typepath:#?}"),
));
}
let PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: ref option_angle_bracketed_args,
..
}) = option_path_segment.arguments
else {
return Err(Error::new(
error_span,
format!(
"Expected AngleBracketed PathArguments in Option \
PathSegment:\n{option_path_segment:#?}"
),
));
};
let bracketed_argument = option_angle_bracketed_args.first().ok_or_else(|| {
Error::new(
error_span,
format!(
"Expected exactly one GenericArgument in AngleBracketedGenericArguments:\n{:#?}",
option_path_segment.arguments
),
)
})?;
let GenericArgument::Type(Type::BareFn(bare_fn_type)) = bracketed_argument else {
return Err(Error::new(
error_span,
format!("Expected TypeBareFn in GenericArgument:\n{bracketed_argument:#?}"),
));
};
Ok(bare_fn_type)
}
/// Compute the function parameters based on the function definition
///
/// # Examples
///
/// The [`TypeBareFn`] representation of
///
/// ```rust, compile_fail
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// ```
///
/// would return the [`Punctuated`] representation of
/// ```rust, compile_fail
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: WDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER
/// ```
fn compute_fn_parameters(
bare_fn_type: &syn::TypeBareFn,
error_span: Span,
) -> Result<Punctuated<BareFnArg, Token![,]>> {
// Validate that the first parameter is PWDF_DRIVER_GLOBALS
let Some(BareFnArg {
ty:
Type::Path(TypePath {
path:
Path {
segments: first_parameter_type_path,
..
},
..
}),
..
}) = bare_fn_type.inputs.first()
else {
return Err(Error::new(
error_span,
format!(
"Expected at least one input parameter of type Path in \
BareFnType:\n{bare_fn_type:#?}"
),
));
};
let Some(last_path_segment) = first_parameter_type_path.last() else {
return Err(Error::new(
error_span,
format!("Expected at least one PathSegment in TypePath:\n{bare_fn_type:#?}"),
));
};
if last_path_segment.ident != "PWDF_DRIVER_GLOBALS" {
return Err(Error::new(
error_span,
format!(
"Expected PWDF_DRIVER_GLOBALS as last PathSegment in TypePath of first BareFnArg \
input:\n{bare_fn_type:#?}"
),
));
}
Ok(bare_fn_type
.inputs
.iter()
.skip(1)
// transform argument names to snake_case with trailing underscores to lessen likelihood
// of shadowing issues
.map(|fn_arg| {
let arg_name = fn_arg.name.as_ref().map(|(ident, colon_token)| {
let modified_name = {
let mut name = ident.to_string().to_snake_case();
name.push_str("__");
name
};
(Ident::new(&modified_name, ident.span()), *colon_token)
});
BareFnArg {
name: arg_name,
..fn_arg.clone()
}
})
.collect())
}
/// Compute the return type based on the function defintion
///
/// # Examples
///
/// The [`TypeBareFn`] representation of
///
/// ```rust, compile_fail
/// unsafe extern "C" fn(
/// DriverGlobals: PWDF_DRIVER_GLOBALS,
/// DriverObject: PDRIVER_OBJECT,
/// RegistryPath: PCUNICODE_STRING,
/// DriverAttributes: PWDF_OBJECT_ATTRIBUTES,
/// DriverConfig: PWDF_DRIVER_CONFIG,
/// Driver: *mut WDFDRIVER,
/// ) -> NTSTATUS,
/// ```
///
/// would return the [`ReturnType`] representation of `wdk_sys::NTSTATUS`
fn compute_return_type(bare_fn_type: &syn::TypeBareFn) -> ReturnType {
bare_fn_type.output.clone()
}
/// Generate the `#[must_use]` attribute if the return type is not `()`
fn generate_must_use_attribute(return_type: &ReturnType) -> Option<Attribute> {
if matches!(return_type, ReturnType::Type(..)) {
Some(parse_quote! { #[must_use] })
} else {
None
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq as pretty_assert_eq;
use quote::ToTokens;
use super::*;
mod to_snake_case {
use super::*;
#[test]
fn camel_case() {
let input = "camelCaseString".to_string();
let expected = "camel_case_string";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn short_camel_case() {
let input = "aB".to_string();
let expected = "a_b";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn pascal_case() {
let input = "PascalCaseString".to_string();
let expected = "pascal_case_string";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn pascal_case_with_leading_acronym() {
let input = "ASCIIEncodedString".to_string();
let expected = "ascii_encoded_string";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn pascal_case_with_trailing_acronym() {
let input = "IsASCII".to_string();
let expected = "is_ascii";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn screaming_snake_case() {
let input = "PFN_WDF_DRIVER_DEVICE_ADD".to_string();
let expected = "pfn_wdf_driver_device_add";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn screaming_snake_case_with_leading_acronym() {
let input = "ASCII_STRING".to_string();
let expected = "ascii_string";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn screaming_snake_case_with_leading_underscore() {
let input = "_WDF_DRIVER_INIT_FLAGS".to_string();
let expected = "_wdf_driver_init_flags";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn snake_case() {
let input = "snake_case_string".to_string();
let expected = "snake_case_string";
pretty_assert_eq!(input.to_snake_case(), expected);
}
#[test]
fn snake_case_with_leading_underscore() {
let input = "_snake_case_with_leading_underscore".to_string();
let expected = "_snake_case_with_leading_underscore";
pretty_assert_eq!(input.to_snake_case(), expected);
}
}
mod inputs {
use super::*;
mod parse {
use super::*;
#[test]
fn valid_input() {
let input_tokens = quote! { "/path/to/generated/types/file.rs", WdfDriverCreate, driver, registry_path, WDF_NO_OBJECT_ATTRIBUTES, &mut driver_config, driver_handle_output };
let expected = Inputs {
types_path: parse_quote! { "/path/to/generated/types/file.rs" },
wdf_function_identifier: format_ident!("WdfDriverCreate"),
wdf_function_arguments: parse_quote! {
driver,
registry_path,
WDF_NO_OBJECT_ATTRIBUTES,
&mut driver_config,
driver_handle_output
},
};
pretty_assert_eq!(parse2::<Inputs>(input_tokens).unwrap(), expected);
}
#[test]
fn valid_input_with_trailing_comma() {
let input_tokens = quote! { "/path/to/generated/types/file.rs" , WdfDriverCreate, driver, registry_path, WDF_NO_OBJECT_ATTRIBUTES, &mut driver_config, driver_handle_output, };
let expected = Inputs {
types_path: parse_quote! { "/path/to/generated/types/file.rs" },
wdf_function_identifier: format_ident!("WdfDriverCreate"),